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,
76 * Avoid a wakeup if event not interesting for us
78 if (key && !(key_to_poll(key) & (EPOLLIN | EPOLLERR)))
80 return autoremove_wake_function(wait, mode, sync, key);
83 * Wait for the last received packet to be different from skb
85 int __skb_wait_for_more_packets(struct sock *sk, int *err, long *timeo_p,
86 const struct sk_buff *skb)
89 DEFINE_WAIT_FUNC(wait, receiver_wake_function);
91 prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
94 error = sock_error(sk);
98 if (sk->sk_receive_queue.prev != skb)
101 /* Socket shut down? */
102 if (sk->sk_shutdown & RCV_SHUTDOWN)
105 /* Sequenced packets can come disconnected.
106 * If so we report the problem
109 if (connection_based(sk) &&
110 !(sk->sk_state == TCP_ESTABLISHED || sk->sk_state == TCP_LISTEN))
114 if (signal_pending(current))
118 *timeo_p = schedule_timeout(*timeo_p);
120 finish_wait(sk_sleep(sk), &wait);
123 error = sock_intr_errno(*timeo_p);
132 EXPORT_SYMBOL(__skb_wait_for_more_packets);
134 static struct sk_buff *skb_set_peeked(struct sk_buff *skb)
136 struct sk_buff *nskb;
141 /* We have to unshare an skb before modifying it. */
142 if (!skb_shared(skb))
145 nskb = skb_clone(skb, GFP_ATOMIC);
147 return ERR_PTR(-ENOMEM);
149 skb->prev->next = nskb;
150 skb->next->prev = nskb;
151 nskb->prev = skb->prev;
152 nskb->next = skb->next;
163 struct sk_buff *__skb_try_recv_from_queue(struct sock *sk,
164 struct sk_buff_head *queue,
166 void (*destructor)(struct sock *sk,
167 struct sk_buff *skb),
168 int *peeked, int *off, int *err,
169 struct sk_buff **last)
171 bool peek_at_off = false;
175 if (unlikely(flags & MSG_PEEK && *off >= 0)) {
181 skb_queue_walk(queue, skb) {
182 if (flags & MSG_PEEK) {
183 if (peek_at_off && _off >= skb->len &&
184 (_off || skb->peeked)) {
189 skb = skb_set_peeked(skb);
196 refcount_inc(&skb->users);
198 __skb_unlink(skb, queue);
209 * __skb_try_recv_datagram - Receive a datagram skbuff
211 * @flags: MSG\_ flags
212 * @destructor: invoked under the receive lock on successful dequeue
213 * @peeked: returns non-zero if this packet has been seen before
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),
247 int *peeked, int *off, int *err,
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);
263 /* Again only user level code calls this function, so nothing
264 * interrupt level will suddenly eat the receive_queue.
266 * Look at current nfs client by the way...
267 * However, this function was correct in any case. 8)
269 spin_lock_irqsave(&queue->lock, cpu_flags);
270 skb = __skb_try_recv_from_queue(sk, queue, flags, destructor,
271 peeked, off, &error, last);
272 spin_unlock_irqrestore(&queue->lock, cpu_flags);
278 if (!sk_can_busy_loop(sk))
281 sk_busy_loop(sk, flags & MSG_DONTWAIT);
282 } while (!skb_queue_empty(&sk->sk_receive_queue));
290 EXPORT_SYMBOL(__skb_try_recv_datagram);
292 struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
293 void (*destructor)(struct sock *sk,
294 struct sk_buff *skb),
295 int *peeked, int *off, int *err)
297 struct sk_buff *skb, *last;
300 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
303 skb = __skb_try_recv_datagram(sk, flags, destructor, peeked,
311 !__skb_wait_for_more_packets(sk, err, &timeo, last));
315 EXPORT_SYMBOL(__skb_recv_datagram);
317 struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags,
318 int noblock, int *err)
322 return __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
323 NULL, &peeked, &off, err);
325 EXPORT_SYMBOL(skb_recv_datagram);
327 void skb_free_datagram(struct sock *sk, struct sk_buff *skb)
330 sk_mem_reclaim_partial(sk);
332 EXPORT_SYMBOL(skb_free_datagram);
334 void __skb_free_datagram_locked(struct sock *sk, struct sk_buff *skb, int len)
338 if (!skb_unref(skb)) {
339 sk_peek_offset_bwd(sk, len);
343 slow = lock_sock_fast(sk);
344 sk_peek_offset_bwd(sk, len);
346 sk_mem_reclaim_partial(sk);
347 unlock_sock_fast(sk, slow);
349 /* skb is now orphaned, can be freed outside of locked section */
352 EXPORT_SYMBOL(__skb_free_datagram_locked);
354 int __sk_queue_drop_skb(struct sock *sk, struct sk_buff_head *sk_queue,
355 struct sk_buff *skb, unsigned int flags,
356 void (*destructor)(struct sock *sk,
357 struct sk_buff *skb))
361 if (flags & MSG_PEEK) {
363 spin_lock_bh(&sk_queue->lock);
365 __skb_unlink(skb, sk_queue);
366 refcount_dec(&skb->users);
371 spin_unlock_bh(&sk_queue->lock);
374 atomic_inc(&sk->sk_drops);
377 EXPORT_SYMBOL(__sk_queue_drop_skb);
380 * skb_kill_datagram - Free a datagram skbuff forcibly
382 * @skb: datagram skbuff
383 * @flags: MSG\_ flags
385 * This function frees a datagram skbuff that was received by
386 * skb_recv_datagram. The flags argument must match the one
387 * used for skb_recv_datagram.
389 * If the MSG_PEEK flag is set, and the packet is still on the
390 * receive queue of the socket, it will be taken off the queue
391 * before it is freed.
393 * This function currently only disables BH when acquiring the
394 * sk_receive_queue lock. Therefore it must not be used in a
395 * context where that lock is acquired in an IRQ context.
397 * It returns 0 if the packet was removed by us.
400 int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags)
402 int err = __sk_queue_drop_skb(sk, &sk->sk_receive_queue, skb, flags,
406 sk_mem_reclaim_partial(sk);
409 EXPORT_SYMBOL(skb_kill_datagram);
412 * skb_copy_datagram_iter - Copy a datagram to an iovec iterator.
413 * @skb: buffer to copy
414 * @offset: offset in the buffer to start copying from
415 * @to: iovec iterator to copy to
416 * @len: amount of data to copy from buffer to iovec
418 int skb_copy_datagram_iter(const struct sk_buff *skb, int offset,
419 struct iov_iter *to, int len)
421 int start = skb_headlen(skb);
422 int i, copy = start - offset, start_off = offset, n;
423 struct sk_buff *frag_iter;
425 trace_skb_copy_datagram_iovec(skb, len);
431 n = copy_to_iter(skb->data + offset, copy, to);
435 if ((len -= copy) == 0)
439 /* Copy paged appendix. Hmm... why does this look so complicated? */
440 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
442 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
444 WARN_ON(start > offset + len);
446 end = start + skb_frag_size(frag);
447 if ((copy = end - offset) > 0) {
450 n = copy_page_to_iter(skb_frag_page(frag),
451 frag->page_offset + offset -
462 skb_walk_frags(skb, frag_iter) {
465 WARN_ON(start > offset + len);
467 end = start + frag_iter->len;
468 if ((copy = end - offset) > 0) {
471 if (skb_copy_datagram_iter(frag_iter, offset - start,
474 if ((len -= copy) == 0)
483 /* This is not really a user copy fault, but rather someone
484 * gave us a bogus length on the skb. We should probably
485 * print a warning here as it may indicate a kernel bug.
489 iov_iter_revert(to, offset - start_off);
493 if (iov_iter_count(to))
498 EXPORT_SYMBOL(skb_copy_datagram_iter);
501 * skb_copy_datagram_from_iter - Copy a datagram from an iov_iter.
502 * @skb: buffer to copy
503 * @offset: offset in the buffer to start copying to
504 * @from: the copy source
505 * @len: amount of data to copy to buffer from iovec
507 * Returns 0 or -EFAULT.
509 int skb_copy_datagram_from_iter(struct sk_buff *skb, int offset,
510 struct iov_iter *from,
513 int start = skb_headlen(skb);
514 int i, copy = start - offset;
515 struct sk_buff *frag_iter;
521 if (copy_from_iter(skb->data + offset, copy, from) != copy)
523 if ((len -= copy) == 0)
528 /* Copy paged appendix. Hmm... why does this look so complicated? */
529 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
531 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
533 WARN_ON(start > offset + len);
535 end = start + skb_frag_size(frag);
536 if ((copy = end - offset) > 0) {
541 copied = copy_page_from_iter(skb_frag_page(frag),
542 frag->page_offset + offset - start,
554 skb_walk_frags(skb, frag_iter) {
557 WARN_ON(start > offset + len);
559 end = start + frag_iter->len;
560 if ((copy = end - offset) > 0) {
563 if (skb_copy_datagram_from_iter(frag_iter,
567 if ((len -= copy) == 0)
579 EXPORT_SYMBOL(skb_copy_datagram_from_iter);
581 int __zerocopy_sg_from_iter(struct sock *sk, struct sk_buff *skb,
582 struct iov_iter *from, size_t length)
584 int frag = skb_shinfo(skb)->nr_frags;
586 while (length && iov_iter_count(from)) {
587 struct page *pages[MAX_SKB_FRAGS];
590 unsigned long truesize;
593 if (frag == MAX_SKB_FRAGS)
596 copied = iov_iter_get_pages(from, pages, length,
597 MAX_SKB_FRAGS - frag, &start);
601 iov_iter_advance(from, copied);
604 truesize = PAGE_ALIGN(copied + start);
605 skb->data_len += copied;
607 skb->truesize += truesize;
608 if (sk && sk->sk_type == SOCK_STREAM) {
609 sk->sk_wmem_queued += truesize;
610 sk_mem_charge(sk, truesize);
612 refcount_add(truesize, &skb->sk->sk_wmem_alloc);
615 int size = min_t(int, copied, PAGE_SIZE - start);
616 skb_fill_page_desc(skb, frag++, pages[n], start, size);
624 EXPORT_SYMBOL(__zerocopy_sg_from_iter);
627 * zerocopy_sg_from_iter - Build a zerocopy datagram from an iov_iter
628 * @skb: buffer to copy
629 * @from: the source to copy from
631 * The function will first copy up to headlen, and then pin the userspace
632 * pages and build frags through them.
634 * Returns 0, -EFAULT or -EMSGSIZE.
636 int zerocopy_sg_from_iter(struct sk_buff *skb, struct iov_iter *from)
638 int copy = min_t(int, skb_headlen(skb), iov_iter_count(from));
640 /* copy up to skb headlen */
641 if (skb_copy_datagram_from_iter(skb, 0, from, copy))
644 return __zerocopy_sg_from_iter(NULL, skb, from, ~0U);
646 EXPORT_SYMBOL(zerocopy_sg_from_iter);
648 static int skb_copy_and_csum_datagram(const struct sk_buff *skb, int offset,
649 struct iov_iter *to, int len,
652 int start = skb_headlen(skb);
653 int i, copy = start - offset, start_off = offset;
654 struct sk_buff *frag_iter;
662 n = csum_and_copy_to_iter(skb->data + offset, copy, csump, to);
666 if ((len -= copy) == 0)
671 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
673 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
675 WARN_ON(start > offset + len);
677 end = start + skb_frag_size(frag);
678 if ((copy = end - offset) > 0) {
680 struct page *page = skb_frag_page(frag);
681 u8 *vaddr = kmap(page);
685 n = csum_and_copy_to_iter(vaddr + frag->page_offset +
686 offset - start, copy,
692 *csump = csum_block_add(*csump, csum2, pos);
700 skb_walk_frags(skb, frag_iter) {
703 WARN_ON(start > offset + len);
705 end = start + frag_iter->len;
706 if ((copy = end - offset) > 0) {
710 if (skb_copy_and_csum_datagram(frag_iter,
715 *csump = csum_block_add(*csump, csum2, pos);
716 if ((len -= copy) == 0)
727 iov_iter_revert(to, offset - start_off);
731 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
735 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
737 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
738 !skb->csum_complete_sw)
739 netdev_rx_csum_fault(skb->dev);
741 if (!skb_shared(skb))
742 skb->csum_valid = !sum;
745 EXPORT_SYMBOL(__skb_checksum_complete_head);
747 __sum16 __skb_checksum_complete(struct sk_buff *skb)
752 csum = skb_checksum(skb, 0, skb->len, 0);
754 /* skb->csum holds pseudo checksum */
755 sum = csum_fold(csum_add(skb->csum, csum));
757 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
758 !skb->csum_complete_sw)
759 netdev_rx_csum_fault(skb->dev);
762 if (!skb_shared(skb)) {
763 /* Save full packet checksum */
765 skb->ip_summed = CHECKSUM_COMPLETE;
766 skb->csum_complete_sw = 1;
767 skb->csum_valid = !sum;
772 EXPORT_SYMBOL(__skb_checksum_complete);
775 * skb_copy_and_csum_datagram_msg - Copy and checksum skb to user iovec.
777 * @hlen: hardware length
780 * Caller _must_ check that skb will fit to this iovec.
782 * Returns: 0 - success.
783 * -EINVAL - checksum failure.
784 * -EFAULT - fault during copy.
786 int skb_copy_and_csum_datagram_msg(struct sk_buff *skb,
787 int hlen, struct msghdr *msg)
790 int chunk = skb->len - hlen;
795 if (msg_data_left(msg) < chunk) {
796 if (__skb_checksum_complete(skb))
798 if (skb_copy_datagram_msg(skb, hlen, msg, chunk))
801 csum = csum_partial(skb->data, hlen, skb->csum);
802 if (skb_copy_and_csum_datagram(skb, hlen, &msg->msg_iter,
806 if (csum_fold(csum)) {
807 iov_iter_revert(&msg->msg_iter, chunk);
811 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE))
812 netdev_rx_csum_fault(skb->dev);
818 EXPORT_SYMBOL(skb_copy_and_csum_datagram_msg);
821 * datagram_poll - generic datagram poll
826 * Datagram poll: Again totally generic. This also handles
827 * sequenced packet sockets providing the socket receive queue
828 * is only ever holding data ready to receive.
830 * Note: when you *don't* use this routine for this protocol,
831 * and you use a different write policy from sock_writeable()
832 * then please supply your own write_space callback.
834 __poll_t datagram_poll(struct file *file, struct socket *sock,
837 struct sock *sk = sock->sk;
840 sock_poll_wait(file, sk_sleep(sk), wait);
843 /* exceptional events? */
844 if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
846 (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
848 if (sk->sk_shutdown & RCV_SHUTDOWN)
849 mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
850 if (sk->sk_shutdown == SHUTDOWN_MASK)
854 if (!skb_queue_empty(&sk->sk_receive_queue))
855 mask |= EPOLLIN | EPOLLRDNORM;
857 /* Connection-based need to check for termination and startup */
858 if (connection_based(sk)) {
859 if (sk->sk_state == TCP_CLOSE)
861 /* connection hasn't started yet? */
862 if (sk->sk_state == TCP_SYN_SENT)
867 if (sock_writeable(sk))
868 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
870 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
874 EXPORT_SYMBOL(datagram_poll);