1 // SPDX-License-Identifier: GPL-2.0
5 * Generic datagram handling routines. These are generic for all
6 * protocols. Possibly a generic IP version on top of these would
7 * make sense. Not tonight however 8-).
8 * This is used because UDP, RAW, PACKET, DDP, IPX, AX.25 and
9 * NetROM layer all have identical poll code and mostly
10 * identical recvmsg() code. So we share it here. The poll was
11 * shared before but buried in udp.c so I moved it.
13 * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>. (datagram_poll() from old
17 * Alan Cox : NULL return from skb_peek_copy()
19 * Alan Cox : Rewrote skb_read_datagram to avoid the
20 * skb_peek_copy stuff.
21 * Alan Cox : Added support for SOCK_SEQPACKET.
22 * IPX can no longer use the SO_TYPE hack
23 * but AX.25 now works right, and SPX is
25 * Alan Cox : Fixed write poll of non IP protocol
27 * Florian La Roche: Changed for my new skbuff handling.
28 * Darryl Miles : Fixed non-blocking SOCK_SEQPACKET.
29 * Linus Torvalds : BSD semantic fixes.
30 * Alan Cox : Datagram iovec handling
31 * Darryl Miles : Fixed non-blocking SOCK_STREAM.
32 * Alan Cox : POSIXisms
33 * Pete Wyckoff : Unconnected accept() fix.
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/kernel.h>
40 #include <linux/uaccess.h>
42 #include <linux/interrupt.h>
43 #include <linux/errno.h>
44 #include <linux/sched.h>
45 #include <linux/inet.h>
46 #include <linux/netdevice.h>
47 #include <linux/rtnetlink.h>
48 #include <linux/poll.h>
49 #include <linux/highmem.h>
50 #include <linux/spinlock.h>
51 #include <linux/slab.h>
52 #include <linux/pagemap.h>
53 #include <linux/iov_iter.h>
54 #include <linux/indirect_call_wrapper.h>
55 #include <linux/crc32.h>
57 #include <net/protocol.h>
58 #include <linux/skbuff.h>
60 #include <net/checksum.h>
62 #include <net/tcp_states.h>
63 #include <trace/events/skb.h>
64 #include <net/busy_poll.h>
69 * Is a socket 'connection oriented' ?
71 static inline int connection_based(struct sock *sk)
73 return sk->sk_type == SOCK_SEQPACKET || sk->sk_type == SOCK_STREAM;
76 static int receiver_wake_function(wait_queue_entry_t *wait, unsigned int mode, int sync,
80 * Avoid a wakeup if event not interesting for us
82 if (key && !(key_to_poll(key) & (EPOLLIN | EPOLLERR)))
84 return autoremove_wake_function(wait, mode, sync, key);
87 * Wait for the last received packet to be different from skb
89 int __skb_wait_for_more_packets(struct sock *sk, struct sk_buff_head *queue,
90 int *err, long *timeo_p,
91 const struct sk_buff *skb)
94 DEFINE_WAIT_FUNC(wait, receiver_wake_function);
96 prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
99 error = sock_error(sk);
103 if (READ_ONCE(queue->prev) != skb)
106 /* Socket shut down? */
107 if (sk->sk_shutdown & RCV_SHUTDOWN)
110 /* Sequenced packets can come disconnected.
111 * If so we report the problem
114 if (connection_based(sk) &&
115 !(sk->sk_state == TCP_ESTABLISHED || sk->sk_state == TCP_LISTEN))
119 if (signal_pending(current))
123 *timeo_p = schedule_timeout(*timeo_p);
125 finish_wait(sk_sleep(sk), &wait);
128 error = sock_intr_errno(*timeo_p);
137 EXPORT_SYMBOL(__skb_wait_for_more_packets);
139 static struct sk_buff *skb_set_peeked(struct sk_buff *skb)
141 struct sk_buff *nskb;
146 /* We have to unshare an skb before modifying it. */
147 if (!skb_shared(skb))
150 nskb = skb_clone(skb, GFP_ATOMIC);
152 return ERR_PTR(-ENOMEM);
154 skb->prev->next = nskb;
155 skb->next->prev = nskb;
156 nskb->prev = skb->prev;
157 nskb->next = skb->next;
168 struct sk_buff *__skb_try_recv_from_queue(struct sk_buff_head *queue,
171 struct sk_buff **last)
173 bool peek_at_off = false;
177 if (unlikely(flags & MSG_PEEK && *off >= 0)) {
183 skb_queue_walk(queue, skb) {
184 if (flags & MSG_PEEK) {
185 if (peek_at_off && _off >= skb->len &&
186 (_off || skb->peeked)) {
191 skb = skb_set_peeked(skb);
197 refcount_inc(&skb->users);
199 __skb_unlink(skb, queue);
208 * __skb_try_recv_datagram - Receive a datagram skbuff
210 * @queue: socket queue from which to receive
211 * @flags: MSG\_ flags
212 * @off: an offset in bytes to peek skb from. Returns an offset
213 * within an skb where data actually starts
214 * @err: error code returned
215 * @last: set to last peeked message to inform the wait function
216 * what to look for when peeking
218 * Get a datagram skbuff, understands the peeking, nonblocking wakeups
219 * and possible races. This replaces identical code in packet, raw and
220 * udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
221 * the long standing peek and read race for datagram sockets. If you
222 * alter this routine remember it must be re-entrant.
224 * This function will lock the socket if a skb is returned, so
225 * the caller needs to unlock the socket in that case (usually by
226 * calling skb_free_datagram). Returns NULL with @err set to
227 * -EAGAIN if no data was available or to some other value if an
228 * error was detected.
230 * * It does not lock socket since today. This function is
231 * * free of race conditions. This measure should/can improve
232 * * significantly datagram socket latencies at high loads,
233 * * when data copying to user space takes lots of time.
234 * * (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet
238 * The order of the tests when we find no data waiting are specified
239 * quite explicitly by POSIX 1003.1g, don't change them without having
240 * the standard around please.
242 struct sk_buff *__skb_try_recv_datagram(struct sock *sk,
243 struct sk_buff_head *queue,
244 unsigned int flags, int *off, int *err,
245 struct sk_buff **last)
248 unsigned long cpu_flags;
250 * Caller is allowed not to check sk->sk_err before skb_recv_datagram()
252 int error = sock_error(sk);
258 /* Again only user level code calls this function, so nothing
259 * interrupt level will suddenly eat the receive_queue.
261 * Look at current nfs client by the way...
262 * However, this function was correct in any case. 8)
264 spin_lock_irqsave(&queue->lock, cpu_flags);
265 skb = __skb_try_recv_from_queue(queue, flags, off, &error,
267 spin_unlock_irqrestore(&queue->lock, cpu_flags);
273 if (!sk_can_busy_loop(sk))
276 sk_busy_loop(sk, flags & MSG_DONTWAIT);
277 } while (READ_ONCE(queue->prev) != *last);
285 EXPORT_SYMBOL(__skb_try_recv_datagram);
287 struct sk_buff *__skb_recv_datagram(struct sock *sk,
288 struct sk_buff_head *sk_queue,
289 unsigned int flags, int *off, int *err)
291 struct sk_buff *skb, *last;
294 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
297 skb = __skb_try_recv_datagram(sk, sk_queue, flags, off, err,
305 !__skb_wait_for_more_packets(sk, sk_queue, err,
310 EXPORT_SYMBOL(__skb_recv_datagram);
312 struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags,
317 return __skb_recv_datagram(sk, &sk->sk_receive_queue, flags,
320 EXPORT_SYMBOL(skb_recv_datagram);
322 void skb_free_datagram(struct sock *sk, struct sk_buff *skb)
326 EXPORT_SYMBOL(skb_free_datagram);
328 int __sk_queue_drop_skb(struct sock *sk, struct sk_buff_head *sk_queue,
329 struct sk_buff *skb, unsigned int flags,
330 void (*destructor)(struct sock *sk,
331 struct sk_buff *skb))
335 if (flags & MSG_PEEK) {
337 spin_lock_bh(&sk_queue->lock);
339 __skb_unlink(skb, sk_queue);
340 refcount_dec(&skb->users);
345 spin_unlock_bh(&sk_queue->lock);
348 atomic_inc(&sk->sk_drops);
351 EXPORT_SYMBOL(__sk_queue_drop_skb);
354 * skb_kill_datagram - Free a datagram skbuff forcibly
356 * @skb: datagram skbuff
357 * @flags: MSG\_ flags
359 * This function frees a datagram skbuff that was received by
360 * skb_recv_datagram. The flags argument must match the one
361 * used for skb_recv_datagram.
363 * If the MSG_PEEK flag is set, and the packet is still on the
364 * receive queue of the socket, it will be taken off the queue
365 * before it is freed.
367 * This function currently only disables BH when acquiring the
368 * sk_receive_queue lock. Therefore it must not be used in a
369 * context where that lock is acquired in an IRQ context.
371 * It returns 0 if the packet was removed by us.
374 int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags)
376 int err = __sk_queue_drop_skb(sk, &sk->sk_receive_queue, skb, flags,
382 EXPORT_SYMBOL(skb_kill_datagram);
384 INDIRECT_CALLABLE_DECLARE(static size_t simple_copy_to_iter(const void *addr,
386 void *data __always_unused,
387 struct iov_iter *i));
389 static int __skb_datagram_iter(const struct sk_buff *skb, int offset,
390 struct iov_iter *to, int len, bool fault_short,
391 size_t (*cb)(const void *, size_t, void *,
392 struct iov_iter *), void *data)
394 int start = skb_headlen(skb);
395 int i, copy = start - offset, start_off = offset, n;
396 struct sk_buff *frag_iter;
402 n = INDIRECT_CALL_1(cb, simple_copy_to_iter,
403 skb->data + offset, copy, data, to);
407 if ((len -= copy) == 0)
411 if (!skb_frags_readable(skb))
414 /* Copy paged appendix. Hmm... why does this look so complicated? */
415 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
417 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
419 WARN_ON(start > offset + len);
421 end = start + skb_frag_size(frag);
422 if ((copy = end - offset) > 0) {
423 u32 p_off, p_len, copied;
431 skb_frag_foreach_page(frag,
432 skb_frag_off(frag) + offset - start,
433 copy, p, p_off, p_len, copied) {
434 vaddr = kmap_local_page(p);
435 n += INDIRECT_CALL_1(cb, simple_copy_to_iter,
436 vaddr + p_off, p_len, data, to);
449 skb_walk_frags(skb, frag_iter) {
452 WARN_ON(start > offset + len);
454 end = start + frag_iter->len;
455 if ((copy = end - offset) > 0) {
458 if (__skb_datagram_iter(frag_iter, offset - start,
459 to, copy, fault_short, cb, data))
461 if ((len -= copy) == 0)
470 /* This is not really a user copy fault, but rather someone
471 * gave us a bogus length on the skb. We should probably
472 * print a warning here as it may indicate a kernel bug.
476 iov_iter_revert(to, offset - start_off);
480 if (fault_short || iov_iter_count(to))
486 #ifdef CONFIG_NET_CRC32C
487 static size_t crc32c_and_copy_to_iter(const void *addr, size_t bytes,
488 void *_crcp, struct iov_iter *i)
493 copied = copy_to_iter(addr, bytes, i);
494 *crcp = crc32c(*crcp, addr, copied);
499 * skb_copy_and_crc32c_datagram_iter - Copy datagram to an iovec iterator
500 * and update a CRC32C value.
501 * @skb: buffer to copy
502 * @offset: offset in the buffer to start copying from
503 * @to: iovec iterator to copy to
504 * @len: amount of data to copy from buffer to iovec
505 * @crcp: pointer to CRC32C value to update
507 * Return: 0 on success, -EFAULT if there was a fault during copy.
509 int skb_copy_and_crc32c_datagram_iter(const struct sk_buff *skb, int offset,
510 struct iov_iter *to, int len, u32 *crcp)
512 return __skb_datagram_iter(skb, offset, to, len, true,
513 crc32c_and_copy_to_iter, crcp);
515 EXPORT_SYMBOL(skb_copy_and_crc32c_datagram_iter);
516 #endif /* CONFIG_NET_CRC32C */
518 static size_t simple_copy_to_iter(const void *addr, size_t bytes,
519 void *data __always_unused, struct iov_iter *i)
521 return copy_to_iter(addr, bytes, i);
525 * skb_copy_datagram_iter - Copy a datagram to an iovec iterator.
526 * @skb: buffer to copy
527 * @offset: offset in the buffer to start copying from
528 * @to: iovec iterator to copy to
529 * @len: amount of data to copy from buffer to iovec
531 int skb_copy_datagram_iter(const struct sk_buff *skb, int offset,
532 struct iov_iter *to, int len)
534 trace_skb_copy_datagram_iovec(skb, len);
535 return __skb_datagram_iter(skb, offset, to, len, false,
536 simple_copy_to_iter, NULL);
538 EXPORT_SYMBOL(skb_copy_datagram_iter);
541 * skb_copy_datagram_from_iter - Copy a datagram from an iov_iter.
542 * @skb: buffer to copy
543 * @offset: offset in the buffer to start copying to
544 * @from: the copy source
545 * @len: amount of data to copy to buffer from iovec
547 * Returns 0 or -EFAULT.
549 int skb_copy_datagram_from_iter(struct sk_buff *skb, int offset,
550 struct iov_iter *from,
553 int start = skb_headlen(skb);
554 int i, copy = start - offset;
555 struct sk_buff *frag_iter;
561 if (copy_from_iter(skb->data + offset, copy, from) != copy)
563 if ((len -= copy) == 0)
568 /* Copy paged appendix. Hmm... why does this look so complicated? */
569 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
571 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
573 WARN_ON(start > offset + len);
575 end = start + skb_frag_size(frag);
576 if ((copy = end - offset) > 0) {
581 copied = copy_page_from_iter(skb_frag_page(frag),
582 skb_frag_off(frag) + offset - start,
594 skb_walk_frags(skb, frag_iter) {
597 WARN_ON(start > offset + len);
599 end = start + frag_iter->len;
600 if ((copy = end - offset) > 0) {
603 if (skb_copy_datagram_from_iter(frag_iter,
607 if ((len -= copy) == 0)
619 EXPORT_SYMBOL(skb_copy_datagram_from_iter);
621 int zerocopy_fill_skb_from_iter(struct sk_buff *skb,
622 struct iov_iter *from, size_t length)
624 int frag = skb_shinfo(skb)->nr_frags;
626 if (!skb_frags_readable(skb))
629 while (length && iov_iter_count(from)) {
630 struct page *head, *last_head = NULL;
631 struct page *pages[MAX_SKB_FRAGS];
632 int refs, order, n = 0;
636 if (frag == MAX_SKB_FRAGS)
639 copied = iov_iter_get_pages2(from, pages, length,
640 MAX_SKB_FRAGS - frag, &start);
646 skb->data_len += copied;
648 skb->truesize += PAGE_ALIGN(copied + start);
650 head = compound_head(pages[n]);
651 order = compound_order(head);
653 for (refs = 0; copied != 0; start = 0) {
654 int size = min_t(int, copied, PAGE_SIZE - start);
656 if (pages[n] - head > (1UL << order) - 1) {
657 head = compound_head(pages[n]);
658 order = compound_order(head);
661 start += (pages[n] - head) << PAGE_SHIFT;
665 skb_frag_t *last = &skb_shinfo(skb)->frags[frag - 1];
667 if (head == skb_frag_page(last) &&
668 start == skb_frag_off(last) + skb_frag_size(last)) {
669 skb_frag_size_add(last, size);
670 /* We combined this page, we need to release
671 * a reference. Since compound pages refcount
672 * is shared among many pages, batch the refcount
673 * adjustments to limit false sharing.
681 page_ref_sub(last_head, refs);
684 skb_fill_page_desc_noacc(skb, frag++, head, start, size);
687 page_ref_sub(last_head, refs);
693 zerocopy_fill_skb_from_devmem(struct sk_buff *skb, struct iov_iter *from,
695 struct net_devmem_dmabuf_binding *binding)
697 int i = skb_shinfo(skb)->nr_frags;
698 size_t virt_addr, size, off;
699 struct net_iov *niov;
701 /* Devmem filling works by taking an IOVEC from the user where the
702 * iov_addrs are interpreted as an offset in bytes into the dma-buf to
703 * send from. We do not support other iter types.
705 if (iov_iter_type(from) != ITER_IOVEC &&
706 iov_iter_type(from) != ITER_UBUF)
709 while (length && iov_iter_count(from)) {
710 if (i == MAX_SKB_FRAGS)
713 virt_addr = (size_t)iter_iov_addr(from);
714 niov = net_devmem_get_niov_at(binding, virt_addr, &off, &size);
718 size = min_t(size_t, size, length);
719 size = min_t(size_t, size, iter_iov_len(from));
721 get_netmem(net_iov_to_netmem(niov));
722 skb_add_rx_frag_netmem(skb, i, net_iov_to_netmem(niov), off,
724 iov_iter_advance(from, size);
732 int __zerocopy_sg_from_iter(struct msghdr *msg, struct sock *sk,
733 struct sk_buff *skb, struct iov_iter *from,
735 struct net_devmem_dmabuf_binding *binding)
737 unsigned long orig_size = skb->truesize;
738 unsigned long truesize;
741 if (msg && msg->msg_ubuf && msg->sg_from_iter)
742 ret = msg->sg_from_iter(skb, from, length);
744 ret = zerocopy_fill_skb_from_devmem(skb, from, length, binding);
746 ret = zerocopy_fill_skb_from_iter(skb, from, length);
748 truesize = skb->truesize - orig_size;
749 if (sk && sk->sk_type == SOCK_STREAM) {
750 sk_wmem_queued_add(sk, truesize);
751 if (!skb_zcopy_pure(skb))
752 sk_mem_charge(sk, truesize);
754 refcount_add(truesize, &skb->sk->sk_wmem_alloc);
758 EXPORT_SYMBOL(__zerocopy_sg_from_iter);
761 * zerocopy_sg_from_iter - Build a zerocopy datagram from an iov_iter
762 * @skb: buffer to copy
763 * @from: the source to copy from
765 * The function will first copy up to headlen, and then pin the userspace
766 * pages and build frags through them.
768 * Returns 0, -EFAULT or -EMSGSIZE.
770 int zerocopy_sg_from_iter(struct sk_buff *skb, struct iov_iter *from)
772 int copy = min_t(int, skb_headlen(skb), iov_iter_count(from));
774 /* copy up to skb headlen */
775 if (skb_copy_datagram_from_iter(skb, 0, from, copy))
778 return __zerocopy_sg_from_iter(NULL, NULL, skb, from, ~0U, NULL);
780 EXPORT_SYMBOL(zerocopy_sg_from_iter);
782 static __always_inline
783 size_t copy_to_user_iter_csum(void __user *iter_to, size_t progress,
784 size_t len, void *from, void *priv2)
786 __wsum next, *csum = priv2;
788 next = csum_and_copy_to_user(from + progress, iter_to, len);
789 *csum = csum_block_add(*csum, next, progress);
790 return next ? 0 : len;
793 static __always_inline
794 size_t memcpy_to_iter_csum(void *iter_to, size_t progress,
795 size_t len, void *from, void *priv2)
797 __wsum *csum = priv2;
798 __wsum next = csum_partial_copy_nocheck(from + progress, iter_to, len);
800 *csum = csum_block_add(*csum, next, progress);
809 static size_t csum_and_copy_to_iter(const void *addr, size_t bytes, void *_csstate,
812 struct csum_state *csstate = _csstate;
815 if (WARN_ON_ONCE(i->data_source))
817 if (unlikely(iov_iter_is_discard(i))) {
818 // can't use csum_memcpy() for that one - data is not copied
819 csstate->csum = csum_block_add(csstate->csum,
820 csum_partial(addr, bytes, 0),
822 csstate->off += bytes;
826 sum = csum_shift(csstate->csum, csstate->off);
828 bytes = iterate_and_advance2(i, bytes, (void *)addr, &sum,
829 copy_to_user_iter_csum,
830 memcpy_to_iter_csum);
831 csstate->csum = csum_shift(sum, csstate->off);
832 csstate->off += bytes;
837 * skb_copy_and_csum_datagram - Copy datagram to an iovec iterator
838 * and update a checksum.
839 * @skb: buffer to copy
840 * @offset: offset in the buffer to start copying from
841 * @to: iovec iterator to copy to
842 * @len: amount of data to copy from buffer to iovec
843 * @csump: checksum pointer
845 static int skb_copy_and_csum_datagram(const struct sk_buff *skb, int offset,
846 struct iov_iter *to, int len,
849 struct csum_state csdata = { .csum = *csump };
852 ret = __skb_datagram_iter(skb, offset, to, len, true,
853 csum_and_copy_to_iter, &csdata);
857 *csump = csdata.csum;
862 * skb_copy_and_csum_datagram_msg - Copy and checksum skb to user iovec.
864 * @hlen: hardware length
867 * Caller _must_ check that skb will fit to this iovec.
869 * Returns: 0 - success.
870 * -EINVAL - checksum failure.
871 * -EFAULT - fault during copy.
873 int skb_copy_and_csum_datagram_msg(struct sk_buff *skb,
874 int hlen, struct msghdr *msg)
877 int chunk = skb->len - hlen;
882 if (msg_data_left(msg) < chunk) {
883 if (__skb_checksum_complete(skb))
885 if (skb_copy_datagram_msg(skb, hlen, msg, chunk))
888 csum = csum_partial(skb->data, hlen, skb->csum);
889 if (skb_copy_and_csum_datagram(skb, hlen, &msg->msg_iter,
893 if (csum_fold(csum)) {
894 iov_iter_revert(&msg->msg_iter, chunk);
898 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
899 !skb->csum_complete_sw)
900 netdev_rx_csum_fault(NULL, skb);
906 EXPORT_SYMBOL(skb_copy_and_csum_datagram_msg);
909 * datagram_poll - generic datagram poll
914 * Datagram poll: Again totally generic. This also handles
915 * sequenced packet sockets providing the socket receive queue
916 * is only ever holding data ready to receive.
918 * Note: when you *don't* use this routine for this protocol,
919 * and you use a different write policy from sock_writeable()
920 * then please supply your own write_space callback.
922 __poll_t datagram_poll(struct file *file, struct socket *sock,
925 struct sock *sk = sock->sk;
929 sock_poll_wait(file, sock, wait);
932 /* exceptional events? */
933 if (READ_ONCE(sk->sk_err) ||
934 !skb_queue_empty_lockless(&sk->sk_error_queue))
936 (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
938 shutdown = READ_ONCE(sk->sk_shutdown);
939 if (shutdown & RCV_SHUTDOWN)
940 mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
941 if (shutdown == SHUTDOWN_MASK)
945 if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
946 mask |= EPOLLIN | EPOLLRDNORM;
948 /* Connection-based need to check for termination and startup */
949 if (connection_based(sk)) {
950 int state = READ_ONCE(sk->sk_state);
952 if (state == TCP_CLOSE)
954 /* connection hasn't started yet? */
955 if (state == TCP_SYN_SENT)
960 if (sock_writeable(sk))
961 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
963 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
967 EXPORT_SYMBOL(datagram_poll);