1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Routines having to do with the 'struct sk_buff' memory handlers.
5 * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
6 * Florian La Roche <rzsfl@rz.uni-sb.de>
9 * Alan Cox : Fixed the worst of the load
11 * Dave Platt : Interrupt stacking fix.
12 * Richard Kooijman : Timestamp fixes.
13 * Alan Cox : Changed buffer format.
14 * Alan Cox : destructor hook for AF_UNIX etc.
15 * Linus Torvalds : Better skb_clone.
16 * Alan Cox : Added skb_copy.
17 * Alan Cox : Added all the changed routines Linus
18 * only put in the headers
19 * Ray VanTassle : Fixed --skb->lock in free
20 * Alan Cox : skb_copy copy arp field
21 * Andi Kleen : slabified it.
22 * Robert Olsson : Removed skb_head_pool
25 * The __skb_ routines should be called with interrupts
26 * disabled, or you better be *real* sure that the operation is atomic
27 * with respect to whatever list is being frobbed (e.g. via lock_sock()
28 * or via disabling bottom half handlers, etc).
32 * The functions in this file will not compile correctly with gcc 2.4.x
35 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/kernel.h>
41 #include <linux/interrupt.h>
43 #include <linux/inet.h>
44 #include <linux/slab.h>
45 #include <linux/tcp.h>
46 #include <linux/udp.h>
47 #include <linux/sctp.h>
48 #include <linux/netdevice.h>
49 #ifdef CONFIG_NET_CLS_ACT
50 #include <net/pkt_sched.h>
52 #include <linux/string.h>
53 #include <linux/skbuff.h>
54 #include <linux/splice.h>
55 #include <linux/cache.h>
56 #include <linux/rtnetlink.h>
57 #include <linux/init.h>
58 #include <linux/scatterlist.h>
59 #include <linux/errqueue.h>
60 #include <linux/prefetch.h>
61 #include <linux/if_vlan.h>
62 #include <linux/mpls.h>
63 #include <linux/kcov.h>
65 #include <net/protocol.h>
68 #include <net/checksum.h>
69 #include <net/ip6_checksum.h>
72 #include <net/mptcp.h>
74 #include <net/page_pool.h>
76 #include <linux/uaccess.h>
77 #include <trace/events/skb.h>
78 #include <linux/highmem.h>
79 #include <linux/capability.h>
80 #include <linux/user_namespace.h>
81 #include <linux/indirect_call_wrapper.h>
82 #include <linux/textsearch.h>
85 #include "sock_destructor.h"
87 struct kmem_cache *skbuff_cache __ro_after_init;
88 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
89 #ifdef CONFIG_SKB_EXTENSIONS
90 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
93 /* skb_small_head_cache and related code is only supported
94 * for CONFIG_SLAB and CONFIG_SLUB.
95 * As soon as SLOB is removed from the kernel, we can clean up this.
97 #if !defined(CONFIG_SLOB)
98 # define HAVE_SKB_SMALL_HEAD_CACHE 1
101 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
102 static struct kmem_cache *skb_small_head_cache __ro_after_init;
104 #define SKB_SMALL_HEAD_SIZE SKB_HEAD_ALIGN(MAX_TCP_HEADER)
106 /* We want SKB_SMALL_HEAD_CACHE_SIZE to not be a power of two.
107 * This should ensure that SKB_SMALL_HEAD_HEADROOM is a unique
108 * size, and we can differentiate heads from skb_small_head_cache
109 * vs system slabs by looking at their size (skb_end_offset()).
111 #define SKB_SMALL_HEAD_CACHE_SIZE \
112 (is_power_of_2(SKB_SMALL_HEAD_SIZE) ? \
113 (SKB_SMALL_HEAD_SIZE + L1_CACHE_BYTES) : \
116 #define SKB_SMALL_HEAD_HEADROOM \
117 SKB_WITH_OVERHEAD(SKB_SMALL_HEAD_CACHE_SIZE)
118 #endif /* HAVE_SKB_SMALL_HEAD_CACHE */
120 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
121 EXPORT_SYMBOL(sysctl_max_skb_frags);
124 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
125 const char * const drop_reasons[] = {
126 [SKB_CONSUMED] = "CONSUMED",
127 DEFINE_DROP_REASON(FN, FN)
129 EXPORT_SYMBOL(drop_reasons);
132 * skb_panic - private function for out-of-line support
136 * @msg: skb_over_panic or skb_under_panic
138 * Out-of-line support for skb_put() and skb_push().
139 * Called via the wrapper skb_over_panic() or skb_under_panic().
140 * Keep out of line to prevent kernel bloat.
141 * __builtin_return_address is not used because it is not always reliable.
143 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
146 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
147 msg, addr, skb->len, sz, skb->head, skb->data,
148 (unsigned long)skb->tail, (unsigned long)skb->end,
149 skb->dev ? skb->dev->name : "<NULL>");
153 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
155 skb_panic(skb, sz, addr, __func__);
158 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
160 skb_panic(skb, sz, addr, __func__);
163 #define NAPI_SKB_CACHE_SIZE 64
164 #define NAPI_SKB_CACHE_BULK 16
165 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
167 #if PAGE_SIZE == SZ_4K
169 #define NAPI_HAS_SMALL_PAGE_FRAG 1
170 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) ((nc).pfmemalloc)
172 /* specialized page frag allocator using a single order 0 page
173 * and slicing it into 1K sized fragment. Constrained to systems
174 * with a very limited amount of 1K fragments fitting a single
175 * page - to avoid excessive truesize underestimation
178 struct page_frag_1k {
184 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
189 offset = nc->offset - SZ_1K;
190 if (likely(offset >= 0))
193 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
197 nc->va = page_address(page);
198 nc->pfmemalloc = page_is_pfmemalloc(page);
199 offset = PAGE_SIZE - SZ_1K;
200 page_ref_add(page, offset / SZ_1K);
204 return nc->va + offset;
208 /* the small page is actually unused in this build; add dummy helpers
209 * to please the compiler and avoid later preprocessor's conditionals
211 #define NAPI_HAS_SMALL_PAGE_FRAG 0
212 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) false
214 struct page_frag_1k {
217 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
224 struct napi_alloc_cache {
225 struct page_frag_cache page;
226 struct page_frag_1k page_small;
227 unsigned int skb_count;
228 void *skb_cache[NAPI_SKB_CACHE_SIZE];
231 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
232 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
234 /* Double check that napi_get_frags() allocates skbs with
235 * skb->head being backed by slab, not a page fragment.
236 * This is to make sure bug fixed in 3226b158e67c
237 * ("net: avoid 32 x truesize under-estimation for tiny skbs")
238 * does not accidentally come back.
240 void napi_get_frags_check(struct napi_struct *napi)
245 skb = napi_get_frags(napi);
246 WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
247 napi_free_frags(napi);
251 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
253 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
255 fragsz = SKB_DATA_ALIGN(fragsz);
257 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
259 EXPORT_SYMBOL(__napi_alloc_frag_align);
261 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
265 fragsz = SKB_DATA_ALIGN(fragsz);
266 if (in_hardirq() || irqs_disabled()) {
267 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
269 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
271 struct napi_alloc_cache *nc;
274 nc = this_cpu_ptr(&napi_alloc_cache);
275 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
280 EXPORT_SYMBOL(__netdev_alloc_frag_align);
282 static struct sk_buff *napi_skb_cache_get(void)
284 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
287 if (unlikely(!nc->skb_count)) {
288 nc->skb_count = kmem_cache_alloc_bulk(skbuff_cache,
292 if (unlikely(!nc->skb_count))
296 skb = nc->skb_cache[--nc->skb_count];
297 kasan_unpoison_object_data(skbuff_cache, skb);
302 static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
305 struct skb_shared_info *shinfo;
307 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
309 /* Assumes caller memset cleared SKB */
310 skb->truesize = SKB_TRUESIZE(size);
311 refcount_set(&skb->users, 1);
314 skb_reset_tail_pointer(skb);
315 skb_set_end_offset(skb, size);
316 skb->mac_header = (typeof(skb->mac_header))~0U;
317 skb->transport_header = (typeof(skb->transport_header))~0U;
318 skb->alloc_cpu = raw_smp_processor_id();
319 /* make sure we initialize shinfo sequentially */
320 shinfo = skb_shinfo(skb);
321 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
322 atomic_set(&shinfo->dataref, 1);
324 skb_set_kcov_handle(skb, kcov_common_handle());
327 static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
332 /* Must find the allocation size (and grow it to match). */
334 /* krealloc() will immediately return "data" when
335 * "ksize(data)" is requested: it is the existing upper
336 * bounds. As a result, GFP_ATOMIC will be ignored. Note
337 * that this "new" pointer needs to be passed back to the
338 * caller for use so the __alloc_size hinting will be
341 resized = krealloc(data, *size, GFP_ATOMIC);
342 WARN_ON_ONCE(resized != data);
346 /* build_skb() variant which can operate on slab buffers.
347 * Note that this should be used sparingly as slab buffers
348 * cannot be combined efficiently by GRO!
350 struct sk_buff *slab_build_skb(void *data)
355 skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
359 memset(skb, 0, offsetof(struct sk_buff, tail));
360 data = __slab_build_skb(skb, data, &size);
361 __finalize_skb_around(skb, data, size);
365 EXPORT_SYMBOL(slab_build_skb);
367 /* Caller must provide SKB that is memset cleared */
368 static void __build_skb_around(struct sk_buff *skb, void *data,
369 unsigned int frag_size)
371 unsigned int size = frag_size;
373 /* frag_size == 0 is considered deprecated now. Callers
374 * using slab buffer should use slab_build_skb() instead.
376 if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
377 data = __slab_build_skb(skb, data, &size);
379 __finalize_skb_around(skb, data, size);
383 * __build_skb - build a network buffer
384 * @data: data buffer provided by caller
385 * @frag_size: size of data (must not be 0)
387 * Allocate a new &sk_buff. Caller provides space holding head and
388 * skb_shared_info. @data must have been allocated from the page
389 * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
390 * allocation is deprecated, and callers should use slab_build_skb()
392 * The return is the new skb buffer.
393 * On a failure the return is %NULL, and @data is not freed.
395 * Before IO, driver allocates only data buffer where NIC put incoming frame
396 * Driver should add room at head (NET_SKB_PAD) and
397 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
398 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
399 * before giving packet to stack.
400 * RX rings only contains data buffers, not full skbs.
402 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
406 skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
410 memset(skb, 0, offsetof(struct sk_buff, tail));
411 __build_skb_around(skb, data, frag_size);
416 /* build_skb() is wrapper over __build_skb(), that specifically
417 * takes care of skb->head and skb->pfmemalloc
419 struct sk_buff *build_skb(void *data, unsigned int frag_size)
421 struct sk_buff *skb = __build_skb(data, frag_size);
423 if (skb && frag_size) {
425 if (page_is_pfmemalloc(virt_to_head_page(data)))
430 EXPORT_SYMBOL(build_skb);
433 * build_skb_around - build a network buffer around provided skb
434 * @skb: sk_buff provide by caller, must be memset cleared
435 * @data: data buffer provided by caller
436 * @frag_size: size of data
438 struct sk_buff *build_skb_around(struct sk_buff *skb,
439 void *data, unsigned int frag_size)
444 __build_skb_around(skb, data, frag_size);
448 if (page_is_pfmemalloc(virt_to_head_page(data)))
453 EXPORT_SYMBOL(build_skb_around);
456 * __napi_build_skb - build a network buffer
457 * @data: data buffer provided by caller
458 * @frag_size: size of data
460 * Version of __build_skb() that uses NAPI percpu caches to obtain
461 * skbuff_head instead of inplace allocation.
463 * Returns a new &sk_buff on success, %NULL on allocation failure.
465 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
469 skb = napi_skb_cache_get();
473 memset(skb, 0, offsetof(struct sk_buff, tail));
474 __build_skb_around(skb, data, frag_size);
480 * napi_build_skb - build a network buffer
481 * @data: data buffer provided by caller
482 * @frag_size: size of data
484 * Version of __napi_build_skb() that takes care of skb->head_frag
485 * and skb->pfmemalloc when the data is a page or page fragment.
487 * Returns a new &sk_buff on success, %NULL on allocation failure.
489 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
491 struct sk_buff *skb = __napi_build_skb(data, frag_size);
493 if (likely(skb) && frag_size) {
495 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
500 EXPORT_SYMBOL(napi_build_skb);
503 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
504 * the caller if emergency pfmemalloc reserves are being used. If it is and
505 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
506 * may be used. Otherwise, the packet data may be discarded until enough
509 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
512 bool ret_pfmemalloc = false;
513 unsigned int obj_size;
516 obj_size = SKB_HEAD_ALIGN(*size);
517 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
518 if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
519 !(flags & KMALLOC_NOT_NORMAL_BITS)) {
520 obj = kmem_cache_alloc_node(skb_small_head_cache,
521 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
523 *size = SKB_SMALL_HEAD_CACHE_SIZE;
524 if (obj || !(gfp_pfmemalloc_allowed(flags)))
526 /* Try again but now we are using pfmemalloc reserves */
527 ret_pfmemalloc = true;
528 obj = kmem_cache_alloc_node(skb_small_head_cache, flags, node);
532 *size = obj_size = kmalloc_size_roundup(obj_size);
534 * Try a regular allocation, when that fails and we're not entitled
535 * to the reserves, fail.
537 obj = kmalloc_node_track_caller(obj_size,
538 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
540 if (obj || !(gfp_pfmemalloc_allowed(flags)))
543 /* Try again but now we are using pfmemalloc reserves */
544 ret_pfmemalloc = true;
545 obj = kmalloc_node_track_caller(obj_size, flags, node);
549 *pfmemalloc = ret_pfmemalloc;
554 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
555 * 'private' fields and also do memory statistics to find all the
561 * __alloc_skb - allocate a network buffer
562 * @size: size to allocate
563 * @gfp_mask: allocation mask
564 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
565 * instead of head cache and allocate a cloned (child) skb.
566 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
567 * allocations in case the data is required for writeback
568 * @node: numa node to allocate memory on
570 * Allocate a new &sk_buff. The returned buffer has no headroom and a
571 * tail room of at least size bytes. The object has a reference count
572 * of one. The return is the buffer. On a failure the return is %NULL.
574 * Buffers may only be allocated from interrupts using a @gfp_mask of
577 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
580 struct kmem_cache *cache;
585 cache = (flags & SKB_ALLOC_FCLONE)
586 ? skbuff_fclone_cache : skbuff_cache;
588 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
589 gfp_mask |= __GFP_MEMALLOC;
592 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
593 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
594 skb = napi_skb_cache_get();
596 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
601 /* We do our best to align skb_shared_info on a separate cache
602 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
603 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
604 * Both skb->head and skb_shared_info are cache line aligned.
606 data = kmalloc_reserve(&size, gfp_mask, node, &pfmemalloc);
609 /* kmalloc_size_roundup() might give us more room than requested.
610 * Put skb_shared_info exactly at the end of allocated zone,
611 * to allow max possible filling before reallocation.
613 prefetchw(data + SKB_WITH_OVERHEAD(size));
616 * Only clear those fields we need to clear, not those that we will
617 * actually initialise below. Hence, don't put any more fields after
618 * the tail pointer in struct sk_buff!
620 memset(skb, 0, offsetof(struct sk_buff, tail));
621 __build_skb_around(skb, data, size);
622 skb->pfmemalloc = pfmemalloc;
624 if (flags & SKB_ALLOC_FCLONE) {
625 struct sk_buff_fclones *fclones;
627 fclones = container_of(skb, struct sk_buff_fclones, skb1);
629 skb->fclone = SKB_FCLONE_ORIG;
630 refcount_set(&fclones->fclone_ref, 1);
636 kmem_cache_free(cache, skb);
639 EXPORT_SYMBOL(__alloc_skb);
642 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
643 * @dev: network device to receive on
644 * @len: length to allocate
645 * @gfp_mask: get_free_pages mask, passed to alloc_skb
647 * Allocate a new &sk_buff and assign it a usage count of one. The
648 * buffer has NET_SKB_PAD headroom built in. Users should allocate
649 * the headroom they think they need without accounting for the
650 * built in space. The built in space is used for optimisations.
652 * %NULL is returned if there is no free memory.
654 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
657 struct page_frag_cache *nc;
664 /* If requested length is either too small or too big,
665 * we use kmalloc() for skb->head allocation.
667 if (len <= SKB_WITH_OVERHEAD(1024) ||
668 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
669 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
670 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
676 len = SKB_HEAD_ALIGN(len);
678 if (sk_memalloc_socks())
679 gfp_mask |= __GFP_MEMALLOC;
681 if (in_hardirq() || irqs_disabled()) {
682 nc = this_cpu_ptr(&netdev_alloc_cache);
683 data = page_frag_alloc(nc, len, gfp_mask);
684 pfmemalloc = nc->pfmemalloc;
687 nc = this_cpu_ptr(&napi_alloc_cache.page);
688 data = page_frag_alloc(nc, len, gfp_mask);
689 pfmemalloc = nc->pfmemalloc;
696 skb = __build_skb(data, len);
697 if (unlikely(!skb)) {
707 skb_reserve(skb, NET_SKB_PAD);
713 EXPORT_SYMBOL(__netdev_alloc_skb);
716 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
717 * @napi: napi instance this buffer was allocated for
718 * @len: length to allocate
719 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
721 * Allocate a new sk_buff for use in NAPI receive. This buffer will
722 * attempt to allocate the head from a special reserved region used
723 * only for NAPI Rx allocation. By doing this we can save several
724 * CPU cycles by avoiding having to disable and re-enable IRQs.
726 * %NULL is returned if there is no free memory.
728 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
731 struct napi_alloc_cache *nc;
736 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
737 len += NET_SKB_PAD + NET_IP_ALIGN;
739 /* If requested length is either too small or too big,
740 * we use kmalloc() for skb->head allocation.
741 * When the small frag allocator is available, prefer it over kmalloc
742 * for small fragments
744 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
745 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
746 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
747 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
754 nc = this_cpu_ptr(&napi_alloc_cache);
756 if (sk_memalloc_socks())
757 gfp_mask |= __GFP_MEMALLOC;
759 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
760 /* we are artificially inflating the allocation size, but
761 * that is not as bad as it may look like, as:
762 * - 'len' less than GRO_MAX_HEAD makes little sense
763 * - On most systems, larger 'len' values lead to fragment
764 * size above 512 bytes
765 * - kmalloc would use the kmalloc-1k slab for such values
766 * - Builds with smaller GRO_MAX_HEAD will very likely do
767 * little networking, as that implies no WiFi and no
768 * tunnels support, and 32 bits arches.
772 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
773 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
775 len = SKB_HEAD_ALIGN(len);
777 data = page_frag_alloc(&nc->page, len, gfp_mask);
778 pfmemalloc = nc->page.pfmemalloc;
784 skb = __napi_build_skb(data, len);
785 if (unlikely(!skb)) {
795 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
796 skb->dev = napi->dev;
801 EXPORT_SYMBOL(__napi_alloc_skb);
803 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
804 int size, unsigned int truesize)
806 skb_fill_page_desc(skb, i, page, off, size);
808 skb->data_len += size;
809 skb->truesize += truesize;
811 EXPORT_SYMBOL(skb_add_rx_frag);
813 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
814 unsigned int truesize)
816 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
818 skb_frag_size_add(frag, size);
820 skb->data_len += size;
821 skb->truesize += truesize;
823 EXPORT_SYMBOL(skb_coalesce_rx_frag);
825 static void skb_drop_list(struct sk_buff **listp)
827 kfree_skb_list(*listp);
831 static inline void skb_drop_fraglist(struct sk_buff *skb)
833 skb_drop_list(&skb_shinfo(skb)->frag_list);
836 static void skb_clone_fraglist(struct sk_buff *skb)
838 struct sk_buff *list;
840 skb_walk_frags(skb, list)
844 static bool skb_pp_recycle(struct sk_buff *skb, void *data)
846 if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
848 return page_pool_return_skb_page(virt_to_page(data));
851 static void skb_kfree_head(void *head, unsigned int end_offset)
853 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
854 if (end_offset == SKB_SMALL_HEAD_HEADROOM)
855 kmem_cache_free(skb_small_head_cache, head);
861 static void skb_free_head(struct sk_buff *skb)
863 unsigned char *head = skb->head;
865 if (skb->head_frag) {
866 if (skb_pp_recycle(skb, head))
870 skb_kfree_head(head, skb_end_offset(skb));
874 static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason)
876 struct skb_shared_info *shinfo = skb_shinfo(skb);
880 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
884 if (skb_zcopy(skb)) {
885 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
887 skb_zcopy_clear(skb, true);
892 for (i = 0; i < shinfo->nr_frags; i++)
893 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
896 if (shinfo->frag_list)
897 kfree_skb_list_reason(shinfo->frag_list, reason);
901 /* When we clone an SKB we copy the reycling bit. The pp_recycle
902 * bit is only set on the head though, so in order to avoid races
903 * while trying to recycle fragments on __skb_frag_unref() we need
904 * to make one SKB responsible for triggering the recycle path.
905 * So disable the recycling bit if an SKB is cloned and we have
906 * additional references to the fragmented part of the SKB.
907 * Eventually the last SKB will have the recycling bit set and it's
908 * dataref set to 0, which will trigger the recycling
914 * Free an skbuff by memory without cleaning the state.
916 static void kfree_skbmem(struct sk_buff *skb)
918 struct sk_buff_fclones *fclones;
920 switch (skb->fclone) {
921 case SKB_FCLONE_UNAVAILABLE:
922 kmem_cache_free(skbuff_cache, skb);
925 case SKB_FCLONE_ORIG:
926 fclones = container_of(skb, struct sk_buff_fclones, skb1);
928 /* We usually free the clone (TX completion) before original skb
929 * This test would have no chance to be true for the clone,
930 * while here, branch prediction will be good.
932 if (refcount_read(&fclones->fclone_ref) == 1)
936 default: /* SKB_FCLONE_CLONE */
937 fclones = container_of(skb, struct sk_buff_fclones, skb2);
940 if (!refcount_dec_and_test(&fclones->fclone_ref))
943 kmem_cache_free(skbuff_fclone_cache, fclones);
946 void skb_release_head_state(struct sk_buff *skb)
949 if (skb->destructor) {
950 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
951 skb->destructor(skb);
953 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
954 nf_conntrack_put(skb_nfct(skb));
959 /* Free everything but the sk_buff shell. */
960 static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason)
962 skb_release_head_state(skb);
963 if (likely(skb->head))
964 skb_release_data(skb, reason);
968 * __kfree_skb - private function
971 * Free an sk_buff. Release anything attached to the buffer.
972 * Clean the state. This is an internal helper function. Users should
973 * always call kfree_skb
976 void __kfree_skb(struct sk_buff *skb)
978 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
981 EXPORT_SYMBOL(__kfree_skb);
983 static __always_inline
984 bool __kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
986 if (unlikely(!skb_unref(skb)))
989 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
991 if (reason == SKB_CONSUMED)
992 trace_consume_skb(skb, __builtin_return_address(0));
994 trace_kfree_skb(skb, __builtin_return_address(0), reason);
999 * kfree_skb_reason - free an sk_buff with special reason
1000 * @skb: buffer to free
1001 * @reason: reason why this skb is dropped
1003 * Drop a reference to the buffer and free it if the usage count has
1004 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
1008 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1010 if (__kfree_skb_reason(skb, reason))
1013 EXPORT_SYMBOL(kfree_skb_reason);
1015 #define KFREE_SKB_BULK_SIZE 16
1017 struct skb_free_array {
1018 unsigned int skb_count;
1019 void *skb_array[KFREE_SKB_BULK_SIZE];
1022 static void kfree_skb_add_bulk(struct sk_buff *skb,
1023 struct skb_free_array *sa,
1024 enum skb_drop_reason reason)
1026 /* if SKB is a clone, don't handle this case */
1027 if (unlikely(skb->fclone != SKB_FCLONE_UNAVAILABLE)) {
1032 skb_release_all(skb, reason);
1033 sa->skb_array[sa->skb_count++] = skb;
1035 if (unlikely(sa->skb_count == KFREE_SKB_BULK_SIZE)) {
1036 kmem_cache_free_bulk(skbuff_cache, KFREE_SKB_BULK_SIZE,
1043 kfree_skb_list_reason(struct sk_buff *segs, enum skb_drop_reason reason)
1045 struct skb_free_array sa;
1050 struct sk_buff *next = segs->next;
1052 if (__kfree_skb_reason(segs, reason)) {
1053 skb_poison_list(segs);
1054 kfree_skb_add_bulk(segs, &sa, reason);
1061 kmem_cache_free_bulk(skbuff_cache, sa.skb_count, sa.skb_array);
1063 EXPORT_SYMBOL(kfree_skb_list_reason);
1065 /* Dump skb information and contents.
1067 * Must only be called from net_ratelimit()-ed paths.
1069 * Dumps whole packets if full_pkt, only headers otherwise.
1071 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
1073 struct skb_shared_info *sh = skb_shinfo(skb);
1074 struct net_device *dev = skb->dev;
1075 struct sock *sk = skb->sk;
1076 struct sk_buff *list_skb;
1077 bool has_mac, has_trans;
1078 int headroom, tailroom;
1079 int i, len, seg_len;
1084 len = min_t(int, skb->len, MAX_HEADER + 128);
1086 headroom = skb_headroom(skb);
1087 tailroom = skb_tailroom(skb);
1089 has_mac = skb_mac_header_was_set(skb);
1090 has_trans = skb_transport_header_was_set(skb);
1092 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
1093 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
1094 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
1095 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
1096 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
1097 level, skb->len, headroom, skb_headlen(skb), tailroom,
1098 has_mac ? skb->mac_header : -1,
1099 has_mac ? skb_mac_header_len(skb) : -1,
1100 skb->network_header,
1101 has_trans ? skb_network_header_len(skb) : -1,
1102 has_trans ? skb->transport_header : -1,
1103 sh->tx_flags, sh->nr_frags,
1104 sh->gso_size, sh->gso_type, sh->gso_segs,
1105 skb->csum, skb->ip_summed, skb->csum_complete_sw,
1106 skb->csum_valid, skb->csum_level,
1107 skb->hash, skb->sw_hash, skb->l4_hash,
1108 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
1111 printk("%sdev name=%s feat=%pNF\n",
1112 level, dev->name, &dev->features);
1114 printk("%ssk family=%hu type=%u proto=%u\n",
1115 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
1117 if (full_pkt && headroom)
1118 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
1119 16, 1, skb->head, headroom, false);
1121 seg_len = min_t(int, skb_headlen(skb), len);
1123 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
1124 16, 1, skb->data, seg_len, false);
1127 if (full_pkt && tailroom)
1128 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
1129 16, 1, skb_tail_pointer(skb), tailroom, false);
1131 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
1132 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1133 u32 p_off, p_len, copied;
1137 skb_frag_foreach_page(frag, skb_frag_off(frag),
1138 skb_frag_size(frag), p, p_off, p_len,
1140 seg_len = min_t(int, p_len, len);
1141 vaddr = kmap_atomic(p);
1142 print_hex_dump(level, "skb frag: ",
1144 16, 1, vaddr + p_off, seg_len, false);
1145 kunmap_atomic(vaddr);
1152 if (full_pkt && skb_has_frag_list(skb)) {
1153 printk("skb fraglist:\n");
1154 skb_walk_frags(skb, list_skb)
1155 skb_dump(level, list_skb, true);
1158 EXPORT_SYMBOL(skb_dump);
1161 * skb_tx_error - report an sk_buff xmit error
1162 * @skb: buffer that triggered an error
1164 * Report xmit error if a device callback is tracking this skb.
1165 * skb must be freed afterwards.
1167 void skb_tx_error(struct sk_buff *skb)
1170 skb_zcopy_downgrade_managed(skb);
1171 skb_zcopy_clear(skb, true);
1174 EXPORT_SYMBOL(skb_tx_error);
1176 #ifdef CONFIG_TRACEPOINTS
1178 * consume_skb - free an skbuff
1179 * @skb: buffer to free
1181 * Drop a ref to the buffer and free it if the usage count has hit zero
1182 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1183 * is being dropped after a failure and notes that
1185 void consume_skb(struct sk_buff *skb)
1187 if (!skb_unref(skb))
1190 trace_consume_skb(skb, __builtin_return_address(0));
1193 EXPORT_SYMBOL(consume_skb);
1197 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1198 * @skb: buffer to free
1200 * Alike consume_skb(), but this variant assumes that this is the last
1201 * skb reference and all the head states have been already dropped
1203 void __consume_stateless_skb(struct sk_buff *skb)
1205 trace_consume_skb(skb, __builtin_return_address(0));
1206 skb_release_data(skb, SKB_CONSUMED);
1210 static void napi_skb_cache_put(struct sk_buff *skb)
1212 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1215 kasan_poison_object_data(skbuff_cache, skb);
1216 nc->skb_cache[nc->skb_count++] = skb;
1218 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1219 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1220 kasan_unpoison_object_data(skbuff_cache,
1223 kmem_cache_free_bulk(skbuff_cache, NAPI_SKB_CACHE_HALF,
1224 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1225 nc->skb_count = NAPI_SKB_CACHE_HALF;
1229 void __kfree_skb_defer(struct sk_buff *skb)
1231 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
1232 napi_skb_cache_put(skb);
1235 void napi_skb_free_stolen_head(struct sk_buff *skb)
1237 if (unlikely(skb->slow_gro)) {
1244 napi_skb_cache_put(skb);
1247 void napi_consume_skb(struct sk_buff *skb, int budget)
1249 /* Zero budget indicate non-NAPI context called us, like netpoll */
1250 if (unlikely(!budget)) {
1251 dev_consume_skb_any(skb);
1255 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1257 if (!skb_unref(skb))
1260 /* if reaching here SKB is ready to free */
1261 trace_consume_skb(skb, __builtin_return_address(0));
1263 /* if SKB is a clone, don't handle this case */
1264 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1269 skb_release_all(skb, SKB_CONSUMED);
1270 napi_skb_cache_put(skb);
1272 EXPORT_SYMBOL(napi_consume_skb);
1274 /* Make sure a field is contained by headers group */
1275 #define CHECK_SKB_FIELD(field) \
1276 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1277 offsetof(struct sk_buff, headers.field)); \
1279 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1281 new->tstamp = old->tstamp;
1282 /* We do not copy old->sk */
1283 new->dev = old->dev;
1284 memcpy(new->cb, old->cb, sizeof(old->cb));
1285 skb_dst_copy(new, old);
1286 __skb_ext_copy(new, old);
1287 __nf_copy(new, old, false);
1289 /* Note : this field could be in the headers group.
1290 * It is not yet because we do not want to have a 16 bit hole
1292 new->queue_mapping = old->queue_mapping;
1294 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1295 CHECK_SKB_FIELD(protocol);
1296 CHECK_SKB_FIELD(csum);
1297 CHECK_SKB_FIELD(hash);
1298 CHECK_SKB_FIELD(priority);
1299 CHECK_SKB_FIELD(skb_iif);
1300 CHECK_SKB_FIELD(vlan_proto);
1301 CHECK_SKB_FIELD(vlan_tci);
1302 CHECK_SKB_FIELD(transport_header);
1303 CHECK_SKB_FIELD(network_header);
1304 CHECK_SKB_FIELD(mac_header);
1305 CHECK_SKB_FIELD(inner_protocol);
1306 CHECK_SKB_FIELD(inner_transport_header);
1307 CHECK_SKB_FIELD(inner_network_header);
1308 CHECK_SKB_FIELD(inner_mac_header);
1309 CHECK_SKB_FIELD(mark);
1310 #ifdef CONFIG_NETWORK_SECMARK
1311 CHECK_SKB_FIELD(secmark);
1313 #ifdef CONFIG_NET_RX_BUSY_POLL
1314 CHECK_SKB_FIELD(napi_id);
1316 CHECK_SKB_FIELD(alloc_cpu);
1318 CHECK_SKB_FIELD(sender_cpu);
1320 #ifdef CONFIG_NET_SCHED
1321 CHECK_SKB_FIELD(tc_index);
1327 * You should not add any new code to this function. Add it to
1328 * __copy_skb_header above instead.
1330 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1332 #define C(x) n->x = skb->x
1334 n->next = n->prev = NULL;
1336 __copy_skb_header(n, skb);
1341 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1347 n->destructor = NULL;
1354 refcount_set(&n->users, 1);
1356 atomic_inc(&(skb_shinfo(skb)->dataref));
1364 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1365 * @first: first sk_buff of the msg
1367 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1371 n = alloc_skb(0, GFP_ATOMIC);
1375 n->len = first->len;
1376 n->data_len = first->len;
1377 n->truesize = first->truesize;
1379 skb_shinfo(n)->frag_list = first;
1381 __copy_skb_header(n, first);
1382 n->destructor = NULL;
1386 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1389 * skb_morph - morph one skb into another
1390 * @dst: the skb to receive the contents
1391 * @src: the skb to supply the contents
1393 * This is identical to skb_clone except that the target skb is
1394 * supplied by the user.
1396 * The target skb is returned upon exit.
1398 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1400 skb_release_all(dst, SKB_CONSUMED);
1401 return __skb_clone(dst, src);
1403 EXPORT_SYMBOL_GPL(skb_morph);
1405 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1407 unsigned long max_pg, num_pg, new_pg, old_pg, rlim;
1408 struct user_struct *user;
1410 if (capable(CAP_IPC_LOCK) || !size)
1413 rlim = rlimit(RLIMIT_MEMLOCK);
1414 if (rlim == RLIM_INFINITY)
1417 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1418 max_pg = rlim >> PAGE_SHIFT;
1419 user = mmp->user ? : current_user();
1421 old_pg = atomic_long_read(&user->locked_vm);
1423 new_pg = old_pg + num_pg;
1424 if (new_pg > max_pg)
1426 } while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1429 mmp->user = get_uid(user);
1430 mmp->num_pg = num_pg;
1432 mmp->num_pg += num_pg;
1437 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1439 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1442 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1443 free_uid(mmp->user);
1446 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1448 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1450 struct ubuf_info_msgzc *uarg;
1451 struct sk_buff *skb;
1453 WARN_ON_ONCE(!in_task());
1455 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1459 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1460 uarg = (void *)skb->cb;
1461 uarg->mmp.user = NULL;
1463 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1468 uarg->ubuf.callback = msg_zerocopy_callback;
1469 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1471 uarg->bytelen = size;
1473 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1474 refcount_set(&uarg->ubuf.refcnt, 1);
1480 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1482 return container_of((void *)uarg, struct sk_buff, cb);
1485 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1486 struct ubuf_info *uarg)
1489 struct ubuf_info_msgzc *uarg_zc;
1490 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1493 /* there might be non MSG_ZEROCOPY users */
1494 if (uarg->callback != msg_zerocopy_callback)
1497 /* realloc only when socket is locked (TCP, UDP cork),
1498 * so uarg->len and sk_zckey access is serialized
1500 if (!sock_owned_by_user(sk)) {
1505 uarg_zc = uarg_to_msgzc(uarg);
1506 bytelen = uarg_zc->bytelen + size;
1507 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1508 /* TCP can create new skb to attach new uarg */
1509 if (sk->sk_type == SOCK_STREAM)
1514 next = (u32)atomic_read(&sk->sk_zckey);
1515 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1516 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1519 uarg_zc->bytelen = bytelen;
1520 atomic_set(&sk->sk_zckey, ++next);
1522 /* no extra ref when appending to datagram (MSG_MORE) */
1523 if (sk->sk_type == SOCK_STREAM)
1524 net_zcopy_get(uarg);
1531 return msg_zerocopy_alloc(sk, size);
1533 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1535 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1537 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1541 old_lo = serr->ee.ee_info;
1542 old_hi = serr->ee.ee_data;
1543 sum_len = old_hi - old_lo + 1ULL + len;
1545 if (sum_len >= (1ULL << 32))
1548 if (lo != old_hi + 1)
1551 serr->ee.ee_data += len;
1555 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1557 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1558 struct sock_exterr_skb *serr;
1559 struct sock *sk = skb->sk;
1560 struct sk_buff_head *q;
1561 unsigned long flags;
1566 mm_unaccount_pinned_pages(&uarg->mmp);
1568 /* if !len, there was only 1 call, and it was aborted
1569 * so do not queue a completion notification
1571 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1576 hi = uarg->id + len - 1;
1577 is_zerocopy = uarg->zerocopy;
1579 serr = SKB_EXT_ERR(skb);
1580 memset(serr, 0, sizeof(*serr));
1581 serr->ee.ee_errno = 0;
1582 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1583 serr->ee.ee_data = hi;
1584 serr->ee.ee_info = lo;
1586 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1588 q = &sk->sk_error_queue;
1589 spin_lock_irqsave(&q->lock, flags);
1590 tail = skb_peek_tail(q);
1591 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1592 !skb_zerocopy_notify_extend(tail, lo, len)) {
1593 __skb_queue_tail(q, skb);
1596 spin_unlock_irqrestore(&q->lock, flags);
1598 sk_error_report(sk);
1605 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1608 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1610 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1612 if (refcount_dec_and_test(&uarg->refcnt))
1613 __msg_zerocopy_callback(uarg_zc);
1615 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1617 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1619 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1621 atomic_dec(&sk->sk_zckey);
1622 uarg_to_msgzc(uarg)->len--;
1625 msg_zerocopy_callback(NULL, uarg, true);
1627 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1629 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1630 struct msghdr *msg, int len,
1631 struct ubuf_info *uarg)
1633 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1634 int err, orig_len = skb->len;
1636 /* An skb can only point to one uarg. This edge case happens when
1637 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1639 if (orig_uarg && uarg != orig_uarg)
1642 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1643 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1644 struct sock *save_sk = skb->sk;
1646 /* Streams do not free skb on error. Reset to prev state. */
1647 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1649 ___pskb_trim(skb, orig_len);
1654 skb_zcopy_set(skb, uarg, NULL);
1655 return skb->len - orig_len;
1657 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1659 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1663 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1664 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1665 skb_frag_ref(skb, i);
1667 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1669 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1672 if (skb_zcopy(orig)) {
1673 if (skb_zcopy(nskb)) {
1674 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1679 if (skb_uarg(nskb) == skb_uarg(orig))
1681 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1684 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1690 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1691 * @skb: the skb to modify
1692 * @gfp_mask: allocation priority
1694 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1695 * It will copy all frags into kernel and drop the reference
1696 * to userspace pages.
1698 * If this function is called from an interrupt gfp_mask() must be
1701 * Returns 0 on success or a negative error code on failure
1702 * to allocate kernel memory to copy to.
1704 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1706 int num_frags = skb_shinfo(skb)->nr_frags;
1707 struct page *page, *head = NULL;
1711 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1717 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1718 for (i = 0; i < new_frags; i++) {
1719 page = alloc_page(gfp_mask);
1722 struct page *next = (struct page *)page_private(head);
1728 set_page_private(page, (unsigned long)head);
1734 for (i = 0; i < num_frags; i++) {
1735 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1736 u32 p_off, p_len, copied;
1740 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1741 p, p_off, p_len, copied) {
1743 vaddr = kmap_atomic(p);
1745 while (done < p_len) {
1746 if (d_off == PAGE_SIZE) {
1748 page = (struct page *)page_private(page);
1750 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1751 memcpy(page_address(page) + d_off,
1752 vaddr + p_off + done, copy);
1756 kunmap_atomic(vaddr);
1760 /* skb frags release userspace buffers */
1761 for (i = 0; i < num_frags; i++)
1762 skb_frag_unref(skb, i);
1764 /* skb frags point to kernel buffers */
1765 for (i = 0; i < new_frags - 1; i++) {
1766 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1767 head = (struct page *)page_private(head);
1769 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1770 skb_shinfo(skb)->nr_frags = new_frags;
1773 skb_zcopy_clear(skb, false);
1776 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1779 * skb_clone - duplicate an sk_buff
1780 * @skb: buffer to clone
1781 * @gfp_mask: allocation priority
1783 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1784 * copies share the same packet data but not structure. The new
1785 * buffer has a reference count of 1. If the allocation fails the
1786 * function returns %NULL otherwise the new buffer is returned.
1788 * If this function is called from an interrupt gfp_mask() must be
1792 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1794 struct sk_buff_fclones *fclones = container_of(skb,
1795 struct sk_buff_fclones,
1799 if (skb_orphan_frags(skb, gfp_mask))
1802 if (skb->fclone == SKB_FCLONE_ORIG &&
1803 refcount_read(&fclones->fclone_ref) == 1) {
1805 refcount_set(&fclones->fclone_ref, 2);
1806 n->fclone = SKB_FCLONE_CLONE;
1808 if (skb_pfmemalloc(skb))
1809 gfp_mask |= __GFP_MEMALLOC;
1811 n = kmem_cache_alloc(skbuff_cache, gfp_mask);
1815 n->fclone = SKB_FCLONE_UNAVAILABLE;
1818 return __skb_clone(n, skb);
1820 EXPORT_SYMBOL(skb_clone);
1822 void skb_headers_offset_update(struct sk_buff *skb, int off)
1824 /* Only adjust this if it actually is csum_start rather than csum */
1825 if (skb->ip_summed == CHECKSUM_PARTIAL)
1826 skb->csum_start += off;
1827 /* {transport,network,mac}_header and tail are relative to skb->head */
1828 skb->transport_header += off;
1829 skb->network_header += off;
1830 if (skb_mac_header_was_set(skb))
1831 skb->mac_header += off;
1832 skb->inner_transport_header += off;
1833 skb->inner_network_header += off;
1834 skb->inner_mac_header += off;
1836 EXPORT_SYMBOL(skb_headers_offset_update);
1838 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1840 __copy_skb_header(new, old);
1842 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1843 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1844 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1846 EXPORT_SYMBOL(skb_copy_header);
1848 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1850 if (skb_pfmemalloc(skb))
1851 return SKB_ALLOC_RX;
1856 * skb_copy - create private copy of an sk_buff
1857 * @skb: buffer to copy
1858 * @gfp_mask: allocation priority
1860 * Make a copy of both an &sk_buff and its data. This is used when the
1861 * caller wishes to modify the data and needs a private copy of the
1862 * data to alter. Returns %NULL on failure or the pointer to the buffer
1863 * on success. The returned buffer has a reference count of 1.
1865 * As by-product this function converts non-linear &sk_buff to linear
1866 * one, so that &sk_buff becomes completely private and caller is allowed
1867 * to modify all the data of returned buffer. This means that this
1868 * function is not recommended for use in circumstances when only
1869 * header is going to be modified. Use pskb_copy() instead.
1872 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1874 int headerlen = skb_headroom(skb);
1875 unsigned int size = skb_end_offset(skb) + skb->data_len;
1876 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1877 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1882 /* Set the data pointer */
1883 skb_reserve(n, headerlen);
1884 /* Set the tail pointer and length */
1885 skb_put(n, skb->len);
1887 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1889 skb_copy_header(n, skb);
1892 EXPORT_SYMBOL(skb_copy);
1895 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1896 * @skb: buffer to copy
1897 * @headroom: headroom of new skb
1898 * @gfp_mask: allocation priority
1899 * @fclone: if true allocate the copy of the skb from the fclone
1900 * cache instead of the head cache; it is recommended to set this
1901 * to true for the cases where the copy will likely be cloned
1903 * Make a copy of both an &sk_buff and part of its data, located
1904 * in header. Fragmented data remain shared. This is used when
1905 * the caller wishes to modify only header of &sk_buff and needs
1906 * private copy of the header to alter. Returns %NULL on failure
1907 * or the pointer to the buffer on success.
1908 * The returned buffer has a reference count of 1.
1911 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1912 gfp_t gfp_mask, bool fclone)
1914 unsigned int size = skb_headlen(skb) + headroom;
1915 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1916 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1921 /* Set the data pointer */
1922 skb_reserve(n, headroom);
1923 /* Set the tail pointer and length */
1924 skb_put(n, skb_headlen(skb));
1925 /* Copy the bytes */
1926 skb_copy_from_linear_data(skb, n->data, n->len);
1928 n->truesize += skb->data_len;
1929 n->data_len = skb->data_len;
1932 if (skb_shinfo(skb)->nr_frags) {
1935 if (skb_orphan_frags(skb, gfp_mask) ||
1936 skb_zerocopy_clone(n, skb, gfp_mask)) {
1941 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1942 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1943 skb_frag_ref(skb, i);
1945 skb_shinfo(n)->nr_frags = i;
1948 if (skb_has_frag_list(skb)) {
1949 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1950 skb_clone_fraglist(n);
1953 skb_copy_header(n, skb);
1957 EXPORT_SYMBOL(__pskb_copy_fclone);
1960 * pskb_expand_head - reallocate header of &sk_buff
1961 * @skb: buffer to reallocate
1962 * @nhead: room to add at head
1963 * @ntail: room to add at tail
1964 * @gfp_mask: allocation priority
1966 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1967 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1968 * reference count of 1. Returns zero in the case of success or error,
1969 * if expansion failed. In the last case, &sk_buff is not changed.
1971 * All the pointers pointing into skb header may change and must be
1972 * reloaded after call to this function.
1975 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1978 unsigned int osize = skb_end_offset(skb);
1979 unsigned int size = osize + nhead + ntail;
1986 BUG_ON(skb_shared(skb));
1988 skb_zcopy_downgrade_managed(skb);
1990 if (skb_pfmemalloc(skb))
1991 gfp_mask |= __GFP_MEMALLOC;
1993 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
1996 size = SKB_WITH_OVERHEAD(size);
1998 /* Copy only real data... and, alas, header. This should be
1999 * optimized for the cases when header is void.
2001 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
2003 memcpy((struct skb_shared_info *)(data + size),
2005 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
2008 * if shinfo is shared we must drop the old head gracefully, but if it
2009 * is not we can just drop the old head and let the existing refcount
2010 * be since all we did is relocate the values
2012 if (skb_cloned(skb)) {
2013 if (skb_orphan_frags(skb, gfp_mask))
2016 refcount_inc(&skb_uarg(skb)->refcnt);
2017 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2018 skb_frag_ref(skb, i);
2020 if (skb_has_frag_list(skb))
2021 skb_clone_fraglist(skb);
2023 skb_release_data(skb, SKB_CONSUMED);
2027 off = (data + nhead) - skb->head;
2033 skb_set_end_offset(skb, size);
2034 #ifdef NET_SKBUFF_DATA_USES_OFFSET
2038 skb_headers_offset_update(skb, nhead);
2042 atomic_set(&skb_shinfo(skb)->dataref, 1);
2044 skb_metadata_clear(skb);
2046 /* It is not generally safe to change skb->truesize.
2047 * For the moment, we really care of rx path, or
2048 * when skb is orphaned (not attached to a socket).
2050 if (!skb->sk || skb->destructor == sock_edemux)
2051 skb->truesize += size - osize;
2056 skb_kfree_head(data, size);
2060 EXPORT_SYMBOL(pskb_expand_head);
2062 /* Make private copy of skb with writable head and some headroom */
2064 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
2066 struct sk_buff *skb2;
2067 int delta = headroom - skb_headroom(skb);
2070 skb2 = pskb_copy(skb, GFP_ATOMIC);
2072 skb2 = skb_clone(skb, GFP_ATOMIC);
2073 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
2081 EXPORT_SYMBOL(skb_realloc_headroom);
2083 /* Note: We plan to rework this in linux-6.4 */
2084 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
2086 unsigned int saved_end_offset, saved_truesize;
2087 struct skb_shared_info *shinfo;
2090 saved_end_offset = skb_end_offset(skb);
2091 saved_truesize = skb->truesize;
2093 res = pskb_expand_head(skb, 0, 0, pri);
2097 skb->truesize = saved_truesize;
2099 if (likely(skb_end_offset(skb) == saved_end_offset))
2102 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
2103 /* We can not change skb->end if the original or new value
2104 * is SKB_SMALL_HEAD_HEADROOM, as it might break skb_kfree_head().
2106 if (saved_end_offset == SKB_SMALL_HEAD_HEADROOM ||
2107 skb_end_offset(skb) == SKB_SMALL_HEAD_HEADROOM) {
2108 /* We think this path should not be taken.
2109 * Add a temporary trace to warn us just in case.
2111 pr_err_once("__skb_unclone_keeptruesize() skb_end_offset() %u -> %u\n",
2112 saved_end_offset, skb_end_offset(skb));
2118 shinfo = skb_shinfo(skb);
2120 /* We are about to change back skb->end,
2121 * we need to move skb_shinfo() to its new location.
2123 memmove(skb->head + saved_end_offset,
2125 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
2127 skb_set_end_offset(skb, saved_end_offset);
2133 * skb_expand_head - reallocate header of &sk_buff
2134 * @skb: buffer to reallocate
2135 * @headroom: needed headroom
2137 * Unlike skb_realloc_headroom, this one does not allocate a new skb
2138 * if possible; copies skb->sk to new skb as needed
2139 * and frees original skb in case of failures.
2141 * It expect increased headroom and generates warning otherwise.
2144 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2146 int delta = headroom - skb_headroom(skb);
2147 int osize = skb_end_offset(skb);
2148 struct sock *sk = skb->sk;
2150 if (WARN_ONCE(delta <= 0,
2151 "%s is expecting an increase in the headroom", __func__))
2154 delta = SKB_DATA_ALIGN(delta);
2155 /* pskb_expand_head() might crash, if skb is shared. */
2156 if (skb_shared(skb) || !is_skb_wmem(skb)) {
2157 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2159 if (unlikely(!nskb))
2163 skb_set_owner_w(nskb, sk);
2167 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2170 if (sk && is_skb_wmem(skb)) {
2171 delta = skb_end_offset(skb) - osize;
2172 refcount_add(delta, &sk->sk_wmem_alloc);
2173 skb->truesize += delta;
2181 EXPORT_SYMBOL(skb_expand_head);
2184 * skb_copy_expand - copy and expand sk_buff
2185 * @skb: buffer to copy
2186 * @newheadroom: new free bytes at head
2187 * @newtailroom: new free bytes at tail
2188 * @gfp_mask: allocation priority
2190 * Make a copy of both an &sk_buff and its data and while doing so
2191 * allocate additional space.
2193 * This is used when the caller wishes to modify the data and needs a
2194 * private copy of the data to alter as well as more space for new fields.
2195 * Returns %NULL on failure or the pointer to the buffer
2196 * on success. The returned buffer has a reference count of 1.
2198 * You must pass %GFP_ATOMIC as the allocation priority if this function
2199 * is called from an interrupt.
2201 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2202 int newheadroom, int newtailroom,
2206 * Allocate the copy buffer
2208 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2209 gfp_mask, skb_alloc_rx_flag(skb),
2211 int oldheadroom = skb_headroom(skb);
2212 int head_copy_len, head_copy_off;
2217 skb_reserve(n, newheadroom);
2219 /* Set the tail pointer and length */
2220 skb_put(n, skb->len);
2222 head_copy_len = oldheadroom;
2224 if (newheadroom <= head_copy_len)
2225 head_copy_len = newheadroom;
2227 head_copy_off = newheadroom - head_copy_len;
2229 /* Copy the linear header and data. */
2230 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2231 skb->len + head_copy_len));
2233 skb_copy_header(n, skb);
2235 skb_headers_offset_update(n, newheadroom - oldheadroom);
2239 EXPORT_SYMBOL(skb_copy_expand);
2242 * __skb_pad - zero pad the tail of an skb
2243 * @skb: buffer to pad
2244 * @pad: space to pad
2245 * @free_on_error: free buffer on error
2247 * Ensure that a buffer is followed by a padding area that is zero
2248 * filled. Used by network drivers which may DMA or transfer data
2249 * beyond the buffer end onto the wire.
2251 * May return error in out of memory cases. The skb is freed on error
2252 * if @free_on_error is true.
2255 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2260 /* If the skbuff is non linear tailroom is always zero.. */
2261 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2262 memset(skb->data+skb->len, 0, pad);
2266 ntail = skb->data_len + pad - (skb->end - skb->tail);
2267 if (likely(skb_cloned(skb) || ntail > 0)) {
2268 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2273 /* FIXME: The use of this function with non-linear skb's really needs
2276 err = skb_linearize(skb);
2280 memset(skb->data + skb->len, 0, pad);
2288 EXPORT_SYMBOL(__skb_pad);
2291 * pskb_put - add data to the tail of a potentially fragmented buffer
2292 * @skb: start of the buffer to use
2293 * @tail: tail fragment of the buffer to use
2294 * @len: amount of data to add
2296 * This function extends the used data area of the potentially
2297 * fragmented buffer. @tail must be the last fragment of @skb -- or
2298 * @skb itself. If this would exceed the total buffer size the kernel
2299 * will panic. A pointer to the first byte of the extra data is
2303 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2306 skb->data_len += len;
2309 return skb_put(tail, len);
2311 EXPORT_SYMBOL_GPL(pskb_put);
2314 * skb_put - add data to a buffer
2315 * @skb: buffer to use
2316 * @len: amount of data to add
2318 * This function extends the used data area of the buffer. If this would
2319 * exceed the total buffer size the kernel will panic. A pointer to the
2320 * first byte of the extra data is returned.
2322 void *skb_put(struct sk_buff *skb, unsigned int len)
2324 void *tmp = skb_tail_pointer(skb);
2325 SKB_LINEAR_ASSERT(skb);
2328 if (unlikely(skb->tail > skb->end))
2329 skb_over_panic(skb, len, __builtin_return_address(0));
2332 EXPORT_SYMBOL(skb_put);
2335 * skb_push - add data to the start of a buffer
2336 * @skb: buffer to use
2337 * @len: amount of data to add
2339 * This function extends the used data area of the buffer at the buffer
2340 * start. If this would exceed the total buffer headroom the kernel will
2341 * panic. A pointer to the first byte of the extra data is returned.
2343 void *skb_push(struct sk_buff *skb, unsigned int len)
2347 if (unlikely(skb->data < skb->head))
2348 skb_under_panic(skb, len, __builtin_return_address(0));
2351 EXPORT_SYMBOL(skb_push);
2354 * skb_pull - remove data from the start of a buffer
2355 * @skb: buffer to use
2356 * @len: amount of data to remove
2358 * This function removes data from the start of a buffer, returning
2359 * the memory to the headroom. A pointer to the next data in the buffer
2360 * is returned. Once the data has been pulled future pushes will overwrite
2363 void *skb_pull(struct sk_buff *skb, unsigned int len)
2365 return skb_pull_inline(skb, len);
2367 EXPORT_SYMBOL(skb_pull);
2370 * skb_pull_data - remove data from the start of a buffer returning its
2371 * original position.
2372 * @skb: buffer to use
2373 * @len: amount of data to remove
2375 * This function removes data from the start of a buffer, returning
2376 * the memory to the headroom. A pointer to the original data in the buffer
2377 * is returned after checking if there is enough data to pull. Once the
2378 * data has been pulled future pushes will overwrite the old data.
2380 void *skb_pull_data(struct sk_buff *skb, size_t len)
2382 void *data = skb->data;
2391 EXPORT_SYMBOL(skb_pull_data);
2394 * skb_trim - remove end from a buffer
2395 * @skb: buffer to alter
2398 * Cut the length of a buffer down by removing data from the tail. If
2399 * the buffer is already under the length specified it is not modified.
2400 * The skb must be linear.
2402 void skb_trim(struct sk_buff *skb, unsigned int len)
2405 __skb_trim(skb, len);
2407 EXPORT_SYMBOL(skb_trim);
2409 /* Trims skb to length len. It can change skb pointers.
2412 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2414 struct sk_buff **fragp;
2415 struct sk_buff *frag;
2416 int offset = skb_headlen(skb);
2417 int nfrags = skb_shinfo(skb)->nr_frags;
2421 if (skb_cloned(skb) &&
2422 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2429 for (; i < nfrags; i++) {
2430 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2437 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2440 skb_shinfo(skb)->nr_frags = i;
2442 for (; i < nfrags; i++)
2443 skb_frag_unref(skb, i);
2445 if (skb_has_frag_list(skb))
2446 skb_drop_fraglist(skb);
2450 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2451 fragp = &frag->next) {
2452 int end = offset + frag->len;
2454 if (skb_shared(frag)) {
2455 struct sk_buff *nfrag;
2457 nfrag = skb_clone(frag, GFP_ATOMIC);
2458 if (unlikely(!nfrag))
2461 nfrag->next = frag->next;
2473 unlikely((err = pskb_trim(frag, len - offset))))
2477 skb_drop_list(&frag->next);
2482 if (len > skb_headlen(skb)) {
2483 skb->data_len -= skb->len - len;
2488 skb_set_tail_pointer(skb, len);
2491 if (!skb->sk || skb->destructor == sock_edemux)
2495 EXPORT_SYMBOL(___pskb_trim);
2497 /* Note : use pskb_trim_rcsum() instead of calling this directly
2499 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2501 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2502 int delta = skb->len - len;
2504 skb->csum = csum_block_sub(skb->csum,
2505 skb_checksum(skb, len, delta, 0),
2507 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2508 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2509 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2511 if (offset + sizeof(__sum16) > hdlen)
2514 return __pskb_trim(skb, len);
2516 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2519 * __pskb_pull_tail - advance tail of skb header
2520 * @skb: buffer to reallocate
2521 * @delta: number of bytes to advance tail
2523 * The function makes a sense only on a fragmented &sk_buff,
2524 * it expands header moving its tail forward and copying necessary
2525 * data from fragmented part.
2527 * &sk_buff MUST have reference count of 1.
2529 * Returns %NULL (and &sk_buff does not change) if pull failed
2530 * or value of new tail of skb in the case of success.
2532 * All the pointers pointing into skb header may change and must be
2533 * reloaded after call to this function.
2536 /* Moves tail of skb head forward, copying data from fragmented part,
2537 * when it is necessary.
2538 * 1. It may fail due to malloc failure.
2539 * 2. It may change skb pointers.
2541 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2543 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2545 /* If skb has not enough free space at tail, get new one
2546 * plus 128 bytes for future expansions. If we have enough
2547 * room at tail, reallocate without expansion only if skb is cloned.
2549 int i, k, eat = (skb->tail + delta) - skb->end;
2551 if (eat > 0 || skb_cloned(skb)) {
2552 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2557 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2558 skb_tail_pointer(skb), delta));
2560 /* Optimization: no fragments, no reasons to preestimate
2561 * size of pulled pages. Superb.
2563 if (!skb_has_frag_list(skb))
2566 /* Estimate size of pulled pages. */
2568 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2569 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2576 /* If we need update frag list, we are in troubles.
2577 * Certainly, it is possible to add an offset to skb data,
2578 * but taking into account that pulling is expected to
2579 * be very rare operation, it is worth to fight against
2580 * further bloating skb head and crucify ourselves here instead.
2581 * Pure masohism, indeed. 8)8)
2584 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2585 struct sk_buff *clone = NULL;
2586 struct sk_buff *insp = NULL;
2589 if (list->len <= eat) {
2590 /* Eaten as whole. */
2595 /* Eaten partially. */
2596 if (skb_is_gso(skb) && !list->head_frag &&
2598 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2600 if (skb_shared(list)) {
2601 /* Sucks! We need to fork list. :-( */
2602 clone = skb_clone(list, GFP_ATOMIC);
2608 /* This may be pulled without
2612 if (!pskb_pull(list, eat)) {
2620 /* Free pulled out fragments. */
2621 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2622 skb_shinfo(skb)->frag_list = list->next;
2625 /* And insert new clone at head. */
2628 skb_shinfo(skb)->frag_list = clone;
2631 /* Success! Now we may commit changes to skb data. */
2636 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2637 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2640 skb_frag_unref(skb, i);
2643 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2645 *frag = skb_shinfo(skb)->frags[i];
2647 skb_frag_off_add(frag, eat);
2648 skb_frag_size_sub(frag, eat);
2656 skb_shinfo(skb)->nr_frags = k;
2660 skb->data_len -= delta;
2663 skb_zcopy_clear(skb, false);
2665 return skb_tail_pointer(skb);
2667 EXPORT_SYMBOL(__pskb_pull_tail);
2670 * skb_copy_bits - copy bits from skb to kernel buffer
2672 * @offset: offset in source
2673 * @to: destination buffer
2674 * @len: number of bytes to copy
2676 * Copy the specified number of bytes from the source skb to the
2677 * destination buffer.
2680 * If its prototype is ever changed,
2681 * check arch/{*}/net/{*}.S files,
2682 * since it is called from BPF assembly code.
2684 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2686 int start = skb_headlen(skb);
2687 struct sk_buff *frag_iter;
2690 if (offset > (int)skb->len - len)
2694 if ((copy = start - offset) > 0) {
2697 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2698 if ((len -= copy) == 0)
2704 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2706 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2708 WARN_ON(start > offset + len);
2710 end = start + skb_frag_size(f);
2711 if ((copy = end - offset) > 0) {
2712 u32 p_off, p_len, copied;
2719 skb_frag_foreach_page(f,
2720 skb_frag_off(f) + offset - start,
2721 copy, p, p_off, p_len, copied) {
2722 vaddr = kmap_atomic(p);
2723 memcpy(to + copied, vaddr + p_off, p_len);
2724 kunmap_atomic(vaddr);
2727 if ((len -= copy) == 0)
2735 skb_walk_frags(skb, frag_iter) {
2738 WARN_ON(start > offset + len);
2740 end = start + frag_iter->len;
2741 if ((copy = end - offset) > 0) {
2744 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2746 if ((len -= copy) == 0)
2760 EXPORT_SYMBOL(skb_copy_bits);
2763 * Callback from splice_to_pipe(), if we need to release some pages
2764 * at the end of the spd in case we error'ed out in filling the pipe.
2766 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2768 put_page(spd->pages[i]);
2771 static struct page *linear_to_page(struct page *page, unsigned int *len,
2772 unsigned int *offset,
2775 struct page_frag *pfrag = sk_page_frag(sk);
2777 if (!sk_page_frag_refill(sk, pfrag))
2780 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2782 memcpy(page_address(pfrag->page) + pfrag->offset,
2783 page_address(page) + *offset, *len);
2784 *offset = pfrag->offset;
2785 pfrag->offset += *len;
2790 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2792 unsigned int offset)
2794 return spd->nr_pages &&
2795 spd->pages[spd->nr_pages - 1] == page &&
2796 (spd->partial[spd->nr_pages - 1].offset +
2797 spd->partial[spd->nr_pages - 1].len == offset);
2801 * Fill page/offset/length into spd, if it can hold more pages.
2803 static bool spd_fill_page(struct splice_pipe_desc *spd,
2804 struct pipe_inode_info *pipe, struct page *page,
2805 unsigned int *len, unsigned int offset,
2809 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2813 page = linear_to_page(page, len, &offset, sk);
2817 if (spd_can_coalesce(spd, page, offset)) {
2818 spd->partial[spd->nr_pages - 1].len += *len;
2822 spd->pages[spd->nr_pages] = page;
2823 spd->partial[spd->nr_pages].len = *len;
2824 spd->partial[spd->nr_pages].offset = offset;
2830 static bool __splice_segment(struct page *page, unsigned int poff,
2831 unsigned int plen, unsigned int *off,
2833 struct splice_pipe_desc *spd, bool linear,
2835 struct pipe_inode_info *pipe)
2840 /* skip this segment if already processed */
2846 /* ignore any bits we already processed */
2852 unsigned int flen = min(*len, plen);
2854 if (spd_fill_page(spd, pipe, page, &flen, poff,
2860 } while (*len && plen);
2866 * Map linear and fragment data from the skb to spd. It reports true if the
2867 * pipe is full or if we already spliced the requested length.
2869 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2870 unsigned int *offset, unsigned int *len,
2871 struct splice_pipe_desc *spd, struct sock *sk)
2874 struct sk_buff *iter;
2876 /* map the linear part :
2877 * If skb->head_frag is set, this 'linear' part is backed by a
2878 * fragment, and if the head is not shared with any clones then
2879 * we can avoid a copy since we own the head portion of this page.
2881 if (__splice_segment(virt_to_page(skb->data),
2882 (unsigned long) skb->data & (PAGE_SIZE - 1),
2885 skb_head_is_locked(skb),
2890 * then map the fragments
2892 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2893 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2895 if (__splice_segment(skb_frag_page(f),
2896 skb_frag_off(f), skb_frag_size(f),
2897 offset, len, spd, false, sk, pipe))
2901 skb_walk_frags(skb, iter) {
2902 if (*offset >= iter->len) {
2903 *offset -= iter->len;
2906 /* __skb_splice_bits() only fails if the output has no room
2907 * left, so no point in going over the frag_list for the error
2910 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2918 * Map data from the skb to a pipe. Should handle both the linear part,
2919 * the fragments, and the frag list.
2921 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2922 struct pipe_inode_info *pipe, unsigned int tlen,
2925 struct partial_page partial[MAX_SKB_FRAGS];
2926 struct page *pages[MAX_SKB_FRAGS];
2927 struct splice_pipe_desc spd = {
2930 .nr_pages_max = MAX_SKB_FRAGS,
2931 .ops = &nosteal_pipe_buf_ops,
2932 .spd_release = sock_spd_release,
2936 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2939 ret = splice_to_pipe(pipe, &spd);
2943 EXPORT_SYMBOL_GPL(skb_splice_bits);
2945 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2946 struct kvec *vec, size_t num, size_t size)
2948 struct socket *sock = sk->sk_socket;
2952 return kernel_sendmsg(sock, msg, vec, num, size);
2955 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2956 size_t size, int flags)
2958 struct socket *sock = sk->sk_socket;
2962 return kernel_sendpage(sock, page, offset, size, flags);
2965 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2966 struct kvec *vec, size_t num, size_t size);
2967 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2968 size_t size, int flags);
2969 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2970 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2972 unsigned int orig_len = len;
2973 struct sk_buff *head = skb;
2974 unsigned short fragidx;
2979 /* Deal with head data */
2980 while (offset < skb_headlen(skb) && len) {
2984 slen = min_t(int, len, skb_headlen(skb) - offset);
2985 kv.iov_base = skb->data + offset;
2987 memset(&msg, 0, sizeof(msg));
2988 msg.msg_flags = MSG_DONTWAIT;
2990 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2991 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2999 /* All the data was skb head? */
3003 /* Make offset relative to start of frags */
3004 offset -= skb_headlen(skb);
3006 /* Find where we are in frag list */
3007 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3008 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3010 if (offset < skb_frag_size(frag))
3013 offset -= skb_frag_size(frag);
3016 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3017 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3019 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
3022 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
3023 sendpage_unlocked, sk,
3024 skb_frag_page(frag),
3025 skb_frag_off(frag) + offset,
3026 slen, MSG_DONTWAIT);
3039 /* Process any frag lists */
3042 if (skb_has_frag_list(skb)) {
3043 skb = skb_shinfo(skb)->frag_list;
3046 } else if (skb->next) {
3053 return orig_len - len;
3056 return orig_len == len ? ret : orig_len - len;
3059 /* Send skb data on a socket. Socket must be locked. */
3060 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
3063 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
3064 kernel_sendpage_locked);
3066 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
3068 /* Send skb data on a socket. Socket must be unlocked. */
3069 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
3071 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
3076 * skb_store_bits - store bits from kernel buffer to skb
3077 * @skb: destination buffer
3078 * @offset: offset in destination
3079 * @from: source buffer
3080 * @len: number of bytes to copy
3082 * Copy the specified number of bytes from the source buffer to the
3083 * destination skb. This function handles all the messy bits of
3084 * traversing fragment lists and such.
3087 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
3089 int start = skb_headlen(skb);
3090 struct sk_buff *frag_iter;
3093 if (offset > (int)skb->len - len)
3096 if ((copy = start - offset) > 0) {
3099 skb_copy_to_linear_data_offset(skb, offset, from, copy);
3100 if ((len -= copy) == 0)
3106 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3107 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3110 WARN_ON(start > offset + len);
3112 end = start + skb_frag_size(frag);
3113 if ((copy = end - offset) > 0) {
3114 u32 p_off, p_len, copied;
3121 skb_frag_foreach_page(frag,
3122 skb_frag_off(frag) + offset - start,
3123 copy, p, p_off, p_len, copied) {
3124 vaddr = kmap_atomic(p);
3125 memcpy(vaddr + p_off, from + copied, p_len);
3126 kunmap_atomic(vaddr);
3129 if ((len -= copy) == 0)
3137 skb_walk_frags(skb, frag_iter) {
3140 WARN_ON(start > offset + len);
3142 end = start + frag_iter->len;
3143 if ((copy = end - offset) > 0) {
3146 if (skb_store_bits(frag_iter, offset - start,
3149 if ((len -= copy) == 0)
3162 EXPORT_SYMBOL(skb_store_bits);
3164 /* Checksum skb data. */
3165 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
3166 __wsum csum, const struct skb_checksum_ops *ops)
3168 int start = skb_headlen(skb);
3169 int i, copy = start - offset;
3170 struct sk_buff *frag_iter;
3173 /* Checksum header. */
3177 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3178 skb->data + offset, copy, csum);
3179 if ((len -= copy) == 0)
3185 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3187 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3189 WARN_ON(start > offset + len);
3191 end = start + skb_frag_size(frag);
3192 if ((copy = end - offset) > 0) {
3193 u32 p_off, p_len, copied;
3201 skb_frag_foreach_page(frag,
3202 skb_frag_off(frag) + offset - start,
3203 copy, p, p_off, p_len, copied) {
3204 vaddr = kmap_atomic(p);
3205 csum2 = INDIRECT_CALL_1(ops->update,
3207 vaddr + p_off, p_len, 0);
3208 kunmap_atomic(vaddr);
3209 csum = INDIRECT_CALL_1(ops->combine,
3210 csum_block_add_ext, csum,
3222 skb_walk_frags(skb, frag_iter) {
3225 WARN_ON(start > offset + len);
3227 end = start + frag_iter->len;
3228 if ((copy = end - offset) > 0) {
3232 csum2 = __skb_checksum(frag_iter, offset - start,
3234 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3235 csum, csum2, pos, copy);
3236 if ((len -= copy) == 0)
3247 EXPORT_SYMBOL(__skb_checksum);
3249 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3250 int len, __wsum csum)
3252 const struct skb_checksum_ops ops = {
3253 .update = csum_partial_ext,
3254 .combine = csum_block_add_ext,
3257 return __skb_checksum(skb, offset, len, csum, &ops);
3259 EXPORT_SYMBOL(skb_checksum);
3261 /* Both of above in one bottle. */
3263 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3266 int start = skb_headlen(skb);
3267 int i, copy = start - offset;
3268 struct sk_buff *frag_iter;
3276 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3278 if ((len -= copy) == 0)
3285 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3288 WARN_ON(start > offset + len);
3290 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3291 if ((copy = end - offset) > 0) {
3292 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3293 u32 p_off, p_len, copied;
3301 skb_frag_foreach_page(frag,
3302 skb_frag_off(frag) + offset - start,
3303 copy, p, p_off, p_len, copied) {
3304 vaddr = kmap_atomic(p);
3305 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3308 kunmap_atomic(vaddr);
3309 csum = csum_block_add(csum, csum2, pos);
3321 skb_walk_frags(skb, frag_iter) {
3325 WARN_ON(start > offset + len);
3327 end = start + frag_iter->len;
3328 if ((copy = end - offset) > 0) {
3331 csum2 = skb_copy_and_csum_bits(frag_iter,
3334 csum = csum_block_add(csum, csum2, pos);
3335 if ((len -= copy) == 0)
3346 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3348 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3352 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3353 /* See comments in __skb_checksum_complete(). */
3355 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3356 !skb->csum_complete_sw)
3357 netdev_rx_csum_fault(skb->dev, skb);
3359 if (!skb_shared(skb))
3360 skb->csum_valid = !sum;
3363 EXPORT_SYMBOL(__skb_checksum_complete_head);
3365 /* This function assumes skb->csum already holds pseudo header's checksum,
3366 * which has been changed from the hardware checksum, for example, by
3367 * __skb_checksum_validate_complete(). And, the original skb->csum must
3368 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3370 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3371 * zero. The new checksum is stored back into skb->csum unless the skb is
3374 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3379 csum = skb_checksum(skb, 0, skb->len, 0);
3381 sum = csum_fold(csum_add(skb->csum, csum));
3382 /* This check is inverted, because we already knew the hardware
3383 * checksum is invalid before calling this function. So, if the
3384 * re-computed checksum is valid instead, then we have a mismatch
3385 * between the original skb->csum and skb_checksum(). This means either
3386 * the original hardware checksum is incorrect or we screw up skb->csum
3387 * when moving skb->data around.
3390 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3391 !skb->csum_complete_sw)
3392 netdev_rx_csum_fault(skb->dev, skb);
3395 if (!skb_shared(skb)) {
3396 /* Save full packet checksum */
3398 skb->ip_summed = CHECKSUM_COMPLETE;
3399 skb->csum_complete_sw = 1;
3400 skb->csum_valid = !sum;
3405 EXPORT_SYMBOL(__skb_checksum_complete);
3407 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3409 net_warn_ratelimited(
3410 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3415 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3416 int offset, int len)
3418 net_warn_ratelimited(
3419 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3424 static const struct skb_checksum_ops default_crc32c_ops = {
3425 .update = warn_crc32c_csum_update,
3426 .combine = warn_crc32c_csum_combine,
3429 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3430 &default_crc32c_ops;
3431 EXPORT_SYMBOL(crc32c_csum_stub);
3434 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3435 * @from: source buffer
3437 * Calculates the amount of linear headroom needed in the 'to' skb passed
3438 * into skb_zerocopy().
3441 skb_zerocopy_headlen(const struct sk_buff *from)
3443 unsigned int hlen = 0;
3445 if (!from->head_frag ||
3446 skb_headlen(from) < L1_CACHE_BYTES ||
3447 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3448 hlen = skb_headlen(from);
3453 if (skb_has_frag_list(from))
3458 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3461 * skb_zerocopy - Zero copy skb to skb
3462 * @to: destination buffer
3463 * @from: source buffer
3464 * @len: number of bytes to copy from source buffer
3465 * @hlen: size of linear headroom in destination buffer
3467 * Copies up to `len` bytes from `from` to `to` by creating references
3468 * to the frags in the source buffer.
3470 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3471 * headroom in the `to` buffer.
3474 * 0: everything is OK
3475 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3476 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3479 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3482 int plen = 0; /* length of skb->head fragment */
3485 unsigned int offset;
3487 BUG_ON(!from->head_frag && !hlen);
3489 /* dont bother with small payloads */
3490 if (len <= skb_tailroom(to))
3491 return skb_copy_bits(from, 0, skb_put(to, len), len);
3494 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3499 plen = min_t(int, skb_headlen(from), len);
3501 page = virt_to_head_page(from->head);
3502 offset = from->data - (unsigned char *)page_address(page);
3503 __skb_fill_page_desc(to, 0, page, offset, plen);
3510 skb_len_add(to, len + plen);
3512 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3516 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3518 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3523 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3524 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3526 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3528 skb_frag_ref(to, j);
3531 skb_shinfo(to)->nr_frags = j;
3535 EXPORT_SYMBOL_GPL(skb_zerocopy);
3537 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3542 if (skb->ip_summed == CHECKSUM_PARTIAL)
3543 csstart = skb_checksum_start_offset(skb);
3545 csstart = skb_headlen(skb);
3547 BUG_ON(csstart > skb_headlen(skb));
3549 skb_copy_from_linear_data(skb, to, csstart);
3552 if (csstart != skb->len)
3553 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3554 skb->len - csstart);
3556 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3557 long csstuff = csstart + skb->csum_offset;
3559 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3562 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3565 * skb_dequeue - remove from the head of the queue
3566 * @list: list to dequeue from
3568 * Remove the head of the list. The list lock is taken so the function
3569 * may be used safely with other locking list functions. The head item is
3570 * returned or %NULL if the list is empty.
3573 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3575 unsigned long flags;
3576 struct sk_buff *result;
3578 spin_lock_irqsave(&list->lock, flags);
3579 result = __skb_dequeue(list);
3580 spin_unlock_irqrestore(&list->lock, flags);
3583 EXPORT_SYMBOL(skb_dequeue);
3586 * skb_dequeue_tail - remove from the tail of the queue
3587 * @list: list to dequeue from
3589 * Remove the tail of the list. The list lock is taken so the function
3590 * may be used safely with other locking list functions. The tail item is
3591 * returned or %NULL if the list is empty.
3593 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3595 unsigned long flags;
3596 struct sk_buff *result;
3598 spin_lock_irqsave(&list->lock, flags);
3599 result = __skb_dequeue_tail(list);
3600 spin_unlock_irqrestore(&list->lock, flags);
3603 EXPORT_SYMBOL(skb_dequeue_tail);
3606 * skb_queue_purge - empty a list
3607 * @list: list to empty
3609 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3610 * the list and one reference dropped. This function takes the list
3611 * lock and is atomic with respect to other list locking functions.
3613 void skb_queue_purge(struct sk_buff_head *list)
3615 struct sk_buff *skb;
3616 while ((skb = skb_dequeue(list)) != NULL)
3619 EXPORT_SYMBOL(skb_queue_purge);
3622 * skb_rbtree_purge - empty a skb rbtree
3623 * @root: root of the rbtree to empty
3624 * Return value: the sum of truesizes of all purged skbs.
3626 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3627 * the list and one reference dropped. This function does not take
3628 * any lock. Synchronization should be handled by the caller (e.g., TCP
3629 * out-of-order queue is protected by the socket lock).
3631 unsigned int skb_rbtree_purge(struct rb_root *root)
3633 struct rb_node *p = rb_first(root);
3634 unsigned int sum = 0;
3637 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3640 rb_erase(&skb->rbnode, root);
3641 sum += skb->truesize;
3648 * skb_queue_head - queue a buffer at the list head
3649 * @list: list to use
3650 * @newsk: buffer to queue
3652 * Queue a buffer at the start of the list. This function takes the
3653 * list lock and can be used safely with other locking &sk_buff functions
3656 * A buffer cannot be placed on two lists at the same time.
3658 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3660 unsigned long flags;
3662 spin_lock_irqsave(&list->lock, flags);
3663 __skb_queue_head(list, newsk);
3664 spin_unlock_irqrestore(&list->lock, flags);
3666 EXPORT_SYMBOL(skb_queue_head);
3669 * skb_queue_tail - queue a buffer at the list tail
3670 * @list: list to use
3671 * @newsk: buffer to queue
3673 * Queue a buffer at the tail of the list. This function takes the
3674 * list lock and can be used safely with other locking &sk_buff functions
3677 * A buffer cannot be placed on two lists at the same time.
3679 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3681 unsigned long flags;
3683 spin_lock_irqsave(&list->lock, flags);
3684 __skb_queue_tail(list, newsk);
3685 spin_unlock_irqrestore(&list->lock, flags);
3687 EXPORT_SYMBOL(skb_queue_tail);
3690 * skb_unlink - remove a buffer from a list
3691 * @skb: buffer to remove
3692 * @list: list to use
3694 * Remove a packet from a list. The list locks are taken and this
3695 * function is atomic with respect to other list locked calls
3697 * You must know what list the SKB is on.
3699 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3701 unsigned long flags;
3703 spin_lock_irqsave(&list->lock, flags);
3704 __skb_unlink(skb, list);
3705 spin_unlock_irqrestore(&list->lock, flags);
3707 EXPORT_SYMBOL(skb_unlink);
3710 * skb_append - append a buffer
3711 * @old: buffer to insert after
3712 * @newsk: buffer to insert
3713 * @list: list to use
3715 * Place a packet after a given packet in a list. The list locks are taken
3716 * and this function is atomic with respect to other list locked calls.
3717 * A buffer cannot be placed on two lists at the same time.
3719 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3721 unsigned long flags;
3723 spin_lock_irqsave(&list->lock, flags);
3724 __skb_queue_after(list, old, newsk);
3725 spin_unlock_irqrestore(&list->lock, flags);
3727 EXPORT_SYMBOL(skb_append);
3729 static inline void skb_split_inside_header(struct sk_buff *skb,
3730 struct sk_buff* skb1,
3731 const u32 len, const int pos)
3735 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3737 /* And move data appendix as is. */
3738 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3739 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3741 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3742 skb_shinfo(skb)->nr_frags = 0;
3743 skb1->data_len = skb->data_len;
3744 skb1->len += skb1->data_len;
3747 skb_set_tail_pointer(skb, len);
3750 static inline void skb_split_no_header(struct sk_buff *skb,
3751 struct sk_buff* skb1,
3752 const u32 len, int pos)
3755 const int nfrags = skb_shinfo(skb)->nr_frags;
3757 skb_shinfo(skb)->nr_frags = 0;
3758 skb1->len = skb1->data_len = skb->len - len;
3760 skb->data_len = len - pos;
3762 for (i = 0; i < nfrags; i++) {
3763 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3765 if (pos + size > len) {
3766 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3770 * We have two variants in this case:
3771 * 1. Move all the frag to the second
3772 * part, if it is possible. F.e.
3773 * this approach is mandatory for TUX,
3774 * where splitting is expensive.
3775 * 2. Split is accurately. We make this.
3777 skb_frag_ref(skb, i);
3778 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3779 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3780 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3781 skb_shinfo(skb)->nr_frags++;
3785 skb_shinfo(skb)->nr_frags++;
3788 skb_shinfo(skb1)->nr_frags = k;
3792 * skb_split - Split fragmented skb to two parts at length len.
3793 * @skb: the buffer to split
3794 * @skb1: the buffer to receive the second part
3795 * @len: new length for skb
3797 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3799 int pos = skb_headlen(skb);
3800 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3802 skb_zcopy_downgrade_managed(skb);
3804 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3805 skb_zerocopy_clone(skb1, skb, 0);
3806 if (len < pos) /* Split line is inside header. */
3807 skb_split_inside_header(skb, skb1, len, pos);
3808 else /* Second chunk has no header, nothing to copy. */
3809 skb_split_no_header(skb, skb1, len, pos);
3811 EXPORT_SYMBOL(skb_split);
3813 /* Shifting from/to a cloned skb is a no-go.
3815 * Caller cannot keep skb_shinfo related pointers past calling here!
3817 static int skb_prepare_for_shift(struct sk_buff *skb)
3819 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3823 * skb_shift - Shifts paged data partially from skb to another
3824 * @tgt: buffer into which tail data gets added
3825 * @skb: buffer from which the paged data comes from
3826 * @shiftlen: shift up to this many bytes
3828 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3829 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3830 * It's up to caller to free skb if everything was shifted.
3832 * If @tgt runs out of frags, the whole operation is aborted.
3834 * Skb cannot include anything else but paged data while tgt is allowed
3835 * to have non-paged data as well.
3837 * TODO: full sized shift could be optimized but that would need
3838 * specialized skb free'er to handle frags without up-to-date nr_frags.
3840 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3842 int from, to, merge, todo;
3843 skb_frag_t *fragfrom, *fragto;
3845 BUG_ON(shiftlen > skb->len);
3847 if (skb_headlen(skb))
3849 if (skb_zcopy(tgt) || skb_zcopy(skb))
3854 to = skb_shinfo(tgt)->nr_frags;
3855 fragfrom = &skb_shinfo(skb)->frags[from];
3857 /* Actual merge is delayed until the point when we know we can
3858 * commit all, so that we don't have to undo partial changes
3861 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3862 skb_frag_off(fragfrom))) {
3867 todo -= skb_frag_size(fragfrom);
3869 if (skb_prepare_for_shift(skb) ||
3870 skb_prepare_for_shift(tgt))
3873 /* All previous frag pointers might be stale! */
3874 fragfrom = &skb_shinfo(skb)->frags[from];
3875 fragto = &skb_shinfo(tgt)->frags[merge];
3877 skb_frag_size_add(fragto, shiftlen);
3878 skb_frag_size_sub(fragfrom, shiftlen);
3879 skb_frag_off_add(fragfrom, shiftlen);
3887 /* Skip full, not-fitting skb to avoid expensive operations */
3888 if ((shiftlen == skb->len) &&
3889 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3892 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3895 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3896 if (to == MAX_SKB_FRAGS)
3899 fragfrom = &skb_shinfo(skb)->frags[from];
3900 fragto = &skb_shinfo(tgt)->frags[to];
3902 if (todo >= skb_frag_size(fragfrom)) {
3903 *fragto = *fragfrom;
3904 todo -= skb_frag_size(fragfrom);
3909 __skb_frag_ref(fragfrom);
3910 skb_frag_page_copy(fragto, fragfrom);
3911 skb_frag_off_copy(fragto, fragfrom);
3912 skb_frag_size_set(fragto, todo);
3914 skb_frag_off_add(fragfrom, todo);
3915 skb_frag_size_sub(fragfrom, todo);
3923 /* Ready to "commit" this state change to tgt */
3924 skb_shinfo(tgt)->nr_frags = to;
3927 fragfrom = &skb_shinfo(skb)->frags[0];
3928 fragto = &skb_shinfo(tgt)->frags[merge];
3930 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3931 __skb_frag_unref(fragfrom, skb->pp_recycle);
3934 /* Reposition in the original skb */
3936 while (from < skb_shinfo(skb)->nr_frags)
3937 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3938 skb_shinfo(skb)->nr_frags = to;
3940 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3943 /* Most likely the tgt won't ever need its checksum anymore, skb on
3944 * the other hand might need it if it needs to be resent
3946 tgt->ip_summed = CHECKSUM_PARTIAL;
3947 skb->ip_summed = CHECKSUM_PARTIAL;
3949 skb_len_add(skb, -shiftlen);
3950 skb_len_add(tgt, shiftlen);
3956 * skb_prepare_seq_read - Prepare a sequential read of skb data
3957 * @skb: the buffer to read
3958 * @from: lower offset of data to be read
3959 * @to: upper offset of data to be read
3960 * @st: state variable
3962 * Initializes the specified state variable. Must be called before
3963 * invoking skb_seq_read() for the first time.
3965 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3966 unsigned int to, struct skb_seq_state *st)
3968 st->lower_offset = from;
3969 st->upper_offset = to;
3970 st->root_skb = st->cur_skb = skb;
3971 st->frag_idx = st->stepped_offset = 0;
3972 st->frag_data = NULL;
3975 EXPORT_SYMBOL(skb_prepare_seq_read);
3978 * skb_seq_read - Sequentially read skb data
3979 * @consumed: number of bytes consumed by the caller so far
3980 * @data: destination pointer for data to be returned
3981 * @st: state variable
3983 * Reads a block of skb data at @consumed relative to the
3984 * lower offset specified to skb_prepare_seq_read(). Assigns
3985 * the head of the data block to @data and returns the length
3986 * of the block or 0 if the end of the skb data or the upper
3987 * offset has been reached.
3989 * The caller is not required to consume all of the data
3990 * returned, i.e. @consumed is typically set to the number
3991 * of bytes already consumed and the next call to
3992 * skb_seq_read() will return the remaining part of the block.
3994 * Note 1: The size of each block of data returned can be arbitrary,
3995 * this limitation is the cost for zerocopy sequential
3996 * reads of potentially non linear data.
3998 * Note 2: Fragment lists within fragments are not implemented
3999 * at the moment, state->root_skb could be replaced with
4000 * a stack for this purpose.
4002 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
4003 struct skb_seq_state *st)
4005 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
4008 if (unlikely(abs_offset >= st->upper_offset)) {
4009 if (st->frag_data) {
4010 kunmap_atomic(st->frag_data);
4011 st->frag_data = NULL;
4017 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
4019 if (abs_offset < block_limit && !st->frag_data) {
4020 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
4021 return block_limit - abs_offset;
4024 if (st->frag_idx == 0 && !st->frag_data)
4025 st->stepped_offset += skb_headlen(st->cur_skb);
4027 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
4028 unsigned int pg_idx, pg_off, pg_sz;
4030 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
4033 pg_off = skb_frag_off(frag);
4034 pg_sz = skb_frag_size(frag);
4036 if (skb_frag_must_loop(skb_frag_page(frag))) {
4037 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
4038 pg_off = offset_in_page(pg_off + st->frag_off);
4039 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
4040 PAGE_SIZE - pg_off);
4043 block_limit = pg_sz + st->stepped_offset;
4044 if (abs_offset < block_limit) {
4046 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
4048 *data = (u8 *)st->frag_data + pg_off +
4049 (abs_offset - st->stepped_offset);
4051 return block_limit - abs_offset;
4054 if (st->frag_data) {
4055 kunmap_atomic(st->frag_data);
4056 st->frag_data = NULL;
4059 st->stepped_offset += pg_sz;
4060 st->frag_off += pg_sz;
4061 if (st->frag_off == skb_frag_size(frag)) {
4067 if (st->frag_data) {
4068 kunmap_atomic(st->frag_data);
4069 st->frag_data = NULL;
4072 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
4073 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
4076 } else if (st->cur_skb->next) {
4077 st->cur_skb = st->cur_skb->next;
4084 EXPORT_SYMBOL(skb_seq_read);
4087 * skb_abort_seq_read - Abort a sequential read of skb data
4088 * @st: state variable
4090 * Must be called if skb_seq_read() was not called until it
4093 void skb_abort_seq_read(struct skb_seq_state *st)
4096 kunmap_atomic(st->frag_data);
4098 EXPORT_SYMBOL(skb_abort_seq_read);
4100 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
4102 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
4103 struct ts_config *conf,
4104 struct ts_state *state)
4106 return skb_seq_read(offset, text, TS_SKB_CB(state));
4109 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
4111 skb_abort_seq_read(TS_SKB_CB(state));
4115 * skb_find_text - Find a text pattern in skb data
4116 * @skb: the buffer to look in
4117 * @from: search offset
4119 * @config: textsearch configuration
4121 * Finds a pattern in the skb data according to the specified
4122 * textsearch configuration. Use textsearch_next() to retrieve
4123 * subsequent occurrences of the pattern. Returns the offset
4124 * to the first occurrence or UINT_MAX if no match was found.
4126 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4127 unsigned int to, struct ts_config *config)
4129 struct ts_state state;
4132 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4134 config->get_next_block = skb_ts_get_next_block;
4135 config->finish = skb_ts_finish;
4137 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
4139 ret = textsearch_find(config, &state);
4140 return (ret <= to - from ? ret : UINT_MAX);
4142 EXPORT_SYMBOL(skb_find_text);
4144 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4145 int offset, size_t size)
4147 int i = skb_shinfo(skb)->nr_frags;
4149 if (skb_can_coalesce(skb, i, page, offset)) {
4150 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4151 } else if (i < MAX_SKB_FRAGS) {
4152 skb_zcopy_downgrade_managed(skb);
4154 skb_fill_page_desc_noacc(skb, i, page, offset, size);
4161 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4164 * skb_pull_rcsum - pull skb and update receive checksum
4165 * @skb: buffer to update
4166 * @len: length of data pulled
4168 * This function performs an skb_pull on the packet and updates
4169 * the CHECKSUM_COMPLETE checksum. It should be used on
4170 * receive path processing instead of skb_pull unless you know
4171 * that the checksum difference is zero (e.g., a valid IP header)
4172 * or you are setting ip_summed to CHECKSUM_NONE.
4174 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4176 unsigned char *data = skb->data;
4178 BUG_ON(len > skb->len);
4179 __skb_pull(skb, len);
4180 skb_postpull_rcsum(skb, data, len);
4183 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4185 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4187 skb_frag_t head_frag;
4190 page = virt_to_head_page(frag_skb->head);
4191 __skb_frag_set_page(&head_frag, page);
4192 skb_frag_off_set(&head_frag, frag_skb->data -
4193 (unsigned char *)page_address(page));
4194 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
4198 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4199 netdev_features_t features,
4200 unsigned int offset)
4202 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4203 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4204 unsigned int delta_truesize = 0;
4205 unsigned int delta_len = 0;
4206 struct sk_buff *tail = NULL;
4207 struct sk_buff *nskb, *tmp;
4210 skb_push(skb, -skb_network_offset(skb) + offset);
4212 skb_shinfo(skb)->frag_list = NULL;
4216 list_skb = list_skb->next;
4219 delta_truesize += nskb->truesize;
4220 if (skb_shared(nskb)) {
4221 tmp = skb_clone(nskb, GFP_ATOMIC);
4225 err = skb_unclone(nskb, GFP_ATOMIC);
4236 if (unlikely(err)) {
4237 nskb->next = list_skb;
4243 delta_len += nskb->len;
4245 skb_push(nskb, -skb_network_offset(nskb) + offset);
4247 skb_release_head_state(nskb);
4248 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4249 __copy_skb_header(nskb, skb);
4251 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4252 nskb->transport_header += len_diff;
4253 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4254 nskb->data - tnl_hlen,
4257 if (skb_needs_linearize(nskb, features) &&
4258 __skb_linearize(nskb))
4262 skb->truesize = skb->truesize - delta_truesize;
4263 skb->data_len = skb->data_len - delta_len;
4264 skb->len = skb->len - delta_len;
4270 if (skb_needs_linearize(skb, features) &&
4271 __skb_linearize(skb))
4279 kfree_skb_list(skb->next);
4281 return ERR_PTR(-ENOMEM);
4283 EXPORT_SYMBOL_GPL(skb_segment_list);
4286 * skb_segment - Perform protocol segmentation on skb.
4287 * @head_skb: buffer to segment
4288 * @features: features for the output path (see dev->features)
4290 * This function performs segmentation on the given skb. It returns
4291 * a pointer to the first in a list of new skbs for the segments.
4292 * In case of error it returns ERR_PTR(err).
4294 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4295 netdev_features_t features)
4297 struct sk_buff *segs = NULL;
4298 struct sk_buff *tail = NULL;
4299 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4300 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4301 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4302 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4303 struct sk_buff *frag_skb = head_skb;
4304 unsigned int offset = doffset;
4305 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4306 unsigned int partial_segs = 0;
4307 unsigned int headroom;
4308 unsigned int len = head_skb->len;
4311 int nfrags = skb_shinfo(head_skb)->nr_frags;
4316 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4317 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4318 struct sk_buff *check_skb;
4320 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4321 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4322 /* gso_size is untrusted, and we have a frag_list with
4323 * a linear non head_frag item.
4325 * If head_skb's headlen does not fit requested gso_size,
4326 * it means that the frag_list members do NOT terminate
4327 * on exact gso_size boundaries. Hence we cannot perform
4328 * skb_frag_t page sharing. Therefore we must fallback to
4329 * copying the frag_list skbs; we do so by disabling SG.
4331 features &= ~NETIF_F_SG;
4337 __skb_push(head_skb, doffset);
4338 proto = skb_network_protocol(head_skb, NULL);
4339 if (unlikely(!proto))
4340 return ERR_PTR(-EINVAL);
4342 sg = !!(features & NETIF_F_SG);
4343 csum = !!can_checksum_protocol(features, proto);
4345 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4346 if (!(features & NETIF_F_GSO_PARTIAL)) {
4347 struct sk_buff *iter;
4348 unsigned int frag_len;
4351 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4354 /* If we get here then all the required
4355 * GSO features except frag_list are supported.
4356 * Try to split the SKB to multiple GSO SKBs
4357 * with no frag_list.
4358 * Currently we can do that only when the buffers don't
4359 * have a linear part and all the buffers except
4360 * the last are of the same length.
4362 frag_len = list_skb->len;
4363 skb_walk_frags(head_skb, iter) {
4364 if (frag_len != iter->len && iter->next)
4366 if (skb_headlen(iter) && !iter->head_frag)
4372 if (len != frag_len)
4376 /* GSO partial only requires that we trim off any excess that
4377 * doesn't fit into an MSS sized block, so take care of that
4380 partial_segs = len / mss;
4381 if (partial_segs > 1)
4382 mss *= partial_segs;
4388 headroom = skb_headroom(head_skb);
4389 pos = skb_headlen(head_skb);
4392 struct sk_buff *nskb;
4393 skb_frag_t *nskb_frag;
4397 if (unlikely(mss == GSO_BY_FRAGS)) {
4398 len = list_skb->len;
4400 len = head_skb->len - offset;
4405 hsize = skb_headlen(head_skb) - offset;
4407 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4408 (skb_headlen(list_skb) == len || sg)) {
4409 BUG_ON(skb_headlen(list_skb) > len);
4412 nfrags = skb_shinfo(list_skb)->nr_frags;
4413 frag = skb_shinfo(list_skb)->frags;
4414 frag_skb = list_skb;
4415 pos += skb_headlen(list_skb);
4417 while (pos < offset + len) {
4418 BUG_ON(i >= nfrags);
4420 size = skb_frag_size(frag);
4421 if (pos + size > offset + len)
4429 nskb = skb_clone(list_skb, GFP_ATOMIC);
4430 list_skb = list_skb->next;
4432 if (unlikely(!nskb))
4435 if (unlikely(pskb_trim(nskb, len))) {
4440 hsize = skb_end_offset(nskb);
4441 if (skb_cow_head(nskb, doffset + headroom)) {
4446 nskb->truesize += skb_end_offset(nskb) - hsize;
4447 skb_release_head_state(nskb);
4448 __skb_push(nskb, doffset);
4452 if (hsize > len || !sg)
4455 nskb = __alloc_skb(hsize + doffset + headroom,
4456 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4459 if (unlikely(!nskb))
4462 skb_reserve(nskb, headroom);
4463 __skb_put(nskb, doffset);
4472 __copy_skb_header(nskb, head_skb);
4474 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4475 skb_reset_mac_len(nskb);
4477 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4478 nskb->data - tnl_hlen,
4479 doffset + tnl_hlen);
4481 if (nskb->len == len + doffset)
4482 goto perform_csum_check;
4486 if (!nskb->remcsum_offload)
4487 nskb->ip_summed = CHECKSUM_NONE;
4488 SKB_GSO_CB(nskb)->csum =
4489 skb_copy_and_csum_bits(head_skb, offset,
4493 SKB_GSO_CB(nskb)->csum_start =
4494 skb_headroom(nskb) + doffset;
4496 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4502 nskb_frag = skb_shinfo(nskb)->frags;
4504 skb_copy_from_linear_data_offset(head_skb, offset,
4505 skb_put(nskb, hsize), hsize);
4507 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4510 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4511 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4514 while (pos < offset + len) {
4517 nfrags = skb_shinfo(list_skb)->nr_frags;
4518 frag = skb_shinfo(list_skb)->frags;
4519 frag_skb = list_skb;
4520 if (!skb_headlen(list_skb)) {
4523 BUG_ON(!list_skb->head_frag);
4525 /* to make room for head_frag. */
4529 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4530 skb_zerocopy_clone(nskb, frag_skb,
4534 list_skb = list_skb->next;
4537 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4539 net_warn_ratelimited(
4540 "skb_segment: too many frags: %u %u\n",
4546 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4547 __skb_frag_ref(nskb_frag);
4548 size = skb_frag_size(nskb_frag);
4551 skb_frag_off_add(nskb_frag, offset - pos);
4552 skb_frag_size_sub(nskb_frag, offset - pos);
4555 skb_shinfo(nskb)->nr_frags++;
4557 if (pos + size <= offset + len) {
4562 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4570 nskb->data_len = len - hsize;
4571 nskb->len += nskb->data_len;
4572 nskb->truesize += nskb->data_len;
4576 if (skb_has_shared_frag(nskb) &&
4577 __skb_linearize(nskb))
4580 if (!nskb->remcsum_offload)
4581 nskb->ip_summed = CHECKSUM_NONE;
4582 SKB_GSO_CB(nskb)->csum =
4583 skb_checksum(nskb, doffset,
4584 nskb->len - doffset, 0);
4585 SKB_GSO_CB(nskb)->csum_start =
4586 skb_headroom(nskb) + doffset;
4588 } while ((offset += len) < head_skb->len);
4590 /* Some callers want to get the end of the list.
4591 * Put it in segs->prev to avoid walking the list.
4592 * (see validate_xmit_skb_list() for example)
4597 struct sk_buff *iter;
4598 int type = skb_shinfo(head_skb)->gso_type;
4599 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4601 /* Update type to add partial and then remove dodgy if set */
4602 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4603 type &= ~SKB_GSO_DODGY;
4605 /* Update GSO info and prepare to start updating headers on
4606 * our way back down the stack of protocols.
4608 for (iter = segs; iter; iter = iter->next) {
4609 skb_shinfo(iter)->gso_size = gso_size;
4610 skb_shinfo(iter)->gso_segs = partial_segs;
4611 skb_shinfo(iter)->gso_type = type;
4612 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4615 if (tail->len - doffset <= gso_size)
4616 skb_shinfo(tail)->gso_size = 0;
4617 else if (tail != segs)
4618 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4621 /* Following permits correct backpressure, for protocols
4622 * using skb_set_owner_w().
4623 * Idea is to tranfert ownership from head_skb to last segment.
4625 if (head_skb->destructor == sock_wfree) {
4626 swap(tail->truesize, head_skb->truesize);
4627 swap(tail->destructor, head_skb->destructor);
4628 swap(tail->sk, head_skb->sk);
4633 kfree_skb_list(segs);
4634 return ERR_PTR(err);
4636 EXPORT_SYMBOL_GPL(skb_segment);
4638 #ifdef CONFIG_SKB_EXTENSIONS
4639 #define SKB_EXT_ALIGN_VALUE 8
4640 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4642 static const u8 skb_ext_type_len[] = {
4643 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4644 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4647 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4649 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4650 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4652 #if IS_ENABLED(CONFIG_MPTCP)
4653 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4655 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4656 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4660 static __always_inline unsigned int skb_ext_total_length(void)
4662 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4663 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4664 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4667 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4669 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4670 skb_ext_type_len[TC_SKB_EXT] +
4672 #if IS_ENABLED(CONFIG_MPTCP)
4673 skb_ext_type_len[SKB_EXT_MPTCP] +
4675 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4676 skb_ext_type_len[SKB_EXT_MCTP] +
4681 static void skb_extensions_init(void)
4683 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4684 BUILD_BUG_ON(skb_ext_total_length() > 255);
4686 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4687 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4689 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4693 static void skb_extensions_init(void) {}
4696 void __init skb_init(void)
4698 skbuff_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4699 sizeof(struct sk_buff),
4701 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4702 offsetof(struct sk_buff, cb),
4703 sizeof_field(struct sk_buff, cb),
4705 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4706 sizeof(struct sk_buff_fclones),
4708 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4710 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
4711 /* usercopy should only access first SKB_SMALL_HEAD_HEADROOM bytes.
4712 * struct skb_shared_info is located at the end of skb->head,
4713 * and should not be copied to/from user.
4715 skb_small_head_cache = kmem_cache_create_usercopy("skbuff_small_head",
4716 SKB_SMALL_HEAD_CACHE_SIZE,
4718 SLAB_HWCACHE_ALIGN | SLAB_PANIC,
4720 SKB_SMALL_HEAD_HEADROOM,
4723 skb_extensions_init();
4727 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4728 unsigned int recursion_level)
4730 int start = skb_headlen(skb);
4731 int i, copy = start - offset;
4732 struct sk_buff *frag_iter;
4735 if (unlikely(recursion_level >= 24))
4741 sg_set_buf(sg, skb->data + offset, copy);
4743 if ((len -= copy) == 0)
4748 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4751 WARN_ON(start > offset + len);
4753 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4754 if ((copy = end - offset) > 0) {
4755 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4756 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4761 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4762 skb_frag_off(frag) + offset - start);
4771 skb_walk_frags(skb, frag_iter) {
4774 WARN_ON(start > offset + len);
4776 end = start + frag_iter->len;
4777 if ((copy = end - offset) > 0) {
4778 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4783 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4784 copy, recursion_level + 1);
4785 if (unlikely(ret < 0))
4788 if ((len -= copy) == 0)
4799 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4800 * @skb: Socket buffer containing the buffers to be mapped
4801 * @sg: The scatter-gather list to map into
4802 * @offset: The offset into the buffer's contents to start mapping
4803 * @len: Length of buffer space to be mapped
4805 * Fill the specified scatter-gather list with mappings/pointers into a
4806 * region of the buffer space attached to a socket buffer. Returns either
4807 * the number of scatterlist items used, or -EMSGSIZE if the contents
4810 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4812 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4817 sg_mark_end(&sg[nsg - 1]);
4821 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4823 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4824 * sglist without mark the sg which contain last skb data as the end.
4825 * So the caller can mannipulate sg list as will when padding new data after
4826 * the first call without calling sg_unmark_end to expend sg list.
4828 * Scenario to use skb_to_sgvec_nomark:
4830 * 2. skb_to_sgvec_nomark(payload1)
4831 * 3. skb_to_sgvec_nomark(payload2)
4833 * This is equivalent to:
4835 * 2. skb_to_sgvec(payload1)
4837 * 4. skb_to_sgvec(payload2)
4839 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4840 * is more preferable.
4842 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4843 int offset, int len)
4845 return __skb_to_sgvec(skb, sg, offset, len, 0);
4847 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4852 * skb_cow_data - Check that a socket buffer's data buffers are writable
4853 * @skb: The socket buffer to check.
4854 * @tailbits: Amount of trailing space to be added
4855 * @trailer: Returned pointer to the skb where the @tailbits space begins
4857 * Make sure that the data buffers attached to a socket buffer are
4858 * writable. If they are not, private copies are made of the data buffers
4859 * and the socket buffer is set to use these instead.
4861 * If @tailbits is given, make sure that there is space to write @tailbits
4862 * bytes of data beyond current end of socket buffer. @trailer will be
4863 * set to point to the skb in which this space begins.
4865 * The number of scatterlist elements required to completely map the
4866 * COW'd and extended socket buffer will be returned.
4868 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4872 struct sk_buff *skb1, **skb_p;
4874 /* If skb is cloned or its head is paged, reallocate
4875 * head pulling out all the pages (pages are considered not writable
4876 * at the moment even if they are anonymous).
4878 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4879 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4882 /* Easy case. Most of packets will go this way. */
4883 if (!skb_has_frag_list(skb)) {
4884 /* A little of trouble, not enough of space for trailer.
4885 * This should not happen, when stack is tuned to generate
4886 * good frames. OK, on miss we reallocate and reserve even more
4887 * space, 128 bytes is fair. */
4889 if (skb_tailroom(skb) < tailbits &&
4890 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4898 /* Misery. We are in troubles, going to mincer fragments... */
4901 skb_p = &skb_shinfo(skb)->frag_list;
4904 while ((skb1 = *skb_p) != NULL) {
4907 /* The fragment is partially pulled by someone,
4908 * this can happen on input. Copy it and everything
4911 if (skb_shared(skb1))
4914 /* If the skb is the last, worry about trailer. */
4916 if (skb1->next == NULL && tailbits) {
4917 if (skb_shinfo(skb1)->nr_frags ||
4918 skb_has_frag_list(skb1) ||
4919 skb_tailroom(skb1) < tailbits)
4920 ntail = tailbits + 128;
4926 skb_shinfo(skb1)->nr_frags ||
4927 skb_has_frag_list(skb1)) {
4928 struct sk_buff *skb2;
4930 /* Fuck, we are miserable poor guys... */
4932 skb2 = skb_copy(skb1, GFP_ATOMIC);
4934 skb2 = skb_copy_expand(skb1,
4938 if (unlikely(skb2 == NULL))
4942 skb_set_owner_w(skb2, skb1->sk);
4944 /* Looking around. Are we still alive?
4945 * OK, link new skb, drop old one */
4947 skb2->next = skb1->next;
4954 skb_p = &skb1->next;
4959 EXPORT_SYMBOL_GPL(skb_cow_data);
4961 static void sock_rmem_free(struct sk_buff *skb)
4963 struct sock *sk = skb->sk;
4965 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4968 static void skb_set_err_queue(struct sk_buff *skb)
4970 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4971 * So, it is safe to (mis)use it to mark skbs on the error queue.
4973 skb->pkt_type = PACKET_OUTGOING;
4974 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4978 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4980 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4982 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4983 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4988 skb->destructor = sock_rmem_free;
4989 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4990 skb_set_err_queue(skb);
4992 /* before exiting rcu section, make sure dst is refcounted */
4995 skb_queue_tail(&sk->sk_error_queue, skb);
4996 if (!sock_flag(sk, SOCK_DEAD))
4997 sk_error_report(sk);
5000 EXPORT_SYMBOL(sock_queue_err_skb);
5002 static bool is_icmp_err_skb(const struct sk_buff *skb)
5004 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
5005 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
5008 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
5010 struct sk_buff_head *q = &sk->sk_error_queue;
5011 struct sk_buff *skb, *skb_next = NULL;
5012 bool icmp_next = false;
5013 unsigned long flags;
5015 spin_lock_irqsave(&q->lock, flags);
5016 skb = __skb_dequeue(q);
5017 if (skb && (skb_next = skb_peek(q))) {
5018 icmp_next = is_icmp_err_skb(skb_next);
5020 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
5022 spin_unlock_irqrestore(&q->lock, flags);
5024 if (is_icmp_err_skb(skb) && !icmp_next)
5028 sk_error_report(sk);
5032 EXPORT_SYMBOL(sock_dequeue_err_skb);
5035 * skb_clone_sk - create clone of skb, and take reference to socket
5036 * @skb: the skb to clone
5038 * This function creates a clone of a buffer that holds a reference on
5039 * sk_refcnt. Buffers created via this function are meant to be
5040 * returned using sock_queue_err_skb, or free via kfree_skb.
5042 * When passing buffers allocated with this function to sock_queue_err_skb
5043 * it is necessary to wrap the call with sock_hold/sock_put in order to
5044 * prevent the socket from being released prior to being enqueued on
5045 * the sk_error_queue.
5047 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
5049 struct sock *sk = skb->sk;
5050 struct sk_buff *clone;
5052 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
5055 clone = skb_clone(skb, GFP_ATOMIC);
5062 clone->destructor = sock_efree;
5066 EXPORT_SYMBOL(skb_clone_sk);
5068 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
5073 struct sock_exterr_skb *serr;
5076 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
5078 serr = SKB_EXT_ERR(skb);
5079 memset(serr, 0, sizeof(*serr));
5080 serr->ee.ee_errno = ENOMSG;
5081 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5082 serr->ee.ee_info = tstype;
5083 serr->opt_stats = opt_stats;
5084 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5085 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
5086 serr->ee.ee_data = skb_shinfo(skb)->tskey;
5088 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5091 err = sock_queue_err_skb(sk, skb);
5097 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5101 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5104 read_lock_bh(&sk->sk_callback_lock);
5105 ret = sk->sk_socket && sk->sk_socket->file &&
5106 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5107 read_unlock_bh(&sk->sk_callback_lock);
5111 void skb_complete_tx_timestamp(struct sk_buff *skb,
5112 struct skb_shared_hwtstamps *hwtstamps)
5114 struct sock *sk = skb->sk;
5116 if (!skb_may_tx_timestamp(sk, false))
5119 /* Take a reference to prevent skb_orphan() from freeing the socket,
5120 * but only if the socket refcount is not zero.
5122 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5123 *skb_hwtstamps(skb) = *hwtstamps;
5124 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5132 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5134 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5135 const struct sk_buff *ack_skb,
5136 struct skb_shared_hwtstamps *hwtstamps,
5137 struct sock *sk, int tstype)
5139 struct sk_buff *skb;
5140 bool tsonly, opt_stats = false;
5145 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5146 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5149 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5150 if (!skb_may_tx_timestamp(sk, tsonly))
5155 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5157 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5162 skb = alloc_skb(0, GFP_ATOMIC);
5164 skb = skb_clone(orig_skb, GFP_ATOMIC);
5170 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5172 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5176 *skb_hwtstamps(skb) = *hwtstamps;
5178 __net_timestamp(skb);
5180 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5182 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5184 void skb_tstamp_tx(struct sk_buff *orig_skb,
5185 struct skb_shared_hwtstamps *hwtstamps)
5187 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5190 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5192 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5194 struct sock *sk = skb->sk;
5195 struct sock_exterr_skb *serr;
5198 skb->wifi_acked_valid = 1;
5199 skb->wifi_acked = acked;
5201 serr = SKB_EXT_ERR(skb);
5202 memset(serr, 0, sizeof(*serr));
5203 serr->ee.ee_errno = ENOMSG;
5204 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5206 /* Take a reference to prevent skb_orphan() from freeing the socket,
5207 * but only if the socket refcount is not zero.
5209 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5210 err = sock_queue_err_skb(sk, skb);
5216 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5219 * skb_partial_csum_set - set up and verify partial csum values for packet
5220 * @skb: the skb to set
5221 * @start: the number of bytes after skb->data to start checksumming.
5222 * @off: the offset from start to place the checksum.
5224 * For untrusted partially-checksummed packets, we need to make sure the values
5225 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5227 * This function checks and sets those values and skb->ip_summed: if this
5228 * returns false you should drop the packet.
5230 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5232 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5233 u32 csum_start = skb_headroom(skb) + (u32)start;
5235 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
5236 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5237 start, off, skb_headroom(skb), skb_headlen(skb));
5240 skb->ip_summed = CHECKSUM_PARTIAL;
5241 skb->csum_start = csum_start;
5242 skb->csum_offset = off;
5243 skb_set_transport_header(skb, start);
5246 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5248 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5251 if (skb_headlen(skb) >= len)
5254 /* If we need to pullup then pullup to the max, so we
5255 * won't need to do it again.
5260 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5263 if (skb_headlen(skb) < len)
5269 #define MAX_TCP_HDR_LEN (15 * 4)
5271 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5272 typeof(IPPROTO_IP) proto,
5279 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5280 off + MAX_TCP_HDR_LEN);
5281 if (!err && !skb_partial_csum_set(skb, off,
5282 offsetof(struct tcphdr,
5285 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5288 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5289 off + sizeof(struct udphdr));
5290 if (!err && !skb_partial_csum_set(skb, off,
5291 offsetof(struct udphdr,
5294 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5297 return ERR_PTR(-EPROTO);
5300 /* This value should be large enough to cover a tagged ethernet header plus
5301 * maximally sized IP and TCP or UDP headers.
5303 #define MAX_IP_HDR_LEN 128
5305 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5314 err = skb_maybe_pull_tail(skb,
5315 sizeof(struct iphdr),
5320 if (ip_is_fragment(ip_hdr(skb)))
5323 off = ip_hdrlen(skb);
5330 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5332 return PTR_ERR(csum);
5335 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5338 ip_hdr(skb)->protocol, 0);
5345 /* This value should be large enough to cover a tagged ethernet header plus
5346 * an IPv6 header, all options, and a maximal TCP or UDP header.
5348 #define MAX_IPV6_HDR_LEN 256
5350 #define OPT_HDR(type, skb, off) \
5351 (type *)(skb_network_header(skb) + (off))
5353 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5366 off = sizeof(struct ipv6hdr);
5368 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5372 nexthdr = ipv6_hdr(skb)->nexthdr;
5374 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5375 while (off <= len && !done) {
5377 case IPPROTO_DSTOPTS:
5378 case IPPROTO_HOPOPTS:
5379 case IPPROTO_ROUTING: {
5380 struct ipv6_opt_hdr *hp;
5382 err = skb_maybe_pull_tail(skb,
5384 sizeof(struct ipv6_opt_hdr),
5389 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5390 nexthdr = hp->nexthdr;
5391 off += ipv6_optlen(hp);
5395 struct ip_auth_hdr *hp;
5397 err = skb_maybe_pull_tail(skb,
5399 sizeof(struct ip_auth_hdr),
5404 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5405 nexthdr = hp->nexthdr;
5406 off += ipv6_authlen(hp);
5409 case IPPROTO_FRAGMENT: {
5410 struct frag_hdr *hp;
5412 err = skb_maybe_pull_tail(skb,
5414 sizeof(struct frag_hdr),
5419 hp = OPT_HDR(struct frag_hdr, skb, off);
5421 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5424 nexthdr = hp->nexthdr;
5425 off += sizeof(struct frag_hdr);
5436 if (!done || fragment)
5439 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5441 return PTR_ERR(csum);
5444 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5445 &ipv6_hdr(skb)->daddr,
5446 skb->len - off, nexthdr, 0);
5454 * skb_checksum_setup - set up partial checksum offset
5455 * @skb: the skb to set up
5456 * @recalculate: if true the pseudo-header checksum will be recalculated
5458 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5462 switch (skb->protocol) {
5463 case htons(ETH_P_IP):
5464 err = skb_checksum_setup_ipv4(skb, recalculate);
5467 case htons(ETH_P_IPV6):
5468 err = skb_checksum_setup_ipv6(skb, recalculate);
5478 EXPORT_SYMBOL(skb_checksum_setup);
5481 * skb_checksum_maybe_trim - maybe trims the given skb
5482 * @skb: the skb to check
5483 * @transport_len: the data length beyond the network header
5485 * Checks whether the given skb has data beyond the given transport length.
5486 * If so, returns a cloned skb trimmed to this transport length.
5487 * Otherwise returns the provided skb. Returns NULL in error cases
5488 * (e.g. transport_len exceeds skb length or out-of-memory).
5490 * Caller needs to set the skb transport header and free any returned skb if it
5491 * differs from the provided skb.
5493 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5494 unsigned int transport_len)
5496 struct sk_buff *skb_chk;
5497 unsigned int len = skb_transport_offset(skb) + transport_len;
5502 else if (skb->len == len)
5505 skb_chk = skb_clone(skb, GFP_ATOMIC);
5509 ret = pskb_trim_rcsum(skb_chk, len);
5519 * skb_checksum_trimmed - validate checksum of an skb
5520 * @skb: the skb to check
5521 * @transport_len: the data length beyond the network header
5522 * @skb_chkf: checksum function to use
5524 * Applies the given checksum function skb_chkf to the provided skb.
5525 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5527 * If the skb has data beyond the given transport length, then a
5528 * trimmed & cloned skb is checked and returned.
5530 * Caller needs to set the skb transport header and free any returned skb if it
5531 * differs from the provided skb.
5533 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5534 unsigned int transport_len,
5535 __sum16(*skb_chkf)(struct sk_buff *skb))
5537 struct sk_buff *skb_chk;
5538 unsigned int offset = skb_transport_offset(skb);
5541 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5545 if (!pskb_may_pull(skb_chk, offset))
5548 skb_pull_rcsum(skb_chk, offset);
5549 ret = skb_chkf(skb_chk);
5550 skb_push_rcsum(skb_chk, offset);
5558 if (skb_chk && skb_chk != skb)
5564 EXPORT_SYMBOL(skb_checksum_trimmed);
5566 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5568 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5571 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5573 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5576 skb_release_head_state(skb);
5577 kmem_cache_free(skbuff_cache, skb);
5582 EXPORT_SYMBOL(kfree_skb_partial);
5585 * skb_try_coalesce - try to merge skb to prior one
5587 * @from: buffer to add
5588 * @fragstolen: pointer to boolean
5589 * @delta_truesize: how much more was allocated than was requested
5591 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5592 bool *fragstolen, int *delta_truesize)
5594 struct skb_shared_info *to_shinfo, *from_shinfo;
5595 int i, delta, len = from->len;
5597 *fragstolen = false;
5602 /* In general, avoid mixing page_pool and non-page_pool allocated
5603 * pages within the same SKB. Additionally avoid dealing with clones
5604 * with page_pool pages, in case the SKB is using page_pool fragment
5605 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5606 * references for cloned SKBs at the moment that would result in
5607 * inconsistent reference counts.
5608 * In theory we could take full references if @from is cloned and
5609 * !@to->pp_recycle but its tricky (due to potential race with
5610 * the clone disappearing) and rare, so not worth dealing with.
5612 if (to->pp_recycle != from->pp_recycle ||
5613 (from->pp_recycle && skb_cloned(from)))
5616 if (len <= skb_tailroom(to)) {
5618 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5619 *delta_truesize = 0;
5623 to_shinfo = skb_shinfo(to);
5624 from_shinfo = skb_shinfo(from);
5625 if (to_shinfo->frag_list || from_shinfo->frag_list)
5627 if (skb_zcopy(to) || skb_zcopy(from))
5630 if (skb_headlen(from) != 0) {
5632 unsigned int offset;
5634 if (to_shinfo->nr_frags +
5635 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5638 if (skb_head_is_locked(from))
5641 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5643 page = virt_to_head_page(from->head);
5644 offset = from->data - (unsigned char *)page_address(page);
5646 skb_fill_page_desc(to, to_shinfo->nr_frags,
5647 page, offset, skb_headlen(from));
5650 if (to_shinfo->nr_frags +
5651 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5654 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5657 WARN_ON_ONCE(delta < len);
5659 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5661 from_shinfo->nr_frags * sizeof(skb_frag_t));
5662 to_shinfo->nr_frags += from_shinfo->nr_frags;
5664 if (!skb_cloned(from))
5665 from_shinfo->nr_frags = 0;
5667 /* if the skb is not cloned this does nothing
5668 * since we set nr_frags to 0.
5670 for (i = 0; i < from_shinfo->nr_frags; i++)
5671 __skb_frag_ref(&from_shinfo->frags[i]);
5673 to->truesize += delta;
5675 to->data_len += len;
5677 *delta_truesize = delta;
5680 EXPORT_SYMBOL(skb_try_coalesce);
5683 * skb_scrub_packet - scrub an skb
5685 * @skb: buffer to clean
5686 * @xnet: packet is crossing netns
5688 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5689 * into/from a tunnel. Some information have to be cleared during these
5691 * skb_scrub_packet can also be used to clean a skb before injecting it in
5692 * another namespace (@xnet == true). We have to clear all information in the
5693 * skb that could impact namespace isolation.
5695 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5697 skb->pkt_type = PACKET_HOST;
5703 nf_reset_trace(skb);
5705 #ifdef CONFIG_NET_SWITCHDEV
5706 skb->offload_fwd_mark = 0;
5707 skb->offload_l3_fwd_mark = 0;
5715 skb_clear_tstamp(skb);
5717 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5720 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5724 * skb_gso_transport_seglen is used to determine the real size of the
5725 * individual segments, including Layer4 headers (TCP/UDP).
5727 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5729 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5731 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5732 unsigned int thlen = 0;
5734 if (skb->encapsulation) {
5735 thlen = skb_inner_transport_header(skb) -
5736 skb_transport_header(skb);
5738 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5739 thlen += inner_tcp_hdrlen(skb);
5740 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5741 thlen = tcp_hdrlen(skb);
5742 } else if (unlikely(skb_is_gso_sctp(skb))) {
5743 thlen = sizeof(struct sctphdr);
5744 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5745 thlen = sizeof(struct udphdr);
5747 /* UFO sets gso_size to the size of the fragmentation
5748 * payload, i.e. the size of the L4 (UDP) header is already
5751 return thlen + shinfo->gso_size;
5755 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5759 * skb_gso_network_seglen is used to determine the real size of the
5760 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5762 * The MAC/L2 header is not accounted for.
5764 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5766 unsigned int hdr_len = skb_transport_header(skb) -
5767 skb_network_header(skb);
5769 return hdr_len + skb_gso_transport_seglen(skb);
5773 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5777 * skb_gso_mac_seglen is used to determine the real size of the
5778 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5779 * headers (TCP/UDP).
5781 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5783 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5785 return hdr_len + skb_gso_transport_seglen(skb);
5789 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5791 * There are a couple of instances where we have a GSO skb, and we
5792 * want to determine what size it would be after it is segmented.
5794 * We might want to check:
5795 * - L3+L4+payload size (e.g. IP forwarding)
5796 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5798 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5802 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5803 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5805 * @max_len: The maximum permissible length.
5807 * Returns true if the segmented length <= max length.
5809 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5810 unsigned int seg_len,
5811 unsigned int max_len) {
5812 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5813 const struct sk_buff *iter;
5815 if (shinfo->gso_size != GSO_BY_FRAGS)
5816 return seg_len <= max_len;
5818 /* Undo this so we can re-use header sizes */
5819 seg_len -= GSO_BY_FRAGS;
5821 skb_walk_frags(skb, iter) {
5822 if (seg_len + skb_headlen(iter) > max_len)
5830 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5833 * @mtu: MTU to validate against
5835 * skb_gso_validate_network_len validates if a given skb will fit a
5836 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5839 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5841 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5843 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5846 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5849 * @len: length to validate against
5851 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5852 * length once split, including L2, L3 and L4 headers and the payload.
5854 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5856 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5858 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5860 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5862 int mac_len, meta_len;
5865 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5870 mac_len = skb->data - skb_mac_header(skb);
5871 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5872 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5873 mac_len - VLAN_HLEN - ETH_TLEN);
5876 meta_len = skb_metadata_len(skb);
5878 meta = skb_metadata_end(skb) - meta_len;
5879 memmove(meta + VLAN_HLEN, meta, meta_len);
5882 skb->mac_header += VLAN_HLEN;
5886 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5888 struct vlan_hdr *vhdr;
5891 if (unlikely(skb_vlan_tag_present(skb))) {
5892 /* vlan_tci is already set-up so leave this for another time */
5896 skb = skb_share_check(skb, GFP_ATOMIC);
5899 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5900 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5903 vhdr = (struct vlan_hdr *)skb->data;
5904 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5905 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5907 skb_pull_rcsum(skb, VLAN_HLEN);
5908 vlan_set_encap_proto(skb, vhdr);
5910 skb = skb_reorder_vlan_header(skb);
5914 skb_reset_network_header(skb);
5915 if (!skb_transport_header_was_set(skb))
5916 skb_reset_transport_header(skb);
5917 skb_reset_mac_len(skb);
5925 EXPORT_SYMBOL(skb_vlan_untag);
5927 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5929 if (!pskb_may_pull(skb, write_len))
5932 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5935 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5937 EXPORT_SYMBOL(skb_ensure_writable);
5939 /* remove VLAN header from packet and update csum accordingly.
5940 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5942 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5944 struct vlan_hdr *vhdr;
5945 int offset = skb->data - skb_mac_header(skb);
5948 if (WARN_ONCE(offset,
5949 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5954 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5958 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5960 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5961 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5963 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5964 __skb_pull(skb, VLAN_HLEN);
5966 vlan_set_encap_proto(skb, vhdr);
5967 skb->mac_header += VLAN_HLEN;
5969 if (skb_network_offset(skb) < ETH_HLEN)
5970 skb_set_network_header(skb, ETH_HLEN);
5972 skb_reset_mac_len(skb);
5976 EXPORT_SYMBOL(__skb_vlan_pop);
5978 /* Pop a vlan tag either from hwaccel or from payload.
5979 * Expects skb->data at mac header.
5981 int skb_vlan_pop(struct sk_buff *skb)
5987 if (likely(skb_vlan_tag_present(skb))) {
5988 __vlan_hwaccel_clear_tag(skb);
5990 if (unlikely(!eth_type_vlan(skb->protocol)))
5993 err = __skb_vlan_pop(skb, &vlan_tci);
5997 /* move next vlan tag to hw accel tag */
5998 if (likely(!eth_type_vlan(skb->protocol)))
6001 vlan_proto = skb->protocol;
6002 err = __skb_vlan_pop(skb, &vlan_tci);
6006 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6009 EXPORT_SYMBOL(skb_vlan_pop);
6011 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
6012 * Expects skb->data at mac header.
6014 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
6016 if (skb_vlan_tag_present(skb)) {
6017 int offset = skb->data - skb_mac_header(skb);
6020 if (WARN_ONCE(offset,
6021 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
6026 err = __vlan_insert_tag(skb, skb->vlan_proto,
6027 skb_vlan_tag_get(skb));
6031 skb->protocol = skb->vlan_proto;
6032 skb->mac_len += VLAN_HLEN;
6034 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6036 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6039 EXPORT_SYMBOL(skb_vlan_push);
6042 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
6044 * @skb: Socket buffer to modify
6046 * Drop the Ethernet header of @skb.
6048 * Expects that skb->data points to the mac header and that no VLAN tags are
6051 * Returns 0 on success, -errno otherwise.
6053 int skb_eth_pop(struct sk_buff *skb)
6055 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
6056 skb_network_offset(skb) < ETH_HLEN)
6059 skb_pull_rcsum(skb, ETH_HLEN);
6060 skb_reset_mac_header(skb);
6061 skb_reset_mac_len(skb);
6065 EXPORT_SYMBOL(skb_eth_pop);
6068 * skb_eth_push() - Add a new Ethernet header at the head of a packet
6070 * @skb: Socket buffer to modify
6071 * @dst: Destination MAC address of the new header
6072 * @src: Source MAC address of the new header
6074 * Prepend @skb with a new Ethernet header.
6076 * Expects that skb->data points to the mac header, which must be empty.
6078 * Returns 0 on success, -errno otherwise.
6080 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6081 const unsigned char *src)
6086 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6089 err = skb_cow_head(skb, sizeof(*eth));
6093 skb_push(skb, sizeof(*eth));
6094 skb_reset_mac_header(skb);
6095 skb_reset_mac_len(skb);
6098 ether_addr_copy(eth->h_dest, dst);
6099 ether_addr_copy(eth->h_source, src);
6100 eth->h_proto = skb->protocol;
6102 skb_postpush_rcsum(skb, eth, sizeof(*eth));
6106 EXPORT_SYMBOL(skb_eth_push);
6108 /* Update the ethertype of hdr and the skb csum value if required. */
6109 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6112 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6113 __be16 diff[] = { ~hdr->h_proto, ethertype };
6115 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6118 hdr->h_proto = ethertype;
6122 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6126 * @mpls_lse: MPLS label stack entry to push
6127 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6128 * @mac_len: length of the MAC header
6129 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6132 * Expects skb->data at mac header.
6134 * Returns 0 on success, -errno otherwise.
6136 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6137 int mac_len, bool ethernet)
6139 struct mpls_shim_hdr *lse;
6142 if (unlikely(!eth_p_mpls(mpls_proto)))
6145 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6146 if (skb->encapsulation)
6149 err = skb_cow_head(skb, MPLS_HLEN);
6153 if (!skb->inner_protocol) {
6154 skb_set_inner_network_header(skb, skb_network_offset(skb));
6155 skb_set_inner_protocol(skb, skb->protocol);
6158 skb_push(skb, MPLS_HLEN);
6159 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6161 skb_reset_mac_header(skb);
6162 skb_set_network_header(skb, mac_len);
6163 skb_reset_mac_len(skb);
6165 lse = mpls_hdr(skb);
6166 lse->label_stack_entry = mpls_lse;
6167 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6169 if (ethernet && mac_len >= ETH_HLEN)
6170 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6171 skb->protocol = mpls_proto;
6175 EXPORT_SYMBOL_GPL(skb_mpls_push);
6178 * skb_mpls_pop() - pop the outermost MPLS header
6181 * @next_proto: ethertype of header after popped MPLS header
6182 * @mac_len: length of the MAC header
6183 * @ethernet: flag to indicate if the packet is ethernet
6185 * Expects skb->data at mac header.
6187 * Returns 0 on success, -errno otherwise.
6189 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6194 if (unlikely(!eth_p_mpls(skb->protocol)))
6197 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6201 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6202 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6205 __skb_pull(skb, MPLS_HLEN);
6206 skb_reset_mac_header(skb);
6207 skb_set_network_header(skb, mac_len);
6209 if (ethernet && mac_len >= ETH_HLEN) {
6212 /* use mpls_hdr() to get ethertype to account for VLANs. */
6213 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6214 skb_mod_eth_type(skb, hdr, next_proto);
6216 skb->protocol = next_proto;
6220 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6223 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6226 * @mpls_lse: new MPLS label stack entry to update to
6228 * Expects skb->data at mac header.
6230 * Returns 0 on success, -errno otherwise.
6232 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6236 if (unlikely(!eth_p_mpls(skb->protocol)))
6239 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6243 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6244 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6246 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6249 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6253 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6256 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6260 * Expects skb->data at mac header.
6262 * Returns 0 on success, -errno otherwise.
6264 int skb_mpls_dec_ttl(struct sk_buff *skb)
6269 if (unlikely(!eth_p_mpls(skb->protocol)))
6272 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6275 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6276 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6280 lse &= ~MPLS_LS_TTL_MASK;
6281 lse |= ttl << MPLS_LS_TTL_SHIFT;
6283 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6285 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6288 * alloc_skb_with_frags - allocate skb with page frags
6290 * @header_len: size of linear part
6291 * @data_len: needed length in frags
6292 * @max_page_order: max page order desired.
6293 * @errcode: pointer to error code if any
6294 * @gfp_mask: allocation mask
6296 * This can be used to allocate a paged skb, given a maximal order for frags.
6298 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6299 unsigned long data_len,
6304 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6305 unsigned long chunk;
6306 struct sk_buff *skb;
6310 *errcode = -EMSGSIZE;
6311 /* Note this test could be relaxed, if we succeed to allocate
6312 * high order pages...
6314 if (npages > MAX_SKB_FRAGS)
6317 *errcode = -ENOBUFS;
6318 skb = alloc_skb(header_len, gfp_mask);
6322 skb->truesize += npages << PAGE_SHIFT;
6324 for (i = 0; npages > 0; i++) {
6325 int order = max_page_order;
6328 if (npages >= 1 << order) {
6329 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6335 /* Do not retry other high order allocations */
6341 page = alloc_page(gfp_mask);
6345 chunk = min_t(unsigned long, data_len,
6346 PAGE_SIZE << order);
6347 skb_fill_page_desc(skb, i, page, 0, chunk);
6349 npages -= 1 << order;
6357 EXPORT_SYMBOL(alloc_skb_with_frags);
6359 /* carve out the first off bytes from skb when off < headlen */
6360 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6361 const int headlen, gfp_t gfp_mask)
6364 unsigned int size = skb_end_offset(skb);
6365 int new_hlen = headlen - off;
6368 if (skb_pfmemalloc(skb))
6369 gfp_mask |= __GFP_MEMALLOC;
6371 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6374 size = SKB_WITH_OVERHEAD(size);
6376 /* Copy real data, and all frags */
6377 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6380 memcpy((struct skb_shared_info *)(data + size),
6382 offsetof(struct skb_shared_info,
6383 frags[skb_shinfo(skb)->nr_frags]));
6384 if (skb_cloned(skb)) {
6385 /* drop the old head gracefully */
6386 if (skb_orphan_frags(skb, gfp_mask)) {
6387 skb_kfree_head(data, size);
6390 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6391 skb_frag_ref(skb, i);
6392 if (skb_has_frag_list(skb))
6393 skb_clone_fraglist(skb);
6394 skb_release_data(skb, SKB_CONSUMED);
6396 /* we can reuse existing recount- all we did was
6405 skb_set_end_offset(skb, size);
6406 skb_set_tail_pointer(skb, skb_headlen(skb));
6407 skb_headers_offset_update(skb, 0);
6411 atomic_set(&skb_shinfo(skb)->dataref, 1);
6416 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6418 /* carve out the first eat bytes from skb's frag_list. May recurse into
6421 static int pskb_carve_frag_list(struct sk_buff *skb,
6422 struct skb_shared_info *shinfo, int eat,
6425 struct sk_buff *list = shinfo->frag_list;
6426 struct sk_buff *clone = NULL;
6427 struct sk_buff *insp = NULL;
6431 pr_err("Not enough bytes to eat. Want %d\n", eat);
6434 if (list->len <= eat) {
6435 /* Eaten as whole. */
6440 /* Eaten partially. */
6441 if (skb_shared(list)) {
6442 clone = skb_clone(list, gfp_mask);
6448 /* This may be pulled without problems. */
6451 if (pskb_carve(list, eat, gfp_mask) < 0) {
6459 /* Free pulled out fragments. */
6460 while ((list = shinfo->frag_list) != insp) {
6461 shinfo->frag_list = list->next;
6464 /* And insert new clone at head. */
6467 shinfo->frag_list = clone;
6472 /* carve off first len bytes from skb. Split line (off) is in the
6473 * non-linear part of skb
6475 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6476 int pos, gfp_t gfp_mask)
6479 unsigned int size = skb_end_offset(skb);
6481 const int nfrags = skb_shinfo(skb)->nr_frags;
6482 struct skb_shared_info *shinfo;
6484 if (skb_pfmemalloc(skb))
6485 gfp_mask |= __GFP_MEMALLOC;
6487 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6490 size = SKB_WITH_OVERHEAD(size);
6492 memcpy((struct skb_shared_info *)(data + size),
6493 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6494 if (skb_orphan_frags(skb, gfp_mask)) {
6495 skb_kfree_head(data, size);
6498 shinfo = (struct skb_shared_info *)(data + size);
6499 for (i = 0; i < nfrags; i++) {
6500 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6502 if (pos + fsize > off) {
6503 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6507 * We have two variants in this case:
6508 * 1. Move all the frag to the second
6509 * part, if it is possible. F.e.
6510 * this approach is mandatory for TUX,
6511 * where splitting is expensive.
6512 * 2. Split is accurately. We make this.
6514 skb_frag_off_add(&shinfo->frags[0], off - pos);
6515 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6517 skb_frag_ref(skb, i);
6522 shinfo->nr_frags = k;
6523 if (skb_has_frag_list(skb))
6524 skb_clone_fraglist(skb);
6526 /* split line is in frag list */
6527 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6528 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6529 if (skb_has_frag_list(skb))
6530 kfree_skb_list(skb_shinfo(skb)->frag_list);
6531 skb_kfree_head(data, size);
6534 skb_release_data(skb, SKB_CONSUMED);
6539 skb_set_end_offset(skb, size);
6540 skb_reset_tail_pointer(skb);
6541 skb_headers_offset_update(skb, 0);
6546 skb->data_len = skb->len;
6547 atomic_set(&skb_shinfo(skb)->dataref, 1);
6551 /* remove len bytes from the beginning of the skb */
6552 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6554 int headlen = skb_headlen(skb);
6557 return pskb_carve_inside_header(skb, len, headlen, gfp);
6559 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6562 /* Extract to_copy bytes starting at off from skb, and return this in
6565 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6566 int to_copy, gfp_t gfp)
6568 struct sk_buff *clone = skb_clone(skb, gfp);
6573 if (pskb_carve(clone, off, gfp) < 0 ||
6574 pskb_trim(clone, to_copy)) {
6580 EXPORT_SYMBOL(pskb_extract);
6583 * skb_condense - try to get rid of fragments/frag_list if possible
6586 * Can be used to save memory before skb is added to a busy queue.
6587 * If packet has bytes in frags and enough tail room in skb->head,
6588 * pull all of them, so that we can free the frags right now and adjust
6591 * We do not reallocate skb->head thus can not fail.
6592 * Caller must re-evaluate skb->truesize if needed.
6594 void skb_condense(struct sk_buff *skb)
6596 if (skb->data_len) {
6597 if (skb->data_len > skb->end - skb->tail ||
6601 /* Nice, we can free page frag(s) right now */
6602 __pskb_pull_tail(skb, skb->data_len);
6604 /* At this point, skb->truesize might be over estimated,
6605 * because skb had a fragment, and fragments do not tell
6607 * When we pulled its content into skb->head, fragment
6608 * was freed, but __pskb_pull_tail() could not possibly
6609 * adjust skb->truesize, not knowing the frag truesize.
6611 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6613 EXPORT_SYMBOL(skb_condense);
6615 #ifdef CONFIG_SKB_EXTENSIONS
6616 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6618 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6622 * __skb_ext_alloc - allocate a new skb extensions storage
6624 * @flags: See kmalloc().
6626 * Returns the newly allocated pointer. The pointer can later attached to a
6627 * skb via __skb_ext_set().
6628 * Note: caller must handle the skb_ext as an opaque data.
6630 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6632 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6635 memset(new->offset, 0, sizeof(new->offset));
6636 refcount_set(&new->refcnt, 1);
6642 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6643 unsigned int old_active)
6645 struct skb_ext *new;
6647 if (refcount_read(&old->refcnt) == 1)
6650 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6654 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6655 refcount_set(&new->refcnt, 1);
6658 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6659 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6662 for (i = 0; i < sp->len; i++)
6663 xfrm_state_hold(sp->xvec[i]);
6671 * __skb_ext_set - attach the specified extension storage to this skb
6674 * @ext: extension storage previously allocated via __skb_ext_alloc()
6676 * Existing extensions, if any, are cleared.
6678 * Returns the pointer to the extension.
6680 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6681 struct skb_ext *ext)
6683 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6686 newlen = newoff + skb_ext_type_len[id];
6687 ext->chunks = newlen;
6688 ext->offset[id] = newoff;
6689 skb->extensions = ext;
6690 skb->active_extensions = 1 << id;
6691 return skb_ext_get_ptr(ext, id);
6695 * skb_ext_add - allocate space for given extension, COW if needed
6697 * @id: extension to allocate space for
6699 * Allocates enough space for the given extension.
6700 * If the extension is already present, a pointer to that extension
6703 * If the skb was cloned, COW applies and the returned memory can be
6704 * modified without changing the extension space of clones buffers.
6706 * Returns pointer to the extension or NULL on allocation failure.
6708 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6710 struct skb_ext *new, *old = NULL;
6711 unsigned int newlen, newoff;
6713 if (skb->active_extensions) {
6714 old = skb->extensions;
6716 new = skb_ext_maybe_cow(old, skb->active_extensions);
6720 if (__skb_ext_exist(new, id))
6723 newoff = new->chunks;
6725 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6727 new = __skb_ext_alloc(GFP_ATOMIC);
6732 newlen = newoff + skb_ext_type_len[id];
6733 new->chunks = newlen;
6734 new->offset[id] = newoff;
6737 skb->extensions = new;
6738 skb->active_extensions |= 1 << id;
6739 return skb_ext_get_ptr(new, id);
6741 EXPORT_SYMBOL(skb_ext_add);
6744 static void skb_ext_put_sp(struct sec_path *sp)
6748 for (i = 0; i < sp->len; i++)
6749 xfrm_state_put(sp->xvec[i]);
6753 #ifdef CONFIG_MCTP_FLOWS
6754 static void skb_ext_put_mctp(struct mctp_flow *flow)
6757 mctp_key_unref(flow->key);
6761 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6763 struct skb_ext *ext = skb->extensions;
6765 skb->active_extensions &= ~(1 << id);
6766 if (skb->active_extensions == 0) {
6767 skb->extensions = NULL;
6770 } else if (id == SKB_EXT_SEC_PATH &&
6771 refcount_read(&ext->refcnt) == 1) {
6772 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6779 EXPORT_SYMBOL(__skb_ext_del);
6781 void __skb_ext_put(struct skb_ext *ext)
6783 /* If this is last clone, nothing can increment
6784 * it after check passes. Avoids one atomic op.
6786 if (refcount_read(&ext->refcnt) == 1)
6789 if (!refcount_dec_and_test(&ext->refcnt))
6793 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6794 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6796 #ifdef CONFIG_MCTP_FLOWS
6797 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6798 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6801 kmem_cache_free(skbuff_ext_cache, ext);
6803 EXPORT_SYMBOL(__skb_ext_put);
6804 #endif /* CONFIG_SKB_EXTENSIONS */
6807 * skb_attempt_defer_free - queue skb for remote freeing
6810 * Put @skb in a per-cpu list, using the cpu which
6811 * allocated the skb/pages to reduce false sharing
6812 * and memory zone spinlock contention.
6814 void skb_attempt_defer_free(struct sk_buff *skb)
6816 int cpu = skb->alloc_cpu;
6817 struct softnet_data *sd;
6818 unsigned long flags;
6819 unsigned int defer_max;
6822 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6824 cpu == raw_smp_processor_id()) {
6825 nodefer: __kfree_skb(skb);
6829 sd = &per_cpu(softnet_data, cpu);
6830 defer_max = READ_ONCE(sysctl_skb_defer_max);
6831 if (READ_ONCE(sd->defer_count) >= defer_max)
6834 spin_lock_irqsave(&sd->defer_lock, flags);
6835 /* Send an IPI every time queue reaches half capacity. */
6836 kick = sd->defer_count == (defer_max >> 1);
6837 /* Paired with the READ_ONCE() few lines above */
6838 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6840 skb->next = sd->defer_list;
6841 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6842 WRITE_ONCE(sd->defer_list, skb);
6843 spin_unlock_irqrestore(&sd->defer_lock, flags);
6845 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6846 * if we are unlucky enough (this seems very unlikely).
6848 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6849 smp_call_function_single_async(cpu, &sd->defer_csd);