1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Routines having to do with the 'struct sk_buff' memory handlers.
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 /* kcm_write_msgs() relies on casting paged frags to bio_vec to use
113 * iov_iter_bvec(). These static asserts ensure the cast is valid is long as the
116 static_assert(offsetof(struct bio_vec, bv_page) ==
117 offsetof(skb_frag_t, netmem));
118 static_assert(sizeof_field(struct bio_vec, bv_page) ==
119 sizeof_field(skb_frag_t, netmem));
121 static_assert(offsetof(struct bio_vec, bv_len) == offsetof(skb_frag_t, len));
122 static_assert(sizeof_field(struct bio_vec, bv_len) ==
123 sizeof_field(skb_frag_t, len));
125 static_assert(offsetof(struct bio_vec, bv_offset) ==
126 offsetof(skb_frag_t, offset));
127 static_assert(sizeof_field(struct bio_vec, bv_offset) ==
128 sizeof_field(skb_frag_t, offset));
131 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
132 static const char * const drop_reasons[] = {
133 [SKB_CONSUMED] = "CONSUMED",
134 DEFINE_DROP_REASON(FN, FN)
137 static const struct drop_reason_list drop_reasons_core = {
138 .reasons = drop_reasons,
139 .n_reasons = ARRAY_SIZE(drop_reasons),
142 const struct drop_reason_list __rcu *
143 drop_reasons_by_subsys[SKB_DROP_REASON_SUBSYS_NUM] = {
144 [SKB_DROP_REASON_SUBSYS_CORE] = RCU_INITIALIZER(&drop_reasons_core),
146 EXPORT_SYMBOL(drop_reasons_by_subsys);
149 * drop_reasons_register_subsys - register another drop reason subsystem
150 * @subsys: the subsystem to register, must not be the core
151 * @list: the list of drop reasons within the subsystem, must point to
152 * a statically initialized list
154 void drop_reasons_register_subsys(enum skb_drop_reason_subsys subsys,
155 const struct drop_reason_list *list)
157 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
158 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
159 "invalid subsystem %d\n", subsys))
162 /* must point to statically allocated memory, so INIT is OK */
163 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], list);
165 EXPORT_SYMBOL_GPL(drop_reasons_register_subsys);
168 * drop_reasons_unregister_subsys - unregister a drop reason subsystem
169 * @subsys: the subsystem to remove, must not be the core
171 * Note: This will synchronize_rcu() to ensure no users when it returns.
173 void drop_reasons_unregister_subsys(enum skb_drop_reason_subsys subsys)
175 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
176 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
177 "invalid subsystem %d\n", subsys))
180 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], NULL);
184 EXPORT_SYMBOL_GPL(drop_reasons_unregister_subsys);
187 * skb_panic - private function for out-of-line support
191 * @msg: skb_over_panic or skb_under_panic
193 * Out-of-line support for skb_put() and skb_push().
194 * Called via the wrapper skb_over_panic() or skb_under_panic().
195 * Keep out of line to prevent kernel bloat.
196 * __builtin_return_address is not used because it is not always reliable.
198 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
201 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
202 msg, addr, skb->len, sz, skb->head, skb->data,
203 (unsigned long)skb->tail, (unsigned long)skb->end,
204 skb->dev ? skb->dev->name : "<NULL>");
208 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
210 skb_panic(skb, sz, addr, __func__);
213 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
215 skb_panic(skb, sz, addr, __func__);
218 #define NAPI_SKB_CACHE_SIZE 64
219 #define NAPI_SKB_CACHE_BULK 16
220 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
222 #if PAGE_SIZE == SZ_4K
224 #define NAPI_HAS_SMALL_PAGE_FRAG 1
225 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) ((nc).pfmemalloc)
227 /* specialized page frag allocator using a single order 0 page
228 * and slicing it into 1K sized fragment. Constrained to systems
229 * with a very limited amount of 1K fragments fitting a single
230 * page - to avoid excessive truesize underestimation
233 struct page_frag_1k {
239 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
244 offset = nc->offset - SZ_1K;
245 if (likely(offset >= 0))
248 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
252 nc->va = page_address(page);
253 nc->pfmemalloc = page_is_pfmemalloc(page);
254 offset = PAGE_SIZE - SZ_1K;
255 page_ref_add(page, offset / SZ_1K);
259 return nc->va + offset;
263 /* the small page is actually unused in this build; add dummy helpers
264 * to please the compiler and avoid later preprocessor's conditionals
266 #define NAPI_HAS_SMALL_PAGE_FRAG 0
267 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) false
269 struct page_frag_1k {
272 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
279 struct napi_alloc_cache {
280 local_lock_t bh_lock;
281 struct page_frag_cache page;
282 struct page_frag_1k page_small;
283 unsigned int skb_count;
284 void *skb_cache[NAPI_SKB_CACHE_SIZE];
287 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
288 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache) = {
289 .bh_lock = INIT_LOCAL_LOCK(bh_lock),
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);
314 fragsz = SKB_DATA_ALIGN(fragsz);
316 local_lock_nested_bh(&napi_alloc_cache.bh_lock);
317 data = __page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC,
319 local_unlock_nested_bh(&napi_alloc_cache.bh_lock);
323 EXPORT_SYMBOL(__napi_alloc_frag_align);
325 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
329 if (in_hardirq() || irqs_disabled()) {
330 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
332 fragsz = SKB_DATA_ALIGN(fragsz);
333 data = __page_frag_alloc_align(nc, fragsz, GFP_ATOMIC,
337 data = __napi_alloc_frag_align(fragsz, align_mask);
342 EXPORT_SYMBOL(__netdev_alloc_frag_align);
344 static struct sk_buff *napi_skb_cache_get(void)
346 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
349 local_lock_nested_bh(&napi_alloc_cache.bh_lock);
350 if (unlikely(!nc->skb_count)) {
351 nc->skb_count = kmem_cache_alloc_bulk(net_hotdata.skbuff_cache,
355 if (unlikely(!nc->skb_count)) {
356 local_unlock_nested_bh(&napi_alloc_cache.bh_lock);
361 skb = nc->skb_cache[--nc->skb_count];
362 local_unlock_nested_bh(&napi_alloc_cache.bh_lock);
363 kasan_mempool_unpoison_object(skb, kmem_cache_size(net_hotdata.skbuff_cache));
368 static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
371 struct skb_shared_info *shinfo;
373 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
375 /* Assumes caller memset cleared SKB */
376 skb->truesize = SKB_TRUESIZE(size);
377 refcount_set(&skb->users, 1);
380 skb_reset_tail_pointer(skb);
381 skb_set_end_offset(skb, size);
382 skb->mac_header = (typeof(skb->mac_header))~0U;
383 skb->transport_header = (typeof(skb->transport_header))~0U;
384 skb->alloc_cpu = raw_smp_processor_id();
385 /* make sure we initialize shinfo sequentially */
386 shinfo = skb_shinfo(skb);
387 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
388 atomic_set(&shinfo->dataref, 1);
390 skb_set_kcov_handle(skb, kcov_common_handle());
393 static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
398 /* Must find the allocation size (and grow it to match). */
400 /* krealloc() will immediately return "data" when
401 * "ksize(data)" is requested: it is the existing upper
402 * bounds. As a result, GFP_ATOMIC will be ignored. Note
403 * that this "new" pointer needs to be passed back to the
404 * caller for use so the __alloc_size hinting will be
407 resized = krealloc(data, *size, GFP_ATOMIC);
408 WARN_ON_ONCE(resized != data);
412 /* build_skb() variant which can operate on slab buffers.
413 * Note that this should be used sparingly as slab buffers
414 * cannot be combined efficiently by GRO!
416 struct sk_buff *slab_build_skb(void *data)
421 skb = kmem_cache_alloc(net_hotdata.skbuff_cache, GFP_ATOMIC);
425 memset(skb, 0, offsetof(struct sk_buff, tail));
426 data = __slab_build_skb(skb, data, &size);
427 __finalize_skb_around(skb, data, size);
431 EXPORT_SYMBOL(slab_build_skb);
433 /* Caller must provide SKB that is memset cleared */
434 static void __build_skb_around(struct sk_buff *skb, void *data,
435 unsigned int frag_size)
437 unsigned int size = frag_size;
439 /* frag_size == 0 is considered deprecated now. Callers
440 * using slab buffer should use slab_build_skb() instead.
442 if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
443 data = __slab_build_skb(skb, data, &size);
445 __finalize_skb_around(skb, data, size);
449 * __build_skb - build a network buffer
450 * @data: data buffer provided by caller
451 * @frag_size: size of data (must not be 0)
453 * Allocate a new &sk_buff. Caller provides space holding head and
454 * skb_shared_info. @data must have been allocated from the page
455 * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
456 * allocation is deprecated, and callers should use slab_build_skb()
458 * The return is the new skb buffer.
459 * On a failure the return is %NULL, and @data is not freed.
461 * Before IO, driver allocates only data buffer where NIC put incoming frame
462 * Driver should add room at head (NET_SKB_PAD) and
463 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
464 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
465 * before giving packet to stack.
466 * RX rings only contains data buffers, not full skbs.
468 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
472 skb = kmem_cache_alloc(net_hotdata.skbuff_cache, GFP_ATOMIC);
476 memset(skb, 0, offsetof(struct sk_buff, tail));
477 __build_skb_around(skb, data, frag_size);
482 /* build_skb() is wrapper over __build_skb(), that specifically
483 * takes care of skb->head and skb->pfmemalloc
485 struct sk_buff *build_skb(void *data, unsigned int frag_size)
487 struct sk_buff *skb = __build_skb(data, frag_size);
489 if (likely(skb && frag_size)) {
491 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
495 EXPORT_SYMBOL(build_skb);
498 * build_skb_around - build a network buffer around provided skb
499 * @skb: sk_buff provide by caller, must be memset cleared
500 * @data: data buffer provided by caller
501 * @frag_size: size of data
503 struct sk_buff *build_skb_around(struct sk_buff *skb,
504 void *data, unsigned int frag_size)
509 __build_skb_around(skb, data, frag_size);
513 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
517 EXPORT_SYMBOL(build_skb_around);
520 * __napi_build_skb - build a network buffer
521 * @data: data buffer provided by caller
522 * @frag_size: size of data
524 * Version of __build_skb() that uses NAPI percpu caches to obtain
525 * skbuff_head instead of inplace allocation.
527 * Returns a new &sk_buff on success, %NULL on allocation failure.
529 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
533 skb = napi_skb_cache_get();
537 memset(skb, 0, offsetof(struct sk_buff, tail));
538 __build_skb_around(skb, data, frag_size);
544 * napi_build_skb - build a network buffer
545 * @data: data buffer provided by caller
546 * @frag_size: size of data
548 * Version of __napi_build_skb() that takes care of skb->head_frag
549 * and skb->pfmemalloc when the data is a page or page fragment.
551 * Returns a new &sk_buff on success, %NULL on allocation failure.
553 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
555 struct sk_buff *skb = __napi_build_skb(data, frag_size);
557 if (likely(skb) && frag_size) {
559 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
564 EXPORT_SYMBOL(napi_build_skb);
567 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
568 * the caller if emergency pfmemalloc reserves are being used. If it is and
569 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
570 * may be used. Otherwise, the packet data may be discarded until enough
573 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
576 bool ret_pfmemalloc = false;
580 obj_size = SKB_HEAD_ALIGN(*size);
581 if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
582 !(flags & KMALLOC_NOT_NORMAL_BITS)) {
583 obj = kmem_cache_alloc_node(net_hotdata.skb_small_head_cache,
584 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
586 *size = SKB_SMALL_HEAD_CACHE_SIZE;
587 if (obj || !(gfp_pfmemalloc_allowed(flags)))
589 /* Try again but now we are using pfmemalloc reserves */
590 ret_pfmemalloc = true;
591 obj = kmem_cache_alloc_node(net_hotdata.skb_small_head_cache, flags, node);
595 obj_size = kmalloc_size_roundup(obj_size);
596 /* The following cast might truncate high-order bits of obj_size, this
597 * is harmless because kmalloc(obj_size >= 2^32) will fail anyway.
599 *size = (unsigned int)obj_size;
602 * Try a regular allocation, when that fails and we're not entitled
603 * to the reserves, fail.
605 obj = kmalloc_node_track_caller(obj_size,
606 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
608 if (obj || !(gfp_pfmemalloc_allowed(flags)))
611 /* Try again but now we are using pfmemalloc reserves */
612 ret_pfmemalloc = true;
613 obj = kmalloc_node_track_caller(obj_size, flags, node);
617 *pfmemalloc = ret_pfmemalloc;
622 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
623 * 'private' fields and also do memory statistics to find all the
629 * __alloc_skb - allocate a network buffer
630 * @size: size to allocate
631 * @gfp_mask: allocation mask
632 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
633 * instead of head cache and allocate a cloned (child) skb.
634 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
635 * allocations in case the data is required for writeback
636 * @node: numa node to allocate memory on
638 * Allocate a new &sk_buff. The returned buffer has no headroom and a
639 * tail room of at least size bytes. The object has a reference count
640 * of one. The return is the buffer. On a failure the return is %NULL.
642 * Buffers may only be allocated from interrupts using a @gfp_mask of
645 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
648 struct kmem_cache *cache;
653 cache = (flags & SKB_ALLOC_FCLONE)
654 ? net_hotdata.skbuff_fclone_cache : net_hotdata.skbuff_cache;
656 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
657 gfp_mask |= __GFP_MEMALLOC;
660 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
661 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
662 skb = napi_skb_cache_get();
664 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
669 /* We do our best to align skb_shared_info on a separate cache
670 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
671 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
672 * Both skb->head and skb_shared_info are cache line aligned.
674 data = kmalloc_reserve(&size, gfp_mask, node, &pfmemalloc);
677 /* kmalloc_size_roundup() might give us more room than requested.
678 * Put skb_shared_info exactly at the end of allocated zone,
679 * to allow max possible filling before reallocation.
681 prefetchw(data + SKB_WITH_OVERHEAD(size));
684 * Only clear those fields we need to clear, not those that we will
685 * actually initialise below. Hence, don't put any more fields after
686 * the tail pointer in struct sk_buff!
688 memset(skb, 0, offsetof(struct sk_buff, tail));
689 __build_skb_around(skb, data, size);
690 skb->pfmemalloc = pfmemalloc;
692 if (flags & SKB_ALLOC_FCLONE) {
693 struct sk_buff_fclones *fclones;
695 fclones = container_of(skb, struct sk_buff_fclones, skb1);
697 skb->fclone = SKB_FCLONE_ORIG;
698 refcount_set(&fclones->fclone_ref, 1);
704 kmem_cache_free(cache, skb);
707 EXPORT_SYMBOL(__alloc_skb);
710 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
711 * @dev: network device to receive on
712 * @len: length to allocate
713 * @gfp_mask: get_free_pages mask, passed to alloc_skb
715 * Allocate a new &sk_buff and assign it a usage count of one. The
716 * buffer has NET_SKB_PAD headroom built in. Users should allocate
717 * the headroom they think they need without accounting for the
718 * built in space. The built in space is used for optimisations.
720 * %NULL is returned if there is no free memory.
722 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
725 struct page_frag_cache *nc;
732 /* If requested length is either too small or too big,
733 * we use kmalloc() for skb->head allocation.
735 if (len <= SKB_WITH_OVERHEAD(1024) ||
736 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
737 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
738 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
744 len = SKB_HEAD_ALIGN(len);
746 if (sk_memalloc_socks())
747 gfp_mask |= __GFP_MEMALLOC;
749 if (in_hardirq() || irqs_disabled()) {
750 nc = this_cpu_ptr(&netdev_alloc_cache);
751 data = page_frag_alloc(nc, len, gfp_mask);
752 pfmemalloc = nc->pfmemalloc;
755 local_lock_nested_bh(&napi_alloc_cache.bh_lock);
757 nc = this_cpu_ptr(&napi_alloc_cache.page);
758 data = page_frag_alloc(nc, len, gfp_mask);
759 pfmemalloc = nc->pfmemalloc;
761 local_unlock_nested_bh(&napi_alloc_cache.bh_lock);
768 skb = __build_skb(data, len);
769 if (unlikely(!skb)) {
779 skb_reserve(skb, NET_SKB_PAD);
785 EXPORT_SYMBOL(__netdev_alloc_skb);
788 * napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
789 * @napi: napi instance this buffer was allocated for
790 * @len: length to allocate
792 * Allocate a new sk_buff for use in NAPI receive. This buffer will
793 * attempt to allocate the head from a special reserved region used
794 * only for NAPI Rx allocation. By doing this we can save several
795 * CPU cycles by avoiding having to disable and re-enable IRQs.
797 * %NULL is returned if there is no free memory.
799 struct sk_buff *napi_alloc_skb(struct napi_struct *napi, unsigned int len)
801 gfp_t gfp_mask = GFP_ATOMIC | __GFP_NOWARN;
802 struct napi_alloc_cache *nc;
807 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
808 len += NET_SKB_PAD + NET_IP_ALIGN;
810 /* If requested length is either too small or too big,
811 * we use kmalloc() for skb->head allocation.
812 * When the small frag allocator is available, prefer it over kmalloc
813 * for small fragments
815 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
816 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
817 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
818 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
825 if (sk_memalloc_socks())
826 gfp_mask |= __GFP_MEMALLOC;
828 local_lock_nested_bh(&napi_alloc_cache.bh_lock);
829 nc = this_cpu_ptr(&napi_alloc_cache);
830 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
831 /* we are artificially inflating the allocation size, but
832 * that is not as bad as it may look like, as:
833 * - 'len' less than GRO_MAX_HEAD makes little sense
834 * - On most systems, larger 'len' values lead to fragment
835 * size above 512 bytes
836 * - kmalloc would use the kmalloc-1k slab for such values
837 * - Builds with smaller GRO_MAX_HEAD will very likely do
838 * little networking, as that implies no WiFi and no
839 * tunnels support, and 32 bits arches.
843 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
844 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
846 len = SKB_HEAD_ALIGN(len);
848 data = page_frag_alloc(&nc->page, len, gfp_mask);
849 pfmemalloc = nc->page.pfmemalloc;
851 local_unlock_nested_bh(&napi_alloc_cache.bh_lock);
856 skb = __napi_build_skb(data, len);
857 if (unlikely(!skb)) {
867 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
868 skb->dev = napi->dev;
873 EXPORT_SYMBOL(napi_alloc_skb);
875 void skb_add_rx_frag_netmem(struct sk_buff *skb, int i, netmem_ref netmem,
876 int off, int size, unsigned int truesize)
878 DEBUG_NET_WARN_ON_ONCE(size > truesize);
880 skb_fill_netmem_desc(skb, i, netmem, off, size);
882 skb->data_len += size;
883 skb->truesize += truesize;
885 EXPORT_SYMBOL(skb_add_rx_frag_netmem);
887 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
888 unsigned int truesize)
890 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
892 DEBUG_NET_WARN_ON_ONCE(size > truesize);
894 skb_frag_size_add(frag, size);
896 skb->data_len += size;
897 skb->truesize += truesize;
899 EXPORT_SYMBOL(skb_coalesce_rx_frag);
901 static void skb_drop_list(struct sk_buff **listp)
903 kfree_skb_list(*listp);
907 static inline void skb_drop_fraglist(struct sk_buff *skb)
909 skb_drop_list(&skb_shinfo(skb)->frag_list);
912 static void skb_clone_fraglist(struct sk_buff *skb)
914 struct sk_buff *list;
916 skb_walk_frags(skb, list)
920 static bool is_pp_page(struct page *page)
922 return (page->pp_magic & ~0x3UL) == PP_SIGNATURE;
925 int skb_pp_cow_data(struct page_pool *pool, struct sk_buff **pskb,
926 unsigned int headroom)
928 #if IS_ENABLED(CONFIG_PAGE_POOL)
929 u32 size, truesize, len, max_head_size, off;
930 struct sk_buff *skb = *pskb, *nskb;
931 int err, i, head_off;
934 /* XDP does not support fraglist so we need to linearize
937 if (skb_has_frag_list(skb))
940 max_head_size = SKB_WITH_OVERHEAD(PAGE_SIZE - headroom);
941 if (skb->len > max_head_size + MAX_SKB_FRAGS * PAGE_SIZE)
944 size = min_t(u32, skb->len, max_head_size);
945 truesize = SKB_HEAD_ALIGN(size) + headroom;
946 data = page_pool_dev_alloc_va(pool, &truesize);
950 nskb = napi_build_skb(data, truesize);
952 page_pool_free_va(pool, data, true);
956 skb_reserve(nskb, headroom);
957 skb_copy_header(nskb, skb);
958 skb_mark_for_recycle(nskb);
960 err = skb_copy_bits(skb, 0, nskb->data, size);
967 head_off = skb_headroom(nskb) - skb_headroom(skb);
968 skb_headers_offset_update(nskb, head_off);
971 len = skb->len - off;
972 for (i = 0; i < MAX_SKB_FRAGS && off < skb->len; i++) {
976 size = min_t(u32, len, PAGE_SIZE);
979 page = page_pool_dev_alloc(pool, &page_off, &truesize);
985 skb_add_rx_frag(nskb, i, page, page_off, size, truesize);
986 err = skb_copy_bits(skb, off, page_address(page) + page_off,
1005 EXPORT_SYMBOL(skb_pp_cow_data);
1007 int skb_cow_data_for_xdp(struct page_pool *pool, struct sk_buff **pskb,
1008 struct bpf_prog *prog)
1010 if (!prog->aux->xdp_has_frags)
1013 return skb_pp_cow_data(pool, pskb, XDP_PACKET_HEADROOM);
1015 EXPORT_SYMBOL(skb_cow_data_for_xdp);
1017 #if IS_ENABLED(CONFIG_PAGE_POOL)
1018 bool napi_pp_put_page(netmem_ref netmem)
1020 struct page *page = netmem_to_page(netmem);
1022 page = compound_head(page);
1024 /* page->pp_magic is OR'ed with PP_SIGNATURE after the allocation
1025 * in order to preserve any existing bits, such as bit 0 for the
1026 * head page of compound page and bit 1 for pfmemalloc page, so
1027 * mask those bits for freeing side when doing below checking,
1028 * and page_is_pfmemalloc() is checked in __page_pool_put_page()
1029 * to avoid recycling the pfmemalloc page.
1031 if (unlikely(!is_pp_page(page)))
1034 page_pool_put_full_netmem(page->pp, page_to_netmem(page), false);
1038 EXPORT_SYMBOL(napi_pp_put_page);
1041 static bool skb_pp_recycle(struct sk_buff *skb, void *data)
1043 if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
1045 return napi_pp_put_page(page_to_netmem(virt_to_page(data)));
1049 * skb_pp_frag_ref() - Increase fragment references of a page pool aware skb
1050 * @skb: page pool aware skb
1052 * Increase the fragment reference count (pp_ref_count) of a skb. This is
1053 * intended to gain fragment references only for page pool aware skbs,
1054 * i.e. when skb->pp_recycle is true, and not for fragments in a
1055 * non-pp-recycling skb. It has a fallback to increase references on normal
1056 * pages, as page pool aware skbs may also have normal page fragments.
1058 static int skb_pp_frag_ref(struct sk_buff *skb)
1060 struct skb_shared_info *shinfo;
1061 struct page *head_page;
1064 if (!skb->pp_recycle)
1067 shinfo = skb_shinfo(skb);
1069 for (i = 0; i < shinfo->nr_frags; i++) {
1070 head_page = compound_head(skb_frag_page(&shinfo->frags[i]));
1071 if (likely(is_pp_page(head_page)))
1072 page_pool_ref_page(head_page);
1074 page_ref_inc(head_page);
1079 static void skb_kfree_head(void *head, unsigned int end_offset)
1081 if (end_offset == SKB_SMALL_HEAD_HEADROOM)
1082 kmem_cache_free(net_hotdata.skb_small_head_cache, head);
1087 static void skb_free_head(struct sk_buff *skb)
1089 unsigned char *head = skb->head;
1091 if (skb->head_frag) {
1092 if (skb_pp_recycle(skb, head))
1094 skb_free_frag(head);
1096 skb_kfree_head(head, skb_end_offset(skb));
1100 static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason)
1102 struct skb_shared_info *shinfo = skb_shinfo(skb);
1105 if (!skb_data_unref(skb, shinfo))
1108 if (skb_zcopy(skb)) {
1109 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
1111 skb_zcopy_clear(skb, true);
1116 for (i = 0; i < shinfo->nr_frags; i++)
1117 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
1120 if (shinfo->frag_list)
1121 kfree_skb_list_reason(shinfo->frag_list, reason);
1125 /* When we clone an SKB we copy the reycling bit. The pp_recycle
1126 * bit is only set on the head though, so in order to avoid races
1127 * while trying to recycle fragments on __skb_frag_unref() we need
1128 * to make one SKB responsible for triggering the recycle path.
1129 * So disable the recycling bit if an SKB is cloned and we have
1130 * additional references to the fragmented part of the SKB.
1131 * Eventually the last SKB will have the recycling bit set and it's
1132 * dataref set to 0, which will trigger the recycling
1134 skb->pp_recycle = 0;
1138 * Free an skbuff by memory without cleaning the state.
1140 static void kfree_skbmem(struct sk_buff *skb)
1142 struct sk_buff_fclones *fclones;
1144 switch (skb->fclone) {
1145 case SKB_FCLONE_UNAVAILABLE:
1146 kmem_cache_free(net_hotdata.skbuff_cache, skb);
1149 case SKB_FCLONE_ORIG:
1150 fclones = container_of(skb, struct sk_buff_fclones, skb1);
1152 /* We usually free the clone (TX completion) before original skb
1153 * This test would have no chance to be true for the clone,
1154 * while here, branch prediction will be good.
1156 if (refcount_read(&fclones->fclone_ref) == 1)
1160 default: /* SKB_FCLONE_CLONE */
1161 fclones = container_of(skb, struct sk_buff_fclones, skb2);
1164 if (!refcount_dec_and_test(&fclones->fclone_ref))
1167 kmem_cache_free(net_hotdata.skbuff_fclone_cache, fclones);
1170 void skb_release_head_state(struct sk_buff *skb)
1173 if (skb->destructor) {
1174 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
1175 skb->destructor(skb);
1177 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
1178 nf_conntrack_put(skb_nfct(skb));
1183 /* Free everything but the sk_buff shell. */
1184 static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason)
1186 skb_release_head_state(skb);
1187 if (likely(skb->head))
1188 skb_release_data(skb, reason);
1192 * __kfree_skb - private function
1195 * Free an sk_buff. Release anything attached to the buffer.
1196 * Clean the state. This is an internal helper function. Users should
1197 * always call kfree_skb
1200 void __kfree_skb(struct sk_buff *skb)
1202 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
1205 EXPORT_SYMBOL(__kfree_skb);
1207 static __always_inline
1208 bool __sk_skb_reason_drop(struct sock *sk, struct sk_buff *skb,
1209 enum skb_drop_reason reason)
1211 if (unlikely(!skb_unref(skb)))
1214 DEBUG_NET_WARN_ON_ONCE(reason == SKB_NOT_DROPPED_YET ||
1215 u32_get_bits(reason,
1216 SKB_DROP_REASON_SUBSYS_MASK) >=
1217 SKB_DROP_REASON_SUBSYS_NUM);
1219 if (reason == SKB_CONSUMED)
1220 trace_consume_skb(skb, __builtin_return_address(0));
1222 trace_kfree_skb(skb, __builtin_return_address(0), reason, sk);
1227 * sk_skb_reason_drop - free an sk_buff with special reason
1228 * @sk: the socket to receive @skb, or NULL if not applicable
1229 * @skb: buffer to free
1230 * @reason: reason why this skb is dropped
1232 * Drop a reference to the buffer and free it if the usage count has hit
1233 * zero. Meanwhile, pass the receiving socket and drop reason to
1234 * 'kfree_skb' tracepoint.
1237 sk_skb_reason_drop(struct sock *sk, struct sk_buff *skb, enum skb_drop_reason reason)
1239 if (__sk_skb_reason_drop(sk, skb, reason))
1242 EXPORT_SYMBOL(sk_skb_reason_drop);
1244 #define KFREE_SKB_BULK_SIZE 16
1246 struct skb_free_array {
1247 unsigned int skb_count;
1248 void *skb_array[KFREE_SKB_BULK_SIZE];
1251 static void kfree_skb_add_bulk(struct sk_buff *skb,
1252 struct skb_free_array *sa,
1253 enum skb_drop_reason reason)
1255 /* if SKB is a clone, don't handle this case */
1256 if (unlikely(skb->fclone != SKB_FCLONE_UNAVAILABLE)) {
1261 skb_release_all(skb, reason);
1262 sa->skb_array[sa->skb_count++] = skb;
1264 if (unlikely(sa->skb_count == KFREE_SKB_BULK_SIZE)) {
1265 kmem_cache_free_bulk(net_hotdata.skbuff_cache, KFREE_SKB_BULK_SIZE,
1272 kfree_skb_list_reason(struct sk_buff *segs, enum skb_drop_reason reason)
1274 struct skb_free_array sa;
1279 struct sk_buff *next = segs->next;
1281 if (__sk_skb_reason_drop(NULL, segs, reason)) {
1282 skb_poison_list(segs);
1283 kfree_skb_add_bulk(segs, &sa, reason);
1290 kmem_cache_free_bulk(net_hotdata.skbuff_cache, sa.skb_count, sa.skb_array);
1292 EXPORT_SYMBOL(kfree_skb_list_reason);
1294 /* Dump skb information and contents.
1296 * Must only be called from net_ratelimit()-ed paths.
1298 * Dumps whole packets if full_pkt, only headers otherwise.
1300 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
1302 struct skb_shared_info *sh = skb_shinfo(skb);
1303 struct net_device *dev = skb->dev;
1304 struct sock *sk = skb->sk;
1305 struct sk_buff *list_skb;
1306 bool has_mac, has_trans;
1307 int headroom, tailroom;
1308 int i, len, seg_len;
1313 len = min_t(int, skb->len, MAX_HEADER + 128);
1315 headroom = skb_headroom(skb);
1316 tailroom = skb_tailroom(skb);
1318 has_mac = skb_mac_header_was_set(skb);
1319 has_trans = skb_transport_header_was_set(skb);
1321 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
1322 "mac=(%d,%d) mac_len=%u net=(%d,%d) trans=%d\n"
1323 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
1324 "csum(0x%x start=%u offset=%u ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
1325 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n"
1326 "priority=0x%x mark=0x%x alloc_cpu=%u vlan_all=0x%x\n"
1327 "encapsulation=%d inner(proto=0x%04x, mac=%u, net=%u, trans=%u)\n",
1328 level, skb->len, headroom, skb_headlen(skb), tailroom,
1329 has_mac ? skb->mac_header : -1,
1330 has_mac ? skb_mac_header_len(skb) : -1,
1332 skb->network_header,
1333 has_trans ? skb_network_header_len(skb) : -1,
1334 has_trans ? skb->transport_header : -1,
1335 sh->tx_flags, sh->nr_frags,
1336 sh->gso_size, sh->gso_type, sh->gso_segs,
1337 skb->csum, skb->csum_start, skb->csum_offset, skb->ip_summed,
1338 skb->csum_complete_sw, skb->csum_valid, skb->csum_level,
1339 skb->hash, skb->sw_hash, skb->l4_hash,
1340 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif,
1341 skb->priority, skb->mark, skb->alloc_cpu, skb->vlan_all,
1342 skb->encapsulation, skb->inner_protocol, skb->inner_mac_header,
1343 skb->inner_network_header, skb->inner_transport_header);
1346 printk("%sdev name=%s feat=%pNF\n",
1347 level, dev->name, &dev->features);
1349 printk("%ssk family=%hu type=%u proto=%u\n",
1350 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
1352 if (full_pkt && headroom)
1353 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
1354 16, 1, skb->head, headroom, false);
1356 seg_len = min_t(int, skb_headlen(skb), len);
1358 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
1359 16, 1, skb->data, seg_len, false);
1362 if (full_pkt && tailroom)
1363 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
1364 16, 1, skb_tail_pointer(skb), tailroom, false);
1366 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
1367 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1368 u32 p_off, p_len, copied;
1372 skb_frag_foreach_page(frag, skb_frag_off(frag),
1373 skb_frag_size(frag), p, p_off, p_len,
1375 seg_len = min_t(int, p_len, len);
1376 vaddr = kmap_atomic(p);
1377 print_hex_dump(level, "skb frag: ",
1379 16, 1, vaddr + p_off, seg_len, false);
1380 kunmap_atomic(vaddr);
1387 if (full_pkt && skb_has_frag_list(skb)) {
1388 printk("skb fraglist:\n");
1389 skb_walk_frags(skb, list_skb)
1390 skb_dump(level, list_skb, true);
1393 EXPORT_SYMBOL(skb_dump);
1396 * skb_tx_error - report an sk_buff xmit error
1397 * @skb: buffer that triggered an error
1399 * Report xmit error if a device callback is tracking this skb.
1400 * skb must be freed afterwards.
1402 void skb_tx_error(struct sk_buff *skb)
1405 skb_zcopy_downgrade_managed(skb);
1406 skb_zcopy_clear(skb, true);
1409 EXPORT_SYMBOL(skb_tx_error);
1411 #ifdef CONFIG_TRACEPOINTS
1413 * consume_skb - free an skbuff
1414 * @skb: buffer to free
1416 * Drop a ref to the buffer and free it if the usage count has hit zero
1417 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1418 * is being dropped after a failure and notes that
1420 void consume_skb(struct sk_buff *skb)
1422 if (!skb_unref(skb))
1425 trace_consume_skb(skb, __builtin_return_address(0));
1428 EXPORT_SYMBOL(consume_skb);
1432 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1433 * @skb: buffer to free
1435 * Alike consume_skb(), but this variant assumes that this is the last
1436 * skb reference and all the head states have been already dropped
1438 void __consume_stateless_skb(struct sk_buff *skb)
1440 trace_consume_skb(skb, __builtin_return_address(0));
1441 skb_release_data(skb, SKB_CONSUMED);
1445 static void napi_skb_cache_put(struct sk_buff *skb)
1447 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1450 if (!kasan_mempool_poison_object(skb))
1453 local_lock_nested_bh(&napi_alloc_cache.bh_lock);
1454 nc->skb_cache[nc->skb_count++] = skb;
1456 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1457 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1458 kasan_mempool_unpoison_object(nc->skb_cache[i],
1459 kmem_cache_size(net_hotdata.skbuff_cache));
1461 kmem_cache_free_bulk(net_hotdata.skbuff_cache, NAPI_SKB_CACHE_HALF,
1462 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1463 nc->skb_count = NAPI_SKB_CACHE_HALF;
1465 local_unlock_nested_bh(&napi_alloc_cache.bh_lock);
1468 void __napi_kfree_skb(struct sk_buff *skb, enum skb_drop_reason reason)
1470 skb_release_all(skb, reason);
1471 napi_skb_cache_put(skb);
1474 void napi_skb_free_stolen_head(struct sk_buff *skb)
1476 if (unlikely(skb->slow_gro)) {
1483 napi_skb_cache_put(skb);
1486 void napi_consume_skb(struct sk_buff *skb, int budget)
1488 /* Zero budget indicate non-NAPI context called us, like netpoll */
1489 if (unlikely(!budget)) {
1490 dev_consume_skb_any(skb);
1494 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1496 if (!skb_unref(skb))
1499 /* if reaching here SKB is ready to free */
1500 trace_consume_skb(skb, __builtin_return_address(0));
1502 /* if SKB is a clone, don't handle this case */
1503 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1508 skb_release_all(skb, SKB_CONSUMED);
1509 napi_skb_cache_put(skb);
1511 EXPORT_SYMBOL(napi_consume_skb);
1513 /* Make sure a field is contained by headers group */
1514 #define CHECK_SKB_FIELD(field) \
1515 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1516 offsetof(struct sk_buff, headers.field)); \
1518 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1520 new->tstamp = old->tstamp;
1521 /* We do not copy old->sk */
1522 new->dev = old->dev;
1523 memcpy(new->cb, old->cb, sizeof(old->cb));
1524 skb_dst_copy(new, old);
1525 __skb_ext_copy(new, old);
1526 __nf_copy(new, old, false);
1528 /* Note : this field could be in the headers group.
1529 * It is not yet because we do not want to have a 16 bit hole
1531 new->queue_mapping = old->queue_mapping;
1533 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1534 CHECK_SKB_FIELD(protocol);
1535 CHECK_SKB_FIELD(csum);
1536 CHECK_SKB_FIELD(hash);
1537 CHECK_SKB_FIELD(priority);
1538 CHECK_SKB_FIELD(skb_iif);
1539 CHECK_SKB_FIELD(vlan_proto);
1540 CHECK_SKB_FIELD(vlan_tci);
1541 CHECK_SKB_FIELD(transport_header);
1542 CHECK_SKB_FIELD(network_header);
1543 CHECK_SKB_FIELD(mac_header);
1544 CHECK_SKB_FIELD(inner_protocol);
1545 CHECK_SKB_FIELD(inner_transport_header);
1546 CHECK_SKB_FIELD(inner_network_header);
1547 CHECK_SKB_FIELD(inner_mac_header);
1548 CHECK_SKB_FIELD(mark);
1549 #ifdef CONFIG_NETWORK_SECMARK
1550 CHECK_SKB_FIELD(secmark);
1552 #ifdef CONFIG_NET_RX_BUSY_POLL
1553 CHECK_SKB_FIELD(napi_id);
1555 CHECK_SKB_FIELD(alloc_cpu);
1557 CHECK_SKB_FIELD(sender_cpu);
1559 #ifdef CONFIG_NET_SCHED
1560 CHECK_SKB_FIELD(tc_index);
1566 * You should not add any new code to this function. Add it to
1567 * __copy_skb_header above instead.
1569 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1571 #define C(x) n->x = skb->x
1573 n->next = n->prev = NULL;
1575 __copy_skb_header(n, skb);
1580 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1586 n->destructor = NULL;
1593 refcount_set(&n->users, 1);
1595 atomic_inc(&(skb_shinfo(skb)->dataref));
1603 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1604 * @first: first sk_buff of the msg
1606 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1610 n = alloc_skb(0, GFP_ATOMIC);
1614 n->len = first->len;
1615 n->data_len = first->len;
1616 n->truesize = first->truesize;
1618 skb_shinfo(n)->frag_list = first;
1620 __copy_skb_header(n, first);
1621 n->destructor = NULL;
1625 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1628 * skb_morph - morph one skb into another
1629 * @dst: the skb to receive the contents
1630 * @src: the skb to supply the contents
1632 * This is identical to skb_clone except that the target skb is
1633 * supplied by the user.
1635 * The target skb is returned upon exit.
1637 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1639 skb_release_all(dst, SKB_CONSUMED);
1640 return __skb_clone(dst, src);
1642 EXPORT_SYMBOL_GPL(skb_morph);
1644 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1646 unsigned long max_pg, num_pg, new_pg, old_pg, rlim;
1647 struct user_struct *user;
1649 if (capable(CAP_IPC_LOCK) || !size)
1652 rlim = rlimit(RLIMIT_MEMLOCK);
1653 if (rlim == RLIM_INFINITY)
1656 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1657 max_pg = rlim >> PAGE_SHIFT;
1658 user = mmp->user ? : current_user();
1660 old_pg = atomic_long_read(&user->locked_vm);
1662 new_pg = old_pg + num_pg;
1663 if (new_pg > max_pg)
1665 } while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1668 mmp->user = get_uid(user);
1669 mmp->num_pg = num_pg;
1671 mmp->num_pg += num_pg;
1676 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1678 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1681 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1682 free_uid(mmp->user);
1685 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1687 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1689 struct ubuf_info_msgzc *uarg;
1690 struct sk_buff *skb;
1692 WARN_ON_ONCE(!in_task());
1694 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1698 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1699 uarg = (void *)skb->cb;
1700 uarg->mmp.user = NULL;
1702 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1707 uarg->ubuf.ops = &msg_zerocopy_ubuf_ops;
1708 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1710 uarg->bytelen = size;
1712 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1713 refcount_set(&uarg->ubuf.refcnt, 1);
1719 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1721 return container_of((void *)uarg, struct sk_buff, cb);
1724 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1725 struct ubuf_info *uarg)
1728 struct ubuf_info_msgzc *uarg_zc;
1729 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1732 /* there might be non MSG_ZEROCOPY users */
1733 if (uarg->ops != &msg_zerocopy_ubuf_ops)
1736 /* realloc only when socket is locked (TCP, UDP cork),
1737 * so uarg->len and sk_zckey access is serialized
1739 if (!sock_owned_by_user(sk)) {
1744 uarg_zc = uarg_to_msgzc(uarg);
1745 bytelen = uarg_zc->bytelen + size;
1746 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1747 /* TCP can create new skb to attach new uarg */
1748 if (sk->sk_type == SOCK_STREAM)
1753 next = (u32)atomic_read(&sk->sk_zckey);
1754 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1755 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1758 uarg_zc->bytelen = bytelen;
1759 atomic_set(&sk->sk_zckey, ++next);
1761 /* no extra ref when appending to datagram (MSG_MORE) */
1762 if (sk->sk_type == SOCK_STREAM)
1763 net_zcopy_get(uarg);
1770 return msg_zerocopy_alloc(sk, size);
1772 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1774 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1776 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1780 old_lo = serr->ee.ee_info;
1781 old_hi = serr->ee.ee_data;
1782 sum_len = old_hi - old_lo + 1ULL + len;
1784 if (sum_len >= (1ULL << 32))
1787 if (lo != old_hi + 1)
1790 serr->ee.ee_data += len;
1794 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1796 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1797 struct sock_exterr_skb *serr;
1798 struct sock *sk = skb->sk;
1799 struct sk_buff_head *q;
1800 unsigned long flags;
1805 mm_unaccount_pinned_pages(&uarg->mmp);
1807 /* if !len, there was only 1 call, and it was aborted
1808 * so do not queue a completion notification
1810 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1815 hi = uarg->id + len - 1;
1816 is_zerocopy = uarg->zerocopy;
1818 serr = SKB_EXT_ERR(skb);
1819 memset(serr, 0, sizeof(*serr));
1820 serr->ee.ee_errno = 0;
1821 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1822 serr->ee.ee_data = hi;
1823 serr->ee.ee_info = lo;
1825 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1827 q = &sk->sk_error_queue;
1828 spin_lock_irqsave(&q->lock, flags);
1829 tail = skb_peek_tail(q);
1830 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1831 !skb_zerocopy_notify_extend(tail, lo, len)) {
1832 __skb_queue_tail(q, skb);
1835 spin_unlock_irqrestore(&q->lock, flags);
1837 sk_error_report(sk);
1844 static void msg_zerocopy_complete(struct sk_buff *skb, struct ubuf_info *uarg,
1847 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1849 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1851 if (refcount_dec_and_test(&uarg->refcnt))
1852 __msg_zerocopy_callback(uarg_zc);
1855 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1857 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1859 atomic_dec(&sk->sk_zckey);
1860 uarg_to_msgzc(uarg)->len--;
1863 msg_zerocopy_complete(NULL, uarg, true);
1865 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1867 const struct ubuf_info_ops msg_zerocopy_ubuf_ops = {
1868 .complete = msg_zerocopy_complete,
1870 EXPORT_SYMBOL_GPL(msg_zerocopy_ubuf_ops);
1872 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1873 struct msghdr *msg, int len,
1874 struct ubuf_info *uarg)
1876 int err, orig_len = skb->len;
1878 if (uarg->ops->link_skb) {
1879 err = uarg->ops->link_skb(skb, uarg);
1883 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1885 /* An skb can only point to one uarg. This edge case happens
1886 * when TCP appends to an skb, but zerocopy_realloc triggered
1889 if (orig_uarg && uarg != orig_uarg)
1893 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1894 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1895 struct sock *save_sk = skb->sk;
1897 /* Streams do not free skb on error. Reset to prev state. */
1898 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1900 ___pskb_trim(skb, orig_len);
1905 skb_zcopy_set(skb, uarg, NULL);
1906 return skb->len - orig_len;
1908 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1910 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1914 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1915 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1916 skb_frag_ref(skb, i);
1918 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1920 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1923 if (skb_zcopy(orig)) {
1924 if (skb_zcopy(nskb)) {
1925 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1930 if (skb_uarg(nskb) == skb_uarg(orig))
1932 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1935 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1941 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1942 * @skb: the skb to modify
1943 * @gfp_mask: allocation priority
1945 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1946 * It will copy all frags into kernel and drop the reference
1947 * to userspace pages.
1949 * If this function is called from an interrupt gfp_mask() must be
1952 * Returns 0 on success or a negative error code on failure
1953 * to allocate kernel memory to copy to.
1955 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1957 int num_frags = skb_shinfo(skb)->nr_frags;
1958 struct page *page, *head = NULL;
1959 int i, order, psize, new_frags;
1962 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1968 /* We might have to allocate high order pages, so compute what minimum
1969 * page order is needed.
1972 while ((PAGE_SIZE << order) * MAX_SKB_FRAGS < __skb_pagelen(skb))
1974 psize = (PAGE_SIZE << order);
1976 new_frags = (__skb_pagelen(skb) + psize - 1) >> (PAGE_SHIFT + order);
1977 for (i = 0; i < new_frags; i++) {
1978 page = alloc_pages(gfp_mask | __GFP_COMP, order);
1981 struct page *next = (struct page *)page_private(head);
1987 set_page_private(page, (unsigned long)head);
1993 for (i = 0; i < num_frags; i++) {
1994 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1995 u32 p_off, p_len, copied;
1999 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
2000 p, p_off, p_len, copied) {
2002 vaddr = kmap_atomic(p);
2004 while (done < p_len) {
2005 if (d_off == psize) {
2007 page = (struct page *)page_private(page);
2009 copy = min_t(u32, psize - d_off, p_len - done);
2010 memcpy(page_address(page) + d_off,
2011 vaddr + p_off + done, copy);
2015 kunmap_atomic(vaddr);
2019 /* skb frags release userspace buffers */
2020 for (i = 0; i < num_frags; i++)
2021 skb_frag_unref(skb, i);
2023 /* skb frags point to kernel buffers */
2024 for (i = 0; i < new_frags - 1; i++) {
2025 __skb_fill_netmem_desc(skb, i, page_to_netmem(head), 0, psize);
2026 head = (struct page *)page_private(head);
2028 __skb_fill_netmem_desc(skb, new_frags - 1, page_to_netmem(head), 0,
2030 skb_shinfo(skb)->nr_frags = new_frags;
2033 skb_zcopy_clear(skb, false);
2036 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
2039 * skb_clone - duplicate an sk_buff
2040 * @skb: buffer to clone
2041 * @gfp_mask: allocation priority
2043 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
2044 * copies share the same packet data but not structure. The new
2045 * buffer has a reference count of 1. If the allocation fails the
2046 * function returns %NULL otherwise the new buffer is returned.
2048 * If this function is called from an interrupt gfp_mask() must be
2052 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
2054 struct sk_buff_fclones *fclones = container_of(skb,
2055 struct sk_buff_fclones,
2059 if (skb_orphan_frags(skb, gfp_mask))
2062 if (skb->fclone == SKB_FCLONE_ORIG &&
2063 refcount_read(&fclones->fclone_ref) == 1) {
2065 refcount_set(&fclones->fclone_ref, 2);
2066 n->fclone = SKB_FCLONE_CLONE;
2068 if (skb_pfmemalloc(skb))
2069 gfp_mask |= __GFP_MEMALLOC;
2071 n = kmem_cache_alloc(net_hotdata.skbuff_cache, gfp_mask);
2075 n->fclone = SKB_FCLONE_UNAVAILABLE;
2078 return __skb_clone(n, skb);
2080 EXPORT_SYMBOL(skb_clone);
2082 void skb_headers_offset_update(struct sk_buff *skb, int off)
2084 /* Only adjust this if it actually is csum_start rather than csum */
2085 if (skb->ip_summed == CHECKSUM_PARTIAL)
2086 skb->csum_start += off;
2087 /* {transport,network,mac}_header and tail are relative to skb->head */
2088 skb->transport_header += off;
2089 skb->network_header += off;
2090 if (skb_mac_header_was_set(skb))
2091 skb->mac_header += off;
2092 skb->inner_transport_header += off;
2093 skb->inner_network_header += off;
2094 skb->inner_mac_header += off;
2096 EXPORT_SYMBOL(skb_headers_offset_update);
2098 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
2100 __copy_skb_header(new, old);
2102 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
2103 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
2104 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
2106 EXPORT_SYMBOL(skb_copy_header);
2108 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
2110 if (skb_pfmemalloc(skb))
2111 return SKB_ALLOC_RX;
2116 * skb_copy - create private copy of an sk_buff
2117 * @skb: buffer to copy
2118 * @gfp_mask: allocation priority
2120 * Make a copy of both an &sk_buff and its data. This is used when the
2121 * caller wishes to modify the data and needs a private copy of the
2122 * data to alter. Returns %NULL on failure or the pointer to the buffer
2123 * on success. The returned buffer has a reference count of 1.
2125 * As by-product this function converts non-linear &sk_buff to linear
2126 * one, so that &sk_buff becomes completely private and caller is allowed
2127 * to modify all the data of returned buffer. This means that this
2128 * function is not recommended for use in circumstances when only
2129 * header is going to be modified. Use pskb_copy() instead.
2132 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
2138 if (WARN_ON_ONCE(skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST))
2141 headerlen = skb_headroom(skb);
2142 size = skb_end_offset(skb) + skb->data_len;
2143 n = __alloc_skb(size, gfp_mask,
2144 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
2148 /* Set the data pointer */
2149 skb_reserve(n, headerlen);
2150 /* Set the tail pointer and length */
2151 skb_put(n, skb->len);
2153 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
2155 skb_copy_header(n, skb);
2158 EXPORT_SYMBOL(skb_copy);
2161 * __pskb_copy_fclone - create copy of an sk_buff with private head.
2162 * @skb: buffer to copy
2163 * @headroom: headroom of new skb
2164 * @gfp_mask: allocation priority
2165 * @fclone: if true allocate the copy of the skb from the fclone
2166 * cache instead of the head cache; it is recommended to set this
2167 * to true for the cases where the copy will likely be cloned
2169 * Make a copy of both an &sk_buff and part of its data, located
2170 * in header. Fragmented data remain shared. This is used when
2171 * the caller wishes to modify only header of &sk_buff and needs
2172 * private copy of the header to alter. Returns %NULL on failure
2173 * or the pointer to the buffer on success.
2174 * The returned buffer has a reference count of 1.
2177 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
2178 gfp_t gfp_mask, bool fclone)
2180 unsigned int size = skb_headlen(skb) + headroom;
2181 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
2182 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
2187 /* Set the data pointer */
2188 skb_reserve(n, headroom);
2189 /* Set the tail pointer and length */
2190 skb_put(n, skb_headlen(skb));
2191 /* Copy the bytes */
2192 skb_copy_from_linear_data(skb, n->data, n->len);
2194 n->truesize += skb->data_len;
2195 n->data_len = skb->data_len;
2198 if (skb_shinfo(skb)->nr_frags) {
2201 if (skb_orphan_frags(skb, gfp_mask) ||
2202 skb_zerocopy_clone(n, skb, gfp_mask)) {
2207 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2208 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
2209 skb_frag_ref(skb, i);
2211 skb_shinfo(n)->nr_frags = i;
2214 if (skb_has_frag_list(skb)) {
2215 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
2216 skb_clone_fraglist(n);
2219 skb_copy_header(n, skb);
2223 EXPORT_SYMBOL(__pskb_copy_fclone);
2226 * pskb_expand_head - reallocate header of &sk_buff
2227 * @skb: buffer to reallocate
2228 * @nhead: room to add at head
2229 * @ntail: room to add at tail
2230 * @gfp_mask: allocation priority
2232 * Expands (or creates identical copy, if @nhead and @ntail are zero)
2233 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
2234 * reference count of 1. Returns zero in the case of success or error,
2235 * if expansion failed. In the last case, &sk_buff is not changed.
2237 * All the pointers pointing into skb header may change and must be
2238 * reloaded after call to this function.
2241 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
2244 unsigned int osize = skb_end_offset(skb);
2245 unsigned int size = osize + nhead + ntail;
2252 BUG_ON(skb_shared(skb));
2254 skb_zcopy_downgrade_managed(skb);
2256 if (skb_pfmemalloc(skb))
2257 gfp_mask |= __GFP_MEMALLOC;
2259 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
2262 size = SKB_WITH_OVERHEAD(size);
2264 /* Copy only real data... and, alas, header. This should be
2265 * optimized for the cases when header is void.
2267 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
2269 memcpy((struct skb_shared_info *)(data + size),
2271 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
2274 * if shinfo is shared we must drop the old head gracefully, but if it
2275 * is not we can just drop the old head and let the existing refcount
2276 * be since all we did is relocate the values
2278 if (skb_cloned(skb)) {
2279 if (skb_orphan_frags(skb, gfp_mask))
2282 refcount_inc(&skb_uarg(skb)->refcnt);
2283 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2284 skb_frag_ref(skb, i);
2286 if (skb_has_frag_list(skb))
2287 skb_clone_fraglist(skb);
2289 skb_release_data(skb, SKB_CONSUMED);
2293 off = (data + nhead) - skb->head;
2299 skb_set_end_offset(skb, size);
2300 #ifdef NET_SKBUFF_DATA_USES_OFFSET
2304 skb_headers_offset_update(skb, nhead);
2308 atomic_set(&skb_shinfo(skb)->dataref, 1);
2310 skb_metadata_clear(skb);
2312 /* It is not generally safe to change skb->truesize.
2313 * For the moment, we really care of rx path, or
2314 * when skb is orphaned (not attached to a socket).
2316 if (!skb->sk || skb->destructor == sock_edemux)
2317 skb->truesize += size - osize;
2322 skb_kfree_head(data, size);
2326 EXPORT_SYMBOL(pskb_expand_head);
2328 /* Make private copy of skb with writable head and some headroom */
2330 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
2332 struct sk_buff *skb2;
2333 int delta = headroom - skb_headroom(skb);
2336 skb2 = pskb_copy(skb, GFP_ATOMIC);
2338 skb2 = skb_clone(skb, GFP_ATOMIC);
2339 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
2347 EXPORT_SYMBOL(skb_realloc_headroom);
2349 /* Note: We plan to rework this in linux-6.4 */
2350 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
2352 unsigned int saved_end_offset, saved_truesize;
2353 struct skb_shared_info *shinfo;
2356 saved_end_offset = skb_end_offset(skb);
2357 saved_truesize = skb->truesize;
2359 res = pskb_expand_head(skb, 0, 0, pri);
2363 skb->truesize = saved_truesize;
2365 if (likely(skb_end_offset(skb) == saved_end_offset))
2368 /* We can not change skb->end if the original or new value
2369 * is SKB_SMALL_HEAD_HEADROOM, as it might break skb_kfree_head().
2371 if (saved_end_offset == SKB_SMALL_HEAD_HEADROOM ||
2372 skb_end_offset(skb) == SKB_SMALL_HEAD_HEADROOM) {
2373 /* We think this path should not be taken.
2374 * Add a temporary trace to warn us just in case.
2376 pr_err_once("__skb_unclone_keeptruesize() skb_end_offset() %u -> %u\n",
2377 saved_end_offset, skb_end_offset(skb));
2382 shinfo = skb_shinfo(skb);
2384 /* We are about to change back skb->end,
2385 * we need to move skb_shinfo() to its new location.
2387 memmove(skb->head + saved_end_offset,
2389 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
2391 skb_set_end_offset(skb, saved_end_offset);
2397 * skb_expand_head - reallocate header of &sk_buff
2398 * @skb: buffer to reallocate
2399 * @headroom: needed headroom
2401 * Unlike skb_realloc_headroom, this one does not allocate a new skb
2402 * if possible; copies skb->sk to new skb as needed
2403 * and frees original skb in case of failures.
2405 * It expect increased headroom and generates warning otherwise.
2408 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2410 int delta = headroom - skb_headroom(skb);
2411 int osize = skb_end_offset(skb);
2412 struct sock *sk = skb->sk;
2414 if (WARN_ONCE(delta <= 0,
2415 "%s is expecting an increase in the headroom", __func__))
2418 delta = SKB_DATA_ALIGN(delta);
2419 /* pskb_expand_head() might crash, if skb is shared. */
2420 if (skb_shared(skb) || !is_skb_wmem(skb)) {
2421 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2423 if (unlikely(!nskb))
2427 skb_set_owner_w(nskb, sk);
2431 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2434 if (sk && is_skb_wmem(skb)) {
2435 delta = skb_end_offset(skb) - osize;
2436 refcount_add(delta, &sk->sk_wmem_alloc);
2437 skb->truesize += delta;
2445 EXPORT_SYMBOL(skb_expand_head);
2448 * skb_copy_expand - copy and expand sk_buff
2449 * @skb: buffer to copy
2450 * @newheadroom: new free bytes at head
2451 * @newtailroom: new free bytes at tail
2452 * @gfp_mask: allocation priority
2454 * Make a copy of both an &sk_buff and its data and while doing so
2455 * allocate additional space.
2457 * This is used when the caller wishes to modify the data and needs a
2458 * private copy of the data to alter as well as more space for new fields.
2459 * Returns %NULL on failure or the pointer to the buffer
2460 * on success. The returned buffer has a reference count of 1.
2462 * You must pass %GFP_ATOMIC as the allocation priority if this function
2463 * is called from an interrupt.
2465 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2466 int newheadroom, int newtailroom,
2470 * Allocate the copy buffer
2472 int head_copy_len, head_copy_off;
2476 if (WARN_ON_ONCE(skb_shinfo(skb)->gso_type & SKB_GSO_FRAGLIST))
2479 oldheadroom = skb_headroom(skb);
2480 n = __alloc_skb(newheadroom + skb->len + newtailroom,
2481 gfp_mask, skb_alloc_rx_flag(skb),
2486 skb_reserve(n, newheadroom);
2488 /* Set the tail pointer and length */
2489 skb_put(n, skb->len);
2491 head_copy_len = oldheadroom;
2493 if (newheadroom <= head_copy_len)
2494 head_copy_len = newheadroom;
2496 head_copy_off = newheadroom - head_copy_len;
2498 /* Copy the linear header and data. */
2499 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2500 skb->len + head_copy_len));
2502 skb_copy_header(n, skb);
2504 skb_headers_offset_update(n, newheadroom - oldheadroom);
2508 EXPORT_SYMBOL(skb_copy_expand);
2511 * __skb_pad - zero pad the tail of an skb
2512 * @skb: buffer to pad
2513 * @pad: space to pad
2514 * @free_on_error: free buffer on error
2516 * Ensure that a buffer is followed by a padding area that is zero
2517 * filled. Used by network drivers which may DMA or transfer data
2518 * beyond the buffer end onto the wire.
2520 * May return error in out of memory cases. The skb is freed on error
2521 * if @free_on_error is true.
2524 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2529 /* If the skbuff is non linear tailroom is always zero.. */
2530 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2531 memset(skb->data+skb->len, 0, pad);
2535 ntail = skb->data_len + pad - (skb->end - skb->tail);
2536 if (likely(skb_cloned(skb) || ntail > 0)) {
2537 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2542 /* FIXME: The use of this function with non-linear skb's really needs
2545 err = skb_linearize(skb);
2549 memset(skb->data + skb->len, 0, pad);
2557 EXPORT_SYMBOL(__skb_pad);
2560 * pskb_put - add data to the tail of a potentially fragmented buffer
2561 * @skb: start of the buffer to use
2562 * @tail: tail fragment of the buffer to use
2563 * @len: amount of data to add
2565 * This function extends the used data area of the potentially
2566 * fragmented buffer. @tail must be the last fragment of @skb -- or
2567 * @skb itself. If this would exceed the total buffer size the kernel
2568 * will panic. A pointer to the first byte of the extra data is
2572 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2575 skb->data_len += len;
2578 return skb_put(tail, len);
2580 EXPORT_SYMBOL_GPL(pskb_put);
2583 * skb_put - add data to a buffer
2584 * @skb: buffer to use
2585 * @len: amount of data to add
2587 * This function extends the used data area of the buffer. If this would
2588 * exceed the total buffer size the kernel will panic. A pointer to the
2589 * first byte of the extra data is returned.
2591 void *skb_put(struct sk_buff *skb, unsigned int len)
2593 void *tmp = skb_tail_pointer(skb);
2594 SKB_LINEAR_ASSERT(skb);
2597 if (unlikely(skb->tail > skb->end))
2598 skb_over_panic(skb, len, __builtin_return_address(0));
2601 EXPORT_SYMBOL(skb_put);
2604 * skb_push - add data to the start of a buffer
2605 * @skb: buffer to use
2606 * @len: amount of data to add
2608 * This function extends the used data area of the buffer at the buffer
2609 * start. If this would exceed the total buffer headroom the kernel will
2610 * panic. A pointer to the first byte of the extra data is returned.
2612 void *skb_push(struct sk_buff *skb, unsigned int len)
2616 if (unlikely(skb->data < skb->head))
2617 skb_under_panic(skb, len, __builtin_return_address(0));
2620 EXPORT_SYMBOL(skb_push);
2623 * skb_pull - remove data from the start of a buffer
2624 * @skb: buffer to use
2625 * @len: amount of data to remove
2627 * This function removes data from the start of a buffer, returning
2628 * the memory to the headroom. A pointer to the next data in the buffer
2629 * is returned. Once the data has been pulled future pushes will overwrite
2632 void *skb_pull(struct sk_buff *skb, unsigned int len)
2634 return skb_pull_inline(skb, len);
2636 EXPORT_SYMBOL(skb_pull);
2639 * skb_pull_data - remove data from the start of a buffer returning its
2640 * original position.
2641 * @skb: buffer to use
2642 * @len: amount of data to remove
2644 * This function removes data from the start of a buffer, returning
2645 * the memory to the headroom. A pointer to the original data in the buffer
2646 * is returned after checking if there is enough data to pull. Once the
2647 * data has been pulled future pushes will overwrite the old data.
2649 void *skb_pull_data(struct sk_buff *skb, size_t len)
2651 void *data = skb->data;
2660 EXPORT_SYMBOL(skb_pull_data);
2663 * skb_trim - remove end from a buffer
2664 * @skb: buffer to alter
2667 * Cut the length of a buffer down by removing data from the tail. If
2668 * the buffer is already under the length specified it is not modified.
2669 * The skb must be linear.
2671 void skb_trim(struct sk_buff *skb, unsigned int len)
2674 __skb_trim(skb, len);
2676 EXPORT_SYMBOL(skb_trim);
2678 /* Trims skb to length len. It can change skb pointers.
2681 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2683 struct sk_buff **fragp;
2684 struct sk_buff *frag;
2685 int offset = skb_headlen(skb);
2686 int nfrags = skb_shinfo(skb)->nr_frags;
2690 if (skb_cloned(skb) &&
2691 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2698 for (; i < nfrags; i++) {
2699 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2706 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2709 skb_shinfo(skb)->nr_frags = i;
2711 for (; i < nfrags; i++)
2712 skb_frag_unref(skb, i);
2714 if (skb_has_frag_list(skb))
2715 skb_drop_fraglist(skb);
2719 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2720 fragp = &frag->next) {
2721 int end = offset + frag->len;
2723 if (skb_shared(frag)) {
2724 struct sk_buff *nfrag;
2726 nfrag = skb_clone(frag, GFP_ATOMIC);
2727 if (unlikely(!nfrag))
2730 nfrag->next = frag->next;
2742 unlikely((err = pskb_trim(frag, len - offset))))
2746 skb_drop_list(&frag->next);
2751 if (len > skb_headlen(skb)) {
2752 skb->data_len -= skb->len - len;
2757 skb_set_tail_pointer(skb, len);
2760 if (!skb->sk || skb->destructor == sock_edemux)
2764 EXPORT_SYMBOL(___pskb_trim);
2766 /* Note : use pskb_trim_rcsum() instead of calling this directly
2768 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2770 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2771 int delta = skb->len - len;
2773 skb->csum = csum_block_sub(skb->csum,
2774 skb_checksum(skb, len, delta, 0),
2776 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2777 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2778 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2780 if (offset + sizeof(__sum16) > hdlen)
2783 return __pskb_trim(skb, len);
2785 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2788 * __pskb_pull_tail - advance tail of skb header
2789 * @skb: buffer to reallocate
2790 * @delta: number of bytes to advance tail
2792 * The function makes a sense only on a fragmented &sk_buff,
2793 * it expands header moving its tail forward and copying necessary
2794 * data from fragmented part.
2796 * &sk_buff MUST have reference count of 1.
2798 * Returns %NULL (and &sk_buff does not change) if pull failed
2799 * or value of new tail of skb in the case of success.
2801 * All the pointers pointing into skb header may change and must be
2802 * reloaded after call to this function.
2805 /* Moves tail of skb head forward, copying data from fragmented part,
2806 * when it is necessary.
2807 * 1. It may fail due to malloc failure.
2808 * 2. It may change skb pointers.
2810 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2812 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2814 /* If skb has not enough free space at tail, get new one
2815 * plus 128 bytes for future expansions. If we have enough
2816 * room at tail, reallocate without expansion only if skb is cloned.
2818 int i, k, eat = (skb->tail + delta) - skb->end;
2820 if (eat > 0 || skb_cloned(skb)) {
2821 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2826 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2827 skb_tail_pointer(skb), delta));
2829 /* Optimization: no fragments, no reasons to preestimate
2830 * size of pulled pages. Superb.
2832 if (!skb_has_frag_list(skb))
2835 /* Estimate size of pulled pages. */
2837 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2838 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2845 /* If we need update frag list, we are in troubles.
2846 * Certainly, it is possible to add an offset to skb data,
2847 * but taking into account that pulling is expected to
2848 * be very rare operation, it is worth to fight against
2849 * further bloating skb head and crucify ourselves here instead.
2850 * Pure masohism, indeed. 8)8)
2853 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2854 struct sk_buff *clone = NULL;
2855 struct sk_buff *insp = NULL;
2858 if (list->len <= eat) {
2859 /* Eaten as whole. */
2864 /* Eaten partially. */
2865 if (skb_is_gso(skb) && !list->head_frag &&
2867 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2869 if (skb_shared(list)) {
2870 /* Sucks! We need to fork list. :-( */
2871 clone = skb_clone(list, GFP_ATOMIC);
2877 /* This may be pulled without
2881 if (!pskb_pull(list, eat)) {
2889 /* Free pulled out fragments. */
2890 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2891 skb_shinfo(skb)->frag_list = list->next;
2894 /* And insert new clone at head. */
2897 skb_shinfo(skb)->frag_list = clone;
2900 /* Success! Now we may commit changes to skb data. */
2905 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2906 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2909 skb_frag_unref(skb, i);
2912 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2914 *frag = skb_shinfo(skb)->frags[i];
2916 skb_frag_off_add(frag, eat);
2917 skb_frag_size_sub(frag, eat);
2925 skb_shinfo(skb)->nr_frags = k;
2929 skb->data_len -= delta;
2932 skb_zcopy_clear(skb, false);
2934 return skb_tail_pointer(skb);
2936 EXPORT_SYMBOL(__pskb_pull_tail);
2939 * skb_copy_bits - copy bits from skb to kernel buffer
2941 * @offset: offset in source
2942 * @to: destination buffer
2943 * @len: number of bytes to copy
2945 * Copy the specified number of bytes from the source skb to the
2946 * destination buffer.
2949 * If its prototype is ever changed,
2950 * check arch/{*}/net/{*}.S files,
2951 * since it is called from BPF assembly code.
2953 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2955 int start = skb_headlen(skb);
2956 struct sk_buff *frag_iter;
2959 if (offset > (int)skb->len - len)
2963 if ((copy = start - offset) > 0) {
2966 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2967 if ((len -= copy) == 0)
2973 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2975 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2977 WARN_ON(start > offset + len);
2979 end = start + skb_frag_size(f);
2980 if ((copy = end - offset) > 0) {
2981 u32 p_off, p_len, copied;
2988 skb_frag_foreach_page(f,
2989 skb_frag_off(f) + offset - start,
2990 copy, p, p_off, p_len, copied) {
2991 vaddr = kmap_atomic(p);
2992 memcpy(to + copied, vaddr + p_off, p_len);
2993 kunmap_atomic(vaddr);
2996 if ((len -= copy) == 0)
3004 skb_walk_frags(skb, frag_iter) {
3007 WARN_ON(start > offset + len);
3009 end = start + frag_iter->len;
3010 if ((copy = end - offset) > 0) {
3013 if (skb_copy_bits(frag_iter, offset - start, to, copy))
3015 if ((len -= copy) == 0)
3029 EXPORT_SYMBOL(skb_copy_bits);
3032 * Callback from splice_to_pipe(), if we need to release some pages
3033 * at the end of the spd in case we error'ed out in filling the pipe.
3035 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
3037 put_page(spd->pages[i]);
3040 static struct page *linear_to_page(struct page *page, unsigned int *len,
3041 unsigned int *offset,
3044 struct page_frag *pfrag = sk_page_frag(sk);
3046 if (!sk_page_frag_refill(sk, pfrag))
3049 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
3051 memcpy(page_address(pfrag->page) + pfrag->offset,
3052 page_address(page) + *offset, *len);
3053 *offset = pfrag->offset;
3054 pfrag->offset += *len;
3059 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
3061 unsigned int offset)
3063 return spd->nr_pages &&
3064 spd->pages[spd->nr_pages - 1] == page &&
3065 (spd->partial[spd->nr_pages - 1].offset +
3066 spd->partial[spd->nr_pages - 1].len == offset);
3070 * Fill page/offset/length into spd, if it can hold more pages.
3072 static bool spd_fill_page(struct splice_pipe_desc *spd,
3073 struct pipe_inode_info *pipe, struct page *page,
3074 unsigned int *len, unsigned int offset,
3078 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
3082 page = linear_to_page(page, len, &offset, sk);
3086 if (spd_can_coalesce(spd, page, offset)) {
3087 spd->partial[spd->nr_pages - 1].len += *len;
3091 spd->pages[spd->nr_pages] = page;
3092 spd->partial[spd->nr_pages].len = *len;
3093 spd->partial[spd->nr_pages].offset = offset;
3099 static bool __splice_segment(struct page *page, unsigned int poff,
3100 unsigned int plen, unsigned int *off,
3102 struct splice_pipe_desc *spd, bool linear,
3104 struct pipe_inode_info *pipe)
3109 /* skip this segment if already processed */
3115 /* ignore any bits we already processed */
3121 unsigned int flen = min(*len, plen);
3123 if (spd_fill_page(spd, pipe, page, &flen, poff,
3129 } while (*len && plen);
3135 * Map linear and fragment data from the skb to spd. It reports true if the
3136 * pipe is full or if we already spliced the requested length.
3138 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
3139 unsigned int *offset, unsigned int *len,
3140 struct splice_pipe_desc *spd, struct sock *sk)
3143 struct sk_buff *iter;
3145 /* map the linear part :
3146 * If skb->head_frag is set, this 'linear' part is backed by a
3147 * fragment, and if the head is not shared with any clones then
3148 * we can avoid a copy since we own the head portion of this page.
3150 if (__splice_segment(virt_to_page(skb->data),
3151 (unsigned long) skb->data & (PAGE_SIZE - 1),
3154 skb_head_is_locked(skb),
3159 * then map the fragments
3161 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
3162 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
3164 if (__splice_segment(skb_frag_page(f),
3165 skb_frag_off(f), skb_frag_size(f),
3166 offset, len, spd, false, sk, pipe))
3170 skb_walk_frags(skb, iter) {
3171 if (*offset >= iter->len) {
3172 *offset -= iter->len;
3175 /* __skb_splice_bits() only fails if the output has no room
3176 * left, so no point in going over the frag_list for the error
3179 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
3187 * Map data from the skb to a pipe. Should handle both the linear part,
3188 * the fragments, and the frag list.
3190 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
3191 struct pipe_inode_info *pipe, unsigned int tlen,
3194 struct partial_page partial[MAX_SKB_FRAGS];
3195 struct page *pages[MAX_SKB_FRAGS];
3196 struct splice_pipe_desc spd = {
3199 .nr_pages_max = MAX_SKB_FRAGS,
3200 .ops = &nosteal_pipe_buf_ops,
3201 .spd_release = sock_spd_release,
3205 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
3208 ret = splice_to_pipe(pipe, &spd);
3212 EXPORT_SYMBOL_GPL(skb_splice_bits);
3214 static int sendmsg_locked(struct sock *sk, struct msghdr *msg)
3216 struct socket *sock = sk->sk_socket;
3217 size_t size = msg_data_left(msg);
3222 if (!sock->ops->sendmsg_locked)
3223 return sock_no_sendmsg_locked(sk, msg, size);
3225 return sock->ops->sendmsg_locked(sk, msg, size);
3228 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg)
3230 struct socket *sock = sk->sk_socket;
3234 return sock_sendmsg(sock, msg);
3237 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg);
3238 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
3239 int len, sendmsg_func sendmsg)
3241 unsigned int orig_len = len;
3242 struct sk_buff *head = skb;
3243 unsigned short fragidx;
3248 /* Deal with head data */
3249 while (offset < skb_headlen(skb) && len) {
3253 slen = min_t(int, len, skb_headlen(skb) - offset);
3254 kv.iov_base = skb->data + offset;
3256 memset(&msg, 0, sizeof(msg));
3257 msg.msg_flags = MSG_DONTWAIT;
3259 iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, &kv, 1, slen);
3260 ret = INDIRECT_CALL_2(sendmsg, sendmsg_locked,
3261 sendmsg_unlocked, sk, &msg);
3269 /* All the data was skb head? */
3273 /* Make offset relative to start of frags */
3274 offset -= skb_headlen(skb);
3276 /* Find where we are in frag list */
3277 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3278 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3280 if (offset < skb_frag_size(frag))
3283 offset -= skb_frag_size(frag);
3286 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3287 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3289 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
3292 struct bio_vec bvec;
3293 struct msghdr msg = {
3294 .msg_flags = MSG_SPLICE_PAGES | MSG_DONTWAIT,
3297 bvec_set_page(&bvec, skb_frag_page(frag), slen,
3298 skb_frag_off(frag) + offset);
3299 iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1,
3302 ret = INDIRECT_CALL_2(sendmsg, sendmsg_locked,
3303 sendmsg_unlocked, sk, &msg);
3316 /* Process any frag lists */
3319 if (skb_has_frag_list(skb)) {
3320 skb = skb_shinfo(skb)->frag_list;
3323 } else if (skb->next) {
3330 return orig_len - len;
3333 return orig_len == len ? ret : orig_len - len;
3336 /* Send skb data on a socket. Socket must be locked. */
3337 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
3340 return __skb_send_sock(sk, skb, offset, len, sendmsg_locked);
3342 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
3344 /* Send skb data on a socket. Socket must be unlocked. */
3345 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
3347 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked);
3351 * skb_store_bits - store bits from kernel buffer to skb
3352 * @skb: destination buffer
3353 * @offset: offset in destination
3354 * @from: source buffer
3355 * @len: number of bytes to copy
3357 * Copy the specified number of bytes from the source buffer to the
3358 * destination skb. This function handles all the messy bits of
3359 * traversing fragment lists and such.
3362 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
3364 int start = skb_headlen(skb);
3365 struct sk_buff *frag_iter;
3368 if (offset > (int)skb->len - len)
3371 if ((copy = start - offset) > 0) {
3374 skb_copy_to_linear_data_offset(skb, offset, from, copy);
3375 if ((len -= copy) == 0)
3381 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3382 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3385 WARN_ON(start > offset + len);
3387 end = start + skb_frag_size(frag);
3388 if ((copy = end - offset) > 0) {
3389 u32 p_off, p_len, copied;
3396 skb_frag_foreach_page(frag,
3397 skb_frag_off(frag) + offset - start,
3398 copy, p, p_off, p_len, copied) {
3399 vaddr = kmap_atomic(p);
3400 memcpy(vaddr + p_off, from + copied, p_len);
3401 kunmap_atomic(vaddr);
3404 if ((len -= copy) == 0)
3412 skb_walk_frags(skb, frag_iter) {
3415 WARN_ON(start > offset + len);
3417 end = start + frag_iter->len;
3418 if ((copy = end - offset) > 0) {
3421 if (skb_store_bits(frag_iter, offset - start,
3424 if ((len -= copy) == 0)
3437 EXPORT_SYMBOL(skb_store_bits);
3439 /* Checksum skb data. */
3440 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
3441 __wsum csum, const struct skb_checksum_ops *ops)
3443 int start = skb_headlen(skb);
3444 int i, copy = start - offset;
3445 struct sk_buff *frag_iter;
3448 /* Checksum header. */
3452 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3453 skb->data + offset, copy, csum);
3454 if ((len -= copy) == 0)
3460 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3462 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3464 WARN_ON(start > offset + len);
3466 end = start + skb_frag_size(frag);
3467 if ((copy = end - offset) > 0) {
3468 u32 p_off, p_len, copied;
3476 skb_frag_foreach_page(frag,
3477 skb_frag_off(frag) + offset - start,
3478 copy, p, p_off, p_len, copied) {
3479 vaddr = kmap_atomic(p);
3480 csum2 = INDIRECT_CALL_1(ops->update,
3482 vaddr + p_off, p_len, 0);
3483 kunmap_atomic(vaddr);
3484 csum = INDIRECT_CALL_1(ops->combine,
3485 csum_block_add_ext, csum,
3497 skb_walk_frags(skb, frag_iter) {
3500 WARN_ON(start > offset + len);
3502 end = start + frag_iter->len;
3503 if ((copy = end - offset) > 0) {
3507 csum2 = __skb_checksum(frag_iter, offset - start,
3509 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3510 csum, csum2, pos, copy);
3511 if ((len -= copy) == 0)
3522 EXPORT_SYMBOL(__skb_checksum);
3524 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3525 int len, __wsum csum)
3527 const struct skb_checksum_ops ops = {
3528 .update = csum_partial_ext,
3529 .combine = csum_block_add_ext,
3532 return __skb_checksum(skb, offset, len, csum, &ops);
3534 EXPORT_SYMBOL(skb_checksum);
3536 /* Both of above in one bottle. */
3538 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3541 int start = skb_headlen(skb);
3542 int i, copy = start - offset;
3543 struct sk_buff *frag_iter;
3551 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3553 if ((len -= copy) == 0)
3560 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3563 WARN_ON(start > offset + len);
3565 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3566 if ((copy = end - offset) > 0) {
3567 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3568 u32 p_off, p_len, copied;
3576 skb_frag_foreach_page(frag,
3577 skb_frag_off(frag) + offset - start,
3578 copy, p, p_off, p_len, copied) {
3579 vaddr = kmap_atomic(p);
3580 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3583 kunmap_atomic(vaddr);
3584 csum = csum_block_add(csum, csum2, pos);
3596 skb_walk_frags(skb, frag_iter) {
3600 WARN_ON(start > offset + len);
3602 end = start + frag_iter->len;
3603 if ((copy = end - offset) > 0) {
3606 csum2 = skb_copy_and_csum_bits(frag_iter,
3609 csum = csum_block_add(csum, csum2, pos);
3610 if ((len -= copy) == 0)
3621 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3623 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3627 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3628 /* See comments in __skb_checksum_complete(). */
3630 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3631 !skb->csum_complete_sw)
3632 netdev_rx_csum_fault(skb->dev, skb);
3634 if (!skb_shared(skb))
3635 skb->csum_valid = !sum;
3638 EXPORT_SYMBOL(__skb_checksum_complete_head);
3640 /* This function assumes skb->csum already holds pseudo header's checksum,
3641 * which has been changed from the hardware checksum, for example, by
3642 * __skb_checksum_validate_complete(). And, the original skb->csum must
3643 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3645 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3646 * zero. The new checksum is stored back into skb->csum unless the skb is
3649 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3654 csum = skb_checksum(skb, 0, skb->len, 0);
3656 sum = csum_fold(csum_add(skb->csum, csum));
3657 /* This check is inverted, because we already knew the hardware
3658 * checksum is invalid before calling this function. So, if the
3659 * re-computed checksum is valid instead, then we have a mismatch
3660 * between the original skb->csum and skb_checksum(). This means either
3661 * the original hardware checksum is incorrect or we screw up skb->csum
3662 * when moving skb->data around.
3665 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3666 !skb->csum_complete_sw)
3667 netdev_rx_csum_fault(skb->dev, skb);
3670 if (!skb_shared(skb)) {
3671 /* Save full packet checksum */
3673 skb->ip_summed = CHECKSUM_COMPLETE;
3674 skb->csum_complete_sw = 1;
3675 skb->csum_valid = !sum;
3680 EXPORT_SYMBOL(__skb_checksum_complete);
3682 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3684 net_warn_ratelimited(
3685 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3690 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3691 int offset, int len)
3693 net_warn_ratelimited(
3694 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3699 static const struct skb_checksum_ops default_crc32c_ops = {
3700 .update = warn_crc32c_csum_update,
3701 .combine = warn_crc32c_csum_combine,
3704 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3705 &default_crc32c_ops;
3706 EXPORT_SYMBOL(crc32c_csum_stub);
3709 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3710 * @from: source buffer
3712 * Calculates the amount of linear headroom needed in the 'to' skb passed
3713 * into skb_zerocopy().
3716 skb_zerocopy_headlen(const struct sk_buff *from)
3718 unsigned int hlen = 0;
3720 if (!from->head_frag ||
3721 skb_headlen(from) < L1_CACHE_BYTES ||
3722 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3723 hlen = skb_headlen(from);
3728 if (skb_has_frag_list(from))
3733 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3736 * skb_zerocopy - Zero copy skb to skb
3737 * @to: destination buffer
3738 * @from: source buffer
3739 * @len: number of bytes to copy from source buffer
3740 * @hlen: size of linear headroom in destination buffer
3742 * Copies up to `len` bytes from `from` to `to` by creating references
3743 * to the frags in the source buffer.
3745 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3746 * headroom in the `to` buffer.
3749 * 0: everything is OK
3750 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3751 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3754 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3757 int plen = 0; /* length of skb->head fragment */
3760 unsigned int offset;
3762 BUG_ON(!from->head_frag && !hlen);
3764 /* dont bother with small payloads */
3765 if (len <= skb_tailroom(to))
3766 return skb_copy_bits(from, 0, skb_put(to, len), len);
3769 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3774 plen = min_t(int, skb_headlen(from), len);
3776 page = virt_to_head_page(from->head);
3777 offset = from->data - (unsigned char *)page_address(page);
3778 __skb_fill_netmem_desc(to, 0, page_to_netmem(page),
3786 skb_len_add(to, len + plen);
3788 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3792 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3794 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3799 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3800 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3802 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3804 skb_frag_ref(to, j);
3807 skb_shinfo(to)->nr_frags = j;
3811 EXPORT_SYMBOL_GPL(skb_zerocopy);
3813 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3818 if (skb->ip_summed == CHECKSUM_PARTIAL)
3819 csstart = skb_checksum_start_offset(skb);
3821 csstart = skb_headlen(skb);
3823 BUG_ON(csstart > skb_headlen(skb));
3825 skb_copy_from_linear_data(skb, to, csstart);
3828 if (csstart != skb->len)
3829 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3830 skb->len - csstart);
3832 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3833 long csstuff = csstart + skb->csum_offset;
3835 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3838 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3841 * skb_dequeue - remove from the head of the queue
3842 * @list: list to dequeue from
3844 * Remove the head of the list. The list lock is taken so the function
3845 * may be used safely with other locking list functions. The head item is
3846 * returned or %NULL if the list is empty.
3849 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3851 unsigned long flags;
3852 struct sk_buff *result;
3854 spin_lock_irqsave(&list->lock, flags);
3855 result = __skb_dequeue(list);
3856 spin_unlock_irqrestore(&list->lock, flags);
3859 EXPORT_SYMBOL(skb_dequeue);
3862 * skb_dequeue_tail - remove from the tail of the queue
3863 * @list: list to dequeue from
3865 * Remove the tail of the list. The list lock is taken so the function
3866 * may be used safely with other locking list functions. The tail item is
3867 * returned or %NULL if the list is empty.
3869 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3871 unsigned long flags;
3872 struct sk_buff *result;
3874 spin_lock_irqsave(&list->lock, flags);
3875 result = __skb_dequeue_tail(list);
3876 spin_unlock_irqrestore(&list->lock, flags);
3879 EXPORT_SYMBOL(skb_dequeue_tail);
3882 * skb_queue_purge_reason - empty a list
3883 * @list: list to empty
3884 * @reason: drop reason
3886 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3887 * the list and one reference dropped. This function takes the list
3888 * lock and is atomic with respect to other list locking functions.
3890 void skb_queue_purge_reason(struct sk_buff_head *list,
3891 enum skb_drop_reason reason)
3893 struct sk_buff_head tmp;
3894 unsigned long flags;
3896 if (skb_queue_empty_lockless(list))
3899 __skb_queue_head_init(&tmp);
3901 spin_lock_irqsave(&list->lock, flags);
3902 skb_queue_splice_init(list, &tmp);
3903 spin_unlock_irqrestore(&list->lock, flags);
3905 __skb_queue_purge_reason(&tmp, reason);
3907 EXPORT_SYMBOL(skb_queue_purge_reason);
3910 * skb_rbtree_purge - empty a skb rbtree
3911 * @root: root of the rbtree to empty
3912 * Return value: the sum of truesizes of all purged skbs.
3914 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3915 * the list and one reference dropped. This function does not take
3916 * any lock. Synchronization should be handled by the caller (e.g., TCP
3917 * out-of-order queue is protected by the socket lock).
3919 unsigned int skb_rbtree_purge(struct rb_root *root)
3921 struct rb_node *p = rb_first(root);
3922 unsigned int sum = 0;
3925 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3928 rb_erase(&skb->rbnode, root);
3929 sum += skb->truesize;
3935 void skb_errqueue_purge(struct sk_buff_head *list)
3937 struct sk_buff *skb, *next;
3938 struct sk_buff_head kill;
3939 unsigned long flags;
3941 __skb_queue_head_init(&kill);
3943 spin_lock_irqsave(&list->lock, flags);
3944 skb_queue_walk_safe(list, skb, next) {
3945 if (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ZEROCOPY ||
3946 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_TIMESTAMPING)
3948 __skb_unlink(skb, list);
3949 __skb_queue_tail(&kill, skb);
3951 spin_unlock_irqrestore(&list->lock, flags);
3952 __skb_queue_purge(&kill);
3954 EXPORT_SYMBOL(skb_errqueue_purge);
3957 * skb_queue_head - queue a buffer at the list head
3958 * @list: list to use
3959 * @newsk: buffer to queue
3961 * Queue a buffer at the start of the list. This function takes the
3962 * list lock and can be used safely with other locking &sk_buff functions
3965 * A buffer cannot be placed on two lists at the same time.
3967 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3969 unsigned long flags;
3971 spin_lock_irqsave(&list->lock, flags);
3972 __skb_queue_head(list, newsk);
3973 spin_unlock_irqrestore(&list->lock, flags);
3975 EXPORT_SYMBOL(skb_queue_head);
3978 * skb_queue_tail - queue a buffer at the list tail
3979 * @list: list to use
3980 * @newsk: buffer to queue
3982 * Queue a buffer at the tail of the list. This function takes the
3983 * list lock and can be used safely with other locking &sk_buff functions
3986 * A buffer cannot be placed on two lists at the same time.
3988 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3990 unsigned long flags;
3992 spin_lock_irqsave(&list->lock, flags);
3993 __skb_queue_tail(list, newsk);
3994 spin_unlock_irqrestore(&list->lock, flags);
3996 EXPORT_SYMBOL(skb_queue_tail);
3999 * skb_unlink - remove a buffer from a list
4000 * @skb: buffer to remove
4001 * @list: list to use
4003 * Remove a packet from a list. The list locks are taken and this
4004 * function is atomic with respect to other list locked calls
4006 * You must know what list the SKB is on.
4008 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
4010 unsigned long flags;
4012 spin_lock_irqsave(&list->lock, flags);
4013 __skb_unlink(skb, list);
4014 spin_unlock_irqrestore(&list->lock, flags);
4016 EXPORT_SYMBOL(skb_unlink);
4019 * skb_append - append a buffer
4020 * @old: buffer to insert after
4021 * @newsk: buffer to insert
4022 * @list: list to use
4024 * Place a packet after a given packet in a list. The list locks are taken
4025 * and this function is atomic with respect to other list locked calls.
4026 * A buffer cannot be placed on two lists at the same time.
4028 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
4030 unsigned long flags;
4032 spin_lock_irqsave(&list->lock, flags);
4033 __skb_queue_after(list, old, newsk);
4034 spin_unlock_irqrestore(&list->lock, flags);
4036 EXPORT_SYMBOL(skb_append);
4038 static inline void skb_split_inside_header(struct sk_buff *skb,
4039 struct sk_buff* skb1,
4040 const u32 len, const int pos)
4044 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
4046 /* And move data appendix as is. */
4047 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
4048 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
4050 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
4051 skb_shinfo(skb)->nr_frags = 0;
4052 skb1->data_len = skb->data_len;
4053 skb1->len += skb1->data_len;
4056 skb_set_tail_pointer(skb, len);
4059 static inline void skb_split_no_header(struct sk_buff *skb,
4060 struct sk_buff* skb1,
4061 const u32 len, int pos)
4064 const int nfrags = skb_shinfo(skb)->nr_frags;
4066 skb_shinfo(skb)->nr_frags = 0;
4067 skb1->len = skb1->data_len = skb->len - len;
4069 skb->data_len = len - pos;
4071 for (i = 0; i < nfrags; i++) {
4072 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
4074 if (pos + size > len) {
4075 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
4079 * We have two variants in this case:
4080 * 1. Move all the frag to the second
4081 * part, if it is possible. F.e.
4082 * this approach is mandatory for TUX,
4083 * where splitting is expensive.
4084 * 2. Split is accurately. We make this.
4086 skb_frag_ref(skb, i);
4087 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
4088 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
4089 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
4090 skb_shinfo(skb)->nr_frags++;
4094 skb_shinfo(skb)->nr_frags++;
4097 skb_shinfo(skb1)->nr_frags = k;
4101 * skb_split - Split fragmented skb to two parts at length len.
4102 * @skb: the buffer to split
4103 * @skb1: the buffer to receive the second part
4104 * @len: new length for skb
4106 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
4108 int pos = skb_headlen(skb);
4109 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
4111 skb_zcopy_downgrade_managed(skb);
4113 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
4114 skb_zerocopy_clone(skb1, skb, 0);
4115 if (len < pos) /* Split line is inside header. */
4116 skb_split_inside_header(skb, skb1, len, pos);
4117 else /* Second chunk has no header, nothing to copy. */
4118 skb_split_no_header(skb, skb1, len, pos);
4120 EXPORT_SYMBOL(skb_split);
4122 /* Shifting from/to a cloned skb is a no-go.
4124 * Caller cannot keep skb_shinfo related pointers past calling here!
4126 static int skb_prepare_for_shift(struct sk_buff *skb)
4128 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
4132 * skb_shift - Shifts paged data partially from skb to another
4133 * @tgt: buffer into which tail data gets added
4134 * @skb: buffer from which the paged data comes from
4135 * @shiftlen: shift up to this many bytes
4137 * Attempts to shift up to shiftlen worth of bytes, which may be less than
4138 * the length of the skb, from skb to tgt. Returns number bytes shifted.
4139 * It's up to caller to free skb if everything was shifted.
4141 * If @tgt runs out of frags, the whole operation is aborted.
4143 * Skb cannot include anything else but paged data while tgt is allowed
4144 * to have non-paged data as well.
4146 * TODO: full sized shift could be optimized but that would need
4147 * specialized skb free'er to handle frags without up-to-date nr_frags.
4149 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
4151 int from, to, merge, todo;
4152 skb_frag_t *fragfrom, *fragto;
4154 BUG_ON(shiftlen > skb->len);
4156 if (skb_headlen(skb))
4158 if (skb_zcopy(tgt) || skb_zcopy(skb))
4161 DEBUG_NET_WARN_ON_ONCE(tgt->pp_recycle != skb->pp_recycle);
4162 DEBUG_NET_WARN_ON_ONCE(skb_cmp_decrypted(tgt, skb));
4166 to = skb_shinfo(tgt)->nr_frags;
4167 fragfrom = &skb_shinfo(skb)->frags[from];
4169 /* Actual merge is delayed until the point when we know we can
4170 * commit all, so that we don't have to undo partial changes
4173 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
4174 skb_frag_off(fragfrom))) {
4179 todo -= skb_frag_size(fragfrom);
4181 if (skb_prepare_for_shift(skb) ||
4182 skb_prepare_for_shift(tgt))
4185 /* All previous frag pointers might be stale! */
4186 fragfrom = &skb_shinfo(skb)->frags[from];
4187 fragto = &skb_shinfo(tgt)->frags[merge];
4189 skb_frag_size_add(fragto, shiftlen);
4190 skb_frag_size_sub(fragfrom, shiftlen);
4191 skb_frag_off_add(fragfrom, shiftlen);
4199 /* Skip full, not-fitting skb to avoid expensive operations */
4200 if ((shiftlen == skb->len) &&
4201 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
4204 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
4207 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
4208 if (to == MAX_SKB_FRAGS)
4211 fragfrom = &skb_shinfo(skb)->frags[from];
4212 fragto = &skb_shinfo(tgt)->frags[to];
4214 if (todo >= skb_frag_size(fragfrom)) {
4215 *fragto = *fragfrom;
4216 todo -= skb_frag_size(fragfrom);
4221 __skb_frag_ref(fragfrom);
4222 skb_frag_page_copy(fragto, fragfrom);
4223 skb_frag_off_copy(fragto, fragfrom);
4224 skb_frag_size_set(fragto, todo);
4226 skb_frag_off_add(fragfrom, todo);
4227 skb_frag_size_sub(fragfrom, todo);
4235 /* Ready to "commit" this state change to tgt */
4236 skb_shinfo(tgt)->nr_frags = to;
4239 fragfrom = &skb_shinfo(skb)->frags[0];
4240 fragto = &skb_shinfo(tgt)->frags[merge];
4242 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
4243 __skb_frag_unref(fragfrom, skb->pp_recycle);
4246 /* Reposition in the original skb */
4248 while (from < skb_shinfo(skb)->nr_frags)
4249 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
4250 skb_shinfo(skb)->nr_frags = to;
4252 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
4255 /* Most likely the tgt won't ever need its checksum anymore, skb on
4256 * the other hand might need it if it needs to be resent
4258 tgt->ip_summed = CHECKSUM_PARTIAL;
4259 skb->ip_summed = CHECKSUM_PARTIAL;
4261 skb_len_add(skb, -shiftlen);
4262 skb_len_add(tgt, shiftlen);
4268 * skb_prepare_seq_read - Prepare a sequential read of skb data
4269 * @skb: the buffer to read
4270 * @from: lower offset of data to be read
4271 * @to: upper offset of data to be read
4272 * @st: state variable
4274 * Initializes the specified state variable. Must be called before
4275 * invoking skb_seq_read() for the first time.
4277 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
4278 unsigned int to, struct skb_seq_state *st)
4280 st->lower_offset = from;
4281 st->upper_offset = to;
4282 st->root_skb = st->cur_skb = skb;
4283 st->frag_idx = st->stepped_offset = 0;
4284 st->frag_data = NULL;
4287 EXPORT_SYMBOL(skb_prepare_seq_read);
4290 * skb_seq_read - Sequentially read skb data
4291 * @consumed: number of bytes consumed by the caller so far
4292 * @data: destination pointer for data to be returned
4293 * @st: state variable
4295 * Reads a block of skb data at @consumed relative to the
4296 * lower offset specified to skb_prepare_seq_read(). Assigns
4297 * the head of the data block to @data and returns the length
4298 * of the block or 0 if the end of the skb data or the upper
4299 * offset has been reached.
4301 * The caller is not required to consume all of the data
4302 * returned, i.e. @consumed is typically set to the number
4303 * of bytes already consumed and the next call to
4304 * skb_seq_read() will return the remaining part of the block.
4306 * Note 1: The size of each block of data returned can be arbitrary,
4307 * this limitation is the cost for zerocopy sequential
4308 * reads of potentially non linear data.
4310 * Note 2: Fragment lists within fragments are not implemented
4311 * at the moment, state->root_skb could be replaced with
4312 * a stack for this purpose.
4314 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
4315 struct skb_seq_state *st)
4317 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
4320 if (unlikely(abs_offset >= st->upper_offset)) {
4321 if (st->frag_data) {
4322 kunmap_atomic(st->frag_data);
4323 st->frag_data = NULL;
4329 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
4331 if (abs_offset < block_limit && !st->frag_data) {
4332 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
4333 return block_limit - abs_offset;
4336 if (st->frag_idx == 0 && !st->frag_data)
4337 st->stepped_offset += skb_headlen(st->cur_skb);
4339 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
4340 unsigned int pg_idx, pg_off, pg_sz;
4342 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
4345 pg_off = skb_frag_off(frag);
4346 pg_sz = skb_frag_size(frag);
4348 if (skb_frag_must_loop(skb_frag_page(frag))) {
4349 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
4350 pg_off = offset_in_page(pg_off + st->frag_off);
4351 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
4352 PAGE_SIZE - pg_off);
4355 block_limit = pg_sz + st->stepped_offset;
4356 if (abs_offset < block_limit) {
4358 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
4360 *data = (u8 *)st->frag_data + pg_off +
4361 (abs_offset - st->stepped_offset);
4363 return block_limit - abs_offset;
4366 if (st->frag_data) {
4367 kunmap_atomic(st->frag_data);
4368 st->frag_data = NULL;
4371 st->stepped_offset += pg_sz;
4372 st->frag_off += pg_sz;
4373 if (st->frag_off == skb_frag_size(frag)) {
4379 if (st->frag_data) {
4380 kunmap_atomic(st->frag_data);
4381 st->frag_data = NULL;
4384 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
4385 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
4388 } else if (st->cur_skb->next) {
4389 st->cur_skb = st->cur_skb->next;
4396 EXPORT_SYMBOL(skb_seq_read);
4399 * skb_abort_seq_read - Abort a sequential read of skb data
4400 * @st: state variable
4402 * Must be called if skb_seq_read() was not called until it
4405 void skb_abort_seq_read(struct skb_seq_state *st)
4408 kunmap_atomic(st->frag_data);
4410 EXPORT_SYMBOL(skb_abort_seq_read);
4412 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
4414 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
4415 struct ts_config *conf,
4416 struct ts_state *state)
4418 return skb_seq_read(offset, text, TS_SKB_CB(state));
4421 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
4423 skb_abort_seq_read(TS_SKB_CB(state));
4427 * skb_find_text - Find a text pattern in skb data
4428 * @skb: the buffer to look in
4429 * @from: search offset
4431 * @config: textsearch configuration
4433 * Finds a pattern in the skb data according to the specified
4434 * textsearch configuration. Use textsearch_next() to retrieve
4435 * subsequent occurrences of the pattern. Returns the offset
4436 * to the first occurrence or UINT_MAX if no match was found.
4438 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4439 unsigned int to, struct ts_config *config)
4441 unsigned int patlen = config->ops->get_pattern_len(config);
4442 struct ts_state state;
4445 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4447 config->get_next_block = skb_ts_get_next_block;
4448 config->finish = skb_ts_finish;
4450 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
4452 ret = textsearch_find(config, &state);
4453 return (ret + patlen <= to - from ? ret : UINT_MAX);
4455 EXPORT_SYMBOL(skb_find_text);
4457 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4458 int offset, size_t size, size_t max_frags)
4460 int i = skb_shinfo(skb)->nr_frags;
4462 if (skb_can_coalesce(skb, i, page, offset)) {
4463 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4464 } else if (i < max_frags) {
4465 skb_zcopy_downgrade_managed(skb);
4467 skb_fill_page_desc_noacc(skb, i, page, offset, size);
4474 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4477 * skb_pull_rcsum - pull skb and update receive checksum
4478 * @skb: buffer to update
4479 * @len: length of data pulled
4481 * This function performs an skb_pull on the packet and updates
4482 * the CHECKSUM_COMPLETE checksum. It should be used on
4483 * receive path processing instead of skb_pull unless you know
4484 * that the checksum difference is zero (e.g., a valid IP header)
4485 * or you are setting ip_summed to CHECKSUM_NONE.
4487 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4489 unsigned char *data = skb->data;
4491 BUG_ON(len > skb->len);
4492 __skb_pull(skb, len);
4493 skb_postpull_rcsum(skb, data, len);
4496 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4498 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4500 skb_frag_t head_frag;
4503 page = virt_to_head_page(frag_skb->head);
4504 skb_frag_fill_page_desc(&head_frag, page, frag_skb->data -
4505 (unsigned char *)page_address(page),
4506 skb_headlen(frag_skb));
4510 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4511 netdev_features_t features,
4512 unsigned int offset)
4514 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4515 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4516 unsigned int delta_truesize = 0;
4517 unsigned int delta_len = 0;
4518 struct sk_buff *tail = NULL;
4519 struct sk_buff *nskb, *tmp;
4522 skb_push(skb, -skb_network_offset(skb) + offset);
4524 /* Ensure the head is writeable before touching the shared info */
4525 err = skb_unclone(skb, GFP_ATOMIC);
4529 skb_shinfo(skb)->frag_list = NULL;
4533 list_skb = list_skb->next;
4536 delta_truesize += nskb->truesize;
4537 if (skb_shared(nskb)) {
4538 tmp = skb_clone(nskb, GFP_ATOMIC);
4542 err = skb_unclone(nskb, GFP_ATOMIC);
4553 if (unlikely(err)) {
4554 nskb->next = list_skb;
4560 delta_len += nskb->len;
4562 skb_push(nskb, -skb_network_offset(nskb) + offset);
4564 skb_release_head_state(nskb);
4565 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4566 __copy_skb_header(nskb, skb);
4568 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4569 nskb->transport_header += len_diff;
4570 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4571 nskb->data - tnl_hlen,
4574 if (skb_needs_linearize(nskb, features) &&
4575 __skb_linearize(nskb))
4579 skb->truesize = skb->truesize - delta_truesize;
4580 skb->data_len = skb->data_len - delta_len;
4581 skb->len = skb->len - delta_len;
4587 if (skb_needs_linearize(skb, features) &&
4588 __skb_linearize(skb))
4596 kfree_skb_list(skb->next);
4598 return ERR_PTR(-ENOMEM);
4600 EXPORT_SYMBOL_GPL(skb_segment_list);
4603 * skb_segment - Perform protocol segmentation on skb.
4604 * @head_skb: buffer to segment
4605 * @features: features for the output path (see dev->features)
4607 * This function performs segmentation on the given skb. It returns
4608 * a pointer to the first in a list of new skbs for the segments.
4609 * In case of error it returns ERR_PTR(err).
4611 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4612 netdev_features_t features)
4614 struct sk_buff *segs = NULL;
4615 struct sk_buff *tail = NULL;
4616 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4617 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4618 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4619 unsigned int offset = doffset;
4620 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4621 unsigned int partial_segs = 0;
4622 unsigned int headroom;
4623 unsigned int len = head_skb->len;
4624 struct sk_buff *frag_skb;
4632 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4633 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4634 struct sk_buff *check_skb;
4636 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4637 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4638 /* gso_size is untrusted, and we have a frag_list with
4639 * a linear non head_frag item.
4641 * If head_skb's headlen does not fit requested gso_size,
4642 * it means that the frag_list members do NOT terminate
4643 * on exact gso_size boundaries. Hence we cannot perform
4644 * skb_frag_t page sharing. Therefore we must fallback to
4645 * copying the frag_list skbs; we do so by disabling SG.
4647 features &= ~NETIF_F_SG;
4653 __skb_push(head_skb, doffset);
4654 proto = skb_network_protocol(head_skb, NULL);
4655 if (unlikely(!proto))
4656 return ERR_PTR(-EINVAL);
4658 sg = !!(features & NETIF_F_SG);
4659 csum = !!can_checksum_protocol(features, proto);
4661 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4662 if (!(features & NETIF_F_GSO_PARTIAL)) {
4663 struct sk_buff *iter;
4664 unsigned int frag_len;
4667 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4670 /* If we get here then all the required
4671 * GSO features except frag_list are supported.
4672 * Try to split the SKB to multiple GSO SKBs
4673 * with no frag_list.
4674 * Currently we can do that only when the buffers don't
4675 * have a linear part and all the buffers except
4676 * the last are of the same length.
4678 frag_len = list_skb->len;
4679 skb_walk_frags(head_skb, iter) {
4680 if (frag_len != iter->len && iter->next)
4682 if (skb_headlen(iter) && !iter->head_frag)
4688 if (len != frag_len)
4692 /* GSO partial only requires that we trim off any excess that
4693 * doesn't fit into an MSS sized block, so take care of that
4695 * Cap len to not accidentally hit GSO_BY_FRAGS.
4697 partial_segs = min(len, GSO_BY_FRAGS - 1) / mss;
4698 if (partial_segs > 1)
4699 mss *= partial_segs;
4705 headroom = skb_headroom(head_skb);
4706 pos = skb_headlen(head_skb);
4708 if (skb_orphan_frags(head_skb, GFP_ATOMIC))
4709 return ERR_PTR(-ENOMEM);
4711 nfrags = skb_shinfo(head_skb)->nr_frags;
4712 frag = skb_shinfo(head_skb)->frags;
4713 frag_skb = head_skb;
4716 struct sk_buff *nskb;
4717 skb_frag_t *nskb_frag;
4721 if (unlikely(mss == GSO_BY_FRAGS)) {
4722 len = list_skb->len;
4724 len = head_skb->len - offset;
4729 hsize = skb_headlen(head_skb) - offset;
4731 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4732 (skb_headlen(list_skb) == len || sg)) {
4733 BUG_ON(skb_headlen(list_skb) > len);
4735 nskb = skb_clone(list_skb, GFP_ATOMIC);
4736 if (unlikely(!nskb))
4740 nfrags = skb_shinfo(list_skb)->nr_frags;
4741 frag = skb_shinfo(list_skb)->frags;
4742 frag_skb = list_skb;
4743 pos += skb_headlen(list_skb);
4745 while (pos < offset + len) {
4746 BUG_ON(i >= nfrags);
4748 size = skb_frag_size(frag);
4749 if (pos + size > offset + len)
4757 list_skb = list_skb->next;
4759 if (unlikely(pskb_trim(nskb, len))) {
4764 hsize = skb_end_offset(nskb);
4765 if (skb_cow_head(nskb, doffset + headroom)) {
4770 nskb->truesize += skb_end_offset(nskb) - hsize;
4771 skb_release_head_state(nskb);
4772 __skb_push(nskb, doffset);
4776 if (hsize > len || !sg)
4779 nskb = __alloc_skb(hsize + doffset + headroom,
4780 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4783 if (unlikely(!nskb))
4786 skb_reserve(nskb, headroom);
4787 __skb_put(nskb, doffset);
4796 __copy_skb_header(nskb, head_skb);
4798 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4799 skb_reset_mac_len(nskb);
4801 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4802 nskb->data - tnl_hlen,
4803 doffset + tnl_hlen);
4805 if (nskb->len == len + doffset)
4806 goto perform_csum_check;
4810 if (!nskb->remcsum_offload)
4811 nskb->ip_summed = CHECKSUM_NONE;
4812 SKB_GSO_CB(nskb)->csum =
4813 skb_copy_and_csum_bits(head_skb, offset,
4817 SKB_GSO_CB(nskb)->csum_start =
4818 skb_headroom(nskb) + doffset;
4820 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4826 nskb_frag = skb_shinfo(nskb)->frags;
4828 skb_copy_from_linear_data_offset(head_skb, offset,
4829 skb_put(nskb, hsize), hsize);
4831 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4834 if (skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4837 while (pos < offset + len) {
4839 if (skb_orphan_frags(list_skb, GFP_ATOMIC) ||
4840 skb_zerocopy_clone(nskb, list_skb,
4845 nfrags = skb_shinfo(list_skb)->nr_frags;
4846 frag = skb_shinfo(list_skb)->frags;
4847 frag_skb = list_skb;
4848 if (!skb_headlen(list_skb)) {
4851 BUG_ON(!list_skb->head_frag);
4853 /* to make room for head_frag. */
4858 list_skb = list_skb->next;
4861 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4863 net_warn_ratelimited(
4864 "skb_segment: too many frags: %u %u\n",
4870 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4871 __skb_frag_ref(nskb_frag);
4872 size = skb_frag_size(nskb_frag);
4875 skb_frag_off_add(nskb_frag, offset - pos);
4876 skb_frag_size_sub(nskb_frag, offset - pos);
4879 skb_shinfo(nskb)->nr_frags++;
4881 if (pos + size <= offset + len) {
4886 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4894 nskb->data_len = len - hsize;
4895 nskb->len += nskb->data_len;
4896 nskb->truesize += nskb->data_len;
4900 if (skb_has_shared_frag(nskb) &&
4901 __skb_linearize(nskb))
4904 if (!nskb->remcsum_offload)
4905 nskb->ip_summed = CHECKSUM_NONE;
4906 SKB_GSO_CB(nskb)->csum =
4907 skb_checksum(nskb, doffset,
4908 nskb->len - doffset, 0);
4909 SKB_GSO_CB(nskb)->csum_start =
4910 skb_headroom(nskb) + doffset;
4912 } while ((offset += len) < head_skb->len);
4914 /* Some callers want to get the end of the list.
4915 * Put it in segs->prev to avoid walking the list.
4916 * (see validate_xmit_skb_list() for example)
4921 struct sk_buff *iter;
4922 int type = skb_shinfo(head_skb)->gso_type;
4923 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4925 /* Update type to add partial and then remove dodgy if set */
4926 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4927 type &= ~SKB_GSO_DODGY;
4929 /* Update GSO info and prepare to start updating headers on
4930 * our way back down the stack of protocols.
4932 for (iter = segs; iter; iter = iter->next) {
4933 skb_shinfo(iter)->gso_size = gso_size;
4934 skb_shinfo(iter)->gso_segs = partial_segs;
4935 skb_shinfo(iter)->gso_type = type;
4936 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4939 if (tail->len - doffset <= gso_size)
4940 skb_shinfo(tail)->gso_size = 0;
4941 else if (tail != segs)
4942 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4945 /* Following permits correct backpressure, for protocols
4946 * using skb_set_owner_w().
4947 * Idea is to tranfert ownership from head_skb to last segment.
4949 if (head_skb->destructor == sock_wfree) {
4950 swap(tail->truesize, head_skb->truesize);
4951 swap(tail->destructor, head_skb->destructor);
4952 swap(tail->sk, head_skb->sk);
4957 kfree_skb_list(segs);
4958 return ERR_PTR(err);
4960 EXPORT_SYMBOL_GPL(skb_segment);
4962 #ifdef CONFIG_SKB_EXTENSIONS
4963 #define SKB_EXT_ALIGN_VALUE 8
4964 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4966 static const u8 skb_ext_type_len[] = {
4967 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4968 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4971 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4973 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4974 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4976 #if IS_ENABLED(CONFIG_MPTCP)
4977 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4979 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4980 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4984 static __always_inline unsigned int skb_ext_total_length(void)
4986 unsigned int l = SKB_EXT_CHUNKSIZEOF(struct skb_ext);
4989 for (i = 0; i < ARRAY_SIZE(skb_ext_type_len); i++)
4990 l += skb_ext_type_len[i];
4995 static void skb_extensions_init(void)
4997 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4998 #if !IS_ENABLED(CONFIG_KCOV_INSTRUMENT_ALL)
4999 BUILD_BUG_ON(skb_ext_total_length() > 255);
5002 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
5003 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
5005 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
5009 static void skb_extensions_init(void) {}
5012 /* The SKB kmem_cache slab is critical for network performance. Never
5013 * merge/alias the slab with similar sized objects. This avoids fragmentation
5014 * that hurts performance of kmem_cache_{alloc,free}_bulk APIs.
5016 #ifndef CONFIG_SLUB_TINY
5017 #define FLAG_SKB_NO_MERGE SLAB_NO_MERGE
5018 #else /* CONFIG_SLUB_TINY - simple loop in kmem_cache_alloc_bulk */
5019 #define FLAG_SKB_NO_MERGE 0
5022 void __init skb_init(void)
5024 net_hotdata.skbuff_cache = kmem_cache_create_usercopy("skbuff_head_cache",
5025 sizeof(struct sk_buff),
5027 SLAB_HWCACHE_ALIGN|SLAB_PANIC|
5029 offsetof(struct sk_buff, cb),
5030 sizeof_field(struct sk_buff, cb),
5032 net_hotdata.skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
5033 sizeof(struct sk_buff_fclones),
5035 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
5037 /* usercopy should only access first SKB_SMALL_HEAD_HEADROOM bytes.
5038 * struct skb_shared_info is located at the end of skb->head,
5039 * and should not be copied to/from user.
5041 net_hotdata.skb_small_head_cache = kmem_cache_create_usercopy("skbuff_small_head",
5042 SKB_SMALL_HEAD_CACHE_SIZE,
5044 SLAB_HWCACHE_ALIGN | SLAB_PANIC,
5046 SKB_SMALL_HEAD_HEADROOM,
5048 skb_extensions_init();
5052 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
5053 unsigned int recursion_level)
5055 int start = skb_headlen(skb);
5056 int i, copy = start - offset;
5057 struct sk_buff *frag_iter;
5060 if (unlikely(recursion_level >= 24))
5066 sg_set_buf(sg, skb->data + offset, copy);
5068 if ((len -= copy) == 0)
5073 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
5076 WARN_ON(start > offset + len);
5078 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
5079 if ((copy = end - offset) > 0) {
5080 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
5081 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
5086 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
5087 skb_frag_off(frag) + offset - start);
5096 skb_walk_frags(skb, frag_iter) {
5099 WARN_ON(start > offset + len);
5101 end = start + frag_iter->len;
5102 if ((copy = end - offset) > 0) {
5103 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
5108 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
5109 copy, recursion_level + 1);
5110 if (unlikely(ret < 0))
5113 if ((len -= copy) == 0)
5124 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
5125 * @skb: Socket buffer containing the buffers to be mapped
5126 * @sg: The scatter-gather list to map into
5127 * @offset: The offset into the buffer's contents to start mapping
5128 * @len: Length of buffer space to be mapped
5130 * Fill the specified scatter-gather list with mappings/pointers into a
5131 * region of the buffer space attached to a socket buffer. Returns either
5132 * the number of scatterlist items used, or -EMSGSIZE if the contents
5135 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
5137 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
5142 sg_mark_end(&sg[nsg - 1]);
5146 EXPORT_SYMBOL_GPL(skb_to_sgvec);
5148 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
5149 * sglist without mark the sg which contain last skb data as the end.
5150 * So the caller can mannipulate sg list as will when padding new data after
5151 * the first call without calling sg_unmark_end to expend sg list.
5153 * Scenario to use skb_to_sgvec_nomark:
5155 * 2. skb_to_sgvec_nomark(payload1)
5156 * 3. skb_to_sgvec_nomark(payload2)
5158 * This is equivalent to:
5160 * 2. skb_to_sgvec(payload1)
5162 * 4. skb_to_sgvec(payload2)
5164 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
5165 * is more preferable.
5167 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
5168 int offset, int len)
5170 return __skb_to_sgvec(skb, sg, offset, len, 0);
5172 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
5177 * skb_cow_data - Check that a socket buffer's data buffers are writable
5178 * @skb: The socket buffer to check.
5179 * @tailbits: Amount of trailing space to be added
5180 * @trailer: Returned pointer to the skb where the @tailbits space begins
5182 * Make sure that the data buffers attached to a socket buffer are
5183 * writable. If they are not, private copies are made of the data buffers
5184 * and the socket buffer is set to use these instead.
5186 * If @tailbits is given, make sure that there is space to write @tailbits
5187 * bytes of data beyond current end of socket buffer. @trailer will be
5188 * set to point to the skb in which this space begins.
5190 * The number of scatterlist elements required to completely map the
5191 * COW'd and extended socket buffer will be returned.
5193 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
5197 struct sk_buff *skb1, **skb_p;
5199 /* If skb is cloned or its head is paged, reallocate
5200 * head pulling out all the pages (pages are considered not writable
5201 * at the moment even if they are anonymous).
5203 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
5204 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
5207 /* Easy case. Most of packets will go this way. */
5208 if (!skb_has_frag_list(skb)) {
5209 /* A little of trouble, not enough of space for trailer.
5210 * This should not happen, when stack is tuned to generate
5211 * good frames. OK, on miss we reallocate and reserve even more
5212 * space, 128 bytes is fair. */
5214 if (skb_tailroom(skb) < tailbits &&
5215 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
5223 /* Misery. We are in troubles, going to mincer fragments... */
5226 skb_p = &skb_shinfo(skb)->frag_list;
5229 while ((skb1 = *skb_p) != NULL) {
5232 /* The fragment is partially pulled by someone,
5233 * this can happen on input. Copy it and everything
5236 if (skb_shared(skb1))
5239 /* If the skb is the last, worry about trailer. */
5241 if (skb1->next == NULL && tailbits) {
5242 if (skb_shinfo(skb1)->nr_frags ||
5243 skb_has_frag_list(skb1) ||
5244 skb_tailroom(skb1) < tailbits)
5245 ntail = tailbits + 128;
5251 skb_shinfo(skb1)->nr_frags ||
5252 skb_has_frag_list(skb1)) {
5253 struct sk_buff *skb2;
5255 /* Fuck, we are miserable poor guys... */
5257 skb2 = skb_copy(skb1, GFP_ATOMIC);
5259 skb2 = skb_copy_expand(skb1,
5263 if (unlikely(skb2 == NULL))
5267 skb_set_owner_w(skb2, skb1->sk);
5269 /* Looking around. Are we still alive?
5270 * OK, link new skb, drop old one */
5272 skb2->next = skb1->next;
5279 skb_p = &skb1->next;
5284 EXPORT_SYMBOL_GPL(skb_cow_data);
5286 static void sock_rmem_free(struct sk_buff *skb)
5288 struct sock *sk = skb->sk;
5290 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
5293 static void skb_set_err_queue(struct sk_buff *skb)
5295 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
5296 * So, it is safe to (mis)use it to mark skbs on the error queue.
5298 skb->pkt_type = PACKET_OUTGOING;
5299 BUILD_BUG_ON(PACKET_OUTGOING == 0);
5303 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
5305 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
5307 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
5308 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
5313 skb->destructor = sock_rmem_free;
5314 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
5315 skb_set_err_queue(skb);
5317 /* before exiting rcu section, make sure dst is refcounted */
5320 skb_queue_tail(&sk->sk_error_queue, skb);
5321 if (!sock_flag(sk, SOCK_DEAD))
5322 sk_error_report(sk);
5325 EXPORT_SYMBOL(sock_queue_err_skb);
5327 static bool is_icmp_err_skb(const struct sk_buff *skb)
5329 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
5330 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
5333 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
5335 struct sk_buff_head *q = &sk->sk_error_queue;
5336 struct sk_buff *skb, *skb_next = NULL;
5337 bool icmp_next = false;
5338 unsigned long flags;
5340 if (skb_queue_empty_lockless(q))
5343 spin_lock_irqsave(&q->lock, flags);
5344 skb = __skb_dequeue(q);
5345 if (skb && (skb_next = skb_peek(q))) {
5346 icmp_next = is_icmp_err_skb(skb_next);
5348 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
5350 spin_unlock_irqrestore(&q->lock, flags);
5352 if (is_icmp_err_skb(skb) && !icmp_next)
5356 sk_error_report(sk);
5360 EXPORT_SYMBOL(sock_dequeue_err_skb);
5363 * skb_clone_sk - create clone of skb, and take reference to socket
5364 * @skb: the skb to clone
5366 * This function creates a clone of a buffer that holds a reference on
5367 * sk_refcnt. Buffers created via this function are meant to be
5368 * returned using sock_queue_err_skb, or free via kfree_skb.
5370 * When passing buffers allocated with this function to sock_queue_err_skb
5371 * it is necessary to wrap the call with sock_hold/sock_put in order to
5372 * prevent the socket from being released prior to being enqueued on
5373 * the sk_error_queue.
5375 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
5377 struct sock *sk = skb->sk;
5378 struct sk_buff *clone;
5380 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
5383 clone = skb_clone(skb, GFP_ATOMIC);
5390 clone->destructor = sock_efree;
5394 EXPORT_SYMBOL(skb_clone_sk);
5396 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
5401 struct sock_exterr_skb *serr;
5404 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
5406 serr = SKB_EXT_ERR(skb);
5407 memset(serr, 0, sizeof(*serr));
5408 serr->ee.ee_errno = ENOMSG;
5409 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5410 serr->ee.ee_info = tstype;
5411 serr->opt_stats = opt_stats;
5412 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5413 if (READ_ONCE(sk->sk_tsflags) & SOF_TIMESTAMPING_OPT_ID) {
5414 serr->ee.ee_data = skb_shinfo(skb)->tskey;
5416 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5419 err = sock_queue_err_skb(sk, skb);
5425 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5429 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5432 read_lock_bh(&sk->sk_callback_lock);
5433 ret = sk->sk_socket && sk->sk_socket->file &&
5434 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5435 read_unlock_bh(&sk->sk_callback_lock);
5439 void skb_complete_tx_timestamp(struct sk_buff *skb,
5440 struct skb_shared_hwtstamps *hwtstamps)
5442 struct sock *sk = skb->sk;
5444 if (!skb_may_tx_timestamp(sk, false))
5447 /* Take a reference to prevent skb_orphan() from freeing the socket,
5448 * but only if the socket refcount is not zero.
5450 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5451 *skb_hwtstamps(skb) = *hwtstamps;
5452 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5460 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5462 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5463 const struct sk_buff *ack_skb,
5464 struct skb_shared_hwtstamps *hwtstamps,
5465 struct sock *sk, int tstype)
5467 struct sk_buff *skb;
5468 bool tsonly, opt_stats = false;
5474 tsflags = READ_ONCE(sk->sk_tsflags);
5475 if (!hwtstamps && !(tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5476 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5479 tsonly = tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5480 if (!skb_may_tx_timestamp(sk, tsonly))
5485 if ((tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5487 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5492 skb = alloc_skb(0, GFP_ATOMIC);
5494 skb = skb_clone(orig_skb, GFP_ATOMIC);
5496 if (skb_orphan_frags_rx(skb, GFP_ATOMIC)) {
5505 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5507 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5511 *skb_hwtstamps(skb) = *hwtstamps;
5513 __net_timestamp(skb);
5515 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5517 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5519 void skb_tstamp_tx(struct sk_buff *orig_skb,
5520 struct skb_shared_hwtstamps *hwtstamps)
5522 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5525 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5527 #ifdef CONFIG_WIRELESS
5528 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5530 struct sock *sk = skb->sk;
5531 struct sock_exterr_skb *serr;
5534 skb->wifi_acked_valid = 1;
5535 skb->wifi_acked = acked;
5537 serr = SKB_EXT_ERR(skb);
5538 memset(serr, 0, sizeof(*serr));
5539 serr->ee.ee_errno = ENOMSG;
5540 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5542 /* Take a reference to prevent skb_orphan() from freeing the socket,
5543 * but only if the socket refcount is not zero.
5545 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5546 err = sock_queue_err_skb(sk, skb);
5552 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5553 #endif /* CONFIG_WIRELESS */
5556 * skb_partial_csum_set - set up and verify partial csum values for packet
5557 * @skb: the skb to set
5558 * @start: the number of bytes after skb->data to start checksumming.
5559 * @off: the offset from start to place the checksum.
5561 * For untrusted partially-checksummed packets, we need to make sure the values
5562 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5564 * This function checks and sets those values and skb->ip_summed: if this
5565 * returns false you should drop the packet.
5567 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5569 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5570 u32 csum_start = skb_headroom(skb) + (u32)start;
5572 if (unlikely(csum_start >= U16_MAX || csum_end > skb_headlen(skb))) {
5573 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5574 start, off, skb_headroom(skb), skb_headlen(skb));
5577 skb->ip_summed = CHECKSUM_PARTIAL;
5578 skb->csum_start = csum_start;
5579 skb->csum_offset = off;
5580 skb->transport_header = csum_start;
5583 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5585 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5588 if (skb_headlen(skb) >= len)
5591 /* If we need to pullup then pullup to the max, so we
5592 * won't need to do it again.
5597 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5600 if (skb_headlen(skb) < len)
5606 #define MAX_TCP_HDR_LEN (15 * 4)
5608 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5609 typeof(IPPROTO_IP) proto,
5616 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5617 off + MAX_TCP_HDR_LEN);
5618 if (!err && !skb_partial_csum_set(skb, off,
5619 offsetof(struct tcphdr,
5622 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5625 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5626 off + sizeof(struct udphdr));
5627 if (!err && !skb_partial_csum_set(skb, off,
5628 offsetof(struct udphdr,
5631 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5634 return ERR_PTR(-EPROTO);
5637 /* This value should be large enough to cover a tagged ethernet header plus
5638 * maximally sized IP and TCP or UDP headers.
5640 #define MAX_IP_HDR_LEN 128
5642 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5651 err = skb_maybe_pull_tail(skb,
5652 sizeof(struct iphdr),
5657 if (ip_is_fragment(ip_hdr(skb)))
5660 off = ip_hdrlen(skb);
5667 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5669 return PTR_ERR(csum);
5672 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5675 ip_hdr(skb)->protocol, 0);
5682 /* This value should be large enough to cover a tagged ethernet header plus
5683 * an IPv6 header, all options, and a maximal TCP or UDP header.
5685 #define MAX_IPV6_HDR_LEN 256
5687 #define OPT_HDR(type, skb, off) \
5688 (type *)(skb_network_header(skb) + (off))
5690 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5703 off = sizeof(struct ipv6hdr);
5705 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5709 nexthdr = ipv6_hdr(skb)->nexthdr;
5711 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5712 while (off <= len && !done) {
5714 case IPPROTO_DSTOPTS:
5715 case IPPROTO_HOPOPTS:
5716 case IPPROTO_ROUTING: {
5717 struct ipv6_opt_hdr *hp;
5719 err = skb_maybe_pull_tail(skb,
5721 sizeof(struct ipv6_opt_hdr),
5726 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5727 nexthdr = hp->nexthdr;
5728 off += ipv6_optlen(hp);
5732 struct ip_auth_hdr *hp;
5734 err = skb_maybe_pull_tail(skb,
5736 sizeof(struct ip_auth_hdr),
5741 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5742 nexthdr = hp->nexthdr;
5743 off += ipv6_authlen(hp);
5746 case IPPROTO_FRAGMENT: {
5747 struct frag_hdr *hp;
5749 err = skb_maybe_pull_tail(skb,
5751 sizeof(struct frag_hdr),
5756 hp = OPT_HDR(struct frag_hdr, skb, off);
5758 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5761 nexthdr = hp->nexthdr;
5762 off += sizeof(struct frag_hdr);
5773 if (!done || fragment)
5776 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5778 return PTR_ERR(csum);
5781 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5782 &ipv6_hdr(skb)->daddr,
5783 skb->len - off, nexthdr, 0);
5791 * skb_checksum_setup - set up partial checksum offset
5792 * @skb: the skb to set up
5793 * @recalculate: if true the pseudo-header checksum will be recalculated
5795 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5799 switch (skb->protocol) {
5800 case htons(ETH_P_IP):
5801 err = skb_checksum_setup_ipv4(skb, recalculate);
5804 case htons(ETH_P_IPV6):
5805 err = skb_checksum_setup_ipv6(skb, recalculate);
5815 EXPORT_SYMBOL(skb_checksum_setup);
5818 * skb_checksum_maybe_trim - maybe trims the given skb
5819 * @skb: the skb to check
5820 * @transport_len: the data length beyond the network header
5822 * Checks whether the given skb has data beyond the given transport length.
5823 * If so, returns a cloned skb trimmed to this transport length.
5824 * Otherwise returns the provided skb. Returns NULL in error cases
5825 * (e.g. transport_len exceeds skb length or out-of-memory).
5827 * Caller needs to set the skb transport header and free any returned skb if it
5828 * differs from the provided skb.
5830 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5831 unsigned int transport_len)
5833 struct sk_buff *skb_chk;
5834 unsigned int len = skb_transport_offset(skb) + transport_len;
5839 else if (skb->len == len)
5842 skb_chk = skb_clone(skb, GFP_ATOMIC);
5846 ret = pskb_trim_rcsum(skb_chk, len);
5856 * skb_checksum_trimmed - validate checksum of an skb
5857 * @skb: the skb to check
5858 * @transport_len: the data length beyond the network header
5859 * @skb_chkf: checksum function to use
5861 * Applies the given checksum function skb_chkf to the provided skb.
5862 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5864 * If the skb has data beyond the given transport length, then a
5865 * trimmed & cloned skb is checked and returned.
5867 * Caller needs to set the skb transport header and free any returned skb if it
5868 * differs from the provided skb.
5870 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5871 unsigned int transport_len,
5872 __sum16(*skb_chkf)(struct sk_buff *skb))
5874 struct sk_buff *skb_chk;
5875 unsigned int offset = skb_transport_offset(skb);
5878 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5882 if (!pskb_may_pull(skb_chk, offset))
5885 skb_pull_rcsum(skb_chk, offset);
5886 ret = skb_chkf(skb_chk);
5887 skb_push_rcsum(skb_chk, offset);
5895 if (skb_chk && skb_chk != skb)
5901 EXPORT_SYMBOL(skb_checksum_trimmed);
5903 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5905 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5908 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5910 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5913 skb_release_head_state(skb);
5914 kmem_cache_free(net_hotdata.skbuff_cache, skb);
5919 EXPORT_SYMBOL(kfree_skb_partial);
5922 * skb_try_coalesce - try to merge skb to prior one
5924 * @from: buffer to add
5925 * @fragstolen: pointer to boolean
5926 * @delta_truesize: how much more was allocated than was requested
5928 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5929 bool *fragstolen, int *delta_truesize)
5931 struct skb_shared_info *to_shinfo, *from_shinfo;
5932 int i, delta, len = from->len;
5934 *fragstolen = false;
5939 /* In general, avoid mixing page_pool and non-page_pool allocated
5940 * pages within the same SKB. In theory we could take full
5941 * references if @from is cloned and !@to->pp_recycle but its
5942 * tricky (due to potential race with the clone disappearing) and
5943 * rare, so not worth dealing with.
5945 if (to->pp_recycle != from->pp_recycle)
5948 if (len <= skb_tailroom(to)) {
5950 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5951 *delta_truesize = 0;
5955 to_shinfo = skb_shinfo(to);
5956 from_shinfo = skb_shinfo(from);
5957 if (to_shinfo->frag_list || from_shinfo->frag_list)
5959 if (skb_zcopy(to) || skb_zcopy(from))
5962 if (skb_headlen(from) != 0) {
5964 unsigned int offset;
5966 if (to_shinfo->nr_frags +
5967 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5970 if (skb_head_is_locked(from))
5973 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5975 page = virt_to_head_page(from->head);
5976 offset = from->data - (unsigned char *)page_address(page);
5978 skb_fill_page_desc(to, to_shinfo->nr_frags,
5979 page, offset, skb_headlen(from));
5982 if (to_shinfo->nr_frags +
5983 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5986 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5989 WARN_ON_ONCE(delta < len);
5991 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5993 from_shinfo->nr_frags * sizeof(skb_frag_t));
5994 to_shinfo->nr_frags += from_shinfo->nr_frags;
5996 if (!skb_cloned(from))
5997 from_shinfo->nr_frags = 0;
5999 /* if the skb is not cloned this does nothing
6000 * since we set nr_frags to 0.
6002 if (skb_pp_frag_ref(from)) {
6003 for (i = 0; i < from_shinfo->nr_frags; i++)
6004 __skb_frag_ref(&from_shinfo->frags[i]);
6007 to->truesize += delta;
6009 to->data_len += len;
6011 *delta_truesize = delta;
6014 EXPORT_SYMBOL(skb_try_coalesce);
6017 * skb_scrub_packet - scrub an skb
6019 * @skb: buffer to clean
6020 * @xnet: packet is crossing netns
6022 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
6023 * into/from a tunnel. Some information have to be cleared during these
6025 * skb_scrub_packet can also be used to clean a skb before injecting it in
6026 * another namespace (@xnet == true). We have to clear all information in the
6027 * skb that could impact namespace isolation.
6029 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
6031 skb->pkt_type = PACKET_HOST;
6037 nf_reset_trace(skb);
6039 #ifdef CONFIG_NET_SWITCHDEV
6040 skb->offload_fwd_mark = 0;
6041 skb->offload_l3_fwd_mark = 0;
6049 skb_clear_tstamp(skb);
6051 EXPORT_SYMBOL_GPL(skb_scrub_packet);
6053 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
6055 int mac_len, meta_len;
6058 if (skb_cow(skb, skb_headroom(skb)) < 0) {
6063 mac_len = skb->data - skb_mac_header(skb);
6064 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
6065 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
6066 mac_len - VLAN_HLEN - ETH_TLEN);
6069 meta_len = skb_metadata_len(skb);
6071 meta = skb_metadata_end(skb) - meta_len;
6072 memmove(meta + VLAN_HLEN, meta, meta_len);
6075 skb->mac_header += VLAN_HLEN;
6079 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
6081 struct vlan_hdr *vhdr;
6084 if (unlikely(skb_vlan_tag_present(skb))) {
6085 /* vlan_tci is already set-up so leave this for another time */
6089 skb = skb_share_check(skb, GFP_ATOMIC);
6092 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
6093 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
6096 vhdr = (struct vlan_hdr *)skb->data;
6097 vlan_tci = ntohs(vhdr->h_vlan_TCI);
6098 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
6100 skb_pull_rcsum(skb, VLAN_HLEN);
6101 vlan_set_encap_proto(skb, vhdr);
6103 skb = skb_reorder_vlan_header(skb);
6107 skb_reset_network_header(skb);
6108 if (!skb_transport_header_was_set(skb))
6109 skb_reset_transport_header(skb);
6110 skb_reset_mac_len(skb);
6118 EXPORT_SYMBOL(skb_vlan_untag);
6120 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
6122 if (!pskb_may_pull(skb, write_len))
6125 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
6128 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
6130 EXPORT_SYMBOL(skb_ensure_writable);
6132 int skb_ensure_writable_head_tail(struct sk_buff *skb, struct net_device *dev)
6134 int needed_headroom = dev->needed_headroom;
6135 int needed_tailroom = dev->needed_tailroom;
6137 /* For tail taggers, we need to pad short frames ourselves, to ensure
6138 * that the tail tag does not fail at its role of being at the end of
6139 * the packet, once the conduit interface pads the frame. Account for
6140 * that pad length here, and pad later.
6142 if (unlikely(needed_tailroom && skb->len < ETH_ZLEN))
6143 needed_tailroom += ETH_ZLEN - skb->len;
6144 /* skb_headroom() returns unsigned int... */
6145 needed_headroom = max_t(int, needed_headroom - skb_headroom(skb), 0);
6146 needed_tailroom = max_t(int, needed_tailroom - skb_tailroom(skb), 0);
6148 if (likely(!needed_headroom && !needed_tailroom && !skb_cloned(skb)))
6149 /* No reallocation needed, yay! */
6152 return pskb_expand_head(skb, needed_headroom, needed_tailroom,
6155 EXPORT_SYMBOL(skb_ensure_writable_head_tail);
6157 /* remove VLAN header from packet and update csum accordingly.
6158 * expects a non skb_vlan_tag_present skb with a vlan tag payload
6160 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
6162 int offset = skb->data - skb_mac_header(skb);
6165 if (WARN_ONCE(offset,
6166 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
6171 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
6175 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6177 vlan_remove_tag(skb, vlan_tci);
6179 skb->mac_header += VLAN_HLEN;
6181 if (skb_network_offset(skb) < ETH_HLEN)
6182 skb_set_network_header(skb, ETH_HLEN);
6184 skb_reset_mac_len(skb);
6188 EXPORT_SYMBOL(__skb_vlan_pop);
6190 /* Pop a vlan tag either from hwaccel or from payload.
6191 * Expects skb->data at mac header.
6193 int skb_vlan_pop(struct sk_buff *skb)
6199 if (likely(skb_vlan_tag_present(skb))) {
6200 __vlan_hwaccel_clear_tag(skb);
6202 if (unlikely(!eth_type_vlan(skb->protocol)))
6205 err = __skb_vlan_pop(skb, &vlan_tci);
6209 /* move next vlan tag to hw accel tag */
6210 if (likely(!eth_type_vlan(skb->protocol)))
6213 vlan_proto = skb->protocol;
6214 err = __skb_vlan_pop(skb, &vlan_tci);
6218 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6221 EXPORT_SYMBOL(skb_vlan_pop);
6223 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
6224 * Expects skb->data at mac header.
6226 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
6228 if (skb_vlan_tag_present(skb)) {
6229 int offset = skb->data - skb_mac_header(skb);
6232 if (WARN_ONCE(offset,
6233 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
6238 err = __vlan_insert_tag(skb, skb->vlan_proto,
6239 skb_vlan_tag_get(skb));
6243 skb->protocol = skb->vlan_proto;
6244 skb->mac_len += VLAN_HLEN;
6246 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6248 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6251 EXPORT_SYMBOL(skb_vlan_push);
6254 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
6256 * @skb: Socket buffer to modify
6258 * Drop the Ethernet header of @skb.
6260 * Expects that skb->data points to the mac header and that no VLAN tags are
6263 * Returns 0 on success, -errno otherwise.
6265 int skb_eth_pop(struct sk_buff *skb)
6267 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
6268 skb_network_offset(skb) < ETH_HLEN)
6271 skb_pull_rcsum(skb, ETH_HLEN);
6272 skb_reset_mac_header(skb);
6273 skb_reset_mac_len(skb);
6277 EXPORT_SYMBOL(skb_eth_pop);
6280 * skb_eth_push() - Add a new Ethernet header at the head of a packet
6282 * @skb: Socket buffer to modify
6283 * @dst: Destination MAC address of the new header
6284 * @src: Source MAC address of the new header
6286 * Prepend @skb with a new Ethernet header.
6288 * Expects that skb->data points to the mac header, which must be empty.
6290 * Returns 0 on success, -errno otherwise.
6292 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6293 const unsigned char *src)
6298 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6301 err = skb_cow_head(skb, sizeof(*eth));
6305 skb_push(skb, sizeof(*eth));
6306 skb_reset_mac_header(skb);
6307 skb_reset_mac_len(skb);
6310 ether_addr_copy(eth->h_dest, dst);
6311 ether_addr_copy(eth->h_source, src);
6312 eth->h_proto = skb->protocol;
6314 skb_postpush_rcsum(skb, eth, sizeof(*eth));
6318 EXPORT_SYMBOL(skb_eth_push);
6320 /* Update the ethertype of hdr and the skb csum value if required. */
6321 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6324 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6325 __be16 diff[] = { ~hdr->h_proto, ethertype };
6327 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6330 hdr->h_proto = ethertype;
6334 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6338 * @mpls_lse: MPLS label stack entry to push
6339 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6340 * @mac_len: length of the MAC header
6341 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6344 * Expects skb->data at mac header.
6346 * Returns 0 on success, -errno otherwise.
6348 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6349 int mac_len, bool ethernet)
6351 struct mpls_shim_hdr *lse;
6354 if (unlikely(!eth_p_mpls(mpls_proto)))
6357 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6358 if (skb->encapsulation)
6361 err = skb_cow_head(skb, MPLS_HLEN);
6365 if (!skb->inner_protocol) {
6366 skb_set_inner_network_header(skb, skb_network_offset(skb));
6367 skb_set_inner_protocol(skb, skb->protocol);
6370 skb_push(skb, MPLS_HLEN);
6371 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6373 skb_reset_mac_header(skb);
6374 skb_set_network_header(skb, mac_len);
6375 skb_reset_mac_len(skb);
6377 lse = mpls_hdr(skb);
6378 lse->label_stack_entry = mpls_lse;
6379 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6381 if (ethernet && mac_len >= ETH_HLEN)
6382 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6383 skb->protocol = mpls_proto;
6387 EXPORT_SYMBOL_GPL(skb_mpls_push);
6390 * skb_mpls_pop() - pop the outermost MPLS header
6393 * @next_proto: ethertype of header after popped MPLS header
6394 * @mac_len: length of the MAC header
6395 * @ethernet: flag to indicate if the packet is ethernet
6397 * Expects skb->data at mac header.
6399 * Returns 0 on success, -errno otherwise.
6401 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6406 if (unlikely(!eth_p_mpls(skb->protocol)))
6409 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6413 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6414 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6417 __skb_pull(skb, MPLS_HLEN);
6418 skb_reset_mac_header(skb);
6419 skb_set_network_header(skb, mac_len);
6421 if (ethernet && mac_len >= ETH_HLEN) {
6424 /* use mpls_hdr() to get ethertype to account for VLANs. */
6425 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6426 skb_mod_eth_type(skb, hdr, next_proto);
6428 skb->protocol = next_proto;
6432 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6435 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6438 * @mpls_lse: new MPLS label stack entry to update to
6440 * Expects skb->data at mac header.
6442 * Returns 0 on success, -errno otherwise.
6444 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6448 if (unlikely(!eth_p_mpls(skb->protocol)))
6451 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6455 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6456 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6458 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6461 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6465 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6468 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6472 * Expects skb->data at mac header.
6474 * Returns 0 on success, -errno otherwise.
6476 int skb_mpls_dec_ttl(struct sk_buff *skb)
6481 if (unlikely(!eth_p_mpls(skb->protocol)))
6484 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6487 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6488 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6492 lse &= ~MPLS_LS_TTL_MASK;
6493 lse |= ttl << MPLS_LS_TTL_SHIFT;
6495 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6497 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6500 * alloc_skb_with_frags - allocate skb with page frags
6502 * @header_len: size of linear part
6503 * @data_len: needed length in frags
6504 * @order: max page order desired.
6505 * @errcode: pointer to error code if any
6506 * @gfp_mask: allocation mask
6508 * This can be used to allocate a paged skb, given a maximal order for frags.
6510 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6511 unsigned long data_len,
6516 unsigned long chunk;
6517 struct sk_buff *skb;
6521 *errcode = -EMSGSIZE;
6522 if (unlikely(data_len > MAX_SKB_FRAGS * (PAGE_SIZE << order)))
6525 *errcode = -ENOBUFS;
6526 skb = alloc_skb(header_len, gfp_mask);
6531 if (nr_frags == MAX_SKB_FRAGS - 1)
6533 while (order && PAGE_ALIGN(data_len) < (PAGE_SIZE << order))
6537 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6546 page = alloc_page(gfp_mask);
6550 chunk = min_t(unsigned long, data_len,
6551 PAGE_SIZE << order);
6552 skb_fill_page_desc(skb, nr_frags, page, 0, chunk);
6554 skb->truesize += (PAGE_SIZE << order);
6563 EXPORT_SYMBOL(alloc_skb_with_frags);
6565 /* carve out the first off bytes from skb when off < headlen */
6566 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6567 const int headlen, gfp_t gfp_mask)
6570 unsigned int size = skb_end_offset(skb);
6571 int new_hlen = headlen - off;
6574 if (skb_pfmemalloc(skb))
6575 gfp_mask |= __GFP_MEMALLOC;
6577 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6580 size = SKB_WITH_OVERHEAD(size);
6582 /* Copy real data, and all frags */
6583 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6586 memcpy((struct skb_shared_info *)(data + size),
6588 offsetof(struct skb_shared_info,
6589 frags[skb_shinfo(skb)->nr_frags]));
6590 if (skb_cloned(skb)) {
6591 /* drop the old head gracefully */
6592 if (skb_orphan_frags(skb, gfp_mask)) {
6593 skb_kfree_head(data, size);
6596 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6597 skb_frag_ref(skb, i);
6598 if (skb_has_frag_list(skb))
6599 skb_clone_fraglist(skb);
6600 skb_release_data(skb, SKB_CONSUMED);
6602 /* we can reuse existing recount- all we did was
6611 skb_set_end_offset(skb, size);
6612 skb_set_tail_pointer(skb, skb_headlen(skb));
6613 skb_headers_offset_update(skb, 0);
6617 atomic_set(&skb_shinfo(skb)->dataref, 1);
6622 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6624 /* carve out the first eat bytes from skb's frag_list. May recurse into
6627 static int pskb_carve_frag_list(struct sk_buff *skb,
6628 struct skb_shared_info *shinfo, int eat,
6631 struct sk_buff *list = shinfo->frag_list;
6632 struct sk_buff *clone = NULL;
6633 struct sk_buff *insp = NULL;
6637 pr_err("Not enough bytes to eat. Want %d\n", eat);
6640 if (list->len <= eat) {
6641 /* Eaten as whole. */
6646 /* Eaten partially. */
6647 if (skb_shared(list)) {
6648 clone = skb_clone(list, gfp_mask);
6654 /* This may be pulled without problems. */
6657 if (pskb_carve(list, eat, gfp_mask) < 0) {
6665 /* Free pulled out fragments. */
6666 while ((list = shinfo->frag_list) != insp) {
6667 shinfo->frag_list = list->next;
6670 /* And insert new clone at head. */
6673 shinfo->frag_list = clone;
6678 /* carve off first len bytes from skb. Split line (off) is in the
6679 * non-linear part of skb
6681 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6682 int pos, gfp_t gfp_mask)
6685 unsigned int size = skb_end_offset(skb);
6687 const int nfrags = skb_shinfo(skb)->nr_frags;
6688 struct skb_shared_info *shinfo;
6690 if (skb_pfmemalloc(skb))
6691 gfp_mask |= __GFP_MEMALLOC;
6693 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6696 size = SKB_WITH_OVERHEAD(size);
6698 memcpy((struct skb_shared_info *)(data + size),
6699 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6700 if (skb_orphan_frags(skb, gfp_mask)) {
6701 skb_kfree_head(data, size);
6704 shinfo = (struct skb_shared_info *)(data + size);
6705 for (i = 0; i < nfrags; i++) {
6706 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6708 if (pos + fsize > off) {
6709 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6713 * We have two variants in this case:
6714 * 1. Move all the frag to the second
6715 * part, if it is possible. F.e.
6716 * this approach is mandatory for TUX,
6717 * where splitting is expensive.
6718 * 2. Split is accurately. We make this.
6720 skb_frag_off_add(&shinfo->frags[0], off - pos);
6721 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6723 skb_frag_ref(skb, i);
6728 shinfo->nr_frags = k;
6729 if (skb_has_frag_list(skb))
6730 skb_clone_fraglist(skb);
6732 /* split line is in frag list */
6733 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6734 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6735 if (skb_has_frag_list(skb))
6736 kfree_skb_list(skb_shinfo(skb)->frag_list);
6737 skb_kfree_head(data, size);
6740 skb_release_data(skb, SKB_CONSUMED);
6745 skb_set_end_offset(skb, size);
6746 skb_reset_tail_pointer(skb);
6747 skb_headers_offset_update(skb, 0);
6752 skb->data_len = skb->len;
6753 atomic_set(&skb_shinfo(skb)->dataref, 1);
6757 /* remove len bytes from the beginning of the skb */
6758 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6760 int headlen = skb_headlen(skb);
6763 return pskb_carve_inside_header(skb, len, headlen, gfp);
6765 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6768 /* Extract to_copy bytes starting at off from skb, and return this in
6771 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6772 int to_copy, gfp_t gfp)
6774 struct sk_buff *clone = skb_clone(skb, gfp);
6779 if (pskb_carve(clone, off, gfp) < 0 ||
6780 pskb_trim(clone, to_copy)) {
6786 EXPORT_SYMBOL(pskb_extract);
6789 * skb_condense - try to get rid of fragments/frag_list if possible
6792 * Can be used to save memory before skb is added to a busy queue.
6793 * If packet has bytes in frags and enough tail room in skb->head,
6794 * pull all of them, so that we can free the frags right now and adjust
6797 * We do not reallocate skb->head thus can not fail.
6798 * Caller must re-evaluate skb->truesize if needed.
6800 void skb_condense(struct sk_buff *skb)
6802 if (skb->data_len) {
6803 if (skb->data_len > skb->end - skb->tail ||
6807 /* Nice, we can free page frag(s) right now */
6808 __pskb_pull_tail(skb, skb->data_len);
6810 /* At this point, skb->truesize might be over estimated,
6811 * because skb had a fragment, and fragments do not tell
6813 * When we pulled its content into skb->head, fragment
6814 * was freed, but __pskb_pull_tail() could not possibly
6815 * adjust skb->truesize, not knowing the frag truesize.
6817 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6819 EXPORT_SYMBOL(skb_condense);
6821 #ifdef CONFIG_SKB_EXTENSIONS
6822 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6824 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6828 * __skb_ext_alloc - allocate a new skb extensions storage
6830 * @flags: See kmalloc().
6832 * Returns the newly allocated pointer. The pointer can later attached to a
6833 * skb via __skb_ext_set().
6834 * Note: caller must handle the skb_ext as an opaque data.
6836 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6838 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6841 memset(new->offset, 0, sizeof(new->offset));
6842 refcount_set(&new->refcnt, 1);
6848 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6849 unsigned int old_active)
6851 struct skb_ext *new;
6853 if (refcount_read(&old->refcnt) == 1)
6856 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6860 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6861 refcount_set(&new->refcnt, 1);
6864 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6865 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6868 for (i = 0; i < sp->len; i++)
6869 xfrm_state_hold(sp->xvec[i]);
6872 #ifdef CONFIG_MCTP_FLOWS
6873 if (old_active & (1 << SKB_EXT_MCTP)) {
6874 struct mctp_flow *flow = skb_ext_get_ptr(old, SKB_EXT_MCTP);
6877 refcount_inc(&flow->key->refs);
6885 * __skb_ext_set - attach the specified extension storage to this skb
6888 * @ext: extension storage previously allocated via __skb_ext_alloc()
6890 * Existing extensions, if any, are cleared.
6892 * Returns the pointer to the extension.
6894 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6895 struct skb_ext *ext)
6897 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6900 newlen = newoff + skb_ext_type_len[id];
6901 ext->chunks = newlen;
6902 ext->offset[id] = newoff;
6903 skb->extensions = ext;
6904 skb->active_extensions = 1 << id;
6905 return skb_ext_get_ptr(ext, id);
6909 * skb_ext_add - allocate space for given extension, COW if needed
6911 * @id: extension to allocate space for
6913 * Allocates enough space for the given extension.
6914 * If the extension is already present, a pointer to that extension
6917 * If the skb was cloned, COW applies and the returned memory can be
6918 * modified without changing the extension space of clones buffers.
6920 * Returns pointer to the extension or NULL on allocation failure.
6922 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6924 struct skb_ext *new, *old = NULL;
6925 unsigned int newlen, newoff;
6927 if (skb->active_extensions) {
6928 old = skb->extensions;
6930 new = skb_ext_maybe_cow(old, skb->active_extensions);
6934 if (__skb_ext_exist(new, id))
6937 newoff = new->chunks;
6939 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6941 new = __skb_ext_alloc(GFP_ATOMIC);
6946 newlen = newoff + skb_ext_type_len[id];
6947 new->chunks = newlen;
6948 new->offset[id] = newoff;
6951 skb->extensions = new;
6952 skb->active_extensions |= 1 << id;
6953 return skb_ext_get_ptr(new, id);
6955 EXPORT_SYMBOL(skb_ext_add);
6958 static void skb_ext_put_sp(struct sec_path *sp)
6962 for (i = 0; i < sp->len; i++)
6963 xfrm_state_put(sp->xvec[i]);
6967 #ifdef CONFIG_MCTP_FLOWS
6968 static void skb_ext_put_mctp(struct mctp_flow *flow)
6971 mctp_key_unref(flow->key);
6975 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6977 struct skb_ext *ext = skb->extensions;
6979 skb->active_extensions &= ~(1 << id);
6980 if (skb->active_extensions == 0) {
6981 skb->extensions = NULL;
6984 } else if (id == SKB_EXT_SEC_PATH &&
6985 refcount_read(&ext->refcnt) == 1) {
6986 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6993 EXPORT_SYMBOL(__skb_ext_del);
6995 void __skb_ext_put(struct skb_ext *ext)
6997 /* If this is last clone, nothing can increment
6998 * it after check passes. Avoids one atomic op.
7000 if (refcount_read(&ext->refcnt) == 1)
7003 if (!refcount_dec_and_test(&ext->refcnt))
7007 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
7008 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
7010 #ifdef CONFIG_MCTP_FLOWS
7011 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
7012 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
7015 kmem_cache_free(skbuff_ext_cache, ext);
7017 EXPORT_SYMBOL(__skb_ext_put);
7018 #endif /* CONFIG_SKB_EXTENSIONS */
7020 static void kfree_skb_napi_cache(struct sk_buff *skb)
7022 /* if SKB is a clone, don't handle this case */
7023 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
7029 __napi_kfree_skb(skb, SKB_CONSUMED);
7034 * skb_attempt_defer_free - queue skb for remote freeing
7037 * Put @skb in a per-cpu list, using the cpu which
7038 * allocated the skb/pages to reduce false sharing
7039 * and memory zone spinlock contention.
7041 void skb_attempt_defer_free(struct sk_buff *skb)
7043 int cpu = skb->alloc_cpu;
7044 struct softnet_data *sd;
7045 unsigned int defer_max;
7048 if (cpu == raw_smp_processor_id() ||
7049 WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
7051 nodefer: kfree_skb_napi_cache(skb);
7055 DEBUG_NET_WARN_ON_ONCE(skb_dst(skb));
7056 DEBUG_NET_WARN_ON_ONCE(skb->destructor);
7058 sd = &per_cpu(softnet_data, cpu);
7059 defer_max = READ_ONCE(net_hotdata.sysctl_skb_defer_max);
7060 if (READ_ONCE(sd->defer_count) >= defer_max)
7063 spin_lock_bh(&sd->defer_lock);
7064 /* Send an IPI every time queue reaches half capacity. */
7065 kick = sd->defer_count == (defer_max >> 1);
7066 /* Paired with the READ_ONCE() few lines above */
7067 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
7069 skb->next = sd->defer_list;
7070 /* Paired with READ_ONCE() in skb_defer_free_flush() */
7071 WRITE_ONCE(sd->defer_list, skb);
7072 spin_unlock_bh(&sd->defer_lock);
7074 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
7075 * if we are unlucky enough (this seems very unlikely).
7078 kick_defer_list_purge(sd, cpu);
7081 static void skb_splice_csum_page(struct sk_buff *skb, struct page *page,
7082 size_t offset, size_t len)
7087 kaddr = kmap_local_page(page);
7088 csum = csum_partial(kaddr + offset, len, 0);
7089 kunmap_local(kaddr);
7090 skb->csum = csum_block_add(skb->csum, csum, skb->len);
7094 * skb_splice_from_iter - Splice (or copy) pages to skbuff
7095 * @skb: The buffer to add pages to
7096 * @iter: Iterator representing the pages to be added
7097 * @maxsize: Maximum amount of pages to be added
7098 * @gfp: Allocation flags
7100 * This is a common helper function for supporting MSG_SPLICE_PAGES. It
7101 * extracts pages from an iterator and adds them to the socket buffer if
7102 * possible, copying them to fragments if not possible (such as if they're slab
7105 * Returns the amount of data spliced/copied or -EMSGSIZE if there's
7106 * insufficient space in the buffer to transfer anything.
7108 ssize_t skb_splice_from_iter(struct sk_buff *skb, struct iov_iter *iter,
7109 ssize_t maxsize, gfp_t gfp)
7111 size_t frag_limit = READ_ONCE(net_hotdata.sysctl_max_skb_frags);
7112 struct page *pages[8], **ppages = pages;
7113 ssize_t spliced = 0, ret = 0;
7116 while (iter->count > 0) {
7117 ssize_t space, nr, len;
7121 space = frag_limit - skb_shinfo(skb)->nr_frags;
7125 /* We might be able to coalesce without increasing nr_frags */
7126 nr = clamp_t(size_t, space, 1, ARRAY_SIZE(pages));
7128 len = iov_iter_extract_pages(iter, &ppages, maxsize, nr, 0, &off);
7136 struct page *page = pages[i++];
7137 size_t part = min_t(size_t, PAGE_SIZE - off, len);
7140 if (WARN_ON_ONCE(!sendpage_ok(page)))
7143 ret = skb_append_pagefrags(skb, page, off, part,
7146 iov_iter_revert(iter, len);
7150 if (skb->ip_summed == CHECKSUM_NONE)
7151 skb_splice_csum_page(skb, page, off, part);
7164 skb_len_add(skb, spliced);
7165 return spliced ?: ret;
7167 EXPORT_SYMBOL(skb_splice_from_iter);
7169 static __always_inline
7170 size_t memcpy_from_iter_csum(void *iter_from, size_t progress,
7171 size_t len, void *to, void *priv2)
7173 __wsum *csum = priv2;
7174 __wsum next = csum_partial_copy_nocheck(iter_from, to + progress, len);
7176 *csum = csum_block_add(*csum, next, progress);
7180 static __always_inline
7181 size_t copy_from_user_iter_csum(void __user *iter_from, size_t progress,
7182 size_t len, void *to, void *priv2)
7184 __wsum next, *csum = priv2;
7186 next = csum_and_copy_from_user(iter_from, to + progress, len);
7187 *csum = csum_block_add(*csum, next, progress);
7188 return next ? 0 : len;
7191 bool csum_and_copy_from_iter_full(void *addr, size_t bytes,
7192 __wsum *csum, struct iov_iter *i)
7196 if (WARN_ON_ONCE(!i->data_source))
7198 copied = iterate_and_advance2(i, bytes, addr, csum,
7199 copy_from_user_iter_csum,
7200 memcpy_from_iter_csum);
7201 if (likely(copied == bytes))
7203 iov_iter_revert(i, copied);
7206 EXPORT_SYMBOL(csum_and_copy_from_iter_full);