Skip to contentSkip to conversation

Introducing AF_PACKET V4 support

RFC PATCH In review Björn Töpel 9 participants 49 messages Oct 31, 2017 – Nov 17, 2017

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

cover Introducing AF_PACKET V4 support

From: Björn Töpel <[email protected]>

This RFC introduces AF_PACKET_V4 and PACKET_ZEROCOPY that are optimized for high performance packet processing and zero-copy semantics. Throughput improvements can be up to 40x compared to V2 and V3 for the micro benchmarks included. Would be great to get your feedback on it.

The main difference between V4 and V2/V3 is that TX and RX descriptors are separated from packet buffers. An RX or TX descriptor points to a data buffer in a packet buffer area. RX and TX can share the same packet buffer so that a packet does not have to be copied between RX and TX. Moreover, if a packet needs to be kept for a while due to a possible retransmit, then the descriptor that points to that packet buffer can be changed to point to another buffer and reused right away. This again avoids copying data.

The RX and TX descriptor rings are registered with the setsockopts PACKET_RX_RING and PACKET_TX_RING, as usual. The packet buffer area is allocated by user space and registered with the kernel using the new PACKET_MEMREG setsockopt. All these three areas are shared between user space and kernel space.

When V4 executes like this, we say that it executes in "copy-mode". Each packet is sent to the Linux stack and a copy of it is sent to user space, so V4 behaves in the same way as V2 and V3. All syscalls operating on file descriptors should just work as if it was V2 or V3. However, when the new PACKET_ZEROCOPY setsockopt is called, V4 starts to operate in true zero-copy mode. In this mode, the networking HW (or SW driver if it is a virtual driver like veth) DMAs/puts packets straight into the packet buffer that is shared between user space and kernel space. The RX and TX descriptor queues of the networking HW are NOT shared to user space. Only the kernel can read and write these and it is the kernel drivers responsibility to translate these HW specific descriptors to the HW agnostic ones in the V4 virtual descriptor rings that user space sees. This way, a malicious user space program cannot mess with the networking HW.

The PACKET_ZEROCOPY setsockopt acts on a queue pair (channel in ethtool speak), so one needs to steer the traffic to the zero-copy enabled queue pair. Which queue to use, is up to the user.

For an untrusted application, HW packet steering to a specific queue pair (the one associated with the application) is a requirement, as the application would otherwise be able to see other user space processes' packets. If the HW cannot support the required packet steering, packets need to be DMA:ed into non user-space visible kernel buffers and from there copied out to user space. This RFC only addresses NIC HW with packet steering capabilities.

PACKET_ZEROCOPY comes with "XDP batteries included", so XDP programs will be executed for zero-copy enabled queues. We're also suggesting adding a new XDP action, XDP_PASS_TO_KERNEL, to pass copies to the kernel stack instead of the V4 user space queue in zero-copy mode.

There's a tpbench benchmarking/test application included. Say that you'd like your UDP traffic from port 4242 to end up in queue 16, that we'll enable zero-copy on. Here, we use ethtool for this:

ethtool -N p3p2 rx-flow-hash udp4 fn
ethtool -N p3p2 flow-type udp4 src-port 4242 dst-port 4242 \
action 16

Running the benchmark in zero-copy mode can then be done using:

      tpbench -i p3p2 --rxdrop --zerocopy 17

Note that the --zerocopy command-line argument is one-based, and not zero-based.

We've run some benchmarks on a dual socket system with two Broadwell E5 2660 @ 2.0 GHz with hyperthreading turned off. Each socket has 14 cores which gives a total of 28, but only two cores are used in these experiments. One for Tx/Rx and one for the user space application. The memory is DDR4 @ 1067 MT/s and the size of each DIMM is 8192MB and with 8 of those DIMMs in the system we have 64 GB of total memory. The compiler used is gcc version 5.4.0 20160609. The NIC is an Intel I40E 40Gbit/s using the i40e driver.

Below are the results in Mpps of the I40E NIC benchmark runs for 64 byte packets, generated by commercial packet generator HW that is generating packets at full 40 Gbit/s line rate.

Benchmark   V2     V3     V4     V4+ZC
rxdrop      0.67   0.73   0.74   33.7
txpush      0.98   0.98   0.91   19.6
l2fwd       0.66   0.71   0.67   15.5

The results are generated using the "bench_all.sh" script.

We'll do a presentation on AF_PACKET V4 in NetDev 2.2 [1] Seoul, Korea, and our paper with complete benchmarks will be released shortly on the NetDev 2.2 site.

