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/skbuff_ref.h>
55 #include <linux/splice.h>
56 #include <linux/cache.h>
57 #include <linux/rtnetlink.h>
58 #include <linux/init.h>
59 #include <linux/scatterlist.h>
60 #include <linux/errqueue.h>
61 #include <linux/prefetch.h>
62 #include <linux/bitfield.h>
63 #include <linux/if_vlan.h>
64 #include <linux/mpls.h>
65 #include <linux/kcov.h>
66 #include <linux/iov_iter.h>
68 #include <net/protocol.h>
71 #include <net/checksum.h>
73 #include <net/hotdata.h>
74 #include <net/ip6_checksum.h>
77 #include <net/mptcp.h>
79 #include <net/page_pool/helpers.h>
80 #include <net/dropreason.h>
82 #include <linux/uaccess.h>
83 #include <trace/events/skb.h>
84 #include <linux/highmem.h>
85 #include <linux/capability.h>
86 #include <linux/user_namespace.h>
87 #include <linux/indirect_call_wrapper.h>
88 #include <linux/textsearch.h>
91 #include "sock_destructor.h"
93 #ifdef CONFIG_SKB_EXTENSIONS
94 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
97 #define SKB_SMALL_HEAD_SIZE SKB_HEAD_ALIGN(MAX_TCP_HEADER)
99 /* We want SKB_SMALL_HEAD_CACHE_SIZE to not be a power of two.
100 * This should ensure that SKB_SMALL_HEAD_HEADROOM is a unique
101 * size, and we can differentiate heads from skb_small_head_cache
102 * vs system slabs by looking at their size (skb_end_offset()).
104 #define SKB_SMALL_HEAD_CACHE_SIZE \
105 (is_power_of_2(SKB_SMALL_HEAD_SIZE) ? \
106 (SKB_SMALL_HEAD_SIZE + L1_CACHE_BYTES) : \
109 #define SKB_SMALL_HEAD_HEADROOM \
110 SKB_WITH_OVERHEAD(SKB_SMALL_HEAD_CACHE_SIZE)
112 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
113 EXPORT_SYMBOL(sysctl_max_skb_frags);
115 /* kcm_write_msgs() relies on casting paged frags to bio_vec to use
116 * iov_iter_bvec(). These static asserts ensure the cast is valid is long as the
119 static_assert(offsetof(struct bio_vec, bv_page) ==
120 offsetof(skb_frag_t, netmem));
121 static_assert(sizeof_field(struct bio_vec, bv_page) ==
122 sizeof_field(skb_frag_t, netmem));
124 static_assert(offsetof(struct bio_vec, bv_len) == offsetof(skb_frag_t, len));
125 static_assert(sizeof_field(struct bio_vec, bv_len) ==
126 sizeof_field(skb_frag_t, len));
128 static_assert(offsetof(struct bio_vec, bv_offset) ==
129 offsetof(skb_frag_t, offset));
130 static_assert(sizeof_field(struct bio_vec, bv_offset) ==
131 sizeof_field(skb_frag_t, offset));
134 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
135 static const char * const drop_reasons[] = {
136 [SKB_CONSUMED] = "CONSUMED",
137 DEFINE_DROP_REASON(FN, FN)
140 static const struct drop_reason_list drop_reasons_core = {
141 .reasons = drop_reasons,
142 .n_reasons = ARRAY_SIZE(drop_reasons),
145 const struct drop_reason_list __rcu *
146 drop_reasons_by_subsys[SKB_DROP_REASON_SUBSYS_NUM] = {
147 [SKB_DROP_REASON_SUBSYS_CORE] = RCU_INITIALIZER(&drop_reasons_core),
149 EXPORT_SYMBOL(drop_reasons_by_subsys);
152 * drop_reasons_register_subsys - register another drop reason subsystem
153 * @subsys: the subsystem to register, must not be the core
154 * @list: the list of drop reasons within the subsystem, must point to
155 * a statically initialized list
157 void drop_reasons_register_subsys(enum skb_drop_reason_subsys subsys,
158 const struct drop_reason_list *list)
160 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
161 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
162 "invalid subsystem %d\n", subsys))
165 /* must point to statically allocated memory, so INIT is OK */
166 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], list);
168 EXPORT_SYMBOL_GPL(drop_reasons_register_subsys);
171 * drop_reasons_unregister_subsys - unregister a drop reason subsystem
172 * @subsys: the subsystem to remove, must not be the core
174 * Note: This will synchronize_rcu() to ensure no users when it returns.
176 void drop_reasons_unregister_subsys(enum skb_drop_reason_subsys subsys)
178 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
179 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
180 "invalid subsystem %d\n", subsys))
183 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], NULL);
187 EXPORT_SYMBOL_GPL(drop_reasons_unregister_subsys);
190 * skb_panic - private function for out-of-line support
194 * @msg: skb_over_panic or skb_under_panic
196 * Out-of-line support for skb_put() and skb_push().
197 * Called via the wrapper skb_over_panic() or skb_under_panic().
198 * Keep out of line to prevent kernel bloat.
199 * __builtin_return_address is not used because it is not always reliable.
201 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
204 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
205 msg, addr, skb->len, sz, skb->head, skb->data,
206 (unsigned long)skb->tail, (unsigned long)skb->end,
207 skb->dev ? skb->dev->name : "<NULL>");
211 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
213 skb_panic(skb, sz, addr, __func__);
216 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
218 skb_panic(skb, sz, addr, __func__);
221 #define NAPI_SKB_CACHE_SIZE 64
222 #define NAPI_SKB_CACHE_BULK 16
223 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
225 #if PAGE_SIZE == SZ_4K
227 #define NAPI_HAS_SMALL_PAGE_FRAG 1
228 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) ((nc).pfmemalloc)
230 /* specialized page frag allocator using a single order 0 page
231 * and slicing it into 1K sized fragment. Constrained to systems
232 * with a very limited amount of 1K fragments fitting a single
233 * page - to avoid excessive truesize underestimation
236 struct page_frag_1k {
242 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
247 offset = nc->offset - SZ_1K;
248 if (likely(offset >= 0))
251 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
255 nc->va = page_address(page);
256 nc->pfmemalloc = page_is_pfmemalloc(page);
257 offset = PAGE_SIZE - SZ_1K;
258 page_ref_add(page, offset / SZ_1K);
262 return nc->va + offset;
266 /* the small page is actually unused in this build; add dummy helpers
267 * to please the compiler and avoid later preprocessor's conditionals
269 #define NAPI_HAS_SMALL_PAGE_FRAG 0
270 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) false
272 struct page_frag_1k {
275 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
282 struct napi_alloc_cache {
283 struct page_frag_cache page;
284 struct page_frag_1k page_small;
285 unsigned int skb_count;
286 void *skb_cache[NAPI_SKB_CACHE_SIZE];
289 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
290 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
292 /* Double check that napi_get_frags() allocates skbs with
293 * skb->head being backed by slab, not a page fragment.
294 * This is to make sure bug fixed in 3226b158e67c
295 * ("net: avoid 32 x truesize under-estimation for tiny skbs")
296 * does not accidentally come back.
298 void napi_get_frags_check(struct napi_struct *napi)
303 skb = napi_get_frags(napi);
304 WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
305 napi_free_frags(napi);
309 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
311 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
313 fragsz = SKB_DATA_ALIGN(fragsz);
315 return __page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC,
318 EXPORT_SYMBOL(__napi_alloc_frag_align);
320 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
324 fragsz = SKB_DATA_ALIGN(fragsz);
325 if (in_hardirq() || irqs_disabled()) {
326 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
328 data = __page_frag_alloc_align(nc, fragsz, GFP_ATOMIC,
331 struct napi_alloc_cache *nc;
334 nc = this_cpu_ptr(&napi_alloc_cache);
335 data = __page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC,
341 EXPORT_SYMBOL(__netdev_alloc_frag_align);
343 static struct sk_buff *napi_skb_cache_get(void)
345 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
348 if (unlikely(!nc->skb_count)) {
349 nc->skb_count = kmem_cache_alloc_bulk(net_hotdata.skbuff_cache,
353 if (unlikely(!nc->skb_count))
357 skb = nc->skb_cache[--nc->skb_count];
358 kasan_mempool_unpoison_object(skb, kmem_cache_size(net_hotdata.skbuff_cache));
363 static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
366 struct skb_shared_info *shinfo;
368 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
370 /* Assumes caller memset cleared SKB */
371 skb->truesize = SKB_TRUESIZE(size);
372 refcount_set(&skb->users, 1);
375 skb_reset_tail_pointer(skb);
376 skb_set_end_offset(skb, size);
377 skb->mac_header = (typeof(skb->mac_header))~0U;
378 skb->transport_header = (typeof(skb->transport_header))~0U;
379 skb->alloc_cpu = raw_smp_processor_id();
380 /* make sure we initialize shinfo sequentially */
381 shinfo = skb_shinfo(skb);
382 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
383 atomic_set(&shinfo->dataref, 1);
385 skb_set_kcov_handle(skb, kcov_common_handle());
388 static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
393 /* Must find the allocation size (and grow it to match). */
395 /* krealloc() will immediately return "data" when
396 * "ksize(data)" is requested: it is the existing upper
397 * bounds. As a result, GFP_ATOMIC will be ignored. Note
398 * that this "new" pointer needs to be passed back to the
399 * caller for use so the __alloc_size hinting will be
402 resized = krealloc(data, *size, GFP_ATOMIC);
403 WARN_ON_ONCE(resized != data);
407 /* build_skb() variant which can operate on slab buffers.
408 * Note that this should be used sparingly as slab buffers
409 * cannot be combined efficiently by GRO!
411 struct sk_buff *slab_build_skb(void *data)
416 skb = kmem_cache_alloc(net_hotdata.skbuff_cache, GFP_ATOMIC);
420 memset(skb, 0, offsetof(struct sk_buff, tail));
421 data = __slab_build_skb(skb, data, &size);
422 __finalize_skb_around(skb, data, size);
426 EXPORT_SYMBOL(slab_build_skb);
428 /* Caller must provide SKB that is memset cleared */
429 static void __build_skb_around(struct sk_buff *skb, void *data,
430 unsigned int frag_size)
432 unsigned int size = frag_size;
434 /* frag_size == 0 is considered deprecated now. Callers
435 * using slab buffer should use slab_build_skb() instead.
437 if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
438 data = __slab_build_skb(skb, data, &size);
440 __finalize_skb_around(skb, data, size);
444 * __build_skb - build a network buffer
445 * @data: data buffer provided by caller
446 * @frag_size: size of data (must not be 0)
448 * Allocate a new &sk_buff. Caller provides space holding head and
449 * skb_shared_info. @data must have been allocated from the page
450 * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
451 * allocation is deprecated, and callers should use slab_build_skb()
453 * The return is the new skb buffer.
454 * On a failure the return is %NULL, and @data is not freed.
456 * Before IO, driver allocates only data buffer where NIC put incoming frame
457 * Driver should add room at head (NET_SKB_PAD) and
458 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
459 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
460 * before giving packet to stack.
461 * RX rings only contains data buffers, not full skbs.
463 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
467 skb = kmem_cache_alloc(net_hotdata.skbuff_cache, GFP_ATOMIC);
471 memset(skb, 0, offsetof(struct sk_buff, tail));
472 __build_skb_around(skb, data, frag_size);
477 /* build_skb() is wrapper over __build_skb(), that specifically
478 * takes care of skb->head and skb->pfmemalloc
480 struct sk_buff *build_skb(void *data, unsigned int frag_size)
482 struct sk_buff *skb = __build_skb(data, frag_size);
484 if (likely(skb && frag_size)) {
486 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
490 EXPORT_SYMBOL(build_skb);
493 * build_skb_around - build a network buffer around provided skb
494 * @skb: sk_buff provide by caller, must be memset cleared
495 * @data: data buffer provided by caller
496 * @frag_size: size of data
498 struct sk_buff *build_skb_around(struct sk_buff *skb,
499 void *data, unsigned int frag_size)
504 __build_skb_around(skb, data, frag_size);
508 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
512 EXPORT_SYMBOL(build_skb_around);
515 * __napi_build_skb - build a network buffer
516 * @data: data buffer provided by caller
517 * @frag_size: size of data
519 * Version of __build_skb() that uses NAPI percpu caches to obtain
520 * skbuff_head instead of inplace allocation.
522 * Returns a new &sk_buff on success, %NULL on allocation failure.
524 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
528 skb = napi_skb_cache_get();
532 memset(skb, 0, offsetof(struct sk_buff, tail));
533 __build_skb_around(skb, data, frag_size);
539 * napi_build_skb - build a network buffer
540 * @data: data buffer provided by caller
541 * @frag_size: size of data
543 * Version of __napi_build_skb() that takes care of skb->head_frag
544 * and skb->pfmemalloc when the data is a page or page fragment.
546 * Returns a new &sk_buff on success, %NULL on allocation failure.
548 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
550 struct sk_buff *skb = __napi_build_skb(data, frag_size);
552 if (likely(skb) && frag_size) {
554 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
559 EXPORT_SYMBOL(napi_build_skb);
562 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
563 * the caller if emergency pfmemalloc reserves are being used. If it is and
564 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
565 * may be used. Otherwise, the packet data may be discarded until enough
568 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
571 bool ret_pfmemalloc = false;
575 obj_size = SKB_HEAD_ALIGN(*size);
576 if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
577 !(flags & KMALLOC_NOT_NORMAL_BITS)) {
578 obj = kmem_cache_alloc_node(net_hotdata.skb_small_head_cache,
579 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
581 *size = SKB_SMALL_HEAD_CACHE_SIZE;
582 if (obj || !(gfp_pfmemalloc_allowed(flags)))
584 /* Try again but now we are using pfmemalloc reserves */
585 ret_pfmemalloc = true;
586 obj = kmem_cache_alloc_node(net_hotdata.skb_small_head_cache, flags, node);
590 obj_size = kmalloc_size_roundup(obj_size);
591 /* The following cast might truncate high-order bits of obj_size, this
592 * is harmless because kmalloc(obj_size >= 2^32) will fail anyway.
594 *size = (unsigned int)obj_size;
597 * Try a regular allocation, when that fails and we're not entitled
598 * to the reserves, fail.
600 obj = kmalloc_node_track_caller(obj_size,
601 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
603 if (obj || !(gfp_pfmemalloc_allowed(flags)))
606 /* Try again but now we are using pfmemalloc reserves */
607 ret_pfmemalloc = true;
608 obj = kmalloc_node_track_caller(obj_size, flags, node);
612 *pfmemalloc = ret_pfmemalloc;
617 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
618 * 'private' fields and also do memory statistics to find all the
624 * __alloc_skb - allocate a network buffer
625 * @size: size to allocate
626 * @gfp_mask: allocation mask
627 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
628 * instead of head cache and allocate a cloned (child) skb.
629 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
630 * allocations in case the data is required for writeback
631 * @node: numa node to allocate memory on
633 * Allocate a new &sk_buff. The returned buffer has no headroom and a
634 * tail room of at least size bytes. The object has a reference count
635 * of one. The return is the buffer. On a failure the return is %NULL.
637 * Buffers may only be allocated from interrupts using a @gfp_mask of
640 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
643 struct kmem_cache *cache;
648 cache = (flags & SKB_ALLOC_FCLONE)
649 ? net_hotdata.skbuff_fclone_cache : net_hotdata.skbuff_cache;
651 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
652 gfp_mask |= __GFP_MEMALLOC;
655 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
656 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
657 skb = napi_skb_cache_get();
659 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
664 /* We do our best to align skb_shared_info on a separate cache
665 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
666 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
667 * Both skb->head and skb_shared_info are cache line aligned.
669 data = kmalloc_reserve(&size, gfp_mask, node, &pfmemalloc);
672 /* kmalloc_size_roundup() might give us more room than requested.
673 * Put skb_shared_info exactly at the end of allocated zone,
674 * to allow max possible filling before reallocation.
676 prefetchw(data + SKB_WITH_OVERHEAD(size));
679 * Only clear those fields we need to clear, not those that we will
680 * actually initialise below. Hence, don't put any more fields after
681 * the tail pointer in struct sk_buff!
683 memset(skb, 0, offsetof(struct sk_buff, tail));
684 __build_skb_around(skb, data, size);
685 skb->pfmemalloc = pfmemalloc;
687 if (flags & SKB_ALLOC_FCLONE) {
688 struct sk_buff_fclones *fclones;
690 fclones = container_of(skb, struct sk_buff_fclones, skb1);
692 skb->fclone = SKB_FCLONE_ORIG;
693 refcount_set(&fclones->fclone_ref, 1);
699 kmem_cache_free(cache, skb);
702 EXPORT_SYMBOL(__alloc_skb);
705 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
706 * @dev: network device to receive on
707 * @len: length to allocate
708 * @gfp_mask: get_free_pages mask, passed to alloc_skb
710 * Allocate a new &sk_buff and assign it a usage count of one. The
711 * buffer has NET_SKB_PAD headroom built in. Users should allocate
712 * the headroom they think they need without accounting for the
713 * built in space. The built in space is used for optimisations.
715 * %NULL is returned if there is no free memory.
717 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
720 struct page_frag_cache *nc;
727 /* If requested length is either too small or too big,
728 * we use kmalloc() for skb->head allocation.
730 if (len <= SKB_WITH_OVERHEAD(1024) ||
731 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
732 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
733 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
739 len = SKB_HEAD_ALIGN(len);
741 if (sk_memalloc_socks())
742 gfp_mask |= __GFP_MEMALLOC;
744 if (in_hardirq() || irqs_disabled()) {
745 nc = this_cpu_ptr(&netdev_alloc_cache);
746 data = page_frag_alloc(nc, len, gfp_mask);
747 pfmemalloc = nc->pfmemalloc;
750 nc = this_cpu_ptr(&napi_alloc_cache.page);
751 data = page_frag_alloc(nc, len, gfp_mask);
752 pfmemalloc = nc->pfmemalloc;
759 skb = __build_skb(data, len);
760 if (unlikely(!skb)) {
770 skb_reserve(skb, NET_SKB_PAD);
776 EXPORT_SYMBOL(__netdev_alloc_skb);
779 * napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
780 * @napi: napi instance this buffer was allocated for
781 * @len: length to allocate
783 * Allocate a new sk_buff for use in NAPI receive. This buffer will
784 * attempt to allocate the head from a special reserved region used
785 * only for NAPI Rx allocation. By doing this we can save several
786 * CPU cycles by avoiding having to disable and re-enable IRQs.
788 * %NULL is returned if there is no free memory.
790 struct sk_buff *napi_alloc_skb(struct napi_struct *napi, unsigned int len)
792 gfp_t gfp_mask = GFP_ATOMIC | __GFP_NOWARN;
793 struct napi_alloc_cache *nc;
798 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
799 len += NET_SKB_PAD + NET_IP_ALIGN;
801 /* If requested length is either too small or too big,
802 * we use kmalloc() for skb->head allocation.
803 * When the small frag allocator is available, prefer it over kmalloc
804 * for small fragments
806 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
807 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
808 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
809 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
816 nc = this_cpu_ptr(&napi_alloc_cache);
818 if (sk_memalloc_socks())
819 gfp_mask |= __GFP_MEMALLOC;
821 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
822 /* we are artificially inflating the allocation size, but
823 * that is not as bad as it may look like, as:
824 * - 'len' less than GRO_MAX_HEAD makes little sense
825 * - On most systems, larger 'len' values lead to fragment
826 * size above 512 bytes
827 * - kmalloc would use the kmalloc-1k slab for such values
828 * - Builds with smaller GRO_MAX_HEAD will very likely do
829 * little networking, as that implies no WiFi and no
830 * tunnels support, and 32 bits arches.
834 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
835 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
837 len = SKB_HEAD_ALIGN(len);
839 data = page_frag_alloc(&nc->page, len, gfp_mask);
840 pfmemalloc = nc->page.pfmemalloc;
846 skb = __napi_build_skb(data, len);
847 if (unlikely(!skb)) {
857 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
858 skb->dev = napi->dev;
863 EXPORT_SYMBOL(napi_alloc_skb);
865 void skb_add_rx_frag_netmem(struct sk_buff *skb, int i, netmem_ref netmem,
866 int off, int size, unsigned int truesize)
868 DEBUG_NET_WARN_ON_ONCE(size > truesize);
870 skb_fill_netmem_desc(skb, i, netmem, off, size);
872 skb->data_len += size;
873 skb->truesize += truesize;
875 EXPORT_SYMBOL(skb_add_rx_frag_netmem);
877 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
878 unsigned int truesize)
880 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
882 DEBUG_NET_WARN_ON_ONCE(size > truesize);
884 skb_frag_size_add(frag, size);
886 skb->data_len += size;
887 skb->truesize += truesize;
889 EXPORT_SYMBOL(skb_coalesce_rx_frag);
891 static void skb_drop_list(struct sk_buff **listp)
893 kfree_skb_list(*listp);
897 static inline void skb_drop_fraglist(struct sk_buff *skb)
899 skb_drop_list(&skb_shinfo(skb)->frag_list);
902 static void skb_clone_fraglist(struct sk_buff *skb)
904 struct sk_buff *list;
906 skb_walk_frags(skb, list)
910 static bool is_pp_page(struct page *page)
912 return (page->pp_magic & ~0x3UL) == PP_SIGNATURE;
915 int skb_pp_cow_data(struct page_pool *pool, struct sk_buff **pskb,
916 unsigned int headroom)
918 #if IS_ENABLED(CONFIG_PAGE_POOL)
919 u32 size, truesize, len, max_head_size, off;
920 struct sk_buff *skb = *pskb, *nskb;
921 int err, i, head_off;
924 /* XDP does not support fraglist so we need to linearize
927 if (skb_has_frag_list(skb))
930 max_head_size = SKB_WITH_OVERHEAD(PAGE_SIZE - headroom);
931 if (skb->len > max_head_size + MAX_SKB_FRAGS * PAGE_SIZE)
934 size = min_t(u32, skb->len, max_head_size);
935 truesize = SKB_HEAD_ALIGN(size) + headroom;
936 data = page_pool_dev_alloc_va(pool, &truesize);
940 nskb = napi_build_skb(data, truesize);
942 page_pool_free_va(pool, data, true);
946 skb_reserve(nskb, headroom);
947 skb_copy_header(nskb, skb);
948 skb_mark_for_recycle(nskb);
950 err = skb_copy_bits(skb, 0, nskb->data, size);
957 head_off = skb_headroom(nskb) - skb_headroom(skb);
958 skb_headers_offset_update(nskb, head_off);
961 len = skb->len - off;
962 for (i = 0; i < MAX_SKB_FRAGS && off < skb->len; i++) {
966 size = min_t(u32, len, PAGE_SIZE);
969 page = page_pool_dev_alloc(pool, &page_off, &truesize);
975 skb_add_rx_frag(nskb, i, page, page_off, size, truesize);
976 err = skb_copy_bits(skb, off, page_address(page) + page_off,
995 EXPORT_SYMBOL(skb_pp_cow_data);
997 int skb_cow_data_for_xdp(struct page_pool *pool, struct sk_buff **pskb,
998 struct bpf_prog *prog)
1000 if (!prog->aux->xdp_has_frags)
1003 return skb_pp_cow_data(pool, pskb, XDP_PACKET_HEADROOM);
1005 EXPORT_SYMBOL(skb_cow_data_for_xdp);
1007 #if IS_ENABLED(CONFIG_PAGE_POOL)
1008 bool napi_pp_put_page(struct page *page)
1010 page = compound_head(page);
1012 /* page->pp_magic is OR'ed with PP_SIGNATURE after the allocation
1013 * in order to preserve any existing bits, such as bit 0 for the
1014 * head page of compound page and bit 1 for pfmemalloc page, so
1015 * mask those bits for freeing side when doing below checking,
1016 * and page_is_pfmemalloc() is checked in __page_pool_put_page()
1017 * to avoid recycling the pfmemalloc page.
1019 if (unlikely(!is_pp_page(page)))
1022 page_pool_put_full_page(page->pp, page, false);
1026 EXPORT_SYMBOL(napi_pp_put_page);
1029 static bool skb_pp_recycle(struct sk_buff *skb, void *data)
1031 if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
1033 return napi_pp_put_page(virt_to_page(data));
1037 * skb_pp_frag_ref() - Increase fragment references of a page pool aware skb
1038 * @skb: page pool aware skb
1040 * Increase the fragment reference count (pp_ref_count) of a skb. This is
1041 * intended to gain fragment references only for page pool aware skbs,
1042 * i.e. when skb->pp_recycle is true, and not for fragments in a
1043 * non-pp-recycling skb. It has a fallback to increase references on normal
1044 * pages, as page pool aware skbs may also have normal page fragments.
1046 static int skb_pp_frag_ref(struct sk_buff *skb)
1048 struct skb_shared_info *shinfo;
1049 struct page *head_page;
1052 if (!skb->pp_recycle)
1055 shinfo = skb_shinfo(skb);
1057 for (i = 0; i < shinfo->nr_frags; i++) {
1058 head_page = compound_head(skb_frag_page(&shinfo->frags[i]));
1059 if (likely(is_pp_page(head_page)))
1060 page_pool_ref_page(head_page);
1062 page_ref_inc(head_page);
1067 static void skb_kfree_head(void *head, unsigned int end_offset)
1069 if (end_offset == SKB_SMALL_HEAD_HEADROOM)
1070 kmem_cache_free(net_hotdata.skb_small_head_cache, head);
1075 static void skb_free_head(struct sk_buff *skb)
1077 unsigned char *head = skb->head;
1079 if (skb->head_frag) {
1080 if (skb_pp_recycle(skb, head))
1082 skb_free_frag(head);
1084 skb_kfree_head(head, skb_end_offset(skb));
1088 static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason)
1090 struct skb_shared_info *shinfo = skb_shinfo(skb);
1093 if (!skb_data_unref(skb, shinfo))
1096 if (skb_zcopy(skb)) {
1097 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
1099 skb_zcopy_clear(skb, true);
1104 for (i = 0; i < shinfo->nr_frags; i++)
1105 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
1108 if (shinfo->frag_list)
1109 kfree_skb_list_reason(shinfo->frag_list, reason);
1113 /* When we clone an SKB we copy the reycling bit. The pp_recycle
1114 * bit is only set on the head though, so in order to avoid races
1115 * while trying to recycle fragments on __skb_frag_unref() we need
1116 * to make one SKB responsible for triggering the recycle path.
1117 * So disable the recycling bit if an SKB is cloned and we have
1118 * additional references to the fragmented part of the SKB.
1119 * Eventually the last SKB will have the recycling bit set and it's
1120 * dataref set to 0, which will trigger the recycling
1122 skb->pp_recycle = 0;
1126 * Free an skbuff by memory without cleaning the state.
1128 static void kfree_skbmem(struct sk_buff *skb)
1130 struct sk_buff_fclones *fclones;
1132 switch (skb->fclone) {
1133 case SKB_FCLONE_UNAVAILABLE:
1134 kmem_cache_free(net_hotdata.skbuff_cache, skb);
1137 case SKB_FCLONE_ORIG:
1138 fclones = container_of(skb, struct sk_buff_fclones, skb1);
1140 /* We usually free the clone (TX completion) before original skb
1141 * This test would have no chance to be true for the clone,
1142 * while here, branch prediction will be good.
1144 if (refcount_read(&fclones->fclone_ref) == 1)
1148 default: /* SKB_FCLONE_CLONE */
1149 fclones = container_of(skb, struct sk_buff_fclones, skb2);
1152 if (!refcount_dec_and_test(&fclones->fclone_ref))
1155 kmem_cache_free(net_hotdata.skbuff_fclone_cache, fclones);
1158 void skb_release_head_state(struct sk_buff *skb)
1161 if (skb->destructor) {
1162 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
1163 skb->destructor(skb);
1165 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
1166 nf_conntrack_put(skb_nfct(skb));
1171 /* Free everything but the sk_buff shell. */
1172 static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason)
1174 skb_release_head_state(skb);
1175 if (likely(skb->head))
1176 skb_release_data(skb, reason);
1180 * __kfree_skb - private function
1183 * Free an sk_buff. Release anything attached to the buffer.
1184 * Clean the state. This is an internal helper function. Users should
1185 * always call kfree_skb
1188 void __kfree_skb(struct sk_buff *skb)
1190 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
1193 EXPORT_SYMBOL(__kfree_skb);
1195 static __always_inline
1196 bool __kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1198 if (unlikely(!skb_unref(skb)))
1201 DEBUG_NET_WARN_ON_ONCE(reason == SKB_NOT_DROPPED_YET ||
1202 u32_get_bits(reason,
1203 SKB_DROP_REASON_SUBSYS_MASK) >=
1204 SKB_DROP_REASON_SUBSYS_NUM);
1206 if (reason == SKB_CONSUMED)
1207 trace_consume_skb(skb, __builtin_return_address(0));
1209 trace_kfree_skb(skb, __builtin_return_address(0), reason);
1214 * kfree_skb_reason - free an sk_buff with special reason
1215 * @skb: buffer to free
1216 * @reason: reason why this skb is dropped
1218 * Drop a reference to the buffer and free it if the usage count has
1219 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
1223 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1225 if (__kfree_skb_reason(skb, reason))
1228 EXPORT_SYMBOL(kfree_skb_reason);
1230 #define KFREE_SKB_BULK_SIZE 16
1232 struct skb_free_array {
1233 unsigned int skb_count;
1234 void *skb_array[KFREE_SKB_BULK_SIZE];
1237 static void kfree_skb_add_bulk(struct sk_buff *skb,
1238 struct skb_free_array *sa,
1239 enum skb_drop_reason reason)
1241 /* if SKB is a clone, don't handle this case */
1242 if (unlikely(skb->fclone != SKB_FCLONE_UNAVAILABLE)) {
1247 skb_release_all(skb, reason);
1248 sa->skb_array[sa->skb_count++] = skb;
1250 if (unlikely(sa->skb_count == KFREE_SKB_BULK_SIZE)) {
1251 kmem_cache_free_bulk(net_hotdata.skbuff_cache, KFREE_SKB_BULK_SIZE,
1258 kfree_skb_list_reason(struct sk_buff *segs, enum skb_drop_reason reason)
1260 struct skb_free_array sa;
1265 struct sk_buff *next = segs->next;
1267 if (__kfree_skb_reason(segs, reason)) {
1268 skb_poison_list(segs);
1269 kfree_skb_add_bulk(segs, &sa, reason);
1276 kmem_cache_free_bulk(net_hotdata.skbuff_cache, sa.skb_count, sa.skb_array);
1278 EXPORT_SYMBOL(kfree_skb_list_reason);
1280 /* Dump skb information and contents.
1282 * Must only be called from net_ratelimit()-ed paths.
1284 * Dumps whole packets if full_pkt, only headers otherwise.
1286 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
1288 struct skb_shared_info *sh = skb_shinfo(skb);
1289 struct net_device *dev = skb->dev;
1290 struct sock *sk = skb->sk;
1291 struct sk_buff *list_skb;
1292 bool has_mac, has_trans;
1293 int headroom, tailroom;
1294 int i, len, seg_len;
1299 len = min_t(int, skb->len, MAX_HEADER + 128);
1301 headroom = skb_headroom(skb);
1302 tailroom = skb_tailroom(skb);
1304 has_mac = skb_mac_header_was_set(skb);
1305 has_trans = skb_transport_header_was_set(skb);
1307 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
1308 "mac=(%d,%d) mac_len=%u net=(%d,%d) trans=%d\n"
1309 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
1310 "csum(0x%x start=%u offset=%u ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
1311 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n"
1312 "priority=0x%x mark=0x%x alloc_cpu=%u vlan_all=0x%x\n"
1313 "encapsulation=%d inner(proto=0x%04x, mac=%u, net=%u, trans=%u)\n",
1314 level, skb->len, headroom, skb_headlen(skb), tailroom,
1315 has_mac ? skb->mac_header : -1,
1316 has_mac ? skb_mac_header_len(skb) : -1,
1318 skb->network_header,
1319 has_trans ? skb_network_header_len(skb) : -1,
1320 has_trans ? skb->transport_header : -1,
1321 sh->tx_flags, sh->nr_frags,
1322 sh->gso_size, sh->gso_type, sh->gso_segs,
1323 skb->csum, skb->csum_start, skb->csum_offset, skb->ip_summed,
1324 skb->csum_complete_sw, skb->csum_valid, skb->csum_level,
1325 skb->hash, skb->sw_hash, skb->l4_hash,
1326 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif,
1327 skb->priority, skb->mark, skb->alloc_cpu, skb->vlan_all,
1328 skb->encapsulation, skb->inner_protocol, skb->inner_mac_header,
1329 skb->inner_network_header, skb->inner_transport_header);
1332 printk("%sdev name=%s feat=%pNF\n",
1333 level, dev->name, &dev->features);
1335 printk("%ssk family=%hu type=%u proto=%u\n",
1336 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
1338 if (full_pkt && headroom)
1339 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
1340 16, 1, skb->head, headroom, false);
1342 seg_len = min_t(int, skb_headlen(skb), len);
1344 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
1345 16, 1, skb->data, seg_len, false);
1348 if (full_pkt && tailroom)
1349 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
1350 16, 1, skb_tail_pointer(skb), tailroom, false);
1352 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
1353 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1354 u32 p_off, p_len, copied;
1358 skb_frag_foreach_page(frag, skb_frag_off(frag),
1359 skb_frag_size(frag), p, p_off, p_len,
1361 seg_len = min_t(int, p_len, len);
1362 vaddr = kmap_atomic(p);
1363 print_hex_dump(level, "skb frag: ",
1365 16, 1, vaddr + p_off, seg_len, false);
1366 kunmap_atomic(vaddr);
1373 if (full_pkt && skb_has_frag_list(skb)) {
1374 printk("skb fraglist:\n");
1375 skb_walk_frags(skb, list_skb)
1376 skb_dump(level, list_skb, true);
1379 EXPORT_SYMBOL(skb_dump);
1382 * skb_tx_error - report an sk_buff xmit error
1383 * @skb: buffer that triggered an error
1385 * Report xmit error if a device callback is tracking this skb.
1386 * skb must be freed afterwards.
1388 void skb_tx_error(struct sk_buff *skb)
1391 skb_zcopy_downgrade_managed(skb);
1392 skb_zcopy_clear(skb, true);
1395 EXPORT_SYMBOL(skb_tx_error);
1397 #ifdef CONFIG_TRACEPOINTS
1399 * consume_skb - free an skbuff
1400 * @skb: buffer to free
1402 * Drop a ref to the buffer and free it if the usage count has hit zero
1403 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1404 * is being dropped after a failure and notes that
1406 void consume_skb(struct sk_buff *skb)
1408 if (!skb_unref(skb))
1411 trace_consume_skb(skb, __builtin_return_address(0));
1414 EXPORT_SYMBOL(consume_skb);
1418 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1419 * @skb: buffer to free
1421 * Alike consume_skb(), but this variant assumes that this is the last
1422 * skb reference and all the head states have been already dropped
1424 void __consume_stateless_skb(struct sk_buff *skb)
1426 trace_consume_skb(skb, __builtin_return_address(0));
1427 skb_release_data(skb, SKB_CONSUMED);
1431 static void napi_skb_cache_put(struct sk_buff *skb)
1433 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1436 if (!kasan_mempool_poison_object(skb))
1439 nc->skb_cache[nc->skb_count++] = skb;
1441 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1442 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1443 kasan_mempool_unpoison_object(nc->skb_cache[i],
1444 kmem_cache_size(net_hotdata.skbuff_cache));
1446 kmem_cache_free_bulk(net_hotdata.skbuff_cache, NAPI_SKB_CACHE_HALF,
1447 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1448 nc->skb_count = NAPI_SKB_CACHE_HALF;
1452 void __napi_kfree_skb(struct sk_buff *skb, enum skb_drop_reason reason)
1454 skb_release_all(skb, reason);
1455 napi_skb_cache_put(skb);
1458 void napi_skb_free_stolen_head(struct sk_buff *skb)
1460 if (unlikely(skb->slow_gro)) {
1467 napi_skb_cache_put(skb);
1470 void napi_consume_skb(struct sk_buff *skb, int budget)
1472 /* Zero budget indicate non-NAPI context called us, like netpoll */
1473 if (unlikely(!budget)) {
1474 dev_consume_skb_any(skb);
1478 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1480 if (!skb_unref(skb))
1483 /* if reaching here SKB is ready to free */
1484 trace_consume_skb(skb, __builtin_return_address(0));
1486 /* if SKB is a clone, don't handle this case */
1487 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1492 skb_release_all(skb, SKB_CONSUMED);
1493 napi_skb_cache_put(skb);
1495 EXPORT_SYMBOL(napi_consume_skb);
1497 /* Make sure a field is contained by headers group */
1498 #define CHECK_SKB_FIELD(field) \
1499 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1500 offsetof(struct sk_buff, headers.field)); \
1502 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1504 new->tstamp = old->tstamp;
1505 /* We do not copy old->sk */
1506 new->dev = old->dev;
1507 memcpy(new->cb, old->cb, sizeof(old->cb));
1508 skb_dst_copy(new, old);
1509 __skb_ext_copy(new, old);
1510 __nf_copy(new, old, false);
1512 /* Note : this field could be in the headers group.
1513 * It is not yet because we do not want to have a 16 bit hole
1515 new->queue_mapping = old->queue_mapping;
1517 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1518 CHECK_SKB_FIELD(protocol);
1519 CHECK_SKB_FIELD(csum);
1520 CHECK_SKB_FIELD(hash);
1521 CHECK_SKB_FIELD(priority);
1522 CHECK_SKB_FIELD(skb_iif);
1523 CHECK_SKB_FIELD(vlan_proto);
1524 CHECK_SKB_FIELD(vlan_tci);
1525 CHECK_SKB_FIELD(transport_header);
1526 CHECK_SKB_FIELD(network_header);
1527 CHECK_SKB_FIELD(mac_header);
1528 CHECK_SKB_FIELD(inner_protocol);
1529 CHECK_SKB_FIELD(inner_transport_header);
1530 CHECK_SKB_FIELD(inner_network_header);
1531 CHECK_SKB_FIELD(inner_mac_header);
1532 CHECK_SKB_FIELD(mark);
1533 #ifdef CONFIG_NETWORK_SECMARK
1534 CHECK_SKB_FIELD(secmark);
1536 #ifdef CONFIG_NET_RX_BUSY_POLL
1537 CHECK_SKB_FIELD(napi_id);
1539 CHECK_SKB_FIELD(alloc_cpu);
1541 CHECK_SKB_FIELD(sender_cpu);
1543 #ifdef CONFIG_NET_SCHED
1544 CHECK_SKB_FIELD(tc_index);
1550 * You should not add any new code to this function. Add it to
1551 * __copy_skb_header above instead.
1553 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1555 #define C(x) n->x = skb->x
1557 n->next = n->prev = NULL;
1559 __copy_skb_header(n, skb);
1564 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1570 n->destructor = NULL;
1577 refcount_set(&n->users, 1);
1579 atomic_inc(&(skb_shinfo(skb)->dataref));
1587 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1588 * @first: first sk_buff of the msg
1590 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1594 n = alloc_skb(0, GFP_ATOMIC);
1598 n->len = first->len;
1599 n->data_len = first->len;
1600 n->truesize = first->truesize;
1602 skb_shinfo(n)->frag_list = first;
1604 __copy_skb_header(n, first);
1605 n->destructor = NULL;
1609 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1612 * skb_morph - morph one skb into another
1613 * @dst: the skb to receive the contents
1614 * @src: the skb to supply the contents
1616 * This is identical to skb_clone except that the target skb is
1617 * supplied by the user.
1619 * The target skb is returned upon exit.
1621 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1623 skb_release_all(dst, SKB_CONSUMED);
1624 return __skb_clone(dst, src);
1626 EXPORT_SYMBOL_GPL(skb_morph);
1628 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1630 unsigned long max_pg, num_pg, new_pg, old_pg, rlim;
1631 struct user_struct *user;
1633 if (capable(CAP_IPC_LOCK) || !size)
1636 rlim = rlimit(RLIMIT_MEMLOCK);
1637 if (rlim == RLIM_INFINITY)
1640 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1641 max_pg = rlim >> PAGE_SHIFT;
1642 user = mmp->user ? : current_user();
1644 old_pg = atomic_long_read(&user->locked_vm);
1646 new_pg = old_pg + num_pg;
1647 if (new_pg > max_pg)
1649 } while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1652 mmp->user = get_uid(user);
1653 mmp->num_pg = num_pg;
1655 mmp->num_pg += num_pg;
1660 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1662 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1665 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1666 free_uid(mmp->user);
1669 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1671 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1673 struct ubuf_info_msgzc *uarg;
1674 struct sk_buff *skb;
1676 WARN_ON_ONCE(!in_task());
1678 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1682 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1683 uarg = (void *)skb->cb;
1684 uarg->mmp.user = NULL;
1686 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1691 uarg->ubuf.callback = msg_zerocopy_callback;
1692 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1694 uarg->bytelen = size;
1696 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1697 refcount_set(&uarg->ubuf.refcnt, 1);
1703 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1705 return container_of((void *)uarg, struct sk_buff, cb);
1708 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1709 struct ubuf_info *uarg)
1712 struct ubuf_info_msgzc *uarg_zc;
1713 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1716 /* there might be non MSG_ZEROCOPY users */
1717 if (uarg->callback != msg_zerocopy_callback)
1720 /* realloc only when socket is locked (TCP, UDP cork),
1721 * so uarg->len and sk_zckey access is serialized
1723 if (!sock_owned_by_user(sk)) {
1728 uarg_zc = uarg_to_msgzc(uarg);
1729 bytelen = uarg_zc->bytelen + size;
1730 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1731 /* TCP can create new skb to attach new uarg */
1732 if (sk->sk_type == SOCK_STREAM)
1737 next = (u32)atomic_read(&sk->sk_zckey);
1738 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1739 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1742 uarg_zc->bytelen = bytelen;
1743 atomic_set(&sk->sk_zckey, ++next);
1745 /* no extra ref when appending to datagram (MSG_MORE) */
1746 if (sk->sk_type == SOCK_STREAM)
1747 net_zcopy_get(uarg);
1754 return msg_zerocopy_alloc(sk, size);
1756 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1758 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1760 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1764 old_lo = serr->ee.ee_info;
1765 old_hi = serr->ee.ee_data;
1766 sum_len = old_hi - old_lo + 1ULL + len;
1768 if (sum_len >= (1ULL << 32))
1771 if (lo != old_hi + 1)
1774 serr->ee.ee_data += len;
1778 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1780 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1781 struct sock_exterr_skb *serr;
1782 struct sock *sk = skb->sk;
1783 struct sk_buff_head *q;
1784 unsigned long flags;
1789 mm_unaccount_pinned_pages(&uarg->mmp);
1791 /* if !len, there was only 1 call, and it was aborted
1792 * so do not queue a completion notification
1794 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1799 hi = uarg->id + len - 1;
1800 is_zerocopy = uarg->zerocopy;
1802 serr = SKB_EXT_ERR(skb);
1803 memset(serr, 0, sizeof(*serr));
1804 serr->ee.ee_errno = 0;
1805 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1806 serr->ee.ee_data = hi;
1807 serr->ee.ee_info = lo;
1809 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1811 q = &sk->sk_error_queue;
1812 spin_lock_irqsave(&q->lock, flags);
1813 tail = skb_peek_tail(q);
1814 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1815 !skb_zerocopy_notify_extend(tail, lo, len)) {
1816 __skb_queue_tail(q, skb);
1819 spin_unlock_irqrestore(&q->lock, flags);
1821 sk_error_report(sk);
1828 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1831 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1833 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1835 if (refcount_dec_and_test(&uarg->refcnt))
1836 __msg_zerocopy_callback(uarg_zc);
1838 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1840 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1842 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1844 atomic_dec(&sk->sk_zckey);
1845 uarg_to_msgzc(uarg)->len--;
1848 msg_zerocopy_callback(NULL, uarg, true);
1850 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1852 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1853 struct msghdr *msg, int len,
1854 struct ubuf_info *uarg)
1856 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1857 int err, orig_len = skb->len;
1859 /* An skb can only point to one uarg. This edge case happens when
1860 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1862 if (orig_uarg && uarg != orig_uarg)
1865 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1866 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1867 struct sock *save_sk = skb->sk;
1869 /* Streams do not free skb on error. Reset to prev state. */
1870 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1872 ___pskb_trim(skb, orig_len);
1877 skb_zcopy_set(skb, uarg, NULL);
1878 return skb->len - orig_len;
1880 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1882 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1886 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1887 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1888 skb_frag_ref(skb, i);
1890 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1892 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1895 if (skb_zcopy(orig)) {
1896 if (skb_zcopy(nskb)) {
1897 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1902 if (skb_uarg(nskb) == skb_uarg(orig))
1904 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1907 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1913 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1914 * @skb: the skb to modify
1915 * @gfp_mask: allocation priority
1917 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1918 * It will copy all frags into kernel and drop the reference
1919 * to userspace pages.
1921 * If this function is called from an interrupt gfp_mask() must be
1924 * Returns 0 on success or a negative error code on failure
1925 * to allocate kernel memory to copy to.
1927 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1929 int num_frags = skb_shinfo(skb)->nr_frags;
1930 struct page *page, *head = NULL;
1931 int i, order, psize, new_frags;
1934 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1940 /* We might have to allocate high order pages, so compute what minimum
1941 * page order is needed.
1944 while ((PAGE_SIZE << order) * MAX_SKB_FRAGS < __skb_pagelen(skb))
1946 psize = (PAGE_SIZE << order);
1948 new_frags = (__skb_pagelen(skb) + psize - 1) >> (PAGE_SHIFT + order);
1949 for (i = 0; i < new_frags; i++) {
1950 page = alloc_pages(gfp_mask | __GFP_COMP, order);
1953 struct page *next = (struct page *)page_private(head);
1959 set_page_private(page, (unsigned long)head);
1965 for (i = 0; i < num_frags; i++) {
1966 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1967 u32 p_off, p_len, copied;
1971 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1972 p, p_off, p_len, copied) {
1974 vaddr = kmap_atomic(p);
1976 while (done < p_len) {
1977 if (d_off == psize) {
1979 page = (struct page *)page_private(page);
1981 copy = min_t(u32, psize - d_off, p_len - done);
1982 memcpy(page_address(page) + d_off,
1983 vaddr + p_off + done, copy);
1987 kunmap_atomic(vaddr);
1991 /* skb frags release userspace buffers */
1992 for (i = 0; i < num_frags; i++)
1993 skb_frag_unref(skb, i);
1995 /* skb frags point to kernel buffers */
1996 for (i = 0; i < new_frags - 1; i++) {
1997 __skb_fill_netmem_desc(skb, i, page_to_netmem(head), 0, psize);
1998 head = (struct page *)page_private(head);
2000 __skb_fill_netmem_desc(skb, new_frags - 1, page_to_netmem(head), 0,
2002 skb_shinfo(skb)->nr_frags = new_frags;
2005 skb_zcopy_clear(skb, false);
2008 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
2011 * skb_clone - duplicate an sk_buff
2012 * @skb: buffer to clone
2013 * @gfp_mask: allocation priority
2015 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
2016 * copies share the same packet data but not structure. The new
2017 * buffer has a reference count of 1. If the allocation fails the
2018 * function returns %NULL otherwise the new buffer is returned.
2020 * If this function is called from an interrupt gfp_mask() must be
2024 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
2026 struct sk_buff_fclones *fclones = container_of(skb,
2027 struct sk_buff_fclones,
2031 if (skb_orphan_frags(skb, gfp_mask))
2034 if (skb->fclone == SKB_FCLONE_ORIG &&
2035 refcount_read(&fclones->fclone_ref) == 1) {
2037 refcount_set(&fclones->fclone_ref, 2);
2038 n->fclone = SKB_FCLONE_CLONE;
2040 if (skb_pfmemalloc(skb))
2041 gfp_mask |= __GFP_MEMALLOC;
2043 n = kmem_cache_alloc(net_hotdata.skbuff_cache, gfp_mask);
2047 n->fclone = SKB_FCLONE_UNAVAILABLE;
2050 return __skb_clone(n, skb);
2052 EXPORT_SYMBOL(skb_clone);
2054 void skb_headers_offset_update(struct sk_buff *skb, int off)
2056 /* Only adjust this if it actually is csum_start rather than csum */
2057 if (skb->ip_summed == CHECKSUM_PARTIAL)
2058 skb->csum_start += off;
2059 /* {transport,network,mac}_header and tail are relative to skb->head */
2060 skb->transport_header += off;
2061 skb->network_header += off;
2062 if (skb_mac_header_was_set(skb))
2063 skb->mac_header += off;
2064 skb->inner_transport_header += off;
2065 skb->inner_network_header += off;
2066 skb->inner_mac_header += off;
2068 EXPORT_SYMBOL(skb_headers_offset_update);
2070 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
2072 __copy_skb_header(new, old);
2074 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
2075 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
2076 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
2078 EXPORT_SYMBOL(skb_copy_header);
2080 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
2082 if (skb_pfmemalloc(skb))
2083 return SKB_ALLOC_RX;
2088 * skb_copy - create private copy of an sk_buff
2089 * @skb: buffer to copy
2090 * @gfp_mask: allocation priority
2092 * Make a copy of both an &sk_buff and its data. This is used when the
2093 * caller wishes to modify the data and needs a private copy of the
2094 * data to alter. Returns %NULL on failure or the pointer to the buffer
2095 * on success. The returned buffer has a reference count of 1.
2097 * As by-product this function converts non-linear &sk_buff to linear
2098 * one, so that &sk_buff becomes completely private and caller is allowed
2099 * to modify all the data of returned buffer. This means that this
2100 * function is not recommended for use in circumstances when only
2101 * header is going to be modified. Use pskb_copy() instead.
2104 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
2106 int headerlen = skb_headroom(skb);
2107 unsigned int size = skb_end_offset(skb) + skb->data_len;
2108 struct sk_buff *n = __alloc_skb(size, gfp_mask,
2109 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
2114 /* Set the data pointer */
2115 skb_reserve(n, headerlen);
2116 /* Set the tail pointer and length */
2117 skb_put(n, skb->len);
2119 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
2121 skb_copy_header(n, skb);
2124 EXPORT_SYMBOL(skb_copy);
2127 * __pskb_copy_fclone - create copy of an sk_buff with private head.
2128 * @skb: buffer to copy
2129 * @headroom: headroom of new skb
2130 * @gfp_mask: allocation priority
2131 * @fclone: if true allocate the copy of the skb from the fclone
2132 * cache instead of the head cache; it is recommended to set this
2133 * to true for the cases where the copy will likely be cloned
2135 * Make a copy of both an &sk_buff and part of its data, located
2136 * in header. Fragmented data remain shared. This is used when
2137 * the caller wishes to modify only header of &sk_buff and needs
2138 * private copy of the header to alter. Returns %NULL on failure
2139 * or the pointer to the buffer on success.
2140 * The returned buffer has a reference count of 1.
2143 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
2144 gfp_t gfp_mask, bool fclone)
2146 unsigned int size = skb_headlen(skb) + headroom;
2147 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
2148 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
2153 /* Set the data pointer */
2154 skb_reserve(n, headroom);
2155 /* Set the tail pointer and length */
2156 skb_put(n, skb_headlen(skb));
2157 /* Copy the bytes */
2158 skb_copy_from_linear_data(skb, n->data, n->len);
2160 n->truesize += skb->data_len;
2161 n->data_len = skb->data_len;
2164 if (skb_shinfo(skb)->nr_frags) {
2167 if (skb_orphan_frags(skb, gfp_mask) ||
2168 skb_zerocopy_clone(n, skb, gfp_mask)) {
2173 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2174 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
2175 skb_frag_ref(skb, i);
2177 skb_shinfo(n)->nr_frags = i;
2180 if (skb_has_frag_list(skb)) {
2181 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
2182 skb_clone_fraglist(n);
2185 skb_copy_header(n, skb);
2189 EXPORT_SYMBOL(__pskb_copy_fclone);
2192 * pskb_expand_head - reallocate header of &sk_buff
2193 * @skb: buffer to reallocate
2194 * @nhead: room to add at head
2195 * @ntail: room to add at tail
2196 * @gfp_mask: allocation priority
2198 * Expands (or creates identical copy, if @nhead and @ntail are zero)
2199 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
2200 * reference count of 1. Returns zero in the case of success or error,
2201 * if expansion failed. In the last case, &sk_buff is not changed.
2203 * All the pointers pointing into skb header may change and must be
2204 * reloaded after call to this function.
2207 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
2210 unsigned int osize = skb_end_offset(skb);
2211 unsigned int size = osize + nhead + ntail;
2218 BUG_ON(skb_shared(skb));
2220 skb_zcopy_downgrade_managed(skb);
2222 if (skb_pfmemalloc(skb))
2223 gfp_mask |= __GFP_MEMALLOC;
2225 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
2228 size = SKB_WITH_OVERHEAD(size);
2230 /* Copy only real data... and, alas, header. This should be
2231 * optimized for the cases when header is void.
2233 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
2235 memcpy((struct skb_shared_info *)(data + size),
2237 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
2240 * if shinfo is shared we must drop the old head gracefully, but if it
2241 * is not we can just drop the old head and let the existing refcount
2242 * be since all we did is relocate the values
2244 if (skb_cloned(skb)) {
2245 if (skb_orphan_frags(skb, gfp_mask))
2248 refcount_inc(&skb_uarg(skb)->refcnt);
2249 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2250 skb_frag_ref(skb, i);
2252 if (skb_has_frag_list(skb))
2253 skb_clone_fraglist(skb);
2255 skb_release_data(skb, SKB_CONSUMED);
2259 off = (data + nhead) - skb->head;
2265 skb_set_end_offset(skb, size);
2266 #ifdef NET_SKBUFF_DATA_USES_OFFSET
2270 skb_headers_offset_update(skb, nhead);
2274 atomic_set(&skb_shinfo(skb)->dataref, 1);
2276 skb_metadata_clear(skb);
2278 /* It is not generally safe to change skb->truesize.
2279 * For the moment, we really care of rx path, or
2280 * when skb is orphaned (not attached to a socket).
2282 if (!skb->sk || skb->destructor == sock_edemux)
2283 skb->truesize += size - osize;
2288 skb_kfree_head(data, size);
2292 EXPORT_SYMBOL(pskb_expand_head);
2294 /* Make private copy of skb with writable head and some headroom */
2296 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
2298 struct sk_buff *skb2;
2299 int delta = headroom - skb_headroom(skb);
2302 skb2 = pskb_copy(skb, GFP_ATOMIC);
2304 skb2 = skb_clone(skb, GFP_ATOMIC);
2305 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
2313 EXPORT_SYMBOL(skb_realloc_headroom);
2315 /* Note: We plan to rework this in linux-6.4 */
2316 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
2318 unsigned int saved_end_offset, saved_truesize;
2319 struct skb_shared_info *shinfo;
2322 saved_end_offset = skb_end_offset(skb);
2323 saved_truesize = skb->truesize;
2325 res = pskb_expand_head(skb, 0, 0, pri);
2329 skb->truesize = saved_truesize;
2331 if (likely(skb_end_offset(skb) == saved_end_offset))
2334 /* We can not change skb->end if the original or new value
2335 * is SKB_SMALL_HEAD_HEADROOM, as it might break skb_kfree_head().
2337 if (saved_end_offset == SKB_SMALL_HEAD_HEADROOM ||
2338 skb_end_offset(skb) == SKB_SMALL_HEAD_HEADROOM) {
2339 /* We think this path should not be taken.
2340 * Add a temporary trace to warn us just in case.
2342 pr_err_once("__skb_unclone_keeptruesize() skb_end_offset() %u -> %u\n",
2343 saved_end_offset, skb_end_offset(skb));
2348 shinfo = skb_shinfo(skb);
2350 /* We are about to change back skb->end,
2351 * we need to move skb_shinfo() to its new location.
2353 memmove(skb->head + saved_end_offset,
2355 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
2357 skb_set_end_offset(skb, saved_end_offset);
2363 * skb_expand_head - reallocate header of &sk_buff
2364 * @skb: buffer to reallocate
2365 * @headroom: needed headroom
2367 * Unlike skb_realloc_headroom, this one does not allocate a new skb
2368 * if possible; copies skb->sk to new skb as needed
2369 * and frees original skb in case of failures.
2371 * It expect increased headroom and generates warning otherwise.
2374 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2376 int delta = headroom - skb_headroom(skb);
2377 int osize = skb_end_offset(skb);
2378 struct sock *sk = skb->sk;
2380 if (WARN_ONCE(delta <= 0,
2381 "%s is expecting an increase in the headroom", __func__))
2384 delta = SKB_DATA_ALIGN(delta);
2385 /* pskb_expand_head() might crash, if skb is shared. */
2386 if (skb_shared(skb) || !is_skb_wmem(skb)) {
2387 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2389 if (unlikely(!nskb))
2393 skb_set_owner_w(nskb, sk);
2397 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2400 if (sk && is_skb_wmem(skb)) {
2401 delta = skb_end_offset(skb) - osize;
2402 refcount_add(delta, &sk->sk_wmem_alloc);
2403 skb->truesize += delta;
2411 EXPORT_SYMBOL(skb_expand_head);
2414 * skb_copy_expand - copy and expand sk_buff
2415 * @skb: buffer to copy
2416 * @newheadroom: new free bytes at head
2417 * @newtailroom: new free bytes at tail
2418 * @gfp_mask: allocation priority
2420 * Make a copy of both an &sk_buff and its data and while doing so
2421 * allocate additional space.
2423 * This is used when the caller wishes to modify the data and needs a
2424 * private copy of the data to alter as well as more space for new fields.
2425 * Returns %NULL on failure or the pointer to the buffer
2426 * on success. The returned buffer has a reference count of 1.
2428 * You must pass %GFP_ATOMIC as the allocation priority if this function
2429 * is called from an interrupt.
2431 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2432 int newheadroom, int newtailroom,
2436 * Allocate the copy buffer
2438 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2439 gfp_mask, skb_alloc_rx_flag(skb),
2441 int oldheadroom = skb_headroom(skb);
2442 int head_copy_len, head_copy_off;
2447 skb_reserve(n, newheadroom);
2449 /* Set the tail pointer and length */
2450 skb_put(n, skb->len);
2452 head_copy_len = oldheadroom;
2454 if (newheadroom <= head_copy_len)
2455 head_copy_len = newheadroom;
2457 head_copy_off = newheadroom - head_copy_len;
2459 /* Copy the linear header and data. */
2460 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2461 skb->len + head_copy_len));
2463 skb_copy_header(n, skb);
2465 skb_headers_offset_update(n, newheadroom - oldheadroom);
2469 EXPORT_SYMBOL(skb_copy_expand);
2472 * __skb_pad - zero pad the tail of an skb
2473 * @skb: buffer to pad
2474 * @pad: space to pad
2475 * @free_on_error: free buffer on error
2477 * Ensure that a buffer is followed by a padding area that is zero
2478 * filled. Used by network drivers which may DMA or transfer data
2479 * beyond the buffer end onto the wire.
2481 * May return error in out of memory cases. The skb is freed on error
2482 * if @free_on_error is true.
2485 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2490 /* If the skbuff is non linear tailroom is always zero.. */
2491 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2492 memset(skb->data+skb->len, 0, pad);
2496 ntail = skb->data_len + pad - (skb->end - skb->tail);
2497 if (likely(skb_cloned(skb) || ntail > 0)) {
2498 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2503 /* FIXME: The use of this function with non-linear skb's really needs
2506 err = skb_linearize(skb);
2510 memset(skb->data + skb->len, 0, pad);
2518 EXPORT_SYMBOL(__skb_pad);
2521 * pskb_put - add data to the tail of a potentially fragmented buffer
2522 * @skb: start of the buffer to use
2523 * @tail: tail fragment of the buffer to use
2524 * @len: amount of data to add
2526 * This function extends the used data area of the potentially
2527 * fragmented buffer. @tail must be the last fragment of @skb -- or
2528 * @skb itself. If this would exceed the total buffer size the kernel
2529 * will panic. A pointer to the first byte of the extra data is
2533 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2536 skb->data_len += len;
2539 return skb_put(tail, len);
2541 EXPORT_SYMBOL_GPL(pskb_put);
2544 * skb_put - add data to a buffer
2545 * @skb: buffer to use
2546 * @len: amount of data to add
2548 * This function extends the used data area of the buffer. If this would
2549 * exceed the total buffer size the kernel will panic. A pointer to the
2550 * first byte of the extra data is returned.
2552 void *skb_put(struct sk_buff *skb, unsigned int len)
2554 void *tmp = skb_tail_pointer(skb);
2555 SKB_LINEAR_ASSERT(skb);
2558 if (unlikely(skb->tail > skb->end))
2559 skb_over_panic(skb, len, __builtin_return_address(0));
2562 EXPORT_SYMBOL(skb_put);
2565 * skb_push - add data to the start of a buffer
2566 * @skb: buffer to use
2567 * @len: amount of data to add
2569 * This function extends the used data area of the buffer at the buffer
2570 * start. If this would exceed the total buffer headroom the kernel will
2571 * panic. A pointer to the first byte of the extra data is returned.
2573 void *skb_push(struct sk_buff *skb, unsigned int len)
2577 if (unlikely(skb->data < skb->head))
2578 skb_under_panic(skb, len, __builtin_return_address(0));
2581 EXPORT_SYMBOL(skb_push);
2584 * skb_pull - remove data from the start of a buffer
2585 * @skb: buffer to use
2586 * @len: amount of data to remove
2588 * This function removes data from the start of a buffer, returning
2589 * the memory to the headroom. A pointer to the next data in the buffer
2590 * is returned. Once the data has been pulled future pushes will overwrite
2593 void *skb_pull(struct sk_buff *skb, unsigned int len)
2595 return skb_pull_inline(skb, len);
2597 EXPORT_SYMBOL(skb_pull);
2600 * skb_pull_data - remove data from the start of a buffer returning its
2601 * original position.
2602 * @skb: buffer to use
2603 * @len: amount of data to remove
2605 * This function removes data from the start of a buffer, returning
2606 * the memory to the headroom. A pointer to the original data in the buffer
2607 * is returned after checking if there is enough data to pull. Once the
2608 * data has been pulled future pushes will overwrite the old data.
2610 void *skb_pull_data(struct sk_buff *skb, size_t len)
2612 void *data = skb->data;
2621 EXPORT_SYMBOL(skb_pull_data);
2624 * skb_trim - remove end from a buffer
2625 * @skb: buffer to alter
2628 * Cut the length of a buffer down by removing data from the tail. If
2629 * the buffer is already under the length specified it is not modified.
2630 * The skb must be linear.
2632 void skb_trim(struct sk_buff *skb, unsigned int len)
2635 __skb_trim(skb, len);
2637 EXPORT_SYMBOL(skb_trim);
2639 /* Trims skb to length len. It can change skb pointers.
2642 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2644 struct sk_buff **fragp;
2645 struct sk_buff *frag;
2646 int offset = skb_headlen(skb);
2647 int nfrags = skb_shinfo(skb)->nr_frags;
2651 if (skb_cloned(skb) &&
2652 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2659 for (; i < nfrags; i++) {
2660 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2667 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2670 skb_shinfo(skb)->nr_frags = i;
2672 for (; i < nfrags; i++)
2673 skb_frag_unref(skb, i);
2675 if (skb_has_frag_list(skb))
2676 skb_drop_fraglist(skb);
2680 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2681 fragp = &frag->next) {
2682 int end = offset + frag->len;
2684 if (skb_shared(frag)) {
2685 struct sk_buff *nfrag;
2687 nfrag = skb_clone(frag, GFP_ATOMIC);
2688 if (unlikely(!nfrag))
2691 nfrag->next = frag->next;
2703 unlikely((err = pskb_trim(frag, len - offset))))
2707 skb_drop_list(&frag->next);
2712 if (len > skb_headlen(skb)) {
2713 skb->data_len -= skb->len - len;
2718 skb_set_tail_pointer(skb, len);
2721 if (!skb->sk || skb->destructor == sock_edemux)
2725 EXPORT_SYMBOL(___pskb_trim);
2727 /* Note : use pskb_trim_rcsum() instead of calling this directly
2729 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2731 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2732 int delta = skb->len - len;
2734 skb->csum = csum_block_sub(skb->csum,
2735 skb_checksum(skb, len, delta, 0),
2737 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2738 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2739 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2741 if (offset + sizeof(__sum16) > hdlen)
2744 return __pskb_trim(skb, len);
2746 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2749 * __pskb_pull_tail - advance tail of skb header
2750 * @skb: buffer to reallocate
2751 * @delta: number of bytes to advance tail
2753 * The function makes a sense only on a fragmented &sk_buff,
2754 * it expands header moving its tail forward and copying necessary
2755 * data from fragmented part.
2757 * &sk_buff MUST have reference count of 1.
2759 * Returns %NULL (and &sk_buff does not change) if pull failed
2760 * or value of new tail of skb in the case of success.
2762 * All the pointers pointing into skb header may change and must be
2763 * reloaded after call to this function.
2766 /* Moves tail of skb head forward, copying data from fragmented part,
2767 * when it is necessary.
2768 * 1. It may fail due to malloc failure.
2769 * 2. It may change skb pointers.
2771 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2773 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2775 /* If skb has not enough free space at tail, get new one
2776 * plus 128 bytes for future expansions. If we have enough
2777 * room at tail, reallocate without expansion only if skb is cloned.
2779 int i, k, eat = (skb->tail + delta) - skb->end;
2781 if (eat > 0 || skb_cloned(skb)) {
2782 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2787 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2788 skb_tail_pointer(skb), delta));
2790 /* Optimization: no fragments, no reasons to preestimate
2791 * size of pulled pages. Superb.
2793 if (!skb_has_frag_list(skb))
2796 /* Estimate size of pulled pages. */
2798 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2799 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2806 /* If we need update frag list, we are in troubles.
2807 * Certainly, it is possible to add an offset to skb data,
2808 * but taking into account that pulling is expected to
2809 * be very rare operation, it is worth to fight against
2810 * further bloating skb head and crucify ourselves here instead.
2811 * Pure masohism, indeed. 8)8)
2814 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2815 struct sk_buff *clone = NULL;
2816 struct sk_buff *insp = NULL;
2819 if (list->len <= eat) {
2820 /* Eaten as whole. */
2825 /* Eaten partially. */
2826 if (skb_is_gso(skb) && !list->head_frag &&
2828 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2830 if (skb_shared(list)) {
2831 /* Sucks! We need to fork list. :-( */
2832 clone = skb_clone(list, GFP_ATOMIC);
2838 /* This may be pulled without
2842 if (!pskb_pull(list, eat)) {
2850 /* Free pulled out fragments. */
2851 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2852 skb_shinfo(skb)->frag_list = list->next;
2855 /* And insert new clone at head. */
2858 skb_shinfo(skb)->frag_list = clone;
2861 /* Success! Now we may commit changes to skb data. */
2866 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2867 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2870 skb_frag_unref(skb, i);
2873 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2875 *frag = skb_shinfo(skb)->frags[i];
2877 skb_frag_off_add(frag, eat);
2878 skb_frag_size_sub(frag, eat);
2886 skb_shinfo(skb)->nr_frags = k;
2890 skb->data_len -= delta;
2893 skb_zcopy_clear(skb, false);
2895 return skb_tail_pointer(skb);
2897 EXPORT_SYMBOL(__pskb_pull_tail);
2900 * skb_copy_bits - copy bits from skb to kernel buffer
2902 * @offset: offset in source
2903 * @to: destination buffer
2904 * @len: number of bytes to copy
2906 * Copy the specified number of bytes from the source skb to the
2907 * destination buffer.
2910 * If its prototype is ever changed,
2911 * check arch/{*}/net/{*}.S files,
2912 * since it is called from BPF assembly code.
2914 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2916 int start = skb_headlen(skb);
2917 struct sk_buff *frag_iter;
2920 if (offset > (int)skb->len - len)
2924 if ((copy = start - offset) > 0) {
2927 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2928 if ((len -= copy) == 0)
2934 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2936 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2938 WARN_ON(start > offset + len);
2940 end = start + skb_frag_size(f);
2941 if ((copy = end - offset) > 0) {
2942 u32 p_off, p_len, copied;
2949 skb_frag_foreach_page(f,
2950 skb_frag_off(f) + offset - start,
2951 copy, p, p_off, p_len, copied) {
2952 vaddr = kmap_atomic(p);
2953 memcpy(to + copied, vaddr + p_off, p_len);
2954 kunmap_atomic(vaddr);
2957 if ((len -= copy) == 0)
2965 skb_walk_frags(skb, frag_iter) {
2968 WARN_ON(start > offset + len);
2970 end = start + frag_iter->len;
2971 if ((copy = end - offset) > 0) {
2974 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2976 if ((len -= copy) == 0)
2990 EXPORT_SYMBOL(skb_copy_bits);
2993 * Callback from splice_to_pipe(), if we need to release some pages
2994 * at the end of the spd in case we error'ed out in filling the pipe.
2996 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2998 put_page(spd->pages[i]);
3001 static struct page *linear_to_page(struct page *page, unsigned int *len,
3002 unsigned int *offset,
3005 struct page_frag *pfrag = sk_page_frag(sk);
3007 if (!sk_page_frag_refill(sk, pfrag))
3010 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
3012 memcpy(page_address(pfrag->page) + pfrag->offset,
3013 page_address(page) + *offset, *len);
3014 *offset = pfrag->offset;
3015 pfrag->offset += *len;
3020 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
3022 unsigned int offset)
3024 return spd->nr_pages &&
3025 spd->pages[spd->nr_pages - 1] == page &&
3026 (spd->partial[spd->nr_pages - 1].offset +
3027 spd->partial[spd->nr_pages - 1].len == offset);
3031 * Fill page/offset/length into spd, if it can hold more pages.
3033 static bool spd_fill_page(struct splice_pipe_desc *spd,
3034 struct pipe_inode_info *pipe, struct page *page,
3035 unsigned int *len, unsigned int offset,
3039 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
3043 page = linear_to_page(page, len, &offset, sk);
3047 if (spd_can_coalesce(spd, page, offset)) {
3048 spd->partial[spd->nr_pages - 1].len += *len;
3052 spd->pages[spd->nr_pages] = page;
3053 spd->partial[spd->nr_pages].len = *len;
3054 spd->partial[spd->nr_pages].offset = offset;
3060 static bool __splice_segment(struct page *page, unsigned int poff,
3061 unsigned int plen, unsigned int *off,
3063 struct splice_pipe_desc *spd, bool linear,
3065 struct pipe_inode_info *pipe)
3070 /* skip this segment if already processed */
3076 /* ignore any bits we already processed */
3082 unsigned int flen = min(*len, plen);
3084 if (spd_fill_page(spd, pipe, page, &flen, poff,
3090 } while (*len && plen);
3096 * Map linear and fragment data from the skb to spd. It reports true if the
3097 * pipe is full or if we already spliced the requested length.
3099 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
3100 unsigned int *offset, unsigned int *len,
3101 struct splice_pipe_desc *spd, struct sock *sk)
3104 struct sk_buff *iter;
3106 /* map the linear part :
3107 * If skb->head_frag is set, this 'linear' part is backed by a
3108 * fragment, and if the head is not shared with any clones then
3109 * we can avoid a copy since we own the head portion of this page.
3111 if (__splice_segment(virt_to_page(skb->data),
3112 (unsigned long) skb->data & (PAGE_SIZE - 1),
3115 skb_head_is_locked(skb),
3120 * then map the fragments
3122 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
3123 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
3125 if (__splice_segment(skb_frag_page(f),
3126 skb_frag_off(f), skb_frag_size(f),
3127 offset, len, spd, false, sk, pipe))
3131 skb_walk_frags(skb, iter) {
3132 if (*offset >= iter->len) {
3133 *offset -= iter->len;
3136 /* __skb_splice_bits() only fails if the output has no room
3137 * left, so no point in going over the frag_list for the error
3140 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
3148 * Map data from the skb to a pipe. Should handle both the linear part,
3149 * the fragments, and the frag list.
3151 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
3152 struct pipe_inode_info *pipe, unsigned int tlen,
3155 struct partial_page partial[MAX_SKB_FRAGS];
3156 struct page *pages[MAX_SKB_FRAGS];
3157 struct splice_pipe_desc spd = {
3160 .nr_pages_max = MAX_SKB_FRAGS,
3161 .ops = &nosteal_pipe_buf_ops,
3162 .spd_release = sock_spd_release,
3166 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
3169 ret = splice_to_pipe(pipe, &spd);
3173 EXPORT_SYMBOL_GPL(skb_splice_bits);
3175 static int sendmsg_locked(struct sock *sk, struct msghdr *msg)
3177 struct socket *sock = sk->sk_socket;
3178 size_t size = msg_data_left(msg);
3183 if (!sock->ops->sendmsg_locked)
3184 return sock_no_sendmsg_locked(sk, msg, size);
3186 return sock->ops->sendmsg_locked(sk, msg, size);
3189 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg)
3191 struct socket *sock = sk->sk_socket;
3195 return sock_sendmsg(sock, msg);
3198 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg);
3199 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
3200 int len, sendmsg_func sendmsg)
3202 unsigned int orig_len = len;
3203 struct sk_buff *head = skb;
3204 unsigned short fragidx;
3209 /* Deal with head data */
3210 while (offset < skb_headlen(skb) && len) {
3214 slen = min_t(int, len, skb_headlen(skb) - offset);
3215 kv.iov_base = skb->data + offset;
3217 memset(&msg, 0, sizeof(msg));
3218 msg.msg_flags = MSG_DONTWAIT;
3220 iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, &kv, 1, slen);
3221 ret = INDIRECT_CALL_2(sendmsg, sendmsg_locked,
3222 sendmsg_unlocked, sk, &msg);
3230 /* All the data was skb head? */
3234 /* Make offset relative to start of frags */
3235 offset -= skb_headlen(skb);
3237 /* Find where we are in frag list */
3238 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3239 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3241 if (offset < skb_frag_size(frag))
3244 offset -= skb_frag_size(frag);
3247 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3248 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3250 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
3253 struct bio_vec bvec;
3254 struct msghdr msg = {
3255 .msg_flags = MSG_SPLICE_PAGES | MSG_DONTWAIT,
3258 bvec_set_page(&bvec, skb_frag_page(frag), slen,
3259 skb_frag_off(frag) + offset);
3260 iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1,
3263 ret = INDIRECT_CALL_2(sendmsg, sendmsg_locked,
3264 sendmsg_unlocked, sk, &msg);
3277 /* Process any frag lists */
3280 if (skb_has_frag_list(skb)) {
3281 skb = skb_shinfo(skb)->frag_list;
3284 } else if (skb->next) {
3291 return orig_len - len;
3294 return orig_len == len ? ret : orig_len - len;
3297 /* Send skb data on a socket. Socket must be locked. */
3298 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
3301 return __skb_send_sock(sk, skb, offset, len, sendmsg_locked);
3303 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
3305 /* Send skb data on a socket. Socket must be unlocked. */
3306 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
3308 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked);
3312 * skb_store_bits - store bits from kernel buffer to skb
3313 * @skb: destination buffer
3314 * @offset: offset in destination
3315 * @from: source buffer
3316 * @len: number of bytes to copy
3318 * Copy the specified number of bytes from the source buffer to the
3319 * destination skb. This function handles all the messy bits of
3320 * traversing fragment lists and such.
3323 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
3325 int start = skb_headlen(skb);
3326 struct sk_buff *frag_iter;
3329 if (offset > (int)skb->len - len)
3332 if ((copy = start - offset) > 0) {
3335 skb_copy_to_linear_data_offset(skb, offset, from, copy);
3336 if ((len -= copy) == 0)
3342 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3343 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3346 WARN_ON(start > offset + len);
3348 end = start + skb_frag_size(frag);
3349 if ((copy = end - offset) > 0) {
3350 u32 p_off, p_len, copied;
3357 skb_frag_foreach_page(frag,
3358 skb_frag_off(frag) + offset - start,
3359 copy, p, p_off, p_len, copied) {
3360 vaddr = kmap_atomic(p);
3361 memcpy(vaddr + p_off, from + copied, p_len);
3362 kunmap_atomic(vaddr);
3365 if ((len -= copy) == 0)
3373 skb_walk_frags(skb, frag_iter) {
3376 WARN_ON(start > offset + len);
3378 end = start + frag_iter->len;
3379 if ((copy = end - offset) > 0) {
3382 if (skb_store_bits(frag_iter, offset - start,
3385 if ((len -= copy) == 0)
3398 EXPORT_SYMBOL(skb_store_bits);
3400 /* Checksum skb data. */
3401 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
3402 __wsum csum, const struct skb_checksum_ops *ops)
3404 int start = skb_headlen(skb);
3405 int i, copy = start - offset;
3406 struct sk_buff *frag_iter;
3409 /* Checksum header. */
3413 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3414 skb->data + offset, copy, csum);
3415 if ((len -= copy) == 0)
3421 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3423 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3425 WARN_ON(start > offset + len);
3427 end = start + skb_frag_size(frag);
3428 if ((copy = end - offset) > 0) {
3429 u32 p_off, p_len, copied;
3437 skb_frag_foreach_page(frag,
3438 skb_frag_off(frag) + offset - start,
3439 copy, p, p_off, p_len, copied) {
3440 vaddr = kmap_atomic(p);
3441 csum2 = INDIRECT_CALL_1(ops->update,
3443 vaddr + p_off, p_len, 0);
3444 kunmap_atomic(vaddr);
3445 csum = INDIRECT_CALL_1(ops->combine,
3446 csum_block_add_ext, csum,
3458 skb_walk_frags(skb, frag_iter) {
3461 WARN_ON(start > offset + len);
3463 end = start + frag_iter->len;
3464 if ((copy = end - offset) > 0) {
3468 csum2 = __skb_checksum(frag_iter, offset - start,
3470 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3471 csum, csum2, pos, copy);
3472 if ((len -= copy) == 0)
3483 EXPORT_SYMBOL(__skb_checksum);
3485 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3486 int len, __wsum csum)
3488 const struct skb_checksum_ops ops = {
3489 .update = csum_partial_ext,
3490 .combine = csum_block_add_ext,
3493 return __skb_checksum(skb, offset, len, csum, &ops);
3495 EXPORT_SYMBOL(skb_checksum);
3497 /* Both of above in one bottle. */
3499 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3502 int start = skb_headlen(skb);
3503 int i, copy = start - offset;
3504 struct sk_buff *frag_iter;
3512 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3514 if ((len -= copy) == 0)
3521 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3524 WARN_ON(start > offset + len);
3526 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3527 if ((copy = end - offset) > 0) {
3528 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3529 u32 p_off, p_len, copied;
3537 skb_frag_foreach_page(frag,
3538 skb_frag_off(frag) + offset - start,
3539 copy, p, p_off, p_len, copied) {
3540 vaddr = kmap_atomic(p);
3541 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3544 kunmap_atomic(vaddr);
3545 csum = csum_block_add(csum, csum2, pos);
3557 skb_walk_frags(skb, frag_iter) {
3561 WARN_ON(start > offset + len);
3563 end = start + frag_iter->len;
3564 if ((copy = end - offset) > 0) {
3567 csum2 = skb_copy_and_csum_bits(frag_iter,
3570 csum = csum_block_add(csum, csum2, pos);
3571 if ((len -= copy) == 0)
3582 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3584 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3588 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3589 /* See comments in __skb_checksum_complete(). */
3591 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3592 !skb->csum_complete_sw)
3593 netdev_rx_csum_fault(skb->dev, skb);
3595 if (!skb_shared(skb))
3596 skb->csum_valid = !sum;
3599 EXPORT_SYMBOL(__skb_checksum_complete_head);
3601 /* This function assumes skb->csum already holds pseudo header's checksum,
3602 * which has been changed from the hardware checksum, for example, by
3603 * __skb_checksum_validate_complete(). And, the original skb->csum must
3604 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3606 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3607 * zero. The new checksum is stored back into skb->csum unless the skb is
3610 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3615 csum = skb_checksum(skb, 0, skb->len, 0);
3617 sum = csum_fold(csum_add(skb->csum, csum));
3618 /* This check is inverted, because we already knew the hardware
3619 * checksum is invalid before calling this function. So, if the
3620 * re-computed checksum is valid instead, then we have a mismatch
3621 * between the original skb->csum and skb_checksum(). This means either
3622 * the original hardware checksum is incorrect or we screw up skb->csum
3623 * when moving skb->data around.
3626 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3627 !skb->csum_complete_sw)
3628 netdev_rx_csum_fault(skb->dev, skb);
3631 if (!skb_shared(skb)) {
3632 /* Save full packet checksum */
3634 skb->ip_summed = CHECKSUM_COMPLETE;
3635 skb->csum_complete_sw = 1;
3636 skb->csum_valid = !sum;
3641 EXPORT_SYMBOL(__skb_checksum_complete);
3643 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3645 net_warn_ratelimited(
3646 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3651 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3652 int offset, int len)
3654 net_warn_ratelimited(
3655 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3660 static const struct skb_checksum_ops default_crc32c_ops = {
3661 .update = warn_crc32c_csum_update,
3662 .combine = warn_crc32c_csum_combine,
3665 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3666 &default_crc32c_ops;
3667 EXPORT_SYMBOL(crc32c_csum_stub);
3670 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3671 * @from: source buffer
3673 * Calculates the amount of linear headroom needed in the 'to' skb passed
3674 * into skb_zerocopy().
3677 skb_zerocopy_headlen(const struct sk_buff *from)
3679 unsigned int hlen = 0;
3681 if (!from->head_frag ||
3682 skb_headlen(from) < L1_CACHE_BYTES ||
3683 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3684 hlen = skb_headlen(from);
3689 if (skb_has_frag_list(from))
3694 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3697 * skb_zerocopy - Zero copy skb to skb
3698 * @to: destination buffer
3699 * @from: source buffer
3700 * @len: number of bytes to copy from source buffer
3701 * @hlen: size of linear headroom in destination buffer
3703 * Copies up to `len` bytes from `from` to `to` by creating references
3704 * to the frags in the source buffer.
3706 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3707 * headroom in the `to` buffer.
3710 * 0: everything is OK
3711 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3712 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3715 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3718 int plen = 0; /* length of skb->head fragment */
3721 unsigned int offset;
3723 BUG_ON(!from->head_frag && !hlen);
3725 /* dont bother with small payloads */
3726 if (len <= skb_tailroom(to))
3727 return skb_copy_bits(from, 0, skb_put(to, len), len);
3730 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3735 plen = min_t(int, skb_headlen(from), len);
3737 page = virt_to_head_page(from->head);
3738 offset = from->data - (unsigned char *)page_address(page);
3739 __skb_fill_netmem_desc(to, 0, page_to_netmem(page),
3747 skb_len_add(to, len + plen);
3749 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3753 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3755 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3760 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3761 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3763 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3765 skb_frag_ref(to, j);
3768 skb_shinfo(to)->nr_frags = j;
3772 EXPORT_SYMBOL_GPL(skb_zerocopy);
3774 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3779 if (skb->ip_summed == CHECKSUM_PARTIAL)
3780 csstart = skb_checksum_start_offset(skb);
3782 csstart = skb_headlen(skb);
3784 BUG_ON(csstart > skb_headlen(skb));
3786 skb_copy_from_linear_data(skb, to, csstart);
3789 if (csstart != skb->len)
3790 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3791 skb->len - csstart);
3793 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3794 long csstuff = csstart + skb->csum_offset;
3796 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3799 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3802 * skb_dequeue - remove from the head of the queue
3803 * @list: list to dequeue from
3805 * Remove the head of the list. The list lock is taken so the function
3806 * may be used safely with other locking list functions. The head item is
3807 * returned or %NULL if the list is empty.
3810 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3812 unsigned long flags;
3813 struct sk_buff *result;
3815 spin_lock_irqsave(&list->lock, flags);
3816 result = __skb_dequeue(list);
3817 spin_unlock_irqrestore(&list->lock, flags);
3820 EXPORT_SYMBOL(skb_dequeue);
3823 * skb_dequeue_tail - remove from the tail of the queue
3824 * @list: list to dequeue from
3826 * Remove the tail of the list. The list lock is taken so the function
3827 * may be used safely with other locking list functions. The tail item is
3828 * returned or %NULL if the list is empty.
3830 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3832 unsigned long flags;
3833 struct sk_buff *result;
3835 spin_lock_irqsave(&list->lock, flags);
3836 result = __skb_dequeue_tail(list);
3837 spin_unlock_irqrestore(&list->lock, flags);
3840 EXPORT_SYMBOL(skb_dequeue_tail);
3843 * skb_queue_purge_reason - empty a list
3844 * @list: list to empty
3845 * @reason: drop reason
3847 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3848 * the list and one reference dropped. This function takes the list
3849 * lock and is atomic with respect to other list locking functions.
3851 void skb_queue_purge_reason(struct sk_buff_head *list,
3852 enum skb_drop_reason reason)
3854 struct sk_buff_head tmp;
3855 unsigned long flags;
3857 if (skb_queue_empty_lockless(list))
3860 __skb_queue_head_init(&tmp);
3862 spin_lock_irqsave(&list->lock, flags);
3863 skb_queue_splice_init(list, &tmp);
3864 spin_unlock_irqrestore(&list->lock, flags);
3866 __skb_queue_purge_reason(&tmp, reason);
3868 EXPORT_SYMBOL(skb_queue_purge_reason);
3871 * skb_rbtree_purge - empty a skb rbtree
3872 * @root: root of the rbtree to empty
3873 * Return value: the sum of truesizes of all purged skbs.
3875 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3876 * the list and one reference dropped. This function does not take
3877 * any lock. Synchronization should be handled by the caller (e.g., TCP
3878 * out-of-order queue is protected by the socket lock).
3880 unsigned int skb_rbtree_purge(struct rb_root *root)
3882 struct rb_node *p = rb_first(root);
3883 unsigned int sum = 0;
3886 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3889 rb_erase(&skb->rbnode, root);
3890 sum += skb->truesize;
3896 void skb_errqueue_purge(struct sk_buff_head *list)
3898 struct sk_buff *skb, *next;
3899 struct sk_buff_head kill;
3900 unsigned long flags;
3902 __skb_queue_head_init(&kill);
3904 spin_lock_irqsave(&list->lock, flags);
3905 skb_queue_walk_safe(list, skb, next) {
3906 if (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ZEROCOPY ||
3907 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_TIMESTAMPING)
3909 __skb_unlink(skb, list);
3910 __skb_queue_tail(&kill, skb);
3912 spin_unlock_irqrestore(&list->lock, flags);
3913 __skb_queue_purge(&kill);
3915 EXPORT_SYMBOL(skb_errqueue_purge);
3918 * skb_queue_head - queue a buffer at the list head
3919 * @list: list to use
3920 * @newsk: buffer to queue
3922 * Queue a buffer at the start of the list. This function takes the
3923 * list lock and can be used safely with other locking &sk_buff functions
3926 * A buffer cannot be placed on two lists at the same time.
3928 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3930 unsigned long flags;
3932 spin_lock_irqsave(&list->lock, flags);
3933 __skb_queue_head(list, newsk);
3934 spin_unlock_irqrestore(&list->lock, flags);
3936 EXPORT_SYMBOL(skb_queue_head);
3939 * skb_queue_tail - queue a buffer at the list tail
3940 * @list: list to use
3941 * @newsk: buffer to queue
3943 * Queue a buffer at the tail of the list. This function takes the
3944 * list lock and can be used safely with other locking &sk_buff functions
3947 * A buffer cannot be placed on two lists at the same time.
3949 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3951 unsigned long flags;
3953 spin_lock_irqsave(&list->lock, flags);
3954 __skb_queue_tail(list, newsk);
3955 spin_unlock_irqrestore(&list->lock, flags);
3957 EXPORT_SYMBOL(skb_queue_tail);
3960 * skb_unlink - remove a buffer from a list
3961 * @skb: buffer to remove
3962 * @list: list to use
3964 * Remove a packet from a list. The list locks are taken and this
3965 * function is atomic with respect to other list locked calls
3967 * You must know what list the SKB is on.
3969 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3971 unsigned long flags;
3973 spin_lock_irqsave(&list->lock, flags);
3974 __skb_unlink(skb, list);
3975 spin_unlock_irqrestore(&list->lock, flags);
3977 EXPORT_SYMBOL(skb_unlink);
3980 * skb_append - append a buffer
3981 * @old: buffer to insert after
3982 * @newsk: buffer to insert
3983 * @list: list to use
3985 * Place a packet after a given packet in a list. The list locks are taken
3986 * and this function is atomic with respect to other list locked calls.
3987 * A buffer cannot be placed on two lists at the same time.
3989 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3991 unsigned long flags;
3993 spin_lock_irqsave(&list->lock, flags);
3994 __skb_queue_after(list, old, newsk);
3995 spin_unlock_irqrestore(&list->lock, flags);
3997 EXPORT_SYMBOL(skb_append);
3999 static inline void skb_split_inside_header(struct sk_buff *skb,
4000 struct sk_buff* skb1,
4001 const u32 len, const int pos)
4005 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
4007 /* And move data appendix as is. */
4008 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
4009 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
4011 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
4012 skb_shinfo(skb)->nr_frags = 0;
4013 skb1->data_len = skb->data_len;
4014 skb1->len += skb1->data_len;
4017 skb_set_tail_pointer(skb, len);
4020 static inline void skb_split_no_header(struct sk_buff *skb,
4021 struct sk_buff* skb1,
4022 const u32 len, int pos)
4025 const int nfrags = skb_shinfo(skb)->nr_frags;
4027 skb_shinfo(skb)->nr_frags = 0;
4028 skb1->len = skb1->data_len = skb->len - len;
4030 skb->data_len = len - pos;
4032 for (i = 0; i < nfrags; i++) {
4033 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
4035 if (pos + size > len) {
4036 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
4040 * We have two variants in this case:
4041 * 1. Move all the frag to the second
4042 * part, if it is possible. F.e.
4043 * this approach is mandatory for TUX,
4044 * where splitting is expensive.
4045 * 2. Split is accurately. We make this.
4047 skb_frag_ref(skb, i);
4048 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
4049 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
4050 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
4051 skb_shinfo(skb)->nr_frags++;
4055 skb_shinfo(skb)->nr_frags++;
4058 skb_shinfo(skb1)->nr_frags = k;
4062 * skb_split - Split fragmented skb to two parts at length len.
4063 * @skb: the buffer to split
4064 * @skb1: the buffer to receive the second part
4065 * @len: new length for skb
4067 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
4069 int pos = skb_headlen(skb);
4070 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
4072 skb_zcopy_downgrade_managed(skb);
4074 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
4075 skb_zerocopy_clone(skb1, skb, 0);
4076 if (len < pos) /* Split line is inside header. */
4077 skb_split_inside_header(skb, skb1, len, pos);
4078 else /* Second chunk has no header, nothing to copy. */
4079 skb_split_no_header(skb, skb1, len, pos);
4081 EXPORT_SYMBOL(skb_split);
4083 /* Shifting from/to a cloned skb is a no-go.
4085 * Caller cannot keep skb_shinfo related pointers past calling here!
4087 static int skb_prepare_for_shift(struct sk_buff *skb)
4089 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
4093 * skb_shift - Shifts paged data partially from skb to another
4094 * @tgt: buffer into which tail data gets added
4095 * @skb: buffer from which the paged data comes from
4096 * @shiftlen: shift up to this many bytes
4098 * Attempts to shift up to shiftlen worth of bytes, which may be less than
4099 * the length of the skb, from skb to tgt. Returns number bytes shifted.
4100 * It's up to caller to free skb if everything was shifted.
4102 * If @tgt runs out of frags, the whole operation is aborted.
4104 * Skb cannot include anything else but paged data while tgt is allowed
4105 * to have non-paged data as well.
4107 * TODO: full sized shift could be optimized but that would need
4108 * specialized skb free'er to handle frags without up-to-date nr_frags.
4110 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
4112 int from, to, merge, todo;
4113 skb_frag_t *fragfrom, *fragto;
4115 BUG_ON(shiftlen > skb->len);
4117 if (skb_headlen(skb))
4119 if (skb_zcopy(tgt) || skb_zcopy(skb))
4124 to = skb_shinfo(tgt)->nr_frags;
4125 fragfrom = &skb_shinfo(skb)->frags[from];
4127 /* Actual merge is delayed until the point when we know we can
4128 * commit all, so that we don't have to undo partial changes
4131 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
4132 skb_frag_off(fragfrom))) {
4137 todo -= skb_frag_size(fragfrom);
4139 if (skb_prepare_for_shift(skb) ||
4140 skb_prepare_for_shift(tgt))
4143 /* All previous frag pointers might be stale! */
4144 fragfrom = &skb_shinfo(skb)->frags[from];
4145 fragto = &skb_shinfo(tgt)->frags[merge];
4147 skb_frag_size_add(fragto, shiftlen);
4148 skb_frag_size_sub(fragfrom, shiftlen);
4149 skb_frag_off_add(fragfrom, shiftlen);
4157 /* Skip full, not-fitting skb to avoid expensive operations */
4158 if ((shiftlen == skb->len) &&
4159 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
4162 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
4165 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
4166 if (to == MAX_SKB_FRAGS)
4169 fragfrom = &skb_shinfo(skb)->frags[from];
4170 fragto = &skb_shinfo(tgt)->frags[to];
4172 if (todo >= skb_frag_size(fragfrom)) {
4173 *fragto = *fragfrom;
4174 todo -= skb_frag_size(fragfrom);
4179 __skb_frag_ref(fragfrom);
4180 skb_frag_page_copy(fragto, fragfrom);
4181 skb_frag_off_copy(fragto, fragfrom);
4182 skb_frag_size_set(fragto, todo);
4184 skb_frag_off_add(fragfrom, todo);
4185 skb_frag_size_sub(fragfrom, todo);
4193 /* Ready to "commit" this state change to tgt */
4194 skb_shinfo(tgt)->nr_frags = to;
4197 fragfrom = &skb_shinfo(skb)->frags[0];
4198 fragto = &skb_shinfo(tgt)->frags[merge];
4200 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
4201 __skb_frag_unref(fragfrom, skb->pp_recycle);
4204 /* Reposition in the original skb */
4206 while (from < skb_shinfo(skb)->nr_frags)
4207 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
4208 skb_shinfo(skb)->nr_frags = to;
4210 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
4213 /* Most likely the tgt won't ever need its checksum anymore, skb on
4214 * the other hand might need it if it needs to be resent
4216 tgt->ip_summed = CHECKSUM_PARTIAL;
4217 skb->ip_summed = CHECKSUM_PARTIAL;
4219 skb_len_add(skb, -shiftlen);
4220 skb_len_add(tgt, shiftlen);
4226 * skb_prepare_seq_read - Prepare a sequential read of skb data
4227 * @skb: the buffer to read
4228 * @from: lower offset of data to be read
4229 * @to: upper offset of data to be read
4230 * @st: state variable
4232 * Initializes the specified state variable. Must be called before
4233 * invoking skb_seq_read() for the first time.
4235 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
4236 unsigned int to, struct skb_seq_state *st)
4238 st->lower_offset = from;
4239 st->upper_offset = to;
4240 st->root_skb = st->cur_skb = skb;
4241 st->frag_idx = st->stepped_offset = 0;
4242 st->frag_data = NULL;
4245 EXPORT_SYMBOL(skb_prepare_seq_read);
4248 * skb_seq_read - Sequentially read skb data
4249 * @consumed: number of bytes consumed by the caller so far
4250 * @data: destination pointer for data to be returned
4251 * @st: state variable
4253 * Reads a block of skb data at @consumed relative to the
4254 * lower offset specified to skb_prepare_seq_read(). Assigns
4255 * the head of the data block to @data and returns the length
4256 * of the block or 0 if the end of the skb data or the upper
4257 * offset has been reached.
4259 * The caller is not required to consume all of the data
4260 * returned, i.e. @consumed is typically set to the number
4261 * of bytes already consumed and the next call to
4262 * skb_seq_read() will return the remaining part of the block.
4264 * Note 1: The size of each block of data returned can be arbitrary,
4265 * this limitation is the cost for zerocopy sequential
4266 * reads of potentially non linear data.
4268 * Note 2: Fragment lists within fragments are not implemented
4269 * at the moment, state->root_skb could be replaced with
4270 * a stack for this purpose.
4272 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
4273 struct skb_seq_state *st)
4275 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
4278 if (unlikely(abs_offset >= st->upper_offset)) {
4279 if (st->frag_data) {
4280 kunmap_atomic(st->frag_data);
4281 st->frag_data = NULL;
4287 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
4289 if (abs_offset < block_limit && !st->frag_data) {
4290 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
4291 return block_limit - abs_offset;
4294 if (st->frag_idx == 0 && !st->frag_data)
4295 st->stepped_offset += skb_headlen(st->cur_skb);
4297 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
4298 unsigned int pg_idx, pg_off, pg_sz;
4300 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
4303 pg_off = skb_frag_off(frag);
4304 pg_sz = skb_frag_size(frag);
4306 if (skb_frag_must_loop(skb_frag_page(frag))) {
4307 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
4308 pg_off = offset_in_page(pg_off + st->frag_off);
4309 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
4310 PAGE_SIZE - pg_off);
4313 block_limit = pg_sz + st->stepped_offset;
4314 if (abs_offset < block_limit) {
4316 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
4318 *data = (u8 *)st->frag_data + pg_off +
4319 (abs_offset - st->stepped_offset);
4321 return block_limit - abs_offset;
4324 if (st->frag_data) {
4325 kunmap_atomic(st->frag_data);
4326 st->frag_data = NULL;
4329 st->stepped_offset += pg_sz;
4330 st->frag_off += pg_sz;
4331 if (st->frag_off == skb_frag_size(frag)) {
4337 if (st->frag_data) {
4338 kunmap_atomic(st->frag_data);
4339 st->frag_data = NULL;
4342 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
4343 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
4346 } else if (st->cur_skb->next) {
4347 st->cur_skb = st->cur_skb->next;
4354 EXPORT_SYMBOL(skb_seq_read);
4357 * skb_abort_seq_read - Abort a sequential read of skb data
4358 * @st: state variable
4360 * Must be called if skb_seq_read() was not called until it
4363 void skb_abort_seq_read(struct skb_seq_state *st)
4366 kunmap_atomic(st->frag_data);
4368 EXPORT_SYMBOL(skb_abort_seq_read);
4370 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
4372 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
4373 struct ts_config *conf,
4374 struct ts_state *state)
4376 return skb_seq_read(offset, text, TS_SKB_CB(state));
4379 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
4381 skb_abort_seq_read(TS_SKB_CB(state));
4385 * skb_find_text - Find a text pattern in skb data
4386 * @skb: the buffer to look in
4387 * @from: search offset
4389 * @config: textsearch configuration
4391 * Finds a pattern in the skb data according to the specified
4392 * textsearch configuration. Use textsearch_next() to retrieve
4393 * subsequent occurrences of the pattern. Returns the offset
4394 * to the first occurrence or UINT_MAX if no match was found.
4396 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4397 unsigned int to, struct ts_config *config)
4399 unsigned int patlen = config->ops->get_pattern_len(config);
4400 struct ts_state state;
4403 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4405 config->get_next_block = skb_ts_get_next_block;
4406 config->finish = skb_ts_finish;
4408 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
4410 ret = textsearch_find(config, &state);
4411 return (ret + patlen <= to - from ? ret : UINT_MAX);
4413 EXPORT_SYMBOL(skb_find_text);
4415 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4416 int offset, size_t size, size_t max_frags)
4418 int i = skb_shinfo(skb)->nr_frags;
4420 if (skb_can_coalesce(skb, i, page, offset)) {
4421 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4422 } else if (i < max_frags) {
4423 skb_zcopy_downgrade_managed(skb);
4425 skb_fill_page_desc_noacc(skb, i, page, offset, size);
4432 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4435 * skb_pull_rcsum - pull skb and update receive checksum
4436 * @skb: buffer to update
4437 * @len: length of data pulled
4439 * This function performs an skb_pull on the packet and updates
4440 * the CHECKSUM_COMPLETE checksum. It should be used on
4441 * receive path processing instead of skb_pull unless you know
4442 * that the checksum difference is zero (e.g., a valid IP header)
4443 * or you are setting ip_summed to CHECKSUM_NONE.
4445 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4447 unsigned char *data = skb->data;
4449 BUG_ON(len > skb->len);
4450 __skb_pull(skb, len);
4451 skb_postpull_rcsum(skb, data, len);
4454 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4456 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4458 skb_frag_t head_frag;
4461 page = virt_to_head_page(frag_skb->head);
4462 skb_frag_fill_page_desc(&head_frag, page, frag_skb->data -
4463 (unsigned char *)page_address(page),
4464 skb_headlen(frag_skb));
4468 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4469 netdev_features_t features,
4470 unsigned int offset)
4472 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4473 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4474 unsigned int delta_truesize = 0;
4475 unsigned int delta_len = 0;
4476 struct sk_buff *tail = NULL;
4477 struct sk_buff *nskb, *tmp;
4480 skb_push(skb, -skb_network_offset(skb) + offset);
4482 /* Ensure the head is writeable before touching the shared info */
4483 err = skb_unclone(skb, GFP_ATOMIC);
4487 skb_shinfo(skb)->frag_list = NULL;
4491 list_skb = list_skb->next;
4494 delta_truesize += nskb->truesize;
4495 if (skb_shared(nskb)) {
4496 tmp = skb_clone(nskb, GFP_ATOMIC);
4500 err = skb_unclone(nskb, GFP_ATOMIC);
4511 if (unlikely(err)) {
4512 nskb->next = list_skb;
4518 delta_len += nskb->len;
4520 skb_push(nskb, -skb_network_offset(nskb) + offset);
4522 skb_release_head_state(nskb);
4523 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4524 __copy_skb_header(nskb, skb);
4526 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4527 nskb->transport_header += len_diff;
4528 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4529 nskb->data - tnl_hlen,
4532 if (skb_needs_linearize(nskb, features) &&
4533 __skb_linearize(nskb))
4537 skb->truesize = skb->truesize - delta_truesize;
4538 skb->data_len = skb->data_len - delta_len;
4539 skb->len = skb->len - delta_len;
4545 if (skb_needs_linearize(skb, features) &&
4546 __skb_linearize(skb))
4554 kfree_skb_list(skb->next);
4556 return ERR_PTR(-ENOMEM);
4558 EXPORT_SYMBOL_GPL(skb_segment_list);
4561 * skb_segment - Perform protocol segmentation on skb.
4562 * @head_skb: buffer to segment
4563 * @features: features for the output path (see dev->features)
4565 * This function performs segmentation on the given skb. It returns
4566 * a pointer to the first in a list of new skbs for the segments.
4567 * In case of error it returns ERR_PTR(err).
4569 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4570 netdev_features_t features)
4572 struct sk_buff *segs = NULL;
4573 struct sk_buff *tail = NULL;
4574 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4575 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4576 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4577 unsigned int offset = doffset;
4578 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4579 unsigned int partial_segs = 0;
4580 unsigned int headroom;
4581 unsigned int len = head_skb->len;
4582 struct sk_buff *frag_skb;
4590 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4591 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4592 struct sk_buff *check_skb;
4594 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4595 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4596 /* gso_size is untrusted, and we have a frag_list with
4597 * a linear non head_frag item.
4599 * If head_skb's headlen does not fit requested gso_size,
4600 * it means that the frag_list members do NOT terminate
4601 * on exact gso_size boundaries. Hence we cannot perform
4602 * skb_frag_t page sharing. Therefore we must fallback to
4603 * copying the frag_list skbs; we do so by disabling SG.
4605 features &= ~NETIF_F_SG;
4611 __skb_push(head_skb, doffset);
4612 proto = skb_network_protocol(head_skb, NULL);
4613 if (unlikely(!proto))
4614 return ERR_PTR(-EINVAL);
4616 sg = !!(features & NETIF_F_SG);
4617 csum = !!can_checksum_protocol(features, proto);
4619 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4620 if (!(features & NETIF_F_GSO_PARTIAL)) {
4621 struct sk_buff *iter;
4622 unsigned int frag_len;
4625 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4628 /* If we get here then all the required
4629 * GSO features except frag_list are supported.
4630 * Try to split the SKB to multiple GSO SKBs
4631 * with no frag_list.
4632 * Currently we can do that only when the buffers don't
4633 * have a linear part and all the buffers except
4634 * the last are of the same length.
4636 frag_len = list_skb->len;
4637 skb_walk_frags(head_skb, iter) {
4638 if (frag_len != iter->len && iter->next)
4640 if (skb_headlen(iter) && !iter->head_frag)
4646 if (len != frag_len)
4650 /* GSO partial only requires that we trim off any excess that
4651 * doesn't fit into an MSS sized block, so take care of that
4653 * Cap len to not accidentally hit GSO_BY_FRAGS.
4655 partial_segs = min(len, GSO_BY_FRAGS - 1) / mss;
4656 if (partial_segs > 1)
4657 mss *= partial_segs;
4663 headroom = skb_headroom(head_skb);
4664 pos = skb_headlen(head_skb);
4666 if (skb_orphan_frags(head_skb, GFP_ATOMIC))
4667 return ERR_PTR(-ENOMEM);
4669 nfrags = skb_shinfo(head_skb)->nr_frags;
4670 frag = skb_shinfo(head_skb)->frags;
4671 frag_skb = head_skb;
4674 struct sk_buff *nskb;
4675 skb_frag_t *nskb_frag;
4679 if (unlikely(mss == GSO_BY_FRAGS)) {
4680 len = list_skb->len;
4682 len = head_skb->len - offset;
4687 hsize = skb_headlen(head_skb) - offset;
4689 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4690 (skb_headlen(list_skb) == len || sg)) {
4691 BUG_ON(skb_headlen(list_skb) > len);
4693 nskb = skb_clone(list_skb, GFP_ATOMIC);
4694 if (unlikely(!nskb))
4698 nfrags = skb_shinfo(list_skb)->nr_frags;
4699 frag = skb_shinfo(list_skb)->frags;
4700 frag_skb = list_skb;
4701 pos += skb_headlen(list_skb);
4703 while (pos < offset + len) {
4704 BUG_ON(i >= nfrags);
4706 size = skb_frag_size(frag);
4707 if (pos + size > offset + len)
4715 list_skb = list_skb->next;
4717 if (unlikely(pskb_trim(nskb, len))) {
4722 hsize = skb_end_offset(nskb);
4723 if (skb_cow_head(nskb, doffset + headroom)) {
4728 nskb->truesize += skb_end_offset(nskb) - hsize;
4729 skb_release_head_state(nskb);
4730 __skb_push(nskb, doffset);
4734 if (hsize > len || !sg)
4737 nskb = __alloc_skb(hsize + doffset + headroom,
4738 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4741 if (unlikely(!nskb))
4744 skb_reserve(nskb, headroom);
4745 __skb_put(nskb, doffset);
4754 __copy_skb_header(nskb, head_skb);
4756 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4757 skb_reset_mac_len(nskb);
4759 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4760 nskb->data - tnl_hlen,
4761 doffset + tnl_hlen);
4763 if (nskb->len == len + doffset)
4764 goto perform_csum_check;
4768 if (!nskb->remcsum_offload)
4769 nskb->ip_summed = CHECKSUM_NONE;
4770 SKB_GSO_CB(nskb)->csum =
4771 skb_copy_and_csum_bits(head_skb, offset,
4775 SKB_GSO_CB(nskb)->csum_start =
4776 skb_headroom(nskb) + doffset;
4778 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4784 nskb_frag = skb_shinfo(nskb)->frags;
4786 skb_copy_from_linear_data_offset(head_skb, offset,
4787 skb_put(nskb, hsize), hsize);
4789 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4792 if (skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4795 while (pos < offset + len) {
4797 if (skb_orphan_frags(list_skb, GFP_ATOMIC) ||
4798 skb_zerocopy_clone(nskb, list_skb,
4803 nfrags = skb_shinfo(list_skb)->nr_frags;
4804 frag = skb_shinfo(list_skb)->frags;
4805 frag_skb = list_skb;
4806 if (!skb_headlen(list_skb)) {
4809 BUG_ON(!list_skb->head_frag);
4811 /* to make room for head_frag. */
4816 list_skb = list_skb->next;
4819 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4821 net_warn_ratelimited(
4822 "skb_segment: too many frags: %u %u\n",
4828 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4829 __skb_frag_ref(nskb_frag);
4830 size = skb_frag_size(nskb_frag);
4833 skb_frag_off_add(nskb_frag, offset - pos);
4834 skb_frag_size_sub(nskb_frag, offset - pos);
4837 skb_shinfo(nskb)->nr_frags++;
4839 if (pos + size <= offset + len) {
4844 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4852 nskb->data_len = len - hsize;
4853 nskb->len += nskb->data_len;
4854 nskb->truesize += nskb->data_len;
4858 if (skb_has_shared_frag(nskb) &&
4859 __skb_linearize(nskb))
4862 if (!nskb->remcsum_offload)
4863 nskb->ip_summed = CHECKSUM_NONE;
4864 SKB_GSO_CB(nskb)->csum =
4865 skb_checksum(nskb, doffset,
4866 nskb->len - doffset, 0);
4867 SKB_GSO_CB(nskb)->csum_start =
4868 skb_headroom(nskb) + doffset;
4870 } while ((offset += len) < head_skb->len);
4872 /* Some callers want to get the end of the list.
4873 * Put it in segs->prev to avoid walking the list.
4874 * (see validate_xmit_skb_list() for example)
4879 struct sk_buff *iter;
4880 int type = skb_shinfo(head_skb)->gso_type;
4881 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4883 /* Update type to add partial and then remove dodgy if set */
4884 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4885 type &= ~SKB_GSO_DODGY;
4887 /* Update GSO info and prepare to start updating headers on
4888 * our way back down the stack of protocols.
4890 for (iter = segs; iter; iter = iter->next) {
4891 skb_shinfo(iter)->gso_size = gso_size;
4892 skb_shinfo(iter)->gso_segs = partial_segs;
4893 skb_shinfo(iter)->gso_type = type;
4894 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4897 if (tail->len - doffset <= gso_size)
4898 skb_shinfo(tail)->gso_size = 0;
4899 else if (tail != segs)
4900 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4903 /* Following permits correct backpressure, for protocols
4904 * using skb_set_owner_w().
4905 * Idea is to tranfert ownership from head_skb to last segment.
4907 if (head_skb->destructor == sock_wfree) {
4908 swap(tail->truesize, head_skb->truesize);
4909 swap(tail->destructor, head_skb->destructor);
4910 swap(tail->sk, head_skb->sk);
4915 kfree_skb_list(segs);
4916 return ERR_PTR(err);
4918 EXPORT_SYMBOL_GPL(skb_segment);
4920 #ifdef CONFIG_SKB_EXTENSIONS
4921 #define SKB_EXT_ALIGN_VALUE 8
4922 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4924 static const u8 skb_ext_type_len[] = {
4925 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4926 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4929 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4931 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4932 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4934 #if IS_ENABLED(CONFIG_MPTCP)
4935 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4937 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4938 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4942 static __always_inline unsigned int skb_ext_total_length(void)
4944 unsigned int l = SKB_EXT_CHUNKSIZEOF(struct skb_ext);
4947 for (i = 0; i < ARRAY_SIZE(skb_ext_type_len); i++)
4948 l += skb_ext_type_len[i];
4953 static void skb_extensions_init(void)
4955 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4956 #if !IS_ENABLED(CONFIG_KCOV_INSTRUMENT_ALL)
4957 BUILD_BUG_ON(skb_ext_total_length() > 255);
4960 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4961 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4963 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4967 static void skb_extensions_init(void) {}
4970 /* The SKB kmem_cache slab is critical for network performance. Never
4971 * merge/alias the slab with similar sized objects. This avoids fragmentation
4972 * that hurts performance of kmem_cache_{alloc,free}_bulk APIs.
4974 #ifndef CONFIG_SLUB_TINY
4975 #define FLAG_SKB_NO_MERGE SLAB_NO_MERGE
4976 #else /* CONFIG_SLUB_TINY - simple loop in kmem_cache_alloc_bulk */
4977 #define FLAG_SKB_NO_MERGE 0
4980 void __init skb_init(void)
4982 net_hotdata.skbuff_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4983 sizeof(struct sk_buff),
4985 SLAB_HWCACHE_ALIGN|SLAB_PANIC|
4987 offsetof(struct sk_buff, cb),
4988 sizeof_field(struct sk_buff, cb),
4990 net_hotdata.skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4991 sizeof(struct sk_buff_fclones),
4993 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4995 /* usercopy should only access first SKB_SMALL_HEAD_HEADROOM bytes.
4996 * struct skb_shared_info is located at the end of skb->head,
4997 * and should not be copied to/from user.
4999 net_hotdata.skb_small_head_cache = kmem_cache_create_usercopy("skbuff_small_head",
5000 SKB_SMALL_HEAD_CACHE_SIZE,
5002 SLAB_HWCACHE_ALIGN | SLAB_PANIC,
5004 SKB_SMALL_HEAD_HEADROOM,
5006 skb_extensions_init();
5010 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
5011 unsigned int recursion_level)
5013 int start = skb_headlen(skb);
5014 int i, copy = start - offset;
5015 struct sk_buff *frag_iter;
5018 if (unlikely(recursion_level >= 24))
5024 sg_set_buf(sg, skb->data + offset, copy);
5026 if ((len -= copy) == 0)
5031 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
5034 WARN_ON(start > offset + len);
5036 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
5037 if ((copy = end - offset) > 0) {
5038 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
5039 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
5044 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
5045 skb_frag_off(frag) + offset - start);
5054 skb_walk_frags(skb, frag_iter) {
5057 WARN_ON(start > offset + len);
5059 end = start + frag_iter->len;
5060 if ((copy = end - offset) > 0) {
5061 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
5066 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
5067 copy, recursion_level + 1);
5068 if (unlikely(ret < 0))
5071 if ((len -= copy) == 0)
5082 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
5083 * @skb: Socket buffer containing the buffers to be mapped
5084 * @sg: The scatter-gather list to map into
5085 * @offset: The offset into the buffer's contents to start mapping
5086 * @len: Length of buffer space to be mapped
5088 * Fill the specified scatter-gather list with mappings/pointers into a
5089 * region of the buffer space attached to a socket buffer. Returns either
5090 * the number of scatterlist items used, or -EMSGSIZE if the contents
5093 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
5095 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
5100 sg_mark_end(&sg[nsg - 1]);
5104 EXPORT_SYMBOL_GPL(skb_to_sgvec);
5106 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
5107 * sglist without mark the sg which contain last skb data as the end.
5108 * So the caller can mannipulate sg list as will when padding new data after
5109 * the first call without calling sg_unmark_end to expend sg list.
5111 * Scenario to use skb_to_sgvec_nomark:
5113 * 2. skb_to_sgvec_nomark(payload1)
5114 * 3. skb_to_sgvec_nomark(payload2)
5116 * This is equivalent to:
5118 * 2. skb_to_sgvec(payload1)
5120 * 4. skb_to_sgvec(payload2)
5122 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
5123 * is more preferable.
5125 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
5126 int offset, int len)
5128 return __skb_to_sgvec(skb, sg, offset, len, 0);
5130 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
5135 * skb_cow_data - Check that a socket buffer's data buffers are writable
5136 * @skb: The socket buffer to check.
5137 * @tailbits: Amount of trailing space to be added
5138 * @trailer: Returned pointer to the skb where the @tailbits space begins
5140 * Make sure that the data buffers attached to a socket buffer are
5141 * writable. If they are not, private copies are made of the data buffers
5142 * and the socket buffer is set to use these instead.
5144 * If @tailbits is given, make sure that there is space to write @tailbits
5145 * bytes of data beyond current end of socket buffer. @trailer will be
5146 * set to point to the skb in which this space begins.
5148 * The number of scatterlist elements required to completely map the
5149 * COW'd and extended socket buffer will be returned.
5151 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
5155 struct sk_buff *skb1, **skb_p;
5157 /* If skb is cloned or its head is paged, reallocate
5158 * head pulling out all the pages (pages are considered not writable
5159 * at the moment even if they are anonymous).
5161 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
5162 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
5165 /* Easy case. Most of packets will go this way. */
5166 if (!skb_has_frag_list(skb)) {
5167 /* A little of trouble, not enough of space for trailer.
5168 * This should not happen, when stack is tuned to generate
5169 * good frames. OK, on miss we reallocate and reserve even more
5170 * space, 128 bytes is fair. */
5172 if (skb_tailroom(skb) < tailbits &&
5173 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
5181 /* Misery. We are in troubles, going to mincer fragments... */
5184 skb_p = &skb_shinfo(skb)->frag_list;
5187 while ((skb1 = *skb_p) != NULL) {
5190 /* The fragment is partially pulled by someone,
5191 * this can happen on input. Copy it and everything
5194 if (skb_shared(skb1))
5197 /* If the skb is the last, worry about trailer. */
5199 if (skb1->next == NULL && tailbits) {
5200 if (skb_shinfo(skb1)->nr_frags ||
5201 skb_has_frag_list(skb1) ||
5202 skb_tailroom(skb1) < tailbits)
5203 ntail = tailbits + 128;
5209 skb_shinfo(skb1)->nr_frags ||
5210 skb_has_frag_list(skb1)) {
5211 struct sk_buff *skb2;
5213 /* Fuck, we are miserable poor guys... */
5215 skb2 = skb_copy(skb1, GFP_ATOMIC);
5217 skb2 = skb_copy_expand(skb1,
5221 if (unlikely(skb2 == NULL))
5225 skb_set_owner_w(skb2, skb1->sk);
5227 /* Looking around. Are we still alive?
5228 * OK, link new skb, drop old one */
5230 skb2->next = skb1->next;
5237 skb_p = &skb1->next;
5242 EXPORT_SYMBOL_GPL(skb_cow_data);
5244 static void sock_rmem_free(struct sk_buff *skb)
5246 struct sock *sk = skb->sk;
5248 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
5251 static void skb_set_err_queue(struct sk_buff *skb)
5253 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
5254 * So, it is safe to (mis)use it to mark skbs on the error queue.
5256 skb->pkt_type = PACKET_OUTGOING;
5257 BUILD_BUG_ON(PACKET_OUTGOING == 0);
5261 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
5263 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
5265 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
5266 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
5271 skb->destructor = sock_rmem_free;
5272 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
5273 skb_set_err_queue(skb);
5275 /* before exiting rcu section, make sure dst is refcounted */
5278 skb_queue_tail(&sk->sk_error_queue, skb);
5279 if (!sock_flag(sk, SOCK_DEAD))
5280 sk_error_report(sk);
5283 EXPORT_SYMBOL(sock_queue_err_skb);
5285 static bool is_icmp_err_skb(const struct sk_buff *skb)
5287 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
5288 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
5291 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
5293 struct sk_buff_head *q = &sk->sk_error_queue;
5294 struct sk_buff *skb, *skb_next = NULL;
5295 bool icmp_next = false;
5296 unsigned long flags;
5298 if (skb_queue_empty_lockless(q))
5301 spin_lock_irqsave(&q->lock, flags);
5302 skb = __skb_dequeue(q);
5303 if (skb && (skb_next = skb_peek(q))) {
5304 icmp_next = is_icmp_err_skb(skb_next);
5306 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
5308 spin_unlock_irqrestore(&q->lock, flags);
5310 if (is_icmp_err_skb(skb) && !icmp_next)
5314 sk_error_report(sk);
5318 EXPORT_SYMBOL(sock_dequeue_err_skb);
5321 * skb_clone_sk - create clone of skb, and take reference to socket
5322 * @skb: the skb to clone
5324 * This function creates a clone of a buffer that holds a reference on
5325 * sk_refcnt. Buffers created via this function are meant to be
5326 * returned using sock_queue_err_skb, or free via kfree_skb.
5328 * When passing buffers allocated with this function to sock_queue_err_skb
5329 * it is necessary to wrap the call with sock_hold/sock_put in order to
5330 * prevent the socket from being released prior to being enqueued on
5331 * the sk_error_queue.
5333 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
5335 struct sock *sk = skb->sk;
5336 struct sk_buff *clone;
5338 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
5341 clone = skb_clone(skb, GFP_ATOMIC);
5348 clone->destructor = sock_efree;
5352 EXPORT_SYMBOL(skb_clone_sk);
5354 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
5359 struct sock_exterr_skb *serr;
5362 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
5364 serr = SKB_EXT_ERR(skb);
5365 memset(serr, 0, sizeof(*serr));
5366 serr->ee.ee_errno = ENOMSG;
5367 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5368 serr->ee.ee_info = tstype;
5369 serr->opt_stats = opt_stats;
5370 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5371 if (READ_ONCE(sk->sk_tsflags) & SOF_TIMESTAMPING_OPT_ID) {
5372 serr->ee.ee_data = skb_shinfo(skb)->tskey;
5374 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5377 err = sock_queue_err_skb(sk, skb);
5383 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5387 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5390 read_lock_bh(&sk->sk_callback_lock);
5391 ret = sk->sk_socket && sk->sk_socket->file &&
5392 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5393 read_unlock_bh(&sk->sk_callback_lock);
5397 void skb_complete_tx_timestamp(struct sk_buff *skb,
5398 struct skb_shared_hwtstamps *hwtstamps)
5400 struct sock *sk = skb->sk;
5402 if (!skb_may_tx_timestamp(sk, false))
5405 /* Take a reference to prevent skb_orphan() from freeing the socket,
5406 * but only if the socket refcount is not zero.
5408 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5409 *skb_hwtstamps(skb) = *hwtstamps;
5410 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5418 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5420 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5421 const struct sk_buff *ack_skb,
5422 struct skb_shared_hwtstamps *hwtstamps,
5423 struct sock *sk, int tstype)
5425 struct sk_buff *skb;
5426 bool tsonly, opt_stats = false;
5432 tsflags = READ_ONCE(sk->sk_tsflags);
5433 if (!hwtstamps && !(tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5434 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5437 tsonly = tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5438 if (!skb_may_tx_timestamp(sk, tsonly))
5443 if ((tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5445 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5450 skb = alloc_skb(0, GFP_ATOMIC);
5452 skb = skb_clone(orig_skb, GFP_ATOMIC);
5454 if (skb_orphan_frags_rx(skb, GFP_ATOMIC)) {
5463 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5465 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5469 *skb_hwtstamps(skb) = *hwtstamps;
5471 __net_timestamp(skb);
5473 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5475 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5477 void skb_tstamp_tx(struct sk_buff *orig_skb,
5478 struct skb_shared_hwtstamps *hwtstamps)
5480 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5483 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5485 #ifdef CONFIG_WIRELESS
5486 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5488 struct sock *sk = skb->sk;
5489 struct sock_exterr_skb *serr;
5492 skb->wifi_acked_valid = 1;
5493 skb->wifi_acked = acked;
5495 serr = SKB_EXT_ERR(skb);
5496 memset(serr, 0, sizeof(*serr));
5497 serr->ee.ee_errno = ENOMSG;
5498 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5500 /* Take a reference to prevent skb_orphan() from freeing the socket,
5501 * but only if the socket refcount is not zero.
5503 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5504 err = sock_queue_err_skb(sk, skb);
5510 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5511 #endif /* CONFIG_WIRELESS */
5514 * skb_partial_csum_set - set up and verify partial csum values for packet
5515 * @skb: the skb to set
5516 * @start: the number of bytes after skb->data to start checksumming.
5517 * @off: the offset from start to place the checksum.
5519 * For untrusted partially-checksummed packets, we need to make sure the values
5520 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5522 * This function checks and sets those values and skb->ip_summed: if this
5523 * returns false you should drop the packet.
5525 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5527 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5528 u32 csum_start = skb_headroom(skb) + (u32)start;
5530 if (unlikely(csum_start >= U16_MAX || csum_end > skb_headlen(skb))) {
5531 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5532 start, off, skb_headroom(skb), skb_headlen(skb));
5535 skb->ip_summed = CHECKSUM_PARTIAL;
5536 skb->csum_start = csum_start;
5537 skb->csum_offset = off;
5538 skb->transport_header = csum_start;
5541 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5543 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5546 if (skb_headlen(skb) >= len)
5549 /* If we need to pullup then pullup to the max, so we
5550 * won't need to do it again.
5555 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5558 if (skb_headlen(skb) < len)
5564 #define MAX_TCP_HDR_LEN (15 * 4)
5566 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5567 typeof(IPPROTO_IP) proto,
5574 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5575 off + MAX_TCP_HDR_LEN);
5576 if (!err && !skb_partial_csum_set(skb, off,
5577 offsetof(struct tcphdr,
5580 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5583 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5584 off + sizeof(struct udphdr));
5585 if (!err && !skb_partial_csum_set(skb, off,
5586 offsetof(struct udphdr,
5589 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5592 return ERR_PTR(-EPROTO);
5595 /* This value should be large enough to cover a tagged ethernet header plus
5596 * maximally sized IP and TCP or UDP headers.
5598 #define MAX_IP_HDR_LEN 128
5600 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5609 err = skb_maybe_pull_tail(skb,
5610 sizeof(struct iphdr),
5615 if (ip_is_fragment(ip_hdr(skb)))
5618 off = ip_hdrlen(skb);
5625 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5627 return PTR_ERR(csum);
5630 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5633 ip_hdr(skb)->protocol, 0);
5640 /* This value should be large enough to cover a tagged ethernet header plus
5641 * an IPv6 header, all options, and a maximal TCP or UDP header.
5643 #define MAX_IPV6_HDR_LEN 256
5645 #define OPT_HDR(type, skb, off) \
5646 (type *)(skb_network_header(skb) + (off))
5648 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5661 off = sizeof(struct ipv6hdr);
5663 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5667 nexthdr = ipv6_hdr(skb)->nexthdr;
5669 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5670 while (off <= len && !done) {
5672 case IPPROTO_DSTOPTS:
5673 case IPPROTO_HOPOPTS:
5674 case IPPROTO_ROUTING: {
5675 struct ipv6_opt_hdr *hp;
5677 err = skb_maybe_pull_tail(skb,
5679 sizeof(struct ipv6_opt_hdr),
5684 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5685 nexthdr = hp->nexthdr;
5686 off += ipv6_optlen(hp);
5690 struct ip_auth_hdr *hp;
5692 err = skb_maybe_pull_tail(skb,
5694 sizeof(struct ip_auth_hdr),
5699 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5700 nexthdr = hp->nexthdr;
5701 off += ipv6_authlen(hp);
5704 case IPPROTO_FRAGMENT: {
5705 struct frag_hdr *hp;
5707 err = skb_maybe_pull_tail(skb,
5709 sizeof(struct frag_hdr),
5714 hp = OPT_HDR(struct frag_hdr, skb, off);
5716 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5719 nexthdr = hp->nexthdr;
5720 off += sizeof(struct frag_hdr);
5731 if (!done || fragment)
5734 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5736 return PTR_ERR(csum);
5739 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5740 &ipv6_hdr(skb)->daddr,
5741 skb->len - off, nexthdr, 0);
5749 * skb_checksum_setup - set up partial checksum offset
5750 * @skb: the skb to set up
5751 * @recalculate: if true the pseudo-header checksum will be recalculated
5753 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5757 switch (skb->protocol) {
5758 case htons(ETH_P_IP):
5759 err = skb_checksum_setup_ipv4(skb, recalculate);
5762 case htons(ETH_P_IPV6):
5763 err = skb_checksum_setup_ipv6(skb, recalculate);
5773 EXPORT_SYMBOL(skb_checksum_setup);
5776 * skb_checksum_maybe_trim - maybe trims the given skb
5777 * @skb: the skb to check
5778 * @transport_len: the data length beyond the network header
5780 * Checks whether the given skb has data beyond the given transport length.
5781 * If so, returns a cloned skb trimmed to this transport length.
5782 * Otherwise returns the provided skb. Returns NULL in error cases
5783 * (e.g. transport_len exceeds skb length or out-of-memory).
5785 * Caller needs to set the skb transport header and free any returned skb if it
5786 * differs from the provided skb.
5788 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5789 unsigned int transport_len)
5791 struct sk_buff *skb_chk;
5792 unsigned int len = skb_transport_offset(skb) + transport_len;
5797 else if (skb->len == len)
5800 skb_chk = skb_clone(skb, GFP_ATOMIC);
5804 ret = pskb_trim_rcsum(skb_chk, len);
5814 * skb_checksum_trimmed - validate checksum of an skb
5815 * @skb: the skb to check
5816 * @transport_len: the data length beyond the network header
5817 * @skb_chkf: checksum function to use
5819 * Applies the given checksum function skb_chkf to the provided skb.
5820 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5822 * If the skb has data beyond the given transport length, then a
5823 * trimmed & cloned skb is checked and returned.
5825 * Caller needs to set the skb transport header and free any returned skb if it
5826 * differs from the provided skb.
5828 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5829 unsigned int transport_len,
5830 __sum16(*skb_chkf)(struct sk_buff *skb))
5832 struct sk_buff *skb_chk;
5833 unsigned int offset = skb_transport_offset(skb);
5836 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5840 if (!pskb_may_pull(skb_chk, offset))
5843 skb_pull_rcsum(skb_chk, offset);
5844 ret = skb_chkf(skb_chk);
5845 skb_push_rcsum(skb_chk, offset);
5853 if (skb_chk && skb_chk != skb)
5859 EXPORT_SYMBOL(skb_checksum_trimmed);
5861 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5863 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5866 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5868 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5871 skb_release_head_state(skb);
5872 kmem_cache_free(net_hotdata.skbuff_cache, skb);
5877 EXPORT_SYMBOL(kfree_skb_partial);
5880 * skb_try_coalesce - try to merge skb to prior one
5882 * @from: buffer to add
5883 * @fragstolen: pointer to boolean
5884 * @delta_truesize: how much more was allocated than was requested
5886 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5887 bool *fragstolen, int *delta_truesize)
5889 struct skb_shared_info *to_shinfo, *from_shinfo;
5890 int i, delta, len = from->len;
5892 *fragstolen = false;
5897 /* In general, avoid mixing page_pool and non-page_pool allocated
5898 * pages within the same SKB. In theory we could take full
5899 * references if @from is cloned and !@to->pp_recycle but its
5900 * tricky (due to potential race with the clone disappearing) and
5901 * rare, so not worth dealing with.
5903 if (to->pp_recycle != from->pp_recycle)
5906 if (len <= skb_tailroom(to)) {
5908 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5909 *delta_truesize = 0;
5913 to_shinfo = skb_shinfo(to);
5914 from_shinfo = skb_shinfo(from);
5915 if (to_shinfo->frag_list || from_shinfo->frag_list)
5917 if (skb_zcopy(to) || skb_zcopy(from))
5920 if (skb_headlen(from) != 0) {
5922 unsigned int offset;
5924 if (to_shinfo->nr_frags +
5925 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5928 if (skb_head_is_locked(from))
5931 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5933 page = virt_to_head_page(from->head);
5934 offset = from->data - (unsigned char *)page_address(page);
5936 skb_fill_page_desc(to, to_shinfo->nr_frags,
5937 page, offset, skb_headlen(from));
5940 if (to_shinfo->nr_frags +
5941 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5944 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5947 WARN_ON_ONCE(delta < len);
5949 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5951 from_shinfo->nr_frags * sizeof(skb_frag_t));
5952 to_shinfo->nr_frags += from_shinfo->nr_frags;
5954 if (!skb_cloned(from))
5955 from_shinfo->nr_frags = 0;
5957 /* if the skb is not cloned this does nothing
5958 * since we set nr_frags to 0.
5960 if (skb_pp_frag_ref(from)) {
5961 for (i = 0; i < from_shinfo->nr_frags; i++)
5962 __skb_frag_ref(&from_shinfo->frags[i]);
5965 to->truesize += delta;
5967 to->data_len += len;
5969 *delta_truesize = delta;
5972 EXPORT_SYMBOL(skb_try_coalesce);
5975 * skb_scrub_packet - scrub an skb
5977 * @skb: buffer to clean
5978 * @xnet: packet is crossing netns
5980 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5981 * into/from a tunnel. Some information have to be cleared during these
5983 * skb_scrub_packet can also be used to clean a skb before injecting it in
5984 * another namespace (@xnet == true). We have to clear all information in the
5985 * skb that could impact namespace isolation.
5987 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5989 skb->pkt_type = PACKET_HOST;
5995 nf_reset_trace(skb);
5997 #ifdef CONFIG_NET_SWITCHDEV
5998 skb->offload_fwd_mark = 0;
5999 skb->offload_l3_fwd_mark = 0;
6007 skb_clear_tstamp(skb);
6009 EXPORT_SYMBOL_GPL(skb_scrub_packet);
6011 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
6013 int mac_len, meta_len;
6016 if (skb_cow(skb, skb_headroom(skb)) < 0) {
6021 mac_len = skb->data - skb_mac_header(skb);
6022 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
6023 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
6024 mac_len - VLAN_HLEN - ETH_TLEN);
6027 meta_len = skb_metadata_len(skb);
6029 meta = skb_metadata_end(skb) - meta_len;
6030 memmove(meta + VLAN_HLEN, meta, meta_len);
6033 skb->mac_header += VLAN_HLEN;
6037 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
6039 struct vlan_hdr *vhdr;
6042 if (unlikely(skb_vlan_tag_present(skb))) {
6043 /* vlan_tci is already set-up so leave this for another time */
6047 skb = skb_share_check(skb, GFP_ATOMIC);
6050 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
6051 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
6054 vhdr = (struct vlan_hdr *)skb->data;
6055 vlan_tci = ntohs(vhdr->h_vlan_TCI);
6056 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
6058 skb_pull_rcsum(skb, VLAN_HLEN);
6059 vlan_set_encap_proto(skb, vhdr);
6061 skb = skb_reorder_vlan_header(skb);
6065 skb_reset_network_header(skb);
6066 if (!skb_transport_header_was_set(skb))
6067 skb_reset_transport_header(skb);
6068 skb_reset_mac_len(skb);
6076 EXPORT_SYMBOL(skb_vlan_untag);
6078 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
6080 if (!pskb_may_pull(skb, write_len))
6083 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
6086 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
6088 EXPORT_SYMBOL(skb_ensure_writable);
6090 int skb_ensure_writable_head_tail(struct sk_buff *skb, struct net_device *dev)
6092 int needed_headroom = dev->needed_headroom;
6093 int needed_tailroom = dev->needed_tailroom;
6095 /* For tail taggers, we need to pad short frames ourselves, to ensure
6096 * that the tail tag does not fail at its role of being at the end of
6097 * the packet, once the conduit interface pads the frame. Account for
6098 * that pad length here, and pad later.
6100 if (unlikely(needed_tailroom && skb->len < ETH_ZLEN))
6101 needed_tailroom += ETH_ZLEN - skb->len;
6102 /* skb_headroom() returns unsigned int... */
6103 needed_headroom = max_t(int, needed_headroom - skb_headroom(skb), 0);
6104 needed_tailroom = max_t(int, needed_tailroom - skb_tailroom(skb), 0);
6106 if (likely(!needed_headroom && !needed_tailroom && !skb_cloned(skb)))
6107 /* No reallocation needed, yay! */
6110 return pskb_expand_head(skb, needed_headroom, needed_tailroom,
6113 EXPORT_SYMBOL(skb_ensure_writable_head_tail);
6115 /* remove VLAN header from packet and update csum accordingly.
6116 * expects a non skb_vlan_tag_present skb with a vlan tag payload
6118 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
6120 int offset = skb->data - skb_mac_header(skb);
6123 if (WARN_ONCE(offset,
6124 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
6129 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
6133 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6135 vlan_remove_tag(skb, vlan_tci);
6137 skb->mac_header += VLAN_HLEN;
6139 if (skb_network_offset(skb) < ETH_HLEN)
6140 skb_set_network_header(skb, ETH_HLEN);
6142 skb_reset_mac_len(skb);
6146 EXPORT_SYMBOL(__skb_vlan_pop);
6148 /* Pop a vlan tag either from hwaccel or from payload.
6149 * Expects skb->data at mac header.
6151 int skb_vlan_pop(struct sk_buff *skb)
6157 if (likely(skb_vlan_tag_present(skb))) {
6158 __vlan_hwaccel_clear_tag(skb);
6160 if (unlikely(!eth_type_vlan(skb->protocol)))
6163 err = __skb_vlan_pop(skb, &vlan_tci);
6167 /* move next vlan tag to hw accel tag */
6168 if (likely(!eth_type_vlan(skb->protocol)))
6171 vlan_proto = skb->protocol;
6172 err = __skb_vlan_pop(skb, &vlan_tci);
6176 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6179 EXPORT_SYMBOL(skb_vlan_pop);
6181 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
6182 * Expects skb->data at mac header.
6184 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
6186 if (skb_vlan_tag_present(skb)) {
6187 int offset = skb->data - skb_mac_header(skb);
6190 if (WARN_ONCE(offset,
6191 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
6196 err = __vlan_insert_tag(skb, skb->vlan_proto,
6197 skb_vlan_tag_get(skb));
6201 skb->protocol = skb->vlan_proto;
6202 skb->mac_len += VLAN_HLEN;
6204 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6206 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6209 EXPORT_SYMBOL(skb_vlan_push);
6212 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
6214 * @skb: Socket buffer to modify
6216 * Drop the Ethernet header of @skb.
6218 * Expects that skb->data points to the mac header and that no VLAN tags are
6221 * Returns 0 on success, -errno otherwise.
6223 int skb_eth_pop(struct sk_buff *skb)
6225 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
6226 skb_network_offset(skb) < ETH_HLEN)
6229 skb_pull_rcsum(skb, ETH_HLEN);
6230 skb_reset_mac_header(skb);
6231 skb_reset_mac_len(skb);
6235 EXPORT_SYMBOL(skb_eth_pop);
6238 * skb_eth_push() - Add a new Ethernet header at the head of a packet
6240 * @skb: Socket buffer to modify
6241 * @dst: Destination MAC address of the new header
6242 * @src: Source MAC address of the new header
6244 * Prepend @skb with a new Ethernet header.
6246 * Expects that skb->data points to the mac header, which must be empty.
6248 * Returns 0 on success, -errno otherwise.
6250 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6251 const unsigned char *src)
6256 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6259 err = skb_cow_head(skb, sizeof(*eth));
6263 skb_push(skb, sizeof(*eth));
6264 skb_reset_mac_header(skb);
6265 skb_reset_mac_len(skb);
6268 ether_addr_copy(eth->h_dest, dst);
6269 ether_addr_copy(eth->h_source, src);
6270 eth->h_proto = skb->protocol;
6272 skb_postpush_rcsum(skb, eth, sizeof(*eth));
6276 EXPORT_SYMBOL(skb_eth_push);
6278 /* Update the ethertype of hdr and the skb csum value if required. */
6279 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6282 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6283 __be16 diff[] = { ~hdr->h_proto, ethertype };
6285 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6288 hdr->h_proto = ethertype;
6292 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6296 * @mpls_lse: MPLS label stack entry to push
6297 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6298 * @mac_len: length of the MAC header
6299 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6302 * Expects skb->data at mac header.
6304 * Returns 0 on success, -errno otherwise.
6306 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6307 int mac_len, bool ethernet)
6309 struct mpls_shim_hdr *lse;
6312 if (unlikely(!eth_p_mpls(mpls_proto)))
6315 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6316 if (skb->encapsulation)
6319 err = skb_cow_head(skb, MPLS_HLEN);
6323 if (!skb->inner_protocol) {
6324 skb_set_inner_network_header(skb, skb_network_offset(skb));
6325 skb_set_inner_protocol(skb, skb->protocol);
6328 skb_push(skb, MPLS_HLEN);
6329 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6331 skb_reset_mac_header(skb);
6332 skb_set_network_header(skb, mac_len);
6333 skb_reset_mac_len(skb);
6335 lse = mpls_hdr(skb);
6336 lse->label_stack_entry = mpls_lse;
6337 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6339 if (ethernet && mac_len >= ETH_HLEN)
6340 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6341 skb->protocol = mpls_proto;
6345 EXPORT_SYMBOL_GPL(skb_mpls_push);
6348 * skb_mpls_pop() - pop the outermost MPLS header
6351 * @next_proto: ethertype of header after popped MPLS header
6352 * @mac_len: length of the MAC header
6353 * @ethernet: flag to indicate if the packet is ethernet
6355 * Expects skb->data at mac header.
6357 * Returns 0 on success, -errno otherwise.
6359 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6364 if (unlikely(!eth_p_mpls(skb->protocol)))
6367 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6371 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6372 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6375 __skb_pull(skb, MPLS_HLEN);
6376 skb_reset_mac_header(skb);
6377 skb_set_network_header(skb, mac_len);
6379 if (ethernet && mac_len >= ETH_HLEN) {
6382 /* use mpls_hdr() to get ethertype to account for VLANs. */
6383 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6384 skb_mod_eth_type(skb, hdr, next_proto);
6386 skb->protocol = next_proto;
6390 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6393 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6396 * @mpls_lse: new MPLS label stack entry to update to
6398 * Expects skb->data at mac header.
6400 * Returns 0 on success, -errno otherwise.
6402 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6406 if (unlikely(!eth_p_mpls(skb->protocol)))
6409 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6413 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6414 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6416 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6419 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6423 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6426 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6430 * Expects skb->data at mac header.
6432 * Returns 0 on success, -errno otherwise.
6434 int skb_mpls_dec_ttl(struct sk_buff *skb)
6439 if (unlikely(!eth_p_mpls(skb->protocol)))
6442 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6445 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6446 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6450 lse &= ~MPLS_LS_TTL_MASK;
6451 lse |= ttl << MPLS_LS_TTL_SHIFT;
6453 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6455 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6458 * alloc_skb_with_frags - allocate skb with page frags
6460 * @header_len: size of linear part
6461 * @data_len: needed length in frags
6462 * @order: max page order desired.
6463 * @errcode: pointer to error code if any
6464 * @gfp_mask: allocation mask
6466 * This can be used to allocate a paged skb, given a maximal order for frags.
6468 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6469 unsigned long data_len,
6474 unsigned long chunk;
6475 struct sk_buff *skb;
6479 *errcode = -EMSGSIZE;
6480 if (unlikely(data_len > MAX_SKB_FRAGS * (PAGE_SIZE << order)))
6483 *errcode = -ENOBUFS;
6484 skb = alloc_skb(header_len, gfp_mask);
6489 if (nr_frags == MAX_SKB_FRAGS - 1)
6491 while (order && PAGE_ALIGN(data_len) < (PAGE_SIZE << order))
6495 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6504 page = alloc_page(gfp_mask);
6508 chunk = min_t(unsigned long, data_len,
6509 PAGE_SIZE << order);
6510 skb_fill_page_desc(skb, nr_frags, page, 0, chunk);
6512 skb->truesize += (PAGE_SIZE << order);
6521 EXPORT_SYMBOL(alloc_skb_with_frags);
6523 /* carve out the first off bytes from skb when off < headlen */
6524 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6525 const int headlen, gfp_t gfp_mask)
6528 unsigned int size = skb_end_offset(skb);
6529 int new_hlen = headlen - off;
6532 if (skb_pfmemalloc(skb))
6533 gfp_mask |= __GFP_MEMALLOC;
6535 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6538 size = SKB_WITH_OVERHEAD(size);
6540 /* Copy real data, and all frags */
6541 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6544 memcpy((struct skb_shared_info *)(data + size),
6546 offsetof(struct skb_shared_info,
6547 frags[skb_shinfo(skb)->nr_frags]));
6548 if (skb_cloned(skb)) {
6549 /* drop the old head gracefully */
6550 if (skb_orphan_frags(skb, gfp_mask)) {
6551 skb_kfree_head(data, size);
6554 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6555 skb_frag_ref(skb, i);
6556 if (skb_has_frag_list(skb))
6557 skb_clone_fraglist(skb);
6558 skb_release_data(skb, SKB_CONSUMED);
6560 /* we can reuse existing recount- all we did was
6569 skb_set_end_offset(skb, size);
6570 skb_set_tail_pointer(skb, skb_headlen(skb));
6571 skb_headers_offset_update(skb, 0);
6575 atomic_set(&skb_shinfo(skb)->dataref, 1);
6580 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6582 /* carve out the first eat bytes from skb's frag_list. May recurse into
6585 static int pskb_carve_frag_list(struct sk_buff *skb,
6586 struct skb_shared_info *shinfo, int eat,
6589 struct sk_buff *list = shinfo->frag_list;
6590 struct sk_buff *clone = NULL;
6591 struct sk_buff *insp = NULL;
6595 pr_err("Not enough bytes to eat. Want %d\n", eat);
6598 if (list->len <= eat) {
6599 /* Eaten as whole. */
6604 /* Eaten partially. */
6605 if (skb_shared(list)) {
6606 clone = skb_clone(list, gfp_mask);
6612 /* This may be pulled without problems. */
6615 if (pskb_carve(list, eat, gfp_mask) < 0) {
6623 /* Free pulled out fragments. */
6624 while ((list = shinfo->frag_list) != insp) {
6625 shinfo->frag_list = list->next;
6628 /* And insert new clone at head. */
6631 shinfo->frag_list = clone;
6636 /* carve off first len bytes from skb. Split line (off) is in the
6637 * non-linear part of skb
6639 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6640 int pos, gfp_t gfp_mask)
6643 unsigned int size = skb_end_offset(skb);
6645 const int nfrags = skb_shinfo(skb)->nr_frags;
6646 struct skb_shared_info *shinfo;
6648 if (skb_pfmemalloc(skb))
6649 gfp_mask |= __GFP_MEMALLOC;
6651 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6654 size = SKB_WITH_OVERHEAD(size);
6656 memcpy((struct skb_shared_info *)(data + size),
6657 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6658 if (skb_orphan_frags(skb, gfp_mask)) {
6659 skb_kfree_head(data, size);
6662 shinfo = (struct skb_shared_info *)(data + size);
6663 for (i = 0; i < nfrags; i++) {
6664 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6666 if (pos + fsize > off) {
6667 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6671 * We have two variants in this case:
6672 * 1. Move all the frag to the second
6673 * part, if it is possible. F.e.
6674 * this approach is mandatory for TUX,
6675 * where splitting is expensive.
6676 * 2. Split is accurately. We make this.
6678 skb_frag_off_add(&shinfo->frags[0], off - pos);
6679 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6681 skb_frag_ref(skb, i);
6686 shinfo->nr_frags = k;
6687 if (skb_has_frag_list(skb))
6688 skb_clone_fraglist(skb);
6690 /* split line is in frag list */
6691 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6692 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6693 if (skb_has_frag_list(skb))
6694 kfree_skb_list(skb_shinfo(skb)->frag_list);
6695 skb_kfree_head(data, size);
6698 skb_release_data(skb, SKB_CONSUMED);
6703 skb_set_end_offset(skb, size);
6704 skb_reset_tail_pointer(skb);
6705 skb_headers_offset_update(skb, 0);
6710 skb->data_len = skb->len;
6711 atomic_set(&skb_shinfo(skb)->dataref, 1);
6715 /* remove len bytes from the beginning of the skb */
6716 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6718 int headlen = skb_headlen(skb);
6721 return pskb_carve_inside_header(skb, len, headlen, gfp);
6723 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6726 /* Extract to_copy bytes starting at off from skb, and return this in
6729 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6730 int to_copy, gfp_t gfp)
6732 struct sk_buff *clone = skb_clone(skb, gfp);
6737 if (pskb_carve(clone, off, gfp) < 0 ||
6738 pskb_trim(clone, to_copy)) {
6744 EXPORT_SYMBOL(pskb_extract);
6747 * skb_condense - try to get rid of fragments/frag_list if possible
6750 * Can be used to save memory before skb is added to a busy queue.
6751 * If packet has bytes in frags and enough tail room in skb->head,
6752 * pull all of them, so that we can free the frags right now and adjust
6755 * We do not reallocate skb->head thus can not fail.
6756 * Caller must re-evaluate skb->truesize if needed.
6758 void skb_condense(struct sk_buff *skb)
6760 if (skb->data_len) {
6761 if (skb->data_len > skb->end - skb->tail ||
6765 /* Nice, we can free page frag(s) right now */
6766 __pskb_pull_tail(skb, skb->data_len);
6768 /* At this point, skb->truesize might be over estimated,
6769 * because skb had a fragment, and fragments do not tell
6771 * When we pulled its content into skb->head, fragment
6772 * was freed, but __pskb_pull_tail() could not possibly
6773 * adjust skb->truesize, not knowing the frag truesize.
6775 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6777 EXPORT_SYMBOL(skb_condense);
6779 #ifdef CONFIG_SKB_EXTENSIONS
6780 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6782 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6786 * __skb_ext_alloc - allocate a new skb extensions storage
6788 * @flags: See kmalloc().
6790 * Returns the newly allocated pointer. The pointer can later attached to a
6791 * skb via __skb_ext_set().
6792 * Note: caller must handle the skb_ext as an opaque data.
6794 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6796 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6799 memset(new->offset, 0, sizeof(new->offset));
6800 refcount_set(&new->refcnt, 1);
6806 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6807 unsigned int old_active)
6809 struct skb_ext *new;
6811 if (refcount_read(&old->refcnt) == 1)
6814 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6818 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6819 refcount_set(&new->refcnt, 1);
6822 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6823 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6826 for (i = 0; i < sp->len; i++)
6827 xfrm_state_hold(sp->xvec[i]);
6830 #ifdef CONFIG_MCTP_FLOWS
6831 if (old_active & (1 << SKB_EXT_MCTP)) {
6832 struct mctp_flow *flow = skb_ext_get_ptr(old, SKB_EXT_MCTP);
6835 refcount_inc(&flow->key->refs);
6843 * __skb_ext_set - attach the specified extension storage to this skb
6846 * @ext: extension storage previously allocated via __skb_ext_alloc()
6848 * Existing extensions, if any, are cleared.
6850 * Returns the pointer to the extension.
6852 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6853 struct skb_ext *ext)
6855 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6858 newlen = newoff + skb_ext_type_len[id];
6859 ext->chunks = newlen;
6860 ext->offset[id] = newoff;
6861 skb->extensions = ext;
6862 skb->active_extensions = 1 << id;
6863 return skb_ext_get_ptr(ext, id);
6867 * skb_ext_add - allocate space for given extension, COW if needed
6869 * @id: extension to allocate space for
6871 * Allocates enough space for the given extension.
6872 * If the extension is already present, a pointer to that extension
6875 * If the skb was cloned, COW applies and the returned memory can be
6876 * modified without changing the extension space of clones buffers.
6878 * Returns pointer to the extension or NULL on allocation failure.
6880 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6882 struct skb_ext *new, *old = NULL;
6883 unsigned int newlen, newoff;
6885 if (skb->active_extensions) {
6886 old = skb->extensions;
6888 new = skb_ext_maybe_cow(old, skb->active_extensions);
6892 if (__skb_ext_exist(new, id))
6895 newoff = new->chunks;
6897 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6899 new = __skb_ext_alloc(GFP_ATOMIC);
6904 newlen = newoff + skb_ext_type_len[id];
6905 new->chunks = newlen;
6906 new->offset[id] = newoff;
6909 skb->extensions = new;
6910 skb->active_extensions |= 1 << id;
6911 return skb_ext_get_ptr(new, id);
6913 EXPORT_SYMBOL(skb_ext_add);
6916 static void skb_ext_put_sp(struct sec_path *sp)
6920 for (i = 0; i < sp->len; i++)
6921 xfrm_state_put(sp->xvec[i]);
6925 #ifdef CONFIG_MCTP_FLOWS
6926 static void skb_ext_put_mctp(struct mctp_flow *flow)
6929 mctp_key_unref(flow->key);
6933 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6935 struct skb_ext *ext = skb->extensions;
6937 skb->active_extensions &= ~(1 << id);
6938 if (skb->active_extensions == 0) {
6939 skb->extensions = NULL;
6942 } else if (id == SKB_EXT_SEC_PATH &&
6943 refcount_read(&ext->refcnt) == 1) {
6944 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6951 EXPORT_SYMBOL(__skb_ext_del);
6953 void __skb_ext_put(struct skb_ext *ext)
6955 /* If this is last clone, nothing can increment
6956 * it after check passes. Avoids one atomic op.
6958 if (refcount_read(&ext->refcnt) == 1)
6961 if (!refcount_dec_and_test(&ext->refcnt))
6965 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6966 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6968 #ifdef CONFIG_MCTP_FLOWS
6969 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6970 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6973 kmem_cache_free(skbuff_ext_cache, ext);
6975 EXPORT_SYMBOL(__skb_ext_put);
6976 #endif /* CONFIG_SKB_EXTENSIONS */
6978 static void kfree_skb_napi_cache(struct sk_buff *skb)
6980 /* if SKB is a clone, don't handle this case */
6981 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
6987 __napi_kfree_skb(skb, SKB_CONSUMED);
6992 * skb_attempt_defer_free - queue skb for remote freeing
6995 * Put @skb in a per-cpu list, using the cpu which
6996 * allocated the skb/pages to reduce false sharing
6997 * and memory zone spinlock contention.
6999 void skb_attempt_defer_free(struct sk_buff *skb)
7001 int cpu = skb->alloc_cpu;
7002 struct softnet_data *sd;
7003 unsigned int defer_max;
7006 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
7008 cpu == raw_smp_processor_id()) {
7009 nodefer: kfree_skb_napi_cache(skb);
7013 DEBUG_NET_WARN_ON_ONCE(skb_dst(skb));
7014 DEBUG_NET_WARN_ON_ONCE(skb->destructor);
7016 sd = &per_cpu(softnet_data, cpu);
7017 defer_max = READ_ONCE(sysctl_skb_defer_max);
7018 if (READ_ONCE(sd->defer_count) >= defer_max)
7021 spin_lock_bh(&sd->defer_lock);
7022 /* Send an IPI every time queue reaches half capacity. */
7023 kick = sd->defer_count == (defer_max >> 1);
7024 /* Paired with the READ_ONCE() few lines above */
7025 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
7027 skb->next = sd->defer_list;
7028 /* Paired with READ_ONCE() in skb_defer_free_flush() */
7029 WRITE_ONCE(sd->defer_list, skb);
7030 spin_unlock_bh(&sd->defer_lock);
7032 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
7033 * if we are unlucky enough (this seems very unlikely).
7036 kick_defer_list_purge(sd, cpu);
7039 static void skb_splice_csum_page(struct sk_buff *skb, struct page *page,
7040 size_t offset, size_t len)
7045 kaddr = kmap_local_page(page);
7046 csum = csum_partial(kaddr + offset, len, 0);
7047 kunmap_local(kaddr);
7048 skb->csum = csum_block_add(skb->csum, csum, skb->len);
7052 * skb_splice_from_iter - Splice (or copy) pages to skbuff
7053 * @skb: The buffer to add pages to
7054 * @iter: Iterator representing the pages to be added
7055 * @maxsize: Maximum amount of pages to be added
7056 * @gfp: Allocation flags
7058 * This is a common helper function for supporting MSG_SPLICE_PAGES. It
7059 * extracts pages from an iterator and adds them to the socket buffer if
7060 * possible, copying them to fragments if not possible (such as if they're slab
7063 * Returns the amount of data spliced/copied or -EMSGSIZE if there's
7064 * insufficient space in the buffer to transfer anything.
7066 ssize_t skb_splice_from_iter(struct sk_buff *skb, struct iov_iter *iter,
7067 ssize_t maxsize, gfp_t gfp)
7069 size_t frag_limit = READ_ONCE(sysctl_max_skb_frags);
7070 struct page *pages[8], **ppages = pages;
7071 ssize_t spliced = 0, ret = 0;
7074 while (iter->count > 0) {
7075 ssize_t space, nr, len;
7079 space = frag_limit - skb_shinfo(skb)->nr_frags;
7083 /* We might be able to coalesce without increasing nr_frags */
7084 nr = clamp_t(size_t, space, 1, ARRAY_SIZE(pages));
7086 len = iov_iter_extract_pages(iter, &ppages, maxsize, nr, 0, &off);
7094 struct page *page = pages[i++];
7095 size_t part = min_t(size_t, PAGE_SIZE - off, len);
7098 if (WARN_ON_ONCE(!sendpage_ok(page)))
7101 ret = skb_append_pagefrags(skb, page, off, part,
7104 iov_iter_revert(iter, len);
7108 if (skb->ip_summed == CHECKSUM_NONE)
7109 skb_splice_csum_page(skb, page, off, part);
7122 skb_len_add(skb, spliced);
7123 return spliced ?: ret;
7125 EXPORT_SYMBOL(skb_splice_from_iter);
7127 static __always_inline
7128 size_t memcpy_from_iter_csum(void *iter_from, size_t progress,
7129 size_t len, void *to, void *priv2)
7131 __wsum *csum = priv2;
7132 __wsum next = csum_partial_copy_nocheck(iter_from, to + progress, len);
7134 *csum = csum_block_add(*csum, next, progress);
7138 static __always_inline
7139 size_t copy_from_user_iter_csum(void __user *iter_from, size_t progress,
7140 size_t len, void *to, void *priv2)
7142 __wsum next, *csum = priv2;
7144 next = csum_and_copy_from_user(iter_from, to + progress, len);
7145 *csum = csum_block_add(*csum, next, progress);
7146 return next ? 0 : len;
7149 bool csum_and_copy_from_iter_full(void *addr, size_t bytes,
7150 __wsum *csum, struct iov_iter *i)
7154 if (WARN_ON_ONCE(!i->data_source))
7156 copied = iterate_and_advance2(i, bytes, addr, csum,
7157 copy_from_user_iter_csum,
7158 memcpy_from_iter_csum);
7159 if (likely(copied == bytes))
7161 iov_iter_revert(i, copied);
7164 EXPORT_SYMBOL(csum_and_copy_from_iter_full);