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>
67 * Is a socket 'connection oriented' ?
69 static inline int connection_based(struct sock *sk)
71 return sk->sk_type == SOCK_SEQPACKET || sk->sk_type == SOCK_STREAM;
74 static int receiver_wake_function(wait_queue_entry_t *wait, unsigned int mode, int sync,
78 * Avoid a wakeup if event not interesting for us
80 if (key && !(key_to_poll(key) & (EPOLLIN | EPOLLERR)))
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 (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),
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);
210 * __skb_try_recv_datagram - Receive a datagram skbuff
212 * @flags: MSG\_ flags
213 * @destructor: invoked under the receive lock on successful dequeue
214 * @off: an offset in bytes to peek skb from. Returns an offset
215 * within an skb where data actually starts
216 * @err: error code returned
217 * @last: set to last peeked message to inform the wait function
218 * what to look for when peeking
220 * Get a datagram skbuff, understands the peeking, nonblocking wakeups
221 * and possible races. This replaces identical code in packet, raw and
222 * udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
223 * the long standing peek and read race for datagram sockets. If you
224 * alter this routine remember it must be re-entrant.
226 * This function will lock the socket if a skb is returned, so
227 * the caller needs to unlock the socket in that case (usually by
228 * calling skb_free_datagram). Returns NULL with @err set to
229 * -EAGAIN if no data was available or to some other value if an
230 * error was detected.
232 * * It does not lock socket since today. This function is
233 * * free of race conditions. This measure should/can improve
234 * * significantly datagram socket latencies at high loads,
235 * * when data copying to user space takes lots of time.
236 * * (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet
240 * The order of the tests when we find no data waiting are specified
241 * quite explicitly by POSIX 1003.1g, don't change them without having
242 * the standard around please.
244 struct sk_buff *__skb_try_recv_datagram(struct sock *sk, unsigned int flags,
245 void (*destructor)(struct sock *sk,
246 struct sk_buff *skb),
248 struct sk_buff **last)
250 struct sk_buff_head *queue = &sk->sk_receive_queue;
252 unsigned long cpu_flags;
254 * Caller is allowed not to check sk->sk_err before skb_recv_datagram()
256 int error = sock_error(sk);
262 /* Again only user level code calls this function, so nothing
263 * interrupt level will suddenly eat the receive_queue.
265 * Look at current nfs client by the way...
266 * However, this function was correct in any case. 8)
268 spin_lock_irqsave(&queue->lock, cpu_flags);
269 skb = __skb_try_recv_from_queue(sk, queue, flags, destructor,
271 spin_unlock_irqrestore(&queue->lock, cpu_flags);
277 if (!sk_can_busy_loop(sk))
280 sk_busy_loop(sk, flags & MSG_DONTWAIT);
281 } while (sk->sk_receive_queue.prev != *last);
289 EXPORT_SYMBOL(__skb_try_recv_datagram);
291 struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
292 void (*destructor)(struct sock *sk,
293 struct sk_buff *skb),
296 struct sk_buff *skb, *last;
299 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
302 skb = __skb_try_recv_datagram(sk, flags, destructor, off, err,
310 !__skb_wait_for_more_packets(sk, err, &timeo, last));
314 EXPORT_SYMBOL(__skb_recv_datagram);
316 struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags,
317 int noblock, int *err)
321 return __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
324 EXPORT_SYMBOL(skb_recv_datagram);
326 void skb_free_datagram(struct sock *sk, struct sk_buff *skb)
329 sk_mem_reclaim_partial(sk);
331 EXPORT_SYMBOL(skb_free_datagram);
333 void __skb_free_datagram_locked(struct sock *sk, struct sk_buff *skb, int len)
337 if (!skb_unref(skb)) {
338 sk_peek_offset_bwd(sk, len);
342 slow = lock_sock_fast(sk);
343 sk_peek_offset_bwd(sk, len);
345 sk_mem_reclaim_partial(sk);
346 unlock_sock_fast(sk, slow);
348 /* skb is now orphaned, can be freed outside of locked section */
351 EXPORT_SYMBOL(__skb_free_datagram_locked);
353 int __sk_queue_drop_skb(struct sock *sk, struct sk_buff_head *sk_queue,
354 struct sk_buff *skb, unsigned int flags,
355 void (*destructor)(struct sock *sk,
356 struct sk_buff *skb))
360 if (flags & MSG_PEEK) {
362 spin_lock_bh(&sk_queue->lock);
364 __skb_unlink(skb, sk_queue);
365 refcount_dec(&skb->users);
370 spin_unlock_bh(&sk_queue->lock);
373 atomic_inc(&sk->sk_drops);
376 EXPORT_SYMBOL(__sk_queue_drop_skb);
379 * skb_kill_datagram - Free a datagram skbuff forcibly
381 * @skb: datagram skbuff
382 * @flags: MSG\_ flags
384 * This function frees a datagram skbuff that was received by
385 * skb_recv_datagram. The flags argument must match the one
386 * used for skb_recv_datagram.
388 * If the MSG_PEEK flag is set, and the packet is still on the
389 * receive queue of the socket, it will be taken off the queue
390 * before it is freed.
392 * This function currently only disables BH when acquiring the
393 * sk_receive_queue lock. Therefore it must not be used in a
394 * context where that lock is acquired in an IRQ context.
396 * It returns 0 if the packet was removed by us.
399 int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags)
401 int err = __sk_queue_drop_skb(sk, &sk->sk_receive_queue, skb, flags,
405 sk_mem_reclaim_partial(sk);
408 EXPORT_SYMBOL(skb_kill_datagram);
410 static int __skb_datagram_iter(const struct sk_buff *skb, int offset,
411 struct iov_iter *to, int len, bool fault_short,
412 size_t (*cb)(const void *, size_t, void *,
413 struct iov_iter *), void *data)
415 int start = skb_headlen(skb);
416 int i, copy = start - offset, start_off = offset, n;
417 struct sk_buff *frag_iter;
423 n = cb(skb->data + offset, copy, data, to);
427 if ((len -= copy) == 0)
431 /* Copy paged appendix. Hmm... why does this look so complicated? */
432 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
434 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
436 WARN_ON(start > offset + len);
438 end = start + skb_frag_size(frag);
439 if ((copy = end - offset) > 0) {
440 struct page *page = skb_frag_page(frag);
441 u8 *vaddr = kmap(page);
445 n = cb(vaddr + skb_frag_off(frag) + offset - start,
457 skb_walk_frags(skb, frag_iter) {
460 WARN_ON(start > offset + len);
462 end = start + frag_iter->len;
463 if ((copy = end - offset) > 0) {
466 if (__skb_datagram_iter(frag_iter, offset - start,
467 to, copy, fault_short, cb, data))
469 if ((len -= copy) == 0)
478 /* This is not really a user copy fault, but rather someone
479 * gave us a bogus length on the skb. We should probably
480 * print a warning here as it may indicate a kernel bug.
484 iov_iter_revert(to, offset - start_off);
488 if (fault_short || iov_iter_count(to))
495 * skb_copy_and_hash_datagram_iter - Copy datagram to an iovec iterator
497 * @skb: buffer to copy
498 * @offset: offset in the buffer to start copying from
499 * @to: iovec iterator to copy to
500 * @len: amount of data to copy from buffer to iovec
501 * @hash: hash request to update
503 int skb_copy_and_hash_datagram_iter(const struct sk_buff *skb, int offset,
504 struct iov_iter *to, int len,
505 struct ahash_request *hash)
507 return __skb_datagram_iter(skb, offset, to, len, true,
508 hash_and_copy_to_iter, hash);
510 EXPORT_SYMBOL(skb_copy_and_hash_datagram_iter);
512 static size_t simple_copy_to_iter(const void *addr, size_t bytes,
513 void *data __always_unused, struct iov_iter *i)
515 return copy_to_iter(addr, bytes, i);
519 * skb_copy_datagram_iter - Copy a datagram to an iovec iterator.
520 * @skb: buffer to copy
521 * @offset: offset in the buffer to start copying from
522 * @to: iovec iterator to copy to
523 * @len: amount of data to copy from buffer to iovec
525 int skb_copy_datagram_iter(const struct sk_buff *skb, int offset,
526 struct iov_iter *to, int len)
528 trace_skb_copy_datagram_iovec(skb, len);
529 return __skb_datagram_iter(skb, offset, to, len, false,
530 simple_copy_to_iter, NULL);
532 EXPORT_SYMBOL(skb_copy_datagram_iter);
535 * skb_copy_datagram_from_iter - Copy a datagram from an iov_iter.
536 * @skb: buffer to copy
537 * @offset: offset in the buffer to start copying to
538 * @from: the copy source
539 * @len: amount of data to copy to buffer from iovec
541 * Returns 0 or -EFAULT.
543 int skb_copy_datagram_from_iter(struct sk_buff *skb, int offset,
544 struct iov_iter *from,
547 int start = skb_headlen(skb);
548 int i, copy = start - offset;
549 struct sk_buff *frag_iter;
555 if (copy_from_iter(skb->data + offset, copy, from) != copy)
557 if ((len -= copy) == 0)
562 /* Copy paged appendix. Hmm... why does this look so complicated? */
563 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
565 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
567 WARN_ON(start > offset + len);
569 end = start + skb_frag_size(frag);
570 if ((copy = end - offset) > 0) {
575 copied = copy_page_from_iter(skb_frag_page(frag),
576 skb_frag_off(frag) + offset - start,
588 skb_walk_frags(skb, frag_iter) {
591 WARN_ON(start > offset + len);
593 end = start + frag_iter->len;
594 if ((copy = end - offset) > 0) {
597 if (skb_copy_datagram_from_iter(frag_iter,
601 if ((len -= copy) == 0)
613 EXPORT_SYMBOL(skb_copy_datagram_from_iter);
615 int __zerocopy_sg_from_iter(struct sock *sk, struct sk_buff *skb,
616 struct iov_iter *from, size_t length)
618 int frag = skb_shinfo(skb)->nr_frags;
620 while (length && iov_iter_count(from)) {
621 struct page *pages[MAX_SKB_FRAGS];
624 unsigned long truesize;
627 if (frag == MAX_SKB_FRAGS)
630 copied = iov_iter_get_pages(from, pages, length,
631 MAX_SKB_FRAGS - frag, &start);
635 iov_iter_advance(from, copied);
638 truesize = PAGE_ALIGN(copied + start);
639 skb->data_len += copied;
641 skb->truesize += truesize;
642 if (sk && sk->sk_type == SOCK_STREAM) {
643 sk->sk_wmem_queued += truesize;
644 sk_mem_charge(sk, truesize);
646 refcount_add(truesize, &skb->sk->sk_wmem_alloc);
649 int size = min_t(int, copied, PAGE_SIZE - start);
650 skb_fill_page_desc(skb, frag++, pages[n], start, size);
658 EXPORT_SYMBOL(__zerocopy_sg_from_iter);
661 * zerocopy_sg_from_iter - Build a zerocopy datagram from an iov_iter
662 * @skb: buffer to copy
663 * @from: the source to copy from
665 * The function will first copy up to headlen, and then pin the userspace
666 * pages and build frags through them.
668 * Returns 0, -EFAULT or -EMSGSIZE.
670 int zerocopy_sg_from_iter(struct sk_buff *skb, struct iov_iter *from)
672 int copy = min_t(int, skb_headlen(skb), iov_iter_count(from));
674 /* copy up to skb headlen */
675 if (skb_copy_datagram_from_iter(skb, 0, from, copy))
678 return __zerocopy_sg_from_iter(NULL, skb, from, ~0U);
680 EXPORT_SYMBOL(zerocopy_sg_from_iter);
683 * skb_copy_and_csum_datagram_iter - Copy datagram to an iovec iterator
684 * and update a checksum.
685 * @skb: buffer to copy
686 * @offset: offset in the buffer to start copying from
687 * @to: iovec iterator to copy to
688 * @len: amount of data to copy from buffer to iovec
689 * @csump: checksum pointer
691 static int skb_copy_and_csum_datagram(const struct sk_buff *skb, int offset,
692 struct iov_iter *to, int len,
695 return __skb_datagram_iter(skb, offset, to, len, true,
696 csum_and_copy_to_iter, csump);
700 * skb_copy_and_csum_datagram_msg - Copy and checksum skb to user iovec.
702 * @hlen: hardware length
705 * Caller _must_ check that skb will fit to this iovec.
707 * Returns: 0 - success.
708 * -EINVAL - checksum failure.
709 * -EFAULT - fault during copy.
711 int skb_copy_and_csum_datagram_msg(struct sk_buff *skb,
712 int hlen, struct msghdr *msg)
715 int chunk = skb->len - hlen;
720 if (msg_data_left(msg) < chunk) {
721 if (__skb_checksum_complete(skb))
723 if (skb_copy_datagram_msg(skb, hlen, msg, chunk))
726 csum = csum_partial(skb->data, hlen, skb->csum);
727 if (skb_copy_and_csum_datagram(skb, hlen, &msg->msg_iter,
731 if (csum_fold(csum)) {
732 iov_iter_revert(&msg->msg_iter, chunk);
736 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
737 !skb->csum_complete_sw)
738 netdev_rx_csum_fault(NULL, skb);
744 EXPORT_SYMBOL(skb_copy_and_csum_datagram_msg);
747 * datagram_poll - generic datagram poll
752 * Datagram poll: Again totally generic. This also handles
753 * sequenced packet sockets providing the socket receive queue
754 * is only ever holding data ready to receive.
756 * Note: when you *don't* use this routine for this protocol,
757 * and you use a different write policy from sock_writeable()
758 * then please supply your own write_space callback.
760 __poll_t datagram_poll(struct file *file, struct socket *sock,
763 struct sock *sk = sock->sk;
766 sock_poll_wait(file, sock, wait);
769 /* exceptional events? */
770 if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
772 (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
774 if (sk->sk_shutdown & RCV_SHUTDOWN)
775 mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
776 if (sk->sk_shutdown == SHUTDOWN_MASK)
780 if (!skb_queue_empty(&sk->sk_receive_queue))
781 mask |= EPOLLIN | EPOLLRDNORM;
783 /* Connection-based need to check for termination and startup */
784 if (connection_based(sk)) {
785 if (sk->sk_state == TCP_CLOSE)
787 /* connection hasn't started yet? */
788 if (sk->sk_state == TCP_SYN_SENT)
793 if (sock_writeable(sk))
794 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
796 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
800 EXPORT_SYMBOL(datagram_poll);