We based this patch set on net-next commit e1ea2f9856b7 ("Merge
git://git.kernel.org/pub/scm/linux/kernel/git/davem/net").

Please focus your review on:

* The V4 user space interface
* PACKET_ZEROCOPY and its semantics
* Packet array interface
* XDP semantics when excuting in zero-copy mode (user space passed buffers)
* XDP_PASS_TO_KERNEL semantics

To do:

* Investigate the user-space ring structure’s performance problems
* Continue the XDP integration into packet arrays
* Optimize performance
* SKB <-> V4 conversions in tp4a_populate & tp4a_flush
* Packet buffer is unnecessarily pinned for virtual devices
* Support shared packet buffers
* Unify V4 and SKB receive path in I40E driver
* Support for packets spanning multiple frames
* Disassociate the packet array implementation from the V4 queue structure

We would really like to thank the reviewers of the limited distribution RFC for all their comments that have helped improve the interfaces and the code significantly: Alexei Starovoitov, Alexander Duyck, Jesper Dangaard Brouer, and John Fastabend. The internal team at Intel that has been helping out reviewing code, writing tests, and sanity checking our ideas: Rami Rosen, Jeff Shaw, Ferruh Yigit, and Qi Zhang, your participation has really helped.

Thanks: Björn and Magnus

[1] https://www.netdevconf.org/2.2/

Björn Töpel (7):
packet: introduce AF_PACKET V4 userspace API
packet: implement PACKET_MEMREG setsockopt
packet: enable AF_PACKET V4 rings
packet: wire up zerocopy for AF_PACKET V4
i40e: AF_PACKET V4 ndo_tp4_zerocopy Rx support
i40e: AF_PACKET V4 ndo_tp4_zerocopy Tx support
samples/tpacket4: added tpbench

Magnus Karlsson (7):
packet: enable Rx for AF_PACKET V4
packet: enable Tx support for AF_PACKET V4
netdevice: add AF_PACKET V4 zerocopy ops
veth: added support for PACKET_ZEROCOPY samples/tpacket4: added veth support
i40e: added XDP support for TP4 enabled queue pairs
xdp: introducing XDP_PASS_TO_KERNEL for PACKET_ZEROCOPY use

 drivers/net/ethernet/intel/i40e/i40e.h         |    3 +
 drivers/net/ethernet/intel/i40e/i40e_ethtool.c |    9 +
 drivers/net/ethernet/intel/i40e/i40e_main.c    |  837 ++++++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.c    |  582 ++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.h    |   38 +
 drivers/net/veth.c                             |  174 +++
 include/linux/netdevice.h                      |   16 +
 include/linux/tpacket4.h                       | 1502 ++++++++++++++++++++++++
 include/uapi/linux/bpf.h                       |    1 +
 include/uapi/linux/if_packet.h                 |   65 +-
 net/packet/af_packet.c                         | 1252 +++++++++++++++++---
 net/packet/internal.h                          |    9 +
 samples/tpacket4/Makefile                      |   12 +
 samples/tpacket4/bench_all.sh                  |   28 +
 samples/tpacket4/tpbench.c                     | 1390 ++++++++++++++++++++++
 15 files changed, 5674 insertions(+), 244 deletions(-)
 create mode 100644 include/linux/tpacket4.h
 create mode 100644 samples/tpacket4/Makefile
 create mode 100755 samples/tpacket4/bench_all.sh
 create mode 100644 samples/tpacket4/tpbench.c
Signature · 1 line
2.11.0
#1 lore raw

RFC PATCH 1/14 packet: introduce AF_PACKET V4 userspace API

From: Björn Töpel <[email protected]>

This patch adds the necessary AF_PACKET V4 structures for usage from userspace. AF_PACKET V4 is a new interface optimized for high performance packet processing.

---
 include/uapi/linux/if_packet.h | 65 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 64 insertions(+), 1 deletion(-)
include/uapi/linux/if_packet.h +64 -1
index 4df96a7dd4fa..8eabcd1b370a 100644
@@ -56,6 +56,8 @@ struct sockaddr_ll {
 #define PACKET_QDISC_BYPASS		20
 #define PACKET_ROLLOVER_STATS		21
 #define PACKET_FANOUT_DATA		22
+#define PACKET_MEMREG			23
+#define PACKET_ZEROCOPY			24
 
 #define PACKET_FANOUT_HASH		0
 #define PACKET_FANOUT_LB		1
@@ -243,13 +245,35 @@ struct tpacket_block_desc {
 	union tpacket_bd_header_u hdr;
 };
 
+#define TP4_DESC_KERNEL	0x0080 /* The descriptor is owned by the kernel */
+#define TP4_PKT_CONT	1 /* The packet continues in the next descriptor */
+
+struct tpacket4_desc {
+	__u32 idx;
+	__u32 len;
+	__u16 offset;
+	__u8  error; /* an errno */
+	__u8  flags;
+	__u8  padding[4];
+};
+
+struct tpacket4_queue {
+	struct tpacket4_desc *ring;
+
+	unsigned int avail_idx;
+	unsigned int last_used_idx;
+	unsigned int num_free;
+	unsigned int ring_mask;
+};
+
 #define TPACKET2_HDRLEN		(TPACKET_ALIGN(sizeof(struct tpacket2_hdr)) + sizeof(struct sockaddr_ll))
 #define TPACKET3_HDRLEN		(TPACKET_ALIGN(sizeof(struct tpacket3_hdr)) + sizeof(struct sockaddr_ll))
 
 enum tpacket_versions {
 	TPACKET_V1,
 	TPACKET_V2,
-	TPACKET_V3
+	TPACKET_V3,
+	TPACKET_V4
 };
 
 /*
@@ -282,9 +306,26 @@ struct tpacket_req3 {
 	unsigned int	tp_feature_req_word;
 };
 
+/* V4 frame structure
+ *
+ * The v4 frame is contained within a frame defined by
+ * PACKET_MEMREG/struct tpacket_memreg_req. Each frame is frame_size
+ * bytes, and laid out as following:
+ *
+ * - Start.
+ * - Gap, at least data_headroom (from struct tpacket_memreg_req),
+ *   chosen so that packet data (Start+data) is at least 64B aligned.
+ */
+
+struct tpacket_req4 {
+	int		mr_fd;	 /* File descriptor for registered buffers */
+	unsigned int	desc_nr; /* Number of entries in descriptor ring */
+};
+
 union tpacket_req_u {
 	struct tpacket_req	req;
 	struct tpacket_req3	req3;
+	struct tpacket_req4	req4;
 };
 
 struct packet_mreq {
@@ -294,6 +335,28 @@ struct packet_mreq {
 	unsigned char	mr_address[8];
 };
 
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *
+ * Corollary: The number of frames that can be stored is
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+	unsigned long	addr;		/* Start of packet data area */
+	unsigned long	len;		/* Length of packet data area */
+	unsigned int	frame_size;	/* Frame size */
+	unsigned int	data_headroom;	/* Frame head room */
+};
+
 #define PACKET_MR_MULTICAST	0
 #define PACKET_MR_PROMISC	1
 #define PACKET_MR_ALLMULTI	2
Signature · 1 line
2.11.0
#14 lore raw

RFC PATCH 2/14 packet: implement PACKET_MEMREG setsockopt

In reply to Björn Töpel

From: Björn Töpel <[email protected]>

Here, the PACKET_MEMREG setsockopt is implemented for the AF_PACKET protocol family. PACKET_MEMREG allows the user to register memory regions that can be used by AF_PACKET V4 as packet data buffers.

---
 include/linux/tpacket4.h | 101 +++++++++++++++++++++++++++++
 net/packet/af_packet.c   | 163 +++++++++++++++++++++++++++++++++++++++++++++++
 net/packet/internal.h    |   4 ++
 3 files changed, 268 insertions(+)
 create mode 100644 include/linux/tpacket4.h
include/linux/tpacket4.h new file +101 -0
new file mode 100644
index 000000000000..fcf4c333c78d
@@ -0,0 +1,101 @@
+/*
+ *  tpacket v4
+ *  Copyright(c) 2017 Intel Corporation.
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms and conditions of the GNU General Public License,
+ * version 2, as published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
+ * more details.
+ */
+
+#ifndef _LINUX_TPACKET4_H
+#define _LINUX_TPACKET4_H
+
+#define TP4_UMEM_MIN_FRAME_SIZE 2048
+#define TP4_KERNEL_HEADROOM 256 /* Headrom for XDP */
+
+struct tp4_umem {
+	struct pid *pid;
+	struct page **pgs;
+	unsigned int npgs;
+	size_t size;
+	unsigned long address;
+	unsigned int frame_size;
+	unsigned int frame_size_log2;
+	unsigned int nframes;
+	unsigned int nfpplog2; /* num frames per page in log2 */
+	unsigned int data_headroom;
+};
+
+/*************** V4 QUEUE OPERATIONS *******************************/
+
+/**
+ * tp4q_umem_new - Creates a new umem (packet buffer)
+ *
+ * @addr: The address to the umem
+ * @size: The size of the umem
+ * @frame_size: The size of each frame, between 2K and PAGE_SIZE
+ * @data_headroom: The desired data headroom before start of the packet
+ *
+ * Returns a pointer to the new umem or NULL for failure
+ **/
+static inline struct tp4_umem *tp4q_umem_new(unsigned long addr, size_t size,
+					     unsigned int frame_size,
+					     unsigned int data_headroom)
+{
+	struct tp4_umem *umem;
+	unsigned int nframes;
+
+	if (frame_size < TP4_UMEM_MIN_FRAME_SIZE || frame_size > PAGE_SIZE) {
+		/* Strictly speaking we could support this, if:
+		 * - huge pages, or*
+		 * - using an IOMMU, or
+		 * - making sure the memory area is consecutive
+		 * but for now, we simply say "computer says no".
+		 */
+		return ERR_PTR(-EINVAL);
+	}
+
+	if (!is_power_of_2(frame_size))
+		return ERR_PTR(-EINVAL);
+
+	if (!PAGE_ALIGNED(addr)) {
+		/* Memory area has to be page size aligned. For
+		 * simplicity, this might change.
+		 */
+		return ERR_PTR(-EINVAL);
+	}
+
+	if ((addr + size) < addr)
+		return ERR_PTR(-EINVAL);
+
+	nframes = size / frame_size;
+	if (nframes == 0)
+		return ERR_PTR(-EINVAL);
+
+	data_headroom =	ALIGN(data_headroom, 64);
+
+	if (frame_size - data_headroom - TP4_KERNEL_HEADROOM < 0)
+		return ERR_PTR(-EINVAL);
+
+	umem = kzalloc(sizeof(*umem), GFP_KERNEL);
+	if (!umem)
+		return ERR_PTR(-ENOMEM);
+
+	umem->pid = get_task_pid(current, PIDTYPE_PID);
+	umem->size = size;
+	umem->address = addr;
+	umem->frame_size = frame_size;
+	umem->frame_size_log2 = ilog2(frame_size);
+	umem->nframes = nframes;
+	umem->nfpplog2 = ilog2(PAGE_SIZE / frame_size);
+	umem->data_headroom = data_headroom;
+
+	return umem;
+}
+
+#endif /* _LINUX_TPACKET4_H */
net/packet/af_packet.c +163 -0

198 lines not on this page · raw message

net/packet/internal.h +4 -0
index 94d1d405a116..9c07cfe1b8a3 100644
@@ -2,6 +2,7 @@
 #define __PACKET_INTERNAL_H__
 
 #include <linux/refcount.h>
+#include <linux/tpacket4.h>
 
 struct packet_mclist {
 	struct packet_mclist	*next;
@@ -109,6 +110,9 @@ struct packet_sock {
 	union  tpacket_stats_u	stats;
 	struct packet_ring_buffer	rx_ring;
 	struct packet_ring_buffer	tx_ring;
+
+	struct tp4_umem			*umem;
+
 	int			copy_thresh;
 	spinlock_t		bind_lock;
 	struct mutex		pg_vec_lock;
Signature · 1 line
2.11.0
#20 lore raw

RFC PATCH 4/14 packet: enable Rx for AF_PACKET V4

In reply to Björn Töpel

From: Magnus Karlsson <[email protected]>

In this commit, ingress support is implemented.

---
 include/linux/tpacket4.h | 361 +++++++++++++++++++++++++++++++++++++++++++++++
 net/packet/af_packet.c   |  83 +++++++----
 2 files changed, 419 insertions(+), 25 deletions(-)
include/linux/tpacket4.h +361 -0
index 44ba38034133..1d4c13d472e5 100644
@@ -191,6 +191,172 @@ static inline struct tp4_umem *tp4q_umem_new(unsigned long addr, size_t size,
 }
 
 /**
+ * tp4q_set_error - Sets an errno on the descriptor
+ *
+ * @desc: Pointer to the descriptor to be manipulated
+ * @errno: The errno number to write to the descriptor
+ **/
+static inline void tp4q_set_error(struct tpacket4_desc *desc,
+				  int errno)
+{
+	desc->error = errno;
+}
+
+/**
+ * tp4q_set_offset - Sets the data offset for the descriptor
+ *
+ * @desc: Pointer to the descriptor to be manipulated
+ * @offset: The data offset to write to the descriptor
+ **/
+static inline void tp4q_set_offset(struct tpacket4_desc *desc,
+				   u16 offset)
+{
+	desc->offset = offset;
+}
+
+/**
+ * tp4q_is_free - Is there a free entry on the queue?
+ *
+ * @q: Pointer to the tp4 queue to examine
+ *
+ * Returns true if there is a free entry, otherwise false
+ **/
+static inline int tp4q_is_free(struct tp4_queue *q)
+{
+	unsigned int idx = q->used_idx & q->ring_mask;
+	unsigned int prev_idx;
+
+	if (!idx)
+		prev_idx = q->ring_mask;
+	else
+		prev_idx = idx - 1;
+
+	/* previous frame is already consumed by userspace
+	 * meaning ring is free
+	 */
+	if (q->ring[prev_idx].flags & TP4_DESC_KERNEL)
+		return 1;
+
+	/* there is some data that userspace can read immediately */
+	return 0;
+}
+
+/**
+ * tp4q_get_data_headroom - How much data headroom does the queue have
+ *
+ * @q: Pointer to the tp4 queue to examine
+ *
+ * Returns the amount of data headroom that has been configured for the
+ * queue
+ **/
+static inline unsigned int tp4q_get_data_headroom(struct tp4_queue *q)
+{
+	return q->umem->data_headroom + TP4_KERNEL_HEADROOM;
+}
+
+/**
+ * tp4q_is_valid_entry - Is the entry valid?
+ *
+ * @q: Pointer to the tp4 queue the descriptor resides in
+ * @desc: Pointer to the descriptor to examine
+ * @validation: The type of validation to perform
+ *
+ * Returns true if the entry is a valid, otherwise false
+ **/
+static inline bool tp4q_is_valid_entry(struct tp4_queue *q,
+				       struct tpacket4_desc *d,
+				       enum tp4_validation validation)
+{
+	if (validation == TP4_VALIDATION_NONE)
+		return true;
+
+	if (unlikely(d->idx >= q->umem->nframes)) {
+		tp4q_set_error(d, EBADF);
+		return false;
+	}
+	if (validation == TP4_VALIDATION_IDX) {
+		tp4q_set_offset(d, tp4q_get_data_headroom(q));
+		return true;
+	}
+
+	/* TP4_VALIDATION_DESC */
+	if (unlikely(d->len > q->umem->frame_size ||
+		     d->len == 0 ||
+		     d->offset > q->umem->frame_size ||
+		     d->offset + d->len > q->umem->frame_size)) {
+		tp4q_set_error(d, EBADF);
+		return false;
+	}
+
+	return true;
+}
+
+/**
+ * tp4q_nb_avail - Returns the number of available entries
+ *
+ * @q: Pointer to the tp4 queue to examine
+ * @dcnt: Max number of entries to check
+ *
+ * Returns the the number of entries available in the queue up to dcnt
+ **/
+static inline int tp4q_nb_avail(struct tp4_queue *q, int dcnt)
+{
+	unsigned int idx, last_avail_idx = q->last_avail_idx;
+	int i, entries = 0;
+
+	for (i = 0; i < dcnt; i++) {
+		idx = (last_avail_idx++) & q->ring_mask;
+		if (!(q->ring[idx].flags & TP4_DESC_KERNEL))
+			break;
+		entries++;
+	}
+
+	return entries;
+}
+
+/**
+ * tp4q_enqueue - Enqueue entries to a tp4 queue
+ *
+ * @q: Pointer to the tp4 queue the descriptor resides in
+ * @d: Pointer to the descriptor to examine
+ * @dcnt: Max number of entries to dequeue
+ *
+ * Returns 0 for success or an errno at failure
+ **/
+static inline int tp4q_enqueue(struct tp4_queue *q,
+			       const struct tpacket4_desc *d, int dcnt)
+{
+	unsigned int used_idx = q->used_idx;
+	int i;
+
+	if (q->num_free < dcnt)
+		return -ENOSPC;
+
+	q->num_free -= dcnt;
+
+	for (i = 0; i < dcnt; i++) {
+		unsigned int idx = (used_idx++) & q->ring_mask;
+
+		q->ring[idx].idx = d[i].idx;
+		q->ring[idx].len = d[i].len;
+		q->ring[idx].offset = d[i].offset;
+		q->ring[idx].error = d[i].error;
+	}
+
+	/* Order flags and data */
+	smp_wmb();
+
+	for (i = dcnt - 1; i >= 0; i--) {
+		unsigned int idx = (q->used_idx + i) & q->ring_mask;
+
+		q->ring[idx].flags = d[i].flags & ~TP4_DESC_KERNEL;
+	}
+	q->used_idx += dcnt;
+
+	return 0;
+}
+
+/**
  * tp4q_enqueue_from_array - Enqueue entries from packet array to tp4 queue
  *
  * @a: Pointer to the packet array to enqueue from
@@ -236,6 +402,45 @@ static inline int tp4q_enqueue_from_array(struct tp4_packet_array *a,
 }
 
 /**
+ * tp4q_dequeue_to_array - Dequeue entries from tp4 queue to packet array
+ *
+ * @a: Pointer to the packet array to dequeue from
+ * @dcnt: Max number of entries to dequeue
+ *
+ * Returns the number of entries dequeued. Non valid entries will be
+ * discarded.
+ **/
+static inline int tp4q_dequeue_to_array(struct tp4_packet_array *a, u32 dcnt)
+{
+	struct tpacket4_desc *d = a->items;
+	int i, entries, valid_entries = 0;
+	struct tp4_queue *q = a->tp4q;
+	u32 start = a->end;
+
+	entries = tp4q_nb_avail(q, dcnt);
+	q->num_free += entries;
+
+	/* Order flags and data */
+	smp_rmb();
+
+	for (i = 0; i < entries; i++) {
+		unsigned int d_idx = start & a->mask;
+		unsigned int idx;
+
+		idx = (q->last_avail_idx++) & q->ring_mask;
+		d[d_idx] = q->ring[idx];
+		if (!tp4q_is_valid_entry(q, &d[d_idx], a->validation)) {
+			WARN_ON_ONCE(tp4q_enqueue(a->tp4q, &d[d_idx], 1));
+			continue;
+		}
+
+		start++;
+		valid_entries++;
+	}
+	return valid_entries;
+}
+
+/**
  * tp4q_disable - Disable a tp4 queue
  *
  * @dev: Pointer to the netdevice the queue is connected to
@@ -309,6 +514,67 @@ static inline int tp4q_enable(struct device *dev,
 	return 0;
 }
 
+/**
+ * tp4q_get_page_offset - Get offset into page frame resides at
+ *
+ * @q: Pointer to the tp4 queue that this frame resides in
+ * @addr: Index of this frame in the packet buffer / umem
+ * @pg: Returns a pointer to the page of this frame
+ * @off: Returns the offset to the page of this frame
+ **/
+static inline void tp4q_get_page_offset(struct tp4_queue *q, u64 addr,
+				       u64 *pg, u64 *off)
+{
+	*pg = addr >> q->umem->nfpplog2;
+	*off = (addr - (*pg << q->umem->nfpplog2))
+	       << q->umem->frame_size_log2;
+}
+
+/**
+ * tp4q_max_data_size - Get the max packet size supported by a queue
+ *
+ * @q: Pointer to the tp4 queue to examine
+ *
+ * Returns the max packet size supported by the queue
+ **/
+static inline unsigned int tp4q_max_data_size(struct tp4_queue *q)
+{
+	return q->umem->frame_size - q->umem->data_headroom -
+		TP4_KERNEL_HEADROOM;
+}
+
+/**
+ * tp4q_get_data - Gets a pointer to the start of the packet
+ *
+ * @q: Pointer to the tp4 queue to examine
+ * @desc: Pointer to descriptor of the packet
+ *
+ * Returns a pointer to the start of the packet the descriptor is pointing
+ * to
+ **/
+static inline void *tp4q_get_data(struct tp4_queue *q,
+				  struct tpacket4_desc *desc)
+{
+	u64 pg, off;
+	u8 *pkt;
+
+	tp4q_get_page_offset(q, desc->idx, &pg, &off);
+	pkt = page_address(q->umem->pgs[pg]);
+	return (u8 *)(pkt + off) + desc->offset;
+}
+
+/**
+ * tp4q_get_desc - Get descriptor associated with frame
+ *
+ * @p: Pointer to the packet to examine
+ *
+ * Returns the descriptor of the current frame of packet p
+ **/
+static inline struct tpacket4_desc *tp4q_get_desc(struct tp4_frame_set *p)
+{
+	return &p->pkt_arr->items[p->curr & p->pkt_arr->mask];
+}
+
 /*************** FRAME OPERATIONS *******************************/
 /* A frame is always just one frame of size frame_size.
  * A frame set is one or more frames.
@@ -331,6 +597,18 @@ static inline bool tp4f_next_frame(struct tp4_frame_set *p)
 }
 
 /**
+ * tp4f_get_data - Gets a pointer to the frame the frame set is on
+ * @p: pointer to the frame set
+ *
+ * Returns a pointer to the data of the frame that the frame set is
+ * pointing to. Note that there might be configured headroom before this
+ **/
+static inline void *tp4f_get_data(struct tp4_frame_set *p)
+{
+	return tp4q_get_data(p->pkt_arr->tp4q, tp4q_get_desc(p));
+}
+
+/**
  * tp4f_set_frame - Sets the properties of a frame
  * @p: pointer to frame
  * @len: the length in bytes of the data in the frame
@@ -443,6 +721,29 @@ static inline bool tp4a_get_flushable_frame_set(struct tp4_packet_array *a,
 }
 
 /**
+ * tp4a_next_frame - Get next frame in array and advance curr pointer
+ * @a: pointer to packet array
+ * @p: supplied pointer to packet structure that is filled in by function
+ *
+ * Returns true if there is a frame, false otherwise. Frame returned in *p.
+ **/
+static inline bool tp4a_next_frame(struct tp4_packet_array *a,
+				   struct tp4_frame_set *p)
+{
+	u32 avail = a->end - a->curr;
+
+	if (avail == 0)
+		return false; /* empty */
+
+	p->pkt_arr = a;
+	p->start = a->curr;
+	p->curr = a->curr;
+	p->end = ++a->curr;
+
+	return true;
+}
+
+/**
  * tp4a_flush - Flush processed packets to associated tp4q
  * @a: pointer to packet array
  *
@@ -489,4 +790,64 @@ static inline void tp4a_free(struct tp4_packet_array *a)
 	kfree(a);
 }
 
+/**
+ * tp4a_get_data_headroom - Returns the data headroom configured for the array
+ * @a: pointer to packet array
+ *
+ * Returns the data headroom configured for the array
+ **/
+static inline unsigned int tp4a_get_data_headroom(struct tp4_packet_array *a)
+{
+	return tp4q_get_data_headroom(a->tp4q);
+}
+
+/**
+ * tp4a_max_data_size - Get the max packet size supported for the array
+ * @a: pointer to packet array
+ *
+ * Returns the maximum size of data that can be put in a frame when headroom
+ * has been accounted for.
+ **/
+static inline unsigned int tp4a_max_data_size(struct tp4_packet_array *a)
+{
+	return tp4q_max_data_size(a->tp4q);
+
+}
+
+/**
+ * tp4a_populate - Populate an array with packets from associated tp4q
+ * @a: pointer to packet array
+ **/
+static inline void tp4a_populate(struct tp4_packet_array *a)
+{
+	u32 cnt, free = a->mask + 1 - (a->end - a->start);
+
+	if (free == 0)
+		return; /* no space! */
+
+	cnt = tp4q_dequeue_to_array(a, free);
+	a->end += cnt;
+}
+
+/**
+ * tp4a_next_frame_populate - Get next frame and populate array if empty
+ * @a: pointer to packet array
+ * @p: supplied pointer to packet structure that is filled in by function
+ *
+ * Returns true if there is a frame, false otherwise. Frame returned in *p.
+ **/
+static inline bool tp4a_next_frame_populate(struct tp4_packet_array *a,
+					    struct tp4_frame_set *p)
+{
+	bool more_frames;
+
+	more_frames = tp4a_next_frame(a, p);
+	if (!more_frames) {
+		tp4a_populate(a);
+		more_frames = tp4a_next_frame(a, p);
+	}
+
+	return more_frames;
+}
+
 #endif /* _LINUX_TPACKET4_H */
net/packet/af_packet.c +58 -25

146 lines not on this page · raw message

Signature · 1 line
2.11.0
#21 lore raw

RFC PATCH 5/14 packet: enable Tx support for AF_PACKET V4

In reply to Björn Töpel

From: Magnus Karlsson <[email protected]>

In this commit AF_PACKET V4 egress support is added.

---
 include/linux/tpacket4.h | 192 +++++++++++++++++++++++++++++++++++++++++++++++
 net/packet/af_packet.c   | 169 ++++++++++++++++++++++++++++++++++++++---
 2 files changed, 350 insertions(+), 11 deletions(-)
include/linux/tpacket4.h +192 -0
index 1d4c13d472e5..ac6c721294e8 100644
@@ -18,6 +18,8 @@
 #define TP4_UMEM_MIN_FRAME_SIZE 2048
 #define TP4_KERNEL_HEADROOM 256 /* Headrom for XDP */
 
+#define TP4A_FRAME_COMPLETED TP4_DESC_KERNEL
+
 enum tp4_validation {
 	TP4_VALIDATION_NONE,	/* No validation is performed */
 	TP4_VALIDATION_IDX,	/* Only address to packet buffer is validated */
@@ -402,6 +404,60 @@ static inline int tp4q_enqueue_from_array(struct tp4_packet_array *a,
 }
 
 /**
+ * tp4q_enqueue_completed_from_array - Enqueue only completed entries
+ *				       from packet array
+ *
+ * @a: Pointer to the packet array to enqueue from
+ * @dcnt: Max number of entries to enqueue
+ *
+ * Returns the number of entries successfully enqueued or a negative errno
+ * at failure.
+ **/
+static inline int tp4q_enqueue_completed_from_array(struct tp4_packet_array *a,
+						    u32 dcnt)
+{
+	struct tp4_queue *q = a->tp4q;
+	unsigned int used_idx = q->used_idx;
+	struct tpacket4_desc *d = a->items;
+	int i, j;
+
+	if (q->num_free < dcnt)
+		return -ENOSPC;
+
+	for (i = 0; i < dcnt; i++) {
+		unsigned int didx = (a->start + i) & a->mask;
+
+		if (d[didx].flags & TP4A_FRAME_COMPLETED) {
+			unsigned int idx = (used_idx++) & q->ring_mask;
+
+			q->ring[idx].idx = d[didx].idx;
+			q->ring[idx].len = d[didx].len;
+			q->ring[idx].offset = d[didx].offset;
+			q->ring[idx].error = d[didx].error;
+		} else {
+			break;
+		}
+	}
+
+	if (i == 0)
+		return 0;
+
+	/* Order flags and data */
+	smp_wmb();
+
+	for (j = i - 1; j >= 0; j--) {
+		unsigned int idx = (q->used_idx + j) & q->ring_mask;
+		unsigned int didx = (a->start + j) & a->mask;
+
+		q->ring[idx].flags = d[didx].flags & ~TP4_DESC_KERNEL;
+	}
+	q->num_free -= i;
+	q->used_idx += i;
+
+	return i;
+}
+
+/**
  * tp4q_dequeue_to_array - Dequeue entries from tp4 queue to packet array
  *
  * @a: Pointer to the packet array to dequeue from
@@ -581,6 +637,15 @@ static inline struct tpacket4_desc *tp4q_get_desc(struct tp4_frame_set *p)
  **/
 
 /**
+ * tp4f_reset - Start to traverse the frames in the set from the beginning
+ * @p: pointer to frame set
+ **/
+static inline void tp4f_reset(struct tp4_frame_set *p)
+{
+	p->curr = p->start;
+}
+
+/**
  * tp4f_next_frame - Go to next frame in frame set
  * @p: pointer to frame set
  *
@@ -597,6 +662,38 @@ static inline bool tp4f_next_frame(struct tp4_frame_set *p)
 }
 
 /**
+ * tp4f_get_frame_id - Get packet buffer id of frame
+ * @p: pointer to frame set
+ *
+ * Returns the id of the packet buffer of the current frame
+ **/
+static inline u64 tp4f_get_frame_id(struct tp4_frame_set *p)
+{
+	return p->pkt_arr->items[p->curr & p->pkt_arr->mask].idx;
+}
+
+/**
+ * tp4f_get_frame_len - Get length of data in current frame
+ * @p: pointer to frame set
+ *
+ * Returns the length of data in the packet buffer of the current frame
+ **/
+static inline u32 tp4f_get_frame_len(struct tp4_frame_set *p)
+{
+	return p->pkt_arr->items[p->curr & p->pkt_arr->mask].len;
+}
+
+/**
+ * tp4f_set_error - Set an error on the current frame
+ * @p: pointer to frame set
+ * @errno: the errno to be assigned
+ **/
+static inline void tp4f_set_error(struct tp4_frame_set *p, int errno)
+{
+	p->pkt_arr->items[p->curr & p->pkt_arr->mask].error = errno;
+}
+
+/**
  * tp4f_get_data - Gets a pointer to the frame the frame set is on
  * @p: pointer to the frame set
  *
@@ -627,6 +724,48 @@ static inline void tp4f_set_frame(struct tp4_frame_set *p, u32 len, u16 offset,
 		d->flags |= TP4_PKT_CONT;
 }
 
+/*************** PACKET OPERATIONS *******************************/
+/* A packet consists of one or more frames. Both frames and packets
+ * are represented by a tp4_frame_set. The only difference is that
+ * packet functions look at the EOP flag.
+ **/
+
+/**
+ * tp4f_get_packet_len - Length of packet
+ * @p: pointer to packet
+ *
+ * Returns the length of the packet in bytes.
+ * Resets curr pointer of packet.
+ **/
+static inline u32 tp4f_get_packet_len(struct tp4_frame_set *p)
+{
+	u32 len = 0;
+
+	tp4f_reset(p);
+
+	do {
+		len += tp4f_get_frame_len(p);
+	} while (tp4f_next_frame(p));
+
+	return len;
+}
+
+/**
+ * tp4f_packet_completed - Mark packet as completed
+ * @p: pointer to packet
+ *
+ * Resets curr pointer of packet.
+ **/
+static inline void tp4f_packet_completed(struct tp4_frame_set *p)
+{
+	tp4f_reset(p);
+
+	do {
+		p->pkt_arr->items[p->curr & p->pkt_arr->mask].flags |=
+			TP4A_FRAME_COMPLETED;
+	} while (tp4f_next_frame(p));
+}
+
 /**************** PACKET_ARRAY FUNCTIONS ********************************/
 
 static inline struct tp4_packet_array *__tp4a_new(
@@ -815,6 +954,59 @@ static inline unsigned int tp4a_max_data_size(struct tp4_packet_array *a)
 }
 
 /**
+ * tp4a_next_packet - Get next packet in array and advance curr pointer
+ * @a: pointer to packet array
+ * @p: supplied pointer to packet structure that is filled in by function
+ *
+ * Returns true if there is a packet, false otherwise. Packet returned in *p.
+ **/
+static inline bool tp4a_next_packet(struct tp4_packet_array *a,
+				    struct tp4_frame_set *p)
+{
+	u32 avail = a->end - a->curr;
+
+	if (avail == 0)
+		return false; /* empty */
+
+	p->pkt_arr = a;
+	p->start = a->curr;
+	p->curr = a->curr;
+	p->end = a->curr;
+
+	/* XXX Sanity check for too-many-frames packets? */
+	while (a->items[p->end++ & a->mask].flags & TP4_PKT_CONT) {
+		avail--;
+		if (avail == 0)
+			return false;
+	}
+
+	a->curr += (p->end - p->start);
+	return true;
+}
+
+/**
+ * tp4a_flush_completed - Flushes only frames marked as completed
+ * @a: pointer to packet array
+ *
+ * Returns 0 for success and -1 for failure
+ **/
+static inline int tp4a_flush_completed(struct tp4_packet_array *a)
+{
+	u32 avail = a->curr - a->start;
+	int ret;
+
+	if (avail == 0)
+		return 0; /* nothing to flush */
+
+	ret = tp4q_enqueue_completed_from_array(a, avail);
+	if (ret < 0)
+		return -1;
+
+	a->start += ret;
+	return 0;
+}
+
+/**
  * tp4a_populate - Populate an array with packets from associated tp4q
  * @a: pointer to packet array
  **/
net/packet/af_packet.c +158 -11

213 lines not on this page · raw message

Signature · 1 line
2.11.0
#22 lore raw

RFC PATCH 6/14 netdevice: add AF_PACKET V4 zerocopy ops

In reply to Björn Töpel

From: Magnus Karlsson <[email protected]>

Two new ndo ops are added. One for enabling/disabling AF_PACKET V4 zerocopy, and one for kicking the egress ring.

---
 include/linux/netdevice.h | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
include/linux/netdevice.h +16 -0
index 5e02f79b2110..1421206bf243 100644
@@ -833,6 +833,8 @@ struct dev_ifalias {
 	char ifalias[];
 };
 
+struct tp4_netdev_parms;
+
 /*
  * This structure defines the management hooks for network devices.
  * The following hooks can be defined; unless noted otherwise, they are
@@ -1133,6 +1135,15 @@ struct dev_ifalias {
  * void (*ndo_xdp_flush)(struct net_device *dev);
  *	This function is used to inform the driver to flush a particular
  *	xdp tx queue. Must be called on same CPU as xdp_xmit.
+ * int (*ndo_tp4_zerocopy)(struct net_device *dev,
+ *			   struct tp4_netdev_parms *parms);
+ *	This function is used to enable and disable the AF_PACKET V4
+ *	PACKET_ZEROCOPY support. See definition of enum tp4_netdev_command
+ *	in tpacket4.h for details.
+ * int (*ndo_tp4_xmit)(struct net_device *dev, int queue_pair);
+ *	This function is used to send packets when the PACKET_ZEROCOPY
+ *	option is set. The rtnl lock is not held when entering this
+ *	function.
  */
 struct net_device_ops {
 	int			(*ndo_init)(struct net_device *dev);
@@ -1320,6 +1331,11 @@ struct net_device_ops {
 	int			(*ndo_xdp_xmit)(struct net_device *dev,
 						struct xdp_buff *xdp);
 	void			(*ndo_xdp_flush)(struct net_device *dev);
+	int                     (*ndo_tp4_zerocopy)(
+					struct net_device *dev,
+					struct tp4_netdev_parms *parms);
+	int                     (*ndo_tp4_xmit)(struct net_device *dev,
+						int queue_pair);
 };
 
 /**
Signature · 1 line
2.11.0
#23 lore raw

RFC PATCH 7/14 packet: wire up zerocopy for AF_PACKET V4

In reply to Björn Töpel

From: Björn Töpel <[email protected]>

This commits adds support for zerocopy mode. Note that zerocopy mode requires that the network interface has been bound to the socket using the bind syscall, and that the corresponding netdev implements the AF_PACKET V4 ndos.

---
 include/linux/tpacket4.h |  38 +++++
 net/packet/af_packet.c   | 399 +++++++++++++++++++++++++++++++++++++++++++----
 net/packet/internal.h    |   1 +
 3 files changed, 404 insertions(+), 34 deletions(-)
include/linux/tpacket4.h +38 -0
index ac6c721294e8..839485108b2d 100644
@@ -105,6 +105,44 @@ struct tp4_frame_set {
 	u32 end;
 };
 
+enum tp4_netdev_command {
+	/* Enable the AF_PACKET V4 zerocopy support. When this is enabled,
+	 * packets will arrive to the socket without being copied resulting
+	 * in better performance. Note that this also means that no packets
+	 * are sent to the kernel stack after this feature has been enabled.
+	 */
+	TP4_ENABLE,
+	/* Disables the PACKET_ZEROCOPY support. */
+	TP4_DISABLE,
+};
+
+/**
+ * struct tp4_netdev_parms - TP4 netdev parameters for configuration
+ *
+ * @command: netdev command, currently enable or disable
+ * @rx_opaque: an opaque pointer to the rx queue
+ * @tx_opaque: an opaque pointer to the tx queue
+ * @data_ready: function to be called when data is ready in poll mode
+ * @data_ready_opauqe: opaque parameter returned with data_ready
+ * @write_space: called when data needs to be transmitted in poll mode
+ * @write_space_opaque: opaque parameter returned with write_space
+ * @error_report: called when there is an error
+ * @error_report_opaque: opaque parameter returned in error_report
+ * @queue_pair: the queue_pair associated with this zero-copy operation
+ **/
+struct tp4_netdev_parms {
+	enum tp4_netdev_command command;
+	void *rx_opaque;
+	void *tx_opaque;
+	void (*data_ready)(void *);
+	void *data_ready_opaque;
+	void (*write_space)(void *);
+	void *write_space_opaque;
+	void (*error_report)(void *, int);
+	void *error_report_opaque;
+	int queue_pair;
+};
+
 /*************** V4 QUEUE OPERATIONS *******************************/
 
 /**
net/packet/af_packet.c +365 -34

499 lines not on this page · raw message

net/packet/internal.h +1 -0
index 3eedab29e4d7..1551cbe7b47b 100644
@@ -116,6 +116,7 @@ struct packet_sock {
 	struct packet_ring_buffer	tx_ring;
 
 	struct tp4_umem			*umem;
+	struct tp4_netdev_parms __rcu	*zc;
 
 	int			copy_thresh;
 	spinlock_t		bind_lock;
Signature · 1 line
2.11.0
#26 lore raw

RFC PATCH 8/14 i40e: AF_PACKET V4 ndo_tp4_zerocopy Rx support

In reply to Björn Töpel

From: Björn Töpel <[email protected]>

This commit adds an implementation for ndo_tp4_zerocopy.

When an AF_PACKET V4 socket enables zerocopy, it will trigger the ndo_tp4_zerocopy implementation. The selected queue pair is disabled, TP4 mode is enabled and the queue pair is re-enabled.

Instead of allocating buffers from the page allocator, buffers from the userland TP4 socket are used. The i40e_alloc_rx_buffers_tp4 function does the allocation.

Pulling buffers from the hardware descriptor queue, validation and passing descriptor to userland is done in i40e_clean_rx_tp4_irq.

Common code for updating stats in i40e_clean_rx_irq and i40e_clean_rx_tp4_irq has been refactored out into a function.

As Rx allocation, descriptor configuration and hardware descriptor ring clean up now has multiple implementations, a couple of new members has been introduced into the struct i40e_ring. Two function pointers, one for Rx buffer allocation, and one for Rx clean up. The i40e_ring also contains some Rx descriptor configuration parameters (rx_buf_len and rx_max_frame), since each Rx ring potentionally can have different configuration. This also opens up for future 16B descriptor usage for TP4 rings.

The TP4 implementation does not use the struct i40e_rx_buffer to track hardware descriptor metadata, but instead uses the packet array directly from tpacket4.h.

All TP4 state is kept in the struct i40e_ring. However, to support that a zerocopy context can survive a soft reset, e.g. when changing the number of queue pairs via ethtool, functionality for storing the TP4 context in the vsi is required. When a soft reset is done, we store the TP4 state in the vsi. The vsi rings are tore down, and when setting the rings up again, the TP4 state from vsi is restored.

---
 drivers/net/ethernet/intel/i40e/i40e.h         |   3 +
 drivers/net/ethernet/intel/i40e/i40e_ethtool.c |   9 +
 drivers/net/ethernet/intel/i40e/i40e_main.c    | 751 ++++++++++++++++++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.c    | 196 ++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.h    |  34 ++
 include/linux/tpacket4.h                       |  85 +++
 6 files changed, 1033 insertions(+), 45 deletions(-)
drivers/net/ethernet/intel/i40e/i40e.h +3 -0
index eb017763646d..56dff7d314c4 100644
@@ -744,6 +744,9 @@ struct i40e_vsi {
 
 	/* VSI specific handlers */
 	irqreturn_t (*irq_handler)(int irq, void *data);
+
+	struct i40e_tp4_ctx **tp4_ctxs; /* Rx context */
+	u16 num_tp4_ctxs;
 } ____cacheline_internodealigned_in_smp;
 
 struct i40e_netdev_priv {
drivers/net/ethernet/intel/i40e/i40e_ethtool.c +9 -0
index 9eb618799a30..da64776108c6 100644
@@ -1515,6 +1515,15 @@ static int i40e_set_ringparam(struct net_device *netdev,
 		goto done;
 	}
 
+	for (i = 0; i < vsi->num_queue_pairs; i++) {
+		if (ring_uses_tp4(vsi->rx_rings[i])) {
+			netdev_warn(netdev,
+				    "FIXME TP4 zerocopy does not support changing descriptors. Take down the interface first\n");
+			err = -ENOTSUPP;
+			goto done;
+		}
+	}
+
 	/* We can't just free everything and then setup again,
 	 * because the ISRs in MSI-X mode get passed pointers
 	 * to the Tx and Rx ring structs.
drivers/net/ethernet/intel/i40e/i40e_main.c +730 -21

853 lines not on this page · raw message

drivers/net/ethernet/intel/i40e/i40e_txrx.c +172 -24

256 lines not on this page · raw message

drivers/net/ethernet/intel/i40e/i40e_txrx.h +34 -0
index fbae1182e2ea..602dcd111938 100644
@@ -27,6 +27,8 @@
 #ifndef _I40E_TXRX_H_
 #define _I40E_TXRX_H_
 
+#include <linux/tpacket4.h>
+
 /* Interrupt Throttling and Rate Limiting Goodies */
 
 #define I40E_MAX_ITR               0x0FF0  /* reg uses 2 usec resolution */
@@ -347,6 +349,14 @@ enum i40e_ring_state_t {
 	__I40E_RING_STATE_NBITS /* must be last */
 };
 
+struct i40e_tp4_ctx {
+	struct tp4_packet_array *arr;
+	void (*ev_handler)(void *);
+	void *ev_opaque;
+	void (*err_handler)(void *, int);
+	void *err_opaque;
+};
+
 /* some useful defines for virtchannel interface, which
  * is the only remaining user of header split
  */
@@ -385,6 +395,7 @@ struct i40e_ring {
 	u16 count;			/* Number of descriptors */
 	u16 reg_idx;			/* HW register index of the ring */
 	u16 rx_buf_len;
+	u16 rx_max_frame;
 
 	/* used in interrupt processing */
 	u16 next_to_use;
@@ -401,6 +412,7 @@ struct i40e_ring {
 #define I40E_TXR_FLAGS_WB_ON_ITR		BIT(0)
 #define I40E_RXR_FLAGS_BUILD_SKB_ENABLED	BIT(1)
 #define I40E_TXR_FLAGS_XDP			BIT(2)
+#define I40E_R_FLAGS_TP4			BIT(3)
 
 	/* stats structs */
 	struct i40e_queue_stats	stats;
@@ -428,6 +440,10 @@ struct i40e_ring {
 					 */
 
 	struct i40e_channel *ch;
+
+	bool (*rx_alloc_fn)(struct i40e_ring *rxr, u16 cleaned_count);
+	int (*clean_irq)(struct i40e_ring *ring, int budget);
+	struct i40e_tp4_ctx tp4;
 } ____cacheline_internodealigned_in_smp;
 
 static inline bool ring_uses_build_skb(struct i40e_ring *ring)
@@ -455,6 +471,21 @@ static inline void set_ring_xdp(struct i40e_ring *ring)
 	ring->flags |= I40E_TXR_FLAGS_XDP;
 }
 
+static inline bool ring_uses_tp4(struct i40e_ring *ring)
+{
+	return !!(ring->flags & I40E_R_FLAGS_TP4);
+}
+
+static inline void set_ring_tp4(struct i40e_ring *ring)
+{
+	ring->flags |= I40E_R_FLAGS_TP4;
+}
+
+static inline void clear_ring_tp4(struct i40e_ring *ring)
+{
+	ring->flags &= ~I40E_R_FLAGS_TP4;
+}
+
 enum i40e_latency_range {
 	I40E_LOWEST_LATENCY = 0,
 	I40E_LOW_LATENCY = 1,
@@ -488,6 +519,9 @@ static inline unsigned int i40e_rx_pg_order(struct i40e_ring *ring)
 #define i40e_rx_pg_size(_ring) (PAGE_SIZE << i40e_rx_pg_order(_ring))
 
 bool i40e_alloc_rx_buffers(struct i40e_ring *rxr, u16 cleaned_count);
+int i40e_clean_rx_irq(struct i40e_ring *rxr, int budget);
+bool i40e_alloc_rx_buffers_tp4(struct i40e_ring *rxr, u16 cleaned_count);
+int i40e_clean_rx_tp4_irq(struct i40e_ring *rxr, int budget);
 netdev_tx_t i40e_lan_xmit_frame(struct sk_buff *skb, struct net_device *netdev);
 void i40e_clean_tx_ring(struct i40e_ring *tx_ring);
 void i40e_clean_rx_ring(struct i40e_ring *rx_ring);
include/linux/tpacket4.h +85 -0

109 lines not on this page · raw message

Signature · 1 line
2.11.0
#27 lore raw

RFC PATCH 9/14 i40e: AF_PACKET V4 ndo_tp4_zerocopy Tx support

In reply to Björn Töpel

From: Björn Töpel <[email protected]>

Here, egress support for TP4 is added, and hence implementing ndo_tp4_xmit. The ndo_tp4_xmit simply kicks the NAPI context.

In the NAPI poll, pulling egress frames from userland, posting the frames to the hardware descriptor queue and clearing completed frames from the egress hardware descriptor ring is done.

The clean_irq i40e_ring member is extended to include the Tx ring clean up as well, resulting in some function signature changes for i40e_clean_tx_irq.

As in the Rx case, we're not using i40e_tx_buffer for storing metadata.

---
 drivers/net/ethernet/intel/i40e/i40e.h      |   2 +-
 drivers/net/ethernet/intel/i40e/i40e_main.c |  98 +++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.c | 266 +++++++++++++++++++++++++---
 drivers/net/ethernet/intel/i40e/i40e_txrx.h |   4 +
 include/linux/tpacket4.h                    |  34 ++++
 5 files changed, 373 insertions(+), 31 deletions(-)
drivers/net/ethernet/intel/i40e/i40e.h +1 -1
index 56dff7d314c4..b33b64b87725 100644
@@ -745,7 +745,7 @@ struct i40e_vsi {
 	/* VSI specific handlers */
 	irqreturn_t (*irq_handler)(int irq, void *data);
 
-	struct i40e_tp4_ctx **tp4_ctxs; /* Rx context */
+	struct i40e_tp4_ctx **tp4_ctxs; /* Rx, Tx context */
 	u16 num_tp4_ctxs;
 } ____cacheline_internodealigned_in_smp;
 
drivers/net/ethernet/intel/i40e/i40e_main.c +92 -6

193 lines not on this page · raw message

drivers/net/ethernet/intel/i40e/i40e_txrx.c +242 -24

310 lines not on this page · raw message

drivers/net/ethernet/intel/i40e/i40e_txrx.h +4 -0
index 602dcd111938..b50215ddabd1 100644
@@ -430,6 +430,7 @@ struct i40e_ring {
 
 	struct rcu_head rcu;		/* to avoid race on free */
 	u16 next_to_alloc;
+	int tp4_xmit;
 	struct sk_buff *skb;		/* When i40e_clean_rx_ring_irq() must
 					 * return before it sees the EOP for
 					 * the current packet, we save that skb
@@ -520,9 +521,12 @@ static inline unsigned int i40e_rx_pg_order(struct i40e_ring *ring)
 
 bool i40e_alloc_rx_buffers(struct i40e_ring *rxr, u16 cleaned_count);
 int i40e_clean_rx_irq(struct i40e_ring *rxr, int budget);
+int i40e_clean_tx_irq(struct i40e_ring *tx_ring, int napi_budget);
 bool i40e_alloc_rx_buffers_tp4(struct i40e_ring *rxr, u16 cleaned_count);
 int i40e_clean_rx_tp4_irq(struct i40e_ring *rxr, int budget);
+int i40e_clean_tx_tp4_irq(struct i40e_ring *txr, int napi_budget);
 netdev_tx_t i40e_lan_xmit_frame(struct sk_buff *skb, struct net_device *netdev);
+int i40e_tp4_xmit(struct net_device *dev, int queue_pair);
 void i40e_clean_tx_ring(struct i40e_ring *tx_ring);
 void i40e_clean_rx_ring(struct i40e_ring *rx_ring);
 int i40e_setup_tx_descriptors(struct i40e_ring *tx_ring);
include/linux/tpacket4.h +34 -0
index 80bc20543599..beaf23f713eb 100644
@@ -757,6 +757,28 @@ static inline void tp4f_set_error(struct tp4_frame_set *p, int errno)
 }
 
 /**
+ * tp4f_is_last_frame - Is this the last frame of the frame set
+ * @p: pointer to frame set
+ *
+ * Returns true if this is the last frame of the frame set, otherwise 0
+ **/
+static inline bool tp4f_is_last_frame(struct tp4_frame_set *p)
+{
+	return p->curr + 1 == p->end;
+}
+
+/**
+ * tp4f_num_frames - Number of frames in a frame set
+ * @p: pointer to frame set
+ *
+ * Returns the number of frames this frame set consists of
+ **/
+static inline u32 tp4f_num_frames(struct tp4_frame_set *p)
+{
+	return p->end - p->start;
+}
+
+/**
  * tp4f_get_data - Gets a pointer to the frame the frame set is on
  * @p: pointer to the frame set
  *
@@ -1165,4 +1187,16 @@ static inline bool tp4a_next_frame_populate(struct tp4_packet_array *a,
 	return more_frames;
 }
 
+/**
+ * tp4a_return_packet - Return packet to the packet array
+ *
+ * @a: pointer to packet array
+ * @p: pointer to the packet to return
+ **/
+static inline void tp4a_return_packet(struct tp4_packet_array *a,
+				      struct tp4_frame_set *p)
+{
+	a->curr = p->start;
+}
+
 #endif /* _LINUX_TPACKET4_H */
Signature · 1 line
2.11.0
#28 lore raw

RFC PATCH 10/14 samples/tpacket4: added tpbench

In reply to Björn Töpel

From: Björn Töpel <[email protected]>

The tpbench program is benchmarking TPACKET_V2 up to TPACKET_V4. There's a bench_all.sh script that makes testing all versions easier.

Note that zero-copy means binding the TPACKET_V4 socket to a certain NIC hardware queue, so you'll need to steer your traffic to a certain NIC hardware queue. Say that you'd like your UDP traffic from port 4242 to end up in queue 16. Here, we use ethtool for this:

  ethtool -N p3p2 rx-flow-hash udp4 fn
  ethtool -N p3p2 flow-type udp4 src-port 4242 dst-port 4242 \
      action 16

running the benchmark in zero-copy mode can then be done using:

  taskset -c 16 ./tpbench -i p3p2 --rxdrop --zerocopy 17

Note that the queue is one-based and not zero-based.

---
 samples/tpacket4/Makefile     |   12 +
 samples/tpacket4/bench_all.sh |   28 +
 samples/tpacket4/tpbench.c    | 1253 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 1293 insertions(+)
 create mode 100644 samples/tpacket4/Makefile
 create mode 100755 samples/tpacket4/bench_all.sh
 create mode 100644 samples/tpacket4/tpbench.c
samples/tpacket4/Makefile new file +12 -0
new file mode 100644
index 000000000000..1dd731ffe3e9
@@ -0,0 +1,12 @@
+# kbuild trick to avoid linker error. Can be omitted if a module is built.
+obj- := dummy.o
+
+# List of programs to build
+hostprogs-y := tpbench
+
+# Tell kbuild to always build the programs
+always := $(hostprogs-y)
+
+HOSTCFLAGS_tpbench.o += -I$(objtree)/usr/include
+
+all: tpbench
samples/tpacket4/bench_all.sh new file +28 -0
new file mode 100755
index 000000000000..8d7ee17e1682
@@ -0,0 +1,28 @@
+#!/bin/bash
+
+DIR=`dirname "${BASH_SOURCE[0]}"`
+
+IF=p3p2
+DURATION=60
+CORE=14
+ZC=17
+
+echo "You might want to change the parameters in ${BASH_SOURCE[0]}"
+echo "${IF} cpu${CORE} duration ${DURATION}s zc ${ZC}"
+
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=2 --rxdrop
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=3 --rxdrop
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=4 --rxdrop
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=4 --rxdrop --zerocopy ${ZC}
+
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=2 --txonly
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=3 --txonly
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=4 --txonly
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=4 --txonly --zerocopy ${ZC}
+
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=2 --l2fwd
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=3 --l2fwd
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=4 --l2fwd
+sudo taskset -c ${CORE} timeout -s int ${DURATION} ${DIR}/tpbench -i ${IF} --version=4 --l2fwd --zerocopy ${ZC}
+
+
samples/tpacket4/tpbench.c new file +1253 -0

1,253 lines not on this page · raw message

Signature · 1 line
2.11.0
#29 lore raw

RFC PATCH 11/14 veth: added support for PACKET_ZEROCOPY

In reply to Björn Töpel

From: Magnus Karlsson <[email protected]>

Add AF_PACKET V4 zerocopy support for the veth driver.

---
 drivers/net/veth.c       | 172 +++++++++++++++++++++++++++++++++++++++++++++++
 include/linux/tpacket4.h | 131 ++++++++++++++++++++++++++++++++++++
 2 files changed, 303 insertions(+)
drivers/net/veth.c +172 -0
index f5438d0978ca..3dfb5fb89460 100644
@@ -19,6 +19,7 @@
 #include <net/xfrm.h>
 #include <linux/veth.h>
 #include <linux/module.h>
+#include <linux/tpacket4.h>
 
 #define DRV_NAME	"veth"
 #define DRV_VERSION	"1.0"
@@ -33,6 +34,10 @@ struct veth_priv {
 	struct net_device __rcu	*peer;
 	atomic64_t		dropped;
 	unsigned		requested_headroom;
+	struct tp4_packet_array *tp4a_rx;
+	struct tp4_packet_array *tp4a_tx;
+	struct napi_struct      *napi;
+	bool                    tp4_zerocopy;
 };
 
 /*
@@ -104,6 +109,12 @@ static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
 	struct net_device *rcv;
 	int length = skb->len;
 
+	/* Drop packets from stack if we are in zerocopy mode. */
+	if (unlikely(priv->tp4_zerocopy)) {
+		consume_skb(skb);
+		return NETDEV_TX_OK;
+	}
+
 	rcu_read_lock();
 	rcv = rcu_dereference(priv->peer);
 	if (unlikely(!rcv)) {
@@ -126,6 +137,64 @@ static netdev_tx_t veth_xmit(struct sk_buff *skb, struct net_device *dev)
 	return NETDEV_TX_OK;
 }
 
+static int veth_tp4_xmit(struct net_device *netdev, int queue_pair)
+{
+	struct veth_priv *priv = netdev_priv(netdev);
+
+	local_bh_disable();
+	napi_schedule(priv->napi);
+	local_bh_enable();
+
+	return NETDEV_TX_OK;
+}
+
+static int veth_napi_poll(struct napi_struct *napi, int budget)
+{
+	struct net_device *netdev = napi->dev;
+	struct pcpu_vstats *stats = this_cpu_ptr(netdev->vstats);
+	struct veth_priv *priv_rcv, *priv = netdev_priv(netdev);
+	struct tp4_packet_array *tp4a_tx = priv->tp4a_tx;
+	struct tp4_packet_array *tp4a_rx;
+	struct net_device *rcv;
+	int npackets = 0;
+	int length = 0;
+
+	rcu_read_lock();
+	rcv = rcu_dereference(priv->peer);
+	if (unlikely(!rcv))
+		goto exit;
+
+	priv_rcv = netdev_priv(rcv);
+	if (unlikely(!priv_rcv->tp4_zerocopy))
+		goto exit;
+
+	/* To make sure we do not read the tp4_queue pointers
+	 * before the other process has enabled zerocopy
+	 */
+	smp_rmb();
+
+	tp4a_rx = priv_rcv->tp4a_rx;
+
+	tp4a_populate(tp4a_tx);
+	tp4a_populate(tp4a_rx);
+
+	npackets = tp4a_copy(tp4a_rx, tp4a_tx, &length);
+
+	WARN_ON_ONCE(tp4a_flush(tp4a_tx));
+	WARN_ON_ONCE(tp4a_flush(tp4a_rx));
+
+	u64_stats_update_begin(&stats->syncp);
+	stats->bytes += length;
+	stats->packets += npackets;
+	u64_stats_update_end(&stats->syncp);
+
+exit:
+	rcu_read_unlock();
+	if (npackets < NAPI_POLL_WEIGHT)
+		napi_complete_done(priv->napi, 0);
+	return npackets;
+}
+
 /*
  * general routines
  */
@@ -276,6 +345,105 @@ static void veth_set_rx_headroom(struct net_device *dev, int new_hr)
 	rcu_read_unlock();
 }
 
+static int veth_tp4_disable(struct net_device *netdev,
+			    struct tp4_netdev_parms *params)
+{
+	struct veth_priv *priv_rcv, *priv = netdev_priv(netdev);
+	struct net_device *rcv;
+
+	if (!priv->tp4_zerocopy)
+		return 0;
+	priv->tp4_zerocopy = false;
+
+	/* Make sure other process sees zero copy as off before starting
+	 * to turn things off
+	 */
+	smp_wmb();
+
+	napi_disable(priv->napi);
+	netif_napi_del(priv->napi);
+
+	rcu_read_lock();
+	rcv = rcu_dereference(priv->peer);
+	if (!rcv) {
+		WARN_ON(!rcv);
+		goto exit;
+	}
+	priv_rcv = netdev_priv(rcv);
+
+	if (priv_rcv->tp4_zerocopy) {
+		/* Wait for other thread to complete
+		 * before removing tp4 queues
+		 */
+		napi_synchronize(priv_rcv->napi);
+	}
+exit:
+	rcu_read_unlock();
+
+	tp4a_free(priv->tp4a_rx);
+	tp4a_free(priv->tp4a_tx);
+	kfree(priv->napi);
+
+	return 0;
+}
+
+static int veth_tp4_enable(struct net_device *netdev,
+			   struct tp4_netdev_parms *params)
+{
+	struct veth_priv *priv = netdev_priv(netdev);
+	int err;
+
+	priv->napi = kzalloc(sizeof(*priv->napi), GFP_KERNEL);
+	if (!priv->napi)
+		return -ENOMEM;
+
+	netif_napi_add(netdev, priv->napi, veth_napi_poll,
+		       NAPI_POLL_WEIGHT);
+
+	priv->tp4a_rx = tp4a_rx_new(params->rx_opaque, NAPI_POLL_WEIGHT, NULL);
+	if (!priv->tp4a_rx) {
+		err = -ENOMEM;
+		goto rxa_err;
+	}
+
+	priv->tp4a_tx = tp4a_tx_new(params->tx_opaque, NAPI_POLL_WEIGHT, NULL);
+	if (!priv->tp4a_tx) {
+		err = -ENOMEM;
+		goto txa_err;
+	}
+
+	/* Make sure other process sees queues initialized before enabling
+	 * zerocopy mode
+	 */
+	smp_wmb();
+	priv->tp4_zerocopy = true;
+	napi_enable(priv->napi);
+
+	return 0;
+
+txa_err:
+	tp4a_free(priv->tp4a_rx);
+rxa_err:
+	netif_napi_del(priv->napi);
+	kfree(priv->napi);
+	return err;
+}
+
+static int veth_tp4_zerocopy(struct net_device *netdev,
+			     struct tp4_netdev_parms *params)
+{
+	switch (params->command) {
+	case TP4_ENABLE:
+		return veth_tp4_enable(netdev, params);
+
+	case TP4_DISABLE:
+		return veth_tp4_disable(netdev, params);
+
+	default:
+		return -ENOTSUPP;
+	}
+}
+
 static const struct net_device_ops veth_netdev_ops = {
 	.ndo_init            = veth_dev_init,
 	.ndo_open            = veth_open,
@@ -290,6 +458,8 @@ static const struct net_device_ops veth_netdev_ops = {
 	.ndo_get_iflink		= veth_get_iflink,
 	.ndo_features_check	= passthru_features_check,
 	.ndo_set_rx_headroom	= veth_set_rx_headroom,
+	.ndo_tp4_zerocopy	= veth_tp4_zerocopy,
+	.ndo_tp4_xmit           = veth_tp4_xmit,
 };
 
 #define VETH_FEATURES (NETIF_F_SG | NETIF_F_FRAGLIST | NETIF_F_HW_CSUM | \
@@ -449,9 +619,11 @@ static int veth_newlink(struct net *src_net, struct net_device *dev,
 
 	priv = netdev_priv(dev);
 	rcu_assign_pointer(priv->peer, peer);
+	priv->tp4_zerocopy = false;
 
 	priv = netdev_priv(peer);
 	rcu_assign_pointer(priv->peer, dev);
+	priv->tp4_zerocopy = false;
 	return 0;
 
 err_register_dev:
include/linux/tpacket4.h +131 -0

143 lines not on this page · raw message

Signature · 1 line
2.11.0
#30 lore raw

RFC PATCH 12/14 samples/tpacket4: added veth support

In reply to Björn Töpel

From: Magnus Karlsson <[email protected]>

This commit adds support for running the benchmark using a veth pair.

---
 samples/tpacket4/tpbench.c | 189 ++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 163 insertions(+), 26 deletions(-)
samples/tpacket4/tpbench.c +163 -26
index 46fb83009e06..2479f182d1b8 100644
@@ -65,8 +65,18 @@ enum benchmark_type {
 static enum tpacket_version opt_tpver = PV4;
 static enum benchmark_type opt_bench = BENCH_RXDROP;
 static const char *opt_if = "";
+static int opt_veth;
 static int opt_zerocopy;
 
+static const char *veth_if1 = "vm1";
+static const char *veth_if2 = "vm2";
+
+/* For process synchronization */
+static int shmid;
+volatile unsigned int *sync_var;
+#define SLEEP_STEP 10
+#define MAX_SLEEP (1000000 / (SLEEP_STEP))
+
 struct tpacket2_queue {
 	void *ring;
 
@@ -296,13 +306,53 @@ static void process_swap_mac(void *queue_pair, unsigned int start,
 	}
 }
 
+static unsigned long get_nsecs(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return ts.tv_sec * 1000000000UL + ts.tv_nsec;
+}
+
 static void run_benchmark(const char *interface_name)
 {
 	unsigned int start, end;
 	struct tp2_queue_pair *qp;
 
+	if (opt_veth) {
+		shmid = shmget(14082017, sizeof(unsigned int),
+			       IPC_CREAT | 666);
+		sync_var = shmat(shmid, 0, 0);
+		if (sync_var == (unsigned int *)-1) {
+			printf("You are probably not running as root\n");
+			exit(EXIT_FAILURE);
+		}
+		*sync_var = 0;
+
+		if (fork() == 0) {
+			opt_if = veth_if2;
+			interface_name = veth_if2;
+		} else {
+			unsigned int i;
+
+			/* Wait for child */
+			for (i = 0; *sync_var == 0 && i < MAX_SLEEP; i++)
+				usleep(SLEEP_STEP);
+			if (i >= MAX_SLEEP) {
+				printf("Wait for vm2 timed out. Exiting.\n");
+				exit(EXIT_FAILURE);
+			}
+		}
+	}
+
 	qp = benchmark.configure(interface_name);
 
+	/* Notify parent that interface configuration completed */
+	if (opt_veth && !strcmp(interface_name, "vm2"))
+		*sync_var = 1;
+
+	start_time = get_nsecs();
+
 	for (;;) {
 		for (;;) {
 			benchmark.rx(qp, &start, &end);
@@ -320,14 +370,6 @@ static void run_benchmark(const char *interface_name)
 	}
 }
 
-static unsigned long get_nsecs(void)
-{
-	struct timespec ts;
-
-	clock_gettime(CLOCK_MONOTONIC, &ts);
-	return ts.tv_sec * 1000000000UL + ts.tv_nsec;
-}
-
 static void *tp2_configure(const char *interface_name)
 {
 	int sfd, noqdisc, ret, ver = TPACKET_V2;
@@ -386,6 +428,36 @@ static void *tp2_configure(const char *interface_name)
 	ret = bind(sfd, (struct sockaddr *)&ll, sizeof(ll));
 	lassert(ret == 0);
 
+	if (opt_veth && !strcmp(interface_name, "vm1"))	{
+		struct tpacket2_queue *txq = &tqp->tx;
+		int i;
+
+		for (i = 0; i < opt_veth; i++) {
+			unsigned int idx = txq->last_used_idx &
+				(txq->ring_size - 1);
+			struct tpacket2_hdr *hdr;
+			unsigned int len;
+
+			hdr = (struct tpacket2_hdr *)(txq->ring +
+					     (idx << txq->frame_size_log2));
+			len = gen_eth_frame((char *)hdr + TPACKET2_HDRLEN -
+					    sizeof(struct sockaddr_ll), i + 1);
+			hdr->tp_snaplen = len;
+			hdr->tp_len = len;
+
+			u_smp_wmb();
+
+			hdr->tp_status = TP_STATUS_SEND_REQUEST;
+			txq->last_used_idx++;
+		}
+
+		ret = sendto(sfd, NULL, 0, MSG_DONTWAIT, NULL, 0);
+		if (!(ret >= 0 || errno == EAGAIN || errno == ENOBUFS))
+			lassert(0);
+
+		tx_npkts += opt_veth;
+	}
+
 	setup_tx_frame();
 
 	return tqp;
@@ -556,6 +628,36 @@ static void *tp3_configure(const char *interface_name)
 	ret = bind(sfd, (struct sockaddr *)&ll, sizeof(ll));
 	lassert(ret == 0);
 
+	if (opt_veth && !strcmp(interface_name, "vm1"))	{
+		struct tpacket2_queue *txq = &tqp->tx;
+		int i;
+
+		for (i = 0; i < opt_veth; i++) {
+			unsigned int idx = txq->last_used_idx &
+				(txq->ring_size - 1);
+			struct tpacket3_hdr *hdr;
+			unsigned int len;
+
+			hdr = (struct tpacket3_hdr *)(txq->ring +
+					     (idx << txq->frame_size_log2));
+			len = gen_eth_frame((char *)hdr + TPACKET3_HDRLEN -
+					    sizeof(struct sockaddr_ll), i + 1);
+			hdr->tp_snaplen = len;
+			hdr->tp_len = len;
+
+			u_smp_wmb();
+
+			hdr->tp_status = TP_STATUS_SEND_REQUEST;
+			txq->last_used_idx++;
+		}
+
+		ret = sendto(sfd, NULL, 0, MSG_DONTWAIT, NULL, 0);
+		if (!(ret >= 0 || errno == EAGAIN || errno == ENOBUFS))
+			lassert(0);
+
+		tx_npkts += opt_veth;
+	}
+
 	setup_tx_frame();
 
 	return tqp;
@@ -783,6 +885,28 @@ static inline int tp4q_enqueue(struct tpacket4_queue *q,
 	return 0;
 }
 
+static inline void *tp4_get_data(void *queue_pair, unsigned int idx,
+				 unsigned int *len)
+{
+	struct tp4_queue_pair *qp = (struct tp4_queue_pair *)queue_pair;
+	struct tp4_umem *umem = qp->umem;
+	struct tpacket4_desc *d;
+
+	d = &qp->rx.ring[idx & qp->rx.ring_mask];
+	*len = d->len;
+
+	return (char *)umem->buffer + (d->idx << umem->frame_size_log2)
+		+ d->offset;
+}
+
+static inline void *tp4_get_buffer(void *queue_pair, unsigned int idx)
+{
+	struct tp4_queue_pair *qp = (struct tp4_queue_pair *)queue_pair;
+	struct tp4_umem *umem = qp->umem;
+
+	return (char *)umem->buffer + (idx << umem->frame_size_log2);
+}
+
 static void *tp4_configure(const char *interface_name)
 {
 	int sfd, noqdisc, ret, ver = TPACKET_V4;
@@ -848,7 +972,27 @@ static void *tp4_configure(const char *interface_name)
 		lassert(ret == 0);
 	}
 
-	for (i = 0; i < (tqp->rx.ring_mask + 1)/4; i++) {
+	if (opt_veth >= (tqp->rx.ring_mask + 1)/4) {
+		printf("Veth batch size too large.\n");
+		exit(EXIT_FAILURE);
+	}
+
+	if (opt_veth && !strcmp(interface_name, "vm1"))	{
+		for (i = 0; i < opt_veth; i++) {
+			struct tpacket4_desc desc = {.idx = i};
+			unsigned int len;
+
+			len = gen_eth_frame(tp4_get_buffer(tqp, i), i + 1);
+
+			desc.len = len;
+			ret = tp4q_enqueue(&tqp->tx, &desc, 1);
+			lassert(ret == 0);
+		}
+		ret = sendto(sfd, NULL, 0, MSG_DONTWAIT, NULL, 0);
+		lassert(ret != -1);
+	}
+
+	for (i = opt_veth; i < (tqp->rx.ring_mask + 1)/4; i++) {
 		struct tpacket4_desc desc = {};
 
 		desc.idx = i;
@@ -902,21 +1046,6 @@ static inline void tp4_rx_release(void *queue_pair, unsigned int start,
 	q->num_free = 0;
 }
 
-static inline void *tp4_get_data(void *queue_pair, unsigned int idx,
-				 unsigned int *len)
-{
-	struct tp4_queue_pair *qp = (struct tp4_queue_pair *)queue_pair;
-	struct tp4_umem *umem = qp->umem;
-	struct tpacket4_desc *d;
-
-	d = &qp->rx.ring[idx & qp->rx.ring_mask];
-	*len = d->len;
-
-	return (char *)umem->buffer + (d->idx << umem->frame_size_log2)
-		+ d->offset;
-}
-
-
 static inline unsigned long tp4_get_data_desc(void *queue_pair,
 					      unsigned int idx,
 					      unsigned int *len,
@@ -1126,6 +1255,7 @@ static struct option long_options[] = {
 	{"l2fwd", no_argument, 0, 'l'},
 	{"zerocopy", required_argument, 0, 'z'},
 	{"interface", required_argument, 0, 'i'},
+	{"veth", required_argument, 0, 'e'},
 	{0, 0, 0, 0}
 };
 
@@ -1152,7 +1282,7 @@ static void parse_command_line(int argc, char **argv)
 	opterr = 0;
 
 	for (;;) {
-		c = getopt_long(argc, argv, "v:rtlz:i:", long_options,
+		c = getopt_long(argc, argv, "v:rtlz:i:e:", long_options,
 				&option_index);
 		if (c == -1)
 			break;
@@ -1182,6 +1312,9 @@ static void parse_command_line(int argc, char **argv)
 		case 'i':
 			opt_if = optarg;
 			break;
+		case 'e':
+			opt_veth = atoi(optarg);
+			break;
 		default:
 			usage();
 		}
@@ -1192,6 +1325,11 @@ static void parse_command_line(int argc, char **argv)
 		usage();
 	}
 
+	if (opt_veth) {
+		opt_bench = BENCH_L2FWD;
+		opt_if = veth_if1;
+	}
+
 	ret = if_nametoindex(opt_if);
 	if (!ret) {
 		fprintf(stderr, "ERROR: interface \"%s\" does not exist\n",
@@ -1246,7 +1384,6 @@ int main(int argc, char **argv)
 	parse_command_line(argc, argv);
 	print_benchmark(true);
 	benchmark = *get_benchmark(opt_tpver, opt_bench);
-	start_time = get_nsecs();
 	run_benchmark(opt_if);
 
 	return 0;
Signature · 1 line
2.11.0
#31 lore raw

RFC PATCH 13/14 i40e: added XDP support for TP4 enabled queue pairs

In reply to Björn Töpel

From: Magnus Karlsson <[email protected]>

In this commit the packet array learned to execute XDP programs on it's flushable range. This means that before the kernel flush completed/filled Rx frame to userspace, an XDP program will be executed and acted upon.

Currently, a packet array user still have to explicitly call the tp4a_run_xdp function, prior a tp4a_flush/tp4a_flush_n call, but this will change in a future patch set.

The XDP_TX/XDP_REDIRECT is doing page allocation, so exepect lousy performance. The i40e XDP infrastructure needs to be aligned to handle TP4 properly.

---
 drivers/net/ethernet/intel/i40e/i40e_main.c |   4 +-
 drivers/net/ethernet/intel/i40e/i40e_txrx.c |  70 +++++++++++-
 drivers/net/veth.c                          |   6 +-
 include/linux/tpacket4.h                    | 160 +++++++++++++++++++++++++++-
 net/packet/af_packet.c                      |   4 +-
 5 files changed, 233 insertions(+), 11 deletions(-)
drivers/net/ethernet/intel/i40e/i40e_main.c +2 -2
index ff6d44dae8d0..b63cc4c8957f 100644
@@ -11398,7 +11398,7 @@ static int i40e_tp4_enable_rx(struct i40e_ring *rxr,
 	size_t elems = __roundup_pow_of_two(rxr->count * 8);
 	struct tp4_packet_array *arr;
 
-	arr = tp4a_rx_new(params->rx_opaque, elems, rxr->dev);
+	arr = tp4a_rx_new(params->rx_opaque, elems, rxr->netdev, rxr->dev);
 	if (!arr)
 		return -ENOMEM;
 
@@ -11428,7 +11428,7 @@ static int i40e_tp4_enable_tx(struct i40e_ring *txr,
 	size_t elems = __roundup_pow_of_two(txr->count * 8);
 	struct tp4_packet_array *arr;
 
-	arr = tp4a_tx_new(params->tx_opaque, elems, txr->dev);
+	arr = tp4a_tx_new(params->tx_opaque, elems, txr->netdev, txr->dev);
 	if (!arr)
 		return -ENOMEM;
 
drivers/net/ethernet/intel/i40e/i40e_txrx.c +68 -2

105 lines not on this page · raw message

drivers/net/veth.c +4 -2
index 3dfb5fb89460..eea1eab00624 100644
@@ -400,13 +400,15 @@ static int veth_tp4_enable(struct net_device *netdev,
 	netif_napi_add(netdev, priv->napi, veth_napi_poll,
 		       NAPI_POLL_WEIGHT);
 
-	priv->tp4a_rx = tp4a_rx_new(params->rx_opaque, NAPI_POLL_WEIGHT, NULL);
+	priv->tp4a_rx = tp4a_rx_new(params->rx_opaque, NAPI_POLL_WEIGHT, NULL,
+				    NULL);
 	if (!priv->tp4a_rx) {
 		err = -ENOMEM;
 		goto rxa_err;
 	}
 
-	priv->tp4a_tx = tp4a_tx_new(params->tx_opaque, NAPI_POLL_WEIGHT, NULL);
+	priv->tp4a_tx = tp4a_tx_new(params->tx_opaque, NAPI_POLL_WEIGHT, NULL,
+				    NULL);
 	if (!priv->tp4a_tx) {
 		err = -ENOMEM;
 		goto txa_err;
include/linux/tpacket4.h +157 -3

208 lines not on this page · raw message

net/packet/af_packet.c +2 -2
index fbfada773463..105cdac13343 100644
@@ -5038,8 +5038,8 @@ packet_v4_ring_new(struct sock *sk, struct tpacket_req4 *req, int tx_ring)
 		  (struct tpacket4_desc *)rb->pg_vec->buffer);
 	spin_unlock_bh(&rb_queue->lock);
 
-	rb->tp4a = tx_ring ? tp4a_tx_new(&rb->tp4q, TP4_ARRAY_SIZE, NULL)
-		   : tp4a_rx_new(&rb->tp4q, TP4_ARRAY_SIZE, NULL);
+	rb->tp4a = tx_ring ? tp4a_tx_new(&rb->tp4q, TP4_ARRAY_SIZE, NULL, NULL)
+		   : tp4a_rx_new(&rb->tp4q, TP4_ARRAY_SIZE, NULL, NULL);
 
 	if (!rb->tp4a) {
 		err = -ENOMEM;
Signature · 1 line
2.11.0
#32 lore raw

RFC PATCH 14/14 xdp: introducing XDP_PASS_TO_KERNEL for PACKET_ZEROCOPY use

In reply to Björn Töpel

From: Magnus Karlsson <[email protected]>

This patch introduces XDP_PASS_TO_KERNEL especially for use with PACKET_ZEROCOPY (ZC) and AF_PACKET V4. When ZC is enabled, XDP_PASS will send a packet to the V4 socket so that the application can receive it. If the XDP program would like to send a packet towards the kernel stack, then XDP_PASS_TO_KERNEL can be used. It will copy the packet from the packet buffer into an skb and pass it on. When PACKET_ZEROCOPY is not enabled, XDP_PASS_TO_KERNEL defaults to XDP_PASS.

Note that in ZC mode, user space will be able to see the packet that XDP is running on, so this is only for trusted applications. For untrusted applications, NIC HW steering support is a requirement to make sure the untrusted applications can only see their own packets.

---
 drivers/net/ethernet/intel/i40e/i40e_txrx.c | 62 +++++++++++++++++++++++++++--
 include/linux/tpacket4.h                    | 17 +++++++-
 include/uapi/linux/bpf.h                    |  1 +
 3 files changed, 75 insertions(+), 5 deletions(-)
drivers/net/ethernet/intel/i40e/i40e_txrx.c +58 -4
index 730fe57ca8ee..bf2680ed2b05 100644
@@ -2050,6 +2050,7 @@ static struct sk_buff *i40e_run_xdp(struct i40e_ring *rx_ring,
 	act = bpf_prog_run_xdp(xdp_prog, xdp);
 	switch (act) {
 	case XDP_PASS:
+	case XDP_PASS_TO_KERNEL:
 		break;
 	case XDP_TX:
 		xdp_ring = rx_ring->vsi->xdp_rings[rx_ring->queue_index];
@@ -2278,7 +2279,8 @@ static inline unsigned int i40e_get_rx_desc_size(union i40e_rx_desc *rxd)
 }
 
 static void i40e_run_xdp_tp4(struct tp4_frame_set *f, bool *recycled,
-			     struct bpf_prog *xdp_prog, struct i40e_ring *xdpr);
+			     struct bpf_prog *xdp_prog, struct i40e_ring *xdpr,
+			     struct i40e_ring *rxr);
 
 /**
  * i40e_clean_rx_tp4_irq - Pulls received packets of the descriptor ring
@@ -2322,7 +2324,7 @@ int i40e_clean_rx_tp4_irq(struct i40e_ring *rxr, int budget)
 
 			xdpr = rxr->vsi->xdp_rings[rxr->queue_index];
 			i40e_run_xdp_tp4(&frame_set, &recycled,
-					 xdp_prog, xdpr);
+					 xdp_prog, xdpr, rxr);
 
 			if (!recycled)
 				nflush++;
@@ -3853,16 +3855,68 @@ static void i40e_tp4_xdp_tx_flush_handler(void *ctx)
 }
 
 /**
+ * i40e_tp4_xdp_tx_flush_handler - XDP pass to kernel callback
+ * @ctx: context. A pointer to the RX ring.
+ * @xdp: XDP buff
+ *
+ * Returns 0 for success and <0 on failure.
+ **/
+static int i40e_tp4_xdp_to_kernel_handler(void *ctx, struct xdp_buff *xdp)
+{
+	struct i40e_ring *rx_ring = ctx;
+	union i40e_rx_desc *rx_desc;
+	struct sk_buff *skb;
+	unsigned int len;
+	u16 vlan_tag;
+	u8 rx_ptype;
+	u64 qword;
+	int err;
+
+	len = xdp->data_end - xdp->data;
+	skb = __napi_alloc_skb(&rx_ring->q_vector->napi, len,
+			       GFP_ATOMIC | __GFP_NOWARN);
+	if (unlikely(!skb))
+		return -ENOMEM;
+
+	/* XXX Use fragments for the data here */
+	skb_put(skb, len);
+	err = skb_store_bits(skb, 0, xdp->data, len);
+	if (unlikely(err)) {
+		kfree_skb(skb);
+		return err;
+	}
+
+	rx_desc = I40E_RX_DESC(rx_ring, rx_ring->next_to_clean);
+	qword = le64_to_cpu(rx_desc->wb.qword1.status_error_len);
+	rx_ptype = (qword & I40E_RXD_QW1_PTYPE_MASK) >>
+		I40E_RXD_QW1_PTYPE_SHIFT;
+
+	/* populate checksum, VLAN, and protocol */
+	i40e_process_skb_fields(rx_ring, rx_desc, skb, rx_ptype);
+
+	vlan_tag = (qword & BIT(I40E_RX_DESC_STATUS_L2TAG1P_SHIFT)) ?
+		le16_to_cpu(rx_desc->wb.qword0.lo_dword.l2tag1) : 0;
+
+	i40e_trace(clean_rx_irq_rx, rx_ring, rx_desc, skb);
+	i40e_receive_skb(rx_ring, skb, vlan_tag);
+
+	return 0;
+}
+
+/**
  * i40e_run_xdp_tp4 - Runs an XDP program on a the flushable range of packets
  * @a: pointer to frame set
  * @recycled: true if element was removed from flushable range
  * @xdp_prog: XDP program
  * @xdpr: XDP Tx ring
+ * @rxr: pointer to RX ring
  **/
 static void i40e_run_xdp_tp4(struct tp4_frame_set *f, bool *recycled,
-			     struct bpf_prog *xdp_prog, struct i40e_ring *xdpr)
+			     struct bpf_prog *xdp_prog, struct i40e_ring *xdpr,
+			     struct i40e_ring *rxr)
 {
 	tp4a_run_xdp(f, recycled, xdp_prog,
 		     i40e_tp4_xdp_tx_handler, xdpr,
-		     i40e_tp4_xdp_tx_flush_handler, xdpr);
+		     i40e_tp4_xdp_tx_flush_handler, xdpr,
+		     i40e_tp4_xdp_to_kernel_handler, rxr);
 }
include/linux/tpacket4.h +16 -1
index cade34e48a2d..9cb879ea558e 100644
@@ -1385,6 +1385,8 @@ static inline void __tp4a_fill_xdp_buff(struct tp4_packet_array *a,
  * @xdp_tx_ctx: XDP xmit handler ctx
  * @xdp_tx_flush_handler: XDP xmit flush handler
  * @xdp_tx_flush_ctx: XDP xmit flush ctx
+ * @xdp_to_kernel_handler: XDP pass to kernel handler
+ * @xdp_to_kernel_ctx: XDP pass to kernel ctx
  **/
 static inline void tp4a_run_xdp(struct tp4_frame_set *f,
 				bool *recycled,
@@ -1393,7 +1395,10 @@ static inline void tp4a_run_xdp(struct tp4_frame_set *f,
 						      struct xdp_buff *xdp),
 				void *xdp_tx_ctx,
 				void (*xdp_tx_flush_handler)(void *ctx),
-				void *xdp_tx_flush_ctx)
+				void *xdp_tx_flush_ctx,
+				int (*xdp_to_kernel_handler)(void *ctx,
+							 struct xdp_buff *xdp),
+				void *xdp_to_kernel_ctx)
 {
 	struct tp4_packet_array *a = f->pkt_arr;
 	struct tpacket4_desc *d, tmp;
@@ -1415,10 +1420,20 @@ static inline void tp4a_run_xdp(struct tp4_frame_set *f,
 	act = bpf_prog_run_xdp(xdp_prog, &xdp);
 	switch (act) {
 	case XDP_PASS:
+	case XDP_PASS_TO_KERNEL:
 		if (data != xdp.data) {
 			diff = data - xdp.data;
 			d->offset += diff;
 		}
+
+		if (act == XDP_PASS_TO_KERNEL) {
+			*recycled = true;
+			tmp = __tp4a_swap_out(a, idx);
+			__tp4a_recycle(a, &tmp);
+
+			err = xdp_to_kernel_handler(xdp_to_kernel_ctx, &xdp);
+		}
+
 		break;
 	case XDP_TX:
 	case XDP_REDIRECT:
include/uapi/linux/bpf.h +1 -0
index 0b7b54d898bd..32d19f5727e2 100644
@@ -875,6 +875,7 @@ enum xdp_action {
 	XDP_PASS,
 	XDP_TX,
 	XDP_REDIRECT,
+	XDP_PASS_TO_KERNEL,
 };
 
 /* user accessible metadata for XDP packet hook
Signature · 1 line
2.11.0
#17 lore raw

RFC PATCH 3/14 packet: enable AF_PACKET V4 rings

In reply to Björn Töpel

From: Björn Töpel <[email protected]>

Allow creation of AF_PACKET V4 rings. Tx and Rx are still disabled.

---
 include/linux/tpacket4.h | 391 +++++++++++++++++++++++++++++++++++++++++++++++
 net/packet/af_packet.c   | 262 +++++++++++++++++++++++++++++--
 net/packet/internal.h    |   4 +
 3 files changed, 641 insertions(+), 16 deletions(-)
include/linux/tpacket4.h +391 -0
index fcf4c333c78d..44ba38034133 100644
@@ -18,6 +18,12 @@
 #define TP4_UMEM_MIN_FRAME_SIZE 2048
 #define TP4_KERNEL_HEADROOM 256 /* Headrom for XDP */
 
+enum tp4_validation {
+	TP4_VALIDATION_NONE,	/* No validation is performed */
+	TP4_VALIDATION_IDX,	/* Only address to packet buffer is validated */
+	TP4_VALIDATION_DESC	/* Full descriptor is validated */
+};
+
 struct tp4_umem {
 	struct pid *pid;
 	struct page **pgs;
@@ -31,9 +37,95 @@ struct tp4_umem {
 	unsigned int data_headroom;
 };
 
+struct tp4_dma_info {
+	dma_addr_t dma;
+	struct page *page;
+};
+
+struct tp4_queue {
+	struct tpacket4_desc *ring;
+
+	unsigned int used_idx;
+	unsigned int last_avail_idx;
+	unsigned int ring_mask;
+	unsigned int num_free;
+
+	struct tp4_umem *umem;
+	struct tp4_dma_info *dma_info;
+	enum dma_data_direction direction;
+};
+
+/**
+ * struct tp4_packet_array - An array of packets/frames
+ *
+ * @tp4q: the tp4q associated with this packet array. Flushes and
+ *	  populates will operate on this.
+ * @dev: pointer to the netdevice the queue should be associated with
+ * @direction: the direction of the DMA channel that is set up.
+ * @validation: type of validation performed on populate
+ * @start: the first packet that has not been processed
+ * @curr: the packet that is currently being processed
+ * @end: the last packet in the array
+ * @mask: convenience variable for internal operations on the array
+ * @items: the actual descriptors to frames/packets that are in the array
+ **/
+struct tp4_packet_array {
+	struct tp4_queue *tp4q;
+	struct device *dev;
+	enum dma_data_direction direction;
+	enum tp4_validation validation;
+	u32 start;
+	u32 curr;
+	u32 end;
+	u32 mask;
+	struct tpacket4_desc items[0];
+};
+
+/**
+ * struct tp4_frame_set - A view of a packet array consisting of
+ *                        one or more frames
+ *
+ * @pkt_arr: the packet array this frame set is located in
+ * @start: the first frame that has not been processed
+ * @curr: the frame that is currently being processed
+ * @end: the last frame in the frame set
+ *
+ * This frame set can either be one or more frames or a single packet
+ * consisting of one or more frames. tp4f_ functions with packet in the
+ * name return a frame set representing a packet, while the other
+ * tp4f_ functions return one or more frames not taking into account if
+ * they consitute a packet or not.
+ **/
+struct tp4_frame_set {
+	struct tp4_packet_array *pkt_arr;
+	u32 start;
+	u32 curr;
+	u32 end;
+};
+
 /*************** V4 QUEUE OPERATIONS *******************************/
 
 /**
+ * tp4q_init - Initializas a tp4 queue
+ *
+ * @q: Pointer to the tp4 queue structure to be initialized
+ * @nentries: Number of descriptor entries in the queue
+ * @umem: Pointer to the umem / packet buffer associated with this queue
+ * @buffer: Pointer to the memory region where the descriptors will reside
+ **/
+static inline void tp4q_init(struct tp4_queue *q, unsigned int nentries,
+			     struct tp4_umem *umem,
+			     struct tpacket4_desc *buffer)
+{
+	q->ring = buffer;
+	q->used_idx = 0;
+	q->last_avail_idx = 0;
+	q->ring_mask = nentries - 1;
+	q->num_free = 0;
+	q->umem = umem;
+}
+
+/**
  * tp4q_umem_new - Creates a new umem (packet buffer)
  *
  * @addr: The address to the umem
@@ -98,4 +190,303 @@ static inline struct tp4_umem *tp4q_umem_new(unsigned long addr, size_t size,
 	return umem;
 }
 
+/**
+ * tp4q_enqueue_from_array - Enqueue entries from packet array to tp4 queue
+ *
+ * @a: Pointer to the packet array to enqueue from
+ * @dcnt: Max number of entries to enqueue
+ *
+ * Returns 0 for success or an errno at failure
+ **/
+static inline int tp4q_enqueue_from_array(struct tp4_packet_array *a,
+					  u32 dcnt)
+{
+	struct tp4_queue *q = a->tp4q;
+	unsigned int used_idx = q->used_idx;
+	struct tpacket4_desc *d = a->items;
+	int i;
+
+	if (q->num_free < dcnt)
+		return -ENOSPC;
+
+	q->num_free -= dcnt;
+
+	for (i = 0; i < dcnt; i++) {
+		unsigned int idx = (used_idx++) & q->ring_mask;
+		unsigned int didx = (a->start + i) & a->mask;
+
+		q->ring[idx].idx = d[didx].idx;
+		q->ring[idx].len = d[didx].len;
+		q->ring[idx].offset = d[didx].offset;
+		q->ring[idx].error = d[didx].error;
+	}
+
+	/* Order flags and data */
+	smp_wmb();
+
+	for (i = dcnt - 1; i >= 0; i--) {
+		unsigned int idx = (q->used_idx + i) & q->ring_mask;
+		unsigned int didx = (a->start + i) & a->mask;
+
+		q->ring[idx].flags = d[didx].flags & ~TP4_DESC_KERNEL;
+	}
+	q->used_idx += dcnt;
+
+	return 0;
+}
+
+/**
+ * tp4q_disable - Disable a tp4 queue
+ *
+ * @dev: Pointer to the netdevice the queue is connected to
+ * @q: Pointer to the tp4 queue to disable
+ **/
+static inline void tp4q_disable(struct device *dev,
+				struct tp4_queue *q)
+{
+	int i;
+
+	if (q->dma_info) {
+		/* Unmap DMA */
+		for (i = 0; i < q->umem->npgs; i++)
+			dma_unmap_page(dev, q->dma_info[i].dma, PAGE_SIZE,
+				       q->direction);
+
+		kfree(q->dma_info);
+		q->dma_info = NULL;
+	}
+}
+
+/**
+ * tp4q_enable - Enable a tp4 queue
+ *
+ * @dev: Pointer to the netdevice the queue should be associated with
+ * @q: Pointer to the tp4 queue to enable
+ * @direction: The direction of the DMA channel that is set up.
+ *
+ * Returns 0 for success or a negative errno for failure
+ **/
+static inline int tp4q_enable(struct device *dev,
+			      struct tp4_queue *q,
+			      enum dma_data_direction direction)
+{
+	int i, j;
+
+	/* DMA map all the buffers in bufs up front, and sync prior
+	 * kicking userspace. Is this sane? Strictly user land owns
+	 * the buffer until they show up on the avail queue. However,
+	 * mapping should be ok.
+	 */
+	if (direction != DMA_NONE) {
+		q->dma_info = kcalloc(q->umem->npgs, sizeof(*q->dma_info),
+				      GFP_KERNEL);
+		if (!q->dma_info)
+			return -ENOMEM;
+
+		for (i = 0; i < q->umem->npgs; i++) {
+			dma_addr_t dma;
+
+			dma = dma_map_page(dev, q->umem->pgs[i], 0,
+					   PAGE_SIZE, direction);
+			if (dma_mapping_error(dev, dma)) {
+				for (j = 0; j < i; j++)
+					dma_unmap_page(dev,
+						       q->dma_info[j].dma,
+						       PAGE_SIZE, direction);
+				kfree(q->dma_info);
+				q->dma_info = NULL;
+				return -EBUSY;
+			}
+
+			q->dma_info[i].page = q->umem->pgs[i];
+			q->dma_info[i].dma = dma;
+		}
+	} else {
+		q->dma_info = NULL;
+	}
+
+	q->direction = direction;
+	return 0;
+}
+
+/*************** FRAME OPERATIONS *******************************/
+/* A frame is always just one frame of size frame_size.
+ * A frame set is one or more frames.
+ **/
+
+/**
+ * tp4f_next_frame - Go to next frame in frame set
+ * @p: pointer to frame set
+ *
+ * Returns true if there is another frame in the frame set.
+ * Advances curr pointer.
+ **/
+static inline bool tp4f_next_frame(struct tp4_frame_set *p)
+{
+	if (p->curr + 1 == p->end)
+		return false;
+
+	p->curr++;
+	return true;
+}
+
+/**
+ * tp4f_set_frame - Sets the properties of a frame
+ * @p: pointer to frame
+ * @len: the length in bytes of the data in the frame
+ * @offset: offset to start of data in frame
+ * @is_eop: Set if this is the last frame of the packet
+ **/
+static inline void tp4f_set_frame(struct tp4_frame_set *p, u32 len, u16 offset,
+				  bool is_eop)
+{
+	struct tpacket4_desc *d =
+		&p->pkt_arr->items[p->curr & p->pkt_arr->mask];
+
+	d->len = len;
+	d->offset = offset;
+	if (!is_eop)
+		d->flags |= TP4_PKT_CONT;
+}
+
+/**************** PACKET_ARRAY FUNCTIONS ********************************/
+
+static inline struct tp4_packet_array *__tp4a_new(
+	struct tp4_queue *tp4q,
+	struct device *dev,
+	enum dma_data_direction direction,
+	enum tp4_validation validation,
+	size_t elems)
+{
+	struct tp4_packet_array *arr;
+	int err;
+
+	if (!is_power_of_2(elems))
+		return NULL;
+
+	arr = kzalloc(sizeof(*arr) + elems * sizeof(struct tpacket4_desc),
+		      GFP_KERNEL);
+	if (!arr)
+		return NULL;
+
+	err = tp4q_enable(dev, tp4q, direction);
+	if (err) {
+		kfree(arr);
+		return NULL;
+	}
+
+	arr->tp4q = tp4q;
+	arr->dev = dev;
+	arr->direction = direction;
+	arr->validation = validation;
+	arr->mask = elems - 1;
+	return arr;
+}
+
+/**
+ * tp4a_rx_new - Create new packet array for ingress
+ * @rx_opaque: opaque from tp4_netdev_params
+ * @elems: number of elements in the packet array
+ * @dev: device or NULL
+ *
+ * Returns a reference to the new packet array or NULL for failure
+ **/
+static inline struct tp4_packet_array *tp4a_rx_new(void *rx_opaque,
+						   size_t elems,
+						   struct device *dev)
+{
+	enum dma_data_direction direction = dev ? DMA_FROM_DEVICE : DMA_NONE;
+
+	return __tp4a_new(rx_opaque, dev, direction, TP4_VALIDATION_IDX,
+			  elems);
+}
+
+/**
+ * tp4a_tx_new - Create new packet array for egress
+ * @tx_opaque: opaque from tp4_netdev_params
+ * @elems: number of elements in the packet array
+ * @dev: device or NULL
+ *
+ * Returns a reference to the new packet array or NULL for failure
+ **/
+static inline struct tp4_packet_array *tp4a_tx_new(void *tx_opaque,
+						   size_t elems,
+						   struct device *dev)
+{
+	enum dma_data_direction direction = dev ? DMA_TO_DEVICE : DMA_NONE;
+
+	return __tp4a_new(tx_opaque, dev, direction, TP4_VALIDATION_DESC,
+			  elems);
+}
+
+/**
+ * tp4a_get_flushable_frame_set - Create a frame set of the flushable region
+ * @a: pointer to packet array
+ * @p: frame set
+ *
+ * Returns true for success and false for failure
+ **/
+static inline bool tp4a_get_flushable_frame_set(struct tp4_packet_array *a,
+						struct tp4_frame_set *p)
+{
+	u32 avail = a->curr - a->start;
+
+	if (avail == 0)
+		return false; /* empty */
+
+	p->pkt_arr = a;
+	p->start = a->start;
+	p->curr = a->start;
+	p->end = a->curr;
+
+	return true;
+}
+
+/**
+ * tp4a_flush - Flush processed packets to associated tp4q
+ * @a: pointer to packet array
+ *
+ * Returns 0 for success and -1 for failure
+ **/
+static inline int tp4a_flush(struct tp4_packet_array *a)
+{
+	u32 avail = a->curr - a->start;
+	int ret;
+
+	if (avail == 0)
+		return 0; /* nothing to flush */
+
+	ret = tp4q_enqueue_from_array(a, avail);
+	if (ret < 0)
+		return -1;
+
+	a->start = a->curr;
+
+	return 0;
+}
+
+/**
+ * tp4a_free - Destroy packet array
+ * @a: pointer to packet array
+ **/
+static inline void tp4a_free(struct tp4_packet_array *a)
+{
+	struct tp4_frame_set f;
+
+	if (a) {
+		/* Flush all outstanding requests. */
+		if (tp4a_get_flushable_frame_set(a, &f)) {
+			do {
+				tp4f_set_frame(&f, 0, 0, true);
+			} while (tp4f_next_frame(&f));
+		}
+
+		WARN_ON_ONCE(tp4a_flush(a));
+
+		tp4q_disable(a->dev, a->tp4q);
+	}
+
+	kfree(a);
+}
+
 #endif /* _LINUX_TPACKET4_H */
net/packet/af_packet.c +246 -16

342 lines not on this page · raw message

net/packet/internal.h +4 -0
index 9c07cfe1b8a3..3eedab29e4d7 100644
@@ -71,6 +71,10 @@ struct packet_ring_buffer {
 	unsigned int __percpu	*pending_refcnt;
 
 	struct tpacket_kbdq_core	prb_bdqc;
+
+	struct tp4_packet_array	*tp4a;
+	struct tp4_queue	tp4q;
+	struct socket		*mrsock;
 };
 
 extern struct mutex fanout_mutex;
Signature · 1 line
2.11.0
maintainer
#2 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to Björn Töpel
Quoted 36 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This patch adds the necessary AF_PACKET V4 structures for usage from userspace. AF_PACKET V4 is a new interface optimized for high performance packet processing.

---
 include/uapi/linux/if_packet.h | 65 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 64 insertions(+), 1 deletion(-)
include/uapi/linux/if_packet.h +19 -0
+struct tpacket4_queue {
+       struct tpacket4_desc *ring;
+
+       unsigned int avail_idx;
+       unsigned int last_used_idx;
+       unsigned int num_free;
+       unsigned int ring_mask;
+};
 
 struct packet_mreq {
@@ -294,6 +335,28 @@ struct packet_mreq {
        unsigned char   mr_address[8];
 };
 
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *

include/uapi/linux/if_packet.h struct packet_mreq { · line 358

Quoted 10 lines
include/uapi/linux/if_packet.h +10 -0
+ * Corollary: The number of frames that can be stored is
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+       unsigned long   addr;           /* Start of packet data area */
+       unsigned long   len;            /* Length of packet data area */
+       unsigned int    frame_size;     /* Frame size */
+       unsigned int    data_headroom;  /* Frame head room */
+};

Existing packet sockets take a tpacket_req, allocate memory and let the user process mmap this. I understand that TPACKET_V4 distinguishes the descriptor from packet pools, but could both use the existing structs and logic (packet_mmap)? That would avoid introducing a lot of new code just for granting user pages to the kernel.

Also, use of unsigned long can cause problems on 32/64 bit compat environments. Prefer fixed width types in uapi. Same for pointer in tpacket4_queue.

#3 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

Quoted 45 lines · Willem de Bruijn
Quoted 44 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This patch adds the necessary AF_PACKET V4 structures for usage from userspace. AF_PACKET V4 is a new interface optimized for high performance packet processing.

---
  include/uapi/linux/if_packet.h | 65 +++++++++++++++++++++++++++++++++++++++++-
  1 file changed, 64 insertions(+), 1 deletion(-)
include/uapi/linux/if_packet.h +27 -0
+struct tpacket4_queue {
+       struct tpacket4_desc *ring;
+
+       unsigned int avail_idx;
+       unsigned int last_used_idx;
+       unsigned int num_free;
+       unsigned int ring_mask;
+};
 
  struct packet_mreq {
@@ -294,6 +335,28 @@ struct packet_mreq {
         unsigned char   mr_address[8];
  };
 
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *
+ * Corollary: The number of frames that can be stored is
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+       unsigned long   addr;           /* Start of packet data area */
+       unsigned long   len;            /* Length of packet data area */
+       unsigned int    frame_size;     /* Frame size */
Quoted 9 lines

include/uapi/linux/if_packet.h struct packet_mreq { · line 358

Quoted 2 lines
include/uapi/linux/if_packet.h +2 -0
+       unsigned int    data_headroom;  /* Frame head room */
+};

Existing packet sockets take a tpacket_req, allocate memory and let the user process mmap this. I understand that TPACKET_V4 distinguishes the descriptor from packet pools, but could both use the existing structs and logic (packet_mmap)? That would avoid introducing a lot of new code just for granting user pages to the kernel.

We could certainly pass the "tpacket_memreg_req" fields as part of descriptor ring setup ("tpacket_req4"), but we went with having the memory register as a new separate setsockopt. Having it separated, makes it easier to compare regions at the kernel side of things. "Is this the same umem as another one?" If we go the path of passing the range at descriptor ring setup, we need to handle all kind of overlapping ranges to determine when a copy is needed or not, in those cases where the packet buffer (i.e. umem) is shared between processes.

Quoted 3 lines

Also, use of unsigned long can cause problems on 32/64 bit compat environments. Prefer fixed width types in uapi. Same for pointer in tpacket4_queue.

I agree; We'll change to a fixed width type in next version. Do you (and others on the list) prefer __u32/__u64 or unsigned int / unsigned long long?

Thanks,
Björn

#4 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

Quoted 56 lines · Björn Töpel
Quoted 45 lines · Willem de Bruijn
Quoted 44 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This patch adds the necessary AF_PACKET V4 structures for usage from userspace. AF_PACKET V4 is a new interface optimized for high performance packet processing.

---
   include/uapi/linux/if_packet.h | 65 +++++++++++++++++++++++++++++++++++++++++-
   1 file changed, 64 insertions(+), 1 deletion(-)
include/uapi/linux/if_packet.h +27 -0
+struct tpacket4_queue {
+       struct tpacket4_desc *ring;
+
+       unsigned int avail_idx;
+       unsigned int last_used_idx;
+       unsigned int num_free;
+       unsigned int ring_mask;
+};
 
   struct packet_mreq {
@@ -294,6 +335,28 @@ struct packet_mreq {
          unsigned char   mr_address[8];
   };
 
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *
+ * Corollary: The number of frames that can be stored is
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+       unsigned long   addr;           /* Start of packet data area */
+       unsigned long   len;            /* Length of packet data area */
+       unsigned int    frame_size;     /* Frame size */
Quoted 9 lines

include/uapi/linux/if_packet.h struct packet_mreq { · line 358

Quoted 2 lines
include/uapi/linux/if_packet.h +2 -0
+       unsigned int    data_headroom;  /* Frame head room */
+};

Existing packet sockets take a tpacket_req, allocate memory and let the user process mmap this. I understand that TPACKET_V4 distinguishes the descriptor from packet pools, but could both use the existing structs and logic (packet_mmap)? That would avoid introducing a lot of new code just for granting user pages to the kernel.

Quoted 8 lines

We could certainly pass the "tpacket_memreg_req" fields as part of descriptor ring setup ("tpacket_req4"), but we went with having the memory register as a new separate setsockopt. Having it separated, makes it easier to compare regions at the kernel side of things. "Is this the same umem as another one?" If we go the path of passing the range at descriptor ring setup, we need to handle all kind of overlapping ranges to determine when a copy is needed or not, in those cases where the packet buffer (i.e. umem) is shared between processes.

Is there a reason to use separate packet socket for umem? Looks like userspace has to create separate packet socket for PACKET_MEMREG.

-Tushar>

Quoted 12 lines
Quoted 3 lines

Also, use of unsigned long can cause problems on 32/64 bit compat environments. Prefer fixed width types in uapi. Same for pointer in tpacket4_queue.

I agree; We'll change to a fixed width type in next version. Do you (and others on the list) prefer __u32/__u64 or unsigned int / unsigned long long?

Thanks,
Björn

#5 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

2017-11-02 17:40 GMT+01:00 Tushar Dave <[email protected]>:

Quoted 75 lines · Björn Töpel
Quoted 62 lines · Willem de Bruijn
Quoted 50 lines
Quoted 47 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This patch adds the necessary AF_PACKET V4 structures for usage from userspace. AF_PACKET V4 is a new interface optimized for high performance packet processing.

---
   include/uapi/linux/if_packet.h | 65
+++++++++++++++++++++++++++++++++++++++++-
   1 file changed, 64 insertions(+), 1 deletion(-)
include/uapi/linux/if_packet.h +28 -0
+struct tpacket4_queue {
+       struct tpacket4_desc *ring;
+
+       unsigned int avail_idx;
+       unsigned int last_used_idx;
+       unsigned int num_free;
+       unsigned int ring_mask;
+};
 
   struct packet_mreq {
@@ -294,6 +335,28 @@ struct packet_mreq {
          unsigned char   mr_address[8];
   };
 
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *
+ * Corollary: The number of frames that can be stored is
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+       unsigned long   addr;           /* Start of packet data area */
+       unsigned long   len;            /* Length of packet data area */
+       unsigned int    frame_size;     /* Frame size */
+       unsigned int    data_headroom;  /* Frame head room */
Quoted 9 lines

Review struct packet_mreq { · line 358

Quoted 1 line
(quoted diff) +1 -0
+};

Existing packet sockets take a tpacket_req, allocate memory and let the user process mmap this. I understand that TPACKET_V4 distinguishes the descriptor from packet pools, but could both use the existing structs and logic (packet_mmap)? That would avoid introducing a lot of new code just for granting user pages to the kernel.

Quoted 8 lines

We could certainly pass the "tpacket_memreg_req" fields as part of descriptor ring setup ("tpacket_req4"), but we went with having the memory register as a new separate setsockopt. Having it separated, makes it easier to compare regions at the kernel side of things. "Is this the same umem as another one?" If we go the path of passing the range at descriptor ring setup, we need to handle all kind of overlapping ranges to determine when a copy is needed or not, in those cases where the packet buffer (i.e. umem) is shared between processes.

Quoted 3 lines

Is there a reason to use separate packet socket for umem? Looks like userspace has to create separate packet socket for PACKET_MEMREG.

Let me clarify; You *can* use a separate socket for umem, but you can also use the same/existing AF_PACKET socket for that.

Björn

Quoted 17 lines

-Tushar>

Quoted 13 lines
Quoted 3 lines

Also, use of unsigned long can cause problems on 32/64 bit compat environments. Prefer fixed width types in uapi. Same for pointer in tpacket4_queue.

I agree; We'll change to a fixed width type in next version. Do you (and others on the list) prefer __u32/__u64 or unsigned int / unsigned long long?

Thanks,
Björn

maintainer
#6 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to Björn Töpel
Quoted 29 lines
Quoted 19 lines
Quoted 19 lines
include/uapi/linux/if_packet.h +19 -0
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *
+ * Corollary: The number of frames that can be stored is
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+       unsigned long   addr;           /* Start of packet data area */
+       unsigned long   len;            /* Length of packet data area */
+       unsigned int    frame_size;     /* Frame size */
Quoted 9 lines

include/uapi/linux/if_packet.h struct packet_mreq { · line 358

Quoted 2 lines
include/uapi/linux/if_packet.h +2 -0
+       unsigned int    data_headroom;  /* Frame head room */
+};

Existing packet sockets take a tpacket_req, allocate memory and let the user process mmap this. I understand that TPACKET_V4 distinguishes the descriptor from packet pools, but could both use the existing structs and logic (packet_mmap)? That would avoid introducing a lot of new code just for granting user pages to the kernel.

Quoted 8 lines

We could certainly pass the "tpacket_memreg_req" fields as part of descriptor ring setup ("tpacket_req4"), but we went with having the memory register as a new separate setsockopt. Having it separated, makes it easier to compare regions at the kernel side of things. "Is this the same umem as another one?" If we go the path of passing the range at descriptor ring setup, we need to handle all kind of overlapping ranges to determine when a copy is needed or not, in those cases where the packet buffer (i.e. umem) is shared between processes.

That's not what I meant. Both descriptor rings and packet pools are memory regions. Packet sockets already have logic to allocate regions and make them available to userspace with mmap(). Packet v4 reuses that logic for its descriptor rings. Can it use the same for its packet pool? Why does the kernel map user memory, instead? That is a lot of non-trivial new logic.

maintainer
#15 lore raw

Re: [RFC PATCH 02/14] packet: implement PACKET_MEMREG setsockopt

In reply to Björn Töpel
Quoted 48 lines · Björn Töpel

From: Björn Töpel <[email protected]>

Here, the PACKET_MEMREG setsockopt is implemented for the AF_PACKET protocol family. PACKET_MEMREG allows the user to register memory regions that can be used by AF_PACKET V4 as packet data buffers.

---

include/linux/tpacket4.h new file +40 -0
+/*************** V4 QUEUE OPERATIONS *******************************/
+
+/**
+ * tp4q_umem_new - Creates a new umem (packet buffer)
+ *
+ * @addr: The address to the umem
+ * @size: The size of the umem
+ * @frame_size: The size of each frame, between 2K and PAGE_SIZE
+ * @data_headroom: The desired data headroom before start of the packet
+ *
+ * Returns a pointer to the new umem or NULL for failure
+ **/
+static inline struct tp4_umem *tp4q_umem_new(unsigned long addr, size_t size,
+                                            unsigned int frame_size,
+                                            unsigned int data_headroom)
+{
+       struct tp4_umem *umem;
+       unsigned int nframes;
+
+       if (frame_size < TP4_UMEM_MIN_FRAME_SIZE || frame_size > PAGE_SIZE) {
+               /* Strictly speaking we could support this, if:
+                * - huge pages, or*
+                * - using an IOMMU, or
+                * - making sure the memory area is consecutive
+                * but for now, we simply say "computer says no".
+                */
+               return ERR_PTR(-EINVAL);
+       }
+
+       if (!is_power_of_2(frame_size))
+               return ERR_PTR(-EINVAL);
+
+       if (!PAGE_ALIGNED(addr)) {
+               /* Memory area has to be page size aligned. For
+                * simplicity, this might change.
+                */
+               return ERR_PTR(-EINVAL);
+       }
+
+       if ((addr + size) < addr)

include/linux/tpacket4.h line 83

Quoted 10 lines
include/linux/tpacket4.h new file +10 -0
+               return ERR_PTR(-EINVAL);
+
+       nframes = size / frame_size;
+       if (nframes == 0)
+               return ERR_PTR(-EINVAL);
+
+       data_headroom = ALIGN(data_headroom, 64);
+
+       if (frame_size - data_headroom - TP4_KERNEL_HEADROOM < 0)
+               return ERR_PTR(-EINVAL);

signed comparison on unsigned int

maintainer
#24 lore raw

Re: [RFC PATCH 07/14] packet: wire up zerocopy for AF_PACKET V4

In reply to Björn Töpel
Quoted 9 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This commits adds support for zerocopy mode. Note that zerocopy mode requires that the network interface has been bound to the socket using the bind syscall, and that the corresponding netdev implements the AF_PACKET V4 ndos.

---

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3176

Quoted 10 lines
net/packet/af_packet.c +10 -0
+
+static void packet_v4_disable_zerocopy(struct net_device *dev,
+                                      struct tp4_netdev_parms *zc)
+{
+       struct tp4_netdev_parms params;
+
+       params = *zc;
+       params.command  = TP4_DISABLE;
+
+       (void)dev->netdev_ops->ndo_tp4_zerocopy(dev, &params);

Don't ignore error return codes.

Quoted 18 lines
net/packet/af_packet.c +18 -0
+static int packet_v4_zerocopy(struct sock *sk, int qp)
+{
+       struct packet_sock *po = pkt_sk(sk);
+       struct socket *sock = sk->sk_socket;
+       struct tp4_netdev_parms *zc = NULL;
+       struct net_device *dev;
+       bool if_up;
+       int ret = 0;
+
+       /* Currently, only RAW sockets are supported.*/
+       if (sock->type != SOCK_RAW)
+               return -EINVAL;
+
+       rtnl_lock();
+       dev = packet_cached_dev_get(po);
+
+       /* Socket needs to be bound to an interface. */
+       if (!dev) {

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3243

Quoted 10 lines
net/packet/af_packet.c +10 -0
+               rtnl_unlock();
+               return -EISCONN;
+       }
+
+       /* The device needs to have both the NDOs implemented. */
+       if (!(dev->netdev_ops->ndo_tp4_zerocopy &&
+             dev->netdev_ops->ndo_tp4_xmit)) {
+               ret = -EOPNOTSUPP;
+               goto out_unlock;
+       }

Inconsistent error handling with above test.

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3248

Quoted 5 lines
net/packet/af_packet.c +5 -0
+
+       if (!(po->rx_ring.pg_vec && po->tx_ring.pg_vec)) {
+               ret = -EOPNOTSUPP;
+               goto out_unlock;
+       }

A ring can be unmapped later with packet_set_ring. Should that operation fail if zerocopy is enabled? After that, it can also change version with PACKET_VERSION.

Quoted 7 lines
net/packet/af_packet.c +7 -0
+
+       if_up = dev->flags & IFF_UP;
+       zc = rtnl_dereference(po->zc);
+
+       /* Disable */
+       if (qp <= 0) {
+               if (!zc)

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3265

Quoted 10 lines
net/packet/af_packet.c +10 -0
+                       goto out_unlock;
+
+               packet_v4_disable_zerocopy(dev, zc);
+               rcu_assign_pointer(po->zc, NULL);
+
+               if (if_up) {
+                       spin_lock(&po->bind_lock);
+                       register_prot_hook(sk);
+                       spin_unlock(&po->bind_lock);
+               }

There have been a bunch of race conditions in this bind code. We need to be very careful with adding more states to the locking, especially when open coding in multiple locations, as this patch does. I counted at least four bind locations. See for instance also
http://patchwork.ozlabs.org/patch/813945/

Quoted 5 lines
net/packet/af_packet.c +5 -0
+
+               goto out_unlock;
+       }
+
+       /* Enable */

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3280

Quoted 10 lines
net/packet/af_packet.c +10 -0
+       if (!zc) {
+               zc = kzalloc(sizeof(*zc), GFP_KERNEL);
+               if (!zc) {
+                       ret = -ENOMEM;
+                       goto out_unlock;
+               }
+       }
+
+       if (zc->queue_pair >= 0)
+               packet_v4_disable_zerocopy(dev, zc);

This calls disable even if zc was freshly allocated. Shoud be > 0?

Quoted 15 lines

static int packet_release(struct socket *sock)
{

net/packet/af_packet.c +5 -0
+       struct tp4_netdev_parms *zc;
        struct sock *sk = sock->sk;
+       struct net_device *dev;
        struct packet_sock *po;
        struct packet_fanout *f;
        struct net *net;
@@ -3337,6 +3541,20 @@ static int packet_release(struct socket *sock)
        sock_prot_inuse_add(net, sk->sk_prot, -1);
        preempt_enable();
 
+       rtnl_lock();
+       zc = rtnl_dereference(po->zc);
+       dev = packet_cached_dev_get(po);

net/packet/af_packet.c static int packet_release(struct socket *sock) · line 3556

Quoted 10 lines
net/packet/af_packet.c +10 -0
+       if (zc && dev)
+               packet_v4_disable_zerocopy(dev, zc);
+       if (dev)
+               dev_put(dev);
+       rtnl_unlock();
+
+       if (zc) {
+               synchronize_rcu();
+               kfree(zc);
+       }

Please use a helper function for anything this complex.

maintainer
#18 lore raw

Re: [RFC PATCH 03/14] packet: enable AF_PACKET V4 rings

In reply to Björn Töpel
Quoted 10 lines
include/linux/tpacket4.h +10 -0
+/**
+ * tp4q_enqueue_from_array - Enqueue entries from packet array to tp4 queue
+ *
+ * @a: Pointer to the packet array to enqueue from
+ * @dcnt: Max number of entries to enqueue
+ *
+ * Returns 0 for success or an errno at failure
+ **/
+static inline int tp4q_enqueue_from_array(struct tp4_packet_array *a,
+                                         u32 dcnt)

include/linux/tpacket4.h static inline struct tp4_umem *tp4q_umem_new(unsigned long addr, size_t size, · line 212

Quoted 10 lines
include/linux/tpacket4.h +10 -0
+{
+       struct tp4_queue *q = a->tp4q;
+       unsigned int used_idx = q->used_idx;
+       struct tpacket4_desc *d = a->items;
+       int i;
+
+       if (q->num_free < dcnt)
+               return -ENOSPC;
+
+       q->num_free -= dcnt;

perhaps annotate with a lockdep_is_held to document which lock ensures mutual exclusion on the ring. Different for tx and rx?

net/packet/af_packet.c static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, · line 194

Quoted 11 lines
net/packet/af_packet.c +3 -0
index b39be424ec0e..190598eb3461 100644
@@ -189,6 +189,9 @@ static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
 #define BLOCK_O2PRIV(x)        ((x)->offset_to_priv)
 #define BLOCK_PRIV(x)          ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
 
+#define RX_RING 0
+#define TX_RING 1
+

Not needed if using bool for tx_ring below. The test effectively already treats it as bool: does not explicitly test these constants.

net/packet/af_packet.c packet_umem_new(unsigned long addr, size_t size, unsigned int frame_size, · line 3127

Quoted 7 lines
net/packet/af_packet.c +7 -0
+static void packet_clear_ring(struct sock *sk, int tx_ring)
+{
+       struct packet_sock *po = pkt_sk(sk);
+       struct packet_ring_buffer *rb;
+       union tpacket_req_u req_u;
+
+       rb = tx_ring ? &po->tx_ring : &po->rx_ring;

I meant here.

maintainer
#33 lore raw
In reply to Björn Töpel
Quoted 10 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This RFC introduces AF_PACKET_V4 and PACKET_ZEROCOPY that are optimized for high performance packet processing and zero-copy semantics. Throughput improvements can be up to 40x compared to V2 and V3 for the micro benchmarks included. Would be great to get your feedback on it.

The main difference between V4 and V2/V3 is that TX and RX descriptors are separated from packet buffers.

Cool feature. I'm looking forward to the netdev talk. Aside from the inline comments in the patches, a few architecture questions.

Is TX support needed? Existing PACKET_TX_RING already sends out packets without copying directly from the tx_ring. Indirection through a descriptor ring is not helpful on TX if all packets still have to come from a pre-registered packet pool. The patch set adds a lot of tx-only code and is complex enough without it.

Can you use the existing PACKET_V2 format for the packet pool? The v4 format is nearly the same as V2. Using the same version might avoid some code duplication and simplify upgrading existing legacy code. Instead of continuing to add new versions whose behavior is implicit, perhaps we can add explicit mode PACKET_INDIRECT to PACKET_V2.

Finally, is it necessary to define a new descriptor ring format? Same for the packet array and frame set. The kernel already has a few, such as virtio for the first, skb_array/ptr_ring, even linux list for the second. These containers add a lot of new boilerplate code. If new formats are absolutely necessary, at least we should consider making them generic (like skb_array and ptr_ring). But I'd like to understand first why, e.g., virtio cannot be used.

#7 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to Willem de Bruijn

2017-11-03 3:29 GMT+01:00 Willem de Bruijn <[email protected]>:

Quoted 38 lines
Quoted 29 lines
Quoted 19 lines
Quoted 19 lines
include/uapi/linux/if_packet.h +19 -0
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *
+ * Corollary: The number of frames that can be stored is
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+       unsigned long   addr;           /* Start of packet data area */
+       unsigned long   len;            /* Length of packet data area */
+       unsigned int    frame_size;     /* Frame size */
Quoted 9 lines

include/uapi/linux/if_packet.h struct packet_mreq { · line 358

Quoted 2 lines
include/uapi/linux/if_packet.h +2 -0
+       unsigned int    data_headroom;  /* Frame head room */
+};

Existing packet sockets take a tpacket_req, allocate memory and let the user process mmap this. I understand that TPACKET_V4 distinguishes the descriptor from packet pools, but could both use the existing structs and logic (packet_mmap)? That would avoid introducing a lot of new code just for granting user pages to the kernel.

Quoted 8 lines

We could certainly pass the "tpacket_memreg_req" fields as part of descriptor ring setup ("tpacket_req4"), but we went with having the memory register as a new separate setsockopt. Having it separated, makes it easier to compare regions at the kernel side of things. "Is this the same umem as another one?" If we go the path of passing the range at descriptor ring setup, we need to handle all kind of overlapping ranges to determine when a copy is needed or not, in those cases where the packet buffer (i.e. umem) is shared between processes.

Quoted 6 lines

That's not what I meant. Both descriptor rings and packet pools are memory regions. Packet sockets already have logic to allocate regions and make them available to userspace with mmap(). Packet v4 reuses that logic for its descriptor rings. Can it use the same for its packet pool? Why does the kernel map user memory, instead? That is a lot of non-trivial new logic.

Ah, got it. So, why do we register packet pool memory, instead of allocating in the kernel and mapping *that* memory.

Actually, we started out with that approach, where the packet_mmap call mapped Tx/Rx descriptor rings and the packet buffer region. We later moved to this (register umem) approach, because it's more flexible for user space, not having to use a AF_PACKET specific allocator (i.e. continue to use regular mallocs, huge pages and such).

I agree that the memory register code is adding a lot of new logic, but I believe it's worth the flexibility for user space. I'm looking into if I can share the memory register logic from Infiniband/verbs subsystem (drivers/infiniband/core/umem.c).

Björn

#16 lore raw

Re: [RFC PATCH 02/14] packet: implement PACKET_MEMREG setsockopt

In reply to Willem de Bruijn

2017-11-03 4:00 GMT+01:00 Willem de Bruijn <[email protected]>:

Quoted 53 lines · Björn Töpel
Quoted 52 lines

From: Björn Töpel <[email protected]>

Here, the PACKET_MEMREG setsockopt is implemented for the AF_PACKET protocol family. PACKET_MEMREG allows the user to register memory regions that can be used by AF_PACKET V4 as packet data buffers.

---

include/linux/tpacket4.h new file +44 -0
+/*************** V4 QUEUE OPERATIONS *******************************/
+
+/**
+ * tp4q_umem_new - Creates a new umem (packet buffer)
+ *
+ * @addr: The address to the umem
+ * @size: The size of the umem
+ * @frame_size: The size of each frame, between 2K and PAGE_SIZE
+ * @data_headroom: The desired data headroom before start of the packet
+ *
+ * Returns a pointer to the new umem or NULL for failure
+ **/
+static inline struct tp4_umem *tp4q_umem_new(unsigned long addr, size_t size,
+                                            unsigned int frame_size,
+                                            unsigned int data_headroom)
+{
+       struct tp4_umem *umem;
+       unsigned int nframes;
+
+       if (frame_size < TP4_UMEM_MIN_FRAME_SIZE || frame_size > PAGE_SIZE) {
+               /* Strictly speaking we could support this, if:
+                * - huge pages, or*
+                * - using an IOMMU, or
+                * - making sure the memory area is consecutive
+                * but for now, we simply say "computer says no".
+                */
+               return ERR_PTR(-EINVAL);
+       }
+
+       if (!is_power_of_2(frame_size))
+               return ERR_PTR(-EINVAL);
+
+       if (!PAGE_ALIGNED(addr)) {
+               /* Memory area has to be page size aligned. For
+                * simplicity, this might change.
+                */
+               return ERR_PTR(-EINVAL);
+       }
+
+       if ((addr + size) < addr)
+               return ERR_PTR(-EINVAL);
+
+       nframes = size / frame_size;
+       if (nframes == 0)
Quoted 8 lines

include/linux/tpacket4.h line 83

Quoted 6 lines
include/linux/tpacket4.h new file +6 -0
+               return ERR_PTR(-EINVAL);
+
+       data_headroom = ALIGN(data_headroom, 64);
+
+       if (frame_size - data_headroom - TP4_KERNEL_HEADROOM < 0)
+               return ERR_PTR(-EINVAL);

signed comparison on unsigned int

Thanks, will address in next revision!

#19 lore raw

Re: [RFC PATCH 03/14] packet: enable AF_PACKET V4 rings

In reply to Willem de Bruijn

2017-11-03 5:16 GMT+01:00 Willem de Bruijn <[email protected]>:

Quoted 15 lines
Quoted 15 lines
include/linux/tpacket4.h +15 -0
+/**
+ * tp4q_enqueue_from_array - Enqueue entries from packet array to tp4 queue
+ *
+ * @a: Pointer to the packet array to enqueue from
+ * @dcnt: Max number of entries to enqueue
+ *
+ * Returns 0 for success or an errno at failure
+ **/
+static inline int tp4q_enqueue_from_array(struct tp4_packet_array *a,
+                                         u32 dcnt)
+{
+       struct tp4_queue *q = a->tp4q;
+       unsigned int used_idx = q->used_idx;
+       struct tpacket4_desc *d = a->items;
+       int i;
Quoted 9 lines

include/linux/tpacket4.h static inline struct tp4_umem *tp4q_umem_new(unsigned long addr, size_t size, · line 212

Quoted 5 lines
include/linux/tpacket4.h +5 -0
+
+       if (q->num_free < dcnt)
+               return -ENOSPC;
+
+       q->num_free -= dcnt;

perhaps annotate with a lockdep_is_held to document which lock ensures mutual exclusion on the ring. Different for tx and rx?

Good idea. I'll give that a try!

Quoted 15 lines

net/packet/af_packet.c static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, · line 194

Quoted 11 lines
net/packet/af_packet.c +3 -0
index b39be424ec0e..190598eb3461 100644
@@ -189,6 +189,9 @@ static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
 #define BLOCK_O2PRIV(x)        ((x)->offset_to_priv)
 #define BLOCK_PRIV(x)          ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
 
+#define RX_RING 0
+#define TX_RING 1
+

Not needed if using bool for tx_ring below. The test effectively already treats it as bool: does not explicitly test these constants.

Quoted 10 lines

net/packet/af_packet.c packet_umem_new(unsigned long addr, size_t size, unsigned int frame_size, · line 3127

Quoted 7 lines
net/packet/af_packet.c +7 -0
+static void packet_clear_ring(struct sock *sk, int tx_ring)
+{
+       struct packet_sock *po = pkt_sk(sk);
+       struct packet_ring_buffer *rb;
+       union tpacket_req_u req_u;
+
+       rb = tx_ring ? &po->tx_ring : &po->rx_ring;

I meant here.

Yup, I'll remove/clean this up.

Björn

#34 lore raw
In reply to Willem de Bruijn
Quoted 28 lines

-----Original Message-----
From: Willem de Bruijn [mailto:[email protected]]
Sent: Friday, November 3, 2017 5:35 AM
To: Björn Töpel <[email protected]>
Cc: Karlsson, Magnus <[email protected]>; Duyck, Alexander H <[email protected]>; Alexander Duyck <[email protected]>; John Fastabend <[email protected]>; Alexei Starovoitov <[email protected]>; Jesper Dangaard Brouer <[email protected]>; [email protected]; [email protected]; Daniel Borkmann <[email protected]>; Network Development <[email protected]>; Topel, Bjorn <[email protected]>; Brandeburg, Jesse <[email protected]>; Singhai, Anjali <[email protected]>; Rosen, Rami <[email protected]>; Shaw, Jeffrey B <[email protected]>; Yigit, Ferruh <[email protected]>; Zhang, Qi Z <[email protected]>
Subject: Re: [RFC PATCH 00/14] Introducing AF_PACKET V4 support

Quoted 5 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This RFC introduces AF_PACKET_V4 and PACKET_ZEROCOPY that are optimized for high performance packet processing and zero-copy semantics. Throughput improvements can be up to 40x compared to V2

and

Quoted 8 lines
Quoted 5 lines

V3 for the micro benchmarks included. Would be great to get your feedback on it.

The main difference between V4 and V2/V3 is that TX and RX descriptors are separated from packet buffers.

Cool feature. I'm looking forward to the netdev talk. Aside from the inline comments in the patches, a few architecture questions.

Glad to hear. Are you going to Netdev in Seoul? If so, let us hook up and discuss your comments in further detail. Some initial thoughts below.

Quoted 5 lines

Is TX support needed? Existing PACKET_TX_RING already sends out packets without copying directly from the tx_ring. Indirection through a descriptor ring is not helpful on TX if all packets still have to come from a pre-registered packet pool. The patch set adds a lot of tx-only code and is complex enough without it.

That is correct, but what if the packet you are going to transmit came in from the receive path and is already in the packet buffer? This might happen if the application is examining/sniffing packets then sending them out, or doing some modification to them. In that case we avoid a copy in V4 since the packet is already in the packet buffer. With V2 and V3, a copy from the RX ring to the TX ring would be needed. In the PACKET_ZEROCOPY case, avoiding this copy increases performance quite a lot.

Quoted 5 lines

Can you use the existing PACKET_V2 format for the packet pool? The v4 format is nearly the same as V2. Using the same version might avoid some code duplication and simplify upgrading existing legacy code. Instead of continuing to add new versions whose behavior is implicit, perhaps we can add explicit mode PACKET_INDIRECT to PACKET_V2.

Interesting idea that I think is worth thinking more about. One problem though with the V2 ring format model, and the current V4 format too by the way, when applied to a user-space allocated memory is that they are symmetric, i.e. that user space and kernel space have to produce and consume the same amount of entries (within the length of the descriptor area). User space sends down a buffer entry that the kernel fills in for RX for example. Symmetric queues do not work when you have a shared packet buffer between two processes. (This is not a requirement, but someone might do a mmap with MAP_SHARED for the packet buffer and then fork of a child that then inherits this packet buffer.) One of the processes might just receive packets, while the other one is transmitting. Or if you have a veth link pair between two processes and they have been set up to share packet buffer area. With a symmetric queue you have to copy even if they share the same packet buffer, but with an asymmetric queue, you do not and the driver only needs to copy the packet buffer id between the TX desc ring of the sender to the RX desc ring of the receiver, not the data. I think this gives an indication that we need a new structure. Anyway, I like your idea and I think it is worth thinking more about it. Let us have a discussion about this at Netdev, if you are there.

Quoted 6 lines

Finally, is it necessary to define a new descriptor ring format? Same for the packet array and frame set. The kernel already has a few, such as virtio for the first, skb_array/ptr_ring, even linux list for the second. These containers add a lot of new boilerplate code. If new formats are absolutely necessary, at least we should consider making them generic (like skb_array and ptr_ring). But I'd like to understand first why, e.g., virtio cannot be used.

Agree with you. Good if we can use something existing. The descriptor format of V4 was based on one of the first Virtio 1.1 proposal by Michael Tsirkin (tools/virtio/ringtest/ring.c). Then we have diverged somewhat due to performance reasons and Virtio 1.1 has done the same but in another direction. We should take a look at the latest Virtio 1.1 proposal again and see what it offers. The reason we did not go with Virtio 0.9 was for performance. Too many indirections, something that the people behind Virtio 1.1 had identified too. With ptr_ring, how do we deal with the pointers in the structure as this now has to go to user-space? In any way, we would like to have a ring structure that is asymmetric for the reasons above. Other than that, we would not mind using anything as long as it is fast. If it already exists, perfect.

/Magnus

#25 lore raw

Re: [RFC PATCH 07/14] packet: wire up zerocopy for AF_PACKET V4

In reply to Willem de Bruijn

2017-11-03 4:17 GMT+01:00 Willem de Bruijn <[email protected]>:

Quoted 8 lines · Björn Töpel
Quoted 7 lines

From: Björn Töpel <[email protected]>

This commits adds support for zerocopy mode. Note that zerocopy mode requires that the network interface has been bound to the socket using the bind syscall, and that the corresponding netdev implements the AF_PACKET V4 ndos.

Quoted 15 lines

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3176

Quoted 12 lines

---

net/packet/af_packet.c +10 -0
+
+static void packet_v4_disable_zerocopy(struct net_device *dev,
+                                      struct tp4_netdev_parms *zc)
+{
+       struct tp4_netdev_parms params;
+
+       params = *zc;
+       params.command  = TP4_DISABLE;
+
+       (void)dev->netdev_ops->ndo_tp4_zerocopy(dev, &params);

Don't ignore error return codes.

Will fix!

Quoted 22 lines
Quoted 22 lines
net/packet/af_packet.c +22 -0
+static int packet_v4_zerocopy(struct sock *sk, int qp)
+{
+       struct packet_sock *po = pkt_sk(sk);
+       struct socket *sock = sk->sk_socket;
+       struct tp4_netdev_parms *zc = NULL;
+       struct net_device *dev;
+       bool if_up;
+       int ret = 0;
+
+       /* Currently, only RAW sockets are supported.*/
+       if (sock->type != SOCK_RAW)
+               return -EINVAL;
+
+       rtnl_lock();
+       dev = packet_cached_dev_get(po);
+
+       /* Socket needs to be bound to an interface. */
+       if (!dev) {
+               rtnl_unlock();
+               return -EISCONN;
+       }
+
Quoted 9 lines

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3243

Quoted 6 lines
net/packet/af_packet.c +6 -0
+       /* The device needs to have both the NDOs implemented. */
+       if (!(dev->netdev_ops->ndo_tp4_zerocopy &&
+             dev->netdev_ops->ndo_tp4_xmit)) {
+               ret = -EOPNOTSUPP;
+               goto out_unlock;
+       }

Inconsistent error handling with above test.

Will fix.

Quoted 10 lines

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3248

Quoted 5 lines
net/packet/af_packet.c +5 -0
+
+       if (!(po->rx_ring.pg_vec && po->tx_ring.pg_vec)) {
+               ret = -EOPNOTSUPP;
+               goto out_unlock;
+       }

A ring can be unmapped later with packet_set_ring. Should that operation fail if zerocopy is enabled? After that, it can also change version with PACKET_VERSION.

You're correct, I've missed this. I need to revisit the scenario when a ring is unmapped, and recreated. Thanks for pointing this out.

Quoted 15 lines
Quoted 15 lines
net/packet/af_packet.c +15 -0
+
+       if_up = dev->flags & IFF_UP;
+       zc = rtnl_dereference(po->zc);
+
+       /* Disable */
+       if (qp <= 0) {
+               if (!zc)
+                       goto out_unlock;
+
+               packet_v4_disable_zerocopy(dev, zc);
+               rcu_assign_pointer(po->zc, NULL);
+
+               if (if_up) {
+                       spin_lock(&po->bind_lock);
+                       register_prot_hook(sk);
Quoted 9 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+                       spin_unlock(&po->bind_lock);
+               }

There have been a bunch of race conditions in this bind code. We need to be very careful with adding more states to the locking, especially when open coding in multiple locations, as this patch does. I counted at least four bind locations. See for instance also
http://patchwork.ozlabs.org/patch/813945/

Yeah, the locking schemes in AF_PACKET is pretty convoluted. I'll document and make the locking more explicit (and avoiding open coding it).

Quoted 11 lines
Quoted 11 lines
net/packet/af_packet.c +10 -0
+
+               goto out_unlock;
+       }
+
+       /* Enable */
+       if (!zc) {
+               zc = kzalloc(sizeof(*zc), GFP_KERNEL);
+               if (!zc) {
+                       ret = -ENOMEM;
+                       goto out_unlock;
Quoted 9 lines

net/packet/af_packet.c static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) · line 3280

Quoted 5 lines
net/packet/af_packet.c +5 -0
+               }
+       }
+
+       if (zc->queue_pair >= 0)
+               packet_v4_disable_zerocopy(dev, zc);

This calls disable even if zc was freshly allocated. Shoud be > 0?

Good catch. It should be > 0.

Quoted 12 lines
Quoted 12 lines

static int packet_release(struct socket *sock)
{

net/packet/af_packet.c +2 -0
+       struct tp4_netdev_parms *zc;
        struct sock *sk = sock->sk;
+       struct net_device *dev;
        struct packet_sock *po;
        struct packet_fanout *f;
        struct net *net;
@@ -3337,6 +3541,20 @@ static int packet_release(struct socket *sock)
        sock_prot_inuse_add(net, sk->sk_prot, -1);
        preempt_enable();
 
Quoted 15 lines

net/packet/af_packet.c static int packet_release(struct socket *sock) · line 3556

Quoted 13 lines
net/packet/af_packet.c +13 -0
+       rtnl_lock();
+       zc = rtnl_dereference(po->zc);
+       dev = packet_cached_dev_get(po);
+       if (zc && dev)
+               packet_v4_disable_zerocopy(dev, zc);
+       if (dev)
+               dev_put(dev);
+       rtnl_unlock();
+
+       if (zc) {
+               synchronize_rcu();
+               kfree(zc);
+       }

Please use a helper function for anything this complex.

Will fix.

Thanks,
Björn

maintainer
#35 lore raw
In reply to Karlsson, Magnus
Quoted 34 lines · Magnus
Quoted 34 lines

-----Original Message-----
From: Willem de Bruijn [mailto:[email protected]]
Sent: Friday, November 3, 2017 5:35 AM
To: Björn Töpel <[email protected]>
Cc: Karlsson, Magnus <[email protected]>; Duyck, Alexander H <[email protected]>; Alexander Duyck <[email protected]>; John Fastabend <[email protected]>; Alexei Starovoitov <[email protected]>; Jesper Dangaard Brouer <[email protected]>; [email protected]; [email protected]; Daniel Borkmann <[email protected]>; Network Development <[email protected]>; Topel, Bjorn <[email protected]>; Brandeburg, Jesse <[email protected]>; Singhai, Anjali <[email protected]>; Rosen, Rami <[email protected]>; Shaw, Jeffrey B <[email protected]>; Yigit, Ferruh <[email protected]>; Zhang, Qi Z <[email protected]>
Subject: Re: [RFC PATCH 00/14] Introducing AF_PACKET V4 support

Quoted 5 lines · Björn Töpel

From: Björn Töpel <[email protected]>

This RFC introduces AF_PACKET_V4 and PACKET_ZEROCOPY that are optimized for high performance packet processing and zero-copy semantics. Throughput improvements can be up to 40x compared to V2

and

Quoted 5 lines

V3 for the micro benchmarks included. Would be great to get your feedback on it.

The main difference between V4 and V2/V3 is that TX and RX descriptors are separated from packet buffers.

Quoted 6 lines
Quoted 2 lines

Cool feature. I'm looking forward to the netdev talk. Aside from the inline comments in the patches, a few architecture questions.

Glad to hear. Are you going to Netdev in Seoul? If so, let us hook up and discuss your comments in further detail. Some initial thoughts below.

Sounds great. I'll be there.

Quoted 8 lines
Quoted 5 lines

Is TX support needed? Existing PACKET_TX_RING already sends out packets without copying directly from the tx_ring. Indirection through a descriptor ring is not helpful on TX if all packets still have to come from a pre-registered packet pool. The patch set adds a lot of tx-only code and is complex enough without it.

That is correct, but what if the packet you are going to transmit came in from the receive path and is already in the packet buffer?

Oh, yes, of course. That is a common use case. I should have thought of that.

Quoted 26 lines

This
might happen if the application is examining/sniffing packets then sending them out, or doing some modification to them. In that case we avoid a copy in V4 since the packet is already in the packet buffer. With V2 and V3, a copy from the RX ring to the TX ring would be needed. In the PACKET_ZEROCOPY case, avoiding this copy increases performance quite a lot.

Quoted 5 lines

Can you use the existing PACKET_V2 format for the packet pool? The v4 format is nearly the same as V2. Using the same version might avoid some code duplication and simplify upgrading existing legacy code. Instead of continuing to add new versions whose behavior is implicit, perhaps we can add explicit mode PACKET_INDIRECT to PACKET_V2.

Interesting idea that I think is worth thinking more about. One problem though with the V2 ring format model, and the current V4 format too by the way, when applied to a user-space allocated memory is that they are symmetric, i.e. that user space and kernel space have to produce and consume the same amount of entries (within the length of the descriptor area). User space sends down a buffer entry that the kernel fills in for RX for example. Symmetric queues do not work when you have a shared packet buffer between two processes. (This is not a requirement, but someone might do a mmap with MAP_SHARED for the packet buffer and then fork of a child that then inherits this packet buffer.) One of the processes might just receive packets, while the other one is transmitting. Or if you have a veth link pair between two

Quoted 8 lines

processes and they have been set up to share packet buffer area. With a symmetric queue you have to copy even if they share the same packet buffer, but with an asymmetric queue, you do not and the driver only needs to copy the packet buffer id between the TX desc ring of the sender to the RX desc ring of the receiver, not the data. I think this gives an indication that we need a new structure. Anyway, I like your idea and I think it is worth thinking more about it. Let us have a discussion about this at Netdev, if you are there.

Okay. I don't quite understand the definition of symmetric here. At least one problem that you describe, the veth pair, is solved by introducing descriptor rings as level of indirection, regardless of the format of the frames in the packet ring (now, really, random access packet pool).

Quoted 7 lines
Quoted 6 lines

Finally, is it necessary to define a new descriptor ring format? Same for the packet array and frame set. The kernel already has a few, such as virtio for the first, skb_array/ptr_ring, even linux list for the second. These containers add a lot of new boilerplate code. If new formats are absolutely necessary, at least we should consider making them generic (like skb_array and ptr_ring). But I'd like to understand first why, e.g., virtio cannot be used.

Quoted 13 lines

Agree with you. Good if we can use something existing. The descriptor format of V4 was based on one of the first Virtio 1.1 proposal by Michael Tsirkin (tools/virtio/ringtest/ring.c). Then we have diverged somewhat due to performance reasons and Virtio 1.1 has done the same but in another direction. We should take a look at the latest Virtio 1.1 proposal again and see what it offers. The reason we did not go with Virtio 0.9 was for performance. Too many indirections, something that the people behind Virtio 1.1 had identified too. With ptr_ring, how do we deal with the pointers in the structure as this now has to go to user-space? In any way, we would like to have a ring structure that is asymmetric for the reasons above. Other than that, we would not mind using anything as long as it is fast. If it already exists, perfect.

Thanks for that context. I was not aware that this format branched off of the early virtio 1.1 draft at all. Yes, I'm not sure where that stands and which workloads it is targeting. One issue is dealing with hw and minimizing communication over the PCI bus. That is not immediately relevant to this virtual descriptor model.

#36 lore raw
In reply to Björn Töpel

2017-10-31 13:41 GMT+01:00 Björn Töpel <[email protected]>:

Quoted 2 lines

From: Björn Töpel <[email protected]>

[...]

Quoted 5 lines

We'll do a presentation on AF_PACKET V4 in NetDev 2.2 [1] Seoul, Korea, and our paper with complete benchmarks will be released shortly on the NetDev 2.2 site.

We're back in the saddle after an excellent netdevconf week. Kudos to the organizers; We had a blast! Thanks for all the constructive feedback.

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos. Further, we'll have the zerocopy behavior for the skb path as well, meaning that an AF_ZEROCOPY socket will consume the skb and we'll honor skb->queue_mapping, meaning that we only consume the packets for the enabled queue.

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

* Minimize the size of the i40e zerocopy patches, by moving the driver specific code to separate patches.

* Do not introduce a new XDP action XDP_PASS_TO_KERNEL, instead use XDP redirect map call with ingress flag.

* Extend the XDP redirect to support explicit allocator/destructor functions. Right now, XDP redirect assumes that the page allocator was used, and the XDP redirect cleanup path is decreasing the page count of the XDP buffer. This assumption breaks for the zerocopy case.

Björn

Quoted 66 lines

We based this patch set on net-next commit e1ea2f9856b7 ("Merge
git://git.kernel.org/pub/scm/linux/kernel/git/davem/net").

Please focus your review on:

* The V4 user space interface
* PACKET_ZEROCOPY and its semantics
* Packet array interface
* XDP semantics when excuting in zero-copy mode (user space passed buffers)
* XDP_PASS_TO_KERNEL semantics

To do:

* Investigate the user-space ring structure’s performance problems
* Continue the XDP integration into packet arrays
* Optimize performance
* SKB <-> V4 conversions in tp4a_populate & tp4a_flush
* Packet buffer is unnecessarily pinned for virtual devices
* Support shared packet buffers
* Unify V4 and SKB receive path in I40E driver
* Support for packets spanning multiple frames
* Disassociate the packet array implementation from the V4 queue structure

We would really like to thank the reviewers of the limited distribution RFC for all their comments that have helped improve the interfaces and the code significantly: Alexei Starovoitov, Alexander Duyck, Jesper Dangaard Brouer, and John Fastabend. The internal team at Intel that has been helping out reviewing code, writing tests, and sanity checking our ideas: Rami Rosen, Jeff Shaw, Ferruh Yigit, and Qi Zhang, your participation has really helped.

Thanks: Björn and Magnus

[1] https://www.netdevconf.org/2.2/

Björn Töpel (7):
packet: introduce AF_PACKET V4 userspace API
packet: implement PACKET_MEMREG setsockopt
packet: enable AF_PACKET V4 rings
packet: wire up zerocopy for AF_PACKET V4
i40e: AF_PACKET V4 ndo_tp4_zerocopy Rx support
i40e: AF_PACKET V4 ndo_tp4_zerocopy Tx support
samples/tpacket4: added tpbench

Magnus Karlsson (7):
packet: enable Rx for AF_PACKET V4
packet: enable Tx support for AF_PACKET V4
netdevice: add AF_PACKET V4 zerocopy ops
veth: added support for PACKET_ZEROCOPY samples/tpacket4: added veth support
i40e: added XDP support for TP4 enabled queue pairs
xdp: introducing XDP_PASS_TO_KERNEL for PACKET_ZEROCOPY use

 drivers/net/ethernet/intel/i40e/i40e.h         |    3 +
 drivers/net/ethernet/intel/i40e/i40e_ethtool.c |    9 +
 drivers/net/ethernet/intel/i40e/i40e_main.c    |  837 ++++++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.c    |  582 ++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.h    |   38 +
 drivers/net/veth.c                             |  174 +++
 include/linux/netdevice.h                      |   16 +
 include/linux/tpacket4.h                       | 1502 ++++++++++++++++++++++++
 include/uapi/linux/bpf.h                       |    1 +
 include/uapi/linux/if_packet.h                 |   65 +-
 net/packet/af_packet.c                         | 1252 +++++++++++++++++-
#37 lore raw
Quoted 14 lines · Björn Töpel

2017-10-31 13:41 GMT+01:00 Björn Töpel <[email protected]>:

Quoted 2 lines

From: Björn Töpel <[email protected]>

[...]

Quoted 5 lines

We'll do a presentation on AF_PACKET V4 in NetDev 2.2 [1] Seoul, Korea, and our paper with complete benchmarks will be released shortly on the NetDev 2.2 site.

We're back in the saddle after an excellent netdevconf week. Kudos to the organizers; We had a blast! Thanks for all the constructive feedback.

Quoted 8 lines

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

Works for me.

Quoted 7 lines

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos. Further, we'll have the zerocopy behavior for the skb path as well, meaning that an AF_ZEROCOPY socket will consume the skb and we'll honor skb->queue_mapping, meaning that we only consume the packets for the enabled queue.

Quoted 9 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

* Minimize the size of the i40e zerocopy patches, by moving the driver specific code to separate patches.

* Do not introduce a new XDP action XDP_PASS_TO_KERNEL, instead use XDP redirect map call with ingress flag.

Sounds good we will need to add this as a separate patch series though.

Quoted 6 lines

* Extend the XDP redirect to support explicit allocator/destructor functions. Right now, XDP redirect assumes that the page allocator was used, and the XDP redirect cleanup path is decreasing the page count of the XDP buffer. This assumption breaks for the zerocopy case.

Probably sync with Andy and Jesper on this. I think they are both looking into something similar.

Thanks,
John

Quoted 4 lines

Björn

#38 lore raw
In reply to Björn Töpel
Quoted 29 lines · Björn Töpel

2017-10-31 13:41 GMT+01:00 Björn Töpel <[email protected]>:

Quoted 2 lines

From: Björn Töpel <[email protected]>

[...]

Quoted 5 lines

We'll do a presentation on AF_PACKET V4 in NetDev 2.2 [1] Seoul, Korea, and our paper with complete benchmarks will be released shortly on the NetDev 2.2 site.

We're back in the saddle after an excellent netdevconf week. Kudos to the organizers; We had a blast! Thanks for all the constructive feedback.

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos. Further, we'll have the zerocopy behavior for the skb path as well, meaning that an AF_ZEROCOPY socket will consume the skb and we'll honor skb->queue_mapping, meaning that we only consume the packets for the enabled queue.

Quoted 2 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

all sounds good to me except above bit.
I don't remember people suggesting to split it this way. What's the value of it without tx?

Quoted 95 lines

* Minimize the size of the i40e zerocopy patches, by moving the driver specific code to separate patches.

* Do not introduce a new XDP action XDP_PASS_TO_KERNEL, instead use XDP redirect map call with ingress flag.

* Extend the XDP redirect to support explicit allocator/destructor functions. Right now, XDP redirect assumes that the page allocator was used, and the XDP redirect cleanup path is decreasing the page count of the XDP buffer. This assumption breaks for the zerocopy case.

Björn

Quoted 79 lines

We based this patch set on net-next commit e1ea2f9856b7 ("Merge
git://git.kernel.org/pub/scm/linux/kernel/git/davem/net").

Please focus your review on:

* The V4 user space interface
* PACKET_ZEROCOPY and its semantics
* Packet array interface
* XDP semantics when excuting in zero-copy mode (user space passed buffers)
* XDP_PASS_TO_KERNEL semantics

To do:

* Investigate the user-space ring structure’s performance problems
* Continue the XDP integration into packet arrays
* Optimize performance
* SKB <-> V4 conversions in tp4a_populate & tp4a_flush
* Packet buffer is unnecessarily pinned for virtual devices
* Support shared packet buffers
* Unify V4 and SKB receive path in I40E driver
* Support for packets spanning multiple frames
* Disassociate the packet array implementation from the V4 queue structure

We would really like to thank the reviewers of the limited distribution RFC for all their comments that have helped improve the interfaces and the code significantly: Alexei Starovoitov, Alexander Duyck, Jesper Dangaard Brouer, and John Fastabend. The internal team at Intel that has been helping out reviewing code, writing tests, and sanity checking our ideas: Rami Rosen, Jeff Shaw, Ferruh Yigit, and Qi Zhang, your participation has really helped.

Thanks: Björn and Magnus

[1] https://urldefense.proofpoint.com/v2/url?u=https-3A__www.netdevconf.org_2.2_&d=DwIFaQ&c=5VD0RTtNlTh3ycd41b3MUw&r=qR6oNZj1CqLATni4ibTgAQ&m=lKyFxON3kKygiOgECLBfmqRwM7ZyXFSUvLED1vP-gos&s=44jzm1W8xkGyZSZVANRygzHz6y4XHbYrYBRM-K5RhTc&e=

Björn Töpel (7):
packet: introduce AF_PACKET V4 userspace API
packet: implement PACKET_MEMREG setsockopt
packet: enable AF_PACKET V4 rings
packet: wire up zerocopy for AF_PACKET V4
i40e: AF_PACKET V4 ndo_tp4_zerocopy Rx support
i40e: AF_PACKET V4 ndo_tp4_zerocopy Tx support
samples/tpacket4: added tpbench

Magnus Karlsson (7):
packet: enable Rx for AF_PACKET V4
packet: enable Tx support for AF_PACKET V4
netdevice: add AF_PACKET V4 zerocopy ops
veth: added support for PACKET_ZEROCOPY samples/tpacket4: added veth support
i40e: added XDP support for TP4 enabled queue pairs
xdp: introducing XDP_PASS_TO_KERNEL for PACKET_ZEROCOPY use

 drivers/net/ethernet/intel/i40e/i40e.h         |    3 +
 drivers/net/ethernet/intel/i40e/i40e_ethtool.c |    9 +
 drivers/net/ethernet/intel/i40e/i40e_main.c    |  837 ++++++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.c    |  582 ++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.h    |   38 +
 drivers/net/veth.c                             |  174 +++
 include/linux/netdevice.h                      |   16 +
 include/linux/tpacket4.h                       | 1502 ++++++++++++++++++++++++
 include/uapi/linux/bpf.h                       |    1 +
 include/uapi/linux/if_packet.h                 |   65 +-
 net/packet/af_packet.c                         | 1252 +++++++++++++++++---
 net/packet/internal.h                          |    9 +
 samples/tpacket4/Makefile                      |   12 +
 samples/tpacket4/bench_all.sh                  |   28 +
 samples/tpacket4/tpbench.c                     | 1390 ++++++++++++++++++++++
 15 files changed, 5674 insertions(+), 244 deletions(-)
 create mode 100644 include/linux/tpacket4.h
 create mode 100644 samples/tpacket4/Makefile
 create mode 100755 samples/tpacket4/bench_all.sh
 create mode 100644 samples/tpacket4/tpbench.c

--
2.11.0

#39 lore raw

2017-11-14 0:50 GMT+01:00 Alexei Starovoitov <[email protected]>:

Quoted 33 lines · Björn Töpel
Quoted 32 lines

2017-10-31 13:41 GMT+01:00 Björn Töpel <[email protected]>:

Quoted 3 lines

From: Björn Töpel <[email protected]>

[...]

Quoted 6 lines

We'll do a presentation on AF_PACKET V4 in NetDev 2.2 [1] Seoul, Korea, and our paper with complete benchmarks will be released shortly on the NetDev 2.2 site.

We're back in the saddle after an excellent netdevconf week. Kudos to the organizers; We had a blast! Thanks for all the constructive feedback.

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos. Further, we'll have the zerocopy behavior for the skb path as well, meaning that an AF_ZEROCOPY socket will consume the skb and we'll honor skb->queue_mapping, meaning that we only consume the packets for the enabled queue.

Quoted 8 lines
Quoted 2 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

all sounds good to me except above bit.
I don't remember people suggesting to split it this way. What's the value of it without tx?

We definitely need Tx for our use-cases! I'll rephrase, so the idea was making the initial patch set without Tx *driver* specific code, e.g. use ndo_xdp_xmit/flush at a later point.

So AF_ZEROCOPY, the socket parts, would have Tx support.

@John Did I recall that correctly?

Quoted 101 lines
Quoted 100 lines

* Minimize the size of the i40e zerocopy patches, by moving the driver specific code to separate patches.

* Do not introduce a new XDP action XDP_PASS_TO_KERNEL, instead use XDP redirect map call with ingress flag.

* Extend the XDP redirect to support explicit allocator/destructor functions. Right now, XDP redirect assumes that the page allocator was used, and the XDP redirect cleanup path is decreasing the page count of the XDP buffer. This assumption breaks for the zerocopy case.

Björn

Quoted 84 lines

We based this patch set on net-next commit e1ea2f9856b7 ("Merge
git://git.kernel.org/pub/scm/linux/kernel/git/davem/net").

Please focus your review on:

* The V4 user space interface
* PACKET_ZEROCOPY and its semantics
* Packet array interface
* XDP semantics when excuting in zero-copy mode (user space passed buffers)
* XDP_PASS_TO_KERNEL semantics

To do:

* Investigate the user-space ring structure’s performance problems
* Continue the XDP integration into packet arrays
* Optimize performance
* SKB <-> V4 conversions in tp4a_populate & tp4a_flush
* Packet buffer is unnecessarily pinned for virtual devices
* Support shared packet buffers
* Unify V4 and SKB receive path in I40E driver
* Support for packets spanning multiple frames
* Disassociate the packet array implementation from the V4 queue structure

We would really like to thank the reviewers of the limited distribution RFC for all their comments that have helped improve the interfaces and the code significantly: Alexei Starovoitov, Alexander Duyck, Jesper Dangaard Brouer, and John Fastabend. The internal team at Intel that has been helping out reviewing code, writing tests, and sanity checking our ideas: Rami Rosen, Jeff Shaw, Ferruh Yigit, and Qi Zhang, your participation has really helped.

Thanks: Björn and Magnus

[1]
https://urldefense.proofpoint.com/v2/url?u=https-3A__www.netdevconf.org_2.2_&d=DwIFaQ&c=5VD0RTtNlTh3ycd41b3MUw&r=qR6oNZj1CqLATni4ibTgAQ&m=lKyFxON3kKygiOgECLBfmqRwM7ZyXFSUvLED1vP-gos&s=44jzm1W8xkGyZSZVANRygzHz6y4XHbYrYBRM-K5RhTc&e=

Björn Töpel (7):
packet: introduce AF_PACKET V4 userspace API
packet: implement PACKET_MEMREG setsockopt
packet: enable AF_PACKET V4 rings
packet: wire up zerocopy for AF_PACKET V4
i40e: AF_PACKET V4 ndo_tp4_zerocopy Rx support
i40e: AF_PACKET V4 ndo_tp4_zerocopy Tx support
samples/tpacket4: added tpbench

Magnus Karlsson (7):
packet: enable Rx for AF_PACKET V4
packet: enable Tx support for AF_PACKET V4
netdevice: add AF_PACKET V4 zerocopy ops
veth: added support for PACKET_ZEROCOPY samples/tpacket4: added veth support
i40e: added XDP support for TP4 enabled queue pairs
xdp: introducing XDP_PASS_TO_KERNEL for PACKET_ZEROCOPY use

 drivers/net/ethernet/intel/i40e/i40e.h         |    3 +
 drivers/net/ethernet/intel/i40e/i40e_ethtool.c |    9 +
 drivers/net/ethernet/intel/i40e/i40e_main.c    |  837 ++++++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.c    |  582 ++++++++-
 drivers/net/ethernet/intel/i40e/i40e_txrx.h    |   38 +
 drivers/net/veth.c                             |  174 +++
 include/linux/netdevice.h                      |   16 +
 include/linux/tpacket4.h                       | 1502
++++++++++++++++++++++++
 include/uapi/linux/bpf.h                       |    1 +
 include/uapi/linux/if_packet.h                 |   65 +-
 net/packet/af_packet.c                         | 1252
+++++++++++++++++---
 net/packet/internal.h                          |    9 +
 samples/tpacket4/Makefile                      |   12 +
 samples/tpacket4/bench_all.sh                  |   28 +
 samples/tpacket4/tpbench.c                     | 1390
++++++++++++++++++++++
 15 files changed, 5674 insertions(+), 244 deletions(-)
 create mode 100644 include/linux/tpacket4.h
 create mode 100644 samples/tpacket4/Makefile
 create mode 100755 samples/tpacket4/bench_all.sh
 create mode 100644 samples/tpacket4/tpbench.c

--
2.11.0

#40 lore raw
Quoted 43 lines · Björn Töpel

2017-11-14 0:50 GMT+01:00 Alexei Starovoitov <[email protected]>:

Quoted 33 lines · Björn Töpel
Quoted 32 lines

2017-10-31 13:41 GMT+01:00 Björn Töpel <[email protected]>:

Quoted 3 lines

From: Björn Töpel <[email protected]>

[...]

Quoted 6 lines

We'll do a presentation on AF_PACKET V4 in NetDev 2.2 [1] Seoul, Korea, and our paper with complete benchmarks will be released shortly on the NetDev 2.2 site.

We're back in the saddle after an excellent netdevconf week. Kudos to the organizers; We had a blast! Thanks for all the constructive feedback.

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos. Further, we'll have the zerocopy behavior for the skb path as well, meaning that an AF_ZEROCOPY socket will consume the skb and we'll honor skb->queue_mapping, meaning that we only consume the packets for the enabled queue.

Quoted 8 lines
Quoted 2 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

all sounds good to me except above bit.
I don't remember people suggesting to split it this way. What's the value of it without tx?

Quoted 8 lines

We definitely need Tx for our use-cases! I'll rephrase, so the idea was making the initial patch set without Tx *driver* specific code, e.g. use ndo_xdp_xmit/flush at a later point.

So AF_ZEROCOPY, the socket parts, would have Tx support.

@John Did I recall that correctly?

Yep, that is what I said. However, on second thought, without the driver tx half I guess tx will be significantly slower. So in order to get the driver API correct in the first go around lets implement this in the first series as well.

Just try to minimize the TX driver work as much as possible.

Thanks,
John

maintainer
#41 lore raw
Quoted 14 lines
Quoted 14 lines
Quoted 9 lines
Quoted 3 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

all sounds good to me except above bit.
I don't remember people suggesting to split it this way. What's the value of it without tx?

We definitely need Tx for our use-cases! I'll rephrase, so the idea was making the initial patch set without Tx *driver* specific code, e.g. use ndo_xdp_xmit/flush at a later point.

Quoted 7 lines
Quoted 4 lines

So AF_ZEROCOPY, the socket parts, would have Tx support.

@John Did I recall that correctly?

Yep, that is what I said. However, on second thought, without the driver tx half I guess tx will be significantly slower.

The idea was that existing packet rings already send without copying, so the benefit from device driver changes is not obvious.

I would leave them out for now and evaluate before possibly sending a separate patchset.

#46 lore raw

Re: [RFC PATCH 00/14] Introducing AF_PACKET V4 support (AF_XDP or AF_CHANNEL?)

In reply to Björn Töpel
Quoted 7 lines · On Mon, 13 Nov 2017 22:07:47 +0900 Björn Töpel <[email protected]> wrote:

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

I mostly like AF_CHANNEL and AF_XDP. I do know XDP is/have-evolved-into a kernel-side facility, that moves XDP-frames/packets _inside_ the kernel.

*BUT* I've always imagined, that we would create a "channel" to userspace. By using XDP_REDIRECT to choose what frames get redirected into which userspace "channel" (new channel-map type). Userspace pre-allocate and register memory/pages exactly like this patchset.

[Step-1]: (non-ZC) XDP_REDIRECT need to copy frame-data into userspace memory pages. And update your packet_array etc. (Use map-flush to get RX bulking).

[Step 2]: (ZC) Userspace call driver NDO to register pages. The XDP_REDIRECT action happens in driver, and can have knowledge about RX-ring. It can know if this RX-ring is Zero-Copy enabled and can skip the copy-step.

Quoted 3 lines

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos.

When driver does not support NDO in above model. I think, that there will still be a significant performance boost for the non-ZC variant. Even-though we need a copy-operation, because there are no memory allocations. As userspace have preallocated and registered pages with the kernel (and mem-limits are implicit via mem-size reg by userspace).

Quoted 2 lines

* Do not introduce a new XDP action XDP_PASS_TO_KERNEL, instead use XDP redirect map call with ingress flag.

In above model, XDP_REDIRECT is used for filtering into a userspace "channel". If ZC gets enabled on a RX-ring queue, then XDP_PASS have to do a copy (RX-ring knowledge is avail), like you describe with XDP_PASS_TO_KERNEL.

Quoted 5 lines

* Extend the XDP redirect to support explicit allocator/destructor functions. Right now, XDP redirect assumes that the page allocator was used, and the XDP redirect cleanup path is decreasing the page count of the XDP buffer. This assumption breaks for the zerocopy case.

Yes, please. If XDP_REDIRECT get call a destructor call-back, then we can allow XDP_REDIRECT out another net_device, even-when ZC is enabled on a RX-ring queue.

Signature · 4 lines
Best regards,
  Jesper Dangaard Brouer
  MSc.CS, Principal Kernel Engineer at Red Hat
  LinkedIn: http://www.linkedin.com/in/brouer
#47 lore raw

Re: [RFC PATCH 00/14] Introducing AF_PACKET V4 support (AF_XDP or AF_CHANNEL?)

2017-11-14 18:19 GMT+01:00 Jesper Dangaard Brouer <[email protected]>:

Quoted 20 lines · On Mon, 13 Nov 2017 22:07:47 +0900 Björn Töpel <[email protected]> wrote:
Quoted 8 lines

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

I mostly like AF_CHANNEL and AF_XDP. I do know XDP is/have-evolved-into a kernel-side facility, that moves XDP-frames/packets _inside_ the kernel.

*BUT* I've always imagined, that we would create a "channel" to userspace. By using XDP_REDIRECT to choose what frames get redirected into which userspace "channel" (new channel-map type). Userspace pre-allocate and register memory/pages exactly like this patchset.

Quoted 9 lines

[Step-1]: (non-ZC) XDP_REDIRECT need to copy frame-data into userspace memory pages. And update your packet_array etc. (Use map-flush to get RX bulking).

[Step 2]: (ZC) Userspace call driver NDO to register pages. The XDP_REDIRECT action happens in driver, and can have knowledge about RX-ring. It can know if this RX-ring is Zero-Copy enabled and can skip the copy-step.

Jesper, I *really* like this approach -- especially the fact that the existing XDP path in the drivers can be reused. I'll spend some time dissecting the details of your suggestion.

Quoted 10 lines
Quoted 3 lines

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos.

When driver does not support NDO in above model. I think, that there will still be a significant performance boost for the non-ZC variant. Even-though we need a copy-operation, because there are no memory allocations. As userspace have preallocated and registered pages with the kernel (and mem-limits are implicit via mem-size reg by userspace).

Yup, and we're not paying for the whole skb creation, given that we execute from XDP_DRV and not XDP_SKB.

Quoted 8 lines
Quoted 2 lines

* Do not introduce a new XDP action XDP_PASS_TO_KERNEL, instead use XDP redirect map call with ingress flag.

In above model, XDP_REDIRECT is used for filtering into a userspace "channel". If ZC gets enabled on a RX-ring queue, then XDP_PASS have to do a copy (RX-ring knowledge is avail), like you describe with XDP_PASS_TO_KERNEL.

Again, this fits nicely in.

Quoted 15 lines
Quoted 5 lines

* Extend the XDP redirect to support explicit allocator/destructor functions. Right now, XDP redirect assumes that the page allocator was used, and the XDP redirect cleanup path is decreasing the page count of the XDP buffer. This assumption breaks for the zerocopy case.

Yes, please. If XDP_REDIRECT get call a destructor call-back, then we can allow XDP_REDIRECT out another net_device, even-when ZC is enabled on a RX-ring queue.

--
Best regards,
Jesper Dangaard Brouer
MSc.CS, Principal Kernel Engineer at Red Hat
LinkedIn: http://www.linkedin.com/in/brouer

#8 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to Björn Töpel
Quoted 7 lines

Actually, we started out with that approach, where the packet_mmap call mapped Tx/Rx descriptor rings and the packet buffer region. We later moved to this (register umem) approach, because it's more flexible for user space, not having to use a AF_PACKET specific allocator (i.e. continue to use regular mallocs, huge pages and such).

One quick question:
Any thoughts on SVM support?
Is SVM support going to be so disruptive that we will need to churn a tp_v5?

If not then to accommodate future SVM enablement do you think it might make sense to add/stuff a control-info union in the tp4_queue (or umem etc). And then in the future, I think setmemreg (or something else) would need to pass the PASID in addition to the malloc'd addr. Assumption here is that the user-app will bind PID<->PASID before invoking the AF_ZC setup.

Quoted 1 line

Björn

Chetan

#11 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to Björn Töpel
Quoted 15 lines · Björn Töpel

From: Björn Töpel <[email protected]>

include/uapi/linux/if_packet.h +12 -0
+/*
+ * struct tpacket_memreg_req is used in conjunction with PACKET_MEMREG
+ * to register user memory which should be used to store the packet
+ * data.
+ *
+ * There are some constraints for the memory being registered:
+ * - The memory area has to be memory page size aligned.
+ * - The frame size has to be a power of 2.
+ * - The frame size cannot be smaller than 2048B.
+ * - The frame size cannot be larger than the memory page size.
+ *
+ * Corollary: The number of frames that can be stored is

include/uapi/linux/if_packet.h struct packet_mreq { · line 359

Quoted 10 lines
include/uapi/linux/if_packet.h +10 -0
+ * len / frame_size.
+ *
+ */
+struct tpacket_memreg_req {
+       unsigned long   addr;           /* Start of packet data area */
+       unsigned long   len;            /* Length of packet data area */
+       unsigned int    frame_size;     /* Frame size */
+       unsigned int    data_headroom;  /* Frame head room */
+};
+

I have not reviewed the entire patchset but I think if we could add a version_hdr and then unionize the fields, it might be easier to add SVM support without having to spin v5. I could be wrong though.

Chetan

maintainer
#12 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

From: chet l <[email protected]>
Date: Wed, 15 Nov 2017 14:34:32 -0800

Quoted 3 lines

I have not reviewed the entire patchset but I think if we could add a version_hdr and then unionize the fields, it might be easier to add SVM support without having to spin v5. I could be wrong though.

Please, NO VERSION FIELDS!

Design things properly from the start rather than using a crutch of being able to "adjust things later".

#42 lore raw
In reply to Willem de Bruijn
Quoted 19 lines · Willem de Bruijn
Quoted 19 lines
Quoted 18 lines
Quoted 9 lines
Quoted 3 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

all sounds good to me except above bit.
I don't remember people suggesting to split it this way. What's the value of it without tx?

We definitely need Tx for our use-cases! I'll rephrase, so the idea was making the initial patch set without Tx *driver* specific code, e.g. use ndo_xdp_xmit/flush at a later point.

So AF_ZEROCOPY, the socket parts, would have Tx support.

@John Did I recall that correctly?

Quoted 8 lines
Quoted 2 lines

Yep, that is what I said. However, on second thought, without the driver tx half I guess tx will be significantly slower.

The idea was that existing packet rings already send without copying, so the benefit from device driver changes is not obvious.

I would leave them out for now and evaluate before possibly sending a separate patchset.

are you suggesting to use new af_zerocopy for rx and old af_packet for tx ? imo that's too cumbersome to use. New interface has to be symmetrical from the start.

maintainer
#43 lore raw
Quoted 29 lines · Alexei Starovoitov
Quoted 28 lines · Willem de Bruijn
Quoted 16 lines
Quoted 16 lines
Quoted 11 lines
Quoted 4 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

all sounds good to me except above bit.
I don't remember people suggesting to split it this way. What's the value of it without tx?

We definitely need Tx for our use-cases! I'll rephrase, so the idea was making the initial patch set without Tx *driver* specific code, e.g. use ndo_xdp_xmit/flush at a later point.

Quoted 7 lines
Quoted 4 lines

So AF_ZEROCOPY, the socket parts, would have Tx support.

@John Did I recall that correctly?

Yep, that is what I said. However, on second thought, without the driver tx half I guess tx will be significantly slower.

The idea was that existing packet rings already send without copying, so the benefit from device driver changes is not obvious.

Quoted 7 lines
Quoted 2 lines

I would leave them out for now and evaluate before possibly sending a separate patchset.

are you suggesting to use new af_zerocopy for rx and old af_packet for tx ? imo that's too cumbersome to use. New interface has to be symmetrical from the start.

No, that tx can be implemented without device driver changes. At least initially.

Unlike rx, tx does not need driver support to implement copy avoidance, as pf_packet tx_ring already has this.

Having to go through ndo_start_xmit does introduce other overhead, notably skb alloc. Perhaps ndo_xdp_xmit is a better choice (but I'm not very familiar with that).

If some cost is inherent to a device-independent solution and needs driver support to avoid it, then that can be added in a follow-on patchset. But this one is large already without the i40e tx patch.

#44 lore raw

2017-11-16 4:35 GMT+01:00 Willem de Bruijn <[email protected]>:

Quoted 44 lines · Alexei Starovoitov
Quoted 29 lines · Willem de Bruijn
Quoted 28 lines
Quoted 16 lines
Quoted 16 lines
Quoted 11 lines
Quoted 4 lines

* Limit the scope of the first patchset to Rx only, and introduce Tx in a separate patchset.

all sounds good to me except above bit.
I don't remember people suggesting to split it this way. What's the value of it without tx?

We definitely need Tx for our use-cases! I'll rephrase, so the idea was making the initial patch set without Tx *driver* specific code, e.g. use ndo_xdp_xmit/flush at a later point.

Quoted 7 lines
Quoted 4 lines

So AF_ZEROCOPY, the socket parts, would have Tx support.

@John Did I recall that correctly?

Yep, that is what I said. However, on second thought, without the driver tx half I guess tx will be significantly slower.

The idea was that existing packet rings already send without copying, so the benefit from device driver changes is not obvious.

Quoted 7 lines
Quoted 2 lines

I would leave them out for now and evaluate before possibly sending a separate patchset.

are you suggesting to use new af_zerocopy for rx and old af_packet for tx ? imo that's too cumbersome to use. New interface has to be symmetrical from the start.

No, that tx can be implemented without device driver changes. At least initially.

Unlike rx, tx does not need driver support to implement copy avoidance, as pf_packet tx_ring already has this.

Quoted 8 lines

Having to go through ndo_start_xmit does introduce other overhead, notably skb alloc. Perhaps ndo_xdp_xmit is a better choice (but I'm not very familiar with that).

If some cost is inherent to a device-independent solution and needs driver support to avoid it, then that can be added in a follow-on patchset. But this one is large already without the i40e tx patch.

Ideally, it would be best not having to introduce yet another xmit ndo. I believe ndo_xdp_xmit/ndo_xdp_flush would be the best fit, but we need to extend it with a destructor callback and potentially some kind of DMA trait. Why DMA? For zerocopy, we know the working set of packet buffers, so they are DMA mapped up front, whereas ndo_xdp_xmit does yet another DMA mapping. Paying for the DMA mapping in the fast-path is something we'd like to avoid.

#48 lore raw

Re: [RFC PATCH 00/14] Introducing AF_PACKET V4 support (AF_XDP or AF_CHANNEL?)

In reply to Björn Töpel
Quoted 31 lines · On Tue, 14 Nov 2017 20:01:01 +0100 Björn Töpel <[email protected]> wrote:

2017-11-14 18:19 GMT+01:00 Jesper Dangaard Brouer <[email protected]>:

Quoted 20 lines · On Mon, 13 Nov 2017 22:07:47 +0900 Björn Töpel <[email protected]> wrote:
Quoted 8 lines

I'll summarize the major points, that we'll address in the next RFC below.

* Instead of extending AF_PACKET with yet another version, introduce a new address/packet family. As for naming had some name suggestions:
AF_CAPTURE, AF_CHANNEL, AF_XDP and AF_ZEROCOPY. We'll go for AF_ZEROCOPY, unless there're no strong opinions against it.

I mostly like AF_CHANNEL and AF_XDP. I do know XDP is/have-evolved-into a kernel-side facility, that moves XDP-frames/packets _inside_ the kernel.

*BUT* I've always imagined, that we would create a "channel" to userspace. By using XDP_REDIRECT to choose what frames get redirected into which userspace "channel" (new channel-map type). Userspace pre-allocate and register memory/pages exactly like this patchset.

Quoted 9 lines

[Step-1]: (non-ZC) XDP_REDIRECT need to copy frame-data into userspace memory pages. And update your packet_array etc. (Use map-flush to get RX bulking).

[Step 2]: (ZC) Userspace call driver NDO to register pages. The XDP_REDIRECT action happens in driver, and can have knowledge about RX-ring. It can know if this RX-ring is Zero-Copy enabled and can skip the copy-step.

Quoted 3 lines

Jesper, I *really* like this approach -- especially the fact that the existing XDP path in the drivers can be reused. I'll spend some time dissecting the details of your suggestion.

I'm very happy that you like this approach :-)

Quoted 11 lines
Quoted 10 lines
Quoted 3 lines

* No explicit zerocopy enablement. Use the zeropcopy path if supported, if not -- fallback to the skb path, for netdevs that don't support the required ndos.

When driver does not support NDO in above model. I think, that there will still be a significant performance boost for the non-ZC variant. Even-though we need a copy-operation, because there are no memory allocations. As userspace have preallocated and registered pages with the kernel (and mem-limits are implicit via mem-size reg by userspace).

Quoted 2 lines

Yup, and we're not paying for the whole skb creation, given that we execute from XDP_DRV and not XDP_SKB.

Yes, exactly. Avoiding the SKB allocation for non-ZC mode will be a significant saving. As your benchmarks showed, the AF_PACKET-V4 approach for non-ZC mode does not give you/us any real performance improvement. This approach would.

Quoted 20 lines
Quoted 8 lines
Quoted 2 lines

* Do not introduce a new XDP action XDP_PASS_TO_KERNEL, instead use XDP redirect map call with ingress flag.

In above model, XDP_REDIRECT is used for filtering into a userspace "channel". If ZC gets enabled on a RX-ring queue, then XDP_PASS have to do a copy (RX-ring knowledge is avail), like you describe with XDP_PASS_TO_KERNEL.

Again, this fits nicely in.

Quoted 9 lines
Quoted 5 lines

* Extend the XDP redirect to support explicit allocator/destructor functions. Right now, XDP redirect assumes that the page allocator was used, and the XDP redirect cleanup path is decreasing the page count of the XDP buffer. This assumption breaks for the zerocopy case.

Yes, please. If XDP_REDIRECT get call a destructor call-back, then we can allow XDP_REDIRECT out another net_device, even-when ZC is enabled on a RX-ring queue.

I will (of-cause) be eager to test and benchmark this approach, as I have high hopes a performance boost even for non-ZC. I know an AF_XDP approach is a lot of work, but I would like to offer to help-out in anyway I can.

Signature · 4 lines
Best regards,
  Jesper Dangaard Brouer
  MSc.CS, Principal Kernel Engineer at Red Hat
  LinkedIn: http://www.linkedin.com/in/brouer
#45 lore raw
In reply to Björn Töpel
Quoted 7 lines · On Thu, 16 Nov 2017 08:09:04 +0100 Björn Töpel <[email protected]> wrote:

Ideally, it would be best not having to introduce yet another xmit ndo. I believe ndo_xdp_xmit/ndo_xdp_flush would be the best fit, but we need to extend it with a destructor callback and potentially some kind of DMA trait. Why DMA? For zerocopy, we know the working set of packet buffers, so they are DMA mapped up front, whereas ndo_xdp_xmit does yet another DMA mapping. Paying for the DMA mapping in the fast-path is something we'd like to avoid.

I like your idea of reusing ndo_xdp_xmit/ndo_xdp_flush. At NetConf I think we agreed that the ndo_xdp_xmit API likely need to change. See[1] slide 11. Andy Gospodarek and Michael Chan wanted to look into the needed API changes (Cc'ed) thus, lets keep them in the loop.

I also appreciate that you are thinking about avoiding the DMA-mapping at TX. It would be a welcomed optimization.

[1] http://people.netfilter.org/hawk/presentations/NetConf2017_Seoul/XDP_devel_update_NetConf2017_Seoul.pdf

Signature · 4 lines
Best regards,
  Jesper Dangaard Brouer
  MSc.CS, Principal Kernel Engineer at Red Hat
  LinkedIn: http://www.linkedin.com/in/brouer
#9 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to chet l
Quoted 2 lines · On Wed, 15 Nov 2017 14:21:38 -0800 chet l <[email protected]> wrote:

One quick question:
Any thoughts on SVM support?

What is SVM ?

Signature · 4 lines
Best regards,
  Jesper Dangaard Brouer
  MSc.CS, Principal Kernel Engineer at Red Hat
  LinkedIn: http://www.linkedin.com/in/brouer
#13 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to David Miller
Quoted 11 lines · David Miller

From: chet l <[email protected]>
Date: Wed, 15 Nov 2017 14:34:32 -0800

Quoted 3 lines

I have not reviewed the entire patchset but I think if we could add a version_hdr and then unionize the fields, it might be easier to add SVM support without having to spin v5. I could be wrong though.

Please, NO VERSION FIELDS!

Design things properly from the start rather than using a crutch of being able to "adjust things later".

Agreed. If this step in tpkt_v4 is able to follow what req1/2/3 did as part of the setsockopt(..) API then it should be ok. If its a different API then it will be difficult for the follow-on version(s) to make seamless changes.

Look at tpacket_req3 for example. Since there was no hdr, I had no option but to align the fields with tpacket_req/req2 during the setup. I won't have access to a SMMUv3 capable ARM platform anytime soon. So I can't actually test/write anything as of now.

Chetan

#10 lore raw

Re: [RFC PATCH 01/14] packet: introduce AF_PACKET V4 userspace API

In reply to Jesper Dangaard Brouer
Quoted 8 lines · Jesper Dangaard Brouer
Quoted 2 lines · On Wed, 15 Nov 2017 14:21:38 -0800 chet l <[email protected]> wrote:

One quick question:
Any thoughts on SVM support?

What is SVM ?

Shared Virtual Memory(PCIe based). So going back to one of your mapping examples. The protocol can be AF_CHANNEL. Modes could be:
AF_ZC , AF_XDP_REDIRECT

Mapping types could be:
AF_NON_SVM(current setup - no PASID needed), AF_SVM(onus is on the user to pass the PASID as part of the setsockopt), AF_SVM++

Chetan