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/uio.h>
55 #include <net/protocol.h>
56 #include <linux/skbuff.h>
58 #include <net/checksum.h>
60 #include <net/tcp_states.h>
61 #include <trace/events/skb.h>
62 #include <net/busy_poll.h>
65 * Is a socket 'connection oriented' ?
67 static inline int connection_based(struct sock *sk)
69 return sk->sk_type == SOCK_SEQPACKET || sk->sk_type == SOCK_STREAM;
72 static int receiver_wake_function(wait_queue_entry_t *wait, unsigned int mode, int sync,
75 unsigned long bits = (unsigned long)key;
78 * Avoid a wakeup if event not interesting for us
80 if (bits && !(bits & (POLLIN | POLLERR)))
82 return autoremove_wake_function(wait, mode, sync, key);
85 * Wait for the last received packet to be different from skb
87 int __skb_wait_for_more_packets(struct sock *sk, int *err, long *timeo_p,
88 const struct sk_buff *skb)
91 DEFINE_WAIT_FUNC(wait, receiver_wake_function);
93 prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
96 error = sock_error(sk);
100 if (READ_ONCE(sk->sk_receive_queue.prev) != skb)
103 /* Socket shut down? */
104 if (sk->sk_shutdown & RCV_SHUTDOWN)
107 /* Sequenced packets can come disconnected.
108 * If so we report the problem
111 if (connection_based(sk) &&
112 !(sk->sk_state == TCP_ESTABLISHED || sk->sk_state == TCP_LISTEN))
116 if (signal_pending(current))
120 *timeo_p = schedule_timeout(*timeo_p);
122 finish_wait(sk_sleep(sk), &wait);
125 error = sock_intr_errno(*timeo_p);
134 EXPORT_SYMBOL(__skb_wait_for_more_packets);
136 static struct sk_buff *skb_set_peeked(struct sk_buff *skb)
138 struct sk_buff *nskb;
143 /* We have to unshare an skb before modifying it. */
144 if (!skb_shared(skb))
147 nskb = skb_clone(skb, GFP_ATOMIC);
149 return ERR_PTR(-ENOMEM);
151 skb->prev->next = nskb;
152 skb->next->prev = nskb;
153 nskb->prev = skb->prev;
154 nskb->next = skb->next;
165 struct sk_buff *__skb_try_recv_from_queue(struct sock *sk,
166 struct sk_buff_head *queue,
168 void (*destructor)(struct sock *sk,
169 struct sk_buff *skb),
170 int *peeked, int *off, int *err,
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);
192 if (unlikely(IS_ERR(skb))) {
198 refcount_inc(&skb->users);
200 __skb_unlink(skb, queue);
211 * __skb_try_recv_datagram - Receive a datagram skbuff
213 * @flags: MSG\_ flags
214 * @destructor: invoked under the receive lock on successful dequeue
215 * @peeked: returns non-zero if this packet has been seen before
216 * @off: an offset in bytes to peek skb from. Returns an offset
217 * within an skb where data actually starts
218 * @err: error code returned
219 * @last: set to last peeked message to inform the wait function
220 * what to look for when peeking
222 * Get a datagram skbuff, understands the peeking, nonblocking wakeups
223 * and possible races. This replaces identical code in packet, raw and
224 * udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
225 * the long standing peek and read race for datagram sockets. If you
226 * alter this routine remember it must be re-entrant.
228 * This function will lock the socket if a skb is returned, so
229 * the caller needs to unlock the socket in that case (usually by
230 * calling skb_free_datagram). Returns NULL with @err set to
231 * -EAGAIN if no data was available or to some other value if an
232 * error was detected.
234 * * It does not lock socket since today. This function is
235 * * free of race conditions. This measure should/can improve
236 * * significantly datagram socket latencies at high loads,
237 * * when data copying to user space takes lots of time.
238 * * (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet
242 * The order of the tests when we find no data waiting are specified
243 * quite explicitly by POSIX 1003.1g, don't change them without having
244 * the standard around please.
246 struct sk_buff *__skb_try_recv_datagram(struct sock *sk, unsigned int flags,
247 void (*destructor)(struct sock *sk,
248 struct sk_buff *skb),
249 int *peeked, int *off, int *err,
250 struct sk_buff **last)
252 struct sk_buff_head *queue = &sk->sk_receive_queue;
254 unsigned long cpu_flags;
256 * Caller is allowed not to check sk->sk_err before skb_recv_datagram()
258 int error = sock_error(sk);
265 /* Again only user level code calls this function, so nothing
266 * interrupt level will suddenly eat the receive_queue.
268 * Look at current nfs client by the way...
269 * However, this function was correct in any case. 8)
271 spin_lock_irqsave(&queue->lock, cpu_flags);
272 skb = __skb_try_recv_from_queue(sk, queue, flags, destructor,
273 peeked, off, &error, last);
274 spin_unlock_irqrestore(&queue->lock, cpu_flags);
280 if (!sk_can_busy_loop(sk))
283 sk_busy_loop(sk, flags & MSG_DONTWAIT);
284 } while (READ_ONCE(sk->sk_receive_queue.prev) != *last);
292 EXPORT_SYMBOL(__skb_try_recv_datagram);
294 struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
295 void (*destructor)(struct sock *sk,
296 struct sk_buff *skb),
297 int *peeked, int *off, int *err)
299 struct sk_buff *skb, *last;
302 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
305 skb = __skb_try_recv_datagram(sk, flags, destructor, peeked,
313 !__skb_wait_for_more_packets(sk, err, &timeo, last));
317 EXPORT_SYMBOL(__skb_recv_datagram);
319 struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags,
320 int noblock, int *err)
324 return __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
325 NULL, &peeked, &off, err);
327 EXPORT_SYMBOL(skb_recv_datagram);
329 void skb_free_datagram(struct sock *sk, struct sk_buff *skb)
332 sk_mem_reclaim_partial(sk);
334 EXPORT_SYMBOL(skb_free_datagram);
336 void __skb_free_datagram_locked(struct sock *sk, struct sk_buff *skb, int len)
340 if (!skb_unref(skb)) {
341 sk_peek_offset_bwd(sk, len);
345 slow = lock_sock_fast(sk);
346 sk_peek_offset_bwd(sk, len);
348 sk_mem_reclaim_partial(sk);
349 unlock_sock_fast(sk, slow);
351 /* skb is now orphaned, can be freed outside of locked section */
354 EXPORT_SYMBOL(__skb_free_datagram_locked);
356 int __sk_queue_drop_skb(struct sock *sk, struct sk_buff_head *sk_queue,
357 struct sk_buff *skb, unsigned int flags,
358 void (*destructor)(struct sock *sk,
359 struct sk_buff *skb))
363 if (flags & MSG_PEEK) {
365 spin_lock_bh(&sk_queue->lock);
367 __skb_unlink(skb, sk_queue);
368 refcount_dec(&skb->users);
373 spin_unlock_bh(&sk_queue->lock);
376 atomic_inc(&sk->sk_drops);
379 EXPORT_SYMBOL(__sk_queue_drop_skb);
382 * skb_kill_datagram - Free a datagram skbuff forcibly
384 * @skb: datagram skbuff
385 * @flags: MSG\_ flags
387 * This function frees a datagram skbuff that was received by
388 * skb_recv_datagram. The flags argument must match the one
389 * used for skb_recv_datagram.
391 * If the MSG_PEEK flag is set, and the packet is still on the
392 * receive queue of the socket, it will be taken off the queue
393 * before it is freed.
395 * This function currently only disables BH when acquiring the
396 * sk_receive_queue lock. Therefore it must not be used in a
397 * context where that lock is acquired in an IRQ context.
399 * It returns 0 if the packet was removed by us.
402 int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags)
404 int err = __sk_queue_drop_skb(sk, &sk->sk_receive_queue, skb, flags,
408 sk_mem_reclaim_partial(sk);
411 EXPORT_SYMBOL(skb_kill_datagram);
414 * skb_copy_datagram_iter - Copy a datagram to an iovec iterator.
415 * @skb: buffer to copy
416 * @offset: offset in the buffer to start copying from
417 * @to: iovec iterator to copy to
418 * @len: amount of data to copy from buffer to iovec
420 int skb_copy_datagram_iter(const struct sk_buff *skb, int offset,
421 struct iov_iter *to, int len)
423 int start = skb_headlen(skb);
424 int i, copy = start - offset, start_off = offset, n;
425 struct sk_buff *frag_iter;
427 trace_skb_copy_datagram_iovec(skb, len);
433 n = copy_to_iter(skb->data + offset, copy, to);
437 if ((len -= copy) == 0)
441 /* Copy paged appendix. Hmm... why does this look so complicated? */
442 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
444 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
446 WARN_ON(start > offset + len);
448 end = start + skb_frag_size(frag);
449 if ((copy = end - offset) > 0) {
452 n = copy_page_to_iter(skb_frag_page(frag),
453 frag->page_offset + offset -
464 skb_walk_frags(skb, frag_iter) {
467 WARN_ON(start > offset + len);
469 end = start + frag_iter->len;
470 if ((copy = end - offset) > 0) {
473 if (skb_copy_datagram_iter(frag_iter, offset - start,
476 if ((len -= copy) == 0)
485 /* This is not really a user copy fault, but rather someone
486 * gave us a bogus length on the skb. We should probably
487 * print a warning here as it may indicate a kernel bug.
491 iov_iter_revert(to, offset - start_off);
495 if (iov_iter_count(to))
500 EXPORT_SYMBOL(skb_copy_datagram_iter);
503 * skb_copy_datagram_from_iter - Copy a datagram from an iov_iter.
504 * @skb: buffer to copy
505 * @offset: offset in the buffer to start copying to
506 * @from: the copy source
507 * @len: amount of data to copy to buffer from iovec
509 * Returns 0 or -EFAULT.
511 int skb_copy_datagram_from_iter(struct sk_buff *skb, int offset,
512 struct iov_iter *from,
515 int start = skb_headlen(skb);
516 int i, copy = start - offset;
517 struct sk_buff *frag_iter;
523 if (copy_from_iter(skb->data + offset, copy, from) != copy)
525 if ((len -= copy) == 0)
530 /* Copy paged appendix. Hmm... why does this look so complicated? */
531 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
533 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
535 WARN_ON(start > offset + len);
537 end = start + skb_frag_size(frag);
538 if ((copy = end - offset) > 0) {
543 copied = copy_page_from_iter(skb_frag_page(frag),
544 frag->page_offset + offset - start,
556 skb_walk_frags(skb, frag_iter) {
559 WARN_ON(start > offset + len);
561 end = start + frag_iter->len;
562 if ((copy = end - offset) > 0) {
565 if (skb_copy_datagram_from_iter(frag_iter,
569 if ((len -= copy) == 0)
581 EXPORT_SYMBOL(skb_copy_datagram_from_iter);
583 int __zerocopy_sg_from_iter(struct sock *sk, struct sk_buff *skb,
584 struct iov_iter *from, size_t length)
586 int frag = skb_shinfo(skb)->nr_frags;
588 while (length && iov_iter_count(from)) {
589 struct page *pages[MAX_SKB_FRAGS];
592 unsigned long truesize;
595 if (frag == MAX_SKB_FRAGS)
598 copied = iov_iter_get_pages(from, pages, length,
599 MAX_SKB_FRAGS - frag, &start);
603 iov_iter_advance(from, copied);
606 truesize = PAGE_ALIGN(copied + start);
607 skb->data_len += copied;
609 skb->truesize += truesize;
610 if (sk && sk->sk_type == SOCK_STREAM) {
611 sk->sk_wmem_queued += truesize;
612 sk_mem_charge(sk, truesize);
614 refcount_add(truesize, &skb->sk->sk_wmem_alloc);
617 int size = min_t(int, copied, PAGE_SIZE - start);
618 skb_fill_page_desc(skb, frag++, pages[n], start, size);
626 EXPORT_SYMBOL(__zerocopy_sg_from_iter);
629 * zerocopy_sg_from_iter - Build a zerocopy datagram from an iov_iter
630 * @skb: buffer to copy
631 * @from: the source to copy from
633 * The function will first copy up to headlen, and then pin the userspace
634 * pages and build frags through them.
636 * Returns 0, -EFAULT or -EMSGSIZE.
638 int zerocopy_sg_from_iter(struct sk_buff *skb, struct iov_iter *from)
640 int copy = min_t(int, skb_headlen(skb), iov_iter_count(from));
642 /* copy up to skb headlen */
643 if (skb_copy_datagram_from_iter(skb, 0, from, copy))
646 return __zerocopy_sg_from_iter(NULL, skb, from, ~0U);
648 EXPORT_SYMBOL(zerocopy_sg_from_iter);
650 static int skb_copy_and_csum_datagram(const struct sk_buff *skb, int offset,
651 struct iov_iter *to, int len,
654 int start = skb_headlen(skb);
655 int i, copy = start - offset, start_off = offset;
656 struct sk_buff *frag_iter;
664 n = csum_and_copy_to_iter(skb->data + offset, copy, csump, to);
668 if ((len -= copy) == 0)
673 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
675 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
677 WARN_ON(start > offset + len);
679 end = start + skb_frag_size(frag);
680 if ((copy = end - offset) > 0) {
682 struct page *page = skb_frag_page(frag);
683 u8 *vaddr = kmap(page);
687 n = csum_and_copy_to_iter(vaddr + frag->page_offset +
688 offset - start, copy,
694 *csump = csum_block_add(*csump, csum2, pos);
702 skb_walk_frags(skb, frag_iter) {
705 WARN_ON(start > offset + len);
707 end = start + frag_iter->len;
708 if ((copy = end - offset) > 0) {
712 if (skb_copy_and_csum_datagram(frag_iter,
717 *csump = csum_block_add(*csump, csum2, pos);
718 if ((len -= copy) == 0)
729 iov_iter_revert(to, offset - start_off);
733 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
737 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
739 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
740 !skb->csum_complete_sw)
741 netdev_rx_csum_fault(skb->dev);
743 if (!skb_shared(skb))
744 skb->csum_valid = !sum;
747 EXPORT_SYMBOL(__skb_checksum_complete_head);
749 __sum16 __skb_checksum_complete(struct sk_buff *skb)
754 csum = skb_checksum(skb, 0, skb->len, 0);
756 /* skb->csum holds pseudo checksum */
757 sum = csum_fold(csum_add(skb->csum, csum));
759 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
760 !skb->csum_complete_sw)
761 netdev_rx_csum_fault(skb->dev);
764 if (!skb_shared(skb)) {
765 /* Save full packet checksum */
767 skb->ip_summed = CHECKSUM_COMPLETE;
768 skb->csum_complete_sw = 1;
769 skb->csum_valid = !sum;
774 EXPORT_SYMBOL(__skb_checksum_complete);
777 * skb_copy_and_csum_datagram_msg - Copy and checksum skb to user iovec.
779 * @hlen: hardware length
782 * Caller _must_ check that skb will fit to this iovec.
784 * Returns: 0 - success.
785 * -EINVAL - checksum failure.
786 * -EFAULT - fault during copy.
788 int skb_copy_and_csum_datagram_msg(struct sk_buff *skb,
789 int hlen, struct msghdr *msg)
792 int chunk = skb->len - hlen;
797 if (msg_data_left(msg) < chunk) {
798 if (__skb_checksum_complete(skb))
800 if (skb_copy_datagram_msg(skb, hlen, msg, chunk))
803 csum = csum_partial(skb->data, hlen, skb->csum);
804 if (skb_copy_and_csum_datagram(skb, hlen, &msg->msg_iter,
808 if (csum_fold(csum)) {
809 iov_iter_revert(&msg->msg_iter, chunk);
813 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
814 !skb->csum_complete_sw)
815 netdev_rx_csum_fault(NULL);
821 EXPORT_SYMBOL(skb_copy_and_csum_datagram_msg);
824 * datagram_poll - generic datagram poll
829 * Datagram poll: Again totally generic. This also handles
830 * sequenced packet sockets providing the socket receive queue
831 * is only ever holding data ready to receive.
833 * Note: when you *don't* use this routine for this protocol,
834 * and you use a different write policy from sock_writeable()
835 * then please supply your own write_space callback.
837 unsigned int datagram_poll(struct file *file, struct socket *sock,
840 struct sock *sk = sock->sk;
843 sock_poll_wait(file, sk_sleep(sk), wait);
846 /* exceptional events? */
847 if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
849 (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
851 if (sk->sk_shutdown & RCV_SHUTDOWN)
852 mask |= POLLRDHUP | POLLIN | POLLRDNORM;
853 if (sk->sk_shutdown == SHUTDOWN_MASK)
857 if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
858 mask |= POLLIN | POLLRDNORM;
860 /* Connection-based need to check for termination and startup */
861 if (connection_based(sk)) {
862 if (sk->sk_state == TCP_CLOSE)
864 /* connection hasn't started yet? */
865 if (sk->sk_state == TCP_SYN_SENT)
870 if (sock_writeable(sk))
871 mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
873 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
877 EXPORT_SYMBOL(datagram_poll);