Linux Networking and Network Devices APIs
Peios: The generated declarations below are read from the kernel source. Peios adds native checks at the file, process, IPC and socket boundaries; inherited comments about Unix permissions or capability names are not a complete access policy. See Peios kernel behaviour and the VFS callback reference for the Peios integration contracts.
Linux Networking #
Networking Base Types #
enum sock_type #
Socket types
Constants
SOCK_STREAM: stream (connection) socketSOCK_DGRAM: datagram (conn.less) socketSOCK_RAW: raw socketSOCK_RDM: reliably-delivered messageSOCK_SEQPACKET: sequential packet socketSOCK_DCCP: Datagram Congestion Control Protocol socketSOCK_PACKET: linux specific way of getting packets at the dev level. For writing rarp and other similar things on the user level.
Description
When adding some new socket type please grep ARCH_HAS_SOCKET_TYPE include/asm-* /socket.h, at least MIPS overrides this enum for binary compat reasons.
enum sock_shutdown_cmd #
Shutdown types
Constants
SHUT_RD: shutdown receptionsSHUT_WR: shutdown transmissionsSHUT_RDWR: shutdown receptions/transmissions
struct socket #
general BSD socket
Definition
;
Members
state: socket state (SS_CONNECTED, etc)type: socket type (SOCK_STREAM, etc)flags: socket flags (SOCK_NOSPACE, etc)file: File back pointer for gcsk: internal networking protocol agnostic socket representationops: protocol specific socket operationswq: wait queue for several uses
Socket Buffer Functions #
skb_frag_size() #
unsigned int Returns the size of a skb fragment
Parameters
const skb_frag_t *frag: skb fragment
skb_frag_size_set() #
void Sets the size of a skb fragment
Parameters
skb_frag_t *frag: skb fragmentunsigned int size: size of fragment
skb_frag_size_add() #
void Increments the size of a skb fragment by delta
Parameters
skb_frag_t *frag: skb fragmentint delta: value to add
skb_frag_size_sub() #
void Decrements the size of a skb fragment by delta
Parameters
skb_frag_t *frag: skb fragmentint delta: value to subtract
skb_frag_must_loop() #
bool Test if p is a high memory page
Parameters
struct page *p: fragment's page
skb_frag_foreach_page() #
loop over pages in a fragment
Parameters
f: skb frag to operate onf_off: offset from start of f->netmemf_len: length from f_off to loop overp: (temp var) current pagep_off: (temp var) offset from start of current page, non-zero only on first page.p_len: (temp var) length in current page, < PAGE_SIZE only on first and last page.copied: (temp var) length so far, excluding current p_len.
Description
A fragment can hold a compound page, in which case per-page operations, notably kmap_atomic, must be called for each regular page.
struct skb_shared_hwtstamps #
hardware time stamps
Definition
;
Members
{unnamed_union}: anonymoushwtstamp: hardware time stamp transformed into duration since arbitrary point in timenetdev_data: address/cookie of network device driver used as reference to actual hardware time stamp
Description
Software time stamps generated by ktime_get_real() are stored in
skb->tstamp.
hwtstamps can only be compared against other hwtstamps from the same device.
This structure is attached to packets as part of the
skb_shared_info. Use skb_hwtstamps() to get a pointer.
struct sk_buff #
socket buffer
Definition
;
Members
{unnamed_union}: anonymous{unnamed_struct}: anonymousnext: Next buffer in listprev: Previous buffer in list{unnamed_union}: anonymousdev: Device we arrived on/are leaving bydev_scratch: (aka dev) alternate use of dev when dev would beNULLrbnode: RB tree node, alternative to next/prev for netem/tcplist: queue headll_node: anchor in an llist (eg socket defer_list)sk: Socket we are owned by{unnamed_union}: anonymouststamp: Time we arrived/leftskb_mstamp_ns: (aka tstamp) earliest departure time; start point for retransmit timercb: Control buffer. Free for use by every layer. Put private vars here{unnamed_union}: anonymous{unnamed_struct}: anonymous_skb_refdst: destination entry (with norefcount bit)destructor: Destruct functiontcp_tsorted_anchor: list structure for TCP (tp->tsorted_sent_queue)_sk_redir: socket redirection information for skmsg_nfct: Associated connection, if any (with nfctinfo bits)len: Length of actual datadata_len: Data lengthmac_len: Length of link layer headerhdr_len: writable header length of cloned skbqueue_mapping: Queue mapping for multiqueue devicescloned: Head may be cloned (check refcnt to be sure)nohdr: Payload reference only, must not modify headerfclone: skbuff clone statuspeeked: this packet has been seen already, so stats have been done for it, don't do them againhead_frag: skb was allocated from page fragments, not allocated bykmalloc()orvmalloc().pfmemalloc: skbuff was allocated from PFMEMALLOC reservespp_recycle: mark the packet for recycling instead of freeing (implies page_pool support on driver)active_extensions: active extensions (skb_ext_id types)pkt_type: Packet classignore_df: allow local fragmentationdst_pending_confirm: need to confirm neighbourip_summed: Driver fed us an IP checksumooo_okay: allow the mapping of a socket to a queue to be changedtstamp_type: When set, skb->tstamp has the delivery_time clock base of skb->tstamp.tc_at_ingress: used within tc_classify to distinguish in/egresstc_skip_classify: do not classify packet. set by IFB deviceremcsum_offload: remote checksum offload is enabledcsum_complete_sw: checksum was completed by softwarecsum_level: indicates the number of consecutive checksums found in the packet minus one that have been verified as CHECKSUM_UNNECESSARY (max 3)inner_protocol_type: whether the inner protocol is ENCAP_TYPE_ETHER or ENCAP_TYPE_IPPROTOl4_hash: indicate hash is a canonical 4-tuple hash over transport ports.sw_hash: indicates hash was computed in software stackwifi_acked_valid: wifi_acked was setwifi_acked: whether frame was acked on wifi or notno_fcs: Request NIC to treat last 4 bytes as Ethernet FCSencapsulation: indicates the inner headers in the skbuff are validencap_hdr_csum: software checksum is neededcsum_valid: checksum is already validndisc_nodetype: router type (from link layer)ipvs_property: skbuff is owned by ipvsnf_trace: netfilter packet trace flagoffload_fwd_mark: Packet was L2-forwarded in hardwareoffload_l3_fwd_mark: Packet was L3-forwarded in hardwareredirected: packet was redirected by packet classifierfrom_ingress: packet was redirected from the ingress pathnf_skip_egress: packet shall skip nf egress - see netfilter_netdev.hdecrypted: Decrypted SKBslow_gro: state present at GRO time, slower prepare step requiredcsum_not_inet: use CRC32c to resolve CHECKSUM_PARTIALunreadable: indicates that at least 1 of the fragments in this skb is unreadable.ntfe_refusal: packet emitted by NTFE as a refusal responsetc_index: Traffic control indexalloc_cpu: CPU which did the skb allocation.{unnamed_union}: anonymouscsum: Checksum (must include start/offset pair){unnamed_struct}: anonymouscsum_start: Offset from skb->head where checksumming should startcsum_offset: Offset from csum_start where checksum should be storedpriority: Packet queueing priorityskb_iif: ifindex of device we arrived onhash: the packet hash{unnamed_union}: anonymousvlan_all: vlan fields (proto & tci){unnamed_struct}: anonymousvlan_proto: vlan encapsulation protocolvlan_tci: vlan tag control information{unnamed_union}: anonymousnapi_id: id of the NAPI struct this skb came fromsender_cpu: (aka napi_id) source CPU in XPSsecmark: security marking{unnamed_union}: anonymousmark: Generic packet markreserved_tailroom: (aka mark) number of bytes of free space available at the tail of an sk_buff{unnamed_union}: anonymousinner_protocol: Protocol (encapsulation)inner_ipproto: (aka inner_protocol) stores ipproto when skb->inner_protocol_type == ENCAP_TYPE_IPPROTO;inner_transport_header: Inner transport layer header (encapsulation)inner_network_header: Network layer header (encapsulation)inner_mac_header: Link layer header (encapsulation)protocol: Packet protocol from drivertransport_header: Transport layer headernetwork_header: Network layer headermac_header: Link layer headerkcov_handle: KCOV remote handle for remote coverage collectiontail: Tail pointerend: End pointerhead: Head of bufferdata: Data head pointertruesize: Buffer sizeusers: User count - see {datagram,tcp}.cextensions: allocated extensions, valid if active_extensions is nonzero
skb_pfmemalloc() #
bool Test if the skb was allocated from PFMEMALLOC reserves
Parameters
const struct sk_buff *skb: buffer
skb_dst() #
struct dst_entry * returns skb dst_entry
Parameters
const struct sk_buff *skb: buffer
Return
skb dst_entry, regardless of reference taken or not.
skb_dstref_steal() #
unsigned long return current dst_entry value and clear it
Parameters
struct sk_buff *skb: buffer
Description
Resets skb dst_entry without adjusting its reference count. Useful in cases where dst_entry needs to be temporarily reset and restored. Note that the returned value cannot be used directly because it might contain SKB_DST_NOREF bit.
When in doubt, prefer skb_dst_drop() over skb_dstref_steal() to correctly
handle dst_entry reference counting.
Return
original skb dst_entry.
skb_dstref_restore() #
void restore skb dst_entry removed via skb_dstref_steal()
Parameters
struct sk_buff *skb: bufferunsigned long refdst: dst entry from a call toskb_dstref_steal()
skb_dst_set() #
void sets skb dst
Parameters
struct sk_buff *skb: bufferstruct dst_entry *dst: dst entry
Description
Sets skb dst, assuming a reference was taken on dst and should
be released by skb_dst_drop()
skb_dst_set_noref() #
void sets skb dst, hopefully, without taking reference
Parameters
struct sk_buff *skb: bufferstruct dst_entry *dst: dst entry
Description
Sets skb dst, assuming a reference was not taken on dst. If dst entry is cached, we do not take reference and dst_release will be avoided by refdst_drop. If dst entry is not cached, we take reference, so that last dst_release can destroy the dst immediately.
skb_dst_is_noref() #
bool Test if skb dst isn't refcounted
Parameters
const struct sk_buff *skb: buffer
skb_napi_id() #
unsigned int Returns the skb's NAPI id
Parameters
const struct sk_buff *skb: buffer
skb_unref() #
bool decrement the skb's reference count
Parameters
struct sk_buff *skb: buffer
Return
true if we can free the skb.
kfree_skb() #
void free an sk_buff with 'NOT_SPECIFIED' reason
Parameters
struct sk_buff *skb: buffer to free
alloc_skb() #
struct sk_buff * allocate a network buffer
Parameters
unsigned int size: size to allocategfp_t priority: allocation mask
Description
This function is a convenient wrapper around __alloc_skb().
skb_fclone_busy() #
bool check if fclone is busy
Parameters
const struct sock *sk: socketconst struct sk_buff *skb: buffer
Return
true if skb is a fast clone, and its clone is not freed.
Some drivers call skb_orphan() in their ndo_start_xmit(),
so we also check that didn't happen.
alloc_skb_fclone() #
struct sk_buff * allocate a network buffer from fclone cache
Parameters
unsigned int size: size to allocategfp_t priority: allocation mask
Description
This function is a convenient wrapper around __alloc_skb().
skb_pad() #
int zero pad the tail of an skb
Parameters
struct sk_buff *skb: buffer to padint pad: space to pad
Description
Ensure that a buffer is followed by a padding area that is zero filled. Used by network drivers which may DMA or transfer data beyond the buffer end onto the wire.
May return error in out of memory cases. The skb is freed on error.
skb_queue_empty() #
int check if a queue is empty
Parameters
const struct sk_buff_head *list: queue head
Description
Returns true if the queue is empty, false otherwise.
skb_queue_empty_lockless() #
bool check if a queue is empty
Parameters
const struct sk_buff_head *list: queue head
Description
Returns true if the queue is empty, false otherwise. This variant can be used in lockless contexts.
skb_queue_is_last() #
bool check if skb is the last entry in the queue
Parameters
const struct sk_buff_head *list: queue headconst struct sk_buff *skb: buffer
Description
Returns true if skb is the last buffer on the list.
skb_queue_is_first() #
bool check if skb is the first entry in the queue
Parameters
const struct sk_buff_head *list: queue headconst struct sk_buff *skb: buffer
Description
Returns true if skb is the first buffer on the list.
skb_queue_next() #
struct sk_buff * return the next packet in the queue
Parameters
const struct sk_buff_head *list: queue headconst struct sk_buff *skb: current buffer
Description
Return the next packet in list after skb. It is only valid to
call this if skb_queue_is_last() evaluates to false.
skb_queue_prev() #
struct sk_buff * return the prev packet in the queue
Parameters
const struct sk_buff_head *list: queue headconst struct sk_buff *skb: current buffer
Description
Return the prev packet in list before skb. It is only valid to
call this if skb_queue_is_first() evaluates to false.
skb_get() #
struct sk_buff * reference buffer
Parameters
struct sk_buff *skb: buffer to reference
Description
Makes another reference to a socket buffer and returns a pointer to the buffer.
skb_cloned() #
int is the buffer a clone
Parameters
const struct sk_buff *skb: buffer to check
Description
Returns true if the buffer was generated with skb_clone() and is
one of multiple shared copies of the buffer. Cloned buffers are
shared data so must not be written to under normal circumstances.
skb_header_cloned() #
int is the header a clone
Parameters
const struct sk_buff *skb: buffer to check
Description
Returns true if modifying the header part of the buffer requires the data to be copied.
__skb_header_release() #
void allow clones to use the headroom
Parameters
struct sk_buff *skb: buffer to operate on
Description
See "DOC: dataref and headerless skbs".
skb_shared() #
int is the buffer shared
Parameters
const struct sk_buff *skb: buffer to check
Description
Returns true if more than one person has a reference to this buffer.
skb_share_check() #
struct sk_buff * check if buffer is shared and if so clone it
Parameters
struct sk_buff *skb: buffer to checkgfp_t pri: priority for memory allocation
Description
If the buffer is shared the buffer is cloned and the old copy drops a reference. A new clone with a single reference is returned. If the buffer is not shared the original buffer is returned. When being called from interrupt status or with spinlocks held pri must be GFP_ATOMIC.
NULL is returned on a memory allocation failure.
skb_unshare() #
struct sk_buff * make a copy of a shared buffer
Parameters
struct sk_buff *skb: buffer to checkgfp_t pri: priority for memory allocation
Description
If the socket buffer is a clone then this function creates a new
copy of the data, drops a reference count on the old copy and returns
the new copy with the reference count at 1. If the buffer is not a clone
the original buffer is returned. When called with a spinlock held or
from interrupt state pri must be GFP_ATOMIC
NULL is returned on a memory allocation failure.
skb_peek() #
struct sk_buff * peek at the head of an sk_buff_head
Parameters
const struct sk_buff_head *list_: list to peek at
Description
Peek an sk_buff. Unlike most other operations you MUST
be careful with this one. A peek leaves the buffer on the
list and someone else may run off with it. You must hold
the appropriate locks or have a private queue to do this.
Returns NULL for an empty list or a pointer to the head element.
The reference count is not incremented and the reference is therefore
volatile. Use with caution.
__skb_peek() #
struct sk_buff * peek at the head of a non-empty sk_buff_head
Parameters
const struct sk_buff_head *list_: list to peek at
Description
Like skb_peek(), but the caller knows that the list is not empty.
skb_peek_next() #
struct sk_buff * peek skb following the given one from a queue
Parameters
struct sk_buff *skb: skb to start fromconst struct sk_buff_head *list_: list to peek at
Description
Returns NULL when the end of the list is met or a pointer to the
next element. The reference count is not incremented and the
reference is therefore volatile. Use with caution.
skb_peek_tail() #
struct sk_buff * peek at the tail of an sk_buff_head
Parameters
const struct sk_buff_head *list_: list to peek at
Description
Peek an sk_buff. Unlike most other operations you MUST
be careful with this one. A peek leaves the buffer on the
list and someone else may run off with it. You must hold
the appropriate locks or have a private queue to do this.
Returns NULL for an empty list or a pointer to the tail element.
The reference count is not incremented and the reference is therefore
volatile. Use with caution.
skb_queue_len() #
__u32 get queue length
Parameters
const struct sk_buff_head *list_: list to measure
Description
Return the length of an sk_buff queue.
skb_queue_len_lockless() #
__u32 get queue length
Parameters
const struct sk_buff_head *list_: list to measure
Description
Return the length of an sk_buff queue.
This variant can be used in lockless contexts.
__skb_queue_head_init() #
void initialize non-spinlock portions of sk_buff_head
Parameters
struct sk_buff_head *list: queue to initialize
Description
This initializes only the list and queue length aspects of an sk_buff_head object. This allows to initialize the list aspects of an sk_buff_head without reinitializing things like the spinlock. It can also be used for on-stack sk_buff_head objects where the spinlock is known to not be used.
skb_queue_splice() #
void join two skb lists, this is designed for stacks
Parameters
const struct sk_buff_head *list: the new list to addstruct sk_buff_head *head: the place to add it in the first list
skb_queue_splice_init() #
void join two skb lists and reinitialise the emptied list
Parameters
struct sk_buff_head *list: the new list to addstruct sk_buff_head *head: the place to add it in the first list
Description
The list at list is reinitialised
skb_queue_splice_tail() #
void join two skb lists, each list being a queue
Parameters
const struct sk_buff_head *list: the new list to addstruct sk_buff_head *head: the place to add it in the first list
skb_queue_splice_tail_init() #
void join two skb lists and reinitialise the emptied list
Parameters
struct sk_buff_head *list: the new list to addstruct sk_buff_head *head: the place to add it in the first list
Description
Each of the lists is a queue. The list at list is reinitialised
__skb_queue_after() #
void queue a buffer at the list head
Parameters
struct sk_buff_head *list: list to usestruct sk_buff *prev: place after this bufferstruct sk_buff *newsk: buffer to queue
Description
Queue a buffer int the middle of a list. This function takes no locks and you must therefore hold required locks before calling it.
A buffer cannot be placed on two lists at the same time.
__skb_queue_head() #
void queue a buffer at the list head
Parameters
struct sk_buff_head *list: list to usestruct sk_buff *newsk: buffer to queue
Description
Queue a buffer at the start of a list. This function takes no locks and you must therefore hold required locks before calling it.
A buffer cannot be placed on two lists at the same time.
__skb_queue_tail() #
void queue a buffer at the list tail
Parameters
struct sk_buff_head *list: list to usestruct sk_buff *newsk: buffer to queue
Description
Queue a buffer at the end of a list. This function takes no locks and you must therefore hold required locks before calling it.
A buffer cannot be placed on two lists at the same time.
__skb_dequeue() #
struct sk_buff * remove from the head of the queue
Parameters
struct sk_buff_head *list: list to dequeue from
Description
Remove the head of the list. This function does not take any locks
so must be used with appropriate locks held only. The head item is
returned or NULL if the list is empty.
__skb_dequeue_tail() #
struct sk_buff * remove from the tail of the queue
Parameters
struct sk_buff_head *list: list to dequeue from
Description
Remove the tail of the list. This function does not take any locks
so must be used with appropriate locks held only. The tail item is
returned or NULL if the list is empty.
skb_len_add() #
void adds a number to len fields of skb
Parameters
struct sk_buff *skb: buffer to add len toint delta: number of bytes to add
__skb_fill_netmem_desc() #
void initialise a fragment in an skb
Parameters
struct sk_buff *skb: buffer containing fragment to be initialisedint i: fragment index to initialisenetmem_ref netmem: the netmem to use for this fragmentint off: the offset to the data with pageint size: the length of the data
Description
Initialises the i'th fragment of skb to point to size bytes at
offset off within page.
Does not take any additional reference on the fragment.
skb_fill_page_desc() #
void initialise a paged fragment in an skb
Parameters
struct sk_buff *skb: buffer containing fragment to be initialisedint i: paged fragment index to initialisestruct page *page: the page to use for this fragmentint off: the offset to the data with pageint size: the length of the data
Description
As per __skb_fill_page_desc() -- initialises the i'th fragment of
skb to point to size bytes at offset off within page. In
addition updates skb such that i is the last fragment.
Does not take any additional reference on the fragment.
skb_fill_page_desc_noacc() #
void initialise a paged fragment in an skb
Parameters
struct sk_buff *skb: buffer containing fragment to be initialisedint i: paged fragment index to initialisestruct page *page: the page to use for this fragmentint off: the offset to the data with pageint size: the length of the data
Description
Variant of skb_fill_page_desc() which does not deal with
pfmemalloc, if page is not owned by us.
skb_headroom() #
unsigned int bytes at buffer head
Parameters
const struct sk_buff *skb: buffer to check
Description
Return the number of bytes of free space at the head of an sk_buff.
skb_tailroom() #
int bytes at buffer end
Parameters
const struct sk_buff *skb: buffer to check
Description
Return the number of bytes of free space at the tail of an sk_buff
skb_availroom() #
int bytes at buffer end
Parameters
const struct sk_buff *skb: buffer to check
Description
Return the number of bytes of free space at the tail of an sk_buff
allocated by sk_stream_alloc()
skb_reserve() #
void adjust headroom
Parameters
struct sk_buff *skb: buffer to alterint len: bytes to move
Description
Increase the headroom of an empty sk_buff by reducing the tail
room. This is only allowed for an empty buffer.
skb_tailroom_reserve() #
void adjust reserved_tailroom
Parameters
struct sk_buff *skb: buffer to alterunsigned int mtu: maximum amount of headlen permittedunsigned int needed_tailroom: minimum amount of reserved_tailroom
Description
Set reserved_tailroom so that headlen can be as large as possible but not larger than mtu and tailroom cannot be smaller than needed_tailroom. The required headroom should already have been reserved before using this function.
skb_reset_transport_header_careful() #
bool conditionally reset transport header
Parameters
struct sk_buff *skb: buffer to alter
Description
Hardened version of skb_reset_transport_header().
Return
true if the operation was a success.
pskb_trim_unique() #
void remove end from a paged unique (not cloned) buffer
Parameters
struct sk_buff *skb: buffer to alterunsigned int len: new length
Description
This is identical to pskb_trim except that the caller knows that the skb is not cloned so we should never get an error due to out- of-memory.
skb_orphan() #
void orphan a buffer
Parameters
struct sk_buff *skb: buffer to orphan
Description
If a buffer currently has an owner then we call the owner's destructor function and make the skb unowned. The buffer continues to exist but is no longer charged to its former owner.
skb_orphan_frags() #
int orphan the frags contained in a buffer
Parameters
struct sk_buff *skb: buffer to orphan frags fromgfp_t gfp_mask: allocation mask for replacement pages
Description
For each frag in the SKB which needs a destructor (i.e. has an owner) create a copy of that frag and release the original page by calling the destructor.
__skb_queue_purge_reason() #
void empty a list
Parameters
struct sk_buff_head *list: list to emptyenum skb_drop_reason reason: drop reason
Description
Delete all buffers on an sk_buff list. Each buffer is removed from
the list and one reference dropped. This function does not take the
list lock and the caller must hold the relevant locks to use it.
netdev_alloc_frag() #
void * allocate a page fragment
Parameters
unsigned int fragsz: fragment size
Description
Allocates a frag from a page for receive buffer. Uses GFP_ATOMIC allocations.
netdev_alloc_skb() #
struct sk_buff * allocate an skbuff for rx on a specific device
Parameters
struct net_device *dev: network device to receive onunsigned int length: length to allocate
Description
Allocate a new sk_buff and assign it a usage count of one. The
buffer has unspecified headroom built in. Users should allocate
the headroom they think they need without accounting for the
built in space. The built in space is used for optimisations.
NULL is returned if there is no free memory. Although this function
allocates memory it can be called from an interrupt.
__dev_alloc_pages() #
struct page * allocate page for network Rx
Parameters
gfp_t gfp_mask: allocation priority. Set __GFP_NOMEMALLOC if not for network Rxunsigned int order: size of the allocation
Description
Allocate a new page.
NULL is returned if there is no free memory.
__dev_alloc_page() #
struct page * allocate a page for network Rx
Parameters
gfp_t gfp_mask: allocation priority. Set __GFP_NOMEMALLOC if not for network Rx
Description
Allocate a new page.
NULL is returned if there is no free memory.
dev_page_is_reusable() #
bool check whether a page can be reused for network Rx
Parameters
const struct page *page: the page to test
Description
A page shouldn't be considered for reusing/recycling if it was allocated under memory pressure or at a distant memory node.
Return
false if this page should be returned to page allocator, true otherwise.
skb_propagate_pfmemalloc() #
void Propagate pfmemalloc if skb is allocated after RX page
Parameters
const struct page *page: The page that was allocated from skb_alloc_pagestruct sk_buff *skb: The skb that may need pfmemalloc set
skb_frag_off() #
unsigned int Returns the offset of a skb fragment
Parameters
const skb_frag_t *frag: the paged fragment
skb_frag_off_add() #
void Increments the offset of a skb fragment by delta
Parameters
skb_frag_t *frag: skb fragmentint delta: value to add
skb_frag_off_set() #
void Sets the offset of a skb fragment
Parameters
skb_frag_t *frag: skb fragmentunsigned int offset: offset of fragment
skb_frag_off_copy() #
void Sets the offset of a skb fragment from another fragment
Parameters
skb_frag_t *fragto: skb fragment where offset is setconst skb_frag_t *fragfrom: skb fragment offset is copied from
skb_frag_net_iov() #
struct net_iov * retrieve the net_iov referred to by fragment
Parameters
const skb_frag_t *frag: the fragment
Return
the struct net_iov associated with frag. Returns NULL if this
frag has no associated net_iov.
skb_frag_page() #
struct page * retrieve the page referred to by a paged fragment
Parameters
const skb_frag_t *frag: the paged fragment
Return
the struct page associated with frag. Returns NULL if this frag
has no associated page.
skb_frag_netmem() #
netmem_ref retrieve the netmem referred to by a fragment
Parameters
const skb_frag_t *frag: the fragment
Return
the netmem_ref associated with frag.
skb_frag_address() #
void * gets the address of the data contained in a paged fragment
Parameters
const skb_frag_t *frag: the paged fragment buffer
Return
the address of the data within frag. The page must already be mapped.
skb_frag_address_safe() #
void * gets the address of the data contained in a paged fragment
Parameters
const skb_frag_t *frag: the paged fragment buffer
Return
the address of the data within frag. Checks that the page
is mapped and returns NULL otherwise.
skb_frag_page_copy() #
void sets the page in a fragment from another fragment
Parameters
skb_frag_t *fragto: skb fragment where page is setconst skb_frag_t *fragfrom: skb fragment page is copied from
__skb_frag_dma_map() #
dma_addr_t maps a paged fragment via the DMA API
Parameters
struct device *dev: the device to map the fragment toconst skb_frag_t *frag: the paged fragment to mapsize_t offset: the offset within the fragment (starting at the fragment's own offset)size_t size: the number of bytes to mapenum dma_data_direction dir: the direction of the mapping (PCI_DMA_*)
Description
Maps the page associated with frag to device.
skb_clone_writable() #
int is the header of a clone writable
Parameters
const struct sk_buff *skb: buffer to checkunsigned int len: length up to which to write
Description
Returns true if modifying the header part of the cloned buffer does not requires the data to be copied.
skb_cow() #
int copy header of skb when it is required
Parameters
struct sk_buff *skb: buffer to cowunsigned int headroom: needed headroom
Description
If the skb passed lacks sufficient headroom or its data part is shared, data is reallocated. If reallocation fails, an error is returned and original skb is not changed.
The result is skb with writable area skb->head...skb->tail and at least headroom of space at head.
skb_cow_head() #
int skb_cow but only making the head writable
Parameters
struct sk_buff *skb: buffer to cowunsigned int headroom: needed headroom
Description
This function is identical to skb_cow except that we replace the skb_cloned check by skb_header_cloned. It should be used when you only need to push on some header and do not need to modify the data.
skb_padto() #
int pad an skbuff up to a minimal size
Parameters
struct sk_buff *skb: buffer to padunsigned int len: minimal length
Description
Pads up a buffer to ensure the trailing bytes exist and are blanked. If the buffer already contains sufficient data it is untouched. Otherwise it is extended. Returns zero on success. The skb is freed on error.
__skb_put_padto() #
int increase size and pad an skbuff up to a minimal size
Parameters
struct sk_buff *skb: buffer to padunsigned int len: minimal lengthbool free_on_error: free buffer on error
Description
Pads up a buffer to ensure the trailing bytes exist and are blanked. If the buffer already contains sufficient data it is untouched. Otherwise it is extended. Returns zero on success. The skb is freed on error if free_on_error is true.
skb_put_padto() #
int increase size and pad an skbuff up to a minimal size
Parameters
struct sk_buff *skb: buffer to padunsigned int len: minimal length
Description
Pads up a buffer to ensure the trailing bytes exist and are blanked. If the buffer already contains sufficient data it is untouched. Otherwise it is extended. Returns zero on success. The skb is freed on error.
skb_linearize() #
int convert paged skb to linear one
Parameters
struct sk_buff *skb: buffer to linarize
Description
If there is no free memory -ENOMEM is returned, otherwise zero is returned and the old skb data released.
skb_has_shared_frag() #
bool can any frag be overwritten
Parameters
const struct sk_buff *skb: buffer to test
Return
true if the skb has at least one frag that might be modified
by an external entity (as in vmsplice()/sendfile())
skb_linearize_cow() #
int make sure skb is linear and writable
Parameters
struct sk_buff *skb: buffer to process
Description
If there is no free memory -ENOMEM is returned, otherwise zero is returned and the old skb data released.
skb_postpull_rcsum() #
void update checksum for received skb after pull
Parameters
struct sk_buff *skb: buffer to updateconst void *start: start of data before pullunsigned int len: length of data pulled
Description
After doing a pull on a received packet, you need to call this to update the CHECKSUM_COMPLETE checksum, or set ip_summed to CHECKSUM_NONE so that it can be recomputed from scratch.
skb_postpush_rcsum() #
void update checksum for received skb after push
Parameters
struct sk_buff *skb: buffer to updateconst void *start: start of data after pushunsigned int len: length of data pushed
Description
After doing a push on a received packet, you need to call this to update the CHECKSUM_COMPLETE checksum.
skb_push_rcsum() #
void * push skb and update receive checksum
Parameters
struct sk_buff *skb: buffer to updateunsigned int len: length of data pulled
Description
This function performs an skb_push on the packet and updates the CHECKSUM_COMPLETE checksum. It should be used on receive path processing instead of skb_push unless you know that the checksum difference is zero (e.g., a valid IP header) or you are setting ip_summed to CHECKSUM_NONE.
pskb_trim_rcsum() #
int trim received skb and update checksum
Parameters
struct sk_buff *skb: buffer to trimunsigned int len: new length
Description
This is exactly the same as pskb_trim except that it ensures the checksum of received packets are still valid after the operation. It can change skb pointers.
skb_needs_linearize() #
bool check if we need to linearize a given skb depending on the given device features.
Parameters
struct sk_buff *skb: socket buffer to checknetdev_features_t features: net device features
Description
Returns true if either:
- skb has frag_list and the device doesn't support FRAGLIST, or
- skb is fragmented and the device does not support SG.
skb_get_timestamp() #
void get timestamp from a skb
Parameters
const struct sk_buff *skb: skb to get stamp fromstruct __kernel_old_timeval *stamp: pointer to struct __kernel_old_timeval to store stamp in
Description
Timestamps are stored in the skb as offsets to a base timestamp. This function converts the offset back to a struct timeval and stores it in stamp.
skb_data_move() #
void Move packet data and metadata after skb_push() or skb_pull().
Parameters
struct sk_buff *skb: packet to operate onconst int len: number of bytes pushed or pulled fromsk_buff->dataconst unsigned int n: number of bytes tomemmove()from pre-push/pullsk_buff->data
Description
Moves n bytes of packet data, can be zero, and all bytes of skb metadata.
Assumes metadata is located immediately before sk_buff->data prior to the
push/pull, and that sufficient headroom exists to hold it after an
skb_push(). Otherwise, metadata is cleared and a one-time warning is issued.
Prefer skb_postpull_data_move() or skb_postpush_data_move() to calling this
helper directly.
skb_postpull_data_move() #
void Move packet data and metadata after skb_pull().
Parameters
struct sk_buff *skb: packet to operate onconst unsigned int len: number of bytes pulled fromsk_buff->dataconst unsigned int n: number of bytes tomemmove()from pre-pullsk_buff->data
Description
See skb_data_move() for details.
skb_postpush_data_move() #
void Move packet data and metadata after skb_push().
Parameters
struct sk_buff *skb: packet to operate onconst unsigned int len: number of bytes pushed ontosk_buff->dataconst unsigned int n: number of bytes tomemmove()from pre-pushsk_buff->data
Description
See skb_data_move() for details.
skb_complete_tx_timestamp() #
void deliver cloned skb with tx timestamps
Parameters
struct sk_buff *skb: clone of the original outgoing packetstruct skb_shared_hwtstamps *hwtstamps: hardware time stamps
Description
PHY drivers may accept clones of transmitted packets for timestamping via their phy_driver.txtstamp method. These drivers must call this function to return the skb back to the stack with a timestamp.
skb_tstamp_tx() #
void queue clone of skb with send time stamps
Parameters
struct sk_buff *orig_skb: the original outgoing packetstruct skb_shared_hwtstamps *hwtstamps: hardware time stamps, may be NULL if not available
Description
If the skb has a socket associated, then this function clones the skb (thus sharing the actual data and optional structures), stores the optional hardware time stamping information (if non NULL) or generates a software time stamp (otherwise), then queues the clone to the error queue of the socket. Errors are silently ignored.
skb_tx_timestamp() #
void Driver hook for transmit timestamping
Parameters
struct sk_buff *skb: A socket buffer.
Description
Ethernet MAC Drivers should call this function in their hard_xmit()
function immediately before giving the sk_buff to the MAC hardware.
Specifically, one should make absolutely sure that this function is called before TX completion of this packet can trigger. Otherwise the packet could potentially already be freed.
skb_complete_wifi_ack() #
void deliver skb with wifi status
Parameters
struct sk_buff *skb: the original outgoing packetbool acked: ack status
skb_checksum_complete() #
__sum16 Calculate checksum of an entire packet
Parameters
struct sk_buff *skb: packet to process
Description
This function calculates the checksum over the entire packet plus the value of skb->csum. The latter can be used to supply the checksum of a pseudo header as used by TCP/UDP. It returns the checksum.
For protocols that contain complete checksums such as ICMP/TCP/UDP, this function can be used to verify that checksum on received packets. In that case the function should return zero if the checksum is correct. In particular, this function will return zero if skb->ip_summed is CHECKSUM_UNNECESSARY which indicates that the hardware has already verified the correctness of the checksum.
struct skb_ext #
sk_buff extensions
Definition
;
Members
refcnt: 1 on allocation, deallocated on 0offset: offset to add to data to obtain extension addresschunks: size currently allocated, stored in SKB_EXT_ALIGN_SHIFT unitsdata: start of extension data, variable sized
Note
-
offsets/lengths are stored in chunks of 8 bytes, this allows
to use 'u8' types while allowing up to 2kb worth of extension data.
skb_checksum_none_assert() #
void make sure skb ip_summed is CHECKSUM_NONE
Parameters
const struct sk_buff *skb: skb to check
Description
fresh skbs have their ip_summed set to CHECKSUM_NONE. Instead of forcing ip_summed to CHECKSUM_NONE, we can use this helper, to document places where we make this assertion.
skb_head_is_locked() #
bool Determine if the skb->head is locked down
Parameters
const struct sk_buff *skb: skb to check
Description
The head on skbs build around a head frag can be removed if they are not cloned. This function returns true if the skb head is locked down due to either being allocated via kmalloc, or by being a clone with multiple references to the head.
struct sock_common #
minimal network layer representation of sockets
Definition
;
Members
{unnamed_union}: anonymousskc_addrpair: 8-byte-aligned __u64 union of skc_daddr & skc_rcv_saddr{unnamed_struct}: anonymousskc_daddr: Foreign IPv4 addrskc_rcv_saddr: Bound local IPv4 addr{unnamed_union}: anonymousskc_hash: hash value used with various protocol lookup tablesskc_u16hashes: two u16 hash values used by UDP lookup tables{unnamed_union}: anonymousskc_portpair: __u32 union of skc_dport & skc_num{unnamed_struct}: anonymousskc_dport: placeholder for inet_dport/tw_dportskc_num: placeholder for inet_num/tw_numskc_family: network address familyskc_state: Connection stateskc_reuse:SO_REUSEADDRsettingskc_reuseport:SO_REUSEPORTsettingskc_ipv6only: socket is IPV6 onlyskc_net_refcnt: socket is using net ref countingskc_bypass_prot_mem: bypass the per-protocol memory accounting for skbskc_bound_dev_if: bound device index if != 0{unnamed_union}: anonymousskc_bind_node: bind hash linkage for various protocol lookup tablesskc_portaddr_node: second hash linkage for UDP/UDP-Lite protocolskc_prot: protocol handlers inside a network familyskc_net: reference to the network namespace of this socketskc_v6_daddr: IPV6 destination addressskc_v6_rcv_saddr: IPV6 source addressskc_cookie: socket's cookie value{unnamed_union}: anonymousskc_flags: place holder for sk_flagsSO_LINGER(l_onoff),SO_BROADCAST,SO_KEEPALIVE,SO_OOBINLINEsettings,SO_TIMESTAMPINGsettingsskc_listener: connection request listener socket (aka rsk_listener) [union with skc_flags]skc_tw_dr: (aka tw_dr) ptr tostruct inet_timewait_death_row[union with skc_flags]{unnamed_union}: anonymousskc_node: main hash linkage for various protocol lookup tablesskc_nulls_node: main hash linkage for TCP/UDP/UDP-Lite protocolskc_tx_queue_mapping: tx queue number for this connectionskc_rx_queue_mapping: rx queue number for this connection{unnamed_union}: anonymousskc_incoming_cpu: record/match cpu processing incoming packetsskc_rcv_wnd: (aka rsk_rcv_wnd) TCP receive window size (possibly scaled) [union with skc_incoming_cpu]skc_tw_rcv_nxt: (aka tw_rcv_nxt) TCP window next expected seq number [union with skc_incoming_cpu]skc_refcnt: reference count
Description
This is the minimal network layer representation of sockets, the header for struct sock and struct inet_timewait_sock.
struct sock #
network layer representation of sockets
Definition
;
Members
__sk_common: shared layout with inet_timewait_socksk_drops: raw/udp drops countersk_peek_off: current peek_offset valuesk_error_queue: rarely usedsk_receive_queue: incoming packetssk_backlog: always used with the per-socket spinlock heldsk_rx_dst: receive input route used by early demuxsk_rx_dst_ifindex: ifindex for sk_rx_dstsk_rx_dst_cookie: cookie for sk_rx_dstsk_ll_usec: usecs to busypoll when there is no datask_napi_id: id of the last napi context to receive data for sksk_busy_poll_budget: napi processing budget when busypollingsk_prefer_busy_poll: prefer busypolling over softirq processingsk_userlocks:SO_SNDBUFandSO_RCVBUFsettingssk_rcvbuf: size of receive buffer in bytessk_filter: socket filtering instructions{unnamed_union}: anonymoussk_wq: sock wait queue and async headsk_data_ready: callback to indicate there is data to be processedsk_rcvtimeo:SO_RCVTIMEOsettingsk_rcvlowat:SO_RCVLOWATsettingsk_err: last errorsk_socket: Identd and reporting IO signalssk_memcg: this socket's memory cgroup associationsk_policy: flow policypsp_assoc: PSP association, if socket is PSP-securedsk_lock: synchronizersk_reserved_mem: space reserved and non-reclaimable for the socketsk_forward_alloc: space allocated forwardsk_tsflags: SO_TIMESTAMPING flagssk_write_pending: a write to stream socket waits to startsk_omem_alloc: "o" is "option" or "other"sk_err_soft: errors that don't cause failure but are the cause of a persistent failure not just 'timed out'sk_wmem_queued: persistent queue sizesk_wmem_alloc: transmit queue bytes committedsk_tsq_flags: TCP Small Queues flags{unnamed_union}: anonymoussk_send_head: front of stuff to transmittcp_rtx_queue: TCP re-transmit queue [union with sk_send_head]sk_write_queue: Packet sending queuesk_frag: cached page frag{unnamed_union}: anonymoussk_timer: sock cleanup timertcp_retransmit_timer: tcp retransmit timermptcp_retransmit_timer: mptcp retransmit timersk_pacing_rate: Pacing rate (if supported by transport/packet scheduler)sk_zckey: counter to order MSG_ZEROCOPY notificationssk_tskey: counter to disambiguate concurrent tstamp requestssk_tx_queue_mapping_jiffies: time in jiffies of last sk_tx_queue_mapping refresh.sk_dst_pending_confirm: need to confirm neighboursk_pacing_status: Pacing status (requested, handled by sch_fq)sk_max_pacing_rate: Maximum pacing rate (SO_MAX_PACING_RATE)sk_sndtimeo:SO_SNDTIMEOsettingsk_priority:SO_PRIORITYsettingsk_mark: generic packet marksk_uid: user id of ownersk_protocol: which protocol this socket belongs in this network familysk_type: socket type (SOCK_STREAM, etc)sk_dst_cache: destination cachesk_route_caps: route capabilities (e.g.NETIF_F_TSO)sk_validate_xmit_skb: ptr to an optional validate functionsk_gso_type: GSO type (e.g.SKB_GSO_TCPV4)sk_gso_max_segs: Maximum number of GSO segmentssk_gso_max_size: Maximum GSO segment size to buildsk_allocation: allocation modesk_txhash: computed flow hash for use on transmitsk_sndbuf: size of send buffer in bytessk_pacing_shift: scaling factor for TCP Small Queuessk_use_task_frag: allowsk_page_frag()to use current->task_frag. Sockets that can be used under memory reclaim should set this to false.sk_gso_disabled: if set, NETIF_F_GSO_MASK is forbidden.sk_kern_sock: True if sock is using kernel lock classessk_no_check_tx:SO_NO_CHECKsetting, set checksum in TX packetssk_no_check_rx: allow zero checksum in RX packetssk_shutdown: mask ofSEND_SHUTDOWNand/orRCV_SHUTDOWNsk_lingertime:SO_LINGERl_linger settingsk_prot_creator: sk_prot of original sock creator (see ipv6_setsockopt, IPV6_ADDRFORM for instance)sk_callback_lock: used with the callbacks in the end of this structsk_ack_backlog: current listen backlogsk_max_ack_backlog: listen backlog set inlisten()sk_ino: inode number (zero if orphaned)sk_peer_lock: lock protecting sk_peer_pid and sk_peer_credsk_bind_phc: SO_TIMESTAMPING bind PHC index of PTP virtual clock for timestampingsk_peer_pid:struct pidfor this socket's peersk_peer_cred:SO_PEERCREDsettingsk_stamp: time stamp of last packet receivedsk_stamp_seq: lock for accessing sk_stamp on 32 bit architectures onlysk_disconnects: number of disconnect operations performed on this sock{unnamed_union}: anonymoussk_txrehash: enable TX hash rethinksk_scm_recv_flags: all flags used byscm_recv(){unnamed_struct}: anonymoussk_scm_credentials: flagged by SO_PASSCRED to recv SCM_CREDENTIALSsk_scm_security: flagged by SO_PASSSEC to recv SCM_SECURITYsk_scm_pidfd: flagged by SO_PASSPIDFD to recv SCM_PIDFDsk_scm_rights: flagged by SO_PASSRIGHTS to recv SCM_RIGHTSsk_scm_unused: unused flags forscm_recv()sk_clockid: clockid used by time-based scheduling (SO_TXTIME)sk_txtime_deadline_mode: set deadline mode for SO_TXTIMEsk_txtime_report_errors: set report errors mode for SO_TXTIMEsk_txtime_unused: unused txtime flagssk_bpf_cb_flags: used inbpf_setsockopt()sk_user_data: RPC layer private data. Write-protected by sk_callback_lock.sk_security: used by security modulessk_cgrp_data: cgroup data for this cgroupsk_state_change: callback to indicate change in the state of the socksk_write_space: callback to indicate there is bf sending space availablesk_error_report: callback to indicate errors (e.g.MSG_ERRQUEUE)sk_backlog_rcv: callback to process the backlogsk_destruct: called at sock freeing time, i.e. when all refcnt == 0sk_reuseport_cb: reuseport group containersk_bpf_storage: ptr to cache and control for bpf_sk_storagesk_drop_counters: optional pointer to numa_drop_counters{unnamed_union}: anonymoussk_rcu: used during RCU grace periodsk_freeptr: used for SLAB_TYPESAFE_BY_RCU managed socketsns_tracker: tracker for netns referencesk_user_frags: xarray of pages the user is holding a reference on.sk_owner: reference to the real owner of the socket that callssock_lock_init_class_and_name().
sk_user_data_is_nocopy() #
bool Test if sk_user_data pointer must not be copied
Parameters
const struct sock *sk: socket
__locked_read_sk_user_data_with_flags() #
void * return the pointer only if argument flags all has been set in sk_user_data. Otherwise return NULL
Parameters
const struct sock *sk: socketuintptr_t flags: flag bits
Description
The caller must be holding sk->sk_callback_lock.
__rcu_dereference_sk_user_data_with_flags() #
void * return the pointer only if argument flags all has been set in sk_user_data. Otherwise return NULL
Parameters
const struct sock *sk: socketuintptr_t flags: flag bits
sk_for_each_entry_offset_rcu() #
iterate over a list at a given struct offset
Parameters
tpos: the type * to use as a loop cursor.pos: thestruct hlist_nodeto use as a loop cursor.head: the head for your list.offset: offset of hlist_node within the struct.
SOCK_CONNECT_BIND #
sock->sk_userlocks flag for auto-bind at connect() time
lock_sock_fast() #
bool fast version of lock_sock
Parameters
struct sock *sk: socket
Description
This version should be used for very small section, where process won't block return false if fast path is taken:
sk_lock.slock locked, owned = 0, BH disabled
return true if slow path is taken:
sk_lock.slock unlocked, owned = 1, BH enabled
unlock_sock_fast() #
void complement of lock_sock_fast
Parameters
struct sock *sk: socketbool slow: slow mode
Description
fast unlock socket for user context.
If slow mode is on, we call regular release_sock()
sk_wmem_alloc_get() #
int returns write allocations
Parameters
const struct sock *sk: socket
Return
sk_wmem_alloc minus initial offset of one
sk_rmem_alloc_get() #
int returns read allocations
Parameters
const struct sock *sk: socket
Return
sk_rmem_alloc
sk_has_allocations() #
bool check if allocations are outstanding
Parameters
const struct sock *sk: socket
Return
true if socket has write or read allocations
skwq_has_sleeper() #
bool check if there are any waiting processes
Parameters
struct socket_wq *wq: struct socket_wq
Return
true if socket_wq has waiting processes
Description
The purpose of the skwq_has_sleeper and sock_poll_wait is to wrap the memory barrier call. They were added due to the race found within the tcp code.
Consider following tcp code paths:
CPU1 CPU2
sys_select receive packet
... ...
__add_wait_queue update tp->rcv_nxt
... ...
tp->rcv_nxt check sock_def_readable
... {
schedule rcu_read_lock();
wq = rcu_dereference(sk->sk_wq);
if (wq && waitqueue_active(&wq->wait))
wake_up_interruptible(&wq->wait)
...
}
The race for tcp fires when the __add_wait_queue changes done by CPU1 stay in its cache, and so does the tp->rcv_nxt update on CPU2 side. The CPU1 could then endup calling schedule and sleep forever if there are no more data on the socket.
sock_poll_wait() #
void wrapper for the poll_wait call.
Parameters
struct file *filp: filestruct socket *sock: socket to wait onpoll_table *p: poll_table
Description
See the comments in the wq_has_sleeper function.
sk_page_frag() #
struct page_frag * return an appropriate page_frag
Parameters
struct sock *sk: socket
Description
Use the per task page_frag instead of the per socket one for
optimization when we know that we're in process context and own
everything that's associated with current.
Both direct reclaim and page faults can nest inside other
socket operations and end up recursing into sk_page_frag()
while it's already in use: explicitly avoid task page_frag
when users disable sk_use_task_frag.
Return
a per task page_frag if context allows that, otherwise a per socket one.
_sock_tx_timestamp() #
void checks whether the outgoing packet is to be time stamped
Parameters
struct sock *sk: socket sending this packetconst struct sockcm_cookie *sockc: pointer to socket cmsg cookie to get timestamping info__u8 *tx_flags: completed with instructions for time stamping__u32 *tskey: filled in with next sk_tskey (not for TCP, which uses seqno)
Note
callers should take care of initial *tx_flags value (usually 0)
sk_eat_skb() #
void Release a skb if it is no longer needed
Parameters
struct sock *sk: socket to eat this skb fromstruct sk_buff *skb: socket buffer to eat
Description
This routine must be called with interrupts disabled or with the socket locked so that the sk_buff queue operation is ok.
sock_alloc_file() #
struct file * Parameters
struct socket *sock: socketint flags: file status flagsconst char *dname: protocol name
Description
Returns the file bound with sock, implicitly storing it
in sock->file. If dname is NULL, sets to "".
On failure sock is released, and an ERR pointer is returned.
This function uses GFP_KERNEL internally.
sock_from_file() #
struct socket * Return the socket bounded to file.
Parameters
struct file *file: file
Description
On failure returns NULL.
sockfd_lookup() #
struct socket * Go from a file number to its socket slot
Parameters
int fd: file handleint *err: pointer to an error code return
Description
The file handle passed in is locked and the socket it is bound to is returned. If an error occurs the err pointer is overwritten with a negative errno code and NULL is returned. The function checks for both invalid handles and passing a handle which is not a socket.
On a success the socket object pointer is returned.
sock_alloc() #
struct socket * allocate a socket
Parameters
void: no arguments
Description
Allocate a new inode and socket object. The two are bound together and initialised. The socket is then returned. If we are out of inodes NULL is returned. This functions uses GFP_KERNEL internally.
sock_release() #
void close a socket
Parameters
struct socket *sock: socket to close
Description
The socket is released from the protocol stack if it has a release callback, and the inode is then released if the socket is bound to an inode not a file.
sock_sendmsg() #
int send a message through sock
Parameters
struct socket *sock: socketstruct msghdr *msg: message to send
Description
Sends msg through sock, passing through LSM. Returns the number of bytes sent, or an error code.
kernel_sendmsg() #
int send a message through sock (kernel-space)
Parameters
struct socket *sock: socketstruct msghdr *msg: message headerstruct kvec *vec: kernel vecsize_t num: vec array lengthsize_t size: total message data size
Description
Builds the message data with vec and sends it through sock. Returns the number of bytes sent, or an error code.
sock_recvmsg() #
int receive a message from sock
Parameters
struct socket *sock: socketstruct msghdr *msg: message to receiveint flags: message flags
Description
Receives msg from sock, passing through LSM. Returns the total number of bytes received, or an error.
kernel_recvmsg() #
int Receive a message from a socket (kernel space)
Parameters
struct socket *sock: The socket to receive the message fromstruct msghdr *msg: Received messagestruct kvec *vec: Input s/g array for message datasize_t num: Size of input s/g arraysize_t size: Number of bytes to readint flags: Message flags (MSG_DONTWAIT, etc...)
Description
On return the msg structure contains the scatter/gather array passed in the vec argument. The array is modified so that it consists of the unfilled portion of the original array.
The returned value is the total number of bytes received, or an error.
sock_create_lite() #
int creates a socket
Parameters
int family: protocol family (AF_INET, ...)int type: communication type (SOCK_STREAM, ...)int protocol: protocol (0, ...)struct socket **res: new socket
Description
Creates a new socket and assigns it to res, passing through LSM.
The new socket initialization is not complete, see kernel_accept().
Returns 0 or an error. On failure res is set to NULL.
This function internally uses GFP_KERNEL.
__sock_create() #
int creates a socket
Parameters
struct net *net: net namespaceint family: protocol family (AF_INET, ...)int type: communication type (SOCK_STREAM, ...)int protocol: protocol (0, ...)struct socket **res: new socketint kern: boolean for kernel space sockets
Description
Creates a new socket and assigns it to res, passing through LSM.
Returns 0 or an error. On failure res is set to NULL. kern must
be set to true if the socket resides in kernel space.
This function internally uses GFP_KERNEL.
sock_create() #
int creates a socket
Parameters
int family: protocol family (AF_INET, ...)int type: communication type (SOCK_STREAM, ...)int protocol: protocol (0, ...)struct socket **res: new socket
Description
A wrapper around __sock_create().
Returns 0 or an error. This function internally uses GFP_KERNEL.
sock_create_kern() #
int creates a socket (kernel space)
Parameters
struct net *net: net namespaceint family: protocol family (AF_INET, ...)int type: communication type (SOCK_STREAM, ...)int protocol: protocol (0, ...)struct socket **res: new socket
Description
A wrapper around __sock_create().
Returns 0 or an error. This function internally uses GFP_KERNEL.
sock_register() #
int add a socket protocol handler
Parameters
const struct net_proto_family *ops: description of protocol
Description
This function is called by a protocol handler that wants to advertise its address family, and have it linked into the socket interface. The value ops->family corresponds to the socket system call protocol family.
sock_unregister() #
void remove a protocol handler
Parameters
int family: protocol family to remove
Description
This function is called by a protocol handler that wants to remove its address family, and have it unlinked from the new socket creation.
If protocol handler is a module, then it can use module reference counts to protect against new references. If protocol handler is not a module then it needs to provide its own protection in the ops->create routine.
kernel_bind() #
int bind an address to a socket (kernel space)
Parameters
struct socket *sock: socketstruct sockaddr_unsized *addr: addressint addrlen: length of address
Description
Returns 0 or an error.
kernel_listen() #
int move socket to listening state (kernel space)
Parameters
struct socket *sock: socketint backlog: pending connections queue size
Description
Returns 0 or an error.
kernel_accept() #
int accept a connection (kernel space)
Parameters
struct socket *sock: listening socketstruct socket **newsock: new connected socketint flags: flags
Description
flags must be SOCK_CLOEXEC, SOCK_NONBLOCK or 0.
If it fails, newsock is guaranteed to be NULL.
Returns 0 or an error.
kernel_connect() #
int connect a socket (kernel space)
Parameters
struct socket *sock: socketstruct sockaddr_unsized *addr: addressint addrlen: address lengthint flags: flags (O_NONBLOCK, ...)
Description
For datagram sockets, addr is the address to which datagrams are sent by default, and the only address from which datagrams are received. For stream sockets, attempts to connect to addr. Returns 0 or an error code.
kernel_getsockname() #
int get the address which the socket is bound (kernel space)
Parameters
struct socket *sock: socketstruct sockaddr *addr: address holder
Description
Fills the addr pointer with the address which the socket is bound. Returns the length of the address in bytes or an error code.
kernel_getpeername() #
int get the address which the socket is connected (kernel space)
Parameters
struct socket *sock: socketstruct sockaddr *addr: address holder
Description
Fills the addr pointer with the address which the socket is connected. Returns the length of the address in bytes or an error code.
kernel_sock_shutdown() #
int shut down part of a full-duplex connection (kernel space)
Parameters
struct socket *sock: socketenum sock_shutdown_cmd how: connection part
Description
Returns 0 or an error.
kernel_sock_ip_overhead() #
u32 returns the IP overhead imposed by a socket
Parameters
struct sock *sk: socket
Description
This routine returns the IP overhead imposed by a socket i.e. the length of the underlying IP header, depending on whether this is an IPv4 or IPv6 socket and the length from IP options turned on at the socket. Assumes that the caller has a lock on the socket.
drop_reasons_register_subsys() #
void register another drop reason subsystem
Parameters
enum skb_drop_reason_subsys subsys: the subsystem to register, must not be the coreconst struct drop_reason_list *list: the list of drop reasons within the subsystem, must point to a statically initialized list
drop_reasons_unregister_subsys() #
void unregister a drop reason subsystem
Parameters
enum skb_drop_reason_subsys subsys: the subsystem to remove, must not be the core
Note
This will synchronize_rcu() to ensure no users when it returns.
napi_skb_cache_get_bulk() #
u32 obtain a number of zeroed skb heads from the cache
Parameters
void **skbs: pointer to an at least n-sized array to fill with skb pointersu32 n: number of entries to provide
Description
Tries to obtain n sk_buff entries from the NAPI percpu cache and writes
the pointers into the provided array skbs. If there are less entries
available, tries to replenish the cache and bulk-allocates the diff from
the MM layer if needed.
The heads are being zeroed with either memset() or __GFP_ZERO, so they are
ready for {,__}build_skb_around() and don't have any data buffers attached.
Must be called only from the BH context.
Return
number of successfully allocated skbs (n if no actual allocation
needed or kmem_cache_alloc_bulk() didn't fail).
build_skb_around() #
struct sk_buff * build a network buffer around provided skb
Parameters
struct sk_buff *skb: sk_buff provide by caller, must be memset clearedvoid *data: data buffer provided by callerunsigned int frag_size: size of data
napi_build_skb() #
struct sk_buff * build a network buffer
Parameters
void *data: data buffer provided by callerunsigned int frag_size: size of data
Description
Version of __napi_build_skb() that takes care of skb->head_frag
and skb->pfmemalloc when the data is a page or page fragment.
Returns a new sk_buff on success, NULL on allocation failure.
__alloc_skb() #
struct sk_buff * allocate a network buffer
Parameters
unsigned int size: size to allocategfp_t gfp_mask: allocation maskint flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache instead of head cache and allocate a cloned (child) skb. If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for allocations in case the data is required for writebackint node: numa node to allocate memory on
Description
Allocate a new sk_buff. The returned buffer has no headroom and a
tail room of at least size bytes. The object has a reference count
of one. The return is the buffer. On a failure the return is NULL.
Buffers may only be allocated from interrupts using a gfp_mask of
GFP_ATOMIC.
__netdev_alloc_skb() #
struct sk_buff * allocate an skbuff for rx on a specific device
Parameters
struct net_device *dev: network device to receive onunsigned int len: length to allocategfp_t gfp_mask: get_free_pages mask, passed to alloc_skb
Description
Allocate a new sk_buff and assign it a usage count of one. The
buffer has NET_SKB_PAD headroom built in. Users should allocate
the headroom they think they need without accounting for the
built in space. The built in space is used for optimisations.
NULL is returned if there is no free memory.
napi_alloc_skb() #
struct sk_buff * allocate skbuff for rx in a specific NAPI instance
Parameters
struct napi_struct *napi: napi instance this buffer was allocated forunsigned int len: length to allocate
Description
Allocate a new sk_buff for use in NAPI receive. This buffer will attempt to allocate the head from a special reserved region used only for NAPI Rx allocation. By doing this we can save several CPU cycles by avoiding having to disable and re-enable IRQs.
NULL is returned if there is no free memory.
__kfree_skb() #
void private function
Parameters
struct sk_buff *skb: buffer
Description
Free an sk_buff. Release anything attached to the buffer. Clean the state. This is an internal helper function. Users should always call kfree_skb
sk_skb_reason_drop() #
void __fix_address free an sk_buff with special reason
Parameters
struct sock *sk: the socket to receive skb, or NULL if not applicablestruct sk_buff *skb: buffer to freeenum skb_drop_reason reason: reason why this skb is dropped
Description
Drop a reference to the buffer and free it if the usage count has hit zero. Meanwhile, pass the receiving socket and drop reason to 'kfree_skb' tracepoint.
skb_tx_error() #
void report an sk_buff xmit error
Parameters
struct sk_buff *skb: buffer that triggered an error
Description
Report xmit error if a device callback is tracking this skb. skb must be freed afterwards.
consume_skb() #
void free an skbuff
Parameters
struct sk_buff *skb: buffer to free
Description
Drop a ref to the buffer and free it if the usage count has hit zero Functions identically to kfree_skb, but kfree_skb assumes that the frame is being dropped after a failure and notes that
napi_consume_skb() #
void consume skb in NAPI context, try to feed skb cache
Parameters
struct sk_buff *skb: buffer to freeint budget: NAPI budget
Description
Non-zero budget must come from the budget argument passed by the core to a NAPI poll function. Note that core may pass budget of 0 to NAPI poll for example when polling for netpoll / netconsole.
Passing budget of 0 is safe from any context, it turns this function
into dev_consume_skb_any().
alloc_skb_for_msg() #
struct sk_buff * allocate sk_buff to wrap frag list forming a msg
Parameters
struct sk_buff *first: first sk_buff of the msg
skb_morph() #
struct sk_buff * morph one skb into another
Parameters
struct sk_buff *dst: the skb to receive the contentsstruct sk_buff *src: the skb to supply the contents
Description
This is identical to skb_clone except that the target skb is supplied by the user.
The target skb is returned upon exit.
skb_copy_ubufs() #
int copy userspace skb frags buffers to kernel
Parameters
struct sk_buff *skb: the skb to modifygfp_t gfp_mask: allocation priority
Description
This must be called on skb with SKBFL_ZEROCOPY_ENABLE. It will copy all frags into kernel and drop the reference to userspace pages.
If this function is called from an interrupt gfp_mask() must be
GFP_ATOMIC.
Returns 0 on success or a negative error code on failure to allocate kernel memory to copy to.
skb_clone() #
struct sk_buff * duplicate an sk_buff
Parameters
struct sk_buff *skb: buffer to clonegfp_t gfp_mask: allocation priority
Description
Duplicate an sk_buff. The new one is not owned by a socket. Both
copies share the same packet data but not structure. The new
buffer has a reference count of 1. If the allocation fails the
function returns NULL otherwise the new buffer is returned.
If this function is called from an interrupt gfp_mask() must be
GFP_ATOMIC.
skb_copy() #
struct sk_buff * create private copy of an sk_buff
Parameters
const struct sk_buff *skb: buffer to copygfp_t gfp_mask: allocation priority
Description
Make a copy of both an sk_buff and its data. This is used when the
caller wishes to modify the data and needs a private copy of the
data to alter. Returns NULL on failure or the pointer to the buffer
on success. The returned buffer has a reference count of 1.
As by-product this function converts non-linear sk_buff to linear
one, so that sk_buff becomes completely private and caller is allowed
to modify all the data of returned buffer. This means that this
function is not recommended for use in circumstances when only
header is going to be modified. Use pskb_copy() instead.
__pskb_copy_fclone() #
struct sk_buff * create copy of an sk_buff with private head.
Parameters
struct sk_buff *skb: buffer to copyint headroom: headroom of new skbgfp_t gfp_mask: allocation prioritybool fclone: if true allocate the copy of the skb from the fclone cache instead of the head cache; it is recommended to set this to true for the cases where the copy will likely be cloned
Description
Make a copy of both an sk_buff and part of its data, located
in header. Fragmented data remain shared. This is used when
the caller wishes to modify only header of sk_buff and needs
private copy of the header to alter. Returns NULL on failure
or the pointer to the buffer on success.
The returned buffer has a reference count of 1.
pskb_expand_head() #
int reallocate header of sk_buff
Parameters
struct sk_buff *skb: buffer to reallocateint nhead: room to add at headint ntail: room to add at tailgfp_t gfp_mask: allocation priority
Description
Expands (or creates identical copy, if nhead and ntail are zero)
header of skb. sk_buff itself is not changed. sk_buff MUST have
reference count of 1. Returns zero in the case of success or error,
if expansion failed. In the last case, sk_buff is not changed.
All the pointers pointing into skb header may change and must be reloaded after call to this function.
Note
-
If you
skb_push()the start of the buffer after reallocating theheader, call
skb_postpush_data_move()first to move the metadata out of the way before writing tosk_buff->data.
skb_expand_head() #
struct sk_buff * reallocate header of sk_buff
Parameters
struct sk_buff *skb: buffer to reallocateunsigned int headroom: needed headroom
Description
Unlike skb_realloc_headroom, this one does not allocate a new skb if possible; copies skb->sk to new skb as needed and frees original skb in case of failures.
It expect increased headroom and generates warning otherwise.
skb_copy_expand() #
struct sk_buff * copy and expand sk_buff
Parameters
const struct sk_buff *skb: buffer to copyint newheadroom: new free bytes at headint newtailroom: new free bytes at tailgfp_t gfp_mask: allocation priority
Description
Make a copy of both an sk_buff and its data and while doing so
allocate additional space.
This is used when the caller wishes to modify the data and needs a
private copy of the data to alter as well as more space for new fields.
Returns NULL on failure or the pointer to the buffer
on success. The returned buffer has a reference count of 1.
You must pass GFP_ATOMIC as the allocation priority if this function
is called from an interrupt.
__skb_pad() #
int zero pad the tail of an skb
Parameters
struct sk_buff *skb: buffer to padint pad: space to padbool free_on_error: free buffer on error
Description
Ensure that a buffer is followed by a padding area that is zero filled. Used by network drivers which may DMA or transfer data beyond the buffer end onto the wire.
May return error in out of memory cases. The skb is freed on error if free_on_error is true.
pskb_put() #
void * add data to the tail of a potentially fragmented buffer
Parameters
struct sk_buff *skb: start of the buffer to usestruct sk_buff *tail: tail fragment of the buffer to useint len: amount of data to add
Description
This function extends the used data area of the potentially fragmented buffer. tail must be the last fragment of skb -- or skb itself. If this would exceed the total buffer size the kernel will panic. A pointer to the first byte of the extra data is returned.
skb_put() #
void * add data to a buffer
Parameters
struct sk_buff *skb: buffer to useunsigned int len: amount of data to add
Description
This function extends the used data area of the buffer. If this would exceed the total buffer size the kernel will panic. A pointer to the first byte of the extra data is returned.
skb_push() #
void * add data to the start of a buffer
Parameters
struct sk_buff *skb: buffer to useunsigned int len: amount of data to add
Description
This function extends the used data area of the buffer at the buffer start. If this would exceed the total buffer headroom the kernel will panic. A pointer to the first byte of the extra data is returned.
skb_pull() #
void * remove data from the start of a buffer
Parameters
struct sk_buff *skb: buffer to useunsigned int len: amount of data to remove
Description
This function removes data from the start of a buffer, returning the memory to the headroom. A pointer to the next data in the buffer is returned. Once the data has been pulled future pushes will overwrite the old data.
skb_pull_data() #
void * remove data from the start of a buffer returning its original position.
Parameters
struct sk_buff *skb: buffer to usesize_t len: amount of data to remove
Description
This function removes data from the start of a buffer, returning the memory to the headroom. A pointer to the original data in the buffer is returned after checking if there is enough data to pull. Once the data has been pulled future pushes will overwrite the old data.
skb_trim() #
void remove end from a buffer
Parameters
struct sk_buff *skb: buffer to alterunsigned int len: new length
Description
Cut the length of a buffer down by removing data from the tail. If the buffer is already under the length specified it is not modified. The skb must be linear.
__pskb_pull_tail() #
void * advance tail of skb header
Parameters
struct sk_buff *skb: buffer to reallocateint delta: number of bytes to advance tail
Description
The function makes a sense only on a fragmented sk_buff,
it expands header moving its tail forward and copying necessary
data from fragmented part.
sk_buff MUST have reference count of 1.
Returns NULL (and sk_buff does not change) if pull failed
or value of new tail of skb in the case of success.
All the pointers pointing into skb header may change and must be reloaded after call to this function.
skb_copy_bits() #
int copy bits from skb to kernel buffer
Parameters
const struct sk_buff *skb: source skbint offset: offset in sourcevoid *to: destination bufferint len: number of bytes to copy
Description
Copy the specified number of bytes from the source skb to the destination buffer.
- CAUTION ! : If its prototype is ever changed, check arch/{}/net/{}.S files, since it is called from BPF assembly code.
skb_store_bits() #
int store bits from kernel buffer to skb
Parameters
struct sk_buff *skb: destination bufferint offset: offset in destinationconst void *from: source bufferint len: number of bytes to copy
Description
Copy the specified number of bytes from the source buffer to the destination skb. This function handles all the messy bits of traversing fragment lists and such.
skb_zerocopy() #
int Zero copy skb to skb
Parameters
struct sk_buff *to: destination bufferstruct sk_buff *from: source bufferint len: number of bytes to copy from source bufferint hlen: size of linear headroom in destination buffer
Description
Copies up to len bytes from from to to by creating references
to the frags in the source buffer.
The hlen as calculated by skb_zerocopy_headlen() specifies the
headroom in the to buffer.
Return value:
0: everything is OK
-ENOMEM: couldn't orphan frags of from due to lack of memory
-EFAULT: skb_copy_bits() found some problem with skb geometry
skb_dequeue() #
struct sk_buff * remove from the head of the queue
Parameters
struct sk_buff_head *list: list to dequeue from
Description
Remove the head of the list. The list lock is taken so the function
may be used safely with other locking list functions. The head item is
returned or NULL if the list is empty.
skb_dequeue_tail() #
struct sk_buff * remove from the tail of the queue
Parameters
struct sk_buff_head *list: list to dequeue from
Description
Remove the tail of the list. The list lock is taken so the function
may be used safely with other locking list functions. The tail item is
returned or NULL if the list is empty.
skb_queue_purge_reason() #
void empty a list
Parameters
struct sk_buff_head *list: list to emptyenum skb_drop_reason reason: drop reason
Description
Delete all buffers on an sk_buff list. Each buffer is removed from
the list and one reference dropped. This function takes the list
lock and is atomic with respect to other list locking functions.
skb_queue_head() #
void queue a buffer at the list head
Parameters
struct sk_buff_head *list: list to usestruct sk_buff *newsk: buffer to queue
Description
Queue a buffer at the start of the list. This function takes the
list lock and can be used safely with other locking sk_buff functions
safely.
A buffer cannot be placed on two lists at the same time.
skb_queue_tail() #
void queue a buffer at the list tail
Parameters
struct sk_buff_head *list: list to usestruct sk_buff *newsk: buffer to queue
Description
Queue a buffer at the tail of the list. This function takes the
list lock and can be used safely with other locking sk_buff functions
safely.
A buffer cannot be placed on two lists at the same time.
skb_unlink() #
void remove a buffer from a list
Parameters
struct sk_buff *skb: buffer to removestruct sk_buff_head *list: list to use
Description
Remove a packet from a list. The list locks are taken and this function is atomic with respect to other list locked calls
You must know what list the SKB is on.
skb_append() #
void append a buffer
Parameters
struct sk_buff *old: buffer to insert afterstruct sk_buff *newsk: buffer to insertstruct sk_buff_head *list: list to use
Description
Place a packet after a given packet in a list. The list locks are taken and this function is atomic with respect to other list locked calls. A buffer cannot be placed on two lists at the same time.
skb_split() #
void Split fragmented skb to two parts at length len.
Parameters
struct sk_buff *skb: the buffer to splitstruct sk_buff *skb1: the buffer to receive the second partconst u32 len: new length for skb
skb_prepare_seq_read() #
void Prepare a sequential read of skb data
Parameters
struct sk_buff *skb: the buffer to readunsigned int from: lower offset of data to be readunsigned int to: upper offset of data to be readstruct skb_seq_state *st: state variable
Description
Initializes the specified state variable. Must be called before
invoking skb_seq_read() for the first time.
skb_seq_read() #
unsigned int Sequentially read skb data
Parameters
unsigned int consumed: number of bytes consumed by the caller so farconst u8 **data: destination pointer for data to be returnedstruct skb_seq_state *st: state variable
Description
Reads a block of skb data at consumed relative to the
lower offset specified to skb_prepare_seq_read(). Assigns
the head of the data block to data and returns the length
of the block or 0 if the end of the skb data or the upper
offset has been reached.
The caller is not required to consume all of the data
returned, i.e. consumed is typically set to the number
of bytes already consumed and the next call to
skb_seq_read() will return the remaining part of the block.
-
Note 1: The size of each block of data returned can be arbitrary,
this limitation is the cost for zerocopy sequential reads of potentially non linear data.
-
Note 2: Fragment lists within fragments are not implemented
at the moment, state->root_skb could be replaced with a stack for this purpose.
skb_abort_seq_read() #
void Abort a sequential read of skb data
Parameters
struct skb_seq_state *st: state variable
Description
Must be called if skb_seq_read() was not called until it
returned 0.
skb_copy_seq_read() #
int copy from a skb_seq_state to a buffer
Parameters
struct skb_seq_state *st: source skb_seq_stateint offset: offset in sourcevoid *to: destination bufferint len: number of bytes to copy
Description
Copy len bytes from offset bytes into the source st to the destination
buffer to. offset should increase (or be unchanged) with each subsequent
call to this function. If offset needs to decrease from the previous use st
should be reset first.
Return
0 on success or -EINVAL if the copy ended early
skb_find_text() #
unsigned int Find a text pattern in skb data
Parameters
struct sk_buff *skb: the buffer to look inunsigned int from: search offsetunsigned int to: search limitstruct ts_config *config: textsearch configuration
Description
Finds a pattern in the skb data according to the specified
textsearch configuration. Use textsearch_next() to retrieve
subsequent occurrences of the pattern. Returns the offset
to the first occurrence or UINT_MAX if no match was found.
skb_pull_rcsum() #
void * pull skb and update receive checksum
Parameters
struct sk_buff *skb: buffer to updateunsigned int len: length of data pulled
Description
This function performs an skb_pull on the packet and updates the CHECKSUM_COMPLETE checksum. It should be used on receive path processing instead of skb_pull unless you know that the checksum difference is zero (e.g., a valid IP header) or you are setting ip_summed to CHECKSUM_NONE.
skb_segment() #
struct sk_buff * Perform protocol segmentation on skb.
Parameters
struct sk_buff *head_skb: buffer to segmentnetdev_features_t features: features for the output path (see dev->features)
Description
This function performs segmentation on the given skb. It returns a pointer to the first in a list of new skbs for the segments. In case of error it returns ERR_PTR(err).
skb_to_sgvec() #
int Fill a scatter-gather list from a socket buffer
Parameters
struct sk_buff *skb: Socket buffer containing the buffers to be mappedstruct scatterlist *sg: The scatter-gather list to map intoint offset: The offset into the buffer's contents to start mappingint len: Length of buffer space to be mapped
Description
Fill the specified scatter-gather list with mappings/pointers into a region of the buffer space attached to a socket buffer. Returns either the number of scatterlist items used, or -EMSGSIZE if the contents could not fit.
skb_cow_data() #
int Check that a socket buffer's data buffers are writable
Parameters
struct sk_buff *skb: The socket buffer to check.int tailbits: Amount of trailing space to be addedstruct sk_buff **trailer: Returned pointer to the skb where the tailbits space begins
Description
Make sure that the data buffers attached to a socket buffer are writable. If they are not, private copies are made of the data buffers and the socket buffer is set to use these instead.
If tailbits is given, make sure that there is space to write tailbits bytes of data beyond current end of socket buffer. trailer will be set to point to the skb in which this space begins.
The number of scatterlist elements required to completely map the COW'd and extended socket buffer will be returned.
skb_clone_sk() #
struct sk_buff * create clone of skb, and take reference to socket
Parameters
struct sk_buff *skb: the skb to clone
Description
This function creates a clone of a buffer that holds a reference on sk_refcnt. Buffers created via this function are meant to be returned using sock_queue_err_skb, or free via kfree_skb.
When passing buffers allocated with this function to sock_queue_err_skb it is necessary to wrap the call with sock_hold/sock_put in order to prevent the socket from being released prior to being enqueued on the sk_error_queue.
skb_partial_csum_set() #
bool set up and verify partial csum values for packet
Parameters
struct sk_buff *skb: the skb to setu16 start: the number of bytes after skb->data to start checksumming.u16 off: the offset from start to place the checksum.
Description
For untrusted partially-checksummed packets, we need to make sure the values for skb->csum_start and skb->csum_offset are valid so we don't oops.
This function checks and sets those values and skb->ip_summed: if this returns false you should drop the packet.
skb_checksum_setup() #
int set up partial checksum offset
Parameters
struct sk_buff *skb: the skb to set upbool recalculate: if true the pseudo-header checksum will be recalculated
skb_checksum_trimmed() #
struct sk_buff * validate checksum of an skb
Parameters
struct sk_buff *skb: the skb to checkunsigned int transport_len: the data length beyond the network header__sum16(*skb_chkf)(struct sk_buff *skb): checksum function to use
Description
Applies the given checksum function skb_chkf to the provided skb. Returns a checked and maybe trimmed skb. Returns NULL on error.
If the skb has data beyond the given transport length, then a trimmed & cloned skb is checked and returned.
Caller needs to set the skb transport header and free any returned skb if it differs from the provided skb.
skb_try_coalesce() #
bool try to merge skb to prior one
Parameters
struct sk_buff *to: prior bufferstruct sk_buff *from: buffer to addbool *fragstolen: pointer to booleanint *delta_truesize: how much more was allocated than was requested
skb_scrub_packet() #
void scrub an skb
Parameters
struct sk_buff *skb: buffer to cleanbool xnet: packet is crossing netns
Description
skb_scrub_packet can be used after encapsulating or decapsulating a packet into/from a tunnel. Some information have to be cleared during these operations. skb_scrub_packet can also be used to clean a skb before injecting it in another namespace (xnet == true). We have to clear all information in the skb that could impact namespace isolation.
skb_eth_pop() #
int Drop the Ethernet header at the head of a packet
Parameters
struct sk_buff *skb: Socket buffer to modify
Description
Drop the Ethernet header of skb.
Expects that skb->data points to the mac header and that no VLAN tags are present.
Returns 0 on success, -errno otherwise.
skb_eth_push() #
int Add a new Ethernet header at the head of a packet
Parameters
struct sk_buff *skb: Socket buffer to modifyconst unsigned char *dst: Destination MAC address of the new headerconst unsigned char *src: Source MAC address of the new header
Description
Prepend skb with a new Ethernet header.
Expects that skb->data points to the mac header, which must be empty.
Returns 0 on success, -errno otherwise.
skb_mpls_push() #
int push a new MPLS header after mac_len bytes from start of the packet
Parameters
struct sk_buff *skb: buffer__be32 mpls_lse: MPLS label stack entry to push__be16 mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)int mac_len: length of the MAC headerbool ethernet: flag to indicate if the resulting packet after skb_mpls_push is ethernet
Description
Expects skb->data at mac header.
Returns 0 on success, -errno otherwise.
skb_mpls_pop() #
int pop the outermost MPLS header
Parameters
struct sk_buff *skb: buffer__be16 next_proto: ethertype of header after popped MPLS headerint mac_len: length of the MAC headerbool ethernet: flag to indicate if the packet is ethernet
Description
Expects skb->data at mac header.
Returns 0 on success, -errno otherwise.
skb_mpls_update_lse() #
int modify outermost MPLS header and update csum
Parameters
struct sk_buff *skb: buffer__be32 mpls_lse: new MPLS label stack entry to update to
Description
Expects skb->data at mac header.
Returns 0 on success, -errno otherwise.
skb_mpls_dec_ttl() #
int decrement the TTL of the outermost MPLS header
Parameters
struct sk_buff *skb: buffer
Description
Expects skb->data at mac header.
Returns 0 on success, -errno otherwise.
alloc_skb_with_frags() #
struct sk_buff * allocate skb with page frags
Parameters
unsigned long header_len: size of linear partunsigned long data_len: needed length in fragsint order: max page order desired.int *errcode: pointer to error code if anygfp_t gfp_mask: allocation mask
Description
This can be used to allocate a paged skb, given a maximal order for frags.
skb_condense() #
void try to get rid of fragments/frag_list if possible
Parameters
struct sk_buff *skb: buffer
Description
Can be used to save memory before skb is added to a busy queue. If packet has bytes in frags and enough tail room in skb->head, pull all of them, so that we can free the frags right now and adjust truesize.
Notes
We do not reallocate skb->head thus can not fail. Caller must re-evaluate skb->truesize if needed.
__skb_ext_set() #
void * attach the specified extension storage to this skb
Parameters
struct sk_buff *skb: bufferenum skb_ext_id id: extension idstruct skb_ext *ext: extension storage previously allocated via__skb_ext_alloc()
Description
Existing extensions, if any, are cleared.
Returns the pointer to the extension.
skb_ext_add() #
void * allocate space for given extension, COW if needed
Parameters
struct sk_buff *skb: bufferenum skb_ext_id id: extension to allocate space for
Description
Allocates enough space for the given extension. If the extension is already present, a pointer to that extension is returned.
If the skb was cloned, COW applies and the returned memory can be modified without changing the extension space of clones buffers.
Returns pointer to the extension or NULL on allocation failure.
skb_splice_from_iter() #
ssize_t Splice (or copy) pages to skbuff
Parameters
struct sk_buff *skb: The buffer to add pages tostruct iov_iter *iter: Iterator representing the pages to be addedssize_t maxsize: Maximum amount of pages to be added
Description
This is a common helper function for supporting MSG_SPLICE_PAGES. It extracts pages from an iterator and adds them to the socket buffer if possible, copying them to fragments if not possible (such as if they're slab pages).
Returns the amount of data spliced/copied or -EMSGSIZE if there's insufficient space in the buffer to transfer anything.
sk_ns_capable() #
bool General socket capability test
Parameters
const struct sock *sk: Socket to use a capability on or throughstruct user_namespace *user_ns: The user namespace of the capability to useint cap: The capability to use
Description
Test to see if the opener of the socket had when the socket was created and the current process has the capability cap in the user namespace user_ns.
sk_capable() #
bool Socket global capability test
Parameters
const struct sock *sk: Socket to use a capability on or throughint cap: The global capability to use
Description
Test to see if the opener of the socket had when the socket was created and the current process has the capability cap in all user namespaces.
sk_net_capable() #
bool Network namespace socket capability test
Parameters
const struct sock *sk: Socket to use a capability on or throughint cap: The capability to use
Description
Test to see if the opener of the socket had when the socket was created and the current process has the capability cap over the network namespace the socket is a member of.
sk_set_memalloc() #
void sets SOCK_MEMALLOC
Parameters
struct sock *sk: socket to set it on
Description
Set SOCK_MEMALLOC on a socket for access to emergency reserves.
It's the responsibility of the admin to adjust min_free_kbytes
to meet the requirements
sk_alloc() #
struct sock * All socket objects are allocated here
Parameters
struct net *net: the applicable net namespaceint family: protocol familygfp_t priority: for allocation (GFP_KERNEL,GFP_ATOMIC, etc)struct proto *prot: struct proto associated with this new sock instanceint kern: is this to be a kernel socket?
sk_clone() #
struct sock * clone a socket
Parameters
const struct sock *sk: the socket to cloneconst gfp_t priority: for allocation (GFP_KERNEL,GFP_ATOMIC, etc)bool lock: if true, lock the cloned sk
Description
If lock is true, the clone is locked by bh_lock_sock(), and
caller must unlock socket even in error path by bh_unlock_sock().
skb_page_frag_refill() #
bool check that a page_frag contains enough room
Parameters
unsigned int sz: minimum size of the fragment we want to getstruct page_frag *pfrag: pointer to page_fraggfp_t gfp: priority for memory allocation
Note
While this allocator tries to use high order pages, there is no guarantee that allocations succeed. Therefore, sz MUST be less or equal than PAGE_SIZE.
sk_wait_data() #
int wait for data to arrive at sk_receive_queue
Parameters
struct sock *sk: sock to wait onlong *timeo: for how longconst struct sk_buff *skb: last skb seen on sk_receive_queue
Description
Now socket state including sk->sk_err is changed only under lock,
hence we may omit checks after joining wait queue.
We check receive queue before schedule() only as optimization;
it is very likely that release_sock() added new data.
__sk_mem_schedule() #
int increase sk_forward_alloc and memory_allocated
Parameters
struct sock *sk: socketint size: memory size to allocateint kind: allocation type
Description
If kind is SK_MEM_SEND, it means wmem allocation. Otherwise it means rmem allocation. This function assumes that protocols which have memory_pressure use sk_wmem_queued as write buffer accounting.
__sk_mem_reclaim() #
void reclaim sk_forward_alloc and memory_allocated
Parameters
struct sock *sk: socketint amount: number of bytes (rounded down to a PAGE_SIZE multiple)
__skb_try_recv_datagram() #
struct sk_buff * Receive a datagram skbuff
Parameters
struct sock *sk: socketstruct sk_buff_head *queue: socket queue from which to receiveunsigned int flags: MSG_ flagsint *off: an offset in bytes to peek skb from. Returns an offset within an skb where data actually startsint *err: error code returnedstruct sk_buff **last: set to last peeked message to inform the wait function what to look for when peeking
Description
Get a datagram skbuff, understands the peeking, nonblocking wakeups and possible races. This replaces identical code in packet, raw and udp, as well as the IPX AX.25 and Appletalk. It also finally fixes the long standing peek and read race for datagram sockets. If you alter this routine remember it must be re-entrant.
This function will lock the socket if a skb is returned, so the caller needs to unlock the socket in that case (usually by calling skb_free_datagram). Returns NULL with err set to -EAGAIN if no data was available or to some other value if an error was detected.
- It does not lock socket since today. This function is
- free of race conditions. This measure should/can improve
- significantly datagram socket latencies at high loads,
- when data copying to user space takes lots of time.
- (BTW I've just killed the last
cli()in IP/IPv6/core/netlink/packet -
- Great win.)
- --ANK (980729)
The order of the tests when we find no data waiting are specified quite explicitly by POSIX 1003.1g, don't change them without having the standard around please.
skb_kill_datagram() #
int Free a datagram skbuff forcibly
Parameters
struct sock *sk: socketstruct sk_buff *skb: datagram skbuffunsigned int flags: MSG_ flags
Description
This function frees a datagram skbuff that was received by skb_recv_datagram. The flags argument must match the one used for skb_recv_datagram.
If the MSG_PEEK flag is set, and the packet is still on the receive queue of the socket, it will be taken off the queue before it is freed.
This function currently only disables BH when acquiring the sk_receive_queue lock. Therefore it must not be used in a context where that lock is acquired in an IRQ context.
It returns 0 if the packet was removed by us.
skb_copy_and_crc32c_datagram_iter() #
int Copy datagram to an iovec iterator and update a CRC32C value.
Parameters
const struct sk_buff *skb: buffer to copyint offset: offset in the buffer to start copying fromstruct iov_iter *to: iovec iterator to copy toint len: amount of data to copy from buffer to iovecu32 *crcp: pointer to CRC32C value to update
Return
0 on success, -EFAULT if there was a fault during copy.
skb_copy_datagram_iter() #
int Copy a datagram to an iovec iterator.
Parameters
const struct sk_buff *skb: buffer to copyint offset: offset in the buffer to start copying fromstruct iov_iter *to: iovec iterator to copy toint len: amount of data to copy from buffer to iovec
skb_copy_datagram_from_iter() #
int Copy a datagram from an iov_iter.
Parameters
struct sk_buff *skb: buffer to copyint offset: offset in the buffer to start copying tostruct iov_iter *from: the copy sourceint len: amount of data to copy to buffer from iovec
Description
Returns 0 or -EFAULT.
zerocopy_sg_from_iter() #
int Build a zerocopy datagram from an iov_iter
Parameters
struct sk_buff *skb: buffer to copystruct iov_iter *from: the source to copy from
Description
The function will first copy up to headlen, and then pin the userspace pages and build frags through them.
Returns 0, -EFAULT or -EMSGSIZE.
skb_copy_and_csum_datagram_msg() #
int Copy and checksum skb to user iovec.
Parameters
struct sk_buff *skb: skbuffint hlen: hardware lengthstruct msghdr *msg: destination
Description
Caller must check that skb will fit to this iovec.
Return
0 - success. -EINVAL - checksum failure. -EFAULT - fault during copy.
datagram_poll_queue() #
__poll_t same as datagram_poll, but on a specific receive queue
Parameters
struct file *file: file structstruct socket *sock: socketpoll_table *wait: poll tablestruct sk_buff_head *rcv_queue: receive queue to poll
Description
Performs polling on the given receive queue, handling shutdown, error, and connection state. This is useful for protocols that deliver userspace-bound packets through a custom queue instead of sk->sk_receive_queue.
Return
poll bitmask indicating the socket's current state
datagram_poll() #
__poll_t generic datagram poll
Parameters
struct file *file: file structstruct socket *sock: socketpoll_table *wait: poll table
Description
Datagram poll: Again totally generic. This also handles sequenced packet sockets providing the socket receive queue is only ever holding data ready to receive.
Note
-
when you don't use this routine for this protocol,
and you use a different write policy from
sock_writeable()then please supply your own write_space callback.
Return
poll bitmask indicating the socket's current state
sk_stream_wait_connect() #
int Wait for a socket to get into the connected state
Parameters
struct sock *sk: sock to wait onlong *timeo_p: for how long to wait
Description
Must be called with the socket locked.
sk_stream_wait_memory() #
int Wait for more memory for a socket
Parameters
struct sock *sk: socket to wait for memorylong *timeo_p: for how long
Socket Filter #
sk_filter_trim_cap() #
int run a packet through a socket filter
Parameters
struct sock *sk: sock associated withsk_buffstruct sk_buff *skb: buffer to filterunsigned int cap: limit on how short the eBPF program may trim the packetenum skb_drop_reason *reason: record drop reason on errors (negative return value)
Description
Run the eBPF program and then cut skb->data to correct size returned by the program. If pkt_len is 0 we toss packet. If skb->len is smaller than pkt_len we keep whole skb->data. This is the socket level wrapper to bpf_prog_run. It returns 0 if the packet should be accepted or -EPERM if the packet should be tossed.
bpf_prog_create() #
int create an unattached filter
Parameters
struct bpf_prog **pfp: the unattached filter that is createdstruct sock_fprog_kern *fprog: the filter program
Description
Create a filter independent of any socket. We first run some sanity checks on it to make sure it does not explode on us later. If an error occurs or there is insufficient memory for the filter a negative errno code is returned. On success the return is zero.
bpf_prog_create_from_user() #
int create an unattached filter from user buffer
Parameters
struct bpf_prog **pfp: the unattached filter that is createdstruct sock_fprog *fprog: the filter programbpf_aux_classic_check_t trans: post-classic verifier transformation handlerbool save_orig: save classic BPF program
Description
This function effectively does the same as bpf_prog_create(), only
that it builds up its insns buffer from user space provided buffer.
It also allows for passing a bpf_aux_classic_check_t handler.
sk_attach_filter() #
int attach a socket filter
Parameters
struct sock_fprog *fprog: the filter programstruct sock *sk: the socket to use
Description
Attach the user's filter code. We first run some sanity checks on it to make sure it does not explode on us later. If an error occurs or there is insufficient memory for the filter a negative errno code is returned. On success the return is zero.
Generic Network Statistics #
struct gnet_stats_basic #
byte/packet throughput statistics
Definition
;
Members
bytes: number of seen bytespackets: number of seen packets
struct gnet_stats_rate_est #
rate estimator
Definition
;
Members
bps: current byte ratepps: current packet rate
struct gnet_stats_rate_est64 #
rate estimator
Definition
;
Members
bps: current byte ratepps: current packet rate
struct gnet_stats_queue #
queuing statistics
Definition
;
Members
qlen: queue lengthbacklog: backlog size of queuedrops: number of dropped packetsrequeues: number of requeuesoverlimits: number of enqueues over the limit
struct gnet_estimator #
rate estimator configuration
Definition
;
Members
interval: sampling periodewma_log: the log of measurement window weight
gnet_stats_start_copy_compat() #
int start dumping procedure in compatibility mode
Parameters
struct sk_buff *skb: socket buffer to put statistics TLVs intoint type: TLV type for top level statistic TLVint tc_stats_type: TLV type for backward compatibility struct tc_stats TLVint xstats_type: TLV type for backward compatibility xstats TLVspinlock_t *lock: statistics lockstruct gnet_dump *d: dumping handleint padattr: padding attribute
Description
Initializes the dumping handle, grabs the statistic lock and appends an empty TLV header to the socket buffer for use a container for all other statistic TLVS.
The dumping handle is marked to be in backward compatibility mode telling
all gnet_stats_copy_XXX() functions to fill a local copy of struct tc_stats.
Returns 0 on success or -1 if the room in the socket buffer was not sufficient.
gnet_stats_start_copy() #
int start dumping procedure in compatibility mode
Parameters
struct sk_buff *skb: socket buffer to put statistics TLVs intoint type: TLV type for top level statistic TLVspinlock_t *lock: statistics lockstruct gnet_dump *d: dumping handleint padattr: padding attribute
Description
Initializes the dumping handle, grabs the statistic lock and appends an empty TLV header to the socket buffer for use a container for all other statistic TLVS.
Returns 0 on success or -1 if the room in the socket buffer was not sufficient.
gnet_stats_copy_basic() #
int copy basic statistics into statistic TLV
Parameters
struct gnet_dump *d: dumping handlestruct gnet_stats_basic_sync __percpu *cpu: copy statistic per cpustruct gnet_stats_basic_sync *b: basic statisticsbool running: true if b represents a running qdisc, thus b's internal values might change during basic reads. Only used if cpu is NULL
Context
task; must not be run from IRQ or BH contexts
Description
Appends the basic statistics to the top level TLV created by
gnet_stats_start_copy().
Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.
gnet_stats_copy_basic_hw() #
int copy basic hw statistics into statistic TLV
Parameters
struct gnet_dump *d: dumping handlestruct gnet_stats_basic_sync __percpu *cpu: copy statistic per cpustruct gnet_stats_basic_sync *b: basic statisticsbool running: true if b represents a running qdisc, thus b's internal values might change during basic reads. Only used if cpu is NULL
Context
task; must not be run from IRQ or BH contexts
Description
Appends the basic statistics to the top level TLV created by
gnet_stats_start_copy().
Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.
gnet_stats_copy_rate_est() #
int copy rate estimator statistics into statistics TLV
Parameters
struct gnet_dump *d: dumping handlestruct net_rate_estimator __rcu **rate_est: rate estimator
Description
Appends the rate estimator statistics to the top level TLV created by
gnet_stats_start_copy().
Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.
gnet_stats_copy_queue() #
int copy queue statistics into statistics TLV
Parameters
struct gnet_dump *d: dumping handlestruct gnet_stats_queue __percpu *cpu_q: per cpu queue statisticsstruct gnet_stats_queue *q: queue statistics__u32 qlen: queue length statistics
Description
Appends the queue statistics to the top level TLV created by
gnet_stats_start_copy(). Using per cpu queue statistics if
they are available.
Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.
gnet_stats_copy_app() #
int copy application specific statistics into statistics TLV
Parameters
struct gnet_dump *d: dumping handlevoid *st: application specific statistics dataint len: length of data
Description
Appends the application specific statistics to the top level TLV created by
gnet_stats_start_copy() and remembers the data for XSTATS if the dumping
handle is in backward compatibility mode.
Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.
gnet_stats_finish_copy() #
int finish dumping procedure
Parameters
struct gnet_dump *d: dumping handle
Description
Corrects the length of the top level TLV to include all TLVs added
by gnet_stats_copy_XXX() calls. Adds the backward compatibility TLVs
if gnet_stats_start_copy_compat() was used and releases the statistics
lock.
Returns 0 on success or -1 with the statistic lock released if the room in the socket buffer was not sufficient.
gen_new_estimator() #
int create a new rate estimator
Parameters
struct gnet_stats_basic_sync *bstats: basic statisticsstruct gnet_stats_basic_sync __percpu *cpu_bstats: bstats per cpustruct net_rate_estimator __rcu **rate_est: rate estimator statisticsspinlock_t *lock: lock for statistics and control pathbool running: true if bstats represents a running qdisc, thus bstats' internal values might change during basic reads. Only used if bstats_cpu is NULLstruct nlattr *opt: rate estimator configuration TLV
Description
Creates a new rate estimator with bstats as source and rate_est
as destination. A new timer with the interval specified in the
configuration TLV is created. Upon each interval, the latest statistics
will be read from bstats and the estimated rate will be stored in
rate_est with the statistics lock grabbed during this period.
Returns 0 on success or a negative error code.
gen_kill_estimator() #
void remove a rate estimator
Parameters
struct net_rate_estimator __rcu **rate_est: rate estimator
Description
Removes the rate estimator.
gen_replace_estimator() #
int replace rate estimator configuration
Parameters
struct gnet_stats_basic_sync *bstats: basic statisticsstruct gnet_stats_basic_sync __percpu *cpu_bstats: bstats per cpustruct net_rate_estimator __rcu **rate_est: rate estimator statisticsspinlock_t *lock: lock for statistics and control pathbool running: true if bstats represents a running qdisc, thus bstats' internal values might change during basic reads. Only used if cpu_bstats is NULLstruct nlattr *opt: rate estimator configuration TLV
Description
Replaces the configuration of a rate estimator by calling
gen_kill_estimator() and gen_new_estimator().
Returns 0 on success or a negative error code.
gen_estimator_active() #
bool test if estimator is currently in use
Parameters
struct net_rate_estimator __rcu **rate_est: rate estimator
Description
Returns true if estimator is active, and false if not.
SUN RPC subsystem #
xdr_encode_opaque_fixed() #
__be32 * Encode fixed length opaque data
Parameters
__be32 *p: pointer to current position in XDR buffer.const void *ptr: pointer to data to encode (or NULL)unsigned int nbytes: size of data.
Description
Copy the array of data of length nbytes at ptr to the XDR buffer at position p, then align to the next 32-bit boundary by padding with zero bytes (see RFC1832).
Note
if ptr is NULL, only the padding is performed.
Returns the updated current XDR buffer position
xdr_encode_opaque() #
__be32 * Encode variable length opaque data
Parameters
__be32 *p: pointer to current position in XDR buffer.const void *ptr: pointer to data to encode (or NULL)unsigned int nbytes: size of data.
Description
Returns the updated current XDR buffer position
xdr_terminate_string() #
void '\0'-terminate a string residing in an xdr_buf
Parameters
const struct xdr_buf *buf: XDR buffer where string residesconst u32 len: length of string, in bytes
xdr_buf_to_bvec() #
unsigned int Copy components of an xdr_buf into a bio_vec array
Parameters
struct bio_vec *bvec: bio_vec array to populateunsigned int bvec_size: element count of bio_vecconst struct xdr_buf *xdr: xdr_buf to be copied
Description
Returns the number of entries consumed in bvec.
xdr_inline_pages() #
void Prepare receive buffer for a large reply
Parameters
struct xdr_buf *xdr: xdr_buf into which reply will be placedunsigned int offset: expected offset where data payload will start, in bytesstruct page **pages: vector of struct page pointersunsigned int base: offset in first page where receive should start, in bytesunsigned int len: expected size of the upper layer data payload, in bytes
_copy_from_pages() #
void Parameters
char *p: pointer to destinationstruct page **pages: array of pagessize_t pgbase: offset of source datasize_t len: length
Description
Copies data into an arbitrary memory location from an array of pages The copy is assumed to be non-overlapping.
xdr_stream_pos() #
unsigned int Return the current offset from the start of the xdr_stream
Parameters
const struct xdr_stream *xdr: pointer to struct xdr_stream
xdr_page_pos() #
unsigned int Return the current offset from the start of the xdr pages
Parameters
const struct xdr_stream *xdr: pointer to struct xdr_stream
xdr_init_encode() #
void Initialize a struct xdr_stream for sending data.
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structstruct xdr_buf *buf: pointer to XDR buffer in which to encode data__be32 *p: current pointer inside XDR bufferstruct rpc_rqst *rqst: pointer to controlling rpc_rqst, for debugging
Note
-
at the moment the RPC client only passes the length of our
scratch buffer in the xdr_buf's header kvec. Previously this meant we needed to call
xdr_adjust_iovec()after encoding the data. With the new scheme, the xdr_stream manages the details of the buffer length, and takes care of adjusting the kvec length for us.
xdr_init_encode_pages() #
void Initialize an xdr_stream for encoding into pages
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structstruct xdr_buf *buf: pointer to XDR buffer into which to encode data
__xdr_commit_encode() #
void Ensure all data is written to buffer
Parameters
struct xdr_stream *xdr: pointer to xdr_stream
Description
We handle encoding across page boundaries by giving the caller a temporary location to write to, then later copying the data into place; xdr_commit_encode does that copying.
Normally the caller doesn't need to call this directly, as the following xdr_reserve_space will do it. But an explicit call may be required at the end of encoding, or any other time when the xdr_buf data might be read.
xdr_reserve_space() #
__be32 * Reserve buffer space for sending
Parameters
struct xdr_stream *xdr: pointer to xdr_streamsize_t nbytes: number of bytes to reserve
Description
Checks that we have enough buffer space to encode 'nbytes' more bytes of data. If so, update the total xdr_buf length, and adjust the length of the current kvec.
The returned pointer is valid only until the next call to
xdr_reserve_space() or xdr_commit_encode() on xdr. The current
implementation of this API guarantees that space reserved for a
four-byte data item remains valid until xdr is destroyed, but
that might not always be true in the future.
xdr_reserve_space_vec() #
int Reserves a large amount of buffer space for sending
Parameters
struct xdr_stream *xdr: pointer to xdr_streamsize_t nbytes: number of bytes to reserve
Description
The size argument passed to xdr_reserve_space() is determined based
on the number of bytes remaining in the current page to avoid
invalidating iov_base pointers when xdr_commit_encode() is called.
- Return values:
0: success-EMSGSIZE: not enough space is available in xdr
xdr_truncate_encode() #
void truncate an encode buffer
Parameters
struct xdr_stream *xdr: pointer to xdr_streamsize_t len: new length of buffer
Description
Truncates the xdr stream, so that xdr->buf->len == len, and xdr->p points at offset len from the start of the buffer, and head, tail, and page lengths are adjusted to correspond.
If this means moving xdr->p to a different buffer, we assume that the end pointer should be set to the end of the current page, except in the case of the head buffer when we assume the head buffer's current length represents the end of the available buffer.
This is not safe to use on a buffer that already has inlined page cache pages (as in a zero-copy server read reply), except for the simple case of truncating from one position in the tail to another.
xdr_truncate_decode() #
void Truncate a decoding stream
Parameters
struct xdr_stream *xdr: pointer to struct xdr_streamsize_t len: Number of bytes to remove
xdr_restrict_buflen() #
int decrease available buffer space
Parameters
struct xdr_stream *xdr: pointer to xdr_streamint newbuflen: new maximum number of bytes available
Description
Adjust our idea of how much space is available in the buffer. If we've already used too much space in the buffer, returns -1. If the available space is already smaller than newbuflen, returns 0 and does nothing. Otherwise, adjusts xdr->buf->buflen to newbuflen and ensures xdr->end is set at most offset newbuflen from the start of the buffer.
xdr_write_pages() #
void Insert a list of pages into an XDR buffer for sending
Parameters
struct xdr_stream *xdr: pointer to xdr_streamstruct page **pages: array of pages to insertunsigned int base: starting offset of first data byte in pagesunsigned int len: number of data bytes in pages to insert
Description
After the pages are added, the tail iovec is instantiated pointing to end of the head buffer, and the stream is set up to encode subsequent items into the tail.
xdr_init_decode() #
void Initialize an xdr_stream for decoding data.
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structstruct xdr_buf *buf: pointer to XDR buffer from which to decode data__be32 *p: current pointer inside XDR bufferstruct rpc_rqst *rqst: pointer to controlling rpc_rqst, for debugging
xdr_init_decode_pages() #
void Initialize an xdr_stream for decoding into pages
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structstruct xdr_buf *buf: pointer to XDR buffer from which to decode datastruct page **pages: list of pages to decode intounsigned int len: length in bytes of buffer in pages
xdr_finish_decode() #
void Clean up the xdr_stream after decoding data.
Parameters
struct xdr_stream *xdr: pointer to xdr_stream struct
xdr_inline_decode() #
__be32 * Retrieve XDR data to decode
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structsize_t nbytes: number of bytes of data to decode
Description
Check if the input buffer is long enough to enable us to decode 'nbytes' more bytes of data starting at the current position. If so return the current pointer, then update the current pointer position.
xdr_read_pages() #
unsigned int align page-based XDR data to current pointer position
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structunsigned int len: number of bytes of page data
Description
Moves data beyond the current pointer position from the XDR head[] buffer into the page list. Any data that lies beyond current position + len bytes is moved into the XDR tail[]. The xdr_stream current position is then advanced past that data to align to the next XDR object in the tail.
Returns the number of XDR encoded bytes now contained in the pages
xdr_set_pagelen() #
void Sets the length of the XDR pages
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structunsigned int len: new length of the XDR page data
Description
Either grows or shrinks the length of the xdr pages by setting pagelen to len bytes. When shrinking, any extra data is moved into buf->tail, whereas when growing any data beyond the current pointer is moved into the tail.
Returns True if the operation was successful, and False otherwise.
xdr_enter_page() #
void decode data from the XDR page
Parameters
struct xdr_stream *xdr: pointer to xdr_stream structunsigned int len: number of bytes of page data
Description
Moves data beyond the current pointer position from the XDR head[] buffer into the page list. Any data that lies beyond current position + "len" bytes is moved into the XDR tail[]. The current pointer is then repositioned at the beginning of the first XDR page.
xdr_buf_subsegment() #
int set subbuf to a portion of buf
Parameters
const struct xdr_buf *buf: an xdr bufferstruct xdr_buf *subbuf: the result bufferunsigned int base: beginning of range in bytesunsigned int len: length of range in bytes
Description
sets subbuf to an xdr buffer representing the portion of buf of length len starting at offset base.
buf and subbuf may be pointers to the same struct xdr_buf.
Returns -1 if base or length are out of bounds.
xdr_stream_subsegment() #
bool set subbuf to a portion of xdr
Parameters
struct xdr_stream *xdr: an xdr_stream set up for decodingstruct xdr_buf *subbuf: the result bufferunsigned int nbytes: length of xdr to extract, in bytes
Description
Sets up subbuf to represent a portion of xdr. The portion starts at the current offset in xdr, and extends for a length of nbytes. If this is successful, xdr is advanced to the next XDR data item following that portion.
- Return values:
true: subbuf has been initialized, and xdr has been advanced.false: a bounds error has occurred
xdr_stream_move_subsegment() #
unsigned int Move part of a stream to another position
Parameters
struct xdr_stream *xdr: the source xdr_streamunsigned int offset: the source offset of the segmentunsigned int target: the target offset of the segmentunsigned int length: the number of bytes to move
Description
Moves length bytes from offset to target in the xdr_stream, overwriting anything in its space. Returns the number of bytes in the segment.
xdr_stream_zero() #
unsigned int zero out a portion of an xdr_stream
Parameters
struct xdr_stream *xdr: an xdr_stream to zero outunsigned int offset: the starting point in the streamunsigned int length: the number of bytes to zero
xdr_buf_trim() #
void lop at most "len" bytes off the end of "buf"
Parameters
struct xdr_buf *buf: buf to be trimmedunsigned int len: number of bytes to reduce "buf" by
Description
Trim an xdr_buf by the given number of bytes by fixing up the lengths. Note that it's possible that we'll trim less than that amount if the xdr_buf is too small, or if (for instance) it's all in the head and the parser has already read too far into it.
xdr_stream_decode_string_dup() #
ssize_t Decode and duplicate variable length string
Parameters
struct xdr_stream *xdr: pointer to xdr_streamchar **str: location to store pointer to stringsize_t maxlen: maximum acceptable string lengthgfp_t gfp_flags: GFP mask to use
Description
- Return values:
On success, returns length of NUL-terminated string stored in *ptr
-EBADMSGon XDR buffer overflow-EMSGSIZEif the size of the string would exceed maxlen-ENOMEMon memory allocation failure
xdr_stream_decode_opaque_auth() #
ssize_t Decode struct opaque_auth (RFC5531 S8.2)
Parameters
struct xdr_stream *xdr: pointer to xdr_streamu32 *flavor: location to store decoded flavorvoid **body: location to store decode bodyunsigned int *body_len: location to store length of decoded body
Description
- Return values:
On success, returns the number of buffer bytes consumed
-EBADMSGon XDR buffer overflow-EMSGSIZEif the decoded size of the body field exceeds 400 octets
xdr_stream_encode_opaque_auth() #
ssize_t Encode struct opaque_auth (RFC5531 S8.2)
Parameters
struct xdr_stream *xdr: pointer to xdr_streamu32 flavor: verifier flavor to encodevoid *body: content of body to encodeunsigned int body_len: length of body to encode
Description
- Return values:
On success, returns length in bytes of XDR buffer consumed
-EBADMSGon XDR buffer overflow-EMSGSIZEif the size of body exceeds 400 octets
svc_reg_xprt_class() #
int Register a server-side RPC transport class
Parameters
struct svc_xprt_class *xcl: New transport class to be registered
Description
Returns zero on success; otherwise a negative errno is returned.
svc_unreg_xprt_class() #
void Unregister a server-side RPC transport class
Parameters
struct svc_xprt_class *xcl: Transport class to be unregistered
svc_xprt_deferred_close() #
void Close a transport
Parameters
struct svc_xprt *xprt: transport instance
Description
Used in contexts that need to defer the work of shutting down the transport to an nfsd thread.
svc_xprt_received() #
void start next receiver thread
Parameters
struct svc_xprt *xprt: controlling transport
Description
The caller must hold the XPT_BUSY bit and must not thereafter touch transport data.
Note
XPT_DATA only gets cleared when a read-attempt finds no (or insufficient) data.
svc_xprt_create_from_sa() #
int Add a new listener to serv from socket address
Parameters
struct svc_serv *serv: target RPC serviceconst char *xprt_name: transport class namestruct net *net: network namespacestruct sockaddr *sap: socket address pointerint flags: SVC_SOCK flagsconst struct cred *cred: credential to bind to this transport
Description
Return local xprt port on success or -EPROTONOSUPPORT on failure
svc_xprt_create() #
int Add a new listener to serv
Parameters
struct svc_serv *serv: target RPC serviceconst char *xprt_name: transport class namestruct net *net: network namespaceconst int family: network address familyconst unsigned short port: listener portint flags: SVC_SOCK flagsconst struct cred *cred: credential to bind to this transport
Description
Return local xprt port on success or -EPROTONOSUPPORT on failure
svc_print_addr() #
char * Format rq_addr field for printing
Parameters
struct svc_rqst *rqstp: svc_rqst struct containing address to printchar *buf: target buffer for formatted addresssize_t len: length of target buffer
svc_xprt_enqueue() #
void Queue a transport on an idle nfsd thread
Parameters
struct svc_xprt *xprt: transport with data pending
svc_reserve() #
void change the space reserved for the reply to a request.
Parameters
struct svc_rqst *rqstp: The request in questionint space: new max space to reserve
Description
Each request reserves some space on the output queue of the transport to make sure the reply fits. This function reduces that reserved space to be the amount of space used already, plus space.
svc_wake_up() #
void Wake up a service thread for non-transport work
Parameters
struct svc_serv *serv: RPC service
Description
Some svc_serv's will have occasional work to do, even when a xprt is not waiting to be serviced. This function is there to "kick" a task in one of those services so that it can wake up and do that work. Note that we only bother with pool 0 as we don't need to wake up more than one thread for this purpose.
svc_recv() #
int Receive and process the next request on any transport
Parameters
struct svc_rqst *rqstp: an idle RPC service threadlong timeo: timeout (in jiffies) (0 means infinite timeout)
Description
This code is carefully organised not to touch any cachelines in the shared svc_serv structure, only cachelines in the local svc_pool.
If the timeout is 0, then the sleep will never time out.
-
Returns -ETIMEDOUT if idle for an extended period
-EBUSY if there is more work to do than available threads 0 otherwise.
svc_xprt_close() #
void Close a client connection
Parameters
struct svc_xprt *xprt: transport to disconnect
svc_xprt_destroy_all() #
void Destroy transports associated with serv
Parameters
struct svc_serv *serv: RPC service to be shut downstruct net *net: target network namespacebool unregister: true if it is OK to unregister the destroyed xprts
Description
Server threads may still be running (especially in the case where the service is still running in other network namespaces).
So we shut down sockets the same way we would on a running server, by
setting XPT_CLOSE, enqueuing, and letting a thread pick it up to do
the close. In the case there are no such other threads,
threads running, svc_clean_up_xprts() does a simple version of a
server's main event loop, and in the case where there are other
threads, we may need to wait a little while and then check again to
see if they're done.
svc_find_listener() #
struct svc_xprt * find an RPC transport instance
Parameters
struct svc_serv *serv: pointer to svc_serv to searchconst char *xcl_name: C string containing transport's class namestruct net *net: owner net pointerconst struct sockaddr *sa: sockaddr containing address
Description
Return the transport instance pointer for the endpoint accepting connections/peer traffic from the specified transport class, and matching sockaddr.
svc_find_xprt() #
struct svc_xprt * find an RPC transport instance
Parameters
struct svc_serv *serv: pointer to svc_serv to searchconst char *xcl_name: C string containing transport's class namestruct net *net: owner net pointerconst sa_family_t af: Address family of transport's local addressconst unsigned short port: transport's IP port number
Description
Return the transport instance pointer for the endpoint accepting connections/peer traffic from the specified transport class, address family and port.
Specifying 0 for the address family or port is effectively a wild-card, and will result in matching the first transport in the service's list that has a matching class name.
svc_xprt_names() #
int format a buffer with a list of transport names
Parameters
struct svc_serv *serv: pointer to an RPC servicechar *buf: pointer to a buffer to be filled inconst int buflen: length of buffer to be filled in
Description
Fills in buf with a string containing a list of transport names, each name terminated with '\n'.
Returns positive length of the filled-in string on success; otherwise a negative errno value is returned if an error occurs.
xprt_register_transport() #
int register a transport implementation
Parameters
struct xprt_class *transport: transport to register
Description
If a transport implementation is loaded as a kernel module, it can call this interface to make itself known to the RPC client.
Return
0: transport successfully registered -EEXIST: transport already registered -EINVAL: transport module being unloaded
xprt_unregister_transport() #
int unregister a transport implementation
Parameters
struct xprt_class *transport: transport to unregister
Return
0: transport successfully unregistered -ENOENT: transport never registered
xprt_find_transport_ident() #
int convert a netid into a transport identifier
Parameters
const char *netid: transport to load
Return
> 0: transport identifier -ENOENT: transport module not available
xprt_reserve_xprt() #
int serialize write access to transports
Parameters
struct rpc_xprt *xprt: pointer to the target transportstruct rpc_task *task: task that is requesting access to the transport
Description
This prevents mixing the payload of separate requests, and prevents transport connects from colliding with writes. No congestion control is provided.
xprt_release_xprt() #
void allow other requests to use a transport
Parameters
struct rpc_xprt *xprt: transport with other tasks potentially waitingstruct rpc_task *task: task that is releasing access to the transport
Description
Note that "task" can be NULL. No congestion control is provided.
xprt_release_xprt_cong() #
void allow other requests to use a transport
Parameters
struct rpc_xprt *xprt: transport with other tasks potentially waitingstruct rpc_task *task: task that is releasing access to the transport
Description
Note that "task" can be NULL. Another task is awoken to use the transport if the transport's congestion window allows it.
xprt_request_get_cong() #
bool Request congestion control credits
Parameters
struct rpc_xprt *xprt: pointer to transportstruct rpc_rqst *req: pointer to RPC request
Description
Useful for transports that require congestion control.
xprt_release_rqst_cong() #
void housekeeping when request is complete
Parameters
struct rpc_task *task: RPC request that recently completed
Description
Useful for transports that require congestion control.
xprt_adjust_cwnd() #
void adjust transport congestion window
Parameters
struct rpc_xprt *xprt: pointer to xprtstruct rpc_task *task: recently completed RPC request used to adjust windowint result: result code of completed RPC request
Description
The transport code maintains an estimate on the maximum number of out- standing RPC requests, using a smoothed version of the congestion avoidance implemented in 44BSD. This is basically the Van Jacobson congestion algorithm: If a retransmit occurs, the congestion window is halved; otherwise, it is incremented by 1/cwnd when
- a reply is received and
- a full number of requests are outstanding and
- the congestion window hasn't been updated recently.
xprt_wake_pending_tasks() #
void wake all tasks on a transport's pending queue
Parameters
struct rpc_xprt *xprt: transport with waiting tasksint status: result code to plant in each task before waking it
xprt_wait_for_buffer_space() #
void wait for transport output buffer to clear
Parameters
struct rpc_xprt *xprt: transport
Description
Note that we only set the timer for the case of RPC_IS_SOFT(), since
we don't in general want to force a socket disconnection due to
an incomplete RPC call transmission.
xprt_write_space() #
bool wake the task waiting for transport output buffer space
Parameters
struct rpc_xprt *xprt: transport with waiting tasks
Description
Can be called in a soft IRQ context, so xprt_write_space never sleeps.
xprt_disconnect_done() #
void mark a transport as disconnected
Parameters
struct rpc_xprt *xprt: transport to flag for disconnect
xprt_force_disconnect() #
void force a transport to disconnect
Parameters
struct rpc_xprt *xprt: transport to disconnect
xprt_reconnect_delay() #
unsigned long compute the wait before scheduling a connect
Parameters
const struct rpc_xprt *xprt: transport instance
xprt_reconnect_backoff() #
void compute the new re-establish timeout
Parameters
struct rpc_xprt *xprt: transport instanceunsigned long init_to: initial reestablish timeout
xprt_lookup_rqst() #
struct rpc_rqst * find an RPC request corresponding to an XID
Parameters
struct rpc_xprt *xprt: transport on which the original request was transmitted__be32 xid: RPC XID of incoming reply
Description
Caller holds xprt->queue_lock.
xprt_pin_rqst() #
void Pin a request on the transport receive list
Parameters
struct rpc_rqst *req: Request to pin
Description
Caller must ensure this is atomic with the call to xprt_lookup_rqst()
so should be holding xprt->queue_lock.
xprt_unpin_rqst() #
void Unpin a request on the transport receive list
Parameters
struct rpc_rqst *req: Request to pin
Description
Caller should be holding xprt->queue_lock.
xprt_update_rtt() #
void Update RPC RTT statistics
Parameters
struct rpc_task *task: RPC request that recently completed
Description
Caller holds xprt->queue_lock.
xprt_complete_rqst() #
void called when reply processing is complete
Parameters
struct rpc_task *task: RPC request that recently completedint copied: actual number of bytes received from the transport
Description
Caller holds xprt->queue_lock.
xprt_wait_for_reply_request_def() #
void wait for reply
Parameters
struct rpc_task *task: pointer to rpc_task
Description
Set a request's retransmit timeout based on the transport's default timeout parameters. Used by transports that don't adjust the retransmit timeout based on round-trip time estimation, and put the task to sleep on the pending queue.
xprt_wait_for_reply_request_rtt() #
void wait for reply using RTT estimator
Parameters
struct rpc_task *task: pointer to rpc_task
Description
Set a request's retransmit timeout using the RTT estimator, and put the task to sleep on the pending queue.
xprt_get() #
struct rpc_xprt * return a reference to an RPC transport.
Parameters
struct rpc_xprt *xprt: pointer to the transport
xprt_put() #
void release a reference to an RPC transport.
Parameters
struct rpc_xprt *xprt: pointer to the transport
rpc_wake_up() #
void wake up all rpc_tasks
Parameters
struct rpc_wait_queue *queue: rpc_wait_queue on which the tasks are sleeping
Description
Grabs queue->lock
rpc_wake_up_status() #
void wake up all rpc_tasks and set their status value.
Parameters
struct rpc_wait_queue *queue: rpc_wait_queue on which the tasks are sleepingint status: status value to set
Description
Grabs queue->lock
rpc_alloc_iostats() #
struct rpc_iostats * allocate an rpc_iostats structure
Parameters
struct rpc_clnt *clnt: RPC program, version, and xprt
rpc_free_iostats() #
void release an rpc_iostats structure
Parameters
struct rpc_iostats *stats: doomed rpc_iostats structure
rpc_count_iostats_metrics() #
void tally up per-task stats
Parameters
const struct rpc_task *task: completed rpc_taskstruct rpc_iostats *op_metrics: stat structure for OP that will accumulate stats from task
rpc_count_iostats() #
void tally up per-task stats
Parameters
const struct rpc_task *task: completed rpc_taskstruct rpc_iostats *stats: array of stat structures
Description
Uses the statidx from task
rpc_queue_upcall() #
int queue an upcall message to userspace
Parameters
struct rpc_pipe *pipe: upcall pipe on which to queue given messagestruct rpc_pipe_msg *msg: message to queue
Description
Call with an inode created by rpc_mkpipe() to queue an upcall.
A userspace process may then later read the upcall by performing a
read on an open file for this inode. It is up to the caller to
initialize the fields of msg (other than msg->list) appropriately.
rpc_mkpipe_dentry() #
int make an rpc_pipefs file for kernel<->userspace communication
Parameters
struct dentry *parent: dentry of directory to create new "pipe" inconst char *name: name of pipevoid *private: private data to associate with the pipe, for the caller's usestruct rpc_pipe *pipe:rpc_pipecontaining input parameters
Description
Data is made available for userspace to read by calls to
rpc_queue_upcall(). The actual reads will result in calls to
ops->upcall, which will be called with the file pointer,
message, and userspace buffer to copy to.
Writes can come at any time, and do not necessarily have to be responses to upcalls. They will result in calls to msg->downcall.
The private argument passed here will be available to all these methods from the file pointer, via RPC_I(file_inode(file))->private.
rpc_unlink() #
void remove a pipe
Parameters
struct rpc_pipe *pipe: the pipe to be removed
Description
After this call, lookups will no longer find the pipe, and any attempts to read or write using preexisting opens of the pipe will return -EPIPE.
rpc_init_pipe_dir_head() #
void initialise a struct rpc_pipe_dir_head
Parameters
struct rpc_pipe_dir_head *pdh: pointer to struct rpc_pipe_dir_head
rpc_init_pipe_dir_object() #
void initialise a struct rpc_pipe_dir_object
Parameters
struct rpc_pipe_dir_object *pdo: pointer to struct rpc_pipe_dir_objectconst struct rpc_pipe_dir_object_ops *pdo_ops: pointer to const struct rpc_pipe_dir_object_opsvoid *pdo_data: pointer to caller-defined data
rpc_add_pipe_dir_object() #
int associate a rpc_pipe_dir_object to a directory
Parameters
struct net *net: pointer to struct netstruct rpc_pipe_dir_head *pdh: pointer to struct rpc_pipe_dir_headstruct rpc_pipe_dir_object *pdo: pointer to struct rpc_pipe_dir_object
rpc_remove_pipe_dir_object() #
void remove a rpc_pipe_dir_object from a directory
Parameters
struct net *net: pointer to struct netstruct rpc_pipe_dir_head *pdh: pointer to struct rpc_pipe_dir_headstruct rpc_pipe_dir_object *pdo: pointer to struct rpc_pipe_dir_object
rpc_find_or_alloc_pipe_dir_object() #
struct rpc_pipe_dir_object * Parameters
struct net *net: pointer to struct netstruct rpc_pipe_dir_head *pdh: pointer to struct rpc_pipe_dir_headint (*match)(struct rpc_pipe_dir_object *, void *): match struct rpc_pipe_dir_object to datastruct rpc_pipe_dir_object *(*alloc)(void *): allocate a new struct rpc_pipe_dir_objectvoid *data: user defined data formatch()andalloc()
rpcb_getport_async() #
void obtain the port for a given RPC service on a given host
Parameters
struct rpc_task *task: task that is waiting for portmapper request
Description
This one can be called for an ongoing RPC request, and can be used in an async (rpciod) context.
rpc_create() #
struct rpc_clnt * create an RPC client and transport with one call
Parameters
struct rpc_create_args *args: rpc_clnt create argument structure
Description
Creates and initializes an RPC transport and an RPC client.
It can ping the server in order to determine if it is up, and to see if it supports this program and version. RPC_CLNT_CREATE_NOPING disables this behavior so asynchronous tasks can also use rpc_create.
rpc_clone_client() #
struct rpc_clnt * Clone an RPC client structure
Parameters
struct rpc_clnt *clnt: RPC client whose parameters are copied
Description
Returns a fresh RPC client or an ERR_PTR.
rpc_clone_client_set_auth() #
struct rpc_clnt * Clone an RPC client structure and set its auth
Parameters
struct rpc_clnt *clnt: RPC client whose parameters are copiedrpc_authflavor_t flavor: security flavor for new client
Description
Returns a fresh RPC client or an ERR_PTR.
rpc_switch_client_transport() #
int switch the RPC transport on the fly
Parameters
struct rpc_clnt *clnt: pointer to a struct rpc_clntstruct xprt_create *args: pointer to the new transport argumentsconst struct rpc_timeout *timeout: pointer to the new timeout parameters
Description
This function allows the caller to switch the RPC transport for the rpc_clnt structure 'clnt' to allow it to connect to a mirrored NFS server, for instance. It assumes that the caller has ensured that there are no active RPC tasks by using some form of locking.
Returns zero if "clnt" is now using the new xprt. Otherwise a negative errno is returned, and "clnt" continues to use the old xprt.
rpc_clnt_iterate_for_each_xprt() #
int Apply a function to all transports
Parameters
struct rpc_clnt *clnt: pointer to clientint (*fn)(struct rpc_clnt *, struct rpc_xprt *, void *): function to applyvoid *data: void pointer to function data
Description
Iterates through the list of RPC transports currently attached to the client and applies the function fn(clnt, xprt, data).
On error, the iteration stops, and the function returns the error value.
rpc_cancel_tasks() #
unsigned long try to cancel a set of RPC tasks
Parameters
struct rpc_clnt *clnt: Pointer to RPC clientint error: RPC task error value to setbool (*fnmatch)(const struct rpc_task *, const void *): Pointer to selector functionconst void *data: User data
Description
Uses fnmatch to define a set of RPC tasks that are to be cancelled. The argument error must be a negative error value.
rpc_bind_new_program() #
struct rpc_clnt * bind a new RPC program to an existing client
Parameters
struct rpc_clnt *old: old rpc_clientconst struct rpc_program *program: rpc program to setu32 vers: rpc program version
Description
Clones the rpc client and sets up a new RPC program. This is mainly of use for enabling different RPC programs to share the same transport. The Sun NFSv2/v3 ACL protocol can do this.
rpc_run_task() #
struct rpc_task * Allocate a new RPC task, then run rpc_execute against it
Parameters
const struct rpc_task_setup *task_setup_data: pointer to task initialisation data
rpc_call_sync() #
int Perform a synchronous RPC call
Parameters
struct rpc_clnt *clnt: pointer to RPC clientconst struct rpc_message *msg: RPC call parametersint flags: RPC call flags
rpc_call_async() #
int Perform an asynchronous RPC call
Parameters
struct rpc_clnt *clnt: pointer to RPC clientconst struct rpc_message *msg: RPC call parametersint flags: RPC call flagsconst struct rpc_call_ops *tk_ops: RPC call opsvoid *data: user call data
rpc_prepare_reply_pages() #
void Prepare to receive a reply data payload into pages
Parameters
struct rpc_rqst *req: RPC request to preparestruct page **pages: vector of struct page pointersunsigned int base: offset in first page where receive should start, in bytesunsigned int len: expected size of the upper layer data payload, in bytesunsigned int hdrsize: expected size of upper layer reply header, in XDR words
rpc_peeraddr() #
size_t extract remote peer address from clnt's xprt
Parameters
struct rpc_clnt *clnt: RPC client structurestruct sockaddr *buf: target buffersize_t bufsize: length of target buffer
Description
Returns the number of bytes that are actually in the stored address.
rpc_peeraddr2str() #
const char * return remote peer address in printable format
Parameters
struct rpc_clnt *clnt: RPC client structureenum rpc_display_format_t format: address format
Description
NB: the lifetime of the memory referenced by the returned pointer is the same as the rpc_xprt itself. As long as the caller uses this pointer, it must hold the RCU read lock.
rpc_localaddr() #
int discover local endpoint address for an RPC client
Parameters
struct rpc_clnt *clnt: RPC client structurestruct sockaddr *buf: target buffersize_t buflen: size of target buffer, in bytes
Description
Returns zero and fills in "buf" and "buflen" if successful; otherwise, a negative errno is returned.
This works even if the underlying transport is not currently connected, or if the upper layer never previously provided a source address.
The result of this function call is transient: multiple calls in succession may give different results, depending on how local networking configuration changes over time.
rpc_net_ns() #
struct net * Get the network namespace for this RPC client
Parameters
struct rpc_clnt *clnt: RPC client to query
rpc_max_payload() #
size_t Get maximum payload size for a transport, in bytes
Parameters
struct rpc_clnt *clnt: RPC client to query
Description
For stream transports, this is one RPC record fragment (see RFC 1831), as we don't support multi-record requests yet. For datagram transports, this is the size of an IP packet minus the IP, UDP, and RPC header sizes.
rpc_max_bc_payload() #
size_t Get maximum backchannel payload size, in bytes
Parameters
struct rpc_clnt *clnt: RPC client to query
rpc_force_rebind() #
void force transport to check that remote port is unchanged
Parameters
struct rpc_clnt *clnt: client to rebind
rpc_clnt_test_and_add_xprt() #
int Test and add a new transport to a rpc_clnt
Parameters
struct rpc_clnt *clnt: pointer to struct rpc_clntstruct rpc_xprt_switch *xps: pointer to struct rpc_xprt_switch,struct rpc_xprt *xprt: pointer struct rpc_xprtvoid *in_max_connect: pointer to the max_connect value for the passed in xprt transport
rpc_clnt_setup_test_and_add_xprt() #
int Parameters
struct rpc_clnt *clnt: struct rpc_clnt to get the new transportstruct rpc_xprt_switch *xps: the rpc_xprt_switch to hold the new transportstruct rpc_xprt *xprt: the rpc_xprt to testvoid *data: a struct rpc_add_xprt_test pointer that holds the test function and test function call data
Description
- This is an rpc_clnt_add_xprt
setup()function which returns 1 so:- caller of the test function must dereference the rpc_xprt_switch and the rpc_xprt.
- test function must call rpc_xprt_switch_add_xprt, usually in the rpc_call_done routine.
Upon success (return of 1), the test function adds the new transport to the rpc_clnt xprt switch
rpc_clnt_add_xprt() #
int Add a new transport to a rpc_clnt
Parameters
struct rpc_clnt *clnt: pointer to struct rpc_clntstruct xprt_create *xprtargs: pointer to struct xprt_createint (*setup)(struct rpc_clnt *, struct rpc_xprt_switch *, struct rpc_xprt *, void *): callback to test and/or set up the connectionvoid *data: pointer to setup function data
Description
Creates a new transport using the parameters set in args and adds it to clnt. If ping is set, then test that connectivity succeeds before adding the new transport.
Network device support #
Driver Support #
dev_add_pack() #
void add packet handler
Parameters
struct packet_type *pt: packet type declaration
Description
Add a protocol handler to the networking stack. The passed packet_type
is linked into kernel lists and may not be freed until it has been
removed from the kernel lists.
This call does not sleep therefore it can not guarantee all CPU's that are in middle of receiving packets will see the new packet type (until the next received packet).
__dev_remove_pack() #
void remove packet handler
Parameters
struct packet_type *pt: packet type declaration
Description
Remove a protocol handler that was previously added to the kernel
protocol handlers by dev_add_pack(). The passed packet_type is removed
from the kernel lists and can be freed or reused once this function
returns.
The packet type might still be in use by receivers and must not be freed until after all the CPU's have gone through a quiescent state.
dev_remove_pack() #
void remove packet handler
Parameters
struct packet_type *pt: packet type declaration
Description
Remove a protocol handler that was previously added to the kernel
protocol handlers by dev_add_pack(). The passed packet_type is removed
from the kernel lists and can be freed or reused once this function
returns.
This call sleeps to guarantee that no CPU is looking at the packet type after return.
dev_get_iflink() #
int get 'iflink' value of a interface
Parameters
const struct net_device *dev: targeted interface
Description
Indicates the ifindex the interface is linked to. Physical interfaces have the same 'ifindex' and 'iflink' values.
dev_fill_metadata_dst() #
int Retrieve tunnel egress information.
Parameters
struct net_device *dev: targeted interfacestruct sk_buff *skb: The packet.
Description
For better visibility of tunnel traffic OVS needs to retrieve egress tunnel information for a packet. Following API allows user to get this info.
__dev_get_by_name() #
struct net_device * find a device by its name
Parameters
struct net *net: the applicable net namespaceconst char *name: name to find
Description
Find an interface by name. Must be called under RTNL semaphore.
If the name is found a pointer to the device is returned.
If the name is not found then NULL is returned. The
reference counters are not incremented so the caller must be
careful with locks.
dev_get_by_name_rcu() #
struct net_device * find a device by its name
Parameters
struct net *net: the applicable net namespaceconst char *name: name to find
Description
Find an interface by name.
If the name is found a pointer to the device is returned.
If the name is not found then NULL is returned.
The reference counters are not incremented so the caller must be
careful with locks. The caller must hold RCU lock.
netdev_get_by_name() #
struct net_device * find a device by its name
Parameters
struct net *net: the applicable net namespaceconst char *name: name to findnetdevice_tracker *tracker: tracking object for the acquired referencegfp_t gfp: allocation flags for the tracker
Description
Find an interface by name. This can be called from any
context and does its own locking. The returned handle has
the usage count incremented and the caller must use netdev_put() to
release it when it is no longer needed. NULL is returned if no
matching device is found.
__dev_get_by_index() #
struct net_device * find a device by its ifindex
Parameters
struct net *net: the applicable net namespaceint ifindex: index of device
Description
Search for an interface by index. Returns NULL if the device
is not found or a pointer to the device. The device has not
had its reference counter increased so the caller must be careful
about locking. The caller must hold the RTNL semaphore.
dev_get_by_index_rcu() #
struct net_device * find a device by its ifindex
Parameters
struct net *net: the applicable net namespaceint ifindex: index of device
Description
Search for an interface by index. Returns NULL if the device
is not found or a pointer to the device. The device has not
had its reference counter increased so the caller must be careful
about locking. The caller must hold RCU lock.
netdev_get_by_index() #
struct net_device * find a device by its ifindex
Parameters
struct net *net: the applicable net namespaceint ifindex: index of devicenetdevice_tracker *tracker: tracking object for the acquired referencegfp_t gfp: allocation flags for the tracker
Description
Search for an interface by index. Returns NULL if the device
is not found or a pointer to the device. The device returned has
had a reference added and the pointer is safe until the user calls
netdev_put() to indicate they have finished with it.
dev_getbyhwaddr_rcu() #
struct net_device * find a device by its hardware address
Parameters
struct net *net: the applicable net namespaceunsigned short type: media type of deviceconst char *ha: hardware address
Description
Search for an interface by MAC address. Returns NULL if the device is not found or a pointer to the device. The caller must hold RCU. The returned device has not had its ref count increased and the caller must therefore be careful about locking
dev_getbyhwaddr() #
struct net_device * find a device by its hardware address
Parameters
struct net *net: the applicable net namespaceunsigned short type: media type of deviceconst char *ha: hardware address
Description
Similar to dev_getbyhwaddr_rcu(), but the owner needs to hold
rtnl_lock.
Context
rtnl_lock() must be held.
Return
pointer to the net_device, or NULL if not found
dev_valid_name() #
bool check if name is okay for network device
Parameters
const char *name: name string
Description
Network device names need to be valid file names to allow sysfs to work. We also disallow any kind of whitespace.
dev_alloc_name() #
int allocate a name for a device
Parameters
struct net_device *dev: deviceconst char *name: name format string
Description
Passed a format string - eg "ltd" it will try and find a suitable
id. It scans list of devices to build up a free map, then chooses
the first empty slot. The caller must hold the dev_base or rtnl lock
while allocating the name and adding the device in order to avoid
duplicates.
Limited to bits_per_byte * page size devices (ie 32K on most platforms).
Returns the number of the unit assigned or a negative errno code.
netdev_features_change() #
void device changes features
Parameters
struct net_device *dev: device to cause notification
Description
Called to indicate a device has changed features.
__netdev_notify_peers() #
void notify network peers about existence of dev, to be called when rtnl lock is already held.
Parameters
struct net_device *dev: network device
Description
Generate traffic such that interested network peers are aware of dev, such as by generating a gratuitous ARP. This may be used when a device wants to inform the rest of the network about some sort of reconfiguration such as a failover event or virtual machine migration.
netdev_notify_peers() #
void notify network peers about existence of dev
Parameters
struct net_device *dev: network device
Description
Generate traffic such that interested network peers are aware of dev, such as by generating a gratuitous ARP. This may be used when a device wants to inform the rest of the network about some sort of reconfiguration such as a failover event or virtual machine migration.
register_netdevice_notifier() #
int register a network notifier block
Parameters
struct notifier_block *nb: notifier
Description
Register a notifier to be called when network device events occur. The notifier passed is linked into the kernel structures and must not be reused until it has been unregistered. A negative errno code is returned on a failure.
When registered all registration and up events are replayed to the new notifier to allow device to have a race free view of the network device list.
unregister_netdevice_notifier() #
int unregister a network notifier block
Parameters
struct notifier_block *nb: notifier
Description
Unregister a notifier previously registered by
register_netdevice_notifier(). The notifier is unlinked into the
kernel structures and may then be reused. A negative errno code
is returned on a failure.
After unregistering unregister and down device events are synthesized for all devices on the device list to the removed notifier to remove the need for special case cleanup code.
register_netdevice_notifier_net() #
int register a per-netns network notifier block
Parameters
struct net *net: network namespacestruct notifier_block *nb: notifier
Description
Register a notifier to be called when network device events occur. The notifier passed is linked into the kernel structures and must not be reused until it has been unregistered. A negative errno code is returned on a failure.
When registered all registration and up events are replayed to the new notifier to allow device to have a race free view of the network device list.
unregister_netdevice_notifier_net() #
int unregister a per-netns network notifier block
Parameters
struct net *net: network namespacestruct notifier_block *nb: notifier
Description
Unregister a notifier previously registered by
register_netdevice_notifier_net(). The notifier is unlinked from the
kernel structures and may then be reused. A negative errno code
is returned on a failure.
After unregistering unregister and down device events are synthesized for all devices on the device list to the removed notifier to remove the need for special case cleanup code.
call_netdevice_notifiers() #
int call all network notifier blocks
Parameters
unsigned long val: value passed unmodified to notifier functionstruct net_device *dev: net_device pointer passed unmodified to notifier function
Description
Call all network notifier blocks. Parameters and return value
are as for raw_notifier_call_chain().
dev_forward_skb() #
int loopback an skb to another netif
Parameters
struct net_device *dev: destination network devicestruct sk_buff *skb: buffer to forward
Description
- return values: NET_RX_SUCCESS (no congestion) NET_RX_DROP (packet was dropped, but freed)
dev_forward_skb can be used for injecting an skb from the start_xmit function of one device into the receive queue of another device.
The receiving device may be in another namespace, so we have to clear all information in the skb that could impact namespace isolation.
dev_nit_active_rcu() #
bool return true if any network interface taps are in use
Parameters
const struct net_device *dev: network device to check for the presence of taps
Description
The caller must hold the RCU lock
netif_set_real_num_rx_queues() #
int set actual number of RX queues used
Parameters
struct net_device *dev: Network deviceunsigned int rxq: Actual number of RX queues
Description
This must be called either with the rtnl_lock held or before registration of the net device. Returns 0 on success, or a negative error code. If called before registration, it always succeeds.
netif_set_real_num_queues() #
int set actual number of RX and TX queues used
Parameters
struct net_device *dev: Network deviceunsigned int txq: Actual number of TX queuesunsigned int rxq: Actual number of RX queues
Description
Set the real number of both TX and RX queues. Does nothing if the number of queues is already correct.
netif_set_tso_max_size() #
void set the max size of TSO frames supported
Parameters
struct net_device *dev: netdev to updateunsigned int size: max skb->len of a TSO frame
Description
Set the limit on the size of TSO super-frames the device can handle.
Unless explicitly set the stack will assume the value of
GSO_LEGACY_MAX_SIZE.
netif_set_tso_max_segs() #
void set the max number of segs supported for TSO
Parameters
struct net_device *dev: netdev to updateunsigned int segs: max number of TCP segments
Description
Set the limit on the number of TCP segments the device can generate from
a single TSO super-frame.
Unless explicitly set the stack will assume the value of GSO_MAX_SEGS.
netif_inherit_tso_max() #
void copy all TSO limits from a lower device to an upper
Parameters
struct net_device *to: netdev to updateconst struct net_device *from: netdev from which to copy the limits
netif_get_num_default_rss_queues() #
int default number of RSS queues
Parameters
void: no arguments
Description
Default value is the number of physical cores if there are only 1 or 2, or divided by 2 if there are more.
netif_device_detach() #
void mark device as removed
Parameters
struct net_device *dev: network device
Description
Mark device as removed from system and therefore no longer available.
netif_device_attach() #
void mark device as attached
Parameters
struct net_device *dev: network device
Description
Mark device as attached from system and restart if needed.
dev_loopback_xmit() #
int loop back skb
Parameters
struct net *net: network namespace this loopback is happening instruct sock *sk: sk needed to be a netfilter okfnstruct sk_buff *skb: buffer to transmit
__dev_queue_xmit() #
int transmit a buffer
Parameters
struct sk_buff *skb: buffer to transmitstruct net_device *sb_dev: suboordinate device used for L2 forwarding offload
Description
Queue a buffer for transmission to a network device. The caller must have set the device and priority and built the buffer before calling this function. The function can be called from an interrupt.
When calling this method, interrupts MUST be enabled. This is because the BH enable code must have IRQs enabled so that it will not deadlock.
Regardless of the return value, the skb is consumed, so it is currently difficult to retry a send to this method. (You can bump the ref count before sending to hold a reference for retry if you are careful.)
Return
- 0 - buffer successfully transmitted
- positive qdisc return code - NET_XMIT_DROP etc.
- negative errno - other errors
rps_may_expire_flow() #
bool check whether an RFS hardware filter may be removed
Parameters
struct net_device *dev: Device on which the filter was setu16 rxq_index: RX queue indexu32 flow_id: Flow ID passed tondo_rx_flow_steer()u16 filter_id: Filter ID returned byndo_rx_flow_steer()
Description
Drivers that implement ndo_rx_flow_steer() should periodically call
this function for each installed filter and remove the filters for
which it returns true.
__netif_rx() #
int Slightly optimized version of netif_rx
Parameters
struct sk_buff *skb: buffer to post
Description
This behaves as netif_rx except that it does not disable bottom halves. As a result this function may only be invoked from the interrupt context (either hard or soft interrupt).
netif_rx() #
int post buffer to the network code
Parameters
struct sk_buff *skb: buffer to post
Description
This function receives a packet from a device driver and queues it for the upper (protocol) levels to process via the backlog NAPI device. It always succeeds. The buffer may be dropped during processing for congestion control or by the protocol layers. The network buffer is passed via the backlog NAPI device. Modern NIC driver should use NAPI and GRO. This function can used from interrupt and from process context. The caller from process context must not disable interrupts before invoking this function.
return values: NET_RX_SUCCESS (no congestion) NET_RX_DROP (packet was dropped)
netdev_is_rx_handler_busy() #
bool check if receive handler is registered
Parameters
struct net_device *dev: device to check
Description
Check if a receive handler is already registered for a given device. Return true if there one.
The caller must hold the rtnl_mutex.
netdev_rx_handler_register() #
int register receive handler
Parameters
struct net_device *dev: device to register a handler forrx_handler_func_t *rx_handler: receive handler to registervoid *rx_handler_data: data pointer that is used by rx handler
Description
Register a receive handler for a device. This handler will then be called from __netif_receive_skb. A negative errno code is returned on a failure.
The caller must hold the rtnl_mutex.
For a general description of rx_handler, see enum rx_handler_result.
netdev_rx_handler_unregister() #
void unregister receive handler
Parameters
struct net_device *dev: device to unregister a handler from
Description
Unregister a receive handler from a device.
The caller must hold the rtnl_mutex.
netif_receive_skb_core() #
int special purpose version of netif_receive_skb
Parameters
struct sk_buff *skb: buffer to process
Description
More direct receive version of netif_receive_skb(). It should
only be used by callers that have a need to skip RPS and Generic XDP.
Caller must also take care of handling if (page_is_)pfmemalloc.
This function may only be called from softirq context and interrupts should be enabled.
Return values (usually ignored): NET_RX_SUCCESS: no congestion NET_RX_DROP: packet was dropped
netif_receive_skb() #
int process receive buffer from network
Parameters
struct sk_buff *skb: buffer to process
Description
netif_receive_skb() is the main receive data processing function.
It always succeeds. The buffer may be dropped during processing
for congestion control or by the protocol layers.
This function may only be called from softirq context and interrupts should be enabled.
Return values (usually ignored): NET_RX_SUCCESS: no congestion NET_RX_DROP: packet was dropped
netif_receive_skb_list() #
void process many receive buffers from network
Parameters
struct list_head *head: list of skbs to process.
Description
Since return value of netif_receive_skb() is normally ignored, and
wouldn't be meaningful for a list, this function returns void.
This function may only be called from softirq context and interrupts should be enabled.
__napi_schedule() #
void schedule for receive
Parameters
struct napi_struct *n: entry to schedule
Description
The entry's receive function will be scheduled to run.
Consider using __napi_schedule_irqoff() if hard irqs are masked.
napi_schedule_prep() #
bool check if napi can be scheduled
Parameters
struct napi_struct *n: napi context
Description
Test if NAPI routine is already running, and if not mark it as running. This is used as a condition variable to insure only one NAPI poll instance runs. We also make sure there is no pending NAPI disable.
__napi_schedule_irqoff() #
void schedule for receive
Parameters
struct napi_struct *n: entry to schedule
Description
Variant of __napi_schedule() assuming hard irqs are masked.
On PREEMPT_RT enabled kernels this maps to __napi_schedule()
because the interrupt disabled assumption might not be true
due to force-threaded interrupts and spinlock substitution.
netif_threaded_enable() #
void enable threaded NAPIs
Parameters
struct net_device *dev: net_device instance
Description
Enable threaded mode for the NAPI instances of the device. This may be useful for devices where multiple NAPI instances get scheduled by a single interrupt. Threaded NAPI allows moving the NAPI processing to cores other than the core where IRQ is mapped.
This function should be called before dev is registered.
netif_queue_set_napi() #
void Associate queue with the napi
Parameters
struct net_device *dev: device to which NAPI and queue belongunsigned int queue_index: Index of queueenum netdev_queue_type type: queue type as RX or TXstruct napi_struct *napi: NAPI context, pass NULL to clear previously set NAPI
Description
Set queue with its corresponding napi context. This should be done after registering the NAPI handler for the queue-vector and the queues have been mapped to the corresponding interrupt vector.
napi_disable() #
void prevent NAPI from scheduling
Parameters
struct napi_struct *n: NAPI context
Description
Stop NAPI from being scheduled on this context.
Waits till any outstanding processing completes.
Takes netdev_lock() for associated net_device.
napi_enable() #
void enable NAPI scheduling
Parameters
struct napi_struct *n: NAPI context
Description
Enable scheduling of a NAPI instance.
Must be paired with napi_disable().
Takes netdev_lock() for associated net_device.
netdev_has_upper_dev() #
bool Check if device is linked to an upper device
Parameters
struct net_device *dev: devicestruct net_device *upper_dev: upper device to check
Description
Find out if a device is linked to specified upper device and return true in case it is. Note that this checks only immediate upper device, not through a complete stack of devices. The caller must hold the RTNL lock.
netdev_has_upper_dev_all_rcu() #
bool Check if device is linked to an upper device
Parameters
struct net_device *dev: devicestruct net_device *upper_dev: upper device to check
Description
Find out if a device is linked to specified upper device and return true in case it is. Note that this checks the entire upper device chain. The caller must hold rcu lock.
netdev_has_any_upper_dev() #
bool Check if device is linked to some device
Parameters
struct net_device *dev: device
Description
Find out if a device is linked to an upper device and return true in case it is. The caller must hold the RTNL lock.
netdev_master_upper_dev_get() #
struct net_device * Get master upper device
Parameters
struct net_device *dev: device
Description
Find a master upper device and return pointer to it or NULL in case it's not there. The caller must hold the RTNL lock.
netdev_upper_get_next_dev_rcu() #
struct net_device * Get the next dev from upper list
Parameters
struct net_device *dev: devicestruct list_head **iter: list_head ** of the current position
Description
Gets the next device from the dev's upper list, starting from iter position. The caller must hold RCU read lock.
netdev_lower_get_next_private() #
void * Get the next ->private from the lower neighbour list
Parameters
struct net_device *dev: devicestruct list_head **iter: list_head ** of the current position
Description
Gets the next netdev_adjacent->private from the dev's lower neighbour list, starting from iter position. The caller must hold either hold the RTNL lock or its own locking that guarantees that the neighbour lower list will remain unchanged.
netdev_lower_get_next_private_rcu() #
void * Get the next ->private from the lower neighbour list, RCU variant
Parameters
struct net_device *dev: devicestruct list_head **iter: list_head ** of the current position
Description
Gets the next netdev_adjacent->private from the dev's lower neighbour list, starting from iter position. The caller must hold RCU read lock.
netdev_lower_get_next() #
void * Get the next device from the lower neighbour list
Parameters
struct net_device *dev: devicestruct list_head **iter: list_head ** of the current position
Description
Gets the next netdev_adjacent from the dev's lower neighbour list, starting from iter position. The caller must hold RTNL lock or its own locking that guarantees that the neighbour lower list will remain unchanged.
netdev_lower_get_first_private_rcu() #
void * Get the first ->private from the lower neighbour list, RCU variant
Parameters
struct net_device *dev: device
Description
Gets the first netdev_adjacent->private from the dev's lower neighbour list. The caller must hold RCU read lock.
netdev_master_upper_dev_get_rcu() #
struct net_device * Get master upper device
Parameters
struct net_device *dev: device
Description
Find a master upper device and return pointer to it or NULL in case it's not there. The caller must hold the RCU read lock.
netdev_upper_dev_link() #
int Add a link to the upper device
Parameters
struct net_device *dev: devicestruct net_device *upper_dev: new upper devicestruct netlink_ext_ack *extack: netlink extended ack
Description
Adds a link to device which is upper to this one. The caller must hold the RTNL lock. On a failure a negative errno code is returned. On success the reference counts are adjusted and the function returns zero.
netdev_master_upper_dev_link() #
int Add a master link to the upper device
Parameters
struct net_device *dev: devicestruct net_device *upper_dev: new upper devicevoid *upper_priv: upper device privatevoid *upper_info: upper info to be passed down via notifierstruct netlink_ext_ack *extack: netlink extended ack
Description
Adds a link to device which is upper to this one. In this case, only one master upper device can be linked, although other non-master devices might be linked as well. The caller must hold the RTNL lock. On a failure a negative errno code is returned. On success the reference counts are adjusted and the function returns zero.
netdev_upper_dev_unlink() #
void Removes a link to upper device
Parameters
struct net_device *dev: devicestruct net_device *upper_dev: new upper device
Description
Removes a link to device which is upper to this one. The caller must hold the RTNL lock.
netdev_bonding_info_change() #
void Dispatch event about slave change
Parameters
struct net_device *dev: devicestruct netdev_bonding_info *bonding_info: info to dispatch
Description
Send NETDEV_BONDING_INFO to netdev notifiers with info. The caller must hold the RTNL lock.
netdev_get_xmit_slave() #
struct net_device * Get the xmit slave of master device
Parameters
struct net_device *dev: devicestruct sk_buff *skb: The packetbool all_slaves: assume all the slaves are active
Description
The reference counters are not incremented so the caller must be
careful with locks. The caller must hold RCU lock.
NULL is returned if no slave is found.
netdev_sk_get_lowest_dev() #
struct net_device * Get the lowest device in chain given device and socket
Parameters
struct net_device *dev: devicestruct sock *sk: the socket
Description
NULL is returned if no lower device is found.
netdev_lower_state_changed() #
void Dispatch event about lower device state change
Parameters
struct net_device *lower_dev: devicevoid *lower_state_info: state to dispatch
Description
Send NETDEV_CHANGELOWERSTATE to netdev notifiers with info. The caller must hold the RTNL lock.
netif_get_flags() #
unsigned int get flags reported to userspace
Parameters
const struct net_device *dev: device
Description
Get the combination of flag bits exported through APIs to userspace.
netif_pre_changeaddr_notify() #
int Call NETDEV_PRE_CHANGEADDR.
Parameters
struct net_device *dev: deviceconst char *addr: new addressstruct netlink_ext_ack *extack: netlink extended ack
Return
0 on success, -errno on failure.
netif_get_port_parent_id() #
int Get the device's port parent identifier
Parameters
struct net_device *dev: network devicestruct netdev_phys_item_id *ppid: pointer to a storage for the port's parent identifierbool recurse: allow/disallow recursion to lower devices
Description
Get the devices's port parent identifier.
Return
0 on success, -errno on failure.
netdev_port_same_parent_id() #
bool Indicate if two network devices have the same port parent identifier
Parameters
struct net_device *a: first network devicestruct net_device *b: second network device
netdev_update_features() #
void recalculate device features
Parameters
struct net_device *dev: the device to check
Description
Recalculate dev->features set and send notifications if it has changed. Should be called after driver or hardware dependent conditions might have changed that influence the features.
netdev_change_features() #
void recalculate device features
Parameters
struct net_device *dev: the device to check
Description
Recalculate dev->features set and send notifications even
if they have not changed. Should be called instead of
netdev_update_features() if also dev->vlan_features might
have changed to allow the changes to be propagated to stacked
VLAN devices.
netif_stacked_transfer_operstate() #
void transfer operstate
Parameters
const struct net_device *rootdev: the root or lower level device to transfer state fromstruct net_device *dev: the device to transfer operstate to
Description
Transfer operational state from root to device. This is normally called when a stacking relationship exists between the root device and the device(a leaf device).
register_netdevice() #
int register a network device
Parameters
struct net_device *dev: device to register
Description
Take a prepared network device structure and make it externally accessible.
A NETDEV_REGISTER message is sent to the netdev notifier chain.
Callers must hold the rtnl lock - you may want register_netdev()
instead of this.
register_netdev() #
int register a network device
Parameters
struct net_device *dev: device to register
Description
Take a completed network device structure and add it to the kernel
interfaces. A NETDEV_REGISTER message is sent to the netdev notifier
chain. 0 is returned on success. A negative errno code is returned
on a failure to set up the device, or if the name is a duplicate.
This is a wrapper around register_netdevice that takes the rtnl semaphore and expands the device name if you passed a format string to alloc_netdev.
dev_get_stats() #
struct rtnl_link_stats64 * get network device statistics
Parameters
struct net_device *dev: device to get statistics fromstruct rtnl_link_stats64 *storage: place to store stats
Description
Get network statistics from device. Return storage. The device driver may provide its own method by setting dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats; otherwise the internal statistics structure is used.
dev_fetch_sw_netstats() #
void get per-cpu network device statistics
Parameters
struct rtnl_link_stats64 *s: place to store statsconst struct pcpu_sw_netstats __percpu *netstats: per-cpu network stats to read from
Description
Read per-cpu network statistics and populate the related fields in s.
dev_get_tstats64() #
void ndo_get_stats64 implementation
Parameters
struct net_device *dev: device to get statistics fromstruct rtnl_link_stats64 *s: place to store stats
Description
Populate s from dev->stats and dev->tstats. Can be used as
ndo_get_stats64() callback.
netdev_sw_irq_coalesce_default_on() #
void enable SW IRQ coalescing by default
Parameters
struct net_device *dev: netdev to enable the IRQ coalescing on
Description
Sets a conservative default for SW IRQ coalescing. Users can use sysfs attributes to override the default values.
alloc_netdev_mqs() #
struct net_device * allocate network device
Parameters
int sizeof_priv: size of private data to allocate space forconst char *name: device name format stringunsigned char name_assign_type: origin of device namevoid (*setup)(struct net_device *): callback to initialize deviceunsigned int txqs: the number of TX subqueues to allocateunsigned int rxqs: the number of RX subqueues to allocate
Description
Allocates a struct net_device with private data area for driver use and performs basic initialization. Also allocates subqueue structs for each queue on the device.
free_netdev() #
void free network device
Parameters
struct net_device *dev: device
Description
This function does the last stage of destroying an allocated device interface. The reference to the device object is released. If this is the last reference then it will be freed.Must be called in process context.
alloc_netdev_dummy() #
struct net_device * Allocate and initialize a dummy net device.
Parameters
int sizeof_priv: size of private data to allocate space for
Return
the allocated net_device on success, NULL otherwise
synchronize_net() #
void Synchronize with packet receive processing
Parameters
void: no arguments
Description
Wait for packets currently being received to be done. Does not block later packets from starting.
unregister_netdevice_queue() #
void remove device from the kernel
Parameters
struct net_device *dev: devicestruct list_head *head: list
Description
This function shuts down a device interface and removes it from the kernel tables. If head not NULL, device is queued to be unregistered later.
Callers must hold the rtnl semaphore. You may want
unregister_netdev() instead of this.
unregister_netdevice_many() #
void unregister many devices
Parameters
struct list_head *head: list of devices
Note
-
As most callers use a stack allocated list_head,
we force a
list_del()to make sure stack won't be corrupted later.
unregister_netdev() #
void remove device from the kernel
Parameters
struct net_device *dev: device
Description
This function shuts down a device interface and removes it from the kernel tables.
This is just a wrapper for unregister_netdevice that takes the rtnl semaphore. In general you want to use this and not unregister_netdevice.
netdev_increment_features() #
netdev_features_t increment feature set by one
Parameters
netdev_features_t all: current feature setnetdev_features_t one: new feature setnetdev_features_t mask: mask feature set
Description
Computes a new feature set after adding a device with feature set one to the master device with current feature set all. Will not enable anything that is off in mask. Returns the new feature set.
netdev_compute_master_upper_features() #
void compute feature from lowers
Parameters
struct net_device *dev: the upper devicebool update_header: whether to update upper device's header_len/headroom/tailroom
Description
Recompute the upper device's feature based on all lower devices.
eth_header() #
int create the Ethernet header
Parameters
struct sk_buff *skb: buffer to alterstruct net_device *dev: source deviceunsigned short type: Ethernet type fieldconst void *daddr: destination address (NULL leave destination address)const void *saddr: source address (NULL use device source address)unsigned int len: packet length (<= skb->len)
Description
Set the protocol type. For a packet of type ETH_P_802_3/2 we put the length in here instead.
eth_get_headlen() #
u32 determine the length of header for an ethernet frame
Parameters
const struct net_device *dev: pointer to network deviceconst void *data: pointer to start of frameu32 len: total length of frame
Description
Make a best effort attempt to pull the length for all of the headers for a given frame in a linear buffer.
eth_type_trans() #
__be16 determine the packet's protocol ID.
Parameters
struct sk_buff *skb: received socket datastruct net_device *dev: receiving network device
Description
The rule here is that we assume 802.3 if the type field is short enough to be a length. This is normal practice and works for any 'now in use' protocol.
eth_header_cache() #
int fill cache entry from neighbour
Parameters
const struct neighbour *neigh: source neighbourstruct hh_cache *hh: destination cache entry__be16 type: Ethernet type field
Description
Create an Ethernet header template from the neighbour.
eth_header_cache_update() #
void update cache entry
Parameters
struct hh_cache *hh: destination cache entryconst struct net_device *dev: network deviceconst unsigned char *haddr: new hardware address
Description
Called by Address Resolution module to notify changes in address.
eth_header_parse_protocol() #
__be16 extract protocol from L2 header
Parameters
const struct sk_buff *skb: packet to extract protocol from
eth_prepare_mac_addr_change() #
int prepare for mac change
Parameters
struct net_device *dev: network devicevoid *p: socket address
eth_commit_mac_addr_change() #
void commit mac change
Parameters
struct net_device *dev: network devicevoid *p: socket address
eth_mac_addr() #
int set new Ethernet hardware address
Parameters
struct net_device *dev: network devicevoid *p: socket address
Description
Change hardware address of device.
This doesn't change hardware matching, so needs to be overridden for most real devices.
ether_setup() #
void setup Ethernet network device
Parameters
struct net_device *dev: network device
Description
Fill in the fields of the device structure with Ethernet-generic values.
alloc_etherdev_mqs() #
struct net_device * Allocates and sets up an Ethernet device
Parameters
int sizeof_priv: Size of additional driver-private structure to be allocated for this Ethernet deviceunsigned int txqs: The number of TX queues this device has.unsigned int rxqs: The number of RX queues this device has.
Description
Fill in the fields of the device structure with Ethernet-generic values. Basically does everything except registering the device.
Constructs a new net device, complete with a private data area of size (sizeof_priv). A 32-byte (not bit) alignment is enforced for this private data area.
platform_get_ethdev_address() #
int Set netdev's MAC address from a given device
Parameters
struct device *dev: Pointer to the devicestruct net_device *netdev: Pointer to netdev to write the address to
Description
Wrapper around eth_platform_get_mac_address() which writes the address
directly to netdev->dev_addr.
fwnode_get_mac_address() #
int Get the MAC from the firmware node
Parameters
struct fwnode_handle *fwnode: Pointer to the firmware nodechar *addr: Address of buffer to store the MAC in
Description
Search the firmware node for the best MAC address to use. 'mac-address' is checked first, because that is supposed to contain to "most recent" MAC address. If that isn't set, then 'local-mac-address' is checked next, because that is the default address. If that isn't set, then the obsolete 'address' is checked, just in case we're using an old device tree.
Note that the 'address' property is supposed to contain a virtual address of the register set, but some DTS files have redefined that property to be the MAC address.
All-zero MAC addresses are rejected, because those could be properties that exist in the firmware tables, but were not updated by the firmware. For example, the DTS could define 'mac-address' and 'local-mac-address', with zero MAC addresses. Some older U-Boots only initialized 'local-mac-address'. In this case, the real MAC is in 'local-mac-address', and 'mac-address' exists but is all zeros.
device_get_mac_address() #
int Get the MAC for a given device
Parameters
struct device *dev: Pointer to the devicechar *addr: Address of buffer to store the MAC in
device_get_ethdev_address() #
int Set netdev's MAC address from a given device
Parameters
struct device *dev: Pointer to the devicestruct net_device *netdev: Pointer to netdev to write the address to
Description
Wrapper around device_get_mac_address() which writes the address
directly to netdev->dev_addr.
netif_carrier_on() #
void set carrier
Parameters
struct net_device *dev: network device
Description
Device has detected acquisition of carrier.
netif_carrier_off() #
void clear carrier
Parameters
struct net_device *dev: network device
Description
Device has detected loss of carrier.
netif_carrier_event() #
void report carrier state event
Parameters
struct net_device *dev: network device
Description
Device has detected a carrier event but the carrier state wasn't changed. Use in drivers when querying carrier state asynchronously, to avoid missing events (link flaps) if link recovers before it's queried.
is_link_local_ether_addr() #
bool Determine if given Ethernet address is link-local
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Return
true if address is link local reserved addr (01:80:c2:00:00:0X) per IEEE 802.1Q 8.6.3 Frame filtering.
Description
Please note: addr must be aligned to u16.
is_zero_ether_addr() #
bool Determine if give Ethernet address is all zeros.
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Return
true if the address is all zeroes.
Description
Please note: addr must be aligned to u16.
is_multicast_ether_addr() #
bool Determine if the Ethernet address is a multicast.
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Return
true if the address is a multicast address. By definition the broadcast address is also a multicast address.
is_local_ether_addr() #
bool Determine if the Ethernet address is locally-assigned one (IEEE 802).
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Return
true if the address is a local address.
is_broadcast_ether_addr() #
bool Determine if the Ethernet address is broadcast
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Return
true if the address is the broadcast address.
Description
Please note: addr must be aligned to u16.
is_unicast_ether_addr() #
bool Determine if the Ethernet address is unicast
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Return
true if the address is a unicast address.
is_valid_ether_addr() #
bool Determine if the given Ethernet address is valid
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Description
Check that the Ethernet address (MAC) is not 00:00:00:00:00:00, is not a multicast address, and is not FF:FF:FF:FF:FF:FF.
Please note: addr must be aligned to u16.
Return
true if the address is valid.
eth_proto_is_802_3() #
bool Determine if a given Ethertype/length is a protocol
Parameters
__be16 proto: Ethertype/length value to be tested
Description
Check that the value from the Ethertype/length field is a valid Ethertype.
Return
true if the valid is an 802.3 supported Ethertype.
eth_random_addr() #
void Generate software assigned random Ethernet address
Parameters
u8 *addr: Pointer to a six-byte array containing the Ethernet address
Description
Generate a random Ethernet address (MAC) that is not multicast and has the local assigned bit set.
eth_broadcast_addr() #
void Assign broadcast address
Parameters
u8 *addr: Pointer to a six-byte array containing the Ethernet address
Description
Assign the broadcast address to the given address array.
eth_zero_addr() #
void Assign zero address
Parameters
u8 *addr: Pointer to a six-byte array containing the Ethernet address
Description
Assign the zero address to the given address array.
eth_hw_addr_random() #
void Generate software assigned random Ethernet and set device flag
Parameters
struct net_device *dev: pointer to net_device structure
Description
Generate a random Ethernet address (MAC) to be used by a net device and set addr_assign_type so the state can be read by sysfs and be used by userspace.
eth_hw_addr_crc() #
u32 Calculate CRC from netdev_hw_addr
Parameters
struct netdev_hw_addr *ha: pointer to hardware address
Description
Calculate CRC from a hardware address as basis for filter hashes.
ether_addr_copy() #
void Copy an Ethernet address
Parameters
u8 *dst: Pointer to a six-byte array Ethernet address destinationconst u8 *src: Pointer to a six-byte array Ethernet address source
Description
Please note: dst & src must both be aligned to u16.
eth_hw_addr_set() #
void Assign Ethernet address to a net_device
Parameters
struct net_device *dev: pointer to net_device structureconst u8 *addr: address to assign
Description
Assign given address to the net_device, addr_assign_type is not changed.
eth_hw_addr_inherit() #
void Copy dev_addr from another net_device
Parameters
struct net_device *dst: pointer to net_device to copy dev_addr tostruct net_device *src: pointer to net_device to copy dev_addr from
Description
Copy the Ethernet address from one net_device to another along with the address attributes (addr_assign_type).
ether_addr_equal() #
bool Compare two Ethernet addresses
Parameters
const u8 *addr1: Pointer to a six-byte array containing the Ethernet addressconst u8 *addr2: Pointer other six-byte array containing the Ethernet address
Description
Compare two Ethernet addresses, returns true if equal
Please note: addr1 & addr2 must both be aligned to u16.
ether_addr_equal_64bits() #
bool Compare two Ethernet addresses
Parameters
const u8 *addr1: Pointer to an array of 8 bytesconst u8 *addr2: Pointer to an other array of 8 bytes
Description
Compare two Ethernet addresses, returns true if equal, false otherwise.
The function doesn't need any conditional branches and possibly uses word memory accesses on CPU allowing cheap unaligned memory reads. arrays = { byte1, byte2, byte3, byte4, byte5, byte6, pad1, pad2 }
Please note that alignment of addr1 & addr2 are only guaranteed to be 16 bits.
ether_addr_equal_unaligned() #
bool Compare two not u16 aligned Ethernet addresses
Parameters
const u8 *addr1: Pointer to a six-byte array containing the Ethernet addressconst u8 *addr2: Pointer other six-byte array containing the Ethernet address
Description
Compare two Ethernet addresses, returns true if equal
Please note: Use only when any Ethernet address may not be u16 aligned.
ether_addr_equal_masked() #
bool Compare two Ethernet addresses with a mask
Parameters
const u8 *addr1: Pointer to a six-byte array containing the 1st Ethernet addressconst u8 *addr2: Pointer to a six-byte array containing the 2nd Ethernet addressconst u8 *mask: Pointer to a six-byte array containing the Ethernet address bitmask
Description
Compare two Ethernet addresses with a mask, returns true if for every bit set in the bitmask the equivalent bits in the ethernet addresses are equal. Using a mask with all bits set is a slower ether_addr_equal.
ether_addr_to_u64() #
u64 Convert an Ethernet address into a u64 value.
Parameters
const u8 *addr: Pointer to a six-byte array containing the Ethernet address
Return
a u64 value of the address
u64_to_ether_addr() #
void Convert a u64 to an Ethernet address.
Parameters
u64 u: u64 to convert to an Ethernet MAC addressu8 *addr: Pointer to a six-byte array to contain the Ethernet address
eth_addr_dec() #
void Decrement the given MAC address
Parameters
u8 *addr: Pointer to a six-byte array containing Ethernet address to decrement
eth_addr_inc() #
void Increment the given MAC address.
Parameters
u8 *addr: Pointer to a six-byte array containing Ethernet address to increment.
eth_addr_add() #
void Add (or subtract) an offset to/from the given MAC address.
Parameters
u8 *addr: Pointer to a six-byte array containing Ethernet address to increment.long offset: Offset to add.
is_etherdev_addr() #
bool Tell if given Ethernet address belongs to the device.
Parameters
const struct net_device *dev: Pointer to a device structureconst u8 addr[6 + 2]: Pointer to a six-byte array containing the Ethernet address
Description
Compare passed address with all addresses of the device. Return true if the address if one of the device addresses.
Note that this function calls ether_addr_equal_64bits() so take care of
the right padding.
compare_ether_header() #
unsigned long Compare two Ethernet headers
Parameters
const void *a: Pointer to Ethernet headerconst void *b: Pointer to Ethernet header
Description
Compare two Ethernet headers, returns 0 if equal. This assumes that the network header (i.e., IP header) is 4-byte aligned OR the platform can handle unaligned access. This is the case for all packets coming into netif_receive_skb or similar entry points.
eth_hw_addr_gen() #
void Generate and assign Ethernet address to a port
Parameters
struct net_device *dev: pointer to port's net_device structureconst u8 *base_addr: base Ethernet addressunsigned int id: offset to add to the base address
Description
Generate a MAC address using a base address and an offset and assign it to a net_device. Commonly used by switch drivers which need to compute addresses for all their ports. addr_assign_type is not changed.
eth_skb_pkt_type() #
void Assign packet type if destination address does not match
Parameters
struct sk_buff *skb: Assigned a packet type if address does not match dev addressconst struct net_device *dev: Network device used to compare packet address against
Description
If the destination MAC address of the packet does not match the network device address, assign an appropriate packet type.
eth_skb_pad() #
int Pad buffer to minimum number of octets for Ethernet frame
Parameters
struct sk_buff *skb: Buffer to pad
Description
An Ethernet frame should have a minimum size of 60 bytes. This function takes short frames and pads them with zeros up to the 60 byte limit.
struct gro_node #
structure to support Generic Receive Offload
Definition
;
Members
bitmask: bitmask to indicate used buckets in hashhash: hashtable of pending aggregated skbs, separated by flowsrx_list: list of pendingGRO_NORMALskbsrx_count: cached current length of rx_listcached_napi_id: napi_struct::napi_id cached for hotpath, 0 for standalone
napi_is_scheduled() #
bool test if NAPI is scheduled
Parameters
struct napi_struct *n: NAPI context
Description
This check is "best-effort". With no locking implemented, a NAPI can be scheduled or terminate right after this check and produce not precise results.
NAPI_STATE_SCHED is an internal state, napi_is_scheduled should not be used normally and napi_schedule should be used instead.
Use only if the driver really needs to check if a NAPI is scheduled for example in the context of delayed timer that can be skipped if a NAPI is already scheduled.
Return
True if NAPI is scheduled, False otherwise.
napi_schedule() #
bool schedule NAPI poll
Parameters
struct napi_struct *n: NAPI context
Description
Schedule NAPI poll routine to be called if it is not already running.
Return
true if we schedule a NAPI or false if not.
Refer to napi_schedule_prep() for additional reason on why
a NAPI might not be scheduled.
napi_schedule_irqoff() #
void schedule NAPI poll
Parameters
struct napi_struct *n: NAPI context
Description
Variant of napi_schedule(), assuming hard irqs are masked.
napi_complete_done() #
bool NAPI processing complete
Parameters
struct napi_struct *n: NAPI contextint work_done: number of packets processed
Description
Mark NAPI processing as complete. Should only be called if poll budget
has not been completely consumed.
Prefer over napi_complete().
Return
false if device should avoid rearming interrupts.
napi_synchronize() #
void wait until NAPI is not running
Parameters
const struct napi_struct *n: NAPI context
Description
Wait until NAPI is done being scheduled on this context. Waits till any outstanding processing completes but does not disable future activations.
napi_if_scheduled_mark_missed() #
bool if napi is running, set the NAPIF_STATE_MISSED
Parameters
struct napi_struct *n: NAPI context
Description
If napi is running, set the NAPIF_STATE_MISSED, and return true if NAPI is scheduled.
enum netdev_priv_flags #
struct net_device priv_flags
Constants
IFF_802_1Q_VLAN: 802.1Q VLAN deviceIFF_EBRIDGE: Ethernet bridging deviceIFF_BONDING: bonding master or slaveIFF_ISATAP: ISATAP interface (RFC4214)IFF_WAN_HDLC: WAN HDLC deviceIFF_XMIT_DST_RELEASE:dev_hard_start_xmit()is allowed to release skb->dstIFF_DONT_BRIDGE: disallow bridging this ether devIFF_DISABLE_NETPOLL: disable netpoll at run-timeIFF_MACVLAN_PORT: device used as macvlan portIFF_BRIDGE_PORT: device used as bridge portIFF_OVS_DATAPATH: device used as Open vSwitch datapath portIFF_TX_SKB_SHARING: The interface supports sharing skbs on transmitIFF_UNICAST_FLT: Supports unicast filteringIFF_TEAM_PORT: device used as team portIFF_SUPP_NOFCS: device supports sending custom FCSIFF_LIVE_ADDR_CHANGE: device supports hardware address change when it's runningIFF_MACVLAN: Macvlan deviceIFF_XMIT_DST_RELEASE_PERM: IFF_XMIT_DST_RELEASE not taking into account underlying stacked devicesIFF_L3MDEV_MASTER: device is an L3 master deviceIFF_NO_QUEUE: device can run without qdisc attachedIFF_OPENVSWITCH: device is a Open vSwitch masterIFF_L3MDEV_SLAVE: device is enslaved to an L3 master deviceIFF_TEAM: device is a team deviceIFF_RXFH_CONFIGURED: device has had Rx Flow indirection table configuredIFF_PHONY_HEADROOM: the headroom value is controlled by an external entity (i.e. the master device for bridged veth)IFF_MACSEC: device is a MACsec deviceIFF_NO_RX_HANDLER: device doesn't support the rx_handler hookIFF_FAILOVER: device is a failover master deviceIFF_FAILOVER_SLAVE: device is lower dev of a failover master deviceIFF_L3MDEV_RX_HANDLER: only invoke the rx handler of L3 master deviceIFF_NO_ADDRCONF: prevent ipv6 addrconfIFF_TX_SKB_NO_LINEAR: device/driver is capable of xmitting frames with skb_headlen(skb) == 0 (data starts from frag0)
Description
These are the struct net_device, they are only set internally
by drivers and used in the kernel. These flags are invisible to
userspace; this means that the order of these flags can change
during any kernel release.
You should add bitfield booleans after either net_device::priv_flags (hotpath) or ::threaded (slowpath) instead of extending these flags.
struct net_device #
The DEVICE structure.
Definition
;
Members
-
priv_flags: flags invisible to userspace defined as bits, see enum netdev_priv_flags for the definitions -
lltx: device supports lockless Tx. Deprecated for real HW drivers. Mainly used by logical interfaces, such as bonding and tunnels -
netmem_tx: device support netmem_tx. -
netdev_ops: Includes several pointers to callbacks, if one wants to override the ndo_*() functions -
header_ops: Includes callbacks for creating,parsing,caching,etc of Layer 2 headers. -
_tx: Array of TX queues -
gso_partial_features: value(s) from NETIF_F_GSO* -
real_num_tx_queues: Number of TX queues currently active in device -
gso_max_size: Maximum size of generic segmentation offload -
gso_ipv4_max_size: Maximum size of generic segmentation offload, for IPv4. -
gso_max_segs: Maximum number of segments that can be passed to the NIC for GSO -
num_tc: Number of traffic classes in the net device -
mtu: Interface MTU value -
needed_headroom: Extra headroom the hardware may need, but not in all cases can this be guaranteed -
tc_to_txq: XXX: need comments on this one -
xps_maps: XXX: need comments on this one -
nf_hooks_egress: netfilter hooks executed for egress packets -
tcx_egress: BPF & clsact qdisc specific data for egress processing -
{unnamed_union}: anonymous -
lstats: Loopback statistics: packets, bytes -
tstats: Tunnel statistics: RX/TX packets, RX/TX bytes -
dstats: Dummy statistics: RX/TX/drop packets, RX/TX bytes -
state: Generic network queuing layer state, see netdev_state_t -
flags: Interface flags (a la BSD) -
hard_header_len: Maximum hardware header length. -
pcpu_stat_type: Type of device statistics which the core should allocate/free: none, lstats, tstats, dstats. none means the driver is handling statistics allocation/ freeing internally. -
features: Currently active device features -
ip6_ptr: IPv6 specific data -
xdp_prog: XDP sockets filter program pointer -
ptype_specific: Device-specific, protocol-specific packet handlers -
ifindex: interface index -
real_num_rx_queues: Number of RX queues currently active in device -
_rx: Array of RX queues -
gro_max_size: Maximum size of aggregated packet in generic receive offload (GRO) -
gro_ipv4_max_size: Maximum size of aggregated packet in generic receive offload (GRO), for IPv4. -
rx_handler: handler for received packets -
rx_handler_data: XXX: need comments on this one -
nd_net: Network namespace this network device is inside protected by lock -
npinfo: XXX: need comments on this one -
tcx_ingress: BPF & clsact qdisc specific data for ingress processing -
name: This is the first field of the "visible" part of this structure (i.e. as seen by users in the "Space.c" file). It is the name of the interface. -
name_node: Name hashlist node -
ifalias: SNMP alias -
mem_end: Shared memory end -
mem_start: Shared memory start -
base_addr: Device I/O address -
dev_list: The global list of network devices -
napi_list: List entry used for polling NAPI devices -
unreg_list: List entry when we are unregistering the device; see the function unregister_netdev -
close_list: List entry used when we are closing the device -
ptype_all: Device-specific packet handlers for all protocols -
adj_list: Directly linked devices, like slaves for bonding -
xdp_features: XDP capability supported by the device -
xdp_metadata_ops: Includes pointers to XDP metadata callbacks. -
xsk_tx_metadata_ops: Includes pointers to AF_XDP TX metadata callbacks. -
gflags: Global flags ( kept as legacy ) -
needed_tailroom: Extra tailroom the hardware may need, but not in all cases can this be guaranteed. Some cases also use LL_MAX_HEADER instead to allocate the skb -
hw_features: User-changeable features -
wanted_features: User-requested features -
vlan_features: Mask of features inheritable by VLAN devices -
hw_enc_features: Mask of features inherited by encapsulating devices This field indicates what encapsulation offloads the hardware is capable of doing, and drivers will need to set them appropriately. -
mpls_features: Mask of features inheritable by MPLS -
mangleid_features: Mask of features requiring MANGLEID, will be disabled together with the latter. -
min_mtu: Interface Minimum MTU value -
max_mtu: Interface Maximum MTU value -
type: Interface hardware type -
min_header_len: Minimum hardware header length -
name_assign_type: network interface name assignment type -
group: The group the device belongs to -
stats: Statistics struct, which was left as a legacy, use rtnl_link_stats64 instead -
core_stats: core networking counters, do not use this in drivers -
carrier_up_count: Number of times the carrier has been up -
carrier_down_count: Number of times the carrier has been down -
wireless_handlers: List of functions to handle Wireless Extensions, instead of ioctl, see <net/iw_handler.h> for details. -
ethtool_ops: Management operations -
l3mdev_ops: Layer 3 master device operations -
ndisc_ops: Includes callbacks for different IPv6 neighbour discovery handling. Necessary for e.g. 6LoWPAN. -
xfrmdev_ops: Transformation offload operations -
tlsdev_ops: Transport Layer Security offload operations -
operstate: RFC2863 operstate -
link_mode: Mapping policy to operstate -
if_port: Selectable AUI, TP, ... -
dma: DMA channel -
perm_addr: Permanent hw address -
addr_assign_type: Hw address assignment type -
addr_len: Hardware address length -
upper_level: Maximum depth level of upper devices. -
lower_level: Maximum depth level of lower devices. -
threaded: napi threaded state. -
neigh_priv_len: Used inneigh_alloc() -
dev_id: Used to differentiate devices that share the same link layer address -
dev_port: Used to differentiate devices that share the same function -
irq: Device IRQ number -
priv_len: Size of the ->priv flexible array -
addr_list_lock: XXX: need comments on this one -
uc: unicast mac addresses -
mc: multicast mac addresses -
dev_addrs: list of device hw addresses -
queues_kset: Group of all Kobjects in the Tx and RX queues -
unlink_list: Asnetif_addr_lock()can be called recursively, keep a list of interfaces to be deleted. -
promiscuity: Number of times the NIC is told to work in promiscuous mode; if it becomes 0 the NIC will exit promiscuous mode -
allmulti: Counter, enables or disables allmulticast mode -
uc_promisc: Counter that indicates promiscuous mode has been enabled due to the need to listen to additional unicast addresses in a device that does not implementndo_set_rx_mode() -
nested_level: Used as a parameter ofspin_lock_nested()of dev->addr_list_lock. -
ip_ptr: IPv4 specific data -
fib_nh_head: nexthops associated with this netdev -
vlan_info: VLAN info -
dsa_ptr: dsa specific data -
tipc_ptr: TIPC specific data -
atalk_ptr: AppleTalk link -
ax25_ptr: AX.25 specific data -
ieee80211_ptr: IEEE 802.11 specific data, assign before registering -
ieee802154_ptr: IEEE 802.15.4 low-rate Wireless Personal Area Network device struct -
mpls_ptr: mpls_dev struct pointer -
mctp_ptr: MCTP specific data -
psp_dev: PSP crypto device registered for this netdev -
dev_addr: Hw address (before bcast, because most packets are unicast) -
num_rx_queues: Number of RX queues allocated atregister_netdev()time -
xdp_zc_max_segs: Maximum number of segments supported by AF_XDP zero copy driver -
ingress_queue: XXX: need comments on this one -
nf_hooks_ingress: netfilter hooks executed for ingress packets -
broadcast: hw bcast address -
rx_cpu_rmap: CPU reverse-mapping for RX completion interrupts, indexed by RX queue number. Assigned by driver. This must only be set if the ndo_rx_flow_steer operation is defined -
index_hlist: Device index hash chain -
num_tx_queues: Number of TX queues allocated atalloc_netdev_mq()time -
qdisc: Root qdisc from userspace point of view -
tx_queue_len: Max frames per queue allowed -
tx_global_lock: XXX: need comments on this one -
xdp_bulkq: XDP device bulk queue -
qdisc_hash: qdisc hash table -
watchdog_timer: List of timers -
watchdog_timeo: Represents the timeout that is used by the watchdog (seedev_watchdog()) -
proto_down_reason: reason a netdev interface is held down -
todo_list: Delayed register/unregister -
pcpu_refcnt: Number of references to this device -
dev_refcnt: Number of references to this device -
refcnt_tracker: Tracker directory for tracked references to this device -
link_watch_list: XXX: need comments on this one -
reg_state: Register/unregister state machine -
dismantle: Device is going to be freed -
moving_ns: device is changing netns, protected by lock -
rtnl_link_initializing: Device being created, suppress events -
needs_free_netdev: Should unregister perform free_netdev? -
priv_destructor: Called from unregister -
ml_priv: Mid-layer private -
ml_priv_type: Mid-layer private type -
garp_port: GARP -
mrp_port: MRP -
dm_private: Drop monitor private -
dev: Class/net/name entry -
sysfs_groups: Space for optional device, statistics and wireless sysfs groups -
sysfs_rx_queue_group: Space for optional per-rx queue attributes -
rtnl_link_ops: Rtnl_link_ops -
stat_ops: Optional ops for queue-aware statistics -
queue_mgmt_ops: Optional ops for queue management -
tso_max_size: Device (as in HW) limit on the max TSO request size -
tso_max_segs: Device (as in HW) limit on the max TSO segment count -
dcbnl_ops: Data Center Bridging netlink ops -
prio_tc_map: XXX: need comments on this one -
fcoe_ddp_xid: Max exchange id for FCoE LRO by ddp -
priomap: XXX: need comments on this one -
link_topo: Physical link topology tracking attached PHYs -
phydev: Physical device may attach itself for hardware timestamping -
sfp_bus: attachedstruct sfp_busstructure. -
qdisc_tx_busylock: lockdep class annotating Qdisc->busylock spinlock -
proto_down: protocol port state information can be sent to the switch driver and used to set the phys state of the switch port. -
irq_affinity_auto: driver wants the core to store and re-assign the IRQ affinity. Set bynetif_enable_irq_affinity(), then the driver must create a persistent napi bynetif_napi_add_config()and finally bind the napi to IRQ (vianetif_napi_set_irq()). -
rx_cpu_rmap_auto: driver wants the core to manage the ARFS rmap. Set by callingnetif_enable_cpu_rmap(). -
see_all_hwtstamp_requests: device wants to see calls tondo_hwtstamp_set()for all timestamp requests regardless of source, even if those aren't HWTSTAMP_SOURCE_NETDEV -
change_proto_down: device supports setting carrier via IFLA_PROTO_DOWN -
netns_immutable: interface can't change network namespaces -
fcoe_mtu: device supports maximum FCoE MTU, 2158 bytes -
net_notifier_list: List of per-net netdev notifier block that follow this device when it is moved to another network namespace. -
macsec_ops: MACsec offloading ops -
udp_tunnel_nic_info: static structure describing the UDP tunnel offload capabilities of the device -
udp_tunnel_nic: UDP tunnel offload state -
cfg: net_device queue-related configuration -
cfg_pending:-
same as cfg but when device is being actively
reconfigured includes any changes to the configuration requested by the user, but which may or may not be rejected.
-
-
ethtool: ethtool related state -
xdp_state: stores info on attached XDP BPF programs -
dev_addr_shadow: Copy of dev_addr to catch direct writes. -
linkwatch_dev_tracker: refcount tracker used by linkwatch. -
watchdog_dev_tracker: refcount tracker used by watchdog. -
dev_registered_tracker: tracker for reference held while registered -
offload_xstats_l3: L3 HW stats for this netdevice. -
devlink_port: Pointer to related devlink port structure. Assigned by a driver before netdev registration using SET_NETDEV_DEVLINK_PORT macro. This pointer is static during the time netdevice is registered. -
dpll_pin: Pointer to the SyncE source pin of a DPLL subsystem, where the clock is recovered. -
page_pools: page pools created for this netdevice -
irq_moder: dim parameters used if IS_ENABLED(CONFIG_DIMLIB). -
max_pacing_offload_horizon: max EDT offload horizon in nsec. -
napi_config: An array of napi_config structures containing per-NAPI settings. -
num_napi_configs: number of allocated NAPI config structs, always >= max(num_rx_queues, num_tx_queues). -
napi_defer_hard_irqs: If not zero, provides a counter that would allow to avoid NIC hard IRQ, on busy queues. -
gro_flush_timeout: timeout for GRO layer in NAPI -
up:-
copy of state's IFF_UP, but safe to read with just lock.
May report false negatives while the device is being opened or closed (lock does not protect .ndo_open, or .ndo_close).
-
-
request_ops_lock: request the core to run all netdev_ops and ethtool_ops under the lock. -
lock: netdev-scope lock, protects a small selection of fields. Should always be taken usingnetdev_lock()/netdev_unlock()helpers. Drivers are free to use it for other protection.For the drivers that implement shaper or queue API, the scope of this lock is expanded to cover most ndo/queue/ethtool/sysfs operations. Drivers may opt-in to this behavior by setting request_ops_lock.
lock protection mixes with rtnl_lock in multiple ways, fields are either:
-
simply protected by the instance lock;
-
double protected - writers hold both locks, readers hold either;
-
ops protected - protected by the lock held around the NDOs and other callbacks, that is the instance lock on devices for which
netdev_need_ops_lock()returns true, otherwise by rtnl_lock; -
double ops protected - always protected by rtnl_lock but for devices for which
netdev_need_ops_lock()returns true - also the instance lock.
Simply protects: gro_flush_timeout, napi_defer_hard_irqs, napi_list, net_shaper_hierarchy, reg_state, threaded
-
Double protects: up, moving_ns, nd_net, xdp_features
-
Double ops protects: real_num_rx_queues, real_num_tx_queues
-
Also protects some fields in: struct napi_struct, struct netdev_queue, struct netdev_rx_queue
Ordering: take after rtnl_lock.
-
-
net_shaper_hierarchy:-
data tracking the current shaper status
see include/net/net_shapers.h
-
-
neighbours: List heads pointing to this device's neighbours' dev_list, one per address-family. -
hwprov: Tracks which PTP performs hardware packet time stamping. -
priv: Flexible array containing private data
Description
Actually, this whole structure is a big mistake. It mixes I/O data with strictly "high-level" data, and it has to know about almost every data structure used in the INET module.
interface address info:
FIXME: cleanup struct net_device such that network protocol info moves out.
netdev_priv() #
void * access network device private data
Parameters
const struct net_device *dev: network device
Description
Get network device private data
netif_napi_add() #
void initialize a NAPI context
Parameters
struct net_device *dev: network devicestruct napi_struct *napi: NAPI contextint (*poll)(struct napi_struct *, int): polling function
Description
netif_napi_add() must be used to initialize a NAPI context prior to calling
any of the other NAPI-related functions.
netif_napi_add_config() #
void initialize a NAPI context with persistent config
Parameters
struct net_device *dev: network devicestruct napi_struct *napi: NAPI contextint (*poll)(struct napi_struct *, int): polling functionint index: the NAPI index
netif_napi_add_tx() #
void initialize a NAPI context to be used for Tx only
Parameters
struct net_device *dev: network devicestruct napi_struct *napi: NAPI contextint (*poll)(struct napi_struct *, int): polling function
Description
This variant of netif_napi_add() should be used from drivers using NAPI
to exclusively poll a TX queue.
This will avoid we add it into napi_hash[], thus polluting this hash table.
__netif_napi_del() #
void remove a NAPI context
Parameters
struct napi_struct *napi: NAPI context
Description
Warning: caller must observe RCU grace period before freeing memory containing napi. Drivers might want to call this helper to combine all the needed RCU grace periods into a single one.
netif_napi_del() #
void remove a NAPI context
Parameters
struct napi_struct *napi: NAPI context
Description
netif_napi_del() removes a NAPI context from the network device NAPI list
netif_start_queue() #
void allow transmit
Parameters
struct net_device *dev: network device
Description
Allow upper layers to call the device hard_start_xmit routine.
netif_wake_queue() #
void restart transmit
Parameters
struct net_device *dev: network device
Description
Allow upper layers to call the device hard_start_xmit routine. Used for flow control when transmit resources are available.
netif_stop_queue() #
void stop transmitted packets
Parameters
struct net_device *dev: network device
Description
Stop upper layers calling the device hard_start_xmit routine. Used for flow control when transmit resources are unavailable.
netif_queue_stopped() #
bool test if transmit queue is flowblocked
Parameters
const struct net_device *dev: network device
Description
Test if transmit queue on device is currently unable to send.
netdev_queue_set_dql_min_limit() #
void set dql minimum limit
Parameters
struct netdev_queue *dev_queue: pointer to transmit queueunsigned int min_limit: dql minimum limit
Description
Forces xmit_more() to return true until the minimum threshold
defined by min_limit is reached (or until the tx queue is
empty). Warning: to be use with care, misuse will impact the
latency.
netdev_txq_bql_enqueue_prefetchw() #
void prefetch bql data for write
Parameters
struct netdev_queue *dev_queue: pointer to transmit queue
Description
BQL enabled drivers might use this helper in their ndo_start_xmit(),
to give appropriate hint to the CPU.
netdev_txq_bql_complete_prefetchw() #
void prefetch bql data for write
Parameters
struct netdev_queue *dev_queue: pointer to transmit queue
Description
BQL enabled drivers might use this helper in their TX completion path, to give appropriate hint to the CPU.
netdev_tx_sent_queue() #
void report the number of bytes queued to a given tx queue
Parameters
struct netdev_queue *dev_queue: network device queueunsigned int bytes: number of bytes queued to the device queue
Description
Report the number of bytes queued for sending/completion to the network
device hardware queue. bytes should be a good approximation and should
exactly match netdev_completed_queue() bytes.
This is typically called once per packet, from ndo_start_xmit().
netdev_sent_queue() #
void report the number of bytes queued to hardware
Parameters
struct net_device *dev: network deviceunsigned int bytes: number of bytes queued to the hardware device queue
Description
Report the number of bytes queued for sending/completion to the network
device hardware queue#0. bytes should be a good approximation and should
exactly match netdev_completed_queue() bytes.
This is typically called once per packet, from ndo_start_xmit().
netdev_tx_completed_queue() #
void report number of packets/bytes at TX completion.
Parameters
struct netdev_queue *dev_queue: network device queueunsigned int pkts: number of packets (currently ignored)unsigned int bytes: number of bytes dequeued from the device queue
Description
Must be called at most once per TX completion round (and not per individual packet), so that BQL can adjust its limits appropriately.
netdev_completed_queue() #
void report bytes and packets completed by device
Parameters
struct net_device *dev: network deviceunsigned int pkts: actual number of packets sent over the mediumunsigned int bytes: actual number of bytes sent over the medium
Description
Report the number of bytes and packets transmitted by the network device
hardware queue over the physical medium, bytes must exactly match the
bytes amount passed to netdev_sent_queue()
netdev_tx_reset_subqueue() #
void reset the BQL stats and state of a netdev queue
Parameters
const struct net_device *dev: network deviceu32 qid: stack index of the queue to reset
netdev_reset_queue() #
void reset the packets and bytes count of a network device
Parameters
struct net_device *dev_queue: network device
Description
Reset the bytes and packet count of a network device and clear the software flow control OFF bit for this network device
netdev_cap_txqueue() #
u16 check if selected tx queue exceeds device queues
Parameters
struct net_device *dev: network deviceu16 queue_index: given tx queue index
Description
Returns 0 if given tx queue index >= number of device tx queues, otherwise returns the originally passed tx queue index.
netif_running() #
bool test if up
Parameters
const struct net_device *dev: network device
Description
Test if the device has been brought up.
netif_start_subqueue() #
void allow sending packets on subqueue
Parameters
struct net_device *dev: network deviceu16 queue_index: sub queue index
Description
Start individual transmit queue of a device with multiple transmit queues.
netif_stop_subqueue() #
void stop sending packets on subqueue
Parameters
struct net_device *dev: network deviceu16 queue_index: sub queue index
Description
Stop individual transmit queue of a device with multiple transmit queues.
__netif_subqueue_stopped() #
bool test status of subqueue
Parameters
const struct net_device *dev: network deviceu16 queue_index: sub queue index
Description
Check individual transmit queue of a device with multiple transmit queues.
netif_subqueue_stopped() #
bool test status of subqueue
Parameters
const struct net_device *dev: network devicestruct sk_buff *skb: sub queue buffer pointer
Description
Check individual transmit queue of a device with multiple transmit queues.
netif_wake_subqueue() #
void allow sending packets on subqueue
Parameters
struct net_device *dev: network deviceu16 queue_index: sub queue index
Description
Resume individual transmit queue of a device with multiple transmit queues.
netif_attr_test_mask() #
bool Test a CPU or Rx queue set in a mask
Parameters
unsigned long j: CPU/Rx queue indexconst unsigned long *mask: bitmask of all cpus/rx queuesunsigned int nr_bits: number of bits in the bitmask
Description
Test if a CPU or Rx queue index is set in a mask of all CPU/Rx queues.
netif_attr_test_online() #
bool Test for online CPU/Rx queue
Parameters
unsigned long j: CPU/Rx queue indexconst unsigned long *online_mask: bitmask for CPUs/Rx queues that are onlineunsigned int nr_bits: number of bits in the bitmask
Return
true if a CPU/Rx queue is online.
netif_attrmask_next() #
unsigned int get the next CPU/Rx queue in a cpu/Rx queues mask
Parameters
int n: CPU/Rx queue indexconst unsigned long *srcp: the cpumask/Rx queue mask pointerunsigned int nr_bits: number of bits in the bitmask
Return
next (after n) CPU/Rx queue index in the mask; >= nr_bits if no further CPUs/Rx queues set.
netif_attrmask_next_and() #
int get the next CPU/Rx queue in *src1p & *src2p
Parameters
int n: CPU/Rx queue indexconst unsigned long *src1p: the first CPUs/Rx queues mask pointerconst unsigned long *src2p: the second CPUs/Rx queues mask pointerunsigned int nr_bits: number of bits in the bitmask
Return
next (after n) CPU/Rx queue index set in both masks; >= nr_bits if no further CPUs/Rx queues set in both.
netif_is_multiqueue() #
bool test if device has multiple transmit queues
Parameters
const struct net_device *dev: network device
Description
Check if device has multiple transmit queues
dev_hold() #
void get reference to device
Parameters
struct net_device *dev: network device
Description
Hold reference to device to keep it from being freed.
Try using netdev_hold() instead.
dev_put() #
void release reference to device
Parameters
struct net_device *dev: network device
Description
Release reference to device to allow it to be freed.
Try using netdev_put() instead.
linkwatch_sync_dev() #
void sync linkwatch for the given device
Parameters
struct net_device *dev: network device to sync linkwatch for
Description
Sync linkwatch for the given device, removing it from the pending work list (if queued).
netif_carrier_ok() #
bool test if carrier present
Parameters
const struct net_device *dev: network device
Description
Check if carrier is present on device
netif_dormant_on() #
void mark device as dormant.
Parameters
struct net_device *dev: network device
Description
Mark device as dormant (as per RFC2863).
The dormant state indicates that the relevant interface is not actually in a condition to pass packets (i.e., it is not 'up') but is in a "pending" state, waiting for some external event. For "on- demand" interfaces, this new state identifies the situation where the interface is waiting for events to place it in the up state.
netif_dormant_off() #
void set device as not dormant.
Parameters
struct net_device *dev: network device
Description
Device is not in dormant state.
netif_dormant() #
bool test if device is dormant
Parameters
const struct net_device *dev: network device
Description
Check if device is dormant.
netif_testing_on() #
void mark device as under test.
Parameters
struct net_device *dev: network device
Description
Mark device as under test (as per RFC2863).
The testing state indicates that some test(s) must be performed on the interface. After completion, of the test, the interface state will change to up, dormant, or down, as appropriate.
netif_testing_off() #
void set device as not under test.
Parameters
struct net_device *dev: network device
Description
Device is not in testing state.
netif_testing() #
bool test if device is under test
Parameters
const struct net_device *dev: network device
Description
Check if device is under test
netif_oper_up() #
bool test if device is operational
Parameters
const struct net_device *dev: network device
Description
Check if carrier is operational
netif_device_present() #
bool is device available or removed
Parameters
const struct net_device *dev: network device
Description
Check if device has not been removed from system.
netif_tx_lock() #
void grab network device transmit lock
Parameters
struct net_device *dev: network device
Description
Get network device transmit lock
__dev_uc_sync() #
int Synchronize device's unicast list
Parameters
struct net_device *dev: device to syncint (*sync)(struct net_device *, const unsigned char *): function to call if address should be addedint (*unsync)(struct net_device *, const unsigned char *): function to call if address should be removed
Description
Add newly added addresses to the interface, and release addresses that have been deleted.
__dev_uc_unsync() #
void Remove synchronized addresses from device
Parameters
struct net_device *dev: device to syncint (*unsync)(struct net_device *, const unsigned char *): function to call if address should be removed
Description
Remove all addresses that were added to the device by dev_uc_sync().
__dev_mc_sync() #
int Synchronize device's multicast list
Parameters
struct net_device *dev: device to syncint (*sync)(struct net_device *, const unsigned char *): function to call if address should be addedint (*unsync)(struct net_device *, const unsigned char *): function to call if address should be removed
Description
Add newly added addresses to the interface, and release addresses that have been deleted.
__dev_mc_unsync() #
void Remove synchronized addresses from device
Parameters
struct net_device *dev: device to syncint (*unsync)(struct net_device *, const unsigned char *): function to call if address should be removed
Description
Remove all addresses that were added to the device by dev_mc_sync().
struct net_shaper #
represents a shaping node on the NIC H/W zeroed field are considered not set.
Definition
;
Members
parent: Unique identifier for the shaper parent, usually impliedhandle: Unique identifier for this shapermetric: Specify if the rate limits refers to PPS or BPSbw_min: Minimum guaranteed rate for this shaperbw_max: Maximum peak rate allowed for this shaperburst: Maximum burst for the peek rate of this shaperpriority: Scheduling priority for this shaperweight: Scheduling weight for this shaper
struct net_shaper_ops #
Operations on device H/W shapers
Definition
;
Members
-
group: create the specified shapers scheduling groupNest the leaves shapers identified under the * node shaper. All the shapers belong to the device specified by binding. The leaves arrays size is specified by leaves_count. Create either the leaves and the node shaper; or if they already exists, links them together in the desired way. leaves scope must be NET_SHAPER_SCOPE_QUEUE.
-
set: Updates the specified shaperUpdates or creates the shaper on the device specified by binding.
-
delete: Removes the specified shaperRemoves the shaper configuration as identified by the given handle on the device specified by binding, restoring the default behavior.
-
capabilities: get the shaper features supported by the deviceFills the bitmask cap with the supported capabilities for the specified scope and device specified by binding.
Description
The operations applies to either net_device and devlink objects. The initial shaping configuration at device initialization is empty: does not constraint the rate in any way. The network core keeps track of the applied user-configuration in the net_device or devlink structure. The operations are serialized via a per device lock.
Device not supporting any kind of nesting should not provide the group operation.
Each shaper is uniquely identified within the device with a 'handle' comprising the shaper scope and a scope-specific id.
PHY Support #
phy_print_status() #
void Convenience function to print out the current phy status
Parameters
struct phy_device *phydev: the phy_device struct
phy_get_rate_matching() #
int determine if rate matching is supported
Parameters
struct phy_device *phydev: The phy device to return rate matching forphy_interface_t iface: The interface mode to use
Description
This determines the type of rate matching (if any) that phy supports
using iface. iface may be PHY_INTERFACE_MODE_NA to determine if any
interface supports rate matching.
Return
The type of rate matching phy supports for iface, or
RATE_MATCH_NONE.
phy_restart_aneg() #
int restart auto-negotiation
Parameters
struct phy_device *phydev: target phy_device struct
Description
Restart the autonegotiation on phydev. Returns >= 0 on success or negative errno on error.
phy_aneg_done() #
int return auto-negotiation status
Parameters
struct phy_device *phydev: target phy_device struct
Description
Return the auto-negotiation status from this phydev Returns > 0 on success or < 0 on error. 0 means that auto-negotiation is still pending.
phy_check_valid() #
bool check if there is a valid PHY setting which matches speed, duplex, and feature mask
Parameters
int speed: speed to matchint duplex: duplex to matchunsigned long *features: A mask of the valid settings
Description
Returns true if there is a valid setting, false otherwise.
phy_mii_ioctl() #
int generic PHY MII ioctl interface
Parameters
struct phy_device *phydev: the phy_device structstruct ifreq *ifr:struct ifreqfor socket ioctl'sint cmd: ioctl cmd to execute
Description
Note that this function is currently incompatible with the PHYCONTROL layer. It changes registers without regard to current state. Use at own risk.
phy_do_ioctl() #
int generic ndo_eth_ioctl implementation
Parameters
struct net_device *dev: the net_device structstruct ifreq *ifr:struct ifreqfor socket ioctl'sint cmd: ioctl cmd to execute
phy_do_ioctl_running() #
int generic ndo_eth_ioctl implementation but test first
Parameters
struct net_device *dev: the net_device structstruct ifreq *ifr:struct ifreqfor socket ioctl'sint cmd: ioctl cmd to execute
Description
Same as phy_do_ioctl, but ensures that net_device is running before handling the ioctl.
phy_trigger_machine() #
void Trigger the state machine to run now
Parameters
struct phy_device *phydev: the phy_device struct
phy_ethtool_get_strings() #
int Get the statistic counter names
Parameters
struct phy_device *phydev: the phy_device structu8 *data: Where to put the strings
phy_ethtool_get_sset_count() #
int Get the number of statistic counters
Parameters
struct phy_device *phydev: the phy_device struct
phy_ethtool_get_stats() #
int Get the statistic counters
Parameters
struct phy_device *phydev: the phy_device structstruct ethtool_stats *stats: What counters to getu64 *data: Where to store the counters
phy_start_cable_test() #
int Start a cable test
Parameters
struct phy_device *phydev: the phy_device structstruct netlink_ext_ack *extack: extack for reporting useful error messages
phy_start_cable_test_tdr() #
int Start a raw TDR cable test
Parameters
struct phy_device *phydev: the phy_device structstruct netlink_ext_ack *extack: extack for reporting useful error messagesconst struct phy_tdr_config *config: Configuration of the test to run
phy_inband_caps() #
unsigned int query which in-band signalling modes are supported
Parameters
struct phy_device *phydev: a pointer to astruct phy_devicephy_interface_t interface: the interface mode for the PHY
Description
Returns zero if it is unknown what in-band signalling is supported by the
PHY (e.g. because the PHY driver doesn't implement the method.) Otherwise,
returns a bit mask of the LINK_INBAND_* values from
enum link_inband_signalling to describe which inband modes are supported
by the PHY for this interface mode.
phy_config_inband() #
int configure the desired PHY in-band mode
Parameters
struct phy_device *phydev: the phy_device structunsigned int modes: in-band modes to configure
Description
-
disables, enables or enables-with-bypass in-band signalling
between the PHY and host system.
Return
zero on success, or negative errno value.
_phy_start_aneg() #
int start auto-negotiation for this PHY device
Parameters
struct phy_device *phydev: the phy_device struct
Description
-
Sanitizes the settings (if we're not autonegotiating
them), and then calls the driver's config_aneg function. If the PHYCONTROL Layer is operating, we change the state to reflect the beginning of Auto-negotiation or forcing.
phy_start_aneg() #
int start auto-negotiation for this PHY device
Parameters
struct phy_device *phydev: the phy_device struct
Description
-
Sanitizes the settings (if we're not autonegotiating
them), and then calls the driver's config_aneg function. If the PHYCONTROL Layer is operating, we change the state to reflect the beginning of Auto-negotiation or forcing.
phy_speed_down() #
int set speed to lowest speed supported by both link partners
Parameters
struct phy_device *phydev: the phy_device structbool sync: perform action synchronously
Description
Typically used to save energy when waiting for a WoL packet
WARNING: Setting sync to false may cause the system being unable to suspend in case the PHY generates an interrupt when finishing the autonegotiation. This interrupt may wake up the system immediately after suspend. Therefore use sync = false only if you're sure it's safe with the respective network chip.
phy_speed_up() #
int (re)set advertised speeds to all supported speeds
Parameters
struct phy_device *phydev: the phy_device struct
Description
Used to revert the effect of phy_speed_down
phy_start_machine() #
void start PHY state machine tracking
Parameters
struct phy_device *phydev: the phy_device struct
Description
-
The PHY infrastructure can run a state machine
which tracks whether the PHY is starting up, negotiating, etc. This function starts the delayed workqueue which tracks the state of the PHY. If you want to maintain your own state machine, do not call this function.
phy_error() #
void enter ERROR state for this PHY device
Parameters
struct phy_device *phydev: target phy_device struct
Description
Moves the PHY to the ERROR state in response to a read or write error, and tells the controller the link is down. Must be called with phydev->lock held.
phy_request_interrupt() #
void request and enable interrupt for a PHY device
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Request and enable the interrupt for the given PHY.
If this fails, then we set irq to PHY_POLL. This should only be called with a valid IRQ number.
phy_free_interrupt() #
void disable and free interrupt for a PHY device
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Disable and free the interrupt for the given PHY.
This should only be called with a valid IRQ number.
phy_stop() #
void Bring down the PHY link, and stop checking the status
Parameters
struct phy_device *phydev: target phy_device struct
phy_start() #
void start or restart a PHY device
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Indicates the attached device's readiness to
handle PHY-related work. Used during startup to start the PHY, and after a call to
phy_stop()to resume operation. Also used to indicate the MDIO bus has cleared an error condition.
phy_mac_interrupt() #
void MAC says the link has changed
Parameters
struct phy_device *phydev: phy_device struct with changed link
Description
The MAC layer is able to indicate there has been a change in the PHY link status. Trigger the state machine and work a work queue.
phy_loopback() #
int Configure loopback mode of PHY
Parameters
struct phy_device *phydev: target phy_device structbool enable: enable or disable loopback modeint speed: enable loopback mode with speed
Description
Configure loopback mode of PHY and signal link down and link up if speed is changing.
Return
0 on success, negative error code on failure.
phy_eee_tx_clock_stop_capable() #
int indicate whether the MAC can stop tx clock
Parameters
struct phy_device *phydev: target phy_device struct
Description
Indicate whether the MAC can disable the transmit xMII clock while in LPI state. Returns 1 if the MAC may stop the transmit clock, 0 if the MAC must not stop the transmit clock, or negative error.
phy_eee_rx_clock_stop() #
int configure PHY receive clock in LPI
Parameters
struct phy_device *phydev: target phy_device structbool clk_stop_enable: flag to indicate whether the clock can be stopped
Description
Configure whether the PHY can disable its receive clock during LPI mode, See IEEE 802.3 sections 22.2.2.2, 35.2.2.10, and 45.2.3.1.4.
Return
0 or negative error.
phy_init_eee() #
int init and check the EEE feature
Parameters
struct phy_device *phydev: target phy_device structbool clk_stop_enable: PHY may stop the clock during LPI
Description
it checks if the Energy-Efficient Ethernet (EEE) is supported by looking at the MMD registers 3.20 and 7.60/61 and it programs the MMD register 3.0 setting the "Clock stop enable" bit if required.
phy_get_eee_err() #
int report the EEE wake error count
Parameters
struct phy_device *phydev: target phy_device struct
Description
it is to report the number of time where the PHY failed to complete its normal wake sequence.
phy_ethtool_get_eee() #
int get EEE supported and status
Parameters
struct phy_device *phydev: target phy_device structstruct ethtool_keee *data: ethtool_keee data
Description
get the current EEE settings, filling in all members of data.
phy_ethtool_set_eee() #
int set EEE supported and status
Parameters
struct phy_device *phydev: target phy_device structstruct ethtool_keee *data: ethtool_keee data
Description
it is to program the Advertisement EEE register.
phy_ethtool_set_wol() #
int Configure Wake On LAN
Parameters
struct phy_device *phydev: target phy_device structstruct ethtool_wolinfo *wol: Configuration requested
phy_ethtool_get_wol() #
void Get the current Wake On LAN configuration
Parameters
struct phy_device *phydev: target phy_device structstruct ethtool_wolinfo *wol: Store the current configuration here
phy_ethtool_nway_reset() #
int Restart auto negotiation
Parameters
struct net_device *ndev: Network device to restart autoneg for
phy_config_interrupt() #
int configure the PHY device for the requested interrupts
Parameters
struct phy_device *phydev: the phy_device structbool interrupts: interrupt flags to configure for this phydev
Description
Returns 0 on success or < 0 on error.
phy_supported_speeds() #
unsigned int return all speeds currently supported by a phy device
Parameters
struct phy_device *phy: The phy device to return supported speeds of.unsigned int *speeds: buffer to store supported speeds in.unsigned int size: size of speeds buffer.
Description
Returns the number of supported speeds, and fills the speeds buffer with the supported speeds. If speeds buffer is too small to contain all currently supported speeds, will return as many speeds as can fit.
phy_sanitize_settings() #
void make sure the PHY is set to supported speed and duplex
Parameters
struct phy_device *phydev: the target phy_device struct
Description
-
Make sure the PHY is set to supported speeds and
duplexes. Drop down by one in this order: 1000/FULL, 1000/HALF, 100/FULL, 100/HALF, 10/FULL, 10/HALF.
__phy_hwtstamp_get() #
int Get hardware timestamping configuration from PHY
Parameters
struct phy_device *phydev: the PHY device structurestruct kernel_hwtstamp_config *config: structure holding the timestamping configuration
Description
Query the PHY device for its current hardware timestamping configuration.
__phy_hwtstamp_set() #
int Modify PHY hardware timestamping configuration
Parameters
struct phy_device *phydev: the PHY device structurestruct kernel_hwtstamp_config *config: structure holding the timestamping configurationstruct netlink_ext_ack *extack: netlink extended ack structure, for error reporting
phy_queue_state_machine() #
void Trigger the state machine to run soon
Parameters
struct phy_device *phydev: the phy_device structunsigned long jiffies: Run the state machine after these jiffies
__phy_ethtool_get_phy_stats() #
void Retrieve standardized PHY statistics
Parameters
struct phy_device *phydev: Pointer to the PHY devicestruct ethtool_eth_phy_stats *phy_stats: Pointer to ethtool_eth_phy_stats structurestruct ethtool_phy_stats *phydev_stats: Pointer to ethtool_phy_stats structure
Description
Fetches PHY statistics using a kernel-defined interface for consistent
diagnostics. Unlike phy_ethtool_get_stats(), which allows custom stats,
this function enforces a standardized format for better interoperability.
__phy_ethtool_get_link_ext_stats() #
void Retrieve extended link statistics for a PHY
Parameters
struct phy_device *phydev: Pointer to the PHY devicestruct ethtool_link_ext_stats *link_stats: Pointer to the structure to store extended link statistics
Description
Populates the ethtool_link_ext_stats structure with link down event counts and additional driver-specific link statistics, if available.
phy_ethtool_get_plca_cfg() #
int Get PLCA RS configuration
Parameters
struct phy_device *phydev: the phy_device structstruct phy_plca_cfg *plca_cfg: where to store the retrieved configuration
Description
Retrieve the PLCA configuration from the PHY. Return 0 on success or a negative value if an error occurred.
plca_check_valid() #
int Check PLCA configuration before enabling
Parameters
struct phy_device *phydev: the phy_device structconst struct phy_plca_cfg *plca_cfg: current PLCA configurationstruct netlink_ext_ack *extack: extack for reporting useful error messages
Description
Checks whether the PLCA and PHY configuration are consistent and it is safe to enable PLCA. Returns 0 on success or a negative value if the PLCA or PHY configuration is not consistent.
phy_ethtool_set_plca_cfg() #
int Set PLCA RS configuration
Parameters
struct phy_device *phydev: the phy_device structconst struct phy_plca_cfg *plca_cfg: new PLCA configuration to applystruct netlink_ext_ack *extack: extack for reporting useful error messages
Description
Sets the PLCA configuration in the PHY. Return 0 on success or a negative value if an error occurred.
phy_ethtool_get_plca_status() #
int Get PLCA RS status information
Parameters
struct phy_device *phydev: the phy_device structstruct phy_plca_status *plca_st: where to store the retrieved status information
Description
Retrieve the PLCA status information from the PHY. Return 0 on success or a negative value if an error occurred.
phy_check_link_status() #
int check link status and set state accordingly
Parameters
struct phy_device *phydev: the phy_device struct
Description
Check for link and whether autoneg was triggered / is running and set state accordingly
phy_stop_machine() #
void stop the PHY state machine tracking
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Stops the state machine delayed workqueue, sets the
state to UP (unless it wasn't up yet). This function must be called BEFORE phy_detach.
phy_disable_interrupts() #
int Disable the PHY interrupts from the PHY side
Parameters
struct phy_device *phydev: target phy_device struct
phy_interrupt() #
irqreturn_t PHY interrupt handler
Parameters
int irq: interrupt linevoid *phy_dat: phy_device pointer
Description
Handle PHY interrupt
phy_enable_interrupts() #
int Enable the interrupts from the PHY side
Parameters
struct phy_device *phydev: target phy_device struct
phy_update_stats() #
int Update PHY device statistics if supported.
Parameters
struct phy_device *phydev: Pointer to the PHY device structure.
Description
If the PHY driver provides an update_stats callback, this function invokes it to update the PHY statistics. If not, it returns 0.
Return
0 on success, or a negative error code if the callback fails.
phy_get_next_update_time() #
unsigned int Determine the next PHY update time
Parameters
struct phy_device *phydev: Pointer to the phy_device structure
Description
This function queries the PHY driver to get the time for the next polling event. If the driver does not implement the callback, a default value is used.
Return
The time for the next polling event in jiffies
phy_state_machine() #
void Handle the state machine
Parameters
struct work_struct *work: work_struct that describes the work to be done
phy_ethtool_set_eee_noneg() #
void Adjusts MAC LPI configuration without PHY renegotiation
Parameters
struct phy_device *phydev: pointer to the target PHY device structureconst struct eee_config *old_cfg: pointer to the eee_config structure containing the old EEE settings
Description
This function updates the Energy Efficient Ethernet (EEE) configuration for cases where only the MAC's Low Power Idle (LPI) configuration changes, without triggering PHY renegotiation. It ensures that the MAC is properly informed of the new LPI settings by cycling the link down and up, which is necessary for the MAC to adopt the new configuration. This adjustment is done only if there is a change in the tx_lpi_enabled or tx_lpi_timer configuration.
phy_speed_to_str() #
const char * Return a string representing the PHY link speed
Parameters
int speed: Speed of the link
phy_duplex_to_str() #
const char * Return string describing the duplex
Parameters
unsigned int duplex: Duplex setting to describe
phy_rate_matching_to_str() #
const char * Return a string describing the rate matching
Parameters
int rate_matching: Type of rate matching to describe
phy_fix_phy_mode_for_mac_delays() #
phy_interface_t Convenience function for fixing PHY mode based on whether mac adds internal delay
Parameters
phy_interface_t interface: The current interface mode of the portbool mac_txid: True if the mac adds internal tx delaybool mac_rxid: True if the mac adds internal rx delay
Return
fixed PHY mode, or PHY_INTERFACE_MODE_NA if the interface can not apply the internal delay
phy_interface_num_ports() #
int Return the number of links that can be carried by a given MAC-PHY physical link. Returns 0 if this is unknown, the number of links else.
Parameters
phy_interface_t interface: The interface mode we want to get the number of ports
phy_set_max_speed() #
void Set the maximum speed the PHY should support
Parameters
struct phy_device *phydev: The phy_device structu32 max_speed: Maximum speed
Description
The PHY might be more capable than the MAC. For example a Fast Ethernet is connected to a 1G PHY. This function allows the MAC to indicate its maximum speed, and so limit what the PHY will advertise.
phy_resolve_aneg_pause() #
void Determine pause autoneg results
Parameters
struct phy_device *phydev: The phy_device struct
Description
Once autoneg has completed the local pause settings can be resolved. Determine if pause and asymmetric pause should be used by the MAC.
phy_resolve_aneg_linkmode() #
void resolve the advertisements into PHY settings
Parameters
struct phy_device *phydev: The phy_device struct
Description
Resolve our and the link partner advertisements into their corresponding speed and duplex. If full duplex was negotiated, extract the pause mode from the link partner mask.
__phy_read_mmd() #
int Convenience function for reading a register from an MMD on a given PHY.
Parameters
struct phy_device *phydev: The phy_device structint devad: The MMD to read from (0..31)u32 regnum: The register on the MMD to read (0..65535)
Description
Same rules as for __phy_read();
phy_read_mmd() #
int Convenience function for reading a register from an MMD on a given PHY.
Parameters
struct phy_device *phydev: The phy_device structint devad: The MMD to read fromu32 regnum: The register on the MMD to read
Description
Same rules as for phy_read();
__phy_write_mmd() #
int Convenience function for writing a register on an MMD on a given PHY.
Parameters
struct phy_device *phydev: The phy_device structint devad: The MMD to read fromu32 regnum: The register on the MMD to readu16 val: value to write to regnum
Description
Same rules as for __phy_write();
phy_write_mmd() #
int Convenience function for writing a register on an MMD on a given PHY.
Parameters
struct phy_device *phydev: The phy_device structint devad: The MMD to read fromu32 regnum: The register on the MMD to readu16 val: value to write to regnum
Description
Same rules as for phy_write();
phy_modify_changed() #
int Function for modifying a PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: new value of bits set in mask to write to regnum
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
Returns negative errno, 0 if there was no change, and 1 in case of change
__phy_modify() #
int Convenience function for modifying a PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: new value of bits set in mask to write to regnum
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
phy_modify() #
int Convenience function for modifying a given PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to writeu16 mask: bit mask of bits to clearu16 set: new value of bits set in mask to write to regnum
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
__phy_modify_mmd_changed() #
int Function for modifying a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: new value of bits set in mask to write to regnum
Description
Unlocked helper function which allows a MMD register to be modified as new register value = (old register value & ~mask) | set
Returns negative errno, 0 if there was no change, and 1 in case of change
phy_modify_mmd_changed() #
int Function for modifying a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: new value of bits set in mask to write to regnum
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
Returns negative errno, 0 if there was no change, and 1 in case of change
__phy_modify_mmd() #
int Convenience function for modifying a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: new value of bits set in mask to write to regnum
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
phy_modify_mmd() #
int Convenience function for modifying a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: new value of bits set in mask to write to regnum
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
phy_save_page() #
int take the bus lock and save the current page
Parameters
struct phy_device *phydev: a pointer to astruct phy_device
Description
Take the MDIO bus lock, and return the current page number. On error,
returns a negative errno. phy_restore_page() must always be called
after this, irrespective of success or failure of this call.
phy_select_page() #
int take the bus lock, save the current page, and set a page
Parameters
struct phy_device *phydev: a pointer to astruct phy_deviceint page: desired page
Description
Take the MDIO bus lock to protect against concurrent access, save the
current PHY page, and set the current page. On error, returns a
negative errno, otherwise returns the previous page number.
phy_restore_page() must always be called after this, irrespective
of success or failure of this call.
phy_restore_page() #
int restore the page register and release the bus lock
Parameters
struct phy_device *phydev: a pointer to astruct phy_deviceint oldpage: the old page, return value fromphy_save_page()orphy_select_page()int ret: operation's return code
Description
Release the MDIO bus lock, restoring oldpage if it is a valid page. This function propagates the earliest error code from the group of operations.
Return
oldpage if it was a negative value, otherwise
ret if it was a negative errno value, otherwise
phy_write_page()'s negative value if it were in error, otherwise
ret.
phy_read_paged() #
int Convenience function for reading a paged register
Parameters
struct phy_device *phydev: a pointer to astruct phy_deviceint page: the page for the phyu32 regnum: register number
Description
Same rules as for phy_read().
phy_write_paged() #
int Convenience function for writing a paged register
Parameters
struct phy_device *phydev: a pointer to astruct phy_deviceint page: the page for the phyu32 regnum: register numberu16 val: value to write
Description
Same rules as for phy_write().
phy_modify_paged_changed() #
int Function for modifying a paged register
Parameters
struct phy_device *phydev: a pointer to astruct phy_deviceint page: the page for the phyu32 regnum: register numberu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Description
Returns negative errno, 0 if there was no change, and 1 in case of change
phy_modify_paged() #
int Convenience function for modifying a paged register
Parameters
struct phy_device *phydev: a pointer to astruct phy_deviceint page: the page for the phyu32 regnum: register numberu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Description
Same rules as for phy_read() and phy_write().
genphy_c45_pma_resume() #
int wakes up the PMA module
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_pma_suspend() #
int suspends the PMA module
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_pma_baset1_setup_master_slave() #
int configures forced master/slave role of BaseT1 devices.
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_pma_setup_forced() #
int configures a forced speed
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_an_config_aneg() #
int configure advertisement registers
Parameters
struct phy_device *phydev: target phy_device struct
Description
Configure advertisement registers based on modes set in phydev->advertising
Returns negative errno code on failure, 0 if advertisement didn't change, or 1 if advertised modes changed.
genphy_c45_an_disable_aneg() #
int disable auto-negotiation
Parameters
struct phy_device *phydev: target phy_device struct
Description
Disable auto-negotiation in the Clause 45 PHY. The link parameters are controlled through the PMA/PMD MMD registers.
Returns zero on success, negative errno code on failure.
genphy_c45_restart_aneg() #
int Enable and restart auto-negotiation
Parameters
struct phy_device *phydev: target phy_device struct
Description
This assumes that the auto-negotiation MMD is present.
Enable and restart auto-negotiation.
genphy_c45_check_and_restart_aneg() #
int Enable and restart auto-negotiation
Parameters
struct phy_device *phydev: target phy_device structbool restart: whether aneg restart is requested
Description
This assumes that the auto-negotiation MMD is present.
Check, and restart auto-negotiation if needed.
genphy_c45_aneg_done() #
int return auto-negotiation complete status
Parameters
struct phy_device *phydev: target phy_device struct
Description
This assumes that the auto-negotiation MMD is present.
Reads the status register from the auto-negotiation MMD, returning:
- positive if auto-negotiation is complete
- negative errno code on error
- zero otherwise
genphy_c45_read_link() #
int read the overall link status from the MMDs
Parameters
struct phy_device *phydev: target phy_device struct
Description
Read the link status from the specified MMDs, and if they all indicate that the link is up, set phydev->link to 1. If an error is encountered, a negative errno will be returned, otherwise zero.
genphy_c45_read_lpa() #
int read the link partner advertisement and pause
Parameters
struct phy_device *phydev: target phy_device struct
Description
Read the Clause 45 defined base (7.19) and 10G (7.33) status registers, filling in the link partner advertisement, pause and asym_pause members in phydev. This assumes that the auto-negotiation MMD is present, and the backplane bit (7.48.0) is clear. Clause 45 PHY drivers are expected to fill in the remainder of the link partner advert from vendor registers.
genphy_c45_pma_baset1_read_master_slave() #
int read forced master/slave configuration
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_read_pma() #
int read link speed etc from PMA
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_read_mdix() #
int read mdix status from PMA
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_read_eee_abilities() #
int read supported EEE link modes
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_an_config_eee_aneg() #
int configure EEE advertisement
Parameters
struct phy_device *phydev: target phy_device struct
genphy_c45_pma_baset1_read_abilities() #
int read supported baset1 link modes from PMA
Parameters
struct phy_device *phydev: target phy_device struct
Description
Read the supported link modes from the extended BASE-T1 ability register
genphy_c45_pma_read_ext_abilities() #
int read supported link modes from PMA
Parameters
struct phy_device *phydev: target phy_device struct
Description
Read the supported link modes from the PMA/PMD extended ability register (Register 1.11).
genphy_c45_pma_read_abilities() #
int read supported link modes from PMA
Parameters
struct phy_device *phydev: target phy_device struct
Description
Read the supported link modes from the PMA Status 2 (1.8) register. If bit 1.8.9 is set, the list of supported modes is build using the values in the PMA Extended Abilities (1.11) register, indicating 1000BASET an 10G related modes. If bit 1.11.14 is set, then the list is also extended with the modes in the 2.5G/5G PMA Extended register (1.21), indicating if 2.5GBASET and 5GBASET are supported.
genphy_c45_read_status() #
int read PHY status
Parameters
struct phy_device *phydev: target phy_device struct
Description
Reads status from PHY and sets phy_device members accordingly.
genphy_c45_config_aneg() #
int restart auto-negotiation or forced setup
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
If auto-negotiation is enabled, we configure the
advertising, and then restart auto-negotiation. If it is not enabled, then we force a configuration.
genphy_c45_fast_retrain() #
int configure fast retrain registers
Parameters
struct phy_device *phydev: target phy_device structbool enable: enable fast retrain or not
Description
-
If fast-retrain is enabled, we configure PHY as
advertising fast retrain capable and THP Bypass Request, then enable fast retrain. If it is not enabled, we configure fast retrain disabled.
genphy_c45_plca_get_cfg() #
int get PLCA configuration from standard registers
Parameters
struct phy_device *phydev: target phy_device structstruct phy_plca_cfg *plca_cfg: output structure to store the PLCA configuration
Description
-
if the PHY complies to the Open Alliance TC14 10BASE-T1S PLCA
Management Registers specifications, this function can be used to retrieve the current PLCA configuration from the standard registers in MMD 31.
genphy_c45_plca_set_cfg() #
int set PLCA configuration using standard registers
Parameters
struct phy_device *phydev: target phy_device structconst struct phy_plca_cfg *plca_cfg: structure containing the PLCA configuration. Fields set to -1 are not to be changed.
Description
-
if the PHY complies to the Open Alliance TC14 10BASE-T1S PLCA
Management Registers specifications, this function can be used to modify the PLCA configuration using the standard registers in MMD 31.
genphy_c45_plca_get_status() #
int get PLCA status from standard registers
Parameters
struct phy_device *phydev: target phy_device structstruct phy_plca_status *plca_st: output structure to store the PLCA status
Description
-
if the PHY complies to the Open Alliance TC14 10BASE-T1S PLCA
Management Registers specifications, this function can be used to retrieve the current PLCA status information from the standard registers in MMD 31.
genphy_c45_eee_is_active() #
int get EEE status
Parameters
struct phy_device *phydev: target phy_device structunsigned long *lp: variable to store LP advertised linkmodes
Description
this function will read link partner PHY advertisement and compare it to local advertisement to return current EEE state.
genphy_c45_ethtool_get_eee() #
int get EEE supported and status
Parameters
struct phy_device *phydev: target phy_device structstruct ethtool_keee *data: ethtool_keee data
Description
it reports the Supported/Advertisement/LP Advertisement capabilities.
genphy_c45_ethtool_set_eee() #
int set EEE supported and status
Parameters
struct phy_device *phydev: target phy_device structstruct ethtool_keee *data: ethtool_keee data
Description
sets the Supported/Advertisement/LP Advertisement capabilities. If eee_enabled is false, no links modes are advertised, but the previously advertised link modes are retained. This allows EEE to be enabled/disabled in a non-destructive way. Returns either error code, 0 if there was no change, or positive value if there was a change which triggered auto-neg.
genphy_c45_oatc14_cable_test_get_status() #
int Get status of OATC14 10Base-T1S PHY cable test.
Parameters
struct phy_device *phydev: pointer to the PHY device structurebool *finished: pointer to a boolean set true if the test is complete
Description
Retrieves the current status of the OATC14 10Base-T1S PHY cable test. This function reads the OATC14 HDD register to determine whether the test results are valid and whether the test has finished.
If the test is complete, the function reports the cable test result via
the ethtool cable test interface using ethnl_cable_test_result(), and then
clears the test control bit in the PHY register to reset the test state.
Return
0 on success, or a negative error code on failure (e.g. register read/write error).
genphy_c45_oatc14_cable_test_start() #
int Start a cable test on an OATC14 10Base-T1S PHY.
Parameters
struct phy_device *phydev: Pointer to the PHY device structure
Description
This function initiates a cable diagnostic test on a Clause 45 OATC14 10Base-T1S capable PHY device. It first reads the PHY’s advanced diagnostic capability register to check if High Definition Diagnostics (HDD) mode is supported. If the PHY does not report HDD capability, cable testing is not supported and the function returns -EOPNOTSUPP.
For PHYs that support HDD, the function sets the appropriate control bits in the OATC14_HDD register to enable and start the cable diagnostic test.
Return
- 0 on success
- -EOPNOTSUPP if the PHY does not support HDD capability
- A negative error code on I/O or register access failures
genphy_c45_oatc14_get_sqi_max() #
int Get maximum supported SQI or SQI+ level of OATC14 10Base-T1S PHY
Parameters
struct phy_device *phydev: pointer to the PHY device structure
Description
This function returns the maximum supported Signal Quality Indicator (SQI) or SQI+ level. The SQI capability is updated on first invocation if it has not already been updated.
Return
- Maximum SQI/SQI+ level supported
- Negative errno on capability read failure
genphy_c45_oatc14_get_sqi() #
int Get Signal Quality Indicator (SQI) from an OATC14 10Base-T1S PHY
Parameters
struct phy_device *phydev: pointer to the PHY device structure
Description
This function reads the SQI+ or SQI value from an OATC14-compatible 10Base-T1S PHY. If SQI+ capability is supported, the function returns the extended SQI+ value; otherwise, it returns the basic SQI value. The SQI capability is updated on first invocation if it has not already been updated.
Return
- SQI/SQI+ value on success
- Negative errno on read failure
enum phy_interface_t #
Interface Mode definitions
Constants
PHY_INTERFACE_MODE_NA: Not Applicable - don't touchPHY_INTERFACE_MODE_INTERNAL: No interface, MAC and PHY combinedPHY_INTERFACE_MODE_MII: Media-independent interfacePHY_INTERFACE_MODE_GMII: Gigabit media-independent interfacePHY_INTERFACE_MODE_SGMII: Serial gigabit media-independent interfacePHY_INTERFACE_MODE_TBI: Ten Bit InterfacePHY_INTERFACE_MODE_REVMII: Reverse Media Independent InterfacePHY_INTERFACE_MODE_RMII: Reduced Media Independent InterfacePHY_INTERFACE_MODE_REVRMII: Reduced Media Independent Interface in PHY rolePHY_INTERFACE_MODE_RGMII: Reduced gigabit media-independent interfacePHY_INTERFACE_MODE_RGMII_ID: RGMII with Internal RX+TX delayPHY_INTERFACE_MODE_RGMII_RXID: RGMII with Internal RX delayPHY_INTERFACE_MODE_RGMII_TXID: RGMII with Internal TX delayPHY_INTERFACE_MODE_RTBI: Reduced TBIPHY_INTERFACE_MODE_SMII: Serial MIIPHY_INTERFACE_MODE_XGMII: 10 gigabit media-independent interfacePHY_INTERFACE_MODE_XLGMII: 40 gigabit media-independent interfacePHY_INTERFACE_MODE_MOCA: Multimedia over CoaxPHY_INTERFACE_MODE_PSGMII: Penta SGMIIPHY_INTERFACE_MODE_QSGMII: Quad SGMIIPHY_INTERFACE_MODE_TRGMII: Turbo RGMIIPHY_INTERFACE_MODE_100BASEX: 100 BaseXPHY_INTERFACE_MODE_1000BASEX: 1000 BaseXPHY_INTERFACE_MODE_2500BASEX: 2500 BaseXPHY_INTERFACE_MODE_5GBASER: 5G BaseRPHY_INTERFACE_MODE_RXAUI: Reduced XAUIPHY_INTERFACE_MODE_XAUI: 10 Gigabit Attachment Unit InterfacePHY_INTERFACE_MODE_10GBASER: 10G BaseRPHY_INTERFACE_MODE_25GBASER: 25G BaseRPHY_INTERFACE_MODE_USXGMII: Universal Serial 10GE MIIPHY_INTERFACE_MODE_10GKR: 10GBASE-KR - with Clause 73 ANPHY_INTERFACE_MODE_QUSGMII: Quad Universal SGMIIPHY_INTERFACE_MODE_1000BASEKX: 1000Base-KX - with Clause 73 ANPHY_INTERFACE_MODE_10G_QXGMII: 10G-QXGMII - 4 ports over 10G USXGMIIPHY_INTERFACE_MODE_50GBASER: 50GBase-R - with Clause 134 FECPHY_INTERFACE_MODE_LAUI: 50 Gigabit Attachment Unit InterfacePHY_INTERFACE_MODE_100GBASEP: 100GBase-P - with Clause 134 FECPHY_INTERFACE_MODE_MIILITE: MII-Lite - MII without RXER TXER CRS COLPHY_INTERFACE_MODE_MAX: Book keeping
Description
Describes the interface between the MAC and PHY.
phy_modes() #
const char * map phy_interface_t enum to device tree binding of phy-mode
Parameters
phy_interface_t interface: enum phy_interface_t value
Description
maps enum phy_interface_t defined in this file
into the device tree binding of 'phy-mode', so that Ethernet
device driver can get PHY interface from device tree.
rgmii_clock() #
long map link speed to the clock rate
Parameters
int speed: link speed value
Description
maps RGMII supported link speeds into the clock rates. This can also be used for MII, GMII, and RMII interface modes as the clock rates are identical, but the caller must be aware that errors for unsupported clock rates will not be signalled.
Return
clock rate or negative errno
struct mdio_bus_stats #
Statistics counters for MDIO busses
Definition
;
Members
transfers: Total number of transfers, i.e. writes + readserrors: Number of MDIO transfers that returned an errorwrites: Number of write transfersreads: Number of read transferssyncp: Synchronisation for incrementing statistics
struct mii_bus #
Represents an MDIO bus
Definition
;
Members
owner: Who owns this devicename: User friendly name for this MDIO device, or driver nameid: Unique identifier for this bus, typical from bus hierarchypriv: Driver private dataread: Perform a read transfer on the buswrite: Perform a write transfer on the busread_c45: Perform a C45 read transfer on the buswrite_c45: Perform a C45 write transfer on the busreset: Perform a reset of the busstats: Statistic counters per device on the busmdio_lock: A lock to ensure that only one thing can read/write the MDIO bus at a timeparent: Parent device of this busstate: State of bus structuredev: Kernel device representationmdio_map: list of all MDIO devices on busphy_mask: PHY addresses to be ignored when probingphy_ignore_ta_mask: PHY addresses to ignore the TA/read failureirq: An array of interrupts, each PHY's interrupt at the index matching its addressreset_delay_us: GPIO reset pulse width in microsecondsreset_post_delay_us: GPIO reset deassert delay in microsecondsreset_gpiod: Reset GPIO descriptor pointershared_lock: protect access to the shared elementshared: shared state across different PHYs
Description
The Bus class for PHYs. Devices which provide access to PHYs should register using this structure
mdiobus_alloc() #
struct mii_bus * Allocate an MDIO bus structure
Parameters
void: no arguments
Description
The internal state of the MDIO bus will be set of MDIOBUS_ALLOCATED ready for the driver to register the bus.
enum phy_state #
PHY state machine states:
Constants
PHY_DOWN: PHY device and driver are not ready for anything. probe should be called if and only if the PHY is in this state, given that the PHY device exists.- PHY driver probe function will set the state to PHY_READY
PHY_READY: PHY is ready to send and receive packets, but the controller is not. By default, PHYs which do not implement probe will be set to this state byphy_probe().- start will set the state to UP
PHY_HALTED: PHY is up, but no polling or interrupts are done.- phy_start moves to PHY_UP
PHY_ERROR: PHY is up, but is in an error state.- phy_stop moves to PHY_HALTED
PHY_UP: The PHY and attached device are ready to do work. Interrupts should be started here.- timer moves to PHY_NOLINK or PHY_RUNNING
PHY_RUNNING: PHY is currently up, running, and possibly sending and/or receiving packets- irq or timer will set PHY_NOLINK if link goes down
- phy_stop moves to PHY_HALTED
PHY_NOLINK: PHY is up, but not currently plugged in.- irq or timer will set PHY_RUNNING if link comes back
- phy_stop moves to PHY_HALTED
PHY_CABLETEST: PHY is performing a cable test. Packet reception/sending is not expected to work, carrier will be indicated as down. PHY will be poll once per second, or on interrupt for it current state. Once complete, move to UP to restart the PHY.- phy_stop aborts the running test and moves to PHY_HALTED
struct phy_c45_device_ids #
802.3-c45 Device Identifiers
Definition
;
Members
devices_in_package: IEEE 802.3 devices in package register value.mmds_present: bit vector of MMDs present.device_ids: The device identifier for each present device.
struct phy_oatc14_sqi_capability #
SQI capability information for OATC14 10Base-T1S PHY
Definition
;
Members
updated: Indicates whether the SQI capability fields have been updated.sqi_max: Maximum supported Signal Quality Indicator (SQI) level reported by the PHY.sqiplus_bits: Bits for SQI+ levels supported by the PHY. 0 - SQI+ is not supported 3 - SQI+ is supported, using 3 bits (8 levels) 4 - SQI+ is supported, using 4 bits (16 levels) 5 - SQI+ is supported, using 5 bits (32 levels) 6 - SQI+ is supported, using 6 bits (64 levels) 7 - SQI+ is supported, using 7 bits (128 levels) 8 - SQI+ is supported, using 8 bits (256 levels)
Description
This structure is used by the OATC14 10Base-T1S PHY driver to store the SQI and SQI+ capability information retrieved from the PHY.
struct phy_device #
An instance of a PHY
Definition
;
Members
mdio: MDIO bus this PHY is ondrv: Pointer to the driver for this PHY instancedevlink: Create a link between phy dev and mac dev, if the external phy used by current mac interface is managed by another mac interface.phyindex: Unique id across the phy's parent tree of phys to address the PHY from userspace, similar to ifindex. A zero index means the PHY wasn't assigned an id yet.phy_id: UID for this device found during discoveryc45_ids: 802.3-c45 Device Identifiers if is_c45.is_c45: Set to true if this PHY uses clause 45 addressing.is_internal: Set to true if this PHY is internal to a MAC.is_pseudo_fixed_link: Set to true if this PHY is an Ethernet switch, etc.is_gigabit_capable: Set to true if PHY supports 1000Mbpshas_fixups: Set to true if this PHY has fixups/quirks.suspended: Set to true if this PHY has been suspended successfully.suspended_by_mdio_bus: Set to true if this PHY was suspended by MDIO bus.sysfs_links: Internal boolean tracking sysfs symbolic links setup/removal.loopback_enabled: Set true if this PHY has been loopbacked successfully.downshifted_rate: Set true if link speed has been downshifted.is_on_sfp_module: Set true if PHY is located on an SFP module.mac_managed_pm: Set true if MAC driver takes of suspending/resuming PHYwol_enabled: Set to true if the PHY or the attached MAC have Wake-on-LAN enabled.is_genphy_driven: PHY is driven by one of the generic PHY driversautoneg: Flag autoneg being usedlink: Current link stateautoneg_complete: Flag auto negotiation of the link has completedpause: Current pauseasym_pause: Current asymmetric pauseinterrupts: Flag interrupts have been enabledirq_suspended: Flag indicating PHY is suspended and therefore interrupt handling shall be postponed until PHY has resumedirq_rerun: Flag indicating interrupts occurred while PHY was suspended, requiring a rerun of the interrupt handler after resumedefault_timestamp: Flag indicating whether we are using the phy timestamp as the default onerate_matching: Current rate matching modestate: State of the PHY for management purposesdev_flags: Device-specific flags used by the PHY driver.interface: enum phy_interface_t valuepossible_interfaces: bitmap if interface modes that the attached PHY will switch between depending on media speed.speed: Current link speedduplex: Current duplexport: Current portmaster_slave_get: Current master/slave advertisementmaster_slave_set: User requested master/slave configurationmaster_slave_state: Current master/slave configurationsupported: Combined MAC/PHY supported linkmodesadvertising: Currently advertised linkmodeslp_advertising: Current link partner advertised linkmodesadv_old: Saved advertised while power saving for WoLsupported_eee: supported PHY EEE linkmodesadvertising_eee: Currently advertised EEE linkmodeseee_disabled_modes: Energy efficient ethernet modes not to be advertisedenable_tx_lpi: When True, MAC should transmit LPI to PHYeee_active: phylib private state, indicating that EEE has been negotiatedeee_cfg: User configuration of EEEhost_interfaces: PHY interface modes supported by hostphy_led_triggers: Array of LED triggersphy_num_led_triggers: Number of triggers in phy_led_triggerslast_triggered: last LED trigger for link speedled_link_trigger: LED trigger for link up/downleds: list of PHY LED structuresirq: IRQ number of the PHY's interrupt (-1 if none)priv: Pointer to driver private datashared: Pointer to private data shared by phys in one packageskb: Netlink message for cable diagnosticsehdr: nNtlink header for cable diagnosticsnest: Netlink nest used for cable diagnosticsstate_queue: Work queue for state machinelock: Mutex for serialization access to PHYsfp_bus_attached: Flag indicating whether the SFP bus has been attachedsfp_bus: SFP bus attached to this PHY's fiber portphylink: Pointer to phylink instance for this PHYattached_dev: The attached enet driver's device instance ptrmii_ts: Pointer to time stamper callbackspsec: Pointer to Power Sourcing Equipment control structports: List of PHY ports structuresn_ports: Number of ports currently attached to the PHYmax_n_ports: Max number of ports this PHY can exposemdix: Current crossovermdix_ctrl: User setting of crossoverpma_extable: Cached value of PMA/PMD Extended Abilities Registerlink_down_events: Number of times link was lostphy_link_change: Callback for phylink for notification of link changeadjust_link: Callback for the enet controller to respond to changes: in the link state.macsec_ops: MACsec offloading ops.oatc14_sqi_capability: SQI capability information for OATC14 10Base-T1S PHY
Description
- Bits [15:0] are free to use by the PHY driver to communicate driver specific behavior.
- Bits [23:16] are currently reserved for future use.
- Bits [31:24] are reserved for defining generic PHY driver behavior.
interrupts currently only supports enabled or disabled, but could be changed in the future to support enabling and disabling specific interrupts
Contains some infrastructure for polling and interrupt handling, as well as handling shifts in PHY hardware state
struct phy_tdr_config #
Configuration of a TDR raw test
Definition
;
Members
first: Distance for first data collection pointlast: Distance for last data collection pointstep: Step between data collection pointspair: Bitmap of cable pairs to collect data for
Description
A structure containing possible configuration parameters for a TDR cable test. The driver does not need to implement all the parameters, but should report what is actually used. All distances are in centimeters.
enum link_inband_signalling #
in-band signalling modes that are supported
Constants
LINK_INBAND_DISABLE: in-band signalling can be disabledLINK_INBAND_ENABLE: in-band signalling can be enabled without bypassLINK_INBAND_BYPASS: in-band signalling can be enabled with bypass
Description
The possible and required bits can only be used if the valid bit is set. If possible is clear, that means inband signalling can not be used. Required is only valid when possible is set, and means that inband signalling must be used.
struct phy_plca_cfg #
Configuration of the PLCA (Physical Layer Collision Avoidance) Reconciliation Sublayer.
Definition
;
Members
version: read-only PLCA register map version. -1 = not available. Ignored when setting the configuration. Format is the same as reported by the PLCA IDVER register (31.CA00). -1 = not available.enabled: PLCA configured mode (enabled/disabled). -1 = not available / don't set. 0 = disabled, anything else = enabled.node_id: the PLCA local node identifier. -1 = not available / don't set. Allowed values [0 .. 254]. 255 = node disabled.node_cnt: the PLCA node count (maximum number of nodes having a TO). Only meaningful for the coordinator (node_id = 0). -1 = not available / don't set. Allowed values [1 .. 255].to_tmr: The value of the PLCA to_timer in bit-times, which determines the PLCA transmit opportunity window opening. See IEEE802.3 Clause 148 for more details. The to_timer shall be set equal over all nodes. -1 = not available / don't set. Allowed values [0 .. 255].burst_cnt: controls how many additional frames a node is allowed to send in single transmit opportunity (TO). The default value of 0 means that the node is allowed exactly one frame per TO. A value of 1 allows two frames per TO, and so on. -1 = not available / don't set. Allowed values [0 .. 255].burst_tmr: controls how many bit times to wait for the MAC to send a new frame before interrupting the burst. This value should be set to a value greater than the MAC inter-packet gap (which is typically 96 bits). -1 = not available / don't set. Allowed values [0 .. 255].
Description
A structure containing configuration parameters for setting/getting the PLCA RS configuration. The driver does not need to implement all the parameters, but should report what is actually used.
struct phy_plca_status #
Status of the PLCA (Physical Layer Collision Avoidance) Reconciliation Sublayer.
Definition
;
Members
pst: The PLCA status as reported by the PST bit in the PLCA STATUS register(31.CA03), indicating BEACON activity.
Description
A structure containing status information of the PLCA RS configuration. The driver does not need to implement all the parameters, but should report what is actually used.
struct phy_led #
An LED driven by the PHY
Definition
;
Members
list: List of LEDsphydev: PHY this LED is attached toled_cdev: Standard LED class structureindex: Number of the LED
struct phy_mse_capability #
Capabilities of Mean Square Error (MSE) measurement interface
Definition
;
Members
max_average_mse: The maximum value for an average MSE snapshot. This defines the scale for the measurement. If the PHY_MSE_CAP_AVG capability is supported, this value MUST be greater than 0. (vendor-specific units).max_peak_mse: The maximum value for a peak MSE snapshot. If either PHY_MSE_CAP_PEAK or PHY_MSE_CAP_WORST_PEAK is supported, this value MUST be greater than 0. (vendor-specific units).refresh_rate_ps: The typical interval, in picoseconds, between hardware updates of the MSE values. This is an estimate, and callers should not assume synchronous sampling. (vendor-specific units).num_symbols: The number of symbols aggregated per hardware sample to calculate the MSE. (vendor-specific units).supported_caps: A bitmask of PHY_MSE_CAP_* values indicating which measurement types (e.g., average, peak) and channels (e.g., per-pair or link-wide) are supported.
Description
Standardization notes:
-
Presence of MSE/SQI/pMSE is defined by OPEN Alliance specs, but numeric scaling, refresh/update rate and aggregation windows are not fixed and are vendor-/product-specific. (OA 100BASE-T1 TC1 v1.0 6.1.; OA 1000BASE-T1 TC12 v2.2 6.1.)
-
Typical recommendations: 2^16 symbols and 0..511 scaling for MSE; pMSE only defined for 100BASE-T1 (sliding window example), others are vendor extensions. Drivers must report actual scale/limits here.
Describes the MSE measurement capabilities for the current link mode. These properties are dynamic and may change when link settings are modified. Callers should re-query this capability after any link state change to ensure they have the most up-to-date information.
Callers should only request measurements for channels and types that are indicated as supported by the supported_caps bitmask. If supported_caps is 0, the device provides no MSE diagnostics, and driver operations should typically return -EOPNOTSUPP.
Snapshot values for average and peak MSE can be normalized to a 0..1 ratio by dividing the raw snapshot by the corresponding max_average_mse or max_peak_mse value.
struct phy_mse_snapshot #
A snapshot of Mean Square Error (MSE) diagnostics
Definition
;
Members
average_mse: The average MSE value over the measurement window. OPEN Alliance references MSE as a DCQ metric; recommends 2^16 symbols and 0..511 scaling. Exact scale and refresh are vendor-specific. (100BASE-T1 TC1 v1.0 6.1.1; 1000BASE-T1 TC12 v2.2 6.1.1).peak_mse: The peak MSE value observed within the measurement window. For 100BASE-T1, "pMSE" is optional and may be implemented via a sliding 128-symbol window with periodic capture; not standardized for 1000BASE-T1. (100BASE-T1 TC1 v1.0 6.1.3, Table "DCQ.peakMSE").worst_peak_mse: A latched high-water mark of the peak MSE since last read (read-to-clear if implemented). OPEN Alliance shows a latched "worst case peak MSE" for 100BASE-T1 pMSE; availability/semantics outside that are vendor-specific. (100BASE-T1 TC1 v1.0 6.1.3, DCQ.peakMSE high byte; 1000BASE-T1 TC12 v2.2 treats DCQ details as vendor-specific.)
Description
Holds a set of MSE diagnostic values that were all captured from a single measurement window.
Values are raw, device-scaled and not normalized. Use struct phy_mse_capability to interpret the scale and sampling window.
struct phy_driver #
Driver structure for a particular PHY type
Definition
;
Members
-
mdiodrv: Data common to all MDIO devices -
phy_id: The result of reading the UID registers of this PHY type, and ANDing them with the phy_id_mask. This driver only works for PHYs with IDs which match this field -
name: The friendly name of this PHY type -
phy_id_mask: Defines the important bits of the phy_id -
features: A mandatory list of features (speed, duplex, etc) supported by this PHY -
flags: A bitfield defining certain other features this PHY supports (like interrupts) -
driver_data: Static driver data -
soft_reset: Called to issue a PHY software reset -
config_init: Called to initialize the PHY, including after a reset -
probe: Called during discovery. Used to set up device-specific structures, if any -
get_features: Probe the hardware to determine what abilities it has. Should only set phydev->supported. -
inband_caps: query whether in-band is supported for the given PHY interface mode. Returns a bitmask of bits defined by enum link_inband_signalling. -
config_inband: configure in-band mode for the PHY -
get_rate_matching: Get the supported type of rate matching for a particular phy interface. This is used by phy consumers to determine whether to advertise lower-speed modes for that interface. It is assumed that if a rate matching mode is supported on an interface, then that interface's rate can be adapted to all slower link speeds supported by the phy. If the interface is not supported, this should returnRATE_MATCH_NONE. -
suspend: Suspend the hardware, saving state if needed -
resume: Resume the hardware, restoring state if needed -
config_aneg: Configures the advertisement and resets autonegotiation if phydev->autoneg is on, forces the speed to the current settings in phydev if phydev->autoneg is off -
aneg_done: Determines the auto negotiation result -
read_status: Determines the negotiated speed and duplex -
config_intr: Enables or disables interrupts. It should also clear any pending interrupts prior to enabling the IRQs and after disabling them. -
handle_interrupt: Override default interrupt handling -
remove: Clears up any memory if needed -
match_phy_device: Returns true if this is a suitable driver for the given phydev. If NULL, matching is based on phy_id and phy_id_mask. -
set_wol: Some devices (e.g. qnap TS-119P II) require PHY register changes to enable Wake on LAN, so set_wol is provided to be called in the ethernet driver's set_wol function. -
get_wol: See set_wol, but for checking whether Wake on LAN is enabled. -
link_change_notify: Called to inform a PHY device driver when the core is about to change the link state. This callback is supposed to be used as fixup hook for drivers that need to take action when the link state changes. Drivers are by no means allowed to mess with the PHY device structure in their implementations. -
read_mmd: PHY specific driver override for reading a MMD register. This function is optional for PHY specific drivers. When not provided, the default MMD read function will be used byphy_read_mmd(), which will use either a direct read for Clause 45 PHYs or an indirect read for Clause 22 PHYs. devnum is the MMD device number within the PHY device, regnum is the register within the selected MMD device. -
write_mmd: PHY specific driver override for writing a MMD register. This function is optional for PHY specific drivers. When not provided, the default MMD write function will be used byphy_write_mmd(), which will use either a direct write for Clause 45 PHYs, or an indirect write for Clause 22 PHYs. devnum is the MMD device number within the PHY device, regnum is the register within the selected MMD device. val is the value to be written. -
read_page: Return the current PHY register page number -
write_page: Set the current PHY register page number -
module_info: Get the size and type of the eeprom contained within a plug-in module -
module_eeprom: Get the eeprom information from the plug-in module -
cable_test_start: Start a cable test -
cable_test_tdr_start: Start a raw TDR cable test -
cable_test_get_status: Once per second, or on interrupt, request the status of the test. -
get_phy_stats: Retrieve PHY statistics. dev: The PHY device for which the statistics are retrieved. eth_stats: structure where Ethernet PHY stats will be stored. stats: structure where additional PHY-specific stats will be stored.Retrieves the supported PHY statistics and populates the provided structures. The input structures are pre-initialized with
ETHTOOL_STAT_NOT_SET, and the driver must only modify members corresponding to supported statistics. Unmodified members will remain set toETHTOOL_STAT_NOT_SETand will not be returned to userspace. -
get_link_stats: Retrieve link statistics. dev: The PHY device for which the statistics are retrieved. link_stats: structure where link-specific stats will be stored.Retrieves link-related statistics for the given PHY device. The input structure is pre-initialized with
ETHTOOL_STAT_NOT_SET, and the driver must only modify members corresponding to supported statistics. Unmodified members will remain set toETHTOOL_STAT_NOT_SETand will not be returned to userspace. -
update_stats: Trigger periodic statistics updates. dev: The PHY device for which statistics updates are triggered.Periodically gathers statistics from the PHY device to update locally maintained 64-bit counters. This is necessary for PHYs that implement reduced-width counters (e.g., 16-bit or 32-bit) which can overflow more frequently compared to 64-bit counters. By invoking this callback, drivers can fetch the current counter values, handle overflow detection, and accumulate the results into local 64-bit counters for accurate reporting through the
get_phy_statsandget_link_statsinterfaces.Return: 0 on success or a negative error code on failure.
-
get_sset_count: Number of statistic counters -
get_strings: Names of the statistic counters -
get_stats: Return the statistic counter values -
get_tunable: Return the value of a tunable -
set_tunable: Set the value of a tunable -
set_loopback: Set the loopback mode of the PHY enable selects if the loopback mode is enabled or disabled. If the loopback mode is enabled, then the speed of the loopback mode can be requested with the speed argument. If the speed argument is zero, then any speed can be selected. If the speed argument is > 0, then this speed shall be selected for the loopback mode or EOPNOTSUPP shall be returned if speed selection is not supported. -
get_sqi: Get the signal quality indication -
get_sqi_max: Get the maximum signal quality indication -
get_mse_capability: Get capabilities and scale of MSE measurement dev: PHY device cap: Output (filled on success)Fill cap with the PHY's MSE capability for the current link mode: scale limits (max_average_mse, max_peak_mse), update interval (refresh_rate_ps), sample length (num_symbols) and the capability bitmask (supported_caps).
Implementations may defer capability report until hardware has converged; in that case they should return -EAGAIN and allow the caller to retry later.
Return: 0 on success. On failure, returns a negative errno code, such as -EOPNOTSUPP if MSE measurement is not supported by the PHY or in the current link mode, or -EAGAIN if the capability information is not yet available.
-
get_mse_snapshot: Retrieve a snapshot of MSE diagnostic values dev: PHY device channel: Channel identifier (PHY_MSE_CHANNEL_*) snapshot: Output (filled on success)Fill snapshot with a correlated set of MSE values from the most recent measurement window.
Callers must validate channel against supported_caps returned by
get_mse_capability(). Drivers must not coerce channel; if the requested selector is not implemented by the device or current link mode, the operation must fail.worst_peak_mse is latched and must be treated as read-to-clear.
Return: 0 on success. On failure, returns a negative errno code, such as -EOPNOTSUPP if MSE measurement is not supported by the PHY or in the current link mode, or -EAGAIN if measurements are not yet available.
-
get_plca_cfg: Return the current PLCA configuration -
set_plca_cfg: Set the PLCA configuration -
get_plca_status: Return the current PLCA status info -
led_brightness_set: Set a PHY LED brightness. Index indicates which of the PHYs led should be set. Value follows the standard LED class meaning, e.g. LED_OFF, LED_HALF, LED_FULL. -
led_blink_set: Set a PHY LED blinking. Index indicates which of the PHYs led should be configured to blink. Delays are in milliseconds and if both are zero then a sensible default should be chosen. The call should adjust the timings in that case and if it can't match the values specified exactly. -
led_hw_is_supported: Can the HW support the given rules. dev: PHY device which has the LED index: Which LED of the PHY device rules The core is interested in these rulesReturn 0 if yes, -EOPNOTSUPP if not, or an error code.
-
led_hw_control_set: Set the HW to control the LED dev: PHY device which has the LED index: Which LED of the PHY device rules The rules used to control the LEDReturns 0, or a an error code.
-
led_hw_control_get: Get how the HW is controlling the LED dev: PHY device which has the LED index: Which LED of the PHY device rules Pointer to the rules used to control the LEDSet *rules to how the HW is currently blinking. Returns 0 on success, or a error code if the current blinking cannot be represented in rules, or some other error happens.
-
led_polarity_set: Set the LED polarity modes dev: PHY device which has the LED index: Which LED of the PHY device modes: bitmap of LED polarity modesConfigure LED with all the required polarity modes in modes to make it correctly turn ON or OFF.
Returns 0, or an error code.
-
get_next_update_time: Get the time until the next update event dev: PHY deviceCallback to determine the time (in jiffies) until the next update event for the PHY state machine. Allows PHY drivers to dynamically adjust polling intervals based on link state or other conditions.
Returns the time in jiffies until the next update event.
-
attach_mii_port: Attach the given MII port to the PHY device dev: PHY device to notify port: The port being addedCalled when an MII port that needs to be driven by the PHY is found.
The port that is being passed may or may not be initialized. If it is already initialized, it is by the generic port representation from devicetree, which superseeds any strapping or vendor-specific properties.
If the port isn't initialized, the port->mediums and port->lanes fields must be set, possibly according to strapping information.
The PHY driver must set the port->interfaces field to indicate the possible MII modes that this PHY can output on the port.
Returns 0, or an error code.
-
attach_mdi_port: Attach the given MII port to the PHY device dev: PHY device to notify port: The port being addedCalled when a port that needs to be driven by the PHY is found. The number of time this will be called depends on phydev->max_n_ports, which the driver can change in .
probe().The port that is being passed may or may not be initialized. If it is already initialized, it is by the generic port representation from devicetree, which superseeds any strapping or vendor-specific properties.
If the port isn't initialized, the port->mediums and port->lanes fields must be set, possibly according to strapping information.
Returns 0, or an error code.
Description
All functions are optional. If config_aneg or read_status are not implemented, the phy core uses the genphy versions. Note that none of these functions should be called from interrupt time. The goal is for the bus read/write functions to be able to block when the bus transaction is happening, and be freed up by an interrupt (The MPC85xx has this ability, though it is not currently supported in the driver).
phy_id_compare() #
bool compare id1 with id2 taking account of mask
Parameters
u32 id1: first PHY IDu32 id2: second PHY IDu32 mask: the PHY ID mask, set bits are significant in matching
Description
Return true if the bits from id1 and id2 specified by mask match. This uses an equivalent test to (id & mask) == (phy_id & mask).
phy_id_compare_vendor() #
bool compare id with vendor mask
Parameters
u32 id: PHY IDu32 vendor_mask: PHY Vendor mask
Return
true if the bits from id match vendor using the generic PHY Vendor mask.
phy_id_compare_model() #
bool compare id with model mask
Parameters
u32 id: PHY IDu32 model_mask: PHY Model mask
Return
true if the bits from id match model using the generic PHY Model mask.
phydev_id_compare() #
bool compare id with the PHY's Clause 22 ID
Parameters
struct phy_device *phydev: the PHY deviceu32 id: the PHY ID to be matched
Description
Compare the phydev clause 22 ID with the provided id and return true or false depending whether it matches, using the bound driver mask. The phydev must be bound to a driver.
phy_is_started() #
bool Convenience function to check whether PHY is started
Parameters
struct phy_device *phydev: The phy_device struct
phy_driver_is_genphy() #
bool Convenience function to check whether PHY is driven by one of the generic PHY drivers
Parameters
struct phy_device *phydev: The phy_device struct
Return
true if PHY is driven by one of the genphy drivers
phy_disable_eee_mode() #
void Don't advertise an EEE mode.
Parameters
struct phy_device *phydev: The phy_device structu32 link_mode: The EEE mode to be disabled
phy_can_wakeup() #
bool indicate whether PHY has driver model wakeup capabilities
Parameters
struct phy_device *phydev: The phy_device struct
Return
true/false depending on the PHY driver's device_set_wakeup_capable()
setting.
phy_may_wakeup() #
bool indicate whether PHY has wakeup enabled
Parameters
struct phy_device *phydev: The phy_device struct
Return
true/false depending on the PHY driver's device_set_wakeup_enabled()
setting if using the driver model, otherwise the legacy determination.
phy_read() #
int Convenience function for reading a given PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to read
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
__phy_read() #
int convenience function for reading a given PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to read
Description
The caller must have taken the MDIO bus lock.
phy_write() #
int Convenience function for writing a given PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to writeu16 val: value to write to regnum
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
__phy_write() #
int Convenience function for writing a given PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to writeu16 val: value to write to regnum
Description
The caller must have taken the MDIO bus lock.
__phy_modify_changed() #
int Convenience function for modifying a PHY register
Parameters
struct phy_device *phydev: a pointer to astruct phy_deviceu32 regnum: register numberu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Description
Unlocked helper function which allows a PHY register to be modified as new register value = (old register value & ~mask) | set
Returns negative errno, 0 if there was no change, and 1 in case of change
phy_read_mmd_poll_timeout() #
Periodically poll a PHY register until a condition is met or a timeout occurs
Parameters
phydev: The phy_device structdevaddr: The MMD to read fromregnum: The register on the MMD to readval: Variable to read the register intocond: Break condition (usually involving val)sleep_us: Maximum time to sleep between reads in us (0 tight-loops). Please readusleep_range()function description for details and limitations.timeout_us: Timeout in us, 0 means never timeoutsleep_before_read: if it is true, sleep sleep_us before read.
Return
0 on success and -ETIMEDOUT upon a timeout. In either case, the last read value at args is stored in val. Must not be called from atomic context if sleep_us or timeout_us are used.
__phy_set_bits() #
int Convenience function for setting bits in a PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to writeu16 val: bits to set
Description
The caller must have taken the MDIO bus lock.
__phy_clear_bits() #
int Convenience function for clearing bits in a PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to writeu16 val: bits to clear
Description
The caller must have taken the MDIO bus lock.
phy_set_bits() #
int Convenience function for setting bits in a PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to writeu16 val: bits to set
phy_clear_bits() #
int Convenience function for clearing bits in a PHY register
Parameters
struct phy_device *phydev: the phy_device structu32 regnum: register number to writeu16 val: bits to clear
__phy_set_bits_mmd() #
int Convenience function for setting bits in a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 val: bits to set
Description
The caller must have taken the MDIO bus lock.
__phy_clear_bits_mmd() #
int Convenience function for clearing bits in a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 val: bits to clear
Description
The caller must have taken the MDIO bus lock.
phy_set_bits_mmd() #
int Convenience function for setting bits in a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 val: bits to set
phy_clear_bits_mmd() #
int Convenience function for clearing bits in a register on MMD
Parameters
struct phy_device *phydev: the phy_device structint devad: the MMD containing register to modifyu32 regnum: register number to modifyu16 val: bits to clear
phy_interrupt_is_valid() #
bool Convenience function for testing a given PHY irq
Parameters
struct phy_device *phydev: the phy_device struct
NOTE
must be kept in sync with addition/removal of PHY_POLL and PHY_MAC_INTERRUPT
phy_polling_mode() #
bool Convenience function for testing whether polling is used to detect PHY status changes
Parameters
struct phy_device *phydev: the phy_device struct
phy_has_hwtstamp() #
bool Tests whether a PHY time stamp configuration.
Parameters
struct phy_device *phydev: the phy_device struct
phy_has_rxtstamp() #
bool Tests whether a PHY supports receive time stamping.
Parameters
struct phy_device *phydev: the phy_device struct
phy_has_tsinfo() #
bool Tests whether a PHY reports time stamping and/or PTP hardware clock capabilities.
Parameters
struct phy_device *phydev: the phy_device struct
phy_has_txtstamp() #
bool Tests whether a PHY supports transmit time stamping.
Parameters
struct phy_device *phydev: the phy_device struct
phy_is_default_hwtstamp() #
bool Is the PHY hwtstamp the default timestamp
Parameters
struct phy_device *phydev: Pointer to phy_device
Description
This is used to get default timestamping device taking into account the new API choice, which is selecting the timestamping from MAC by default if the phydev does not have default_timestamp flag enabled.
Return
True if phy is the default hw timestamp, false otherwise.
phy_on_sfp() #
bool Convenience function for testing if a PHY is on an SFP module
Parameters
struct phy_device *phydev: the phy_device struct
phy_interface_mode_is_rgmii() #
bool Convenience function for testing if a PHY interface mode is RGMII (all variants)
Parameters
phy_interface_t mode: thephy_interface_tenum
phy_interface_mode_is_8023z() #
bool does the PHY interface mode use 802.3z negotiation
Parameters
phy_interface_t mode: one ofenum phy_interface_t
Description
Returns true if the PHY interface mode uses the 16-bit negotiation word as defined in 802.3z. (See 802.3-2015 37.2.1 Config_Reg encoding)
phy_interface_is_rgmii() #
bool Convenience function for testing if a PHY interface is RGMII (all variants)
Parameters
struct phy_device *phydev: the phy_device struct
phy_is_pseudo_fixed_link() #
bool Convenience function for testing if this PHY is the CPU port facing side of an Ethernet switch, or similar.
Parameters
struct phy_device *phydev: the phy_device struct
phy_module_driver() #
Helper macro for registering PHY drivers
Parameters
__phy_drivers: array of PHY drivers to register__count: Numbers of members in array
Description
Helper macro for PHY drivers which do not do anything special in module
init/exit. Each module may only use this macro once, and calling it
replaces module_init() and module_exit().
genphy_match_phy_device() #
int match a PHY device with a PHY driver
Parameters
struct phy_device *phydev: target phy_device structconst struct phy_driver *phydrv: target phy_driver struct
Description
Checks whether the given PHY device matches the specified PHY driver. For Clause 45 PHYs, iterates over the available device identifiers and compares them against the driver's expected PHY ID, applying the provided mask. For Clause 22 PHYs, a direct ID comparison is performed.
Return
1 if the PHY device matches the driver, 0 otherwise.
get_phy_device() #
struct phy_device * reads the specified PHY device and returns its phy_device struct
Parameters
struct mii_bus *bus: the target MII busint addr: PHY address on the MII busbool is_c45: If true the PHY uses the 802.3 clause 45 protocol
Description
Probe for a PHY at addr on bus.
When probing for a clause 22 PHY, then read the ID registers. If we find
a valid ID, allocate and return a struct phy_device.
When probing for a clause 45 PHY, read the "devices in package" registers.
If the "devices in package" appears valid, read the ID registers for each
MMD, allocate and return a struct phy_device.
Returns an allocated struct phy_device on success, -ENODEV if there is
no PHY present, or -EIO on bus access error.
phy_device_register() #
int Register the phy device on the MDIO bus
Parameters
struct phy_device *phydev: phy_device structure to be added to the MDIO bus
phy_device_remove() #
void Remove a previously registered phy device from the MDIO bus
Parameters
struct phy_device *phydev: phy_device structure to remove
Description
This doesn't free the phy_device itself, it merely reverses the effects
of phy_device_register(). Use phy_device_free() to free the device
after calling this function.
phy_get_c45_ids() #
int Read 802.3-c45 IDs for phy device.
Parameters
struct phy_device *phydev: phy_device structure to read 802.3-c45 IDs
Description
Returns zero on success, -EIO on bus access error, or -ENODEV if
the "devices in package" is invalid.
phy_find_next() #
struct phy_device * finds the next PHY device on the bus
Parameters
struct mii_bus *bus: the target MII busstruct phy_device *pos: cursor
Return
next phy_device on the bus, or NULL
phy_connect_direct() #
int connect an ethernet device to a specific phy_device
Parameters
struct net_device *dev: the network device to connectstruct phy_device *phydev: the pointer to the phy devicevoid (*handler)(struct net_device *): callback function for state change notificationsphy_interface_t interface: PHY device's interface
phy_connect() #
struct phy_device * connect an ethernet device to a PHY device
Parameters
struct net_device *dev: the network device to connectconst char *bus_id: the id string of the PHY device to connectvoid (*handler)(struct net_device *): callback function for state change notificationsphy_interface_t interface: PHY device's interface
Description
-
Convenience function for connecting ethernet
devices to PHY devices. The default behavior is for the PHY infrastructure to handle everything, and only notify the connected driver when the link status changes. If you don't want, or can't use the provided functionality, you may choose to call only the subset of functions which provide the desired functionality.
phy_disconnect() #
void disable interrupts, stop state machine, and detach a PHY device
Parameters
struct phy_device *phydev: target phy_device struct
phy_attach_direct() #
int attach a network device to a given PHY device pointer
Parameters
struct net_device *dev: network device to attachstruct phy_device *phydev: Pointer to phy_device to attachu32 flags: PHY device's dev_flagsphy_interface_t interface: PHY device's interface
Description
-
Called by drivers to attach to a particular PHY
device. The phy_device is found, and properly hooked up to the phy_driver. If no driver is attached, then a generic driver is used. The phy_device is given a ptr to the attaching device, and given a callback for link status change. The phy_device is returned to the attaching driver. This function takes a reference on the phy device.
phy_attach() #
struct phy_device * attach a network device to a particular PHY device
Parameters
struct net_device *dev: network device to attachconst char *bus_id: Bus ID of PHY device to attachphy_interface_t interface: PHY device's interface
Description
-
Same as
phy_attach_direct()except that a PHY bus_idstring is passed instead of a pointer to a struct phy_device.
phy_detach() #
void detach a PHY device from its network device
Parameters
struct phy_device *phydev: target phy_device struct
Description
This detaches the phy device from its network device and the phy
driver, and drops the reference count taken in phy_attach_direct().
phy_reset_after_clk_enable() #
int perform a PHY reset if needed
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Some PHYs are known to need a reset after their refclk was
enabled. This function evaluates the flags and perform the reset if it's needed. Returns < 0 on error, 0 if the phy wasn't reset and 1 if the phy was reset.
genphy_setup_forced() #
int configures/forces speed/duplex from phydev
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Configures MII_BMCR to force speed/duplex
to the values in phydev. Assumes that the values are valid. Please see
phy_sanitize_settings().
genphy_restart_aneg() #
int Enable and Restart Autonegotiation
Parameters
struct phy_device *phydev: target phy_device struct
genphy_check_and_restart_aneg() #
int Enable and restart auto-negotiation
Parameters
struct phy_device *phydev: target phy_device structbool restart: whether aneg restart is requested
Description
Check, and restart auto-negotiation if needed.
__genphy_config_aneg() #
int restart auto-negotiation or write BMCR
Parameters
struct phy_device *phydev: target phy_device structbool changed: whether autoneg is requested
Description
-
If auto-negotiation is enabled, we configure the
advertising, and then restart auto-negotiation. If it is not enabled, then we write the BMCR.
genphy_c37_config_aneg() #
int restart auto-negotiation or write BMCR
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
If auto-negotiation is enabled, we configure the
advertising, and then restart auto-negotiation. If it is not enabled, then we write the BMCR. This function is intended for use with Clause 37 1000Base-X mode.
genphy_aneg_done() #
int return auto-negotiation status
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Reads the status register and returns 0 either if
auto-negotiation is incomplete, or if there was an error. Returns BMSR_ANEGCOMPLETE if auto-negotiation is done.
genphy_update_link() #
int update link status in phydev
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Update the value in phydev->link to reflect the
current link value. In order to do this, we need to read the status register twice, keeping the second value.
genphy_read_status_fixed() #
int read the link parameters for !aneg mode
Parameters
struct phy_device *phydev: target phy_device struct
Description
Read the current duplex and speed state for a PHY operating with autonegotiation disabled.
genphy_read_status() #
int check the link status and update current link state
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Check the link, then figure out the current state
by comparing what we advertise with what the link partner advertises. Start by checking the gigabit possibilities, then move on to 10/100.
genphy_c37_read_status() #
int check the link status and update current link state
Parameters
struct phy_device *phydev: target phy_device structbool *changed: pointer where to store if link changed
Description
-
Check the link, then figure out the current state
by comparing what we advertise with what the link partner advertises. This function is for Clause 37 1000Base-X mode.
If link has changed, changed is set to true, false otherwise.
genphy_soft_reset() #
int software reset the PHY via BMCR_RESET bit
Parameters
struct phy_device *phydev: target phy_device struct
Description
Perform a software PHY reset using the standard BMCR_RESET bit and poll for the reset bit to be cleared.
Return
0 on success, < 0 on failure
genphy_read_abilities() #
int read PHY abilities from Clause 22 registers
Parameters
struct phy_device *phydev: target phy_device struct
Description
Reads the PHY's abilities and populates phydev->supported accordingly.
Return
0 on success, < 0 on failure
phy_remove_link_mode() #
void Remove a supported link mode
Parameters
struct phy_device *phydev: phy_device structure to remove link mode fromu32 link_mode: Link mode to be removed
Description
Some MACs don't support all link modes which the PHY does. e.g. a 1G MAC often does not support 1000Half. Add a helper to remove a link mode.
phy_advertise_supported() #
void Advertise all supported modes
Parameters
struct phy_device *phydev: target phy_device struct
Description
Called to advertise all supported modes, doesn't touch pause mode advertising.
phy_advertise_eee_all() #
void Advertise all supported EEE modes
Parameters
struct phy_device *phydev: target phy_device struct
Description
Per default phylib preserves the EEE advertising at the time of
phy probing, which might be a subset of the supported EEE modes. Use this
function when all supported EEE modes should be advertised. This does not
trigger auto-negotiation, so must be called before phy_start()/
phylink_start() which will start auto-negotiation.
phy_support_eee() #
void Set initial EEE policy configuration
Parameters
struct phy_device *phydev: Target phy_device struct
Description
This function configures the initial policy for Energy Efficient Ethernet (EEE) on the specified PHY device, influencing that EEE capabilities are advertised before the link is established. It should be called during PHY registration by the MAC driver and/or the PHY driver (for SmartEEE PHYs) if MAC supports LPI or PHY is capable to compensate missing LPI functionality of the MAC.
The function sets default EEE policy parameters, including preparing the PHY to advertise EEE capabilities based on hardware support.
It also sets the expected configuration for Low Power Idle (LPI) in the MAC driver. If the PHY framework determines that both local and remote advertisements support EEE, and the negotiated link mode is compatible with EEE, it will set enable_tx_lpi = true. The MAC driver is expected to act on this setting by enabling the LPI timer if enable_tx_lpi is set.
phy_disable_eee() #
void Disable EEE for the PHY
Parameters
struct phy_device *phydev: Target phy_device struct
Description
This function is used by MAC drivers for MAC's which don't support EEE. It disables EEE on the PHY layer.
phy_support_sym_pause() #
void Enable support of symmetrical pause
Parameters
struct phy_device *phydev: target phy_device struct
Description
Called by the MAC to indicate is supports symmetrical Pause, but not asym pause.
phy_support_asym_pause() #
void Enable support of asym pause
Parameters
struct phy_device *phydev: target phy_device struct
Description
Called by the MAC to indicate is supports Asym Pause.
phy_set_sym_pause() #
void Configure symmetric Pause
Parameters
struct phy_device *phydev: target phy_device structbool rx: Receiver Pause is supportedbool tx: Transmit Pause is supportedbool autoneg: Auto neg should be used
Description
Configure advertised Pause support depending on if receiver pause and pause auto neg is supported. Generally called from the set_pauseparam .ndo.
phy_set_asym_pause() #
void Configure Pause and Asym Pause
Parameters
struct phy_device *phydev: target phy_device structbool rx: Receiver Pause is supportedbool tx: Transmit Pause is supported
Description
Configure advertised Pause support depending on if transmit and receiver pause is supported. If there has been a change in adverting, trigger a new autoneg. Generally called from the set_pauseparam .ndo.
phy_validate_pause() #
bool Test if the PHY/MAC support the pause configuration
Parameters
struct phy_device *phydev: phy_device structstruct ethtool_pauseparam *pp: requested pause configuration
Description
Test if the PHY/MAC combination supports the Pause configuration the user is requesting. Returns True if it is supported, false otherwise.
phy_get_pause() #
void resolve negotiated pause modes
Parameters
struct phy_device *phydev: phy_device structbool *tx_pause: pointer to bool to indicate whether transmit pause should be enabled.bool *rx_pause: pointer to bool to indicate whether receive pause should be enabled.
Description
Resolve and return the flow control modes according to the negotiation
result. This includes checking that we are operating in full duplex mode.
See linkmode_resolve_pause() for further details.
phy_get_internal_delay() #
s32 returns the index of the internal delay
Parameters
struct phy_device *phydev: phy_device structconst int *delay_values: array of delays the PHY supportsint size: the size of the delay arraybool is_rx: boolean to indicate to get the rx internal delay
Description
Returns the index within the array of internal delay passed in. If the device property is not present then the interface type is checked if the interface defines use of internal delay then a 1 is returned otherwise a 0 is returned. The array must be in ascending order. If PHY does not have an ascending order array then size = 0 and the value of the delay property is returned. Return -EINVAL if the delay is invalid or cannot be found.
phy_get_tx_amplitude_gain() #
int stores tx amplitude gain in val
Parameters
struct phy_device *phydev: phy_device structstruct device *dev: pointer to the devices device structenum ethtool_link_mode_bit_indices linkmode: linkmode for which the tx amplitude gain should be retrievedu32 *val: tx amplitude gain
Return
0 on success, < 0 on failure
phy_get_mac_termination() #
int stores MAC termination in val
Parameters
struct phy_device *phydev: phy_device structstruct device *dev: pointer to the devices device structu32 *val: MAC termination
Return
0 on success, < 0 on failure
phy_get_sfp_port() #
struct phy_port * Returns the first valid SFP port of a PHY
Parameters
struct phy_device *phydev: pointer to the PHY device to get the SFP port from
Return
The first active SFP (serdes) port of a PHY device, NULL if none exist.
fwnode_mdio_find_device() #
struct mdio_device * Given a fwnode, find the mdio_device
Parameters
struct fwnode_handle *fwnode: pointer to the mdio_device's fwnode
Description
If successful, returns a pointer to the mdio_device with the embedded
struct device refcount incremented by one, or NULL on failure.
The caller should call put_device() on the mdio_device after its use.
fwnode_phy_find_device() #
struct phy_device * For provided phy_fwnode, find phy_device.
Parameters
struct fwnode_handle *phy_fwnode: Pointer to the phy's fwnode.
Description
If successful, returns a pointer to the phy_device with the embedded struct device refcount incremented by one, or NULL on failure.
fwnode_get_phy_node() #
struct fwnode_handle * Get the phy_node using the named reference.
Parameters
const struct fwnode_handle *fwnode: Pointer to fwnode from which phy_node has to be obtained.
Description
Refer return conditions of fwnode_find_reference().
For ACPI, only "phy-handle" is supported. Legacy DT properties "phy"
and "phy-device" are not supported in ACPI. DT supports all the three
named references to the phy node.
phy_uses_state_machine() #
bool test whether consumer driver uses PAL state machine
Parameters
struct phy_device *phydev: the target PHY device structure
Description
Ultimately, this aims to indirectly determine whether the PHY is attached
to a consumer which uses the state machine by calling phy_start() and
phy_stop().
When the PHY driver consumer uses phylib, it must have previously called
phy_connect_direct() or one of its derivatives, so that phy_prepare_link()
has set up a hook for monitoring state changes.
When the PHY driver is used by the MAC driver consumer through phylink (the
only other provider of a phy_link_change() method), using the PHY state
machine is not optional.
Return
true if consumer calls phy_start() and phy_stop(), false otherwise.
phy_register_fixup() #
int creates a new phy_fixup and adds it to the list
Parameters
const char *bus_id: A string which matches phydev->mdio.dev.bus_id (or NULL)u32 phy_uid: Used to match against phydev->phy_id (the UID of the PHY)u32 phy_uid_mask: Applied to phydev->phy_id and fixup->phy_uid before comparison (or 0 to disable id-based matching)int (*run)(struct phy_device *): The actual code to be run when a matching PHY is found
get_phy_c45_ids() #
int reads the specified addr for its 802.3-c45 IDs.
Parameters
struct mii_bus *bus: the target MII busint addr: PHY address on the MII busstruct phy_c45_device_ids *c45_ids: where to store the c45 ID information.
Description
Read the PHY "devices in package". If this appears to be valid, read the PHY identifiers for each device. Return the "devices in package" and identifiers in c45_ids.
Returns zero on success, -EIO on bus access error, or -ENODEV if
the "devices in package" is invalid or no device responds.
get_phy_c22_id() #
int reads the specified addr for its clause 22 ID.
Parameters
struct mii_bus *bus: the target MII busint addr: PHY address on the MII busu32 *phy_id: where to store the ID retrieved.
Description
Read the 802.3 clause 22 PHY ID from the PHY at addr on the bus,
placing it in phy_id. Return zero on successful read and the ID is
valid, -EIO on bus access error, or -ENODEV if no device responds
or invalid ID.
phy_prepare_link() #
void prepares the PHY layer to monitor link status
Parameters
struct phy_device *phydev: target phy_device structvoid (*handler)(struct net_device *): callback function for link status change notifications
Description
-
Tells the PHY infrastructure to handle the
gory details on monitoring link status (whether through polling or an interrupt), and to call back to the connected device driver when the link status changes. If you want to monitor your own link state, don't call this function.
phy_poll_reset() #
int Safely wait until a PHY reset has properly completed
Parameters
struct phy_device *phydev: The PHY device to poll
Description
-
According to IEEE 802.3, Section 2, Subsection 22.2.4.1.1, as
published in 2008, a PHY reset may take up to 0.5 seconds. The MII BMCR register must be polled until the BMCR_RESET bit clears.
Furthermore, any attempts to write to PHY registers may have no effect or even generate MDIO bus errors until this is complete.
Some PHYs (such as the Marvell 88E1111) don't entirely conform to the standard and do not fully reset after the BMCR_RESET bit is set, and may even REQUIRE a soft-reset to properly restart autonegotiation. In an effort to support such broken PHYs, this function is separate from the standard
phy_init_hw()which will zero all the other bits in the BMCR and reapply all driver-specific and board-specific fixups.
phy_sfp_connect_phy() #
int Connect the SFP module's PHY to the upstream PHY
Parameters
void *upstream: pointer to the upstream phy devicestruct phy_device *phy: pointer to the SFP module's phy device
Description
This helper allows keeping track of PHY devices on the link. It adds the SFP module's phy to the phy namespace of the upstream phy
Return
0 on success, otherwise a negative error code.
phy_sfp_disconnect_phy() #
void Disconnect the SFP module's PHY from the upstream PHY
Parameters
void *upstream: pointer to the upstream phy devicestruct phy_device *phy: pointer to the SFP module's phy device
Description
This helper allows keeping track of PHY devices on the link. It removes the SFP module's phy to the phy namespace of the upstream phy. As the module phy will be destroyed, re-inserting the same module will add a new phy with a new index.
phy_sfp_attach() #
void attach the SFP bus to the PHY upstream network device
Parameters
void *upstream: pointer to the phy devicestruct sfp_bus *bus: sfp bus representing cage being attached
Description
This is used to fill in the sfp_upstream_ops .attach member.
phy_sfp_detach() #
void detach the SFP bus from the PHY upstream network device
Parameters
void *upstream: pointer to the phy devicestruct sfp_bus *bus: sfp bus representing cage being attached
Description
This is used to fill in the sfp_upstream_ops .detach member.
phy_sfp_probe() #
int probe for a SFP cage attached to this PHY device
Parameters
struct phy_device *phydev: Pointer to phy_device
genphy_config_advert() #
int sanitize and advertise auto-negotiation parameters
Parameters
struct phy_device *phydev: target phy_device structconst unsigned long *advert: auto-negotiation parameters to advertise
Description
-
Writes MII_ADVERTISE with the appropriate values,
after sanitizing the values to make sure we only advertise what is supported. Returns < 0 on error, 0 if the PHY's advertisement hasn't changed, and > 0 if it has changed.
genphy_c37_config_advert() #
int sanitize and advertise auto-negotiation parameters
Parameters
struct phy_device *phydev: target phy_device struct
Description
-
Writes MII_ADVERTISE with the appropriate values,
after sanitizing the values to make sure we only advertise what is supported. Returns < 0 on error, 0 if the PHY's advertisement hasn't changed, and > 0 if it has changed. This function is intended for Clause 37 1000Base-X mode.
phy_probe() #
int probe and init a PHY device
Parameters
struct device *dev: device to probe and init
Description
Take care of setting up the phy_device structure, set the state to READY.
phy_driver_register() #
int register a phy_driver with the PHY layer
Parameters
struct phy_driver *new_driver: new phy_driver to registerstruct module *owner: module owning this PHY
mdio_find_bus() #
struct mii_bus * Given the name of a mdiobus, find the mii_bus.
Parameters
const char *mdio_name: The name of a mdiobus.
Return
a reference to the mii_bus, or NULL if none found. The embedded struct device will have its reference count incremented, and this must be put_deviced'ed once the bus is finished with.
of_mdio_find_bus() #
struct mii_bus * Given an mii_bus node, find the mii_bus.
Parameters
struct device_node *mdio_bus_np: Pointer to the mii_bus.
Return
a reference to the mii_bus, or NULL if none found. The embedded struct device will have its reference count incremented, and this must be put once the bus is finished with.
Description
Because the association of a device_node and mii_bus is made via
of_mdiobus_register(), the mii_bus cannot be found before it is
registered with of_mdiobus_register().
__mdiobus_read() #
int Unlocked version of the mdiobus_read function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to read
Return
The register value if successful, negative error code on failure
Description
Read a MDIO bus register. Caller must hold the mdio bus lock.
NOTE
MUST NOT be called from interrupt context.
__mdiobus_write() #
int Unlocked version of the mdiobus_write function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to writeu16 val: value to write to regnum
Return
Zero if successful, negative error code on failure
Description
Write a MDIO bus register. Caller must hold the mdio bus lock.
NOTE
MUST NOT be called from interrupt context.
__mdiobus_modify_changed() #
int Unlocked version of the mdiobus_modify function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Return
1 if the register was modified, 0 if no change was needed, negative on any error condition
Description
Read, modify, and if any change, write the register value back to the device.
NOTE
MUST NOT be called from interrupt context.
__mdiobus_c45_read() #
int Unlocked version of the mdiobus_c45_read function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to read
Return
The register value if successful, negative error code on failure
Description
Read a MDIO bus register. Caller must hold the mdio bus lock.
NOTE
MUST NOT be called from interrupt context.
__mdiobus_c45_write() #
int Unlocked version of the mdiobus_write function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to writeu16 val: value to write to regnum
Return
Zero if successful, negative error code on failure
Description
Write a MDIO bus register. Caller must hold the mdio bus lock.
NOTE
MUST NOT be called from interrupt context.
mdiobus_read_nested() #
int Nested version of the mdiobus_read function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to read
Return
The register value if successful, negative error code on failure
Description
In case of nested MDIO bus access avoid lockdep false positives by
using mutex_lock_nested().
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_read() #
int Convenience function for reading a given MII mgmt register
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to read
Return
The register value if successful, negative error code on failure
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_c45_read() #
int Convenience function for reading a given MII mgmt register
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to read
Return
The register value if successful, negative error code on failure
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_c45_read_nested() #
int Nested version of the mdiobus_c45_read function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to read
Return
The register value if successful, negative error code on failure
Description
In case of nested MDIO bus access avoid lockdep false positives by
using mutex_lock_nested().
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_write_nested() #
int Nested version of the mdiobus_write function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to writeu16 val: value to write to regnum
Return
Zero if successful, negative error code on failure
Description
In case of nested MDIO bus access avoid lockdep false positives by
using mutex_lock_nested().
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_write() #
int Convenience function for writing a given MII mgmt register
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to writeu16 val: value to write to regnum
Return
Zero if successful, negative error code on failure
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_c45_write() #
int Convenience function for writing a given MII mgmt register
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to writeu16 val: value to write to regnum
Return
Zero if successful, negative error code on failure
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_c45_write_nested() #
int Nested version of the mdiobus_c45_write function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to writeu16 val: value to write to regnum
Return
Zero if successful, negative error code on failure
Description
In case of nested MDIO bus access avoid lockdep false positives by
using mutex_lock_nested().
NOTE
MUST NOT be called from interrupt context, because the bus read/write functions may wait for an interrupt to conclude the operation.
mdiobus_modify() #
int Convenience function for modifying a given mdio device register
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to writeu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Return
0 on success, negative on any error condition
mdiobus_c45_modify() #
int Convenience function for modifying a given mdio device register
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to writeu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Return
0 on success, negative on any error condition
mdiobus_modify_changed() #
int Convenience function for modifying a given mdio device register and returning if it changed
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressu32 regnum: register number to writeu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Return
1 if the register was modified, 0 if no change was needed, negative on any error condition
mdiobus_c45_modify_changed() #
int Convenience function for modifying a given mdio device register and returning if it changed
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to writeu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Return
1 if the register was modified, 0 if no change was needed, negative on any error condition
mdiobus_release() #
void mii_bus device release callback
Parameters
struct device *d: the target struct device that contains the mii_bus
Description
called when the last reference to an mii_bus is dropped, to free the underlying memory.
__mdiobus_c45_modify_changed() #
int Unlocked version of the mdiobus_modify function
Parameters
struct mii_bus *bus: the mii_bus structint addr: the phy addressint devad: device address to readu32 regnum: register number to modifyu16 mask: bit mask of bits to clearu16 set: bit mask of bits to set
Return
1 if the register was modified, 0 if no change was needed, negative on any error condition
Description
Read, modify, and if any change, write the register value back to the device. Any error returns a negative number.
NOTE
MUST NOT be called from interrupt context.
mdio_bus_match() #
int determine if given MDIO driver supports the given MDIO device
Parameters
struct device *dev: target MDIO deviceconst struct device_driver *drv: given MDIO driver
Return
1 if the driver supports the device, 0 otherwise
Description
-
This may require calling the devices own match function,
since different classes of MDIO devices have different match criteria.
PHYLINK #
PHYLINK interfaces traditional network drivers with PHYLIB, fixed-links, and SFF modules (eg, hot-pluggable SFP) that may contain PHYs. PHYLINK provides management of the link state and link modes.
struct phylink_link_state #
link state structure
Definition
;
Members
advertising: ethtool bitmask containing advertised link modeslp_advertising: ethtool bitmask containing link partner advertised link modesinterface: linktypedef phy_interface_tmodespeed: link speed, one of the SPEED_* constants.duplex: link duplex mode, one of DUPLEX_* constants.pause: link pause state, described by MLO_PAUSE_* constants.rate_matching: rate matching being performed, one of the RATE_MATCH_* constants. If rate matching is taking place, then the speed/duplex of the medium link mode (speed and duplex) and the speed/duplex of the phy interface mode (interface) are different.link: true if the link is up.an_complete: true if autonegotiation has completed.
struct phylink_config #
PHYLINK configuration structure
Definition
;
Members
dev: a pointer to a struct device associated with the MACtype: operation type of PHYLINK instancepoll_fixed_state: if true, starts link_poll, if MAC link is atMLO_AN_FIXEDmode.mac_managed_pm: if true, indicate the MAC driver is responsible for PHY PM.mac_requires_rxc: if true, the MAC always requires a receive clock from PHY. The PHY driver should start the clock signal as soon as possible and avoid stopping it during suspend events.default_an_inband: if true, defaults to MLO_AN_INBAND rather than MLO_AN_PHY. A fixed-link specification will override.eee_rx_clk_stop_enable: if true, PHY can stop the receive clock during LPIget_fixed_state: callback to execute to determine the fixed link state, if MAC link is atMLO_AN_FIXEDmode.supported_interfaces: bitmap describing which PHY_INTERFACE_MODE_xxx are supported by the MAC/PCS.lpi_interfaces: bitmap describing which PHY interface modes can support LPI signalling.mac_capabilities: MAC pause/speed/duplex capabilities.lpi_capabilities: MAC speeds which can support LPI signallinglpi_timer_default: Default EEE LPI timer setting.eee_enabled_default: If set, EEE will be enabled by phylink at creation timewol_phy_legacy: Use Wake-on-Lan with PHY even ifphy_can_wakeup()is falsewol_phy_speed_ctrl: Use phy speed control on suspend/resumewol_mac_support: Bitmask of MAC supportedWAKE_*options
struct phylink_mac_ops #
MAC operations structure.
Definition
;
Members
mac_get_caps: Get MAC capabilities for interface mode.mac_select_pcs: Select a PCS for the interface mode.mac_prepare: prepare for a major reconfiguration of the interface.mac_config: configure the MAC for the selected mode and state.mac_finish: finish a major reconfiguration of the interface.mac_link_down: take the link down.mac_link_up: allow the link to come up.mac_disable_tx_lpi: disable LPI.mac_enable_tx_lpi: enable and configure LPI.mac_wol_set: configure Wake-on-Lan settings at the MAC.
Description
The individual methods are described more fully below.
mac_get_caps() #
unsigned long Get MAC capabilities for interface mode.
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.phy_interface_t interface: PHY interface mode.
Description
Optional method. When not provided, config->mac_capabilities will be used. When implemented, this returns the MAC capabilities for the specified interface mode where there is some special handling required by the MAC driver (e.g. not supporting half-duplex in certain interface modes.)
mac_select_pcs() #
struct phylink_pcs * Select a PCS for the interface mode.
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.phy_interface_t interface: PHY interface mode for PCS
Description
Return the struct phylink_pcs for the specified interface mode, or
NULL if none is required, or an error pointer on error.
This must not modify any state. It is used to query which PCS should be used. Phylink will use this during validation to ensure that the configuration is valid, and when setting a configuration to internally set the PCS that will be used.
mac_prepare() #
int prepare to change the PHY interface mode
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.unsigned int mode: one ofMLO_AN_FIXED,MLO_AN_PHY,MLO_AN_INBAND.phy_interface_t iface: interface mode to switch to
Description
phylink will call this method at the beginning of a full initialisation of the link, which includes changing the interface mode or at initial startup time. It may be called for the current mode. The MAC driver should perform whatever actions are required, e.g. disabling the Serdes PHY.
This will be the first call in the sequence:
Returns zero on success, or negative errno on failure which will be reported to the kernel log.
mac_config() #
void configure the MAC for the selected mode and state
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.unsigned int mode: one ofMLO_AN_FIXED,MLO_AN_PHY,MLO_AN_INBAND.const struct phylink_link_state *state: a pointer to astruct phylink_link_state.
Description
Note - not all members of state are valid. In particular,
state->lp_advertising, state->link, state->an_complete are never
guaranteed to be correct, and so any mac_config() implementation must
never reference these fields.
This will only be called to reconfigure the MAC for a "major" change in e.g. interface mode. It will not be called for changes in speed, duplex or pause modes or to change the in-band advertisement.
In all negotiation modes, as defined by mode, state->pause indicates the
pause settings which should be applied as follows. If MLO_PAUSE_AN is not
set, MLO_PAUSE_TX and MLO_PAUSE_RX indicate whether the MAC should send
pause frames and/or act on received pause frames respectively. Otherwise,
the results of in-band negotiation/status from the MAC PCS should be used
to control the MAC pause mode settings.
The action performed depends on the currently selected mode:
-
MLO_AN_FIXED,MLO_AN_PHY: Configure for non-inband negotiation mode, where the link settings are completely communicated viamac_link_up(). The physical link protocol from the MAC is specified by state->interface.state->advertising may be used, but is not required.
Older drivers (prior to the
mac_link_up()change) may use state->speed, state->duplex and state->pause to configure the MAC, but this is deprecated; such drivers should be converted to usemac_link_up().Other members of state must be ignored.
Valid state members: interface, advertising. Deprecated state members: speed, duplex, pause.
-
MLO_AN_INBAND: place the link in an inband negotiation mode (such as 802.3z 1000base-X or Cisco SGMII mode depending on the state->interface mode). In both cases, link state management (whether the link is up or not) is performed by the MAC, and reported via thepcs_get_state()callback. Changes in link state must be made by callingphylink_mac_change().Interface mode specific details are mentioned below.
If in 802.3z mode, the link speed is fixed, dependent on the state->interface. Duplex and pause modes are negotiated via the in-band configuration word. Advertised pause modes are set according to state->advertising. Beware of MACs which only support full duplex at gigabit and higher speeds.
If in Cisco SGMII mode, the link speed and duplex mode are passed in the serial bitstream 16-bit configuration word, and the MAC should be configured to read these bits and acknowledge the configuration word. Nothing is advertised by the MAC. The MAC is responsible for reading the configuration word and configuring itself accordingly.
Valid state members: interface, pause, advertising.
Implementations are expected to update the MAC to reflect the requested settings - i.o.w., if nothing has changed between two calls, no action is expected. If only flow control settings have changed, flow control should be updated without taking the link down. This "update" behaviour is critical to avoid bouncing the link up status.
mac_finish() #
int finish a to change the PHY interface mode
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.unsigned int mode: one ofMLO_AN_FIXED,MLO_AN_PHY,MLO_AN_INBAND.phy_interface_t iface: interface mode to switch to
Description
phylink will call this if it called mac_prepare() to allow the MAC to
complete any necessary steps after the MAC and PCS have been configured
for the mode and iface. E.g. a MAC driver may wish to re-enable the
Serdes PHY here if it was previously disabled by mac_prepare().
Returns zero on success, or negative errno on failure which will be reported to the kernel log.
mac_link_down() #
void notification that the link has gone down
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.unsigned int mode: link autonegotiation modephy_interface_t interface: linktypedef phy_interface_tmode
Description
Notifies the MAC that the link has gone down. This will not be called
unless mac_link_up() has been previously called.
The MAC should stop processing packets for transmission and reception.
phylink will have called netif_carrier_off() to notify the networking
stack that the link has gone down, so MAC drivers should not make this
call.
If mode is MLO_AN_INBAND, then this function must not prevent the
link coming up.
mac_link_up() #
void notification that the link has come up
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.struct phy_device *phy: any attached phy (deprecated - please use LPI interfaces)unsigned int mode: link autonegotiation modephy_interface_t interface: linktypedef phy_interface_tmodeint speed: link speedint duplex: link duplexbool tx_pause: link transmit pause enablement statusbool rx_pause: link receive pause enablement status
Description
Notifies the MAC that the link has come up, and the parameters of the
link as seen from the MACs point of view. If mac_link_up() has been
called previously, there will be an intervening call to mac_link_down()
before this method will be subsequently called.
speed, duplex, tx_pause and rx_pause indicate the finalised link settings, and should be used to configure the MAC block appropriately where these settings are not automatically conveyed from the PCS block, or if in-band negotiation (as defined by phylink_autoneg_inband(mode)) is disabled.
Note that when 802.3z in-band negotiation is in use, it is possible that the user wishes to override the pause settings, and this should be allowed when considering the implementation of this method.
Once configured, the MAC may begin to process packets for transmission and reception.
Interface type selection must be done in mac_config().
mac_disable_tx_lpi() #
void disable LPI generation at the MAC
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.
Description
Disable generation of LPI at the MAC, effectively preventing the MAC from indicating that it is idle.
mac_enable_tx_lpi() #
int configure and enable LPI generation at the MAC
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.u32 timer: LPI timeout in microseconds.bool tx_clk_stop: allow xMII transmit clock to be stopped during LPI
Description
Configure the LPI timeout accordingly. This will only be called when the link is already up, to cater for situations where the hardware needs to be programmed according to the link speed.
Enable LPI generation at the MAC, and configure whether the xMII transmit clock may be stopped.
Return
0 on success. Please consult with rmk before returning an error.
mac_wol_set() #
int configure the Wake-on-Lan parameters
Parameters
struct phylink_config *config: a pointer to astruct phylink_config.u32 wolopts: Bitmask ofWAKE_*flags for enabled Wake-On-Lan modes.const u8 *sopass: SecureOn(tm) password; meaningful only forWAKE_MAGICSECURE
Description
Enable the specified Wake-on-Lan options at the MAC. Options that the PHY can handle will have been removed from wolopts.
The presence of this method enables phylink-managed WoL support.
Return
0 on success.
struct phylink_pcs #
PHYLINK PCS instance
Definition
;
Members
supported_interfaces: describing which PHY_INTERFACE_MODE_xxx are supported by this PCS.ops: a pointer to thestruct phylink_pcs_opsstructurephylink: pointer tostruct phylink_configpoll: poll the PCS for link changesrxc_always_on: The MAC driver requires the reference clock to always be on. Standalone PCS drivers which do not have access to a PHY device can check this instead of PHY_F_RXC_ALWAYS_ON.
Description
This structure is designed to be embedded within the PCS private data, and will be passed between phylink and the PCS.
The phylink member is private to phylink and must not be touched by the PCS driver.
struct phylink_pcs_ops #
MAC PCS operations structure.
Definition
;
Members
pcs_validate: validate the link configuration.pcs_inband_caps: query inband support for interface mode.pcs_enable: enable the PCS.pcs_disable: disable the PCS.pcs_pre_config: pre-mac_config method (for errata)pcs_post_config: post-mac_config method (for arrata)pcs_get_state: read the current MAC PCS link state from the hardware.pcs_config: configure the MAC PCS for the selected mode and state.pcs_an_restart: restart 802.3z BaseX autonegotiation.pcs_link_up: program the PCS for the resolved link configuration (where necessary).pcs_disable_eee: optional notification to PCS that EEE has been disabled at the MAC.pcs_enable_eee: optional notification to PCS that EEE will be enabled at the MAC.pcs_pre_init: configure PCS components necessary for MAC hardware initialization e.g. RX clock for stmmac.
pcs_validate() #
int validate the link configuration.
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.unsigned long *supported: ethtool bitmask for supported link modes.const struct phylink_link_state *state: a const pointer to astruct phylink_link_state.
Description
Validate the interface mode, and advertising's autoneg bit, removing any
media ethtool link modes that would not be supportable from the supported
mask. Phylink will propagate the changes to the advertising mask. See the
struct phylink_mac_ops validate() method.
Returns -EINVAL if the interface mode/autoneg mode is not supported. Returns non-zero positive if the link state can be supported.
pcs_inband_caps() #
unsigned int query PCS in-band capabilities for interface mode.
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.phy_interface_t interface: interface mode to be queried
Description
Returns zero if it is unknown what in-band signalling is supported by the
PHY (e.g. because the PHY driver doesn't implement the method.) Otherwise,
returns a bit mask of the LINK_INBAND_* values from
enum link_inband_signalling to describe which inband modes are supported
for this interface mode.
pcs_enable() #
int enable the PCS.
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.
pcs_disable() #
void disable the PCS.
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.
pcs_get_state() #
void Read the current inband link state from the hardware
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.unsigned int neg_mode: link negotiation mode (PHYLINK_PCS_NEG_xxx)struct phylink_link_state *state: a pointer to astruct phylink_link_state.
Description
Read the current inband link state from the MAC PCS, reporting the
current speed in state->speed, duplex mode in state->duplex, pause
mode in state->pause using the MLO_PAUSE_RX and MLO_PAUSE_TX bits,
negotiation completion state in state->an_complete, and link up state
in state->link. If possible, state->lp_advertising should also be
populated.
Note that the neg_mode parameter is always the PHYLINK_PCS_NEG_xxx state, not MLO_AN_xxx.
pcs_config() #
int Configure the PCS mode and advertisement
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.unsigned int neg_mode: link negotiation mode (see below)phy_interface_t interface: interface mode to be usedconst unsigned long *advertising: adertisement ethtool link mode maskbool permit_pause_to_mac: permit forwarding pause resolution to MAC
Description
Configure the PCS for the operating mode, the interface mode, and set the advertisement mask. permit_pause_to_mac indicates whether the hardware may forward the pause mode resolution to the MAC.
When operating in MLO_AN_INBAND, inband should always be enabled,
otherwise inband should be disabled.
For SGMII, there is no advertisement from the MAC side, the PCS should be programmed to acknowledge the inband word from the PHY.
For 1000BASE-X, the advertisement should be programmed into the PCS.
For most 10GBASE-R, there is no advertisement.
The neg_mode argument should be tested via the phylink_mode_() family of
functions, or for PCS that set pcs->neg_mode true, should be tested
against the PHYLINK_PCS_NEG_ definitions.
pcs_config() will be called when configuration of the PCS is required
or when the advertisement is possibly updated. It must not unnecessarily
disrupt an established link.
When an autonegotiation restart is required for 802.3z modes, .pcs_config()
should return a positive non-zero integer (e.g. 1) to indicate to phylink
to call the pcs_an_restart() method.
pcs_an_restart() #
void restart 802.3z BaseX autonegotiation
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.
Description
When PCS ops are present, this overrides mac_an_restart() in struct phylink_mac_ops.
pcs_link_up() #
void program the PCS for the resolved link configuration
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.unsigned int neg_mode: link negotiation mode (see below)phy_interface_t interface: linktypedef phy_interface_tmodeint speed: link speedint duplex: link duplex
Description
This call will be made just before mac_link_up() to inform the PCS of
the resolved link parameters. For example, a PCS operating in SGMII
mode without in-band AN needs to be manually configured for the link
and duplex setting. Otherwise, this should be a no-op.
The mode argument should be tested via the phylink_mode_() family of
functions, or for PCS that set pcs->neg_mode true, should be tested
against the PHYLINK_PCS_NEG_ definitions.
pcs_disable_eee() #
void Disable EEE at the PCS
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs
Description
Optional method informing the PCS that EEE has been disabled at the MAC.
pcs_enable_eee() #
void Enable EEE at the PCS
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs
Description
Optional method informing the PCS that EEE is about to be enabled at the MAC.
pcs_pre_init() #
int Configure PCS components necessary for MAC initialization
Parameters
struct phylink_pcs *pcs: a pointer to astruct phylink_pcs.
Description
This function can be called by MAC drivers through the
phylink_pcs_pre_init() wrapper, before their hardware is initialized. It
should not be called after the link is brought up, as reconfiguring the PCS
at this point could break the link.
Some MAC devices require specific hardware initialization to be performed by their associated PCS device before they can properly initialize their own hardware. An example of this is the initialization of stmmac controllers, which requires an active REF_CLK signal to be provided by the PHY/PCS.
By calling phylink_pcs_pre_init(), MAC drivers can ensure that the PCS is
setup in a way that allows for successful hardware initialization.
The specific configuration performed by pcs_pre_init() is dependent on the
model of PCS and the requirements of the MAC device attached to it. PCS
driver authors should consider whether their target device is to be used in
conjunction with a MAC device whose driver calls phylink_pcs_pre_init(). MAC
driver authors should document their requirements for the PCS
pre-initialization.
phylink_get_link_timer_ns() #
int return the PCS link timer value
Parameters
phy_interface_t interface: linktypedef phy_interface_tmode
Description
Return the PCS link timer setting in nanoseconds for the PHY interface mode, or -EINVAL if not appropriate.
phylink_mac_implements_lpi() #
bool determine if MAC implements LPI ops
Parameters
const struct phylink_mac_ops *ops: phylink_mac_ops structure
Description
Returns true if the phylink MAC operations structure indicates that the LPI operations have been implemented, false otherwise.
struct phylink #
internal data type for phylink
Definition
;
phylink_set_port_modes() #
void set the port type modes in the ethtool mask
Parameters
unsigned long *mask: ethtool link mode mask
Description
Sets all the port type modes in the ethtool mask. MAC drivers should use this in their 'validate' callback.
phylink_interface_max_speed() #
int get the maximum speed of a phy interface
Parameters
phy_interface_t interface: phy interface mode defined bytypedef phy_interface_t
Description
Determine the maximum speed of a phy interface. This is intended to help determine the correct speed to pass to the MAC when the phy is performing rate matching.
Return
The maximum speed of interface
phylink_caps_to_link_caps() #
unsigned long Convert a set of MAC capabilities LINK caps
Parameters
unsigned long caps: A set of MAC capabilities
Return
The corresponding set of LINK_CAPA as defined in phy-caps.h
phylink_caps_to_linkmodes() #
void Convert capabilities to ethtool link modes
Parameters
unsigned long *linkmodes: ethtool linkmode mask (must be already initialised)unsigned long caps: bitmask of MAC capabilities
Description
Set all possible pause, speed and duplex linkmodes in linkmodes that are supported by the caps. linkmodes must have been initialised previously.
phylink_limit_mac_speed() #
void limit the phylink_config to a maximum speed
Parameters
struct phylink_config *config: pointer to astruct phylink_configu32 max_speed: maximum speed
Description
Mask off MAC capabilities for speeds higher than the max_speed parameter. Any further motifications of config.mac_capabilities will override this.
phylink_cap_from_speed_duplex() #
unsigned long Get mac capability from speed/duplex
Parameters
int speed: the speed to search forunsigned int duplex: the duplex to search for
Description
Find the mac capability for a given speed and duplex.
Return
A mask with the mac capability patching speed and duplex, or 0 if there were no matches.
phylink_get_capabilities() #
unsigned long get capabilities for a given MAC
Parameters
phy_interface_t interface: phy interface mode defined bytypedef phy_interface_tunsigned long mac_capabilities: bitmask of MAC capabilitiesint rate_matching: type of rate matching being performed
Description
Get the MAC capabilities that are supported by the interface mode and mac_capabilities.
phylink_validate_mask_caps() #
void Restrict link modes based on caps
Parameters
unsigned long *supported: ethtool bitmask for supported link modes.struct phylink_link_state *state: pointer to astruct phylink_link_state.unsigned long mac_capabilities: bitmask of MAC capabilities
Description
Calculate the supported link modes based on mac_capabilities, and restrict supported and state based on that. Use this function if your capabiliies aren't constant, such as if they vary depending on the interface.
phylink_pcs_neg_mode() #
void helper to determine PCS inband mode
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct phylink_pcs *pcs: a pointer tostruct phylink_pcsphy_interface_t interface: interface mode to be usedconst unsigned long *advertising: adertisement ethtool link mode mask
Description
Determines the negotiation mode to be used by the PCS, and returns one of:
PHYLINK_PCS_NEG_NONE: interface mode does not support inbandPHYLINK_PCS_NEG_OUTBAND: an out of band mode (e.g. reading the PHY) will be used.PHYLINK_PCS_NEG_INBAND_DISABLED: inband mode selected but autoneg disabledPHYLINK_PCS_NEG_INBAND_ENABLED: inband mode selected and autoneg enabled
Note
this is for cases where the PCS itself is involved in negotiation (e.g. Clause 37, SGMII and similar) not Clause 73.
phylink_set_fixed_link() #
int set the fixed link
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()const struct phylink_link_state *state: a pointer to a struct phylink_link_state.
Description
This function is used when the link parameters are known and do not change, making it suitable for certain types of network connections.
Return
zero on success or negative error code.
phylink_create() #
struct phylink * create a phylink instance
Parameters
struct phylink_config *config: a pointer to the targetstruct phylink_configconst struct fwnode_handle *fwnode: a pointer to astruct fwnode_handledescribing the network interfacephy_interface_t iface: the desired link mode defined bytypedef phy_interface_tconst struct phylink_mac_ops *mac_ops: a pointer to astruct phylink_mac_opsfor the MAC.
Description
Create a new phylink instance, and parse the link parameters found in np. This will parse in-band modes, fixed-link or SFP configuration.
Note
the rtnl lock must not be held when calling this function.
Returns a pointer to a struct phylink, or an error-pointer value. Users
must use IS_ERR() to check for errors from this function.
phylink_destroy() #
void cleanup and destroy the phylink instance
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Destroy a phylink instance. Any PHY that has been attached must have been
cleaned up via phylink_disconnect_phy() prior to calling this function.
Note
the rtnl lock must not be held when calling this function.
phylink_expects_phy() #
bool Determine if phylink expects a phy to be attached
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
When using fixed-link mode, or in-band mode with 1000base-X or 2500base-X, no PHY is needed.
Returns true if phylink will be expecting a PHY.
phylink_connect_phy() #
int connect a PHY to the phylink instance
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct phy_device *phy: a pointer to astruct phy_device.
Description
Connect phy to the phylink instance specified by pl by calling
phy_attach_direct(). Configure the phy according to the MAC driver's
capabilities, start the PHYLIB state machine and enable any interrupts
that the PHY supports.
This updates the phylink's ethtool supported and advertising link mode masks.
Returns 0 on success or a negative errno.
phylink_of_phy_connect() #
int connect the PHY specified in the DT mode.
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct device_node *dn: a pointer to astruct device_node.u32 flags: PHY-specific flags to communicate to the PHY device driver
Description
Connect the phy specified in the device node dn to the phylink instance
specified by pl. Actions specified in phylink_connect_phy() will be
performed.
Returns 0 on success or a negative errno.
phylink_fwnode_phy_connect() #
int connect the PHY specified in the fwnode.
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()const struct fwnode_handle *fwnode: a pointer to astruct fwnode_handle.u32 flags: PHY-specific flags to communicate to the PHY device driver
Description
Connect the phy specified fwnode to the phylink instance specified by pl.
Returns 0 on success or a negative errno.
phylink_disconnect_phy() #
void disconnect any PHY attached to the phylink instance.
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Disconnect any current PHY from the phylink instance described by pl.
phylink_mac_change() #
void notify phylink of a change in MAC state
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()bool up: indicates whether the link is currently up.
Description
The MAC driver should call this driver when the state of its link changes (eg, link failure, new negotiation results, etc.)
phylink_pcs_change() #
void notify phylink of a change to PCS link state
Parameters
struct phylink_pcs *pcs: pointer tostruct phylink_pcsbool up: indicates whether the link is currently up.
Description
The PCS driver should call this when the state of its link changes
(e.g. link failure, new negotiation results, etc.) Note: it should
not determine "up" by reading the BMSR. If in doubt about the link
state at interrupt time, then pass true if pcs_get_state() returns
the latched link-down state, otherwise pass false.
phylink_start() #
void start a phylink instance
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Start the phylink instance specified by pl, configuring the MAC for the
desired link mode(s) and negotiation style. This should be called from the
network device driver's struct net_device_ops ndo_open() method.
phylink_stop() #
void stop a phylink instance
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Stop the phylink instance specified by pl. This should be called from the
network device driver's struct net_device_ops ndo_stop() method. The
network device's carrier state should not be changed prior to calling this
function.
This will synchronously bring down the link if the link is not already
down (in other words, it will trigger a mac_link_down() method call.)
phylink_rx_clk_stop_block() #
void block PHY ability to stop receive clock in LPI
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Disable the PHY's ability to stop the receive clock while the receive path
is in EEE LPI state, until the number of calls to phylink_rx_clk_stop_block()
are balanced by calls to phylink_rx_clk_stop_unblock().
phylink_rx_clk_stop_unblock() #
void unblock PHY ability to stop receive clock
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
All calls to phylink_rx_clk_stop_block() must be balanced with a
corresponding call to phylink_rx_clk_stop_unblock() to restore the PHYs
ability to stop the receive clock when the receive path is in EEE LPI mode.
phylink_suspend() #
void handle a network device suspend event
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()bool mac_wol: true if the MAC needs to receive packets for Wake-on-Lan
Description
Handle a network device suspend event. There are several cases:
- If Wake-on-Lan is not active, we can bring down the link between
the MAC and PHY by calling
phylink_stop(). - If Wake-on-Lan is active, and being handled only by the PHY, we can also bring down the link between the MAC and PHY.
- If Wake-on-Lan is active, but being handled by the MAC, the MAC still needs to receive packets, so we can not bring the link down.
Note
when phylink managed Wake-on-Lan is in use, mac_wol is ignored. (struct phylink_mac_ops.mac_set_wol populated.)
phylink_prepare_resume() #
void prepare to resume a network device
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Optional, but if called must be called prior to phylink_resume().
Prepare to resume a network device, preparing the PHY as necessary.
phylink_resume() #
void handle a network device resume event
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Undo the effects of phylink_suspend(), returning the link to an
operational state.
phylink_ethtool_get_wol() #
void get the wake on lan parameters for the PHY
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ethtool_wolinfo *wol: a pointer tostruct ethtool_wolinfoto hold the read parameters
Description
Read the wake on lan parameters from the PHY attached to the phylink instance specified by pl. If no PHY is currently attached, report no support for wake on lan.
phylink_ethtool_set_wol() #
int set wake on lan parameters
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ethtool_wolinfo *wol: a pointer tostruct ethtool_wolinfofor the desired parameters
Description
Set the wake on lan parameters for the PHY attached to the phylink
instance specified by pl. If no PHY is attached, returns EOPNOTSUPP
error.
Returns zero on success or negative errno code.
phylink_ethtool_ksettings_get() #
int get the current link settings
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ethtool_link_ksettings *kset: a pointer to astruct ethtool_link_ksettingsto hold link settings
Description
Read the current link settings for the phylink instance specified by pl. This will be the link settings read from the MAC, PHY or fixed link settings depending on the current negotiation mode.
phylink_ethtool_ksettings_set() #
int set the link settings
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()const struct ethtool_link_ksettings *kset: a pointer to astruct ethtool_link_ksettingsfor the desired modes
phylink_ethtool_nway_reset() #
int restart negotiation
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Restart negotiation for the phylink instance specified by pl. This will cause any attached phy to restart negotiation with the link partner, and if the MAC is in a BaseX mode, the MAC will also be requested to restart negotiation.
Returns zero on success, or negative error code.
phylink_ethtool_get_pauseparam() #
void get the current pause parameters
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ethtool_pauseparam *pause: a pointer to astruct ethtool_pauseparam
phylink_ethtool_set_pauseparam() #
int set the current pause parameters
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ethtool_pauseparam *pause: a pointer to astruct ethtool_pauseparam
phylink_get_eee_err() #
int read the energy efficient ethernet error counter
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create().
Description
Read the Energy Efficient Ethernet error counter from the PHY associated with the phylink instance specified by pl.
Returns positive error counter value, or negative error code.
phylink_ethtool_get_eee() #
int read the energy efficient ethernet parameters
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ethtool_keee *eee: a pointer to astruct ethtool_keeefor the read parameters
phylink_ethtool_set_eee() #
int set the energy efficient ethernet parameters
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ethtool_keee *eee: a pointer to astruct ethtool_keeefor the desired parameters
phylink_mii_ioctl() #
int generic mii ioctl interface
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()struct ifreq *ifr: a pointer to astruct ifreqfor socket ioctlsint cmd: ioctl cmd to execute
Description
Perform the specified MII ioctl on the PHY attached to the phylink instance specified by pl. If no PHY is attached, emulate the presence of the PHY.
SIOCGMIIPHY: read register from the current PHY.SIOCGMIIREG: read register from the specified PHY.SIOCSMIIREG: set a register on the specified PHY.
Return
zero on success or negative error code.
phylink_speed_down() #
int set the non-SFP PHY to lowest speed supported by both link partners
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()bool sync: perform action synchronously
Description
If we have a PHY that is not part of a SFP module, then set the speed
as described in the phy_speed_down() function. Please see this function
for a description of the sync parameter.
Returns zero if there is no PHY, otherwise as per phy_speed_down().
phylink_speed_up() #
int restore the advertised speeds prior to the call to phylink_speed_down()
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
If we have a PHY that is not part of a SFP module, then restore the
PHY speeds as per phy_speed_up().
Returns zero if there is no PHY, otherwise as per phy_speed_up().
phylink_decode_usxgmii_word() #
void decode the USXGMII word from a MAC PCS
Parameters
struct phylink_link_state *state: a pointer to a struct phylink_link_state.uint16_t lpa: a 16 bit value which stores the USXGMII auto-negotiation word
Description
Helper for MAC PCS supporting the USXGMII protocol and the auto-negotiation code word. Decode the USXGMII code word and populate the corresponding fields (speed, duplex) into the phylink_link_state structure.
phylink_decode_usgmii_word() #
void decode the USGMII word from a MAC PCS
Parameters
struct phylink_link_state *state: a pointer to a struct phylink_link_state.uint16_t lpa: a 16 bit value which stores the USGMII auto-negotiation word
Description
Helper for MAC PCS supporting the USGMII protocol and the auto-negotiation code word. Decode the USGMII code word and populate the corresponding fields (speed, duplex) into the phylink_link_state structure. The structure for this word is the same as the USXGMII word, except it only supports speeds up to 1Gbps.
phylink_mii_c22_pcs_decode_state() #
void Decode MAC PCS state from MII registers
Parameters
struct phylink_link_state *state: a pointer to astruct phylink_link_state.unsigned int neg_mode: link negotiation mode (PHYLINK_PCS_NEG_xxx)u16 bmsr: The value of theMII_BMSRregisteru16 lpa: The value of theMII_LPAregister
Description
Helper for MAC PCS supporting the 802.3 clause 22 register set for clause 37 negotiation and/or SGMII control.
Parse the Clause 37 or Cisco SGMII link partner negotiation word into
the phylink state structure. This is suitable to be used for implementing
the pcs_get_state() member of the struct phylink_pcs_ops structure if
accessing bmsr and lpa cannot be done with MDIO directly.
phylink_mii_c22_pcs_get_state() #
void read the MAC PCS state
Parameters
struct mdio_device *pcs: a pointer to astruct mdio_device.unsigned int neg_mode: link negotiation mode (PHYLINK_PCS_NEG_xxx)struct phylink_link_state *state: a pointer to astruct phylink_link_state.
Description
Helper for MAC PCS supporting the 802.3 clause 22 register set for clause 37 negotiation and/or SGMII control.
Read the MAC PCS state from the MII device configured in config and
parse the Clause 37 or Cisco SGMII link partner negotiation word into
the phylink state structure. This is suitable to be directly plugged
into the pcs_get_state() member of the struct phylink_pcs_ops
structure.
phylink_mii_c22_pcs_encode_advertisement() #
int configure the clause 37 PCS advertisement
Parameters
phy_interface_t interface: the PHY interface mode being configuredconst unsigned long *advertising: the ethtool advertisement mask
Description
Helper for MAC PCS supporting the 802.3 clause 22 register set for clause 37 negotiation and/or SGMII control.
Encode the clause 37 PCS advertisement as specified by interface and advertising.
Return
The new value for adv, or -EINVAL if it should not be changed.
phylink_mii_c22_pcs_config() #
int configure clause 22 PCS
Parameters
struct mdio_device *pcs: a pointer to astruct mdio_device.phy_interface_t interface: the PHY interface mode being configuredconst unsigned long *advertising: the ethtool advertisement maskunsigned int neg_mode: PCS negotiation mode
Description
Configure a Clause 22 PCS PHY with the appropriate negotiation parameters for the mode, interface and advertising parameters. Returns negative error number on failure, zero if the advertisement has not changed, or positive if there is a change.
phylink_mii_c22_pcs_an_restart() #
void restart 802.3z autonegotiation
Parameters
struct mdio_device *pcs: a pointer to astruct mdio_device.
Description
Helper for MAC PCS supporting the 802.3 clause 22 register set for clause 37 negotiation.
Restart the clause 37 negotiation with the link partner. This is
suitable to be directly plugged into the pcs_get_state() member
of the struct phylink_pcs_ops structure.
phylink_replay_link_begin() #
void begin replay of link callbacks for driver which loses state
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Helper for MAC drivers which may perform a destructive reset at runtime.
Both the own driver's mac_link_down() method is called, as well as the
pcs_link_down() method of the split PCS (if any).
This is similar to phylink_stop(), except it does not alter the state of
the phylib PHY (it is assumed that it is not affected by the MAC destructive
reset).
phylink_replay_link_end() #
void end replay of link callbacks for driver which lost state
Parameters
struct phylink *pl: a pointer to astruct phylinkreturned fromphylink_create()
Description
Helper for MAC drivers which may perform a destructive reset at runtime.
Both the own driver's mac_config() and mac_link_up() methods, as well as the
pcs_config() and pcs_link_up() method of the split PCS (if any), are called.
This is similar to phylink_start(), except it does not alter the state of
the phylib PHY.
One must call this method only within the same rtnl_lock() critical section
as a previous phylink_replay_link_start().
SFP support #
struct sfp_bus #
internal representation of a sfp bus
Definition
;
struct sfp_eeprom_id #
raw SFP module identification information
Definition
;
Members
base: base SFP module identification structureext: extended SFP module identification structure
Description
See the SFF-8472 specification and related documents for the definition of these structure members. This can be obtained from https://www.snia.org/technology-communities/sff/specifications
struct sfp_module_caps #
sfp module capabilities
Definition
;
Members
interfaces: bitmap of interfaces that the module may supportlink_modes: bitmap of ethtool link modes that the module may supportmay_have_phy: indicate whether the module may have an ethernet PHY There is no way to be sure that a module has a PHY as the EEPROM doesn't contain this information. When set, this does not mean that the module definitely has a PHY.port: one of ethtoolPORT_*definitions, parsed from the module EEPROM, orPORT_OTHERif the port type is not known.
struct sfp_upstream_ops #
upstream operations structure
Definition
;
Members
attach: called when the sfp socket driver is bound to the upstream (mandatory).detach: called when the sfp socket driver is unbound from the upstream (mandatory).module_insert: called after a module has been detected to determine whether the module is supported for the upstream device.module_remove: called after the module has been removed.module_start: called after the PHY probe stepmodule_stop: called before the PHY is removedlink_down: called when the link is non-operational for whatever reason.link_up: called when the link is operational.connect_phy: called when an I2C accessible PHY has been detected on the module.disconnect_phy: called when a module with an I2C accessible PHY has been removed.
sfp_select_interface() #
phy_interface_t Select appropriate phy_interface_t mode
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp moduleconst unsigned long *link_modes: ethtool link modes mask
Description
Derive the phy_interface_t mode for the SFP module from the link modes mask.
sfp_bus_put() #
void put a reference on the struct sfp_bus
Parameters
struct sfp_bus *bus: thestruct sfp_busfound viasfp_bus_find_fwnode()
Description
Put a reference on the struct sfp_bus and free the underlying structure
if this was the last reference.
sfp_get_module_info() #
int Get the ethtool_modinfo for a SFP module
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp modulestruct ethtool_modinfo *modinfo: astruct ethtool_modinfo
Description
Fill in the type and eeprom_len parameters in modinfo for a module on the sfp bus specified by bus.
Returns 0 on success or a negative errno number.
sfp_get_module_eeprom() #
int Read the SFP module EEPROM
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp modulestruct ethtool_eeprom *ee: astruct ethtool_eepromu8 *data: buffer to contain the EEPROM data (must be at least ee->len bytes)
Description
Read the EEPROM as specified by the supplied ee. See the documentation
for struct ethtool_eeprom for the region to be read.
Returns 0 on success or a negative errno number.
sfp_get_module_eeprom_by_page() #
int Read a page from the SFP module EEPROM
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp moduleconst struct ethtool_module_eeprom *page: astruct ethtool_module_eepromstruct netlink_ext_ack *extack: extack for reporting problems
Description
Read an EEPROM page as specified by the supplied page. See the
documentation for struct ethtool_module_eeprom for the page to be read.
Returns 0 on success or a negative errno number. More error information might be provided via extack
sfp_upstream_start() #
void Inform the SFP that the network device is up
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp module
Description
Inform the SFP socket that the network device is now up, so that the
module can be enabled by allowing TX_DISABLE to be deasserted. This
should be called from the network device driver's struct net_device_ops
ndo_open() method.
sfp_upstream_stop() #
void Inform the SFP that the network device is down
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp module
Description
Inform the SFP socket that the network device is now up, so that the
module can be disabled by asserting TX_DISABLE, disabling the laser
in optical modules. This should be called from the network device
driver's struct net_device_ops ndo_stop() method.
sfp_upstream_set_signal_rate() #
void set data signalling rate
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp moduleunsigned int rate_kbd: signalling rate in units of 1000 baud
Description
Configure the rate select settings on the SFP module for the signalling rate (not the same as the data rate).
- Locks that may be held: Phylink's state_mutex rtnl lock SFP's sm_mutex
sfp_bus_find_fwnode() #
struct sfp_bus * parse and locate the SFP bus from fwnode
Parameters
const struct fwnode_handle *fwnode: firmware node for the parent device (MAC or PHY)
Description
Parse the parent device's firmware node for a SFP bus, and locate
the sfp_bus structure, incrementing its reference count. This must
be put via sfp_bus_put() when done.
- corresponding to the errors detailed for
fwnode_property_get_reference_args(). -ENOMEMif we failed to allocate the bus.- an error from the upstream's
connect_phy()method.
Return
- on success, a pointer to the sfp_bus structure,
NULLif no SFP is specified,- on failure, an error pointer value:
sfp_bus_add_upstream() #
int parse and register the neighbouring device
Parameters
struct sfp_bus *bus: thestruct sfp_busfound viasfp_bus_find_fwnode()void *upstream: the upstream private dataconst struct sfp_upstream_ops *ops: the upstream'sstruct sfp_upstream_ops
Description
Add upstream driver for the SFP bus, and if the bus is complete, register
the SFP bus using sfp_register_upstream(). This takes a reference on the
bus, so it is safe to put the bus after this call.
- corresponding to the errors detailed for
fwnode_property_get_reference_args(). -ENOMEMif we failed to allocate the bus.- an error from the upstream's
connect_phy()method.
Return
- on success, a pointer to the sfp_bus structure,
NULLif no SFP is specified,- on failure, an error pointer value:
sfp_bus_del_upstream() #
void Delete a sfp bus
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp module
Description
Delete a previously registered upstream connection for the SFP
module. bus should have been added by sfp_bus_add_upstream().
sfp_get_name() #
const char * Get the SFP device name
Parameters
struct sfp_bus *bus: a pointer to thestruct sfp_busstructure for the sfp module
Description
Gets the SFP device's name, if bus has a registered socket. Callers must hold RTNL, and the returned name is only valid until RTNL is released.
Return
- The name of the SFP device registered with
sfp_register_socket() NULLif no device was registered on bus