socket sendmsg MSG_ZEROCOPY
Subsystems (17)
Willem de Bruijn
maintainerv2 cover socket sendmsg MSG_ZEROCOPY
From: Willem de Bruijn <[email protected]>
Introduce zerocopy socket send flag MSG_ZEROCOPY. This extends the shared page support (SKBTX_SHARED_FRAG) from sendpage to sendmsg. Implement the feature for TCP, UDP, RAW and packet sockets.
On a send call with MSG_ZEROCOPY, the kernel pins user pages and links these directly into the skbuff frags[] array.
Each send call with MSG_ZEROCOPY that transmits data will eventually queue a completion notification on the error queue: a per-socket u32 incremented on each such call. A request may have to revert to copy to succeed, for instance when a device cannot support scatter-gather IO. In that case a flag is passed along to notify that the operation succeeded without zerocopy optimization.
The implementation extends the existing zerocopy infra for tuntap, vhost and xen with features needed for TCP, notably reference counting to handle cloning on retransmit and GSO.
For more details, see also the netdev 2.1 paper and presentation at
https://netdevconf.org/2.1/session.html?debruijn
Changelog:
v1 -> v2:
- fix (kbuild-bot): do not remove uarg until patch 5
- fix (kbuild-bot): move zerocopy_sg_from_iter doc with function
- fix: remove unused extern in header file
RFCv2 -> v1:
- patch 2
- review comment: in skb_copy_ubufs, always allocate order-0 page, also when replacing compound source pages.
- patch 3
- fix: always queue completion notification on MSG_ZEROCOPY, also if revert to copy.
- fix: on syscall abort, correctly revert notification state
- minor: skip queue notification on SOCK_DEAD
- minor: replace BUG_ON with WARN_ON in recoverable error
- patch 4
- new: add socket option SOCK_ZEROCOPY.
only honor MSG_ZEROCOPY if set, ignore for legacy apps.
- patch 5
- fix: clear zerocopy state on skb_linearize
- patch 6
- fix: only coalesce if prev errqueue elem is zerocopy
- minor: try coalescing with list tail instead of head
- minor: merge bytelen limit patch
- patch 7
- new: signal when data had to be copied
- patch 8 (tcp)
- optimize: avoid setting PSH bit when exceeding max frags. that limits GRO on the client. do not goto new_segment.
- fix: fail on MSG_ZEROCOPY | MSG_FASTOPEN
- minor: do not wait for memory: does not work for optmem
- minor: simplify alloc
- patch 9 (udp)
- new: add PF_INET6
- fix: attach zerocopy notification even if revert to copy
- minor: simplify alloc size arithmetic
- patch 10 (raw hdrinc)
- new: add PF_INET6
- patch 11 (pf_packet)
- minor: simplify slightly
- patch 12
- new msg_zerocopy regression test: use veth pair to test all protocols: ipv4/ipv6/packet, tcp/udp/raw, cork all relevant ethtool settings: rx off, sg off all relevant packet lengths: 0, <MAX_HEADER, max size
RFC -> RFCv2:
- review comment: do not loop skb with zerocopy frags onto rx:
add skb_orphan_frags_rx to orphan even refcounted frags call this in __netif_receive_skb_core, deliver_skb and tun:
the same as 1080e512d44d ("net: orphan frags on receive")
- fix: hold an explicit sk reference on each notification skb. previously relied on the reference (or wmem) held by the data skb that would trigger notification, but this breaks on skb_orphan.
- fix: when aborting a send, do not inc the zerocopy counter this caused gaps in the notification chain
- fix: in packet with SOCK_DGRAM, pull ll headers before calling zerocopy_sg_from_iter
- fix: if sock_zerocopy_realloc does not allow coalescing, do not fail, just allocate a new ubuf
- fix: in tcp, check return value of second allocation attempt
- chg: allocate notification skbs from optmem
to avoid affecting tcp write queue accounting (TSQ)
- chg: limit #locked pages (ulimit) per user instead of per process
- chg: grow notification ids from 16 to 32 bit
- pass range [lo, hi] through 32 bit fields ee_info and ee_data
- chg: rebased to davem-net-next on top of v4.10-rc7
- add: limit notification coalescing
sharing ubufs limits overhead, but delays notification until the last packet is released, possibly unbounded. Add a cap.
- tests: add snd_zerocopy_lo pf_packet test
- tests: two bugfixes (add do_flush_tcp, ++sent not only in debug)
Limitations / Known Issues:
- TCP may build slightly smaller than max TSO packets due to exceeding MAX_SKB_FRAGS frags when zerocopy pages are unaligned.
- All SKBTX_SHARED_FRAG may require additional __skb_linearize or skb_copy_ubufs calls in u32, skb_find_text, similar to skb_checksum_help.
- UDP and RAW may be of limited use without loopback due to MTU being too small to see copy avoidance gains.
Notification skbuffs are allocated from optmem. For sockets that cannot effectively coalesce notifications, the optmem max may need to be increased to avoid hitting -ENOBUFS:
sysctl -w net.core.optmem_max=1048576
In application load, copy avoidance shows a roughly 5% systemwide reduction in cycles when streaming large flows and a 4-8% reduction in wall clock time on early tensorflow test workloads.
For the single-machine veth tests to succeed, loopback support has to be temporarily enabled by making skb_orphan_frags_rx map to skb_orphan_frags.
* Performance
The below table shows cycles reported by perf for a netperf process sending a single 10 Gbps TCP_STREAM. The first three columns show Mcycles spent in the netperf process context. The second three columns show time spent systemwide (-a -C A,B) on the two cpus that run the process and interrupt handler. Reported is the median of at least 3 runs. std is a standard netperf, zc uses zerocopy and % is the ratio. Netperf is pinned to cpu 2, network interrupts to cpu3, rps and rfs are disabled and the kernel is booted with idle=halt.
NETPERF=./netperf -t TCP_STREAM -H $host -T 2 -l 30 -- -m $size
perf stat -e cycles $NETPERF
perf stat -C 2,3 -a -e cycles $NETPERF
--process cycles-- ----cpu cycles----
std zc % std zc %
4K 27,609 11,217 41 49,217 39,175 79
16K 21,370 3,823 18 43,540 29,213 67
64K 20,557 2,312 11 42,189 26,910 64
256K 21,110 2,134 10 43,006 27,104 63
1M 20,987 1,610 8 42,759 25,931 61Perf record indicates the main source of these differences. Process cycles only at 1M writes (perf record; perf report -n):
std:
Samples: 42K of event 'cycles', Event count (approx.): 21258597313
79.41% 33884 netperf [kernel.kallsyms] [k] copy_user_generic_string 3.27% 1396 netperf [kernel.kallsyms] [k] tcp_sendmsg 1.66% 694 netperf [kernel.kallsyms] [k] get_page_from_freelist 0.79% 325 netperf [kernel.kallsyms] [k] tcp_ack 0.43% 188 netperf [kernel.kallsyms] [k] __alloc_skb
zc:
Samples: 1K of event 'cycles', Event count (approx.): 1439509124
30.36% 584 netperf.zerocop [kernel.kallsyms] [k] gup_pte_range 14.63% 284 netperf.zerocop [kernel.kallsyms] [k] __zerocopy_sg_from_iter 8.03% 159 netperf.zerocop [kernel.kallsyms] [k] skb_zerocopy_add_frags_iter 4.84% 96 netperf.zerocop [kernel.kallsyms] [k] __alloc_skb 3.10% 60 netperf.zerocop [kernel.kallsyms] [k] kmem_cache_alloc_node
* Safety
The number of pages that can be pinned on behalf of a user with MSG_ZEROCOPY is bound by the locked memory ulimit.
While the kernel holds process memory pinned, a process cannot safely reuse those pages for other purposes. Packets looped onto the receive stack and queued to a socket can be held indefinitely. Avoid unbounded notification latency by restricting user pages to egress paths only. skb_orphan_frags_rx() will create a private copy of pages even for refcounted packets when these are looped, as did skb_orphan_frags for the original tun zerocopy implementation.
Pages are not remapped read-only. Processes can modify packet contents while packets are in flight in the kernel path. Bytes on which kernel control flow depends (headers) are copied to avoid TOCTTOU attacks. Datapath integrity does not otherwise depend on payload, with three
exceptions: checksums, optional sk_filter/tc u32/.. and device + driver logic. The effect of wrong checksums is limited to the misbehaving process. TC filters that access contents may have to be excluded by adding an skb_orphan_frags_rx.
Processes can also safely avoid OOM conditions by bounding the number of bytes passed with MSG_ZEROCOPY and by removing shared pages after transmission from their own memory map.
Willem de Bruijn (13):
sock: allocate skbs from optmem
sock: skb_copy_ubufs support for compound pages
sock: add MSG_ZEROCOPY
sock: add SOCK_ZEROCOPY sockopt
sock: enable MSG_ZEROCOPY
sock: MSG_ZEROCOPY notification coalescing
sock: add ee_code SO_EE_CODE_ZEROCOPY_COPIED
sock: ulimit on MSG_ZEROCOPY pages
tcp: enable MSG_ZEROCOPY
udp: enable MSG_ZEROCOPY
raw: enable MSG_ZEROCOPY with IP_HDRINCL packet: enable MSG_ZEROCOPY test: add msg_zerocopy test
arch/alpha/include/uapi/asm/socket.h | 2 + arch/frv/include/uapi/asm/socket.h | 2 + arch/ia64/include/uapi/asm/socket.h | 2 + arch/m32r/include/uapi/asm/socket.h | 2 + arch/mips/include/uapi/asm/socket.h | 2 + arch/mn10300/include/uapi/asm/socket.h | 2 + arch/parisc/include/uapi/asm/socket.h | 2 + arch/s390/include/uapi/asm/socket.h | 2 + arch/sparc/include/uapi/asm/socket.h | 2 + arch/xtensa/include/uapi/asm/socket.h | 2 + drivers/net/tun.c | 2 +- drivers/vhost/net.c | 1 + include/linux/sched/user.h | 3 +- include/linux/skbuff.h | 106 ++++- include/linux/socket.h | 1 + include/net/sock.h | 4 + include/uapi/asm-generic/socket.h | 2 + include/uapi/linux/errqueue.h | 3 + net/core/datagram.c | 55 ++- net/core/dev.c | 4 +- net/core/skbuff.c | 390 ++++++++++++++-- net/core/sock.c | 43 ++ net/ipv4/ip_output.c | 37 +- net/ipv4/raw.c | 23 +- net/ipv4/tcp.c | 32 +- net/ipv6/ip6_output.c | 40 +- net/ipv6/raw.c | 20 +- net/packet/af_packet.c | 36 +- tools/testing/selftests/net/.gitignore | 1 + tools/testing/selftests/net/Makefile | 2 +- tools/testing/selftests/net/msg_zerocopy.c | 697 ++++++++++++++++++++++++++++ tools/testing/selftests/net/msg_zerocopy.sh | 113 +++++ 32 files changed, 1535 insertions(+), 100 deletions(-) create mode 100644 tools/testing/selftests/net/msg_zerocopy.c create mode 100755 tools/testing/selftests/net/msg_zerocopy.sh
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 1/13 sock: allocate skbs from optmem
From: Willem de Bruijn <[email protected]>
Add sock_omalloc and sock_ofree to be able to allocate control skbs, for instance for looping errors onto sk_error_queue.
The transmit budget (sk_wmem_alloc) is involved in transmit skb shaping, most notably in TCP Small Queues. Using this budget for control packets would impact transmission.
--- include/net/sock.h | 2 ++ net/core/sock.c | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+)
include/net/sock.h +2 -0
@@ -1524,6 +1524,8 @@ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, gfp_t priority);void __sock_wfree (struct sk_buff *skb);void sock_wfree (struct sk_buff *skb); +struct sk_buff *sock_omalloc (struct sock *sk,unsigned long size, +gfp_t priority);void skb_orphan_partial (struct sk_buff *skb);void sock_rfree (struct sk_buff *skb);void sock_efree (struct sk_buff *skb);
net/core/sock.c +27 -0
@@ -1890,6 +1890,33 @@ struct sk_buff *sock_wmalloc(struct sock *sk, unsigned long size, int force, }EXPORT_SYMBOL (sock_wmalloc); +static void sock_ofree (struct sk_buff *skb) +{ +struct sock *sk = skb->sk; + +atomic_sub (skb->truesize, &sk->sk_omem_alloc); +} + +struct sk_buff *sock_omalloc (struct sock *sk,unsigned long size, +gfp_t priority) +{ +struct sk_buff *skb; + +/* small safe race: SKB_TRUESIZE may differ from final skb->truesize */ +if (atomic_read (&sk->sk_omem_alloc) +SKB_TRUESIZE (size) > + sysctl_optmem_max) +return NULL ; + + skb =alloc_skb (size, priority); +if (!skb) +return NULL ; + +atomic_add (skb->truesize, &sk->sk_omem_alloc); + skb->sk = sk; + skb->destructor = sock_ofree; +return skb; +} +/* * Allocate a memory block from the socket's option memory buffer. */
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 2/13 sock: skb_copy_ubufs support for compound pages
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
Refine skb_copy_ubufs to support compound pages. With upcoming TCP and UDP zerocopy sendmsg, such fragments may appear.
The existing code replaces each page one for one. Splitting each compound page into an independent number of regular pages can result in exceeding limit MAX_SKB_FRAGS.
Instead, fill all destination pages but the last to PAGE_SIZE. Split the existing alloc + copy loop into separate stages. Compute the bytelength and allocate the minimum number of pages needed to hold this. Revise the copy loop to fill each destination page.
It is not safe to modify skb frags when the skbuff is shared. No existing codepath should hit this case.
Eventually, this fragile function can perhaps be replaced with calls to skb_linearize -- when converted to not always require GFP_ATOMIC.
--- include/linux/skbuff.h | 9 +++++++-- net/core/skbuff.c | 49 ++++++++++++++++++++++++++++++++++++++----------- 2 files changed, 45 insertions(+), 13 deletions(-)
include/linux/skbuff.h +7 -2
@@ -1783,13 +1783,18 @@ static inline unsigned int skb_headlen(const struct sk_buff *skb)return skb->len - skb->data_len; } -static inline unsigned int skb_pagelen (const struct sk_buff *skb) +static inline unsigned int __skb_pagelen (const struct sk_buff *skb) {unsigned int i, len =0 ;for (i =skb_shinfo (skb)->nr_frags -1 ; (int )i >=0 ; i--) len +=skb_frag_size (&skb_shinfo (skb)->frags[i]); -return len +skb_headlen (skb); +return len; +} + +static inline unsigned int skb_pagelen (const struct sk_buff *skb) +{ +return skb_headlen (skb) +__skb_pagelen (skb); }/**
net/core/skbuff.c +38 -11
78 lines not on this page · raw message
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
A message that is not in the archive (sent off-list or not yet received): 20170621203652.15306-1-willemdebruijn.kernel-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
PATCH v2 3/13 sock: add MSG_ZEROCOPY
From: Willem de Bruijn <[email protected]>
The kernel supports zerocopy sendmsg in virtio and tap. Expand the infrastructure to support other socket types. Introduce a completion notification channel over the socket error queue. Notifications are returned with ee_origin SO_EE_ORIGIN_ZEROCOPY. ee_errno is 0 to avoid blocking the send/recv path on receiving notifications.
Add reference counting, to support the skb split, merge, resize and clone operations possible with SOCK_STREAM and other socket types.
The patch does not yet modify any datapaths.
--- include/linux/skbuff.h | 61 ++++++++++++++++ include/linux/socket.h | 1 + include/net/sock.h | 2 + include/uapi/linux/errqueue.h | 1 + net/core/datagram.c | 55 +++++++++------ net/core/skbuff.c | 157 ++++++++++++++++++++++++++++++++++++++++++ net/core/sock.c | 2 + 7 files changed, 258 insertions(+), 21 deletions(-)
include/linux/skbuff.h +61 -0
@@ -393,6 +393,7 @@ enum { SKBTX_SCHED_TSTAMP = 1 << 6, }; +#define SKBTX_ZEROCOPY_FRAG (SKBTX_DEV_ZEROCOPY | SKBTX_SHARED_FRAG)#define SKBTX_ANY_SW_TSTAMP (SKBTX_SW_TSTAMP | \ SKBTX_SCHED_TSTAMP)#define SKBTX_ANY_TSTAMP (SKBTX_HW_TSTAMP | SKBTX_ANY_SW_TSTAMP)
@@ -409,8 +410,30 @@ struct ubuf_info {void (*callback)(struct ubuf_info *,bool zerocopy_success);void *ctx;unsigned long desc; +atomic_t refcnt; }; +#define skb_uarg (SKB ) ((struct ubuf_info *)(skb_shinfo(SKB)->destructor_arg)) + +struct ubuf_info *sock_zerocopy_alloc (struct sock *sk,size_t size); + +static inline void sock_zerocopy_get (struct ubuf_info *uarg) +{ +atomic_inc (&uarg->refcnt); +} + +void sock_zerocopy_put (struct ubuf_info *uarg); +void sock_zerocopy_put_abort (struct ubuf_info *uarg); + +void sock_zerocopy_callback (struct ubuf_info *uarg,bool success); + +int skb_zerocopy_iter (struct sock *sk,struct sk_buff *skb,struct msghdr *msg, +int len); +int skb_zerocopy_iter_alloc (struct sk_buff *skb,struct msghdr *msg,int len); +int skb_zerocopy_iter_stream (struct sock *sk,struct sk_buff *skb, +struct msghdr *msg,int len, +struct ubuf_info *uarg); +/* This data is invariant across clones and lives at * the end of the header data, ie. at skb->end. */
@@ -1201,6 +1224,44 @@ static inline struct skb_shared_hwtstamps *skb_hwtstamps(struct sk_buff *skb)return &skb_shinfo (skb)->hwtstamps; } +static inline struct ubuf_info *skb_zcopy (struct sk_buff *skb) +{ +bool is_zcopy = skb &&skb_shinfo (skb)->tx_flags &SKBTX_DEV_ZEROCOPY ; + +return is_zcopy ?skb_uarg (skb) :NULL ; +} + +static inline void skb_zcopy_set (struct sk_buff *skb,struct ubuf_info *uarg) +{ +if (skb && uarg && !skb_zcopy (skb)) { +sock_zerocopy_get (uarg); +skb_shinfo (skb)->destructor_arg = uarg; +skb_shinfo (skb)->tx_flags |=SKBTX_ZEROCOPY_FRAG ; + } +} + +/* Release a reference on a zerocopy structure */ +static inline void skb_zcopy_clear (struct sk_buff *skb,bool zerocopy) +{ +struct ubuf_info *uarg =skb_zcopy (skb); + +if (uarg) { +sock_zerocopy_put (uarg); +skb_shinfo (skb)->tx_flags &= ~SKBTX_ZEROCOPY_FRAG ; + } +} + +/* Abort a zerocopy operation and revert zckey on error in send syscall */ +static inline void skb_zcopy_abort (struct sk_buff *skb) +{ +struct ubuf_info *uarg =skb_zcopy (skb); + +if (uarg) { +sock_zerocopy_put_abort (uarg); +skb_shinfo (skb)->tx_flags &= ~SKBTX_ZEROCOPY_FRAG ; + } +} +/** * skb_queue_empty - check if a queue is empty * @list: queue head
include/linux/socket.h +1 -0
@@ -287,6 +287,7 @@ struct ucred {#define MSG_BATCH 0x40000/* sendmmsg(): more messages coming */ #define MSG_EOF MSG_FIN +#define MSG_ZEROCOPY 0x4000000/* Use user data in kernel path */ #define MSG_FASTOPEN 0x20000000/* Send data in TCP SYN */ #define MSG_CMSG_CLOEXEC 0x40000000/* Set close_on_exec for file descriptor received through
include/net/sock.h +2 -0
@@ -290,6 +290,7 @@ struct sock_common {* @sk_stamp: time stamp of last packet received * @sk_tsflags: SO_TIMESTAMPING socket options * @sk_tskey: counter to disambiguate concurrent tstamp requests +* @sk_zckey: counter to order MSG_ZEROCOPY notifications * @sk_socket: Identd and reporting IO signals * @sk_user_data: RPC layer private data * @sk_frag: cached page frag
@@ -458,6 +459,7 @@ struct sock {u16 sk_tsflags;u8 sk_shutdown;u32 sk_tskey; +atomic_t sk_zckey;struct socket *sk_socket;void *sk_user_data;#ifdef CONFIG_SECURITY
include/uapi/linux/errqueue.h +1 -0
@@ -18,6 +18,7 @@ struct sock_extended_err {#define SO_EE_ORIGIN_ICMP 2#define SO_EE_ORIGIN_ICMP6 3#define SO_EE_ORIGIN_TXSTATUS 4 +#define SO_EE_ORIGIN_ZEROCOPY 5#define SO_EE_ORIGIN_TIMESTAMPING SO_EE_ORIGIN_TXSTATUS#define SO_EE_OFFENDER (ee) ((struct sockaddr*)((ee)+1))
net/core/datagram.c +34 -21
85 lines not on this page · raw message
net/core/skbuff.c +157 -0
163 lines not on this page · raw message
net/core/sock.c +2 -0
@@ -1637,6 +1637,7 @@ struct sock *sk_clone_lock(const struct sock *sk, const gfp_t priority)atomic_set (&newsk->sk_drops,0 ); newsk->sk_send_head =NULL ; newsk->sk_userlocks = sk->sk_userlocks & ~SOCK_BINDPORT_LOCK ; +atomic_set (&newsk->sk_zckey,0 );sock_reset_flag (newsk,SOCK_DONE );
@@ -2667,6 +2668,7 @@ void sock_init_data(struct socket *sock, struct sock *sk) sk->sk_sndtimeo =MAX_SCHEDULE_TIMEOUT ; sk->sk_stamp =SK_DEFAULT_STAMP ; +atomic_set (&sk->sk_zckey,0 );#ifdef CONFIG_NET_RX_BUSY_POLL sk->sk_napi_id =0 ;
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
PATCH v2 7/13 sock: add ee_code SO_EE_CODE_ZEROCOPY_COPIED
In reply to a message not in the archiveFrom: Willem de Bruijn <[email protected]>
A send request with MSG_ZEROCOPY falls back to copying when a request cannot be completed in zerocopy mode.
Notify processes when the call reverted to copying through a new bit in the completion notification, so that they can optionally decline passing the flag on subsequent calls on the same path.
--- include/linux/skbuff.h | 2 ++ include/uapi/linux/errqueue.h | 2 ++ net/core/skbuff.c | 5 ++++- 3 files changed, 8 insertions(+), 1 deletion(-)
include/linux/skbuff.h +2 -0
@@ -416,6 +416,7 @@ struct ubuf_info {struct {u32 id;u16 len; +u16 zerocopy:1 ;u32 bytelen; }; };
@@ -1257,6 +1258,7 @@ static inline void skb_zcopy_clear(struct sk_buff *skb, bool zerocopy)struct ubuf_info *uarg =skb_zcopy (skb);if (uarg) { + uarg->zerocopy = uarg->zerocopy && zerocopy;sock_zerocopy_put (uarg);skb_shinfo (skb)->tx_flags &= ~SKBTX_ZEROCOPY_FRAG ; }
include/uapi/linux/errqueue.h +2 -0
@@ -23,6 +23,8 @@ struct sock_extended_err {#define SO_EE_OFFENDER (ee) ((struct sockaddr*)((ee)+1)) +#define SO_EE_CODE_ZEROCOPY_COPIED 1 +/** * struct scm_timestamping - timestamps exposed through cmsg *
net/core/skbuff.c +4 -1
@@ -943,6 +943,7 @@ struct ubuf_info *sock_zerocopy_alloc(struct sock *sk, size_t size) uarg->callback = sock_zerocopy_callback; uarg->id = ((u32 )atomic_inc_return (&sk->sk_zckey)) -1 ; uarg->len =1 ; + uarg->zerocopy =1 ; uarg->bytelen = size;atomic_set (&uarg->refcnt,0 );sock_hold (sk);
@@ -1039,6 +1040,8 @@ void sock_zerocopy_callback(struct ubuf_info *uarg, bool success) serr->ee.ee_origin =SO_EE_ORIGIN_ZEROCOPY ; serr->ee.ee_data = hi; serr->ee.ee_info = lo; +if (!success) + serr->ee.ee_code |=SO_EE_CODE_ZEROCOPY_COPIED ;spin_lock_irqsave (&q->lock, flags); tail =skb_peek_tail (q);
@@ -1061,7 +1064,7 @@ void sock_zerocopy_put(struct ubuf_info *uarg) {if (uarg &&atomic_dec_and_test (&uarg->refcnt)) {if (uarg->callback) - uarg->callback (uarg, true); + uarg->callback (uarg, uarg->zerocopy);else consume_skb (skb_from_uarg (uarg)); }
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
PATCH v2 8/13 sock: ulimit on MSG_ZEROCOPY pages
In reply to a message not in the archiveFrom: Willem de Bruijn <[email protected]>
Bound the number of pages that a user may pin.
Follow the lead of perf tools to maintain a per-user bound on memory locked pages commit 789f90fcf6b0 ("perf_counter: per user mlock gift")
--- include/linux/sched/user.h | 3 ++- include/linux/skbuff.h | 5 +++++ net/core/skbuff.c | 48 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 1 deletion(-)
include/linux/sched/user.h +2 -1
@@ -36,7 +36,8 @@ struct user_struct {struct hlist_node uidhash_node;kuid_t uid; -#if defined(CONFIG_PERF_EVENTS ) || defined(CONFIG_BPF_SYSCALL ) +#if defined(CONFIG_PERF_EVENTS ) || defined(CONFIG_BPF_SYSCALL ) || \ + defined(CONFIG_NET )atomic_long_t locked_vm;#endif };
include/linux/skbuff.h +5 -0
@@ -421,6 +421,11 @@ struct ubuf_info { }; };atomic_t refcnt; + +struct mmpin { +struct user_struct *user; +unsigned int num_pg; + } mmp; };#define skb_uarg (SKB ) ((struct ubuf_info *)(skb_shinfo(SKB)->destructor_arg))
net/core/skbuff.c +48 -0
72 lines not on this page · raw message
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 4/13 sock: add SOCK_ZEROCOPY sockopt
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
The send call ignores unknown flags. Legacy applications may already unwittingly pass MSG_ZEROCOPY. Continue to ignore this flag unless a socket opts in to zerocopy.
Introduce socket option SO_ZEROCOPY to enable MSG_ZEROCOPY processing. Processes can also query this socket option to detect kernel support for the feature. Older kernels will return ENOPROTOOPT.
--- arch/alpha/include/uapi/asm/socket.h | 2 ++ arch/frv/include/uapi/asm/socket.h | 2 ++ arch/ia64/include/uapi/asm/socket.h | 2 ++ arch/m32r/include/uapi/asm/socket.h | 2 ++ arch/mips/include/uapi/asm/socket.h | 2 ++ arch/mn10300/include/uapi/asm/socket.h | 2 ++ arch/parisc/include/uapi/asm/socket.h | 2 ++ arch/s390/include/uapi/asm/socket.h | 2 ++ arch/sparc/include/uapi/asm/socket.h | 2 ++ arch/xtensa/include/uapi/asm/socket.h | 2 ++ include/uapi/asm-generic/socket.h | 2 ++ net/core/skbuff.c | 3 +++ net/core/sock.c | 14 ++++++++++++++ 13 files changed, 39 insertions(+)
arch/alpha/include/uapi/asm/socket.h +2 -0
@@ -107,4 +107,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _UAPI_ASM_SOCKET_H */
arch/frv/include/uapi/asm/socket.h +2 -0
@@ -100,5 +100,7 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _ASM_SOCKET_H */
arch/ia64/include/uapi/asm/socket.h +2 -0
@@ -109,4 +109,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _ASM_IA64_SOCKET_H */
arch/m32r/include/uapi/asm/socket.h +2 -0
@@ -100,4 +100,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _ASM_M32R_SOCKET_H */
arch/mips/include/uapi/asm/socket.h +2 -0
@@ -118,4 +118,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _UAPI_ASM_SOCKET_H */
arch/mn10300/include/uapi/asm/socket.h +2 -0
@@ -100,4 +100,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _ASM_SOCKET_H */
arch/parisc/include/uapi/asm/socket.h +2 -0
@@ -99,4 +99,6 @@#define SCM_TIMESTAMPING_PKTINFO 0x4033 +#define SO_ZEROCOPY 0x4034 +#endif /* _UAPI_ASM_SOCKET_H */
arch/s390/include/uapi/asm/socket.h +2 -0
@@ -106,4 +106,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _ASM_SOCKET_H */
arch/sparc/include/uapi/asm/socket.h +2 -0
@@ -96,6 +96,8 @@#define SCM_TIMESTAMPING_PKTINFO 0x003c +#define SO_ZEROCOPY 0x003d +/* Security levels - as per NRL IPv6 - don't actually do anything */ #define SO_SECURITY_AUTHENTICATION 0x5001#define SO_SECURITY_ENCRYPTION_TRANSPORT 0x5002
arch/xtensa/include/uapi/asm/socket.h +2 -0
@@ -111,4 +111,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* _XTENSA_SOCKET_H */
include/uapi/asm-generic/socket.h +2 -0
@@ -102,4 +102,6 @@#define SCM_TIMESTAMPING_PKTINFO 58 +#define SO_ZEROCOPY 59 +#endif /* __ASM_GENERIC_SOCKET_H */
net/core/skbuff.c +3 -0
@@ -948,6 +948,9 @@ struct ubuf_info *sock_zerocopy_alloc(struct sock *sk, size_t size)WARN_ON_ONCE (!in_task ()); +if (!sock_flag (sk,SOCK_ZEROCOPY )) +return NULL ; + skb =sock_omalloc (sk,0 ,GFP_KERNEL );if (!skb)return NULL ;
net/core/sock.c +14 -0
@@ -1055,6 +1055,16 @@ int sock_setsockopt(struct socket *sock, int level, int optname,if (val ==1 )dst_negative_advice (sk);break ; + +case SO_ZEROCOPY : +if (sk->sk_state !=TCP_CLOSE ) + ret = -EBUSY ; +else if (val <0 || val >1 ) + ret = -EINVAL ; +else +sock_valbool_flag (sk,SOCK_ZEROCOPY , valbool); +break ; +default : ret = -ENOPROTOOPT ;break ;
@@ -1350,6 +1360,10 @@ int sock_getsockopt(struct socket *sock, int level, int optname, v.val64 =sock_gen_cookie (sk);break ; +case SO_ZEROCOPY : + v.val =sock_flag (sk,SOCK_ZEROCOPY ); +break ; +default :/* We implement the SO_SNDLOWAT etc to not be settable * (1003.1g 7).
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
A message that is not in the archive (sent off-list or not yet received): 20170621203652.15306-5-willemdebruijn.kernel-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org
Re: [PATCH net-next v2 04/13] sock: add SOCK_ZEROCOPY sockopt
Quoted 11 lines · Willem de Bruijn
From: Willem de Bruijn <[email protected]>
The send call ignores unknown flags. Legacy applications may already unwittingly pass
MSG_ZEROCOPY. Continue to ignore this flag unless a socket opts in to zerocopy.Introduce socket option
SO_ZEROCOPYto enableMSG_ZEROCOPYprocessing. Processes can also query this socket option to detect kernel support for the feature. Older kernels will return ENOPROTOOPT.Signed-off-by Willem de Bruijn <[email protected]>
This was not rebased on top of the SO_PEERGROUPS patch. I will send a v3.
Willem de Bruijn
maintainerPATCH v2 5/13 sock: enable MSG_ZEROCOPY
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
Prepare the datapath for refcounted ubuf_info. Clone ubuf_info with skb_zerocopy_clone() wherever needed due to skb split, merge, resize or clone.
Split skb_orphan_frags into two variants. The split, merge, .. paths support reference counted zerocopy buffers, so do not do a deep copy. Add skb_orphan_frags_rx for paths that may loop packets to receive sockets. That is not allowed, as it may cause unbounded latency. Deep copy all zerocopy copy buffers, ref-counted or not, in this path.
The exact locations to modify were chosen by exhaustively searching through all code that might modify skb_frag references and/or the the SKBTX_DEV_ZEROCOPY tx_flags bit.
The changes err on the safe side, in two ways.
(1) legacy ubuf_info paths virtio and tap are not modified. They keep a 1:1 ubuf_info to sk_buff relationship. Calls to skb_orphan_frags still call skb_copy_ubufs and thus copy frags in this case.
(2) not all copies deep in the stack are addressed yet. skb_shift, skb_split and skb_try_coalesce can be refined to avoid copying. These are not in the hot path and this patch is hairy enough as is, so that is left for future refinement.
--- drivers/net/tun.c | 2 +- drivers/vhost/net.c | 1 + include/linux/skbuff.h | 14 +++++++++++++- net/core/dev.c | 4 ++-- net/core/skbuff.c | 48 +++++++++++++++++++----------------------------- 5 files changed, 36 insertions(+), 33 deletions(-)
drivers/net/tun.c +1 -1
@@ -892,7 +892,7 @@ static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev) sk_filter(tfile->socket.sk, skb)) goto drop; -if (unlikely (skb_orphan_frags (skb,GFP_ATOMIC ))) +if (unlikely (skb_orphan_frags_rx (skb,GFP_ATOMIC ))) goto drop;skb_tx_timestamp (skb);
drivers/vhost/net.c +1 -0
@@ -533,6 +533,7 @@ static void handle_tx(struct vhost_net *net) ubuf->callback = vhost_zerocopy_callback; ubuf->ctx = nvq->ubufs; ubuf->desc = nvq->upend_idx; +atomic_set (&ubuf->refcnt,1 ); msg.msg_control = ubuf; msg.msg_controllen =sizeof (ubuf); ubufs = nvq->ubufs;
include/linux/skbuff.h +13 -1
@@ -2473,7 +2473,17 @@ static inline void skb_orphan(struct sk_buff *skb)*/ static inline int skb_orphan_frags (struct sk_buff *skb,gfp_t gfp_mask) { -if (likely (!(skb_shinfo (skb)->tx_flags &SKBTX_DEV_ZEROCOPY ))) +if (likely (!skb_zcopy (skb))) +return 0 ; +if (skb_uarg (skb)->callback == sock_zerocopy_callback) +return 0 ; +return skb_copy_ubufs (skb, gfp_mask); +} + +/* Frags must be orphaned, even if refcounted, if skb might loop to rx path */ +static inline int skb_orphan_frags_rx (struct sk_buff *skb,gfp_t gfp_mask) +{ +if (likely (!skb_zcopy (skb)))return 0 ;return skb_copy_ubufs (skb, gfp_mask); }
@@ -2905,6 +2915,8 @@ static inline int skb_add_data(struct sk_buff *skb,static inline bool skb_can_coalesce (struct sk_buff *skb,int i,const struct page *page,int off) { +if (skb_zcopy (skb)) +return false;if (i) {const struct skb_frag_struct *frag = &skb_shinfo (skb)->frags[i -1 ];
net/core/dev.c +2 -2
@@ -1860,7 +1860,7 @@ static inline int deliver_skb(struct sk_buff *skb, struct packet_type *pt_prev, struct net_device *orig_dev) { - if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC))) + if (unlikely(skb_orphan_frags_rx(skb, GFP_ATOMIC))) return -ENOMEM;atomic_inc (&skb->users);return pt_prev->func (skb, skb->dev, pt_prev, orig_dev);
@@ -4292,7 +4292,7 @@ static int __netif_receive_skb_core(struct sk_buff *skb, bool pfmemalloc) }if (pt_prev) { -if (unlikely (skb_orphan_frags (skb,GFP_ATOMIC ))) +if (unlikely (skb_orphan_frags_rx (skb,GFP_ATOMIC ))) goto drop;else ret = pt_prev->func (skb, skb->dev, pt_prev, orig_dev);
net/core/skbuff.c +19 -29
137 lines not on this page · raw message
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 6/13 sock: MSG_ZEROCOPY notification coalescing
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
In the simple case, each sendmsg() call generates data and eventually a zerocopy ready notification N, where N indicates the Nth successful invocation of sendmsg() with the MSG_ZEROCOPY flag on this socket.
TCP and corked sockets can cause send() calls to append new data to an existing sk_buff and, thus, ubuf_info. In that case the notification must hold a range. odify ubuf_info to store a inclusive range [N..N+m] and add skb_zerocopy_realloc() to optionally extend an existing range.
Also coalesce notifications in this common case: if a notification [1, 1] is about to be queued while [0, 0] is the queue tail, just modify the head of the queue to read [0, 1].
Coalescing is limited to a few TSO frames worth of data to bound notification latency.
--- include/linux/skbuff.h | 15 ++++++-- net/core/skbuff.c | 98 ++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 104 insertions(+), 9 deletions(-)
include/linux/skbuff.h +13 -2
@@ -408,14 +408,25 @@ enum {*/ struct ubuf_info {void (*callback)(struct ubuf_info *,bool zerocopy_success); -void *ctx; -unsigned long desc; +union { +struct { +unsigned long desc; +void *ctx; + }; +struct { +u32 id; +u16 len; +u32 bytelen; + }; + };atomic_t refcnt; };#define skb_uarg (SKB ) ((struct ubuf_info *)(skb_shinfo(SKB)->destructor_arg))struct ubuf_info *sock_zerocopy_alloc (struct sock *sk,size_t size); +struct ubuf_info *sock_zerocopy_realloc (struct sock *sk,size_t size, +struct ubuf_info *uarg);static inline void sock_zerocopy_get (struct ubuf_info *uarg) {
net/core/skbuff.c +91 -7
137 lines not on this page · raw message
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 9/13 tcp: enable MSG_ZEROCOPY
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
Enable support for MSG_ZEROCOPY to the TCP stack. TSO and GSO are both supported. Only data sent to remote destinations is sent without copying. Packets looped onto a local destination have their payload copied to avoid unbounded latency.
Tested:
A 10x TCP_STREAM between two hosts showed a reduction in netserver process cycles by up to 70%, depending on packet size. Systemwide, savings are of course much less pronounced, at up to 20% best case.
msg_zerocopy.sh 4 tcp:
without zerocopy
tx=121792 (7600 MB) txc=0 zc=n
rx=60458 (7600 MB)with zerocopy
tx=286257 (17863 MB) txc=286257 zc=y
rx=140022 (17863 MB) This test opens a pair of sockets over veth, one one calls send with 64KB and optionally MSG_ZEROCOPY and on the other reads the initial bytes. The receiver truncates, so this is strictly an upper bound on what is achievable. It is more representative of sending data out of a physical NIC (when payload is not touched, either).
--- net/ipv4/tcp.c | 32 +++++++++++++++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-)
net/ipv4/tcp.c +31 -1
@@ -1149,6 +1149,7 @@ int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)struct tcp_sock *tp =tcp_sk (sk);struct sk_buff *skb;struct sockcm_cookie sockc; +struct ubuf_info *uarg =NULL ;int flags, err, copied =0 ;int mss_now =0 , size_goal, copied_syn =0 ;bool process_backlog = false;
@@ -1158,6 +1159,26 @@ int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)lock_sock (sk); flags = msg->msg_flags; + +if (flags &MSG_ZEROCOPY && size) { +if (sk->sk_state !=TCP_ESTABLISHED ) { + err = -EINVAL ; + goto out_err; + } + + skb =tcp_send_head (sk) ?tcp_write_queue_tail (sk) :NULL ; + uarg =sock_zerocopy_realloc (sk, size,skb_zcopy (skb)); +if (!uarg) { + err = -ENOBUFS ; + goto out_err; + } + +/* skb may be freed in main loop, keep extra ref on uarg */ +sock_zerocopy_get (uarg); +if (!(sk_check_csum_caps (sk) && sk->sk_route_caps &NETIF_F_SG )) + uarg->zerocopy =0 ; + } +if (unlikely (flags &MSG_FASTOPEN ||inet_sk (sk)->defer_connect)) { err =tcp_sendmsg_fastopen (sk, msg, &copied_syn, size);if (err == -EINPROGRESS && copied_syn >0 )
@@ -1281,7 +1302,7 @@ int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size) err =skb_add_data_nocache (sk, skb, &msg->msg_iter, copy);if (err) goto do_fault; - }else { + }else if (!uarg || !uarg->zerocopy) {bool merge = true;int i =skb_shinfo (skb)->nr_frags;struct page_frag *pfrag =sk_page_frag (sk);
@@ -1319,6 +1340,13 @@ int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)page_ref_inc (pfrag->page); } pfrag->offset += copy; + }else { + err =skb_zerocopy_iter_stream (sk, skb, msg, copy, uarg); +if (err == -EMSGSIZE || err == -EEXIST ) + goto new_segment; +if (err <0 ) + goto do_error; + copy = err; }if (!copied)
@@ -1365,6 +1393,7 @@ int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)tcp_push (sk, flags, mss_now, tp->nonagle, size_goal); } out_nopush: +sock_zerocopy_put (uarg);release_sock (sk);return copied + copied_syn;
@@ -1382,6 +1411,7 @@ int tcp_sendmsg(struct sock *sk, struct msghdr *msg, size_t size)if (copied + copied_syn) goto out; out_err: +sock_zerocopy_put_abort (uarg); err =sk_stream_error (sk, flags, err);/* make sure we wake any epoll edge trigger waiter */ if (unlikely(skb_queue_len(&sk->sk_write_queue) == 0 &&
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 10/13 udp: enable MSG_ZEROCOPY
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
Add MSG_ZEROCOPY support to INET(6). This includes UDP, but also RAW sockets that do not take the raw_send_hdrinc() path.
Zerocopy is only effective when payload is not touched at all. Limit it to paths that support both checksum offload and scatter-gather.
When a caller passes MSG_ZEROCOPY to send and it returns a positive result, the caller must always receive a completion notification. Therefore, attach the structure even when zerocopy is not possible. Also in edge cases, such as corking with mixed zc/non-zc calls.
Tested:
msg_zerocopy.sh 4 udp:
without zerocopy
tx=146127 (9118 MB) txc=0 zc=n
rx=146127 (9118 MB)with zerocopy
tx=335789 (20954 MB) txc=335789 zc=y
rx=335789 (20954 MB) msg_zerocopy.sh 4 raw:
without zerocopy
tx=106461 (6643 MB) txc=0 zc=n
rx=106461 (6643 MB)with zerocopy
tx=296082 (18476 MB) txc=296082 zc=y
rx=296082 (18476 MB)--- net/core/skbuff.c | 4 ++++ net/ipv4/ip_output.c | 37 ++++++++++++++++++++++++++++++------- net/ipv6/ip6_output.c | 40 +++++++++++++++++++++++++++++++++------- 3 files changed, 67 insertions(+), 14 deletions(-)
net/core/skbuff.c +4 -0
@@ -1145,6 +1145,10 @@ extern int __zerocopy_sg_from_iter(struct sock *sk, struct sk_buff *skb,int skb_zerocopy_iter (struct sock *sk,struct sk_buff *skb,struct msghdr *msg,int len) { +/* raw has extra indirection in raw_frag_vec */ +if (sk->sk_type ==SOCK_RAW && sk->sk_family !=PF_PACKET ) + msg = *(struct msghdr **)msg; +return __zerocopy_sg_from_iter (sk, skb, &msg->msg_iter, len); }EXPORT_SYMBOL_GPL (skb_zerocopy_iter);
net/ipv4/ip_output.c +30 -7
@@ -919,7 +919,7 @@ static int __ip_append_data(struct sock *sk, {struct inet_sock *inet =inet_sk (sk);struct sk_buff *skb; - +struct ubuf_info *uarg =NULL ;struct ip_options *opt = cork->opt;int hh_len;int exthdrlen;
@@ -963,9 +963,21 @@ static int __ip_append_data(struct sock *sk, !exthdrlen) csummode =CHECKSUM_PARTIAL ; +if (flags &MSG_ZEROCOPY && length) { + uarg =sock_zerocopy_realloc (sk, length,skb_zcopy (skb)); +if (!uarg) +return -ENOBUFS ; + +if (!(rt->dst.dev->features &NETIF_F_SG ) || + (sk->sk_type ==SOCK_DGRAM && csummode ==CHECKSUM_NONE )) { + uarg->zerocopy =0 ; +skb_zcopy_set (skb, uarg); + } + } + cork->length += length;if ((((length + fragheaderlen) > mtu) || (skb &&skb_is_gso (skb))) && - (sk->sk_protocol ==IPPROTO_UDP ) && + (sk->sk_protocol ==IPPROTO_UDP ) && !uarg && (rt->dst.dev->features &NETIF_F_UFO ) && !dst_xfrm (&rt->dst) && (sk->sk_type ==SOCK_DGRAM ) && !sk->sk_no_check_tx) { err = ip_ufo_append_data(sk, queue, getfrag, from, length,
@@ -997,6 +1009,7 @@ static int __ip_append_data(struct sock *sk,unsigned int fraglen;unsigned int fraggap;unsigned int alloclen; +unsigned int zcopylen =0 ;struct sk_buff *skb_prev; alloc_new_skb: skb_prev = skb;
@@ -1017,8 +1030,12 @@ static int __ip_append_data(struct sock *sk,if ((flags &MSG_MORE ) && !(rt->dst.dev->features&NETIF_F_SG )) alloclen = mtu; -else +else if (!uarg || !uarg->zerocopy) alloclen = fraglen; +else { + alloclen =min_t (int, fraglen,MAX_HEADER ); + zcopylen = fraglen - alloclen; + } alloclen += exthdrlen;
@@ -1059,11 +1076,12 @@ static int __ip_append_data(struct sock *sk, cork->tx_flags =0 ;skb_shinfo (skb)->tskey = tskey; tskey =0 ; +skb_zcopy_set (skb, uarg);/* * Find where to start putting bytes. */ - data =skb_put (skb, fraglen + exthdrlen); + data =skb_put (skb, fraglen + exthdrlen - zcopylen);skb_set_network_header (skb, exthdrlen); skb->transport_header = (skb->network_header + fragheaderlen);
@@ -1079,7 +1097,7 @@ static int __ip_append_data(struct sock *sk,pskb_trim_unique (skb_prev, maxfraglen); } - copy = datalen - transhdrlen - fraggap; + copy = datalen - transhdrlen - fraggap - zcopylen;if (copy >0 &&getfrag (from, data + transhdrlen, offset, copy, fraggap, skb) <0 ) { err = -EFAULT ;kfree_skb (skb);
@@ -1087,7 +1105,7 @@ static int __ip_append_data(struct sock *sk, } offset += copy; - length -= datalen - fraggap; + length -= copy + transhdrlen; transhdrlen =0 ; exthdrlen =0 ; csummode =CHECKSUM_NONE ;
@@ -1115,7 +1133,7 @@ static int __ip_append_data(struct sock *sk, err = -EFAULT ; goto error; } - }else { + }else if (!uarg || !uarg->zerocopy) {int i =skb_shinfo (skb)->nr_frags; err = -ENOMEM ;
@@ -1145,6 +1163,10 @@ static int __ip_append_data(struct sock *sk, skb->data_len += copy; skb->truesize += copy;atomic_add (copy, &sk->sk_wmem_alloc); + }else { + err =skb_zerocopy_iter (sk, skb, from, copy); +if (err) + goto error; } offset += copy; length -= copy;
@@ -1155,6 +1177,7 @@ static int __ip_append_data(struct sock *sk, error_efault: err = -EFAULT ; error: +sock_zerocopy_put_abort (uarg); cork->length -= length;IP_INC_STATS (sock_net (sk),IPSTATS_MIB_OUTDISCARDS );return err;
net/ipv6/ip6_output.c +33 -7
@@ -1307,6 +1307,7 @@ static int __ip6_append_data(struct sock *sk,struct ipv6_txoptions *opt = v6_cork->opt;int csummode =CHECKSUM_NONE ;unsigned int maxnonfragsize, headersize; +struct ubuf_info *uarg =NULL ; skb =skb_peek_tail (queue);if (!skb) {
@@ -1368,6 +1369,18 @@ static int __ip6_append_data(struct sock *sk, tskey = sk->sk_tskey++; } +if (flags &MSG_ZEROCOPY && length) { + uarg =sock_zerocopy_realloc (sk, length,skb_zcopy (skb)); +if (!uarg) +return -ENOBUFS ; + +if (!(rt->dst.dev->features &NETIF_F_SG ) || + (sk->sk_type ==SOCK_DGRAM && csummode ==CHECKSUM_NONE )) { + uarg->zerocopy =0 ; +skb_zcopy_set (skb, uarg); + } + } +/* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU.
@@ -1387,7 +1400,7 @@ static int __ip6_append_data(struct sock *sk, cork->length += length;if ((((length + fragheaderlen) > mtu) || (skb &&skb_is_gso (skb))) && - (sk->sk_protocol ==IPPROTO_UDP ) && + (sk->sk_protocol ==IPPROTO_UDP ) && !uarg && (rt->dst.dev->features &NETIF_F_UFO ) && !dst_xfrm (&rt->dst) && (sk->sk_type ==SOCK_DGRAM ) && !udp_get_no_check6_tx (sk)) { err = ip6_ufo_append_data(sk, queue, getfrag, from, length,
@@ -1413,6 +1426,7 @@ static int __ip6_append_data(struct sock *sk,unsigned int fraglen;unsigned int fraggap;unsigned int alloclen; +unsigned int zcopylen =0 ; alloc_new_skb:/* There's no room in the current skb */ if (skb)
@@ -1435,11 +1449,17 @@ static int __ip6_append_data(struct sock *sk,if (datalen > (cork->length <= mtu && !(cork->flags &IPCORK_ALLFRAG ) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; + fraglen = datalen + fragheaderlen; +if ((flags &MSG_MORE ) && !(rt->dst.dev->features&NETIF_F_SG )) alloclen = mtu; -else - alloclen = datalen + fragheaderlen; +else if (!uarg || !uarg->zerocopy) + alloclen = fraglen; +else { + alloclen =min_t (int, fraglen,MAX_HEADER ); + zcopylen = fraglen - alloclen; + } alloclen += dst_exthdrlen;
@@ -1461,7 +1481,7 @@ static int __ip6_append_data(struct sock *sk,*/ alloclen +=sizeof (struct frag_hdr ); - copy = datalen - transhdrlen - fraggap; + copy = datalen - transhdrlen - fraggap - zcopylen;if (copy <0 ) { err = -EINVAL ; goto error;
@@ -1497,11 +1517,12 @@ static int __ip6_append_data(struct sock *sk, tx_flags =0 ;skb_shinfo (skb)->tskey = tskey; tskey =0 ; +skb_zcopy_set (skb, uarg);/* * Find where to start putting bytes */ - data =skb_put (skb, fraglen); + data =skb_put (skb, fraglen - zcopylen);skb_set_network_header (skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header +
@@ -1524,7 +1545,7 @@ static int __ip6_append_data(struct sock *sk, } offset += copy; - length -= datalen - fraggap; + length -= copy + transhdrlen; transhdrlen =0 ; exthdrlen =0 ; dst_exthdrlen =0 ;
@@ -1552,7 +1573,7 @@ static int __ip6_append_data(struct sock *sk, err = -EFAULT ; goto error; } - }else { + }else if (!uarg || !uarg->zerocopy) {int i =skb_shinfo (skb)->nr_frags; err = -ENOMEM ;
@@ -1582,6 +1603,10 @@ static int __ip6_append_data(struct sock *sk, skb->data_len += copy; skb->truesize += copy;atomic_add (copy, &sk->sk_wmem_alloc); + }else { + err =skb_zerocopy_iter (sk, skb, from, copy); +if (err) + goto error; } offset += copy; length -= copy;
@@ -1592,6 +1617,7 @@ static int __ip6_append_data(struct sock *sk, error_efault: err = -EFAULT ; error: +sock_zerocopy_put_abort (uarg); cork->length -= length;IP6_INC_STATS (sock_net (sk), rt->rt6i_idev,IPSTATS_MIB_OUTDISCARDS );return err;
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 11/13 raw: enable MSG_ZEROCOPY with IP_HDRINCL
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
Zerocopy support for udp also enables it for some raw sockets. Only raw sockets that have hdrinc set take a different path. Add zerocopy support for this variant.
Tested:
msg_zerocopy.sh 4 raw_hdrincl:
without zerocopy
tx=150438 (9390 MB) txc=0 zc=n
rx=150438 (9387 MB)with zerocopy
tx=292454 (18255 MB) txc=292454 zc=y
rx=292454 (18250 MB)--- net/ipv4/raw.c | 23 +++++++++++++++++++---- net/ipv6/raw.c | 20 +++++++++++++++++--- 2 files changed, 36 insertions(+), 7 deletions(-)
net/ipv4/raw.c +19 -4
@@ -351,7 +351,7 @@ static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4,unsigned int iphlen;int err;struct rtable *rt = *rtp; -int hlen, tlen; +int hlen, tlen, linear;if (length > rt->dst.dev->mtu) { ip_local_error(sk, EMSGSIZE, fl4->daddr, inet->inet_dport,
@@ -366,8 +366,14 @@ static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4, hlen =LL_RESERVED_SPACE (rt->dst.dev); tlen = rt->dst.dev->needed_tailroom; + linear = length; + +if (flags &MSG_ZEROCOPY && + rt->dst.dev->features &NETIF_F_SG ) + linear =min_t (int, linear,MAX_HEADER ); + skb =sock_alloc_send_skb (sk, - length + hlen + tlen +15 , + linear + hlen + tlen +15 , flags &MSG_DONTWAIT , &err);if (!skb) goto error;
@@ -380,7 +386,7 @@ static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4,skb_reset_network_header (skb); iph =ip_hdr (skb); -skb_put (skb, length); +skb_put (skb, linear); skb->ip_summed =CHECKSUM_NONE ;
@@ -391,7 +397,7 @@ static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4, skb->transport_header = skb->network_header; err = -EFAULT ; -if (memcpy_from_msg (iph, msg, length)) +if (memcpy_from_msg (iph, msg, linear)) goto error_free; iphlen = iph->ihl *4 ;
@@ -423,6 +429,13 @@ static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4, skb_transport_header(skb))->type); } +if (flags &MSG_ZEROCOPY ) { + err =skb_zerocopy_iter_alloc (skb, (void *)&msg, + length - linear); +if (err) + goto error_zcopy; + } + err =NF_HOOK (NFPROTO_IPV4 ,NF_INET_LOCAL_OUT , net, sk, skb,NULL , rt->dst.dev, dst_output);
@@ -433,6 +446,8 @@ static int raw_send_hdrinc(struct sock *sk, struct flowi4 *fl4, out:return 0 ; +error_zcopy: +skb_zcopy_abort (skb); error_free:kfree_skb (skb); error:
net/ipv6/raw.c +17 -3
@@ -627,6 +627,7 @@ static int rawv6_send_hdrinc(struct sock *sk, struct msghdr *msg, int length,struct rt6_info *rt = (struct rt6_info *)*dstp;int hlen =LL_RESERVED_SPACE (rt->dst.dev);int tlen = rt->dst.dev->needed_tailroom; +int linear = length;if (length > rt->dst.dev->mtu) {ipv6_local_error (sk,EMSGSIZE , fl6, rt->dst.dev->mtu);
@@ -637,8 +638,12 @@ static int rawv6_send_hdrinc(struct sock *sk, struct msghdr *msg, int length,if (flags&MSG_PROBE ) goto out; +if (flags &MSG_ZEROCOPY && + rt->dst.dev->features &NETIF_F_SG ) + linear =min_t (int, length,MAX_HEADER ); + skb =sock_alloc_send_skb (sk, - length + hlen + tlen +15 , + linear + hlen + tlen +15 , flags &MSG_DONTWAIT , &err);if (!skb) goto error;
@@ -650,7 +655,7 @@ static int rawv6_send_hdrinc(struct sock *sk, struct msghdr *msg, int length,skb_dst_set (skb, &rt->dst); *dstp =NULL ; -skb_put (skb, length); +skb_put (skb, linear);skb_reset_network_header (skb); iph =ipv6_hdr (skb);
@@ -660,10 +665,17 @@ static int rawv6_send_hdrinc(struct sock *sk, struct msghdr *msg, int length,skb_set_dst_pending_confirm (skb,1 ); skb->transport_header = skb->network_header; - err =memcpy_from_msg (iph, msg, length); + err =memcpy_from_msg (iph, msg, linear);if (err) goto error_fault; +if (flags &MSG_ZEROCOPY ) { + err =skb_zerocopy_iter_alloc (skb, (void *)&msg, + length - linear); +if (err) + goto error_zcopy; + } +/* if egress device is enslaved to an L3 master device pass the * skb to its handler for processing */
@@ -681,6 +693,8 @@ static int rawv6_send_hdrinc(struct sock *sk, struct msghdr *msg, int length, out:return 0 ; +error_zcopy: +skb_zcopy_abort (skb); error_fault: err = -EFAULT ;kfree_skb (skb);
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 12/13 packet: enable MSG_ZEROCOPY
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
Support MSG_ZEROCOPY on PF_PACKET transmission.
Tested:
msg_zerocopy.sh 4 packet:
without zerocopy
tx=121543 (7588 MB) txc=0 zc=n
rx=121543 (7584 MB)with zerocopy
tx=338252 (21119 MB) txc=338252 zc=y
rx=338252 (21108 MB) msg_zerocopy.sh 4 packet_dgram:
without zerocopy
tx=122699 (7659 MB) txc=0 zc=n
rx=122699 (7656 MB)with zerocopy
tx=340390 (21248 MB) txc=340390 zc=y
rx=340390 (21241 MB)--- net/packet/af_packet.c | 36 ++++++++++++++++++++++++++---------- 1 file changed, 26 insertions(+), 10 deletions(-)
net/packet/af_packet.c +26 -10
@@ -2795,30 +2795,39 @@ static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)static struct sk_buff *packet_alloc_skb (struct sock *sk,size_t prepad,size_t reserve,size_t len, -size_t linear,int noblock, +size_t linear,int flags,int *err) {struct sk_buff *skb; +size_t data_len; -/* Under a page? Don't bother with paged skb. */ -if (prepad + len <PAGE_SIZE || !linear) - linear = len; +if (flags &MSG_ZEROCOPY ) { +/* Minimize linear, but respect header lower bound */ + linear = reserve +min (len,max_t (size_t, linear,MAX_HEADER )); + data_len =0 ; + }else { +/* Under a page? Don't bother with paged skb. */ +if (prepad + len <PAGE_SIZE || !linear) + linear = len; + data_len = len - linear; + } - skb =sock_alloc_send_pskb (sk, prepad + linear, len - linear, noblock, - err,0 ); + skb =sock_alloc_send_pskb (sk, prepad + linear, data_len, + flags &MSG_DONTWAIT , err,0 );if (!skb)return NULL ;skb_reserve (skb, reserve);skb_put (skb, linear); - skb->data_len = len - linear; - skb->len += len - linear; + skb->data_len = data_len; + skb->len += data_len;return skb; }static int packet_snd (struct socket *sock,struct msghdr *msg,size_t len) { +struct iov_iter *from = &msg->msg_iter;struct sock *sk = sock->sk; DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);struct sk_buff *skb;
@@ -2894,7 +2903,7 @@ static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) linear =__virtio16_to_cpu (vio_le (), vnet_hdr.hdr_len); linear =max (linear,min_t (int, len, dev->hard_header_len)); skb =packet_alloc_skb (sk, hlen + tlen, hlen, len, linear, - msg->msg_flags &MSG_DONTWAIT , &err); + msg->msg_flags, &err);if (skb ==NULL ) goto out_unlock;
@@ -2908,10 +2917,16 @@ static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len) }/* Returns -EFAULT on error */ - err =skb_copy_datagram_from_iter (skb, offset, &msg->msg_iter, len); + err =skb_copy_datagram_from_iter (skb, offset, from, skb->len - offset);if (err) goto out_free; +if (msg->msg_flags &MSG_ZEROCOPY && len) { + err =skb_zerocopy_iter_alloc (skb, msg,iov_iter_count (from)); +if (err) + goto out_free; + } +if (sock->type ==SOCK_RAW && !dev_validate_header (dev, skb->data, len)) { err = -EINVAL ;
@@ -2954,6 +2969,7 @@ static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)return len; out_free: +skb_zcopy_abort (skb);kfree_skb (skb); out_unlock:if (dev)
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog
Willem de Bruijn
maintainerPATCH v2 13/13 test: add msg_zerocopy test
In reply to Willem de BruijnFrom: Willem de Bruijn <[email protected]>
Introduce regression test for msg_zerocopy feature. Send traffic from one process to another with and without zerocopy.
Evaluate tcp, udp, raw and packet sockets, including variants
- udp: corking and corking with mixed copy/zerocopy calls
- raw: with and without hdrincl
- packet: at both raw and dgram level
Test on both ipv4 and ipv6, optionally with ethtool changes to disable scatter-gather, tx checksum or tso offload. All of these can affect zerocopy behavior.
The regression test can be run on a single machine if over a veth pair. Then skb_orphan_frags_rx must be modified to be identical to skb_orphan_frags to allow forwarding zerocopy locally.
The msg_zerocopy.sh script will setup the veth pair in network namespaces and run all tests.
--- tools/testing/selftests/net/.gitignore | 1 + tools/testing/selftests/net/Makefile | 2 +- tools/testing/selftests/net/msg_zerocopy.c | 697 ++++++++++++++++++++++++++++ tools/testing/selftests/net/msg_zerocopy.sh | 113 +++++ 4 files changed, 812 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/net/msg_zerocopy.c create mode 100755 tools/testing/selftests/net/msg_zerocopy.sh
tools/testing/selftests/net/.gitignore +1 -0
@@ -1,3 +1,4 @@ +msg_zerocopy socket psock_fanout psock_tpacket
tools/testing/selftests/net/Makefile +1 -1
@@ -9,7 +9,7 @@ TEST_PROGS := run_netsocktests run_afpackettests test_bpf.sh netdevice.sh TEST_GEN_FILES = socket TEST_GEN_FILES += psock_fanout psock_tpacket TEST_GEN_FILES += reuseport_bpf reuseport_bpf_cpu reuseport_bpf_numa -TEST_GEN_FILES += reuseport_dualstack +TEST_GEN_FILES += reuseport_dualstack msg_zerocopy include ../lib.mk
tools/testing/selftests/net/msg_zerocopy.c new file +697 -0
697 lines not on this page · raw message
tools/testing/selftests/net/msg_zerocopy.sh new file +113 -0
113 lines not on this page · raw message
Signature · 1 line
2.13.1.611.g7e3b11ae1-goog