4 * Generic datagram handling routines. These are generic for all
5 * protocols. Possibly a generic IP version on top of these would
6 * make sense. Not tonight however 8-).
7 * This is used because UDP, RAW, PACKET, DDP, IPX, AX.25 and
8 * NetROM layer all have identical poll code and mostly
9 * identical recvmsg() code. So we share it here. The poll was
10 * shared before but buried in udp.c so I moved it.
12 * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>. (datagram_poll() from old
16 * Alan Cox : NULL return from skb_peek_copy()
18 * Alan Cox : Rewrote skb_read_datagram to avoid the
19 * skb_peek_copy stuff.
20 * Alan Cox : Added support for SOCK_SEQPACKET.
21 * IPX can no longer use the SO_TYPE hack
22 * but AX.25 now works right, and SPX is
24 * Alan Cox : Fixed write poll of non IP protocol
26 * Florian La Roche: Changed for my new skbuff handling.
27 * Darryl Miles : Fixed non-blocking SOCK_SEQPACKET.
28 * Linus Torvalds : BSD semantic fixes.
29 * Alan Cox : Datagram iovec handling
30 * Darryl Miles : Fixed non-blocking SOCK_STREAM.
31 * Alan Cox : POSIXisms
32 * Pete Wyckoff : Unconnected accept() fix.
36 #include <linux/module.h>
37 #include <linux/types.h>
38 #include <linux/kernel.h>
39 #include <linux/uaccess.h>
41 #include <linux/interrupt.h>
42 #include <linux/errno.h>
43 #include <linux/sched.h>
44 #include <linux/inet.h>
45 #include <linux/netdevice.h>
46 #include <linux/rtnetlink.h>
47 #include <linux/poll.h>
48 #include <linux/highmem.h>
49 #include <linux/spinlock.h>
50 #include <linux/slab.h>
51 #include <linux/pagemap.h>
52 #include <linux/uio.h>
54 #include <net/protocol.h>
55 #include <linux/skbuff.h>
57 #include <net/checksum.h>
59 #include <net/tcp_states.h>
60 #include <trace/events/skb.h>
61 #include <net/busy_poll.h>
64 * Is a socket 'connection oriented' ?
66 static inline int connection_based(struct sock *sk)
68 return sk->sk_type == SOCK_SEQPACKET || sk->sk_type == SOCK_STREAM;
71 static int receiver_wake_function(wait_queue_entry_t *wait, unsigned int mode, int sync,
74 unsigned long bits = (unsigned long)key;
77 * Avoid a wakeup if event not interesting for us
79 if (bits && !(bits & (POLLIN | POLLERR)))
81 return autoremove_wake_function(wait, mode, sync, key);
84 * Wait for the last received packet to be different from skb
86 int __skb_wait_for_more_packets(struct sock *sk, int *err, long *timeo_p,
87 const struct sk_buff *skb)
90 DEFINE_WAIT_FUNC(wait, receiver_wake_function);
92 prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
95 error = sock_error(sk);
99 if (sk->sk_receive_queue.prev != skb)
102 /* Socket shut down? */
103 if (sk->sk_shutdown & RCV_SHUTDOWN)
106 /* Sequenced packets can come disconnected.
107 * If so we report the problem
110 if (connection_based(sk) &&
111 !(sk->sk_state == TCP_ESTABLISHED || sk->sk_state == TCP_LISTEN))
115 if (signal_pending(current))
119 *timeo_p = schedule_timeout(*timeo_p);
121 finish_wait(sk_sleep(sk), &wait);
124 error = sock_intr_errno(*timeo_p);
133 EXPORT_SYMBOL(__skb_wait_for_more_packets);
135 static struct sk_buff *skb_set_peeked(struct sk_buff *skb)
137 struct sk_buff *nskb;
142 /* We have to unshare an skb before modifying it. */
143 if (!skb_shared(skb))
146 nskb = skb_clone(skb, GFP_ATOMIC);
148 return ERR_PTR(-ENOMEM);
150 skb->prev->next = nskb;
151 skb->next->prev = nskb;
152 nskb->prev = skb->prev;
153 nskb->next = skb->next;
164 struct sk_buff *__skb_try_recv_from_queue(struct sock *sk,
165 struct sk_buff_head *queue,
167 void (*destructor)(struct sock *sk,
168 struct sk_buff *skb),
169 int *peeked, int *off, int *err,
170 struct sk_buff **last)
172 bool peek_at_off = false;
176 if (unlikely(flags & MSG_PEEK && *off >= 0)) {
182 skb_queue_walk(queue, skb) {
183 if (flags & MSG_PEEK) {
184 if (peek_at_off && _off >= skb->len &&
185 (_off || skb->peeked)) {
190 skb = skb_set_peeked(skb);
191 if (unlikely(IS_ERR(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 * @peeked: returns non-zero if this packet has been seen before
215 * @off: an offset in bytes to peek skb from. Returns an offset
216 * within an skb where data actually starts
217 * @err: error code returned
218 * @last: set to last peeked message to inform the wait function
219 * what to look for when peeking
221 * Get a datagram skbuff, understands the peeking, nonblocking wakeups
222 * and possible races. This replaces identical code in packet, raw and
223 * udp, as well as the IPX AX.25 and Appletalk. It also finally fixes
224 * the long standing peek and read race for datagram sockets. If you
225 * alter this routine remember it must be re-entrant.
227 * This function will lock the socket if a skb is returned, so
228 * the caller needs to unlock the socket in that case (usually by
229 * calling skb_free_datagram). Returns NULL with @err set to
230 * -EAGAIN if no data was available or to some other value if an
231 * error was detected.
233 * * It does not lock socket since today. This function is
234 * * free of race conditions. This measure should/can improve
235 * * significantly datagram socket latencies at high loads,
236 * * when data copying to user space takes lots of time.
237 * * (BTW I've just killed the last cli() in IP/IPv6/core/netlink/packet
241 * The order of the tests when we find no data waiting are specified
242 * quite explicitly by POSIX 1003.1g, don't change them without having
243 * the standard around please.
245 struct sk_buff *__skb_try_recv_datagram(struct sock *sk, unsigned int flags,
246 void (*destructor)(struct sock *sk,
247 struct sk_buff *skb),
248 int *peeked, int *off, int *err,
249 struct sk_buff **last)
251 struct sk_buff_head *queue = &sk->sk_receive_queue;
253 unsigned long cpu_flags;
255 * Caller is allowed not to check sk->sk_err before skb_recv_datagram()
257 int error = sock_error(sk);
264 /* Again only user level code calls this function, so nothing
265 * interrupt level will suddenly eat the receive_queue.
267 * Look at current nfs client by the way...
268 * However, this function was correct in any case. 8)
270 spin_lock_irqsave(&queue->lock, cpu_flags);
271 skb = __skb_try_recv_from_queue(sk, queue, flags, destructor,
272 peeked, off, &error, last);
273 spin_unlock_irqrestore(&queue->lock, cpu_flags);
279 if (!sk_can_busy_loop(sk))
282 sk_busy_loop(sk, flags & MSG_DONTWAIT);
283 } while (!skb_queue_empty(&sk->sk_receive_queue));
291 EXPORT_SYMBOL(__skb_try_recv_datagram);
293 struct sk_buff *__skb_recv_datagram(struct sock *sk, unsigned int flags,
294 void (*destructor)(struct sock *sk,
295 struct sk_buff *skb),
296 int *peeked, int *off, int *err)
298 struct sk_buff *skb, *last;
301 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
304 skb = __skb_try_recv_datagram(sk, flags, destructor, peeked,
312 !__skb_wait_for_more_packets(sk, err, &timeo, last));
316 EXPORT_SYMBOL(__skb_recv_datagram);
318 struct sk_buff *skb_recv_datagram(struct sock *sk, unsigned int flags,
319 int noblock, int *err)
323 return __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0),
324 NULL, &peeked, &off, err);
326 EXPORT_SYMBOL(skb_recv_datagram);
328 void skb_free_datagram(struct sock *sk, struct sk_buff *skb)
331 sk_mem_reclaim_partial(sk);
333 EXPORT_SYMBOL(skb_free_datagram);
335 void __skb_free_datagram_locked(struct sock *sk, struct sk_buff *skb, int len)
339 if (!skb_unref(skb)) {
340 sk_peek_offset_bwd(sk, len);
344 slow = lock_sock_fast(sk);
345 sk_peek_offset_bwd(sk, len);
347 sk_mem_reclaim_partial(sk);
348 unlock_sock_fast(sk, slow);
350 /* skb is now orphaned, can be freed outside of locked section */
353 EXPORT_SYMBOL(__skb_free_datagram_locked);
355 int __sk_queue_drop_skb(struct sock *sk, struct sk_buff_head *sk_queue,
356 struct sk_buff *skb, unsigned int flags,
357 void (*destructor)(struct sock *sk,
358 struct sk_buff *skb))
362 if (flags & MSG_PEEK) {
364 spin_lock_bh(&sk_queue->lock);
365 if (skb == skb_peek(sk_queue)) {
366 __skb_unlink(skb, sk_queue);
367 refcount_dec(&skb->users);
372 spin_unlock_bh(&sk_queue->lock);
375 atomic_inc(&sk->sk_drops);
378 EXPORT_SYMBOL(__sk_queue_drop_skb);
381 * skb_kill_datagram - Free a datagram skbuff forcibly
383 * @skb: datagram skbuff
384 * @flags: MSG\_ flags
386 * This function frees a datagram skbuff that was received by
387 * skb_recv_datagram. The flags argument must match the one
388 * used for skb_recv_datagram.
390 * If the MSG_PEEK flag is set, and the packet is still on the
391 * receive queue of the socket, it will be taken off the queue
392 * before it is freed.
394 * This function currently only disables BH when acquiring the
395 * sk_receive_queue lock. Therefore it must not be used in a
396 * context where that lock is acquired in an IRQ context.
398 * It returns 0 if the packet was removed by us.
401 int skb_kill_datagram(struct sock *sk, struct sk_buff *skb, unsigned int flags)
403 int err = __sk_queue_drop_skb(sk, &sk->sk_receive_queue, skb, flags,
407 sk_mem_reclaim_partial(sk);
410 EXPORT_SYMBOL(skb_kill_datagram);
413 * skb_copy_datagram_iter - Copy a datagram to an iovec iterator.
414 * @skb: buffer to copy
415 * @offset: offset in the buffer to start copying from
416 * @to: iovec iterator to copy to
417 * @len: amount of data to copy from buffer to iovec
419 int skb_copy_datagram_iter(const struct sk_buff *skb, int offset,
420 struct iov_iter *to, int len)
422 int start = skb_headlen(skb);
423 int i, copy = start - offset, start_off = offset, n;
424 struct sk_buff *frag_iter;
426 trace_skb_copy_datagram_iovec(skb, len);
432 n = copy_to_iter(skb->data + offset, copy, to);
436 if ((len -= copy) == 0)
440 /* Copy paged appendix. Hmm... why does this look so complicated? */
441 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
443 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
445 WARN_ON(start > offset + len);
447 end = start + skb_frag_size(frag);
448 if ((copy = end - offset) > 0) {
451 n = copy_page_to_iter(skb_frag_page(frag),
452 frag->page_offset + offset -
463 skb_walk_frags(skb, frag_iter) {
466 WARN_ON(start > offset + len);
468 end = start + frag_iter->len;
469 if ((copy = end - offset) > 0) {
472 if (skb_copy_datagram_iter(frag_iter, offset - start,
475 if ((len -= copy) == 0)
484 /* This is not really a user copy fault, but rather someone
485 * gave us a bogus length on the skb. We should probably
486 * print a warning here as it may indicate a kernel bug.
490 iov_iter_revert(to, offset - start_off);
494 if (iov_iter_count(to))
499 EXPORT_SYMBOL(skb_copy_datagram_iter);
502 * skb_copy_datagram_from_iter - Copy a datagram from an iov_iter.
503 * @skb: buffer to copy
504 * @offset: offset in the buffer to start copying to
505 * @from: the copy source
506 * @len: amount of data to copy to buffer from iovec
508 * Returns 0 or -EFAULT.
510 int skb_copy_datagram_from_iter(struct sk_buff *skb, int offset,
511 struct iov_iter *from,
514 int start = skb_headlen(skb);
515 int i, copy = start - offset;
516 struct sk_buff *frag_iter;
522 if (copy_from_iter(skb->data + offset, copy, from) != copy)
524 if ((len -= copy) == 0)
529 /* Copy paged appendix. Hmm... why does this look so complicated? */
530 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
532 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
534 WARN_ON(start > offset + len);
536 end = start + skb_frag_size(frag);
537 if ((copy = end - offset) > 0) {
542 copied = copy_page_from_iter(skb_frag_page(frag),
543 frag->page_offset + offset - start,
555 skb_walk_frags(skb, frag_iter) {
558 WARN_ON(start > offset + len);
560 end = start + frag_iter->len;
561 if ((copy = end - offset) > 0) {
564 if (skb_copy_datagram_from_iter(frag_iter,
568 if ((len -= copy) == 0)
580 EXPORT_SYMBOL(skb_copy_datagram_from_iter);
583 * zerocopy_sg_from_iter - Build a zerocopy datagram from an iov_iter
584 * @skb: buffer to copy
585 * @from: the source to copy from
587 * The function will first copy up to headlen, and then pin the userspace
588 * pages and build frags through them.
590 * Returns 0, -EFAULT or -EMSGSIZE.
592 int zerocopy_sg_from_iter(struct sk_buff *skb, struct iov_iter *from)
594 int len = iov_iter_count(from);
595 int copy = min_t(int, skb_headlen(skb), len);
598 /* copy up to skb headlen */
599 if (skb_copy_datagram_from_iter(skb, 0, from, copy))
602 while (iov_iter_count(from)) {
603 struct page *pages[MAX_SKB_FRAGS];
606 unsigned long truesize;
609 if (frag == MAX_SKB_FRAGS)
612 copied = iov_iter_get_pages(from, pages, ~0U,
613 MAX_SKB_FRAGS - frag, &start);
617 iov_iter_advance(from, copied);
619 truesize = PAGE_ALIGN(copied + start);
620 skb->data_len += copied;
622 skb->truesize += truesize;
623 refcount_add(truesize, &skb->sk->sk_wmem_alloc);
625 int size = min_t(int, copied, PAGE_SIZE - start);
626 skb_fill_page_desc(skb, frag++, pages[n], start, size);
634 EXPORT_SYMBOL(zerocopy_sg_from_iter);
636 static int skb_copy_and_csum_datagram(const struct sk_buff *skb, int offset,
637 struct iov_iter *to, int len,
640 int start = skb_headlen(skb);
641 int i, copy = start - offset, start_off = offset;
642 struct sk_buff *frag_iter;
650 n = csum_and_copy_to_iter(skb->data + offset, copy, csump, to);
654 if ((len -= copy) == 0)
659 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
661 const skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
663 WARN_ON(start > offset + len);
665 end = start + skb_frag_size(frag);
666 if ((copy = end - offset) > 0) {
668 struct page *page = skb_frag_page(frag);
669 u8 *vaddr = kmap(page);
673 n = csum_and_copy_to_iter(vaddr + frag->page_offset +
674 offset - start, copy,
680 *csump = csum_block_add(*csump, csum2, pos);
688 skb_walk_frags(skb, frag_iter) {
691 WARN_ON(start > offset + len);
693 end = start + frag_iter->len;
694 if ((copy = end - offset) > 0) {
698 if (skb_copy_and_csum_datagram(frag_iter,
703 *csump = csum_block_add(*csump, csum2, pos);
704 if ((len -= copy) == 0)
715 iov_iter_revert(to, offset - start_off);
719 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
723 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
725 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
726 !skb->csum_complete_sw)
727 netdev_rx_csum_fault(skb->dev);
729 if (!skb_shared(skb))
730 skb->csum_valid = !sum;
733 EXPORT_SYMBOL(__skb_checksum_complete_head);
735 __sum16 __skb_checksum_complete(struct sk_buff *skb)
740 csum = skb_checksum(skb, 0, skb->len, 0);
742 /* skb->csum holds pseudo checksum */
743 sum = csum_fold(csum_add(skb->csum, csum));
745 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
746 !skb->csum_complete_sw)
747 netdev_rx_csum_fault(skb->dev);
750 if (!skb_shared(skb)) {
751 /* Save full packet checksum */
753 skb->ip_summed = CHECKSUM_COMPLETE;
754 skb->csum_complete_sw = 1;
755 skb->csum_valid = !sum;
760 EXPORT_SYMBOL(__skb_checksum_complete);
763 * skb_copy_and_csum_datagram_msg - Copy and checksum skb to user iovec.
765 * @hlen: hardware length
768 * Caller _must_ check that skb will fit to this iovec.
770 * Returns: 0 - success.
771 * -EINVAL - checksum failure.
772 * -EFAULT - fault during copy.
774 int skb_copy_and_csum_datagram_msg(struct sk_buff *skb,
775 int hlen, struct msghdr *msg)
778 int chunk = skb->len - hlen;
783 if (msg_data_left(msg) < chunk) {
784 if (__skb_checksum_complete(skb))
786 if (skb_copy_datagram_msg(skb, hlen, msg, chunk))
789 csum = csum_partial(skb->data, hlen, skb->csum);
790 if (skb_copy_and_csum_datagram(skb, hlen, &msg->msg_iter,
794 if (csum_fold(csum)) {
795 iov_iter_revert(&msg->msg_iter, chunk);
799 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE))
800 netdev_rx_csum_fault(skb->dev);
806 EXPORT_SYMBOL(skb_copy_and_csum_datagram_msg);
809 * datagram_poll - generic datagram poll
814 * Datagram poll: Again totally generic. This also handles
815 * sequenced packet sockets providing the socket receive queue
816 * is only ever holding data ready to receive.
818 * Note: when you *don't* use this routine for this protocol,
819 * and you use a different write policy from sock_writeable()
820 * then please supply your own write_space callback.
822 unsigned int datagram_poll(struct file *file, struct socket *sock,
825 struct sock *sk = sock->sk;
828 sock_poll_wait(file, sk_sleep(sk), wait);
831 /* exceptional events? */
832 if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
834 (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
836 if (sk->sk_shutdown & RCV_SHUTDOWN)
837 mask |= POLLRDHUP | POLLIN | POLLRDNORM;
838 if (sk->sk_shutdown == SHUTDOWN_MASK)
842 if (!skb_queue_empty(&sk->sk_receive_queue))
843 mask |= POLLIN | POLLRDNORM;
845 /* Connection-based need to check for termination and startup */
846 if (connection_based(sk)) {
847 if (sk->sk_state == TCP_CLOSE)
849 /* connection hasn't started yet? */
850 if (sk->sk_state == TCP_SYN_SENT)
855 if (sock_writeable(sk))
856 mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
858 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
862 EXPORT_SYMBOL(datagram_poll);