1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Routines having to do with the 'struct sk_buff' memory handlers.
5 * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
6 * Florian La Roche <rzsfl@rz.uni-sb.de>
9 * Alan Cox : Fixed the worst of the load
11 * Dave Platt : Interrupt stacking fix.
12 * Richard Kooijman : Timestamp fixes.
13 * Alan Cox : Changed buffer format.
14 * Alan Cox : destructor hook for AF_UNIX etc.
15 * Linus Torvalds : Better skb_clone.
16 * Alan Cox : Added skb_copy.
17 * Alan Cox : Added all the changed routines Linus
18 * only put in the headers
19 * Ray VanTassle : Fixed --skb->lock in free
20 * Alan Cox : skb_copy copy arp field
21 * Andi Kleen : slabified it.
22 * Robert Olsson : Removed skb_head_pool
25 * The __skb_ routines should be called with interrupts
26 * disabled, or you better be *real* sure that the operation is atomic
27 * with respect to whatever list is being frobbed (e.g. via lock_sock()
28 * or via disabling bottom half handlers, etc).
32 * The functions in this file will not compile correctly with gcc 2.4.x
35 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/kernel.h>
41 #include <linux/interrupt.h>
43 #include <linux/inet.h>
44 #include <linux/slab.h>
45 #include <linux/tcp.h>
46 #include <linux/udp.h>
47 #include <linux/sctp.h>
48 #include <linux/netdevice.h>
49 #ifdef CONFIG_NET_CLS_ACT
50 #include <net/pkt_sched.h>
52 #include <linux/string.h>
53 #include <linux/skbuff.h>
54 #include <linux/splice.h>
55 #include <linux/cache.h>
56 #include <linux/rtnetlink.h>
57 #include <linux/init.h>
58 #include <linux/scatterlist.h>
59 #include <linux/errqueue.h>
60 #include <linux/prefetch.h>
61 #include <linux/bitfield.h>
62 #include <linux/if_vlan.h>
63 #include <linux/mpls.h>
64 #include <linux/kcov.h>
66 #include <net/protocol.h>
69 #include <net/checksum.h>
70 #include <net/ip6_checksum.h>
73 #include <net/mptcp.h>
75 #include <net/page_pool.h>
76 #include <net/dropreason.h>
78 #include <linux/uaccess.h>
79 #include <trace/events/skb.h>
80 #include <linux/highmem.h>
81 #include <linux/capability.h>
82 #include <linux/user_namespace.h>
83 #include <linux/indirect_call_wrapper.h>
84 #include <linux/textsearch.h>
87 #include "sock_destructor.h"
89 struct kmem_cache *skbuff_cache __ro_after_init;
90 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
91 #ifdef CONFIG_SKB_EXTENSIONS
92 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
96 static struct kmem_cache *skb_small_head_cache __ro_after_init;
98 #define SKB_SMALL_HEAD_SIZE SKB_HEAD_ALIGN(MAX_TCP_HEADER)
100 /* We want SKB_SMALL_HEAD_CACHE_SIZE to not be a power of two.
101 * This should ensure that SKB_SMALL_HEAD_HEADROOM is a unique
102 * size, and we can differentiate heads from skb_small_head_cache
103 * vs system slabs by looking at their size (skb_end_offset()).
105 #define SKB_SMALL_HEAD_CACHE_SIZE \
106 (is_power_of_2(SKB_SMALL_HEAD_SIZE) ? \
107 (SKB_SMALL_HEAD_SIZE + L1_CACHE_BYTES) : \
110 #define SKB_SMALL_HEAD_HEADROOM \
111 SKB_WITH_OVERHEAD(SKB_SMALL_HEAD_CACHE_SIZE)
113 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
114 EXPORT_SYMBOL(sysctl_max_skb_frags);
117 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
118 static const char * const drop_reasons[] = {
119 [SKB_CONSUMED] = "CONSUMED",
120 DEFINE_DROP_REASON(FN, FN)
123 static const struct drop_reason_list drop_reasons_core = {
124 .reasons = drop_reasons,
125 .n_reasons = ARRAY_SIZE(drop_reasons),
128 const struct drop_reason_list __rcu *
129 drop_reasons_by_subsys[SKB_DROP_REASON_SUBSYS_NUM] = {
130 [SKB_DROP_REASON_SUBSYS_CORE] = RCU_INITIALIZER(&drop_reasons_core),
132 EXPORT_SYMBOL(drop_reasons_by_subsys);
135 * drop_reasons_register_subsys - register another drop reason subsystem
136 * @subsys: the subsystem to register, must not be the core
137 * @list: the list of drop reasons within the subsystem, must point to
138 * a statically initialized list
140 void drop_reasons_register_subsys(enum skb_drop_reason_subsys subsys,
141 const struct drop_reason_list *list)
143 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
144 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
145 "invalid subsystem %d\n", subsys))
148 /* must point to statically allocated memory, so INIT is OK */
149 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], list);
151 EXPORT_SYMBOL_GPL(drop_reasons_register_subsys);
154 * drop_reasons_unregister_subsys - unregister a drop reason subsystem
155 * @subsys: the subsystem to remove, must not be the core
157 * Note: This will synchronize_rcu() to ensure no users when it returns.
159 void drop_reasons_unregister_subsys(enum skb_drop_reason_subsys subsys)
161 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
162 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
163 "invalid subsystem %d\n", subsys))
166 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], NULL);
170 EXPORT_SYMBOL_GPL(drop_reasons_unregister_subsys);
173 * skb_panic - private function for out-of-line support
177 * @msg: skb_over_panic or skb_under_panic
179 * Out-of-line support for skb_put() and skb_push().
180 * Called via the wrapper skb_over_panic() or skb_under_panic().
181 * Keep out of line to prevent kernel bloat.
182 * __builtin_return_address is not used because it is not always reliable.
184 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
187 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
188 msg, addr, skb->len, sz, skb->head, skb->data,
189 (unsigned long)skb->tail, (unsigned long)skb->end,
190 skb->dev ? skb->dev->name : "<NULL>");
194 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
196 skb_panic(skb, sz, addr, __func__);
199 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
201 skb_panic(skb, sz, addr, __func__);
204 #define NAPI_SKB_CACHE_SIZE 64
205 #define NAPI_SKB_CACHE_BULK 16
206 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
208 #if PAGE_SIZE == SZ_4K
210 #define NAPI_HAS_SMALL_PAGE_FRAG 1
211 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) ((nc).pfmemalloc)
213 /* specialized page frag allocator using a single order 0 page
214 * and slicing it into 1K sized fragment. Constrained to systems
215 * with a very limited amount of 1K fragments fitting a single
216 * page - to avoid excessive truesize underestimation
219 struct page_frag_1k {
225 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
230 offset = nc->offset - SZ_1K;
231 if (likely(offset >= 0))
234 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
238 nc->va = page_address(page);
239 nc->pfmemalloc = page_is_pfmemalloc(page);
240 offset = PAGE_SIZE - SZ_1K;
241 page_ref_add(page, offset / SZ_1K);
245 return nc->va + offset;
249 /* the small page is actually unused in this build; add dummy helpers
250 * to please the compiler and avoid later preprocessor's conditionals
252 #define NAPI_HAS_SMALL_PAGE_FRAG 0
253 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) false
255 struct page_frag_1k {
258 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
265 struct napi_alloc_cache {
266 struct page_frag_cache page;
267 struct page_frag_1k page_small;
268 unsigned int skb_count;
269 void *skb_cache[NAPI_SKB_CACHE_SIZE];
272 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
273 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
275 /* Double check that napi_get_frags() allocates skbs with
276 * skb->head being backed by slab, not a page fragment.
277 * This is to make sure bug fixed in 3226b158e67c
278 * ("net: avoid 32 x truesize under-estimation for tiny skbs")
279 * does not accidentally come back.
281 void napi_get_frags_check(struct napi_struct *napi)
286 skb = napi_get_frags(napi);
287 WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
288 napi_free_frags(napi);
292 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
294 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
296 fragsz = SKB_DATA_ALIGN(fragsz);
298 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
300 EXPORT_SYMBOL(__napi_alloc_frag_align);
302 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
306 fragsz = SKB_DATA_ALIGN(fragsz);
307 if (in_hardirq() || irqs_disabled()) {
308 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
310 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
312 struct napi_alloc_cache *nc;
315 nc = this_cpu_ptr(&napi_alloc_cache);
316 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
321 EXPORT_SYMBOL(__netdev_alloc_frag_align);
323 static struct sk_buff *napi_skb_cache_get(void)
325 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
328 if (unlikely(!nc->skb_count)) {
329 nc->skb_count = kmem_cache_alloc_bulk(skbuff_cache,
333 if (unlikely(!nc->skb_count))
337 skb = nc->skb_cache[--nc->skb_count];
338 kasan_unpoison_object_data(skbuff_cache, skb);
343 static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
346 struct skb_shared_info *shinfo;
348 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
350 /* Assumes caller memset cleared SKB */
351 skb->truesize = SKB_TRUESIZE(size);
352 refcount_set(&skb->users, 1);
355 skb_reset_tail_pointer(skb);
356 skb_set_end_offset(skb, size);
357 skb->mac_header = (typeof(skb->mac_header))~0U;
358 skb->transport_header = (typeof(skb->transport_header))~0U;
359 skb->alloc_cpu = raw_smp_processor_id();
360 /* make sure we initialize shinfo sequentially */
361 shinfo = skb_shinfo(skb);
362 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
363 atomic_set(&shinfo->dataref, 1);
365 skb_set_kcov_handle(skb, kcov_common_handle());
368 static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
373 /* Must find the allocation size (and grow it to match). */
375 /* krealloc() will immediately return "data" when
376 * "ksize(data)" is requested: it is the existing upper
377 * bounds. As a result, GFP_ATOMIC will be ignored. Note
378 * that this "new" pointer needs to be passed back to the
379 * caller for use so the __alloc_size hinting will be
382 resized = krealloc(data, *size, GFP_ATOMIC);
383 WARN_ON_ONCE(resized != data);
387 /* build_skb() variant which can operate on slab buffers.
388 * Note that this should be used sparingly as slab buffers
389 * cannot be combined efficiently by GRO!
391 struct sk_buff *slab_build_skb(void *data)
396 skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
400 memset(skb, 0, offsetof(struct sk_buff, tail));
401 data = __slab_build_skb(skb, data, &size);
402 __finalize_skb_around(skb, data, size);
406 EXPORT_SYMBOL(slab_build_skb);
408 /* Caller must provide SKB that is memset cleared */
409 static void __build_skb_around(struct sk_buff *skb, void *data,
410 unsigned int frag_size)
412 unsigned int size = frag_size;
414 /* frag_size == 0 is considered deprecated now. Callers
415 * using slab buffer should use slab_build_skb() instead.
417 if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
418 data = __slab_build_skb(skb, data, &size);
420 __finalize_skb_around(skb, data, size);
424 * __build_skb - build a network buffer
425 * @data: data buffer provided by caller
426 * @frag_size: size of data (must not be 0)
428 * Allocate a new &sk_buff. Caller provides space holding head and
429 * skb_shared_info. @data must have been allocated from the page
430 * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
431 * allocation is deprecated, and callers should use slab_build_skb()
433 * The return is the new skb buffer.
434 * On a failure the return is %NULL, and @data is not freed.
436 * Before IO, driver allocates only data buffer where NIC put incoming frame
437 * Driver should add room at head (NET_SKB_PAD) and
438 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
439 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
440 * before giving packet to stack.
441 * RX rings only contains data buffers, not full skbs.
443 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
447 skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
451 memset(skb, 0, offsetof(struct sk_buff, tail));
452 __build_skb_around(skb, data, frag_size);
457 /* build_skb() is wrapper over __build_skb(), that specifically
458 * takes care of skb->head and skb->pfmemalloc
460 struct sk_buff *build_skb(void *data, unsigned int frag_size)
462 struct sk_buff *skb = __build_skb(data, frag_size);
464 if (likely(skb && frag_size)) {
466 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
470 EXPORT_SYMBOL(build_skb);
473 * build_skb_around - build a network buffer around provided skb
474 * @skb: sk_buff provide by caller, must be memset cleared
475 * @data: data buffer provided by caller
476 * @frag_size: size of data
478 struct sk_buff *build_skb_around(struct sk_buff *skb,
479 void *data, unsigned int frag_size)
484 __build_skb_around(skb, data, frag_size);
488 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
492 EXPORT_SYMBOL(build_skb_around);
495 * __napi_build_skb - build a network buffer
496 * @data: data buffer provided by caller
497 * @frag_size: size of data
499 * Version of __build_skb() that uses NAPI percpu caches to obtain
500 * skbuff_head instead of inplace allocation.
502 * Returns a new &sk_buff on success, %NULL on allocation failure.
504 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
508 skb = napi_skb_cache_get();
512 memset(skb, 0, offsetof(struct sk_buff, tail));
513 __build_skb_around(skb, data, frag_size);
519 * napi_build_skb - build a network buffer
520 * @data: data buffer provided by caller
521 * @frag_size: size of data
523 * Version of __napi_build_skb() that takes care of skb->head_frag
524 * and skb->pfmemalloc when the data is a page or page fragment.
526 * Returns a new &sk_buff on success, %NULL on allocation failure.
528 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
530 struct sk_buff *skb = __napi_build_skb(data, frag_size);
532 if (likely(skb) && frag_size) {
534 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
539 EXPORT_SYMBOL(napi_build_skb);
542 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
543 * the caller if emergency pfmemalloc reserves are being used. If it is and
544 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
545 * may be used. Otherwise, the packet data may be discarded until enough
548 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
551 bool ret_pfmemalloc = false;
552 unsigned int obj_size;
555 obj_size = SKB_HEAD_ALIGN(*size);
556 if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
557 !(flags & KMALLOC_NOT_NORMAL_BITS)) {
558 obj = kmem_cache_alloc_node(skb_small_head_cache,
559 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
561 *size = SKB_SMALL_HEAD_CACHE_SIZE;
562 if (obj || !(gfp_pfmemalloc_allowed(flags)))
564 /* Try again but now we are using pfmemalloc reserves */
565 ret_pfmemalloc = true;
566 obj = kmem_cache_alloc_node(skb_small_head_cache, flags, node);
569 *size = obj_size = kmalloc_size_roundup(obj_size);
571 * Try a regular allocation, when that fails and we're not entitled
572 * to the reserves, fail.
574 obj = kmalloc_node_track_caller(obj_size,
575 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
577 if (obj || !(gfp_pfmemalloc_allowed(flags)))
580 /* Try again but now we are using pfmemalloc reserves */
581 ret_pfmemalloc = true;
582 obj = kmalloc_node_track_caller(obj_size, flags, node);
586 *pfmemalloc = ret_pfmemalloc;
591 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
592 * 'private' fields and also do memory statistics to find all the
598 * __alloc_skb - allocate a network buffer
599 * @size: size to allocate
600 * @gfp_mask: allocation mask
601 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
602 * instead of head cache and allocate a cloned (child) skb.
603 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
604 * allocations in case the data is required for writeback
605 * @node: numa node to allocate memory on
607 * Allocate a new &sk_buff. The returned buffer has no headroom and a
608 * tail room of at least size bytes. The object has a reference count
609 * of one. The return is the buffer. On a failure the return is %NULL.
611 * Buffers may only be allocated from interrupts using a @gfp_mask of
614 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
617 struct kmem_cache *cache;
622 cache = (flags & SKB_ALLOC_FCLONE)
623 ? skbuff_fclone_cache : skbuff_cache;
625 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
626 gfp_mask |= __GFP_MEMALLOC;
629 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
630 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
631 skb = napi_skb_cache_get();
633 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
638 /* We do our best to align skb_shared_info on a separate cache
639 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
640 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
641 * Both skb->head and skb_shared_info are cache line aligned.
643 data = kmalloc_reserve(&size, gfp_mask, node, &pfmemalloc);
646 /* kmalloc_size_roundup() might give us more room than requested.
647 * Put skb_shared_info exactly at the end of allocated zone,
648 * to allow max possible filling before reallocation.
650 prefetchw(data + SKB_WITH_OVERHEAD(size));
653 * Only clear those fields we need to clear, not those that we will
654 * actually initialise below. Hence, don't put any more fields after
655 * the tail pointer in struct sk_buff!
657 memset(skb, 0, offsetof(struct sk_buff, tail));
658 __build_skb_around(skb, data, size);
659 skb->pfmemalloc = pfmemalloc;
661 if (flags & SKB_ALLOC_FCLONE) {
662 struct sk_buff_fclones *fclones;
664 fclones = container_of(skb, struct sk_buff_fclones, skb1);
666 skb->fclone = SKB_FCLONE_ORIG;
667 refcount_set(&fclones->fclone_ref, 1);
673 kmem_cache_free(cache, skb);
676 EXPORT_SYMBOL(__alloc_skb);
679 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
680 * @dev: network device to receive on
681 * @len: length to allocate
682 * @gfp_mask: get_free_pages mask, passed to alloc_skb
684 * Allocate a new &sk_buff and assign it a usage count of one. The
685 * buffer has NET_SKB_PAD headroom built in. Users should allocate
686 * the headroom they think they need without accounting for the
687 * built in space. The built in space is used for optimisations.
689 * %NULL is returned if there is no free memory.
691 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
694 struct page_frag_cache *nc;
701 /* If requested length is either too small or too big,
702 * we use kmalloc() for skb->head allocation.
704 if (len <= SKB_WITH_OVERHEAD(1024) ||
705 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
706 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
707 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
713 len = SKB_HEAD_ALIGN(len);
715 if (sk_memalloc_socks())
716 gfp_mask |= __GFP_MEMALLOC;
718 if (in_hardirq() || irqs_disabled()) {
719 nc = this_cpu_ptr(&netdev_alloc_cache);
720 data = page_frag_alloc(nc, len, gfp_mask);
721 pfmemalloc = nc->pfmemalloc;
724 nc = this_cpu_ptr(&napi_alloc_cache.page);
725 data = page_frag_alloc(nc, len, gfp_mask);
726 pfmemalloc = nc->pfmemalloc;
733 skb = __build_skb(data, len);
734 if (unlikely(!skb)) {
744 skb_reserve(skb, NET_SKB_PAD);
750 EXPORT_SYMBOL(__netdev_alloc_skb);
753 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
754 * @napi: napi instance this buffer was allocated for
755 * @len: length to allocate
756 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
758 * Allocate a new sk_buff for use in NAPI receive. This buffer will
759 * attempt to allocate the head from a special reserved region used
760 * only for NAPI Rx allocation. By doing this we can save several
761 * CPU cycles by avoiding having to disable and re-enable IRQs.
763 * %NULL is returned if there is no free memory.
765 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
768 struct napi_alloc_cache *nc;
773 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
774 len += NET_SKB_PAD + NET_IP_ALIGN;
776 /* If requested length is either too small or too big,
777 * we use kmalloc() for skb->head allocation.
778 * When the small frag allocator is available, prefer it over kmalloc
779 * for small fragments
781 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
782 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
783 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
784 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
791 nc = this_cpu_ptr(&napi_alloc_cache);
793 if (sk_memalloc_socks())
794 gfp_mask |= __GFP_MEMALLOC;
796 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
797 /* we are artificially inflating the allocation size, but
798 * that is not as bad as it may look like, as:
799 * - 'len' less than GRO_MAX_HEAD makes little sense
800 * - On most systems, larger 'len' values lead to fragment
801 * size above 512 bytes
802 * - kmalloc would use the kmalloc-1k slab for such values
803 * - Builds with smaller GRO_MAX_HEAD will very likely do
804 * little networking, as that implies no WiFi and no
805 * tunnels support, and 32 bits arches.
809 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
810 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
812 len = SKB_HEAD_ALIGN(len);
814 data = page_frag_alloc(&nc->page, len, gfp_mask);
815 pfmemalloc = nc->page.pfmemalloc;
821 skb = __napi_build_skb(data, len);
822 if (unlikely(!skb)) {
832 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
833 skb->dev = napi->dev;
838 EXPORT_SYMBOL(__napi_alloc_skb);
840 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
841 int size, unsigned int truesize)
843 skb_fill_page_desc(skb, i, page, off, size);
845 skb->data_len += size;
846 skb->truesize += truesize;
848 EXPORT_SYMBOL(skb_add_rx_frag);
850 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
851 unsigned int truesize)
853 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
855 skb_frag_size_add(frag, size);
857 skb->data_len += size;
858 skb->truesize += truesize;
860 EXPORT_SYMBOL(skb_coalesce_rx_frag);
862 static void skb_drop_list(struct sk_buff **listp)
864 kfree_skb_list(*listp);
868 static inline void skb_drop_fraglist(struct sk_buff *skb)
870 skb_drop_list(&skb_shinfo(skb)->frag_list);
873 static void skb_clone_fraglist(struct sk_buff *skb)
875 struct sk_buff *list;
877 skb_walk_frags(skb, list)
881 static bool skb_pp_recycle(struct sk_buff *skb, void *data, bool napi_safe)
883 if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
885 return page_pool_return_skb_page(virt_to_page(data), napi_safe);
888 static void skb_kfree_head(void *head, unsigned int end_offset)
890 if (end_offset == SKB_SMALL_HEAD_HEADROOM)
891 kmem_cache_free(skb_small_head_cache, head);
896 static void skb_free_head(struct sk_buff *skb, bool napi_safe)
898 unsigned char *head = skb->head;
900 if (skb->head_frag) {
901 if (skb_pp_recycle(skb, head, napi_safe))
905 skb_kfree_head(head, skb_end_offset(skb));
909 static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason,
912 struct skb_shared_info *shinfo = skb_shinfo(skb);
916 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
920 if (skb_zcopy(skb)) {
921 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
923 skb_zcopy_clear(skb, true);
928 for (i = 0; i < shinfo->nr_frags; i++)
929 napi_frag_unref(&shinfo->frags[i], skb->pp_recycle, napi_safe);
932 if (shinfo->frag_list)
933 kfree_skb_list_reason(shinfo->frag_list, reason);
935 skb_free_head(skb, napi_safe);
937 /* When we clone an SKB we copy the reycling bit. The pp_recycle
938 * bit is only set on the head though, so in order to avoid races
939 * while trying to recycle fragments on __skb_frag_unref() we need
940 * to make one SKB responsible for triggering the recycle path.
941 * So disable the recycling bit if an SKB is cloned and we have
942 * additional references to the fragmented part of the SKB.
943 * Eventually the last SKB will have the recycling bit set and it's
944 * dataref set to 0, which will trigger the recycling
950 * Free an skbuff by memory without cleaning the state.
952 static void kfree_skbmem(struct sk_buff *skb)
954 struct sk_buff_fclones *fclones;
956 switch (skb->fclone) {
957 case SKB_FCLONE_UNAVAILABLE:
958 kmem_cache_free(skbuff_cache, skb);
961 case SKB_FCLONE_ORIG:
962 fclones = container_of(skb, struct sk_buff_fclones, skb1);
964 /* We usually free the clone (TX completion) before original skb
965 * This test would have no chance to be true for the clone,
966 * while here, branch prediction will be good.
968 if (refcount_read(&fclones->fclone_ref) == 1)
972 default: /* SKB_FCLONE_CLONE */
973 fclones = container_of(skb, struct sk_buff_fclones, skb2);
976 if (!refcount_dec_and_test(&fclones->fclone_ref))
979 kmem_cache_free(skbuff_fclone_cache, fclones);
982 void skb_release_head_state(struct sk_buff *skb)
985 if (skb->destructor) {
986 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
987 skb->destructor(skb);
989 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
990 nf_conntrack_put(skb_nfct(skb));
995 /* Free everything but the sk_buff shell. */
996 static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason,
999 skb_release_head_state(skb);
1000 if (likely(skb->head))
1001 skb_release_data(skb, reason, napi_safe);
1005 * __kfree_skb - private function
1008 * Free an sk_buff. Release anything attached to the buffer.
1009 * Clean the state. This is an internal helper function. Users should
1010 * always call kfree_skb
1013 void __kfree_skb(struct sk_buff *skb)
1015 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED, false);
1018 EXPORT_SYMBOL(__kfree_skb);
1020 static __always_inline
1021 bool __kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1023 if (unlikely(!skb_unref(skb)))
1026 DEBUG_NET_WARN_ON_ONCE(reason == SKB_NOT_DROPPED_YET ||
1027 u32_get_bits(reason,
1028 SKB_DROP_REASON_SUBSYS_MASK) >=
1029 SKB_DROP_REASON_SUBSYS_NUM);
1031 if (reason == SKB_CONSUMED)
1032 trace_consume_skb(skb, __builtin_return_address(0));
1034 trace_kfree_skb(skb, __builtin_return_address(0), reason);
1039 * kfree_skb_reason - free an sk_buff with special reason
1040 * @skb: buffer to free
1041 * @reason: reason why this skb is dropped
1043 * Drop a reference to the buffer and free it if the usage count has
1044 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
1048 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1050 if (__kfree_skb_reason(skb, reason))
1053 EXPORT_SYMBOL(kfree_skb_reason);
1055 #define KFREE_SKB_BULK_SIZE 16
1057 struct skb_free_array {
1058 unsigned int skb_count;
1059 void *skb_array[KFREE_SKB_BULK_SIZE];
1062 static void kfree_skb_add_bulk(struct sk_buff *skb,
1063 struct skb_free_array *sa,
1064 enum skb_drop_reason reason)
1066 /* if SKB is a clone, don't handle this case */
1067 if (unlikely(skb->fclone != SKB_FCLONE_UNAVAILABLE)) {
1072 skb_release_all(skb, reason, false);
1073 sa->skb_array[sa->skb_count++] = skb;
1075 if (unlikely(sa->skb_count == KFREE_SKB_BULK_SIZE)) {
1076 kmem_cache_free_bulk(skbuff_cache, KFREE_SKB_BULK_SIZE,
1083 kfree_skb_list_reason(struct sk_buff *segs, enum skb_drop_reason reason)
1085 struct skb_free_array sa;
1090 struct sk_buff *next = segs->next;
1092 if (__kfree_skb_reason(segs, reason)) {
1093 skb_poison_list(segs);
1094 kfree_skb_add_bulk(segs, &sa, reason);
1101 kmem_cache_free_bulk(skbuff_cache, sa.skb_count, sa.skb_array);
1103 EXPORT_SYMBOL(kfree_skb_list_reason);
1105 /* Dump skb information and contents.
1107 * Must only be called from net_ratelimit()-ed paths.
1109 * Dumps whole packets if full_pkt, only headers otherwise.
1111 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
1113 struct skb_shared_info *sh = skb_shinfo(skb);
1114 struct net_device *dev = skb->dev;
1115 struct sock *sk = skb->sk;
1116 struct sk_buff *list_skb;
1117 bool has_mac, has_trans;
1118 int headroom, tailroom;
1119 int i, len, seg_len;
1124 len = min_t(int, skb->len, MAX_HEADER + 128);
1126 headroom = skb_headroom(skb);
1127 tailroom = skb_tailroom(skb);
1129 has_mac = skb_mac_header_was_set(skb);
1130 has_trans = skb_transport_header_was_set(skb);
1132 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
1133 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
1134 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
1135 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
1136 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
1137 level, skb->len, headroom, skb_headlen(skb), tailroom,
1138 has_mac ? skb->mac_header : -1,
1139 has_mac ? skb_mac_header_len(skb) : -1,
1140 skb->network_header,
1141 has_trans ? skb_network_header_len(skb) : -1,
1142 has_trans ? skb->transport_header : -1,
1143 sh->tx_flags, sh->nr_frags,
1144 sh->gso_size, sh->gso_type, sh->gso_segs,
1145 skb->csum, skb->ip_summed, skb->csum_complete_sw,
1146 skb->csum_valid, skb->csum_level,
1147 skb->hash, skb->sw_hash, skb->l4_hash,
1148 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
1151 printk("%sdev name=%s feat=%pNF\n",
1152 level, dev->name, &dev->features);
1154 printk("%ssk family=%hu type=%u proto=%u\n",
1155 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
1157 if (full_pkt && headroom)
1158 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
1159 16, 1, skb->head, headroom, false);
1161 seg_len = min_t(int, skb_headlen(skb), len);
1163 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
1164 16, 1, skb->data, seg_len, false);
1167 if (full_pkt && tailroom)
1168 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
1169 16, 1, skb_tail_pointer(skb), tailroom, false);
1171 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
1172 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1173 u32 p_off, p_len, copied;
1177 skb_frag_foreach_page(frag, skb_frag_off(frag),
1178 skb_frag_size(frag), p, p_off, p_len,
1180 seg_len = min_t(int, p_len, len);
1181 vaddr = kmap_atomic(p);
1182 print_hex_dump(level, "skb frag: ",
1184 16, 1, vaddr + p_off, seg_len, false);
1185 kunmap_atomic(vaddr);
1192 if (full_pkt && skb_has_frag_list(skb)) {
1193 printk("skb fraglist:\n");
1194 skb_walk_frags(skb, list_skb)
1195 skb_dump(level, list_skb, true);
1198 EXPORT_SYMBOL(skb_dump);
1201 * skb_tx_error - report an sk_buff xmit error
1202 * @skb: buffer that triggered an error
1204 * Report xmit error if a device callback is tracking this skb.
1205 * skb must be freed afterwards.
1207 void skb_tx_error(struct sk_buff *skb)
1210 skb_zcopy_downgrade_managed(skb);
1211 skb_zcopy_clear(skb, true);
1214 EXPORT_SYMBOL(skb_tx_error);
1216 #ifdef CONFIG_TRACEPOINTS
1218 * consume_skb - free an skbuff
1219 * @skb: buffer to free
1221 * Drop a ref to the buffer and free it if the usage count has hit zero
1222 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1223 * is being dropped after a failure and notes that
1225 void consume_skb(struct sk_buff *skb)
1227 if (!skb_unref(skb))
1230 trace_consume_skb(skb, __builtin_return_address(0));
1233 EXPORT_SYMBOL(consume_skb);
1237 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1238 * @skb: buffer to free
1240 * Alike consume_skb(), but this variant assumes that this is the last
1241 * skb reference and all the head states have been already dropped
1243 void __consume_stateless_skb(struct sk_buff *skb)
1245 trace_consume_skb(skb, __builtin_return_address(0));
1246 skb_release_data(skb, SKB_CONSUMED, false);
1250 static void napi_skb_cache_put(struct sk_buff *skb)
1252 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1255 kasan_poison_object_data(skbuff_cache, skb);
1256 nc->skb_cache[nc->skb_count++] = skb;
1258 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1259 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1260 kasan_unpoison_object_data(skbuff_cache,
1263 kmem_cache_free_bulk(skbuff_cache, NAPI_SKB_CACHE_HALF,
1264 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1265 nc->skb_count = NAPI_SKB_CACHE_HALF;
1269 void __napi_kfree_skb(struct sk_buff *skb, enum skb_drop_reason reason)
1271 skb_release_all(skb, reason, true);
1272 napi_skb_cache_put(skb);
1275 void napi_skb_free_stolen_head(struct sk_buff *skb)
1277 if (unlikely(skb->slow_gro)) {
1284 napi_skb_cache_put(skb);
1287 void napi_consume_skb(struct sk_buff *skb, int budget)
1289 /* Zero budget indicate non-NAPI context called us, like netpoll */
1290 if (unlikely(!budget)) {
1291 dev_consume_skb_any(skb);
1295 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1297 if (!skb_unref(skb))
1300 /* if reaching here SKB is ready to free */
1301 trace_consume_skb(skb, __builtin_return_address(0));
1303 /* if SKB is a clone, don't handle this case */
1304 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1309 skb_release_all(skb, SKB_CONSUMED, !!budget);
1310 napi_skb_cache_put(skb);
1312 EXPORT_SYMBOL(napi_consume_skb);
1314 /* Make sure a field is contained by headers group */
1315 #define CHECK_SKB_FIELD(field) \
1316 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1317 offsetof(struct sk_buff, headers.field)); \
1319 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1321 new->tstamp = old->tstamp;
1322 /* We do not copy old->sk */
1323 new->dev = old->dev;
1324 memcpy(new->cb, old->cb, sizeof(old->cb));
1325 skb_dst_copy(new, old);
1326 __skb_ext_copy(new, old);
1327 __nf_copy(new, old, false);
1329 /* Note : this field could be in the headers group.
1330 * It is not yet because we do not want to have a 16 bit hole
1332 new->queue_mapping = old->queue_mapping;
1334 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1335 CHECK_SKB_FIELD(protocol);
1336 CHECK_SKB_FIELD(csum);
1337 CHECK_SKB_FIELD(hash);
1338 CHECK_SKB_FIELD(priority);
1339 CHECK_SKB_FIELD(skb_iif);
1340 CHECK_SKB_FIELD(vlan_proto);
1341 CHECK_SKB_FIELD(vlan_tci);
1342 CHECK_SKB_FIELD(transport_header);
1343 CHECK_SKB_FIELD(network_header);
1344 CHECK_SKB_FIELD(mac_header);
1345 CHECK_SKB_FIELD(inner_protocol);
1346 CHECK_SKB_FIELD(inner_transport_header);
1347 CHECK_SKB_FIELD(inner_network_header);
1348 CHECK_SKB_FIELD(inner_mac_header);
1349 CHECK_SKB_FIELD(mark);
1350 #ifdef CONFIG_NETWORK_SECMARK
1351 CHECK_SKB_FIELD(secmark);
1353 #ifdef CONFIG_NET_RX_BUSY_POLL
1354 CHECK_SKB_FIELD(napi_id);
1356 CHECK_SKB_FIELD(alloc_cpu);
1358 CHECK_SKB_FIELD(sender_cpu);
1360 #ifdef CONFIG_NET_SCHED
1361 CHECK_SKB_FIELD(tc_index);
1367 * You should not add any new code to this function. Add it to
1368 * __copy_skb_header above instead.
1370 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1372 #define C(x) n->x = skb->x
1374 n->next = n->prev = NULL;
1376 __copy_skb_header(n, skb);
1381 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1387 n->destructor = NULL;
1394 refcount_set(&n->users, 1);
1396 atomic_inc(&(skb_shinfo(skb)->dataref));
1404 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1405 * @first: first sk_buff of the msg
1407 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1411 n = alloc_skb(0, GFP_ATOMIC);
1415 n->len = first->len;
1416 n->data_len = first->len;
1417 n->truesize = first->truesize;
1419 skb_shinfo(n)->frag_list = first;
1421 __copy_skb_header(n, first);
1422 n->destructor = NULL;
1426 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1429 * skb_morph - morph one skb into another
1430 * @dst: the skb to receive the contents
1431 * @src: the skb to supply the contents
1433 * This is identical to skb_clone except that the target skb is
1434 * supplied by the user.
1436 * The target skb is returned upon exit.
1438 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1440 skb_release_all(dst, SKB_CONSUMED, false);
1441 return __skb_clone(dst, src);
1443 EXPORT_SYMBOL_GPL(skb_morph);
1445 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1447 unsigned long max_pg, num_pg, new_pg, old_pg, rlim;
1448 struct user_struct *user;
1450 if (capable(CAP_IPC_LOCK) || !size)
1453 rlim = rlimit(RLIMIT_MEMLOCK);
1454 if (rlim == RLIM_INFINITY)
1457 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1458 max_pg = rlim >> PAGE_SHIFT;
1459 user = mmp->user ? : current_user();
1461 old_pg = atomic_long_read(&user->locked_vm);
1463 new_pg = old_pg + num_pg;
1464 if (new_pg > max_pg)
1466 } while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1469 mmp->user = get_uid(user);
1470 mmp->num_pg = num_pg;
1472 mmp->num_pg += num_pg;
1477 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1479 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1482 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1483 free_uid(mmp->user);
1486 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1488 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1490 struct ubuf_info_msgzc *uarg;
1491 struct sk_buff *skb;
1493 WARN_ON_ONCE(!in_task());
1495 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1499 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1500 uarg = (void *)skb->cb;
1501 uarg->mmp.user = NULL;
1503 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1508 uarg->ubuf.callback = msg_zerocopy_callback;
1509 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1511 uarg->bytelen = size;
1513 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1514 refcount_set(&uarg->ubuf.refcnt, 1);
1520 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1522 return container_of((void *)uarg, struct sk_buff, cb);
1525 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1526 struct ubuf_info *uarg)
1529 struct ubuf_info_msgzc *uarg_zc;
1530 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1533 /* there might be non MSG_ZEROCOPY users */
1534 if (uarg->callback != msg_zerocopy_callback)
1537 /* realloc only when socket is locked (TCP, UDP cork),
1538 * so uarg->len and sk_zckey access is serialized
1540 if (!sock_owned_by_user(sk)) {
1545 uarg_zc = uarg_to_msgzc(uarg);
1546 bytelen = uarg_zc->bytelen + size;
1547 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1548 /* TCP can create new skb to attach new uarg */
1549 if (sk->sk_type == SOCK_STREAM)
1554 next = (u32)atomic_read(&sk->sk_zckey);
1555 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1556 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1559 uarg_zc->bytelen = bytelen;
1560 atomic_set(&sk->sk_zckey, ++next);
1562 /* no extra ref when appending to datagram (MSG_MORE) */
1563 if (sk->sk_type == SOCK_STREAM)
1564 net_zcopy_get(uarg);
1571 return msg_zerocopy_alloc(sk, size);
1573 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1575 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1577 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1581 old_lo = serr->ee.ee_info;
1582 old_hi = serr->ee.ee_data;
1583 sum_len = old_hi - old_lo + 1ULL + len;
1585 if (sum_len >= (1ULL << 32))
1588 if (lo != old_hi + 1)
1591 serr->ee.ee_data += len;
1595 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1597 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1598 struct sock_exterr_skb *serr;
1599 struct sock *sk = skb->sk;
1600 struct sk_buff_head *q;
1601 unsigned long flags;
1606 mm_unaccount_pinned_pages(&uarg->mmp);
1608 /* if !len, there was only 1 call, and it was aborted
1609 * so do not queue a completion notification
1611 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1616 hi = uarg->id + len - 1;
1617 is_zerocopy = uarg->zerocopy;
1619 serr = SKB_EXT_ERR(skb);
1620 memset(serr, 0, sizeof(*serr));
1621 serr->ee.ee_errno = 0;
1622 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1623 serr->ee.ee_data = hi;
1624 serr->ee.ee_info = lo;
1626 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1628 q = &sk->sk_error_queue;
1629 spin_lock_irqsave(&q->lock, flags);
1630 tail = skb_peek_tail(q);
1631 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1632 !skb_zerocopy_notify_extend(tail, lo, len)) {
1633 __skb_queue_tail(q, skb);
1636 spin_unlock_irqrestore(&q->lock, flags);
1638 sk_error_report(sk);
1645 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1648 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1650 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1652 if (refcount_dec_and_test(&uarg->refcnt))
1653 __msg_zerocopy_callback(uarg_zc);
1655 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1657 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1659 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1661 atomic_dec(&sk->sk_zckey);
1662 uarg_to_msgzc(uarg)->len--;
1665 msg_zerocopy_callback(NULL, uarg, true);
1667 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1669 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1670 struct msghdr *msg, int len,
1671 struct ubuf_info *uarg)
1673 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1674 int err, orig_len = skb->len;
1676 /* An skb can only point to one uarg. This edge case happens when
1677 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1679 if (orig_uarg && uarg != orig_uarg)
1682 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1683 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1684 struct sock *save_sk = skb->sk;
1686 /* Streams do not free skb on error. Reset to prev state. */
1687 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1689 ___pskb_trim(skb, orig_len);
1694 skb_zcopy_set(skb, uarg, NULL);
1695 return skb->len - orig_len;
1697 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1699 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1703 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1704 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1705 skb_frag_ref(skb, i);
1707 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1709 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1712 if (skb_zcopy(orig)) {
1713 if (skb_zcopy(nskb)) {
1714 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1719 if (skb_uarg(nskb) == skb_uarg(orig))
1721 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1724 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1730 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1731 * @skb: the skb to modify
1732 * @gfp_mask: allocation priority
1734 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1735 * It will copy all frags into kernel and drop the reference
1736 * to userspace pages.
1738 * If this function is called from an interrupt gfp_mask() must be
1741 * Returns 0 on success or a negative error code on failure
1742 * to allocate kernel memory to copy to.
1744 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1746 int num_frags = skb_shinfo(skb)->nr_frags;
1747 struct page *page, *head = NULL;
1748 int i, order, psize, new_frags;
1751 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1757 /* We might have to allocate high order pages, so compute what minimum
1758 * page order is needed.
1761 while ((PAGE_SIZE << order) * MAX_SKB_FRAGS < __skb_pagelen(skb))
1763 psize = (PAGE_SIZE << order);
1765 new_frags = (__skb_pagelen(skb) + psize - 1) >> (PAGE_SHIFT + order);
1766 for (i = 0; i < new_frags; i++) {
1767 page = alloc_pages(gfp_mask | __GFP_COMP, order);
1770 struct page *next = (struct page *)page_private(head);
1776 set_page_private(page, (unsigned long)head);
1782 for (i = 0; i < num_frags; i++) {
1783 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1784 u32 p_off, p_len, copied;
1788 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1789 p, p_off, p_len, copied) {
1791 vaddr = kmap_atomic(p);
1793 while (done < p_len) {
1794 if (d_off == psize) {
1796 page = (struct page *)page_private(page);
1798 copy = min_t(u32, psize - d_off, p_len - done);
1799 memcpy(page_address(page) + d_off,
1800 vaddr + p_off + done, copy);
1804 kunmap_atomic(vaddr);
1808 /* skb frags release userspace buffers */
1809 for (i = 0; i < num_frags; i++)
1810 skb_frag_unref(skb, i);
1812 /* skb frags point to kernel buffers */
1813 for (i = 0; i < new_frags - 1; i++) {
1814 __skb_fill_page_desc(skb, i, head, 0, psize);
1815 head = (struct page *)page_private(head);
1817 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1818 skb_shinfo(skb)->nr_frags = new_frags;
1821 skb_zcopy_clear(skb, false);
1824 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1827 * skb_clone - duplicate an sk_buff
1828 * @skb: buffer to clone
1829 * @gfp_mask: allocation priority
1831 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1832 * copies share the same packet data but not structure. The new
1833 * buffer has a reference count of 1. If the allocation fails the
1834 * function returns %NULL otherwise the new buffer is returned.
1836 * If this function is called from an interrupt gfp_mask() must be
1840 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1842 struct sk_buff_fclones *fclones = container_of(skb,
1843 struct sk_buff_fclones,
1847 if (skb_orphan_frags(skb, gfp_mask))
1850 if (skb->fclone == SKB_FCLONE_ORIG &&
1851 refcount_read(&fclones->fclone_ref) == 1) {
1853 refcount_set(&fclones->fclone_ref, 2);
1854 n->fclone = SKB_FCLONE_CLONE;
1856 if (skb_pfmemalloc(skb))
1857 gfp_mask |= __GFP_MEMALLOC;
1859 n = kmem_cache_alloc(skbuff_cache, gfp_mask);
1863 n->fclone = SKB_FCLONE_UNAVAILABLE;
1866 return __skb_clone(n, skb);
1868 EXPORT_SYMBOL(skb_clone);
1870 void skb_headers_offset_update(struct sk_buff *skb, int off)
1872 /* Only adjust this if it actually is csum_start rather than csum */
1873 if (skb->ip_summed == CHECKSUM_PARTIAL)
1874 skb->csum_start += off;
1875 /* {transport,network,mac}_header and tail are relative to skb->head */
1876 skb->transport_header += off;
1877 skb->network_header += off;
1878 if (skb_mac_header_was_set(skb))
1879 skb->mac_header += off;
1880 skb->inner_transport_header += off;
1881 skb->inner_network_header += off;
1882 skb->inner_mac_header += off;
1884 EXPORT_SYMBOL(skb_headers_offset_update);
1886 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1888 __copy_skb_header(new, old);
1890 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1891 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1892 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1894 EXPORT_SYMBOL(skb_copy_header);
1896 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1898 if (skb_pfmemalloc(skb))
1899 return SKB_ALLOC_RX;
1904 * skb_copy - create private copy of an sk_buff
1905 * @skb: buffer to copy
1906 * @gfp_mask: allocation priority
1908 * Make a copy of both an &sk_buff and its data. This is used when the
1909 * caller wishes to modify the data and needs a private copy of the
1910 * data to alter. Returns %NULL on failure or the pointer to the buffer
1911 * on success. The returned buffer has a reference count of 1.
1913 * As by-product this function converts non-linear &sk_buff to linear
1914 * one, so that &sk_buff becomes completely private and caller is allowed
1915 * to modify all the data of returned buffer. This means that this
1916 * function is not recommended for use in circumstances when only
1917 * header is going to be modified. Use pskb_copy() instead.
1920 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1922 int headerlen = skb_headroom(skb);
1923 unsigned int size = skb_end_offset(skb) + skb->data_len;
1924 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1925 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1930 /* Set the data pointer */
1931 skb_reserve(n, headerlen);
1932 /* Set the tail pointer and length */
1933 skb_put(n, skb->len);
1935 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1937 skb_copy_header(n, skb);
1940 EXPORT_SYMBOL(skb_copy);
1943 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1944 * @skb: buffer to copy
1945 * @headroom: headroom of new skb
1946 * @gfp_mask: allocation priority
1947 * @fclone: if true allocate the copy of the skb from the fclone
1948 * cache instead of the head cache; it is recommended to set this
1949 * to true for the cases where the copy will likely be cloned
1951 * Make a copy of both an &sk_buff and part of its data, located
1952 * in header. Fragmented data remain shared. This is used when
1953 * the caller wishes to modify only header of &sk_buff and needs
1954 * private copy of the header to alter. Returns %NULL on failure
1955 * or the pointer to the buffer on success.
1956 * The returned buffer has a reference count of 1.
1959 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1960 gfp_t gfp_mask, bool fclone)
1962 unsigned int size = skb_headlen(skb) + headroom;
1963 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1964 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1969 /* Set the data pointer */
1970 skb_reserve(n, headroom);
1971 /* Set the tail pointer and length */
1972 skb_put(n, skb_headlen(skb));
1973 /* Copy the bytes */
1974 skb_copy_from_linear_data(skb, n->data, n->len);
1976 n->truesize += skb->data_len;
1977 n->data_len = skb->data_len;
1980 if (skb_shinfo(skb)->nr_frags) {
1983 if (skb_orphan_frags(skb, gfp_mask) ||
1984 skb_zerocopy_clone(n, skb, gfp_mask)) {
1989 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1990 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1991 skb_frag_ref(skb, i);
1993 skb_shinfo(n)->nr_frags = i;
1996 if (skb_has_frag_list(skb)) {
1997 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1998 skb_clone_fraglist(n);
2001 skb_copy_header(n, skb);
2005 EXPORT_SYMBOL(__pskb_copy_fclone);
2008 * pskb_expand_head - reallocate header of &sk_buff
2009 * @skb: buffer to reallocate
2010 * @nhead: room to add at head
2011 * @ntail: room to add at tail
2012 * @gfp_mask: allocation priority
2014 * Expands (or creates identical copy, if @nhead and @ntail are zero)
2015 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
2016 * reference count of 1. Returns zero in the case of success or error,
2017 * if expansion failed. In the last case, &sk_buff is not changed.
2019 * All the pointers pointing into skb header may change and must be
2020 * reloaded after call to this function.
2023 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
2026 unsigned int osize = skb_end_offset(skb);
2027 unsigned int size = osize + nhead + ntail;
2034 BUG_ON(skb_shared(skb));
2036 skb_zcopy_downgrade_managed(skb);
2038 if (skb_pfmemalloc(skb))
2039 gfp_mask |= __GFP_MEMALLOC;
2041 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
2044 size = SKB_WITH_OVERHEAD(size);
2046 /* Copy only real data... and, alas, header. This should be
2047 * optimized for the cases when header is void.
2049 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
2051 memcpy((struct skb_shared_info *)(data + size),
2053 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
2056 * if shinfo is shared we must drop the old head gracefully, but if it
2057 * is not we can just drop the old head and let the existing refcount
2058 * be since all we did is relocate the values
2060 if (skb_cloned(skb)) {
2061 if (skb_orphan_frags(skb, gfp_mask))
2064 refcount_inc(&skb_uarg(skb)->refcnt);
2065 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2066 skb_frag_ref(skb, i);
2068 if (skb_has_frag_list(skb))
2069 skb_clone_fraglist(skb);
2071 skb_release_data(skb, SKB_CONSUMED, false);
2073 skb_free_head(skb, false);
2075 off = (data + nhead) - skb->head;
2081 skb_set_end_offset(skb, size);
2082 #ifdef NET_SKBUFF_DATA_USES_OFFSET
2086 skb_headers_offset_update(skb, nhead);
2090 atomic_set(&skb_shinfo(skb)->dataref, 1);
2092 skb_metadata_clear(skb);
2094 /* It is not generally safe to change skb->truesize.
2095 * For the moment, we really care of rx path, or
2096 * when skb is orphaned (not attached to a socket).
2098 if (!skb->sk || skb->destructor == sock_edemux)
2099 skb->truesize += size - osize;
2104 skb_kfree_head(data, size);
2108 EXPORT_SYMBOL(pskb_expand_head);
2110 /* Make private copy of skb with writable head and some headroom */
2112 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
2114 struct sk_buff *skb2;
2115 int delta = headroom - skb_headroom(skb);
2118 skb2 = pskb_copy(skb, GFP_ATOMIC);
2120 skb2 = skb_clone(skb, GFP_ATOMIC);
2121 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
2129 EXPORT_SYMBOL(skb_realloc_headroom);
2131 /* Note: We plan to rework this in linux-6.4 */
2132 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
2134 unsigned int saved_end_offset, saved_truesize;
2135 struct skb_shared_info *shinfo;
2138 saved_end_offset = skb_end_offset(skb);
2139 saved_truesize = skb->truesize;
2141 res = pskb_expand_head(skb, 0, 0, pri);
2145 skb->truesize = saved_truesize;
2147 if (likely(skb_end_offset(skb) == saved_end_offset))
2150 /* We can not change skb->end if the original or new value
2151 * is SKB_SMALL_HEAD_HEADROOM, as it might break skb_kfree_head().
2153 if (saved_end_offset == SKB_SMALL_HEAD_HEADROOM ||
2154 skb_end_offset(skb) == SKB_SMALL_HEAD_HEADROOM) {
2155 /* We think this path should not be taken.
2156 * Add a temporary trace to warn us just in case.
2158 pr_err_once("__skb_unclone_keeptruesize() skb_end_offset() %u -> %u\n",
2159 saved_end_offset, skb_end_offset(skb));
2164 shinfo = skb_shinfo(skb);
2166 /* We are about to change back skb->end,
2167 * we need to move skb_shinfo() to its new location.
2169 memmove(skb->head + saved_end_offset,
2171 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
2173 skb_set_end_offset(skb, saved_end_offset);
2179 * skb_expand_head - reallocate header of &sk_buff
2180 * @skb: buffer to reallocate
2181 * @headroom: needed headroom
2183 * Unlike skb_realloc_headroom, this one does not allocate a new skb
2184 * if possible; copies skb->sk to new skb as needed
2185 * and frees original skb in case of failures.
2187 * It expect increased headroom and generates warning otherwise.
2190 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2192 int delta = headroom - skb_headroom(skb);
2193 int osize = skb_end_offset(skb);
2194 struct sock *sk = skb->sk;
2196 if (WARN_ONCE(delta <= 0,
2197 "%s is expecting an increase in the headroom", __func__))
2200 delta = SKB_DATA_ALIGN(delta);
2201 /* pskb_expand_head() might crash, if skb is shared. */
2202 if (skb_shared(skb) || !is_skb_wmem(skb)) {
2203 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2205 if (unlikely(!nskb))
2209 skb_set_owner_w(nskb, sk);
2213 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2216 if (sk && is_skb_wmem(skb)) {
2217 delta = skb_end_offset(skb) - osize;
2218 refcount_add(delta, &sk->sk_wmem_alloc);
2219 skb->truesize += delta;
2227 EXPORT_SYMBOL(skb_expand_head);
2230 * skb_copy_expand - copy and expand sk_buff
2231 * @skb: buffer to copy
2232 * @newheadroom: new free bytes at head
2233 * @newtailroom: new free bytes at tail
2234 * @gfp_mask: allocation priority
2236 * Make a copy of both an &sk_buff and its data and while doing so
2237 * allocate additional space.
2239 * This is used when the caller wishes to modify the data and needs a
2240 * private copy of the data to alter as well as more space for new fields.
2241 * Returns %NULL on failure or the pointer to the buffer
2242 * on success. The returned buffer has a reference count of 1.
2244 * You must pass %GFP_ATOMIC as the allocation priority if this function
2245 * is called from an interrupt.
2247 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2248 int newheadroom, int newtailroom,
2252 * Allocate the copy buffer
2254 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2255 gfp_mask, skb_alloc_rx_flag(skb),
2257 int oldheadroom = skb_headroom(skb);
2258 int head_copy_len, head_copy_off;
2263 skb_reserve(n, newheadroom);
2265 /* Set the tail pointer and length */
2266 skb_put(n, skb->len);
2268 head_copy_len = oldheadroom;
2270 if (newheadroom <= head_copy_len)
2271 head_copy_len = newheadroom;
2273 head_copy_off = newheadroom - head_copy_len;
2275 /* Copy the linear header and data. */
2276 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2277 skb->len + head_copy_len));
2279 skb_copy_header(n, skb);
2281 skb_headers_offset_update(n, newheadroom - oldheadroom);
2285 EXPORT_SYMBOL(skb_copy_expand);
2288 * __skb_pad - zero pad the tail of an skb
2289 * @skb: buffer to pad
2290 * @pad: space to pad
2291 * @free_on_error: free buffer on error
2293 * Ensure that a buffer is followed by a padding area that is zero
2294 * filled. Used by network drivers which may DMA or transfer data
2295 * beyond the buffer end onto the wire.
2297 * May return error in out of memory cases. The skb is freed on error
2298 * if @free_on_error is true.
2301 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2306 /* If the skbuff is non linear tailroom is always zero.. */
2307 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2308 memset(skb->data+skb->len, 0, pad);
2312 ntail = skb->data_len + pad - (skb->end - skb->tail);
2313 if (likely(skb_cloned(skb) || ntail > 0)) {
2314 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2319 /* FIXME: The use of this function with non-linear skb's really needs
2322 err = skb_linearize(skb);
2326 memset(skb->data + skb->len, 0, pad);
2334 EXPORT_SYMBOL(__skb_pad);
2337 * pskb_put - add data to the tail of a potentially fragmented buffer
2338 * @skb: start of the buffer to use
2339 * @tail: tail fragment of the buffer to use
2340 * @len: amount of data to add
2342 * This function extends the used data area of the potentially
2343 * fragmented buffer. @tail must be the last fragment of @skb -- or
2344 * @skb itself. If this would exceed the total buffer size the kernel
2345 * will panic. A pointer to the first byte of the extra data is
2349 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2352 skb->data_len += len;
2355 return skb_put(tail, len);
2357 EXPORT_SYMBOL_GPL(pskb_put);
2360 * skb_put - add data to a buffer
2361 * @skb: buffer to use
2362 * @len: amount of data to add
2364 * This function extends the used data area of the buffer. If this would
2365 * exceed the total buffer size the kernel will panic. A pointer to the
2366 * first byte of the extra data is returned.
2368 void *skb_put(struct sk_buff *skb, unsigned int len)
2370 void *tmp = skb_tail_pointer(skb);
2371 SKB_LINEAR_ASSERT(skb);
2374 if (unlikely(skb->tail > skb->end))
2375 skb_over_panic(skb, len, __builtin_return_address(0));
2378 EXPORT_SYMBOL(skb_put);
2381 * skb_push - add data to the start of a buffer
2382 * @skb: buffer to use
2383 * @len: amount of data to add
2385 * This function extends the used data area of the buffer at the buffer
2386 * start. If this would exceed the total buffer headroom the kernel will
2387 * panic. A pointer to the first byte of the extra data is returned.
2389 void *skb_push(struct sk_buff *skb, unsigned int len)
2393 if (unlikely(skb->data < skb->head))
2394 skb_under_panic(skb, len, __builtin_return_address(0));
2397 EXPORT_SYMBOL(skb_push);
2400 * skb_pull - remove data from the start of a buffer
2401 * @skb: buffer to use
2402 * @len: amount of data to remove
2404 * This function removes data from the start of a buffer, returning
2405 * the memory to the headroom. A pointer to the next data in the buffer
2406 * is returned. Once the data has been pulled future pushes will overwrite
2409 void *skb_pull(struct sk_buff *skb, unsigned int len)
2411 return skb_pull_inline(skb, len);
2413 EXPORT_SYMBOL(skb_pull);
2416 * skb_pull_data - remove data from the start of a buffer returning its
2417 * original position.
2418 * @skb: buffer to use
2419 * @len: amount of data to remove
2421 * This function removes data from the start of a buffer, returning
2422 * the memory to the headroom. A pointer to the original data in the buffer
2423 * is returned after checking if there is enough data to pull. Once the
2424 * data has been pulled future pushes will overwrite the old data.
2426 void *skb_pull_data(struct sk_buff *skb, size_t len)
2428 void *data = skb->data;
2437 EXPORT_SYMBOL(skb_pull_data);
2440 * skb_trim - remove end from a buffer
2441 * @skb: buffer to alter
2444 * Cut the length of a buffer down by removing data from the tail. If
2445 * the buffer is already under the length specified it is not modified.
2446 * The skb must be linear.
2448 void skb_trim(struct sk_buff *skb, unsigned int len)
2451 __skb_trim(skb, len);
2453 EXPORT_SYMBOL(skb_trim);
2455 /* Trims skb to length len. It can change skb pointers.
2458 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2460 struct sk_buff **fragp;
2461 struct sk_buff *frag;
2462 int offset = skb_headlen(skb);
2463 int nfrags = skb_shinfo(skb)->nr_frags;
2467 if (skb_cloned(skb) &&
2468 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2475 for (; i < nfrags; i++) {
2476 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2483 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2486 skb_shinfo(skb)->nr_frags = i;
2488 for (; i < nfrags; i++)
2489 skb_frag_unref(skb, i);
2491 if (skb_has_frag_list(skb))
2492 skb_drop_fraglist(skb);
2496 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2497 fragp = &frag->next) {
2498 int end = offset + frag->len;
2500 if (skb_shared(frag)) {
2501 struct sk_buff *nfrag;
2503 nfrag = skb_clone(frag, GFP_ATOMIC);
2504 if (unlikely(!nfrag))
2507 nfrag->next = frag->next;
2519 unlikely((err = pskb_trim(frag, len - offset))))
2523 skb_drop_list(&frag->next);
2528 if (len > skb_headlen(skb)) {
2529 skb->data_len -= skb->len - len;
2534 skb_set_tail_pointer(skb, len);
2537 if (!skb->sk || skb->destructor == sock_edemux)
2541 EXPORT_SYMBOL(___pskb_trim);
2543 /* Note : use pskb_trim_rcsum() instead of calling this directly
2545 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2547 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2548 int delta = skb->len - len;
2550 skb->csum = csum_block_sub(skb->csum,
2551 skb_checksum(skb, len, delta, 0),
2553 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2554 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2555 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2557 if (offset + sizeof(__sum16) > hdlen)
2560 return __pskb_trim(skb, len);
2562 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2565 * __pskb_pull_tail - advance tail of skb header
2566 * @skb: buffer to reallocate
2567 * @delta: number of bytes to advance tail
2569 * The function makes a sense only on a fragmented &sk_buff,
2570 * it expands header moving its tail forward and copying necessary
2571 * data from fragmented part.
2573 * &sk_buff MUST have reference count of 1.
2575 * Returns %NULL (and &sk_buff does not change) if pull failed
2576 * or value of new tail of skb in the case of success.
2578 * All the pointers pointing into skb header may change and must be
2579 * reloaded after call to this function.
2582 /* Moves tail of skb head forward, copying data from fragmented part,
2583 * when it is necessary.
2584 * 1. It may fail due to malloc failure.
2585 * 2. It may change skb pointers.
2587 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2589 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2591 /* If skb has not enough free space at tail, get new one
2592 * plus 128 bytes for future expansions. If we have enough
2593 * room at tail, reallocate without expansion only if skb is cloned.
2595 int i, k, eat = (skb->tail + delta) - skb->end;
2597 if (eat > 0 || skb_cloned(skb)) {
2598 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2603 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2604 skb_tail_pointer(skb), delta));
2606 /* Optimization: no fragments, no reasons to preestimate
2607 * size of pulled pages. Superb.
2609 if (!skb_has_frag_list(skb))
2612 /* Estimate size of pulled pages. */
2614 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2615 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2622 /* If we need update frag list, we are in troubles.
2623 * Certainly, it is possible to add an offset to skb data,
2624 * but taking into account that pulling is expected to
2625 * be very rare operation, it is worth to fight against
2626 * further bloating skb head and crucify ourselves here instead.
2627 * Pure masohism, indeed. 8)8)
2630 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2631 struct sk_buff *clone = NULL;
2632 struct sk_buff *insp = NULL;
2635 if (list->len <= eat) {
2636 /* Eaten as whole. */
2641 /* Eaten partially. */
2642 if (skb_is_gso(skb) && !list->head_frag &&
2644 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2646 if (skb_shared(list)) {
2647 /* Sucks! We need to fork list. :-( */
2648 clone = skb_clone(list, GFP_ATOMIC);
2654 /* This may be pulled without
2658 if (!pskb_pull(list, eat)) {
2666 /* Free pulled out fragments. */
2667 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2668 skb_shinfo(skb)->frag_list = list->next;
2671 /* And insert new clone at head. */
2674 skb_shinfo(skb)->frag_list = clone;
2677 /* Success! Now we may commit changes to skb data. */
2682 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2683 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2686 skb_frag_unref(skb, i);
2689 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2691 *frag = skb_shinfo(skb)->frags[i];
2693 skb_frag_off_add(frag, eat);
2694 skb_frag_size_sub(frag, eat);
2702 skb_shinfo(skb)->nr_frags = k;
2706 skb->data_len -= delta;
2709 skb_zcopy_clear(skb, false);
2711 return skb_tail_pointer(skb);
2713 EXPORT_SYMBOL(__pskb_pull_tail);
2716 * skb_copy_bits - copy bits from skb to kernel buffer
2718 * @offset: offset in source
2719 * @to: destination buffer
2720 * @len: number of bytes to copy
2722 * Copy the specified number of bytes from the source skb to the
2723 * destination buffer.
2726 * If its prototype is ever changed,
2727 * check arch/{*}/net/{*}.S files,
2728 * since it is called from BPF assembly code.
2730 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2732 int start = skb_headlen(skb);
2733 struct sk_buff *frag_iter;
2736 if (offset > (int)skb->len - len)
2740 if ((copy = start - offset) > 0) {
2743 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2744 if ((len -= copy) == 0)
2750 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2752 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2754 WARN_ON(start > offset + len);
2756 end = start + skb_frag_size(f);
2757 if ((copy = end - offset) > 0) {
2758 u32 p_off, p_len, copied;
2765 skb_frag_foreach_page(f,
2766 skb_frag_off(f) + offset - start,
2767 copy, p, p_off, p_len, copied) {
2768 vaddr = kmap_atomic(p);
2769 memcpy(to + copied, vaddr + p_off, p_len);
2770 kunmap_atomic(vaddr);
2773 if ((len -= copy) == 0)
2781 skb_walk_frags(skb, frag_iter) {
2784 WARN_ON(start > offset + len);
2786 end = start + frag_iter->len;
2787 if ((copy = end - offset) > 0) {
2790 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2792 if ((len -= copy) == 0)
2806 EXPORT_SYMBOL(skb_copy_bits);
2809 * Callback from splice_to_pipe(), if we need to release some pages
2810 * at the end of the spd in case we error'ed out in filling the pipe.
2812 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2814 put_page(spd->pages[i]);
2817 static struct page *linear_to_page(struct page *page, unsigned int *len,
2818 unsigned int *offset,
2821 struct page_frag *pfrag = sk_page_frag(sk);
2823 if (!sk_page_frag_refill(sk, pfrag))
2826 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2828 memcpy(page_address(pfrag->page) + pfrag->offset,
2829 page_address(page) + *offset, *len);
2830 *offset = pfrag->offset;
2831 pfrag->offset += *len;
2836 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2838 unsigned int offset)
2840 return spd->nr_pages &&
2841 spd->pages[spd->nr_pages - 1] == page &&
2842 (spd->partial[spd->nr_pages - 1].offset +
2843 spd->partial[spd->nr_pages - 1].len == offset);
2847 * Fill page/offset/length into spd, if it can hold more pages.
2849 static bool spd_fill_page(struct splice_pipe_desc *spd,
2850 struct pipe_inode_info *pipe, struct page *page,
2851 unsigned int *len, unsigned int offset,
2855 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2859 page = linear_to_page(page, len, &offset, sk);
2863 if (spd_can_coalesce(spd, page, offset)) {
2864 spd->partial[spd->nr_pages - 1].len += *len;
2868 spd->pages[spd->nr_pages] = page;
2869 spd->partial[spd->nr_pages].len = *len;
2870 spd->partial[spd->nr_pages].offset = offset;
2876 static bool __splice_segment(struct page *page, unsigned int poff,
2877 unsigned int plen, unsigned int *off,
2879 struct splice_pipe_desc *spd, bool linear,
2881 struct pipe_inode_info *pipe)
2886 /* skip this segment if already processed */
2892 /* ignore any bits we already processed */
2898 unsigned int flen = min(*len, plen);
2900 if (spd_fill_page(spd, pipe, page, &flen, poff,
2906 } while (*len && plen);
2912 * Map linear and fragment data from the skb to spd. It reports true if the
2913 * pipe is full or if we already spliced the requested length.
2915 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2916 unsigned int *offset, unsigned int *len,
2917 struct splice_pipe_desc *spd, struct sock *sk)
2920 struct sk_buff *iter;
2922 /* map the linear part :
2923 * If skb->head_frag is set, this 'linear' part is backed by a
2924 * fragment, and if the head is not shared with any clones then
2925 * we can avoid a copy since we own the head portion of this page.
2927 if (__splice_segment(virt_to_page(skb->data),
2928 (unsigned long) skb->data & (PAGE_SIZE - 1),
2931 skb_head_is_locked(skb),
2936 * then map the fragments
2938 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2939 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2941 if (__splice_segment(skb_frag_page(f),
2942 skb_frag_off(f), skb_frag_size(f),
2943 offset, len, spd, false, sk, pipe))
2947 skb_walk_frags(skb, iter) {
2948 if (*offset >= iter->len) {
2949 *offset -= iter->len;
2952 /* __skb_splice_bits() only fails if the output has no room
2953 * left, so no point in going over the frag_list for the error
2956 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2964 * Map data from the skb to a pipe. Should handle both the linear part,
2965 * the fragments, and the frag list.
2967 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2968 struct pipe_inode_info *pipe, unsigned int tlen,
2971 struct partial_page partial[MAX_SKB_FRAGS];
2972 struct page *pages[MAX_SKB_FRAGS];
2973 struct splice_pipe_desc spd = {
2976 .nr_pages_max = MAX_SKB_FRAGS,
2977 .ops = &nosteal_pipe_buf_ops,
2978 .spd_release = sock_spd_release,
2982 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2985 ret = splice_to_pipe(pipe, &spd);
2989 EXPORT_SYMBOL_GPL(skb_splice_bits);
2991 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2992 struct kvec *vec, size_t num, size_t size)
2994 struct socket *sock = sk->sk_socket;
2998 return kernel_sendmsg(sock, msg, vec, num, size);
3001 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
3002 size_t size, int flags)
3004 struct socket *sock = sk->sk_socket;
3008 return kernel_sendpage(sock, page, offset, size, flags);
3011 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
3012 struct kvec *vec, size_t num, size_t size);
3013 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
3014 size_t size, int flags);
3015 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
3016 int len, sendmsg_func sendmsg, sendpage_func sendpage)
3018 unsigned int orig_len = len;
3019 struct sk_buff *head = skb;
3020 unsigned short fragidx;
3025 /* Deal with head data */
3026 while (offset < skb_headlen(skb) && len) {
3030 slen = min_t(int, len, skb_headlen(skb) - offset);
3031 kv.iov_base = skb->data + offset;
3033 memset(&msg, 0, sizeof(msg));
3034 msg.msg_flags = MSG_DONTWAIT;
3036 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
3037 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
3045 /* All the data was skb head? */
3049 /* Make offset relative to start of frags */
3050 offset -= skb_headlen(skb);
3052 /* Find where we are in frag list */
3053 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3054 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3056 if (offset < skb_frag_size(frag))
3059 offset -= skb_frag_size(frag);
3062 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3063 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3065 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
3068 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
3069 sendpage_unlocked, sk,
3070 skb_frag_page(frag),
3071 skb_frag_off(frag) + offset,
3072 slen, MSG_DONTWAIT);
3085 /* Process any frag lists */
3088 if (skb_has_frag_list(skb)) {
3089 skb = skb_shinfo(skb)->frag_list;
3092 } else if (skb->next) {
3099 return orig_len - len;
3102 return orig_len == len ? ret : orig_len - len;
3105 /* Send skb data on a socket. Socket must be locked. */
3106 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
3109 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
3110 kernel_sendpage_locked);
3112 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
3114 /* Send skb data on a socket. Socket must be unlocked. */
3115 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
3117 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
3122 * skb_store_bits - store bits from kernel buffer to skb
3123 * @skb: destination buffer
3124 * @offset: offset in destination
3125 * @from: source buffer
3126 * @len: number of bytes to copy
3128 * Copy the specified number of bytes from the source buffer to the
3129 * destination skb. This function handles all the messy bits of
3130 * traversing fragment lists and such.
3133 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
3135 int start = skb_headlen(skb);
3136 struct sk_buff *frag_iter;
3139 if (offset > (int)skb->len - len)
3142 if ((copy = start - offset) > 0) {
3145 skb_copy_to_linear_data_offset(skb, offset, from, copy);
3146 if ((len -= copy) == 0)
3152 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3153 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3156 WARN_ON(start > offset + len);
3158 end = start + skb_frag_size(frag);
3159 if ((copy = end - offset) > 0) {
3160 u32 p_off, p_len, copied;
3167 skb_frag_foreach_page(frag,
3168 skb_frag_off(frag) + offset - start,
3169 copy, p, p_off, p_len, copied) {
3170 vaddr = kmap_atomic(p);
3171 memcpy(vaddr + p_off, from + copied, p_len);
3172 kunmap_atomic(vaddr);
3175 if ((len -= copy) == 0)
3183 skb_walk_frags(skb, frag_iter) {
3186 WARN_ON(start > offset + len);
3188 end = start + frag_iter->len;
3189 if ((copy = end - offset) > 0) {
3192 if (skb_store_bits(frag_iter, offset - start,
3195 if ((len -= copy) == 0)
3208 EXPORT_SYMBOL(skb_store_bits);
3210 /* Checksum skb data. */
3211 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
3212 __wsum csum, const struct skb_checksum_ops *ops)
3214 int start = skb_headlen(skb);
3215 int i, copy = start - offset;
3216 struct sk_buff *frag_iter;
3219 /* Checksum header. */
3223 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3224 skb->data + offset, copy, csum);
3225 if ((len -= copy) == 0)
3231 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3233 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3235 WARN_ON(start > offset + len);
3237 end = start + skb_frag_size(frag);
3238 if ((copy = end - offset) > 0) {
3239 u32 p_off, p_len, copied;
3247 skb_frag_foreach_page(frag,
3248 skb_frag_off(frag) + offset - start,
3249 copy, p, p_off, p_len, copied) {
3250 vaddr = kmap_atomic(p);
3251 csum2 = INDIRECT_CALL_1(ops->update,
3253 vaddr + p_off, p_len, 0);
3254 kunmap_atomic(vaddr);
3255 csum = INDIRECT_CALL_1(ops->combine,
3256 csum_block_add_ext, csum,
3268 skb_walk_frags(skb, frag_iter) {
3271 WARN_ON(start > offset + len);
3273 end = start + frag_iter->len;
3274 if ((copy = end - offset) > 0) {
3278 csum2 = __skb_checksum(frag_iter, offset - start,
3280 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3281 csum, csum2, pos, copy);
3282 if ((len -= copy) == 0)
3293 EXPORT_SYMBOL(__skb_checksum);
3295 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3296 int len, __wsum csum)
3298 const struct skb_checksum_ops ops = {
3299 .update = csum_partial_ext,
3300 .combine = csum_block_add_ext,
3303 return __skb_checksum(skb, offset, len, csum, &ops);
3305 EXPORT_SYMBOL(skb_checksum);
3307 /* Both of above in one bottle. */
3309 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3312 int start = skb_headlen(skb);
3313 int i, copy = start - offset;
3314 struct sk_buff *frag_iter;
3322 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3324 if ((len -= copy) == 0)
3331 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3334 WARN_ON(start > offset + len);
3336 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3337 if ((copy = end - offset) > 0) {
3338 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3339 u32 p_off, p_len, copied;
3347 skb_frag_foreach_page(frag,
3348 skb_frag_off(frag) + offset - start,
3349 copy, p, p_off, p_len, copied) {
3350 vaddr = kmap_atomic(p);
3351 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3354 kunmap_atomic(vaddr);
3355 csum = csum_block_add(csum, csum2, pos);
3367 skb_walk_frags(skb, frag_iter) {
3371 WARN_ON(start > offset + len);
3373 end = start + frag_iter->len;
3374 if ((copy = end - offset) > 0) {
3377 csum2 = skb_copy_and_csum_bits(frag_iter,
3380 csum = csum_block_add(csum, csum2, pos);
3381 if ((len -= copy) == 0)
3392 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3394 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3398 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3399 /* See comments in __skb_checksum_complete(). */
3401 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3402 !skb->csum_complete_sw)
3403 netdev_rx_csum_fault(skb->dev, skb);
3405 if (!skb_shared(skb))
3406 skb->csum_valid = !sum;
3409 EXPORT_SYMBOL(__skb_checksum_complete_head);
3411 /* This function assumes skb->csum already holds pseudo header's checksum,
3412 * which has been changed from the hardware checksum, for example, by
3413 * __skb_checksum_validate_complete(). And, the original skb->csum must
3414 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3416 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3417 * zero. The new checksum is stored back into skb->csum unless the skb is
3420 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3425 csum = skb_checksum(skb, 0, skb->len, 0);
3427 sum = csum_fold(csum_add(skb->csum, csum));
3428 /* This check is inverted, because we already knew the hardware
3429 * checksum is invalid before calling this function. So, if the
3430 * re-computed checksum is valid instead, then we have a mismatch
3431 * between the original skb->csum and skb_checksum(). This means either
3432 * the original hardware checksum is incorrect or we screw up skb->csum
3433 * when moving skb->data around.
3436 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3437 !skb->csum_complete_sw)
3438 netdev_rx_csum_fault(skb->dev, skb);
3441 if (!skb_shared(skb)) {
3442 /* Save full packet checksum */
3444 skb->ip_summed = CHECKSUM_COMPLETE;
3445 skb->csum_complete_sw = 1;
3446 skb->csum_valid = !sum;
3451 EXPORT_SYMBOL(__skb_checksum_complete);
3453 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3455 net_warn_ratelimited(
3456 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3461 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3462 int offset, int len)
3464 net_warn_ratelimited(
3465 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3470 static const struct skb_checksum_ops default_crc32c_ops = {
3471 .update = warn_crc32c_csum_update,
3472 .combine = warn_crc32c_csum_combine,
3475 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3476 &default_crc32c_ops;
3477 EXPORT_SYMBOL(crc32c_csum_stub);
3480 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3481 * @from: source buffer
3483 * Calculates the amount of linear headroom needed in the 'to' skb passed
3484 * into skb_zerocopy().
3487 skb_zerocopy_headlen(const struct sk_buff *from)
3489 unsigned int hlen = 0;
3491 if (!from->head_frag ||
3492 skb_headlen(from) < L1_CACHE_BYTES ||
3493 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3494 hlen = skb_headlen(from);
3499 if (skb_has_frag_list(from))
3504 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3507 * skb_zerocopy - Zero copy skb to skb
3508 * @to: destination buffer
3509 * @from: source buffer
3510 * @len: number of bytes to copy from source buffer
3511 * @hlen: size of linear headroom in destination buffer
3513 * Copies up to `len` bytes from `from` to `to` by creating references
3514 * to the frags in the source buffer.
3516 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3517 * headroom in the `to` buffer.
3520 * 0: everything is OK
3521 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3522 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3525 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3528 int plen = 0; /* length of skb->head fragment */
3531 unsigned int offset;
3533 BUG_ON(!from->head_frag && !hlen);
3535 /* dont bother with small payloads */
3536 if (len <= skb_tailroom(to))
3537 return skb_copy_bits(from, 0, skb_put(to, len), len);
3540 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3545 plen = min_t(int, skb_headlen(from), len);
3547 page = virt_to_head_page(from->head);
3548 offset = from->data - (unsigned char *)page_address(page);
3549 __skb_fill_page_desc(to, 0, page, offset, plen);
3556 skb_len_add(to, len + plen);
3558 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3562 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3564 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3569 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3570 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3572 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3574 skb_frag_ref(to, j);
3577 skb_shinfo(to)->nr_frags = j;
3581 EXPORT_SYMBOL_GPL(skb_zerocopy);
3583 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3588 if (skb->ip_summed == CHECKSUM_PARTIAL)
3589 csstart = skb_checksum_start_offset(skb);
3591 csstart = skb_headlen(skb);
3593 BUG_ON(csstart > skb_headlen(skb));
3595 skb_copy_from_linear_data(skb, to, csstart);
3598 if (csstart != skb->len)
3599 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3600 skb->len - csstart);
3602 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3603 long csstuff = csstart + skb->csum_offset;
3605 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3608 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3611 * skb_dequeue - remove from the head of the queue
3612 * @list: list to dequeue from
3614 * Remove the head of the list. The list lock is taken so the function
3615 * may be used safely with other locking list functions. The head item is
3616 * returned or %NULL if the list is empty.
3619 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3621 unsigned long flags;
3622 struct sk_buff *result;
3624 spin_lock_irqsave(&list->lock, flags);
3625 result = __skb_dequeue(list);
3626 spin_unlock_irqrestore(&list->lock, flags);
3629 EXPORT_SYMBOL(skb_dequeue);
3632 * skb_dequeue_tail - remove from the tail of the queue
3633 * @list: list to dequeue from
3635 * Remove the tail of the list. The list lock is taken so the function
3636 * may be used safely with other locking list functions. The tail item is
3637 * returned or %NULL if the list is empty.
3639 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3641 unsigned long flags;
3642 struct sk_buff *result;
3644 spin_lock_irqsave(&list->lock, flags);
3645 result = __skb_dequeue_tail(list);
3646 spin_unlock_irqrestore(&list->lock, flags);
3649 EXPORT_SYMBOL(skb_dequeue_tail);
3652 * skb_queue_purge - empty a list
3653 * @list: list to empty
3655 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3656 * the list and one reference dropped. This function takes the list
3657 * lock and is atomic with respect to other list locking functions.
3659 void skb_queue_purge(struct sk_buff_head *list)
3661 struct sk_buff *skb;
3662 while ((skb = skb_dequeue(list)) != NULL)
3665 EXPORT_SYMBOL(skb_queue_purge);
3668 * skb_rbtree_purge - empty a skb rbtree
3669 * @root: root of the rbtree to empty
3670 * Return value: the sum of truesizes of all purged skbs.
3672 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3673 * the list and one reference dropped. This function does not take
3674 * any lock. Synchronization should be handled by the caller (e.g., TCP
3675 * out-of-order queue is protected by the socket lock).
3677 unsigned int skb_rbtree_purge(struct rb_root *root)
3679 struct rb_node *p = rb_first(root);
3680 unsigned int sum = 0;
3683 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3686 rb_erase(&skb->rbnode, root);
3687 sum += skb->truesize;
3694 * skb_queue_head - queue a buffer at the list head
3695 * @list: list to use
3696 * @newsk: buffer to queue
3698 * Queue a buffer at the start of the list. This function takes the
3699 * list lock and can be used safely with other locking &sk_buff functions
3702 * A buffer cannot be placed on two lists at the same time.
3704 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3706 unsigned long flags;
3708 spin_lock_irqsave(&list->lock, flags);
3709 __skb_queue_head(list, newsk);
3710 spin_unlock_irqrestore(&list->lock, flags);
3712 EXPORT_SYMBOL(skb_queue_head);
3715 * skb_queue_tail - queue a buffer at the list tail
3716 * @list: list to use
3717 * @newsk: buffer to queue
3719 * Queue a buffer at the tail of the list. This function takes the
3720 * list lock and can be used safely with other locking &sk_buff functions
3723 * A buffer cannot be placed on two lists at the same time.
3725 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3727 unsigned long flags;
3729 spin_lock_irqsave(&list->lock, flags);
3730 __skb_queue_tail(list, newsk);
3731 spin_unlock_irqrestore(&list->lock, flags);
3733 EXPORT_SYMBOL(skb_queue_tail);
3736 * skb_unlink - remove a buffer from a list
3737 * @skb: buffer to remove
3738 * @list: list to use
3740 * Remove a packet from a list. The list locks are taken and this
3741 * function is atomic with respect to other list locked calls
3743 * You must know what list the SKB is on.
3745 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3747 unsigned long flags;
3749 spin_lock_irqsave(&list->lock, flags);
3750 __skb_unlink(skb, list);
3751 spin_unlock_irqrestore(&list->lock, flags);
3753 EXPORT_SYMBOL(skb_unlink);
3756 * skb_append - append a buffer
3757 * @old: buffer to insert after
3758 * @newsk: buffer to insert
3759 * @list: list to use
3761 * Place a packet after a given packet in a list. The list locks are taken
3762 * and this function is atomic with respect to other list locked calls.
3763 * A buffer cannot be placed on two lists at the same time.
3765 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3767 unsigned long flags;
3769 spin_lock_irqsave(&list->lock, flags);
3770 __skb_queue_after(list, old, newsk);
3771 spin_unlock_irqrestore(&list->lock, flags);
3773 EXPORT_SYMBOL(skb_append);
3775 static inline void skb_split_inside_header(struct sk_buff *skb,
3776 struct sk_buff* skb1,
3777 const u32 len, const int pos)
3781 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3783 /* And move data appendix as is. */
3784 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3785 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3787 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3788 skb_shinfo(skb)->nr_frags = 0;
3789 skb1->data_len = skb->data_len;
3790 skb1->len += skb1->data_len;
3793 skb_set_tail_pointer(skb, len);
3796 static inline void skb_split_no_header(struct sk_buff *skb,
3797 struct sk_buff* skb1,
3798 const u32 len, int pos)
3801 const int nfrags = skb_shinfo(skb)->nr_frags;
3803 skb_shinfo(skb)->nr_frags = 0;
3804 skb1->len = skb1->data_len = skb->len - len;
3806 skb->data_len = len - pos;
3808 for (i = 0; i < nfrags; i++) {
3809 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3811 if (pos + size > len) {
3812 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3816 * We have two variants in this case:
3817 * 1. Move all the frag to the second
3818 * part, if it is possible. F.e.
3819 * this approach is mandatory for TUX,
3820 * where splitting is expensive.
3821 * 2. Split is accurately. We make this.
3823 skb_frag_ref(skb, i);
3824 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3825 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3826 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3827 skb_shinfo(skb)->nr_frags++;
3831 skb_shinfo(skb)->nr_frags++;
3834 skb_shinfo(skb1)->nr_frags = k;
3838 * skb_split - Split fragmented skb to two parts at length len.
3839 * @skb: the buffer to split
3840 * @skb1: the buffer to receive the second part
3841 * @len: new length for skb
3843 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3845 int pos = skb_headlen(skb);
3846 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3848 skb_zcopy_downgrade_managed(skb);
3850 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3851 skb_zerocopy_clone(skb1, skb, 0);
3852 if (len < pos) /* Split line is inside header. */
3853 skb_split_inside_header(skb, skb1, len, pos);
3854 else /* Second chunk has no header, nothing to copy. */
3855 skb_split_no_header(skb, skb1, len, pos);
3857 EXPORT_SYMBOL(skb_split);
3859 /* Shifting from/to a cloned skb is a no-go.
3861 * Caller cannot keep skb_shinfo related pointers past calling here!
3863 static int skb_prepare_for_shift(struct sk_buff *skb)
3865 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3869 * skb_shift - Shifts paged data partially from skb to another
3870 * @tgt: buffer into which tail data gets added
3871 * @skb: buffer from which the paged data comes from
3872 * @shiftlen: shift up to this many bytes
3874 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3875 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3876 * It's up to caller to free skb if everything was shifted.
3878 * If @tgt runs out of frags, the whole operation is aborted.
3880 * Skb cannot include anything else but paged data while tgt is allowed
3881 * to have non-paged data as well.
3883 * TODO: full sized shift could be optimized but that would need
3884 * specialized skb free'er to handle frags without up-to-date nr_frags.
3886 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3888 int from, to, merge, todo;
3889 skb_frag_t *fragfrom, *fragto;
3891 BUG_ON(shiftlen > skb->len);
3893 if (skb_headlen(skb))
3895 if (skb_zcopy(tgt) || skb_zcopy(skb))
3900 to = skb_shinfo(tgt)->nr_frags;
3901 fragfrom = &skb_shinfo(skb)->frags[from];
3903 /* Actual merge is delayed until the point when we know we can
3904 * commit all, so that we don't have to undo partial changes
3907 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3908 skb_frag_off(fragfrom))) {
3913 todo -= skb_frag_size(fragfrom);
3915 if (skb_prepare_for_shift(skb) ||
3916 skb_prepare_for_shift(tgt))
3919 /* All previous frag pointers might be stale! */
3920 fragfrom = &skb_shinfo(skb)->frags[from];
3921 fragto = &skb_shinfo(tgt)->frags[merge];
3923 skb_frag_size_add(fragto, shiftlen);
3924 skb_frag_size_sub(fragfrom, shiftlen);
3925 skb_frag_off_add(fragfrom, shiftlen);
3933 /* Skip full, not-fitting skb to avoid expensive operations */
3934 if ((shiftlen == skb->len) &&
3935 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3938 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3941 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3942 if (to == MAX_SKB_FRAGS)
3945 fragfrom = &skb_shinfo(skb)->frags[from];
3946 fragto = &skb_shinfo(tgt)->frags[to];
3948 if (todo >= skb_frag_size(fragfrom)) {
3949 *fragto = *fragfrom;
3950 todo -= skb_frag_size(fragfrom);
3955 __skb_frag_ref(fragfrom);
3956 skb_frag_page_copy(fragto, fragfrom);
3957 skb_frag_off_copy(fragto, fragfrom);
3958 skb_frag_size_set(fragto, todo);
3960 skb_frag_off_add(fragfrom, todo);
3961 skb_frag_size_sub(fragfrom, todo);
3969 /* Ready to "commit" this state change to tgt */
3970 skb_shinfo(tgt)->nr_frags = to;
3973 fragfrom = &skb_shinfo(skb)->frags[0];
3974 fragto = &skb_shinfo(tgt)->frags[merge];
3976 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3977 __skb_frag_unref(fragfrom, skb->pp_recycle);
3980 /* Reposition in the original skb */
3982 while (from < skb_shinfo(skb)->nr_frags)
3983 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3984 skb_shinfo(skb)->nr_frags = to;
3986 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3989 /* Most likely the tgt won't ever need its checksum anymore, skb on
3990 * the other hand might need it if it needs to be resent
3992 tgt->ip_summed = CHECKSUM_PARTIAL;
3993 skb->ip_summed = CHECKSUM_PARTIAL;
3995 skb_len_add(skb, -shiftlen);
3996 skb_len_add(tgt, shiftlen);
4002 * skb_prepare_seq_read - Prepare a sequential read of skb data
4003 * @skb: the buffer to read
4004 * @from: lower offset of data to be read
4005 * @to: upper offset of data to be read
4006 * @st: state variable
4008 * Initializes the specified state variable. Must be called before
4009 * invoking skb_seq_read() for the first time.
4011 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
4012 unsigned int to, struct skb_seq_state *st)
4014 st->lower_offset = from;
4015 st->upper_offset = to;
4016 st->root_skb = st->cur_skb = skb;
4017 st->frag_idx = st->stepped_offset = 0;
4018 st->frag_data = NULL;
4021 EXPORT_SYMBOL(skb_prepare_seq_read);
4024 * skb_seq_read - Sequentially read skb data
4025 * @consumed: number of bytes consumed by the caller so far
4026 * @data: destination pointer for data to be returned
4027 * @st: state variable
4029 * Reads a block of skb data at @consumed relative to the
4030 * lower offset specified to skb_prepare_seq_read(). Assigns
4031 * the head of the data block to @data and returns the length
4032 * of the block or 0 if the end of the skb data or the upper
4033 * offset has been reached.
4035 * The caller is not required to consume all of the data
4036 * returned, i.e. @consumed is typically set to the number
4037 * of bytes already consumed and the next call to
4038 * skb_seq_read() will return the remaining part of the block.
4040 * Note 1: The size of each block of data returned can be arbitrary,
4041 * this limitation is the cost for zerocopy sequential
4042 * reads of potentially non linear data.
4044 * Note 2: Fragment lists within fragments are not implemented
4045 * at the moment, state->root_skb could be replaced with
4046 * a stack for this purpose.
4048 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
4049 struct skb_seq_state *st)
4051 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
4054 if (unlikely(abs_offset >= st->upper_offset)) {
4055 if (st->frag_data) {
4056 kunmap_atomic(st->frag_data);
4057 st->frag_data = NULL;
4063 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
4065 if (abs_offset < block_limit && !st->frag_data) {
4066 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
4067 return block_limit - abs_offset;
4070 if (st->frag_idx == 0 && !st->frag_data)
4071 st->stepped_offset += skb_headlen(st->cur_skb);
4073 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
4074 unsigned int pg_idx, pg_off, pg_sz;
4076 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
4079 pg_off = skb_frag_off(frag);
4080 pg_sz = skb_frag_size(frag);
4082 if (skb_frag_must_loop(skb_frag_page(frag))) {
4083 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
4084 pg_off = offset_in_page(pg_off + st->frag_off);
4085 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
4086 PAGE_SIZE - pg_off);
4089 block_limit = pg_sz + st->stepped_offset;
4090 if (abs_offset < block_limit) {
4092 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
4094 *data = (u8 *)st->frag_data + pg_off +
4095 (abs_offset - st->stepped_offset);
4097 return block_limit - abs_offset;
4100 if (st->frag_data) {
4101 kunmap_atomic(st->frag_data);
4102 st->frag_data = NULL;
4105 st->stepped_offset += pg_sz;
4106 st->frag_off += pg_sz;
4107 if (st->frag_off == skb_frag_size(frag)) {
4113 if (st->frag_data) {
4114 kunmap_atomic(st->frag_data);
4115 st->frag_data = NULL;
4118 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
4119 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
4122 } else if (st->cur_skb->next) {
4123 st->cur_skb = st->cur_skb->next;
4130 EXPORT_SYMBOL(skb_seq_read);
4133 * skb_abort_seq_read - Abort a sequential read of skb data
4134 * @st: state variable
4136 * Must be called if skb_seq_read() was not called until it
4139 void skb_abort_seq_read(struct skb_seq_state *st)
4142 kunmap_atomic(st->frag_data);
4144 EXPORT_SYMBOL(skb_abort_seq_read);
4146 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
4148 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
4149 struct ts_config *conf,
4150 struct ts_state *state)
4152 return skb_seq_read(offset, text, TS_SKB_CB(state));
4155 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
4157 skb_abort_seq_read(TS_SKB_CB(state));
4161 * skb_find_text - Find a text pattern in skb data
4162 * @skb: the buffer to look in
4163 * @from: search offset
4165 * @config: textsearch configuration
4167 * Finds a pattern in the skb data according to the specified
4168 * textsearch configuration. Use textsearch_next() to retrieve
4169 * subsequent occurrences of the pattern. Returns the offset
4170 * to the first occurrence or UINT_MAX if no match was found.
4172 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4173 unsigned int to, struct ts_config *config)
4175 struct ts_state state;
4178 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4180 config->get_next_block = skb_ts_get_next_block;
4181 config->finish = skb_ts_finish;
4183 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
4185 ret = textsearch_find(config, &state);
4186 return (ret <= to - from ? ret : UINT_MAX);
4188 EXPORT_SYMBOL(skb_find_text);
4190 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4191 int offset, size_t size)
4193 int i = skb_shinfo(skb)->nr_frags;
4195 if (skb_can_coalesce(skb, i, page, offset)) {
4196 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4197 } else if (i < MAX_SKB_FRAGS) {
4198 skb_zcopy_downgrade_managed(skb);
4200 skb_fill_page_desc_noacc(skb, i, page, offset, size);
4207 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4210 * skb_pull_rcsum - pull skb and update receive checksum
4211 * @skb: buffer to update
4212 * @len: length of data pulled
4214 * This function performs an skb_pull on the packet and updates
4215 * the CHECKSUM_COMPLETE checksum. It should be used on
4216 * receive path processing instead of skb_pull unless you know
4217 * that the checksum difference is zero (e.g., a valid IP header)
4218 * or you are setting ip_summed to CHECKSUM_NONE.
4220 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4222 unsigned char *data = skb->data;
4224 BUG_ON(len > skb->len);
4225 __skb_pull(skb, len);
4226 skb_postpull_rcsum(skb, data, len);
4229 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4231 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4233 skb_frag_t head_frag;
4236 page = virt_to_head_page(frag_skb->head);
4237 __skb_frag_set_page(&head_frag, page);
4238 skb_frag_off_set(&head_frag, frag_skb->data -
4239 (unsigned char *)page_address(page));
4240 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
4244 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4245 netdev_features_t features,
4246 unsigned int offset)
4248 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4249 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4250 unsigned int delta_truesize = 0;
4251 unsigned int delta_len = 0;
4252 struct sk_buff *tail = NULL;
4253 struct sk_buff *nskb, *tmp;
4256 skb_push(skb, -skb_network_offset(skb) + offset);
4258 skb_shinfo(skb)->frag_list = NULL;
4262 list_skb = list_skb->next;
4265 delta_truesize += nskb->truesize;
4266 if (skb_shared(nskb)) {
4267 tmp = skb_clone(nskb, GFP_ATOMIC);
4271 err = skb_unclone(nskb, GFP_ATOMIC);
4282 if (unlikely(err)) {
4283 nskb->next = list_skb;
4289 delta_len += nskb->len;
4291 skb_push(nskb, -skb_network_offset(nskb) + offset);
4293 skb_release_head_state(nskb);
4294 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4295 __copy_skb_header(nskb, skb);
4297 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4298 nskb->transport_header += len_diff;
4299 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4300 nskb->data - tnl_hlen,
4303 if (skb_needs_linearize(nskb, features) &&
4304 __skb_linearize(nskb))
4308 skb->truesize = skb->truesize - delta_truesize;
4309 skb->data_len = skb->data_len - delta_len;
4310 skb->len = skb->len - delta_len;
4316 if (skb_needs_linearize(skb, features) &&
4317 __skb_linearize(skb))
4325 kfree_skb_list(skb->next);
4327 return ERR_PTR(-ENOMEM);
4329 EXPORT_SYMBOL_GPL(skb_segment_list);
4332 * skb_segment - Perform protocol segmentation on skb.
4333 * @head_skb: buffer to segment
4334 * @features: features for the output path (see dev->features)
4336 * This function performs segmentation on the given skb. It returns
4337 * a pointer to the first in a list of new skbs for the segments.
4338 * In case of error it returns ERR_PTR(err).
4340 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4341 netdev_features_t features)
4343 struct sk_buff *segs = NULL;
4344 struct sk_buff *tail = NULL;
4345 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4346 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4347 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4348 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4349 struct sk_buff *frag_skb = head_skb;
4350 unsigned int offset = doffset;
4351 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4352 unsigned int partial_segs = 0;
4353 unsigned int headroom;
4354 unsigned int len = head_skb->len;
4357 int nfrags = skb_shinfo(head_skb)->nr_frags;
4362 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4363 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4364 struct sk_buff *check_skb;
4366 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4367 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4368 /* gso_size is untrusted, and we have a frag_list with
4369 * a linear non head_frag item.
4371 * If head_skb's headlen does not fit requested gso_size,
4372 * it means that the frag_list members do NOT terminate
4373 * on exact gso_size boundaries. Hence we cannot perform
4374 * skb_frag_t page sharing. Therefore we must fallback to
4375 * copying the frag_list skbs; we do so by disabling SG.
4377 features &= ~NETIF_F_SG;
4383 __skb_push(head_skb, doffset);
4384 proto = skb_network_protocol(head_skb, NULL);
4385 if (unlikely(!proto))
4386 return ERR_PTR(-EINVAL);
4388 sg = !!(features & NETIF_F_SG);
4389 csum = !!can_checksum_protocol(features, proto);
4391 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4392 if (!(features & NETIF_F_GSO_PARTIAL)) {
4393 struct sk_buff *iter;
4394 unsigned int frag_len;
4397 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4400 /* If we get here then all the required
4401 * GSO features except frag_list are supported.
4402 * Try to split the SKB to multiple GSO SKBs
4403 * with no frag_list.
4404 * Currently we can do that only when the buffers don't
4405 * have a linear part and all the buffers except
4406 * the last are of the same length.
4408 frag_len = list_skb->len;
4409 skb_walk_frags(head_skb, iter) {
4410 if (frag_len != iter->len && iter->next)
4412 if (skb_headlen(iter) && !iter->head_frag)
4418 if (len != frag_len)
4422 /* GSO partial only requires that we trim off any excess that
4423 * doesn't fit into an MSS sized block, so take care of that
4426 partial_segs = len / mss;
4427 if (partial_segs > 1)
4428 mss *= partial_segs;
4434 headroom = skb_headroom(head_skb);
4435 pos = skb_headlen(head_skb);
4438 struct sk_buff *nskb;
4439 skb_frag_t *nskb_frag;
4443 if (unlikely(mss == GSO_BY_FRAGS)) {
4444 len = list_skb->len;
4446 len = head_skb->len - offset;
4451 hsize = skb_headlen(head_skb) - offset;
4453 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4454 (skb_headlen(list_skb) == len || sg)) {
4455 BUG_ON(skb_headlen(list_skb) > len);
4458 nfrags = skb_shinfo(list_skb)->nr_frags;
4459 frag = skb_shinfo(list_skb)->frags;
4460 frag_skb = list_skb;
4461 pos += skb_headlen(list_skb);
4463 while (pos < offset + len) {
4464 BUG_ON(i >= nfrags);
4466 size = skb_frag_size(frag);
4467 if (pos + size > offset + len)
4475 nskb = skb_clone(list_skb, GFP_ATOMIC);
4476 list_skb = list_skb->next;
4478 if (unlikely(!nskb))
4481 if (unlikely(pskb_trim(nskb, len))) {
4486 hsize = skb_end_offset(nskb);
4487 if (skb_cow_head(nskb, doffset + headroom)) {
4492 nskb->truesize += skb_end_offset(nskb) - hsize;
4493 skb_release_head_state(nskb);
4494 __skb_push(nskb, doffset);
4498 if (hsize > len || !sg)
4501 nskb = __alloc_skb(hsize + doffset + headroom,
4502 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4505 if (unlikely(!nskb))
4508 skb_reserve(nskb, headroom);
4509 __skb_put(nskb, doffset);
4518 __copy_skb_header(nskb, head_skb);
4520 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4521 skb_reset_mac_len(nskb);
4523 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4524 nskb->data - tnl_hlen,
4525 doffset + tnl_hlen);
4527 if (nskb->len == len + doffset)
4528 goto perform_csum_check;
4532 if (!nskb->remcsum_offload)
4533 nskb->ip_summed = CHECKSUM_NONE;
4534 SKB_GSO_CB(nskb)->csum =
4535 skb_copy_and_csum_bits(head_skb, offset,
4539 SKB_GSO_CB(nskb)->csum_start =
4540 skb_headroom(nskb) + doffset;
4542 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4548 nskb_frag = skb_shinfo(nskb)->frags;
4550 skb_copy_from_linear_data_offset(head_skb, offset,
4551 skb_put(nskb, hsize), hsize);
4553 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4556 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4557 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4560 while (pos < offset + len) {
4563 nfrags = skb_shinfo(list_skb)->nr_frags;
4564 frag = skb_shinfo(list_skb)->frags;
4565 frag_skb = list_skb;
4566 if (!skb_headlen(list_skb)) {
4569 BUG_ON(!list_skb->head_frag);
4571 /* to make room for head_frag. */
4575 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4576 skb_zerocopy_clone(nskb, frag_skb,
4580 list_skb = list_skb->next;
4583 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4585 net_warn_ratelimited(
4586 "skb_segment: too many frags: %u %u\n",
4592 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4593 __skb_frag_ref(nskb_frag);
4594 size = skb_frag_size(nskb_frag);
4597 skb_frag_off_add(nskb_frag, offset - pos);
4598 skb_frag_size_sub(nskb_frag, offset - pos);
4601 skb_shinfo(nskb)->nr_frags++;
4603 if (pos + size <= offset + len) {
4608 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4616 nskb->data_len = len - hsize;
4617 nskb->len += nskb->data_len;
4618 nskb->truesize += nskb->data_len;
4622 if (skb_has_shared_frag(nskb) &&
4623 __skb_linearize(nskb))
4626 if (!nskb->remcsum_offload)
4627 nskb->ip_summed = CHECKSUM_NONE;
4628 SKB_GSO_CB(nskb)->csum =
4629 skb_checksum(nskb, doffset,
4630 nskb->len - doffset, 0);
4631 SKB_GSO_CB(nskb)->csum_start =
4632 skb_headroom(nskb) + doffset;
4634 } while ((offset += len) < head_skb->len);
4636 /* Some callers want to get the end of the list.
4637 * Put it in segs->prev to avoid walking the list.
4638 * (see validate_xmit_skb_list() for example)
4643 struct sk_buff *iter;
4644 int type = skb_shinfo(head_skb)->gso_type;
4645 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4647 /* Update type to add partial and then remove dodgy if set */
4648 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4649 type &= ~SKB_GSO_DODGY;
4651 /* Update GSO info and prepare to start updating headers on
4652 * our way back down the stack of protocols.
4654 for (iter = segs; iter; iter = iter->next) {
4655 skb_shinfo(iter)->gso_size = gso_size;
4656 skb_shinfo(iter)->gso_segs = partial_segs;
4657 skb_shinfo(iter)->gso_type = type;
4658 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4661 if (tail->len - doffset <= gso_size)
4662 skb_shinfo(tail)->gso_size = 0;
4663 else if (tail != segs)
4664 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4667 /* Following permits correct backpressure, for protocols
4668 * using skb_set_owner_w().
4669 * Idea is to tranfert ownership from head_skb to last segment.
4671 if (head_skb->destructor == sock_wfree) {
4672 swap(tail->truesize, head_skb->truesize);
4673 swap(tail->destructor, head_skb->destructor);
4674 swap(tail->sk, head_skb->sk);
4679 kfree_skb_list(segs);
4680 return ERR_PTR(err);
4682 EXPORT_SYMBOL_GPL(skb_segment);
4684 #ifdef CONFIG_SKB_EXTENSIONS
4685 #define SKB_EXT_ALIGN_VALUE 8
4686 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4688 static const u8 skb_ext_type_len[] = {
4689 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4690 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4693 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4695 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4696 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4698 #if IS_ENABLED(CONFIG_MPTCP)
4699 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4701 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4702 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4706 static __always_inline unsigned int skb_ext_total_length(void)
4708 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4709 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4710 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4713 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4715 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4716 skb_ext_type_len[TC_SKB_EXT] +
4718 #if IS_ENABLED(CONFIG_MPTCP)
4719 skb_ext_type_len[SKB_EXT_MPTCP] +
4721 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4722 skb_ext_type_len[SKB_EXT_MCTP] +
4727 static void skb_extensions_init(void)
4729 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4730 BUILD_BUG_ON(skb_ext_total_length() > 255);
4732 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4733 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4735 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4739 static void skb_extensions_init(void) {}
4742 void __init skb_init(void)
4744 skbuff_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4745 sizeof(struct sk_buff),
4747 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4748 offsetof(struct sk_buff, cb),
4749 sizeof_field(struct sk_buff, cb),
4751 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4752 sizeof(struct sk_buff_fclones),
4754 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4756 /* usercopy should only access first SKB_SMALL_HEAD_HEADROOM bytes.
4757 * struct skb_shared_info is located at the end of skb->head,
4758 * and should not be copied to/from user.
4760 skb_small_head_cache = kmem_cache_create_usercopy("skbuff_small_head",
4761 SKB_SMALL_HEAD_CACHE_SIZE,
4763 SLAB_HWCACHE_ALIGN | SLAB_PANIC,
4765 SKB_SMALL_HEAD_HEADROOM,
4767 skb_extensions_init();
4771 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4772 unsigned int recursion_level)
4774 int start = skb_headlen(skb);
4775 int i, copy = start - offset;
4776 struct sk_buff *frag_iter;
4779 if (unlikely(recursion_level >= 24))
4785 sg_set_buf(sg, skb->data + offset, copy);
4787 if ((len -= copy) == 0)
4792 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4795 WARN_ON(start > offset + len);
4797 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4798 if ((copy = end - offset) > 0) {
4799 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4800 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4805 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4806 skb_frag_off(frag) + offset - start);
4815 skb_walk_frags(skb, frag_iter) {
4818 WARN_ON(start > offset + len);
4820 end = start + frag_iter->len;
4821 if ((copy = end - offset) > 0) {
4822 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4827 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4828 copy, recursion_level + 1);
4829 if (unlikely(ret < 0))
4832 if ((len -= copy) == 0)
4843 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4844 * @skb: Socket buffer containing the buffers to be mapped
4845 * @sg: The scatter-gather list to map into
4846 * @offset: The offset into the buffer's contents to start mapping
4847 * @len: Length of buffer space to be mapped
4849 * Fill the specified scatter-gather list with mappings/pointers into a
4850 * region of the buffer space attached to a socket buffer. Returns either
4851 * the number of scatterlist items used, or -EMSGSIZE if the contents
4854 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4856 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4861 sg_mark_end(&sg[nsg - 1]);
4865 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4867 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4868 * sglist without mark the sg which contain last skb data as the end.
4869 * So the caller can mannipulate sg list as will when padding new data after
4870 * the first call without calling sg_unmark_end to expend sg list.
4872 * Scenario to use skb_to_sgvec_nomark:
4874 * 2. skb_to_sgvec_nomark(payload1)
4875 * 3. skb_to_sgvec_nomark(payload2)
4877 * This is equivalent to:
4879 * 2. skb_to_sgvec(payload1)
4881 * 4. skb_to_sgvec(payload2)
4883 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4884 * is more preferable.
4886 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4887 int offset, int len)
4889 return __skb_to_sgvec(skb, sg, offset, len, 0);
4891 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4896 * skb_cow_data - Check that a socket buffer's data buffers are writable
4897 * @skb: The socket buffer to check.
4898 * @tailbits: Amount of trailing space to be added
4899 * @trailer: Returned pointer to the skb where the @tailbits space begins
4901 * Make sure that the data buffers attached to a socket buffer are
4902 * writable. If they are not, private copies are made of the data buffers
4903 * and the socket buffer is set to use these instead.
4905 * If @tailbits is given, make sure that there is space to write @tailbits
4906 * bytes of data beyond current end of socket buffer. @trailer will be
4907 * set to point to the skb in which this space begins.
4909 * The number of scatterlist elements required to completely map the
4910 * COW'd and extended socket buffer will be returned.
4912 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4916 struct sk_buff *skb1, **skb_p;
4918 /* If skb is cloned or its head is paged, reallocate
4919 * head pulling out all the pages (pages are considered not writable
4920 * at the moment even if they are anonymous).
4922 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4923 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4926 /* Easy case. Most of packets will go this way. */
4927 if (!skb_has_frag_list(skb)) {
4928 /* A little of trouble, not enough of space for trailer.
4929 * This should not happen, when stack is tuned to generate
4930 * good frames. OK, on miss we reallocate and reserve even more
4931 * space, 128 bytes is fair. */
4933 if (skb_tailroom(skb) < tailbits &&
4934 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4942 /* Misery. We are in troubles, going to mincer fragments... */
4945 skb_p = &skb_shinfo(skb)->frag_list;
4948 while ((skb1 = *skb_p) != NULL) {
4951 /* The fragment is partially pulled by someone,
4952 * this can happen on input. Copy it and everything
4955 if (skb_shared(skb1))
4958 /* If the skb is the last, worry about trailer. */
4960 if (skb1->next == NULL && tailbits) {
4961 if (skb_shinfo(skb1)->nr_frags ||
4962 skb_has_frag_list(skb1) ||
4963 skb_tailroom(skb1) < tailbits)
4964 ntail = tailbits + 128;
4970 skb_shinfo(skb1)->nr_frags ||
4971 skb_has_frag_list(skb1)) {
4972 struct sk_buff *skb2;
4974 /* Fuck, we are miserable poor guys... */
4976 skb2 = skb_copy(skb1, GFP_ATOMIC);
4978 skb2 = skb_copy_expand(skb1,
4982 if (unlikely(skb2 == NULL))
4986 skb_set_owner_w(skb2, skb1->sk);
4988 /* Looking around. Are we still alive?
4989 * OK, link new skb, drop old one */
4991 skb2->next = skb1->next;
4998 skb_p = &skb1->next;
5003 EXPORT_SYMBOL_GPL(skb_cow_data);
5005 static void sock_rmem_free(struct sk_buff *skb)
5007 struct sock *sk = skb->sk;
5009 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
5012 static void skb_set_err_queue(struct sk_buff *skb)
5014 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
5015 * So, it is safe to (mis)use it to mark skbs on the error queue.
5017 skb->pkt_type = PACKET_OUTGOING;
5018 BUILD_BUG_ON(PACKET_OUTGOING == 0);
5022 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
5024 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
5026 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
5027 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
5032 skb->destructor = sock_rmem_free;
5033 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
5034 skb_set_err_queue(skb);
5036 /* before exiting rcu section, make sure dst is refcounted */
5039 skb_queue_tail(&sk->sk_error_queue, skb);
5040 if (!sock_flag(sk, SOCK_DEAD))
5041 sk_error_report(sk);
5044 EXPORT_SYMBOL(sock_queue_err_skb);
5046 static bool is_icmp_err_skb(const struct sk_buff *skb)
5048 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
5049 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
5052 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
5054 struct sk_buff_head *q = &sk->sk_error_queue;
5055 struct sk_buff *skb, *skb_next = NULL;
5056 bool icmp_next = false;
5057 unsigned long flags;
5059 spin_lock_irqsave(&q->lock, flags);
5060 skb = __skb_dequeue(q);
5061 if (skb && (skb_next = skb_peek(q))) {
5062 icmp_next = is_icmp_err_skb(skb_next);
5064 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
5066 spin_unlock_irqrestore(&q->lock, flags);
5068 if (is_icmp_err_skb(skb) && !icmp_next)
5072 sk_error_report(sk);
5076 EXPORT_SYMBOL(sock_dequeue_err_skb);
5079 * skb_clone_sk - create clone of skb, and take reference to socket
5080 * @skb: the skb to clone
5082 * This function creates a clone of a buffer that holds a reference on
5083 * sk_refcnt. Buffers created via this function are meant to be
5084 * returned using sock_queue_err_skb, or free via kfree_skb.
5086 * When passing buffers allocated with this function to sock_queue_err_skb
5087 * it is necessary to wrap the call with sock_hold/sock_put in order to
5088 * prevent the socket from being released prior to being enqueued on
5089 * the sk_error_queue.
5091 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
5093 struct sock *sk = skb->sk;
5094 struct sk_buff *clone;
5096 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
5099 clone = skb_clone(skb, GFP_ATOMIC);
5106 clone->destructor = sock_efree;
5110 EXPORT_SYMBOL(skb_clone_sk);
5112 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
5117 struct sock_exterr_skb *serr;
5120 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
5122 serr = SKB_EXT_ERR(skb);
5123 memset(serr, 0, sizeof(*serr));
5124 serr->ee.ee_errno = ENOMSG;
5125 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5126 serr->ee.ee_info = tstype;
5127 serr->opt_stats = opt_stats;
5128 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5129 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
5130 serr->ee.ee_data = skb_shinfo(skb)->tskey;
5132 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5135 err = sock_queue_err_skb(sk, skb);
5141 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5145 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5148 read_lock_bh(&sk->sk_callback_lock);
5149 ret = sk->sk_socket && sk->sk_socket->file &&
5150 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5151 read_unlock_bh(&sk->sk_callback_lock);
5155 void skb_complete_tx_timestamp(struct sk_buff *skb,
5156 struct skb_shared_hwtstamps *hwtstamps)
5158 struct sock *sk = skb->sk;
5160 if (!skb_may_tx_timestamp(sk, false))
5163 /* Take a reference to prevent skb_orphan() from freeing the socket,
5164 * but only if the socket refcount is not zero.
5166 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5167 *skb_hwtstamps(skb) = *hwtstamps;
5168 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5176 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5178 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5179 const struct sk_buff *ack_skb,
5180 struct skb_shared_hwtstamps *hwtstamps,
5181 struct sock *sk, int tstype)
5183 struct sk_buff *skb;
5184 bool tsonly, opt_stats = false;
5189 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5190 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5193 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5194 if (!skb_may_tx_timestamp(sk, tsonly))
5199 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5201 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5206 skb = alloc_skb(0, GFP_ATOMIC);
5208 skb = skb_clone(orig_skb, GFP_ATOMIC);
5210 if (skb_orphan_frags_rx(skb, GFP_ATOMIC))
5217 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5219 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5223 *skb_hwtstamps(skb) = *hwtstamps;
5225 __net_timestamp(skb);
5227 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5229 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5231 void skb_tstamp_tx(struct sk_buff *orig_skb,
5232 struct skb_shared_hwtstamps *hwtstamps)
5234 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5237 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5239 #ifdef CONFIG_WIRELESS
5240 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5242 struct sock *sk = skb->sk;
5243 struct sock_exterr_skb *serr;
5246 skb->wifi_acked_valid = 1;
5247 skb->wifi_acked = acked;
5249 serr = SKB_EXT_ERR(skb);
5250 memset(serr, 0, sizeof(*serr));
5251 serr->ee.ee_errno = ENOMSG;
5252 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5254 /* Take a reference to prevent skb_orphan() from freeing the socket,
5255 * but only if the socket refcount is not zero.
5257 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5258 err = sock_queue_err_skb(sk, skb);
5264 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5265 #endif /* CONFIG_WIRELESS */
5268 * skb_partial_csum_set - set up and verify partial csum values for packet
5269 * @skb: the skb to set
5270 * @start: the number of bytes after skb->data to start checksumming.
5271 * @off: the offset from start to place the checksum.
5273 * For untrusted partially-checksummed packets, we need to make sure the values
5274 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5276 * This function checks and sets those values and skb->ip_summed: if this
5277 * returns false you should drop the packet.
5279 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5281 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5282 u32 csum_start = skb_headroom(skb) + (u32)start;
5284 if (unlikely(csum_start >= U16_MAX || csum_end > skb_headlen(skb))) {
5285 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5286 start, off, skb_headroom(skb), skb_headlen(skb));
5289 skb->ip_summed = CHECKSUM_PARTIAL;
5290 skb->csum_start = csum_start;
5291 skb->csum_offset = off;
5292 skb->transport_header = csum_start;
5295 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5297 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5300 if (skb_headlen(skb) >= len)
5303 /* If we need to pullup then pullup to the max, so we
5304 * won't need to do it again.
5309 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5312 if (skb_headlen(skb) < len)
5318 #define MAX_TCP_HDR_LEN (15 * 4)
5320 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5321 typeof(IPPROTO_IP) proto,
5328 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5329 off + MAX_TCP_HDR_LEN);
5330 if (!err && !skb_partial_csum_set(skb, off,
5331 offsetof(struct tcphdr,
5334 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5337 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5338 off + sizeof(struct udphdr));
5339 if (!err && !skb_partial_csum_set(skb, off,
5340 offsetof(struct udphdr,
5343 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5346 return ERR_PTR(-EPROTO);
5349 /* This value should be large enough to cover a tagged ethernet header plus
5350 * maximally sized IP and TCP or UDP headers.
5352 #define MAX_IP_HDR_LEN 128
5354 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5363 err = skb_maybe_pull_tail(skb,
5364 sizeof(struct iphdr),
5369 if (ip_is_fragment(ip_hdr(skb)))
5372 off = ip_hdrlen(skb);
5379 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5381 return PTR_ERR(csum);
5384 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5387 ip_hdr(skb)->protocol, 0);
5394 /* This value should be large enough to cover a tagged ethernet header plus
5395 * an IPv6 header, all options, and a maximal TCP or UDP header.
5397 #define MAX_IPV6_HDR_LEN 256
5399 #define OPT_HDR(type, skb, off) \
5400 (type *)(skb_network_header(skb) + (off))
5402 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5415 off = sizeof(struct ipv6hdr);
5417 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5421 nexthdr = ipv6_hdr(skb)->nexthdr;
5423 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5424 while (off <= len && !done) {
5426 case IPPROTO_DSTOPTS:
5427 case IPPROTO_HOPOPTS:
5428 case IPPROTO_ROUTING: {
5429 struct ipv6_opt_hdr *hp;
5431 err = skb_maybe_pull_tail(skb,
5433 sizeof(struct ipv6_opt_hdr),
5438 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5439 nexthdr = hp->nexthdr;
5440 off += ipv6_optlen(hp);
5444 struct ip_auth_hdr *hp;
5446 err = skb_maybe_pull_tail(skb,
5448 sizeof(struct ip_auth_hdr),
5453 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5454 nexthdr = hp->nexthdr;
5455 off += ipv6_authlen(hp);
5458 case IPPROTO_FRAGMENT: {
5459 struct frag_hdr *hp;
5461 err = skb_maybe_pull_tail(skb,
5463 sizeof(struct frag_hdr),
5468 hp = OPT_HDR(struct frag_hdr, skb, off);
5470 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5473 nexthdr = hp->nexthdr;
5474 off += sizeof(struct frag_hdr);
5485 if (!done || fragment)
5488 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5490 return PTR_ERR(csum);
5493 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5494 &ipv6_hdr(skb)->daddr,
5495 skb->len - off, nexthdr, 0);
5503 * skb_checksum_setup - set up partial checksum offset
5504 * @skb: the skb to set up
5505 * @recalculate: if true the pseudo-header checksum will be recalculated
5507 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5511 switch (skb->protocol) {
5512 case htons(ETH_P_IP):
5513 err = skb_checksum_setup_ipv4(skb, recalculate);
5516 case htons(ETH_P_IPV6):
5517 err = skb_checksum_setup_ipv6(skb, recalculate);
5527 EXPORT_SYMBOL(skb_checksum_setup);
5530 * skb_checksum_maybe_trim - maybe trims the given skb
5531 * @skb: the skb to check
5532 * @transport_len: the data length beyond the network header
5534 * Checks whether the given skb has data beyond the given transport length.
5535 * If so, returns a cloned skb trimmed to this transport length.
5536 * Otherwise returns the provided skb. Returns NULL in error cases
5537 * (e.g. transport_len exceeds skb length or out-of-memory).
5539 * Caller needs to set the skb transport header and free any returned skb if it
5540 * differs from the provided skb.
5542 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5543 unsigned int transport_len)
5545 struct sk_buff *skb_chk;
5546 unsigned int len = skb_transport_offset(skb) + transport_len;
5551 else if (skb->len == len)
5554 skb_chk = skb_clone(skb, GFP_ATOMIC);
5558 ret = pskb_trim_rcsum(skb_chk, len);
5568 * skb_checksum_trimmed - validate checksum of an skb
5569 * @skb: the skb to check
5570 * @transport_len: the data length beyond the network header
5571 * @skb_chkf: checksum function to use
5573 * Applies the given checksum function skb_chkf to the provided skb.
5574 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5576 * If the skb has data beyond the given transport length, then a
5577 * trimmed & cloned skb is checked and returned.
5579 * Caller needs to set the skb transport header and free any returned skb if it
5580 * differs from the provided skb.
5582 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5583 unsigned int transport_len,
5584 __sum16(*skb_chkf)(struct sk_buff *skb))
5586 struct sk_buff *skb_chk;
5587 unsigned int offset = skb_transport_offset(skb);
5590 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5594 if (!pskb_may_pull(skb_chk, offset))
5597 skb_pull_rcsum(skb_chk, offset);
5598 ret = skb_chkf(skb_chk);
5599 skb_push_rcsum(skb_chk, offset);
5607 if (skb_chk && skb_chk != skb)
5613 EXPORT_SYMBOL(skb_checksum_trimmed);
5615 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5617 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5620 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5622 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5625 skb_release_head_state(skb);
5626 kmem_cache_free(skbuff_cache, skb);
5631 EXPORT_SYMBOL(kfree_skb_partial);
5634 * skb_try_coalesce - try to merge skb to prior one
5636 * @from: buffer to add
5637 * @fragstolen: pointer to boolean
5638 * @delta_truesize: how much more was allocated than was requested
5640 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5641 bool *fragstolen, int *delta_truesize)
5643 struct skb_shared_info *to_shinfo, *from_shinfo;
5644 int i, delta, len = from->len;
5646 *fragstolen = false;
5651 /* In general, avoid mixing page_pool and non-page_pool allocated
5652 * pages within the same SKB. Additionally avoid dealing with clones
5653 * with page_pool pages, in case the SKB is using page_pool fragment
5654 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5655 * references for cloned SKBs at the moment that would result in
5656 * inconsistent reference counts.
5657 * In theory we could take full references if @from is cloned and
5658 * !@to->pp_recycle but its tricky (due to potential race with
5659 * the clone disappearing) and rare, so not worth dealing with.
5661 if (to->pp_recycle != from->pp_recycle ||
5662 (from->pp_recycle && skb_cloned(from)))
5665 if (len <= skb_tailroom(to)) {
5667 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5668 *delta_truesize = 0;
5672 to_shinfo = skb_shinfo(to);
5673 from_shinfo = skb_shinfo(from);
5674 if (to_shinfo->frag_list || from_shinfo->frag_list)
5676 if (skb_zcopy(to) || skb_zcopy(from))
5679 if (skb_headlen(from) != 0) {
5681 unsigned int offset;
5683 if (to_shinfo->nr_frags +
5684 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5687 if (skb_head_is_locked(from))
5690 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5692 page = virt_to_head_page(from->head);
5693 offset = from->data - (unsigned char *)page_address(page);
5695 skb_fill_page_desc(to, to_shinfo->nr_frags,
5696 page, offset, skb_headlen(from));
5699 if (to_shinfo->nr_frags +
5700 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5703 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5706 WARN_ON_ONCE(delta < len);
5708 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5710 from_shinfo->nr_frags * sizeof(skb_frag_t));
5711 to_shinfo->nr_frags += from_shinfo->nr_frags;
5713 if (!skb_cloned(from))
5714 from_shinfo->nr_frags = 0;
5716 /* if the skb is not cloned this does nothing
5717 * since we set nr_frags to 0.
5719 for (i = 0; i < from_shinfo->nr_frags; i++)
5720 __skb_frag_ref(&from_shinfo->frags[i]);
5722 to->truesize += delta;
5724 to->data_len += len;
5726 *delta_truesize = delta;
5729 EXPORT_SYMBOL(skb_try_coalesce);
5732 * skb_scrub_packet - scrub an skb
5734 * @skb: buffer to clean
5735 * @xnet: packet is crossing netns
5737 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5738 * into/from a tunnel. Some information have to be cleared during these
5740 * skb_scrub_packet can also be used to clean a skb before injecting it in
5741 * another namespace (@xnet == true). We have to clear all information in the
5742 * skb that could impact namespace isolation.
5744 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5746 skb->pkt_type = PACKET_HOST;
5752 nf_reset_trace(skb);
5754 #ifdef CONFIG_NET_SWITCHDEV
5755 skb->offload_fwd_mark = 0;
5756 skb->offload_l3_fwd_mark = 0;
5764 skb_clear_tstamp(skb);
5766 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5769 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5773 * skb_gso_transport_seglen is used to determine the real size of the
5774 * individual segments, including Layer4 headers (TCP/UDP).
5776 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5778 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5780 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5781 unsigned int thlen = 0;
5783 if (skb->encapsulation) {
5784 thlen = skb_inner_transport_header(skb) -
5785 skb_transport_header(skb);
5787 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5788 thlen += inner_tcp_hdrlen(skb);
5789 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5790 thlen = tcp_hdrlen(skb);
5791 } else if (unlikely(skb_is_gso_sctp(skb))) {
5792 thlen = sizeof(struct sctphdr);
5793 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5794 thlen = sizeof(struct udphdr);
5796 /* UFO sets gso_size to the size of the fragmentation
5797 * payload, i.e. the size of the L4 (UDP) header is already
5800 return thlen + shinfo->gso_size;
5804 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5808 * skb_gso_network_seglen is used to determine the real size of the
5809 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5811 * The MAC/L2 header is not accounted for.
5813 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5815 unsigned int hdr_len = skb_transport_header(skb) -
5816 skb_network_header(skb);
5818 return hdr_len + skb_gso_transport_seglen(skb);
5822 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5826 * skb_gso_mac_seglen is used to determine the real size of the
5827 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5828 * headers (TCP/UDP).
5830 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5832 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5834 return hdr_len + skb_gso_transport_seglen(skb);
5838 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5840 * There are a couple of instances where we have a GSO skb, and we
5841 * want to determine what size it would be after it is segmented.
5843 * We might want to check:
5844 * - L3+L4+payload size (e.g. IP forwarding)
5845 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5847 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5851 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5852 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5854 * @max_len: The maximum permissible length.
5856 * Returns true if the segmented length <= max length.
5858 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5859 unsigned int seg_len,
5860 unsigned int max_len) {
5861 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5862 const struct sk_buff *iter;
5864 if (shinfo->gso_size != GSO_BY_FRAGS)
5865 return seg_len <= max_len;
5867 /* Undo this so we can re-use header sizes */
5868 seg_len -= GSO_BY_FRAGS;
5870 skb_walk_frags(skb, iter) {
5871 if (seg_len + skb_headlen(iter) > max_len)
5879 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5882 * @mtu: MTU to validate against
5884 * skb_gso_validate_network_len validates if a given skb will fit a
5885 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5888 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5890 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5892 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5895 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5898 * @len: length to validate against
5900 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5901 * length once split, including L2, L3 and L4 headers and the payload.
5903 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5905 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5907 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5909 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5911 int mac_len, meta_len;
5914 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5919 mac_len = skb->data - skb_mac_header(skb);
5920 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5921 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5922 mac_len - VLAN_HLEN - ETH_TLEN);
5925 meta_len = skb_metadata_len(skb);
5927 meta = skb_metadata_end(skb) - meta_len;
5928 memmove(meta + VLAN_HLEN, meta, meta_len);
5931 skb->mac_header += VLAN_HLEN;
5935 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5937 struct vlan_hdr *vhdr;
5940 if (unlikely(skb_vlan_tag_present(skb))) {
5941 /* vlan_tci is already set-up so leave this for another time */
5945 skb = skb_share_check(skb, GFP_ATOMIC);
5948 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5949 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5952 vhdr = (struct vlan_hdr *)skb->data;
5953 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5954 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5956 skb_pull_rcsum(skb, VLAN_HLEN);
5957 vlan_set_encap_proto(skb, vhdr);
5959 skb = skb_reorder_vlan_header(skb);
5963 skb_reset_network_header(skb);
5964 if (!skb_transport_header_was_set(skb))
5965 skb_reset_transport_header(skb);
5966 skb_reset_mac_len(skb);
5974 EXPORT_SYMBOL(skb_vlan_untag);
5976 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5978 if (!pskb_may_pull(skb, write_len))
5981 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5984 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5986 EXPORT_SYMBOL(skb_ensure_writable);
5988 /* remove VLAN header from packet and update csum accordingly.
5989 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5991 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5993 int offset = skb->data - skb_mac_header(skb);
5996 if (WARN_ONCE(offset,
5997 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
6002 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
6006 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6008 vlan_remove_tag(skb, vlan_tci);
6010 skb->mac_header += VLAN_HLEN;
6012 if (skb_network_offset(skb) < ETH_HLEN)
6013 skb_set_network_header(skb, ETH_HLEN);
6015 skb_reset_mac_len(skb);
6019 EXPORT_SYMBOL(__skb_vlan_pop);
6021 /* Pop a vlan tag either from hwaccel or from payload.
6022 * Expects skb->data at mac header.
6024 int skb_vlan_pop(struct sk_buff *skb)
6030 if (likely(skb_vlan_tag_present(skb))) {
6031 __vlan_hwaccel_clear_tag(skb);
6033 if (unlikely(!eth_type_vlan(skb->protocol)))
6036 err = __skb_vlan_pop(skb, &vlan_tci);
6040 /* move next vlan tag to hw accel tag */
6041 if (likely(!eth_type_vlan(skb->protocol)))
6044 vlan_proto = skb->protocol;
6045 err = __skb_vlan_pop(skb, &vlan_tci);
6049 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6052 EXPORT_SYMBOL(skb_vlan_pop);
6054 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
6055 * Expects skb->data at mac header.
6057 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
6059 if (skb_vlan_tag_present(skb)) {
6060 int offset = skb->data - skb_mac_header(skb);
6063 if (WARN_ONCE(offset,
6064 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
6069 err = __vlan_insert_tag(skb, skb->vlan_proto,
6070 skb_vlan_tag_get(skb));
6074 skb->protocol = skb->vlan_proto;
6075 skb->mac_len += VLAN_HLEN;
6077 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6079 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6082 EXPORT_SYMBOL(skb_vlan_push);
6085 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
6087 * @skb: Socket buffer to modify
6089 * Drop the Ethernet header of @skb.
6091 * Expects that skb->data points to the mac header and that no VLAN tags are
6094 * Returns 0 on success, -errno otherwise.
6096 int skb_eth_pop(struct sk_buff *skb)
6098 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
6099 skb_network_offset(skb) < ETH_HLEN)
6102 skb_pull_rcsum(skb, ETH_HLEN);
6103 skb_reset_mac_header(skb);
6104 skb_reset_mac_len(skb);
6108 EXPORT_SYMBOL(skb_eth_pop);
6111 * skb_eth_push() - Add a new Ethernet header at the head of a packet
6113 * @skb: Socket buffer to modify
6114 * @dst: Destination MAC address of the new header
6115 * @src: Source MAC address of the new header
6117 * Prepend @skb with a new Ethernet header.
6119 * Expects that skb->data points to the mac header, which must be empty.
6121 * Returns 0 on success, -errno otherwise.
6123 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6124 const unsigned char *src)
6129 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6132 err = skb_cow_head(skb, sizeof(*eth));
6136 skb_push(skb, sizeof(*eth));
6137 skb_reset_mac_header(skb);
6138 skb_reset_mac_len(skb);
6141 ether_addr_copy(eth->h_dest, dst);
6142 ether_addr_copy(eth->h_source, src);
6143 eth->h_proto = skb->protocol;
6145 skb_postpush_rcsum(skb, eth, sizeof(*eth));
6149 EXPORT_SYMBOL(skb_eth_push);
6151 /* Update the ethertype of hdr and the skb csum value if required. */
6152 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6155 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6156 __be16 diff[] = { ~hdr->h_proto, ethertype };
6158 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6161 hdr->h_proto = ethertype;
6165 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6169 * @mpls_lse: MPLS label stack entry to push
6170 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6171 * @mac_len: length of the MAC header
6172 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6175 * Expects skb->data at mac header.
6177 * Returns 0 on success, -errno otherwise.
6179 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6180 int mac_len, bool ethernet)
6182 struct mpls_shim_hdr *lse;
6185 if (unlikely(!eth_p_mpls(mpls_proto)))
6188 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6189 if (skb->encapsulation)
6192 err = skb_cow_head(skb, MPLS_HLEN);
6196 if (!skb->inner_protocol) {
6197 skb_set_inner_network_header(skb, skb_network_offset(skb));
6198 skb_set_inner_protocol(skb, skb->protocol);
6201 skb_push(skb, MPLS_HLEN);
6202 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6204 skb_reset_mac_header(skb);
6205 skb_set_network_header(skb, mac_len);
6206 skb_reset_mac_len(skb);
6208 lse = mpls_hdr(skb);
6209 lse->label_stack_entry = mpls_lse;
6210 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6212 if (ethernet && mac_len >= ETH_HLEN)
6213 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6214 skb->protocol = mpls_proto;
6218 EXPORT_SYMBOL_GPL(skb_mpls_push);
6221 * skb_mpls_pop() - pop the outermost MPLS header
6224 * @next_proto: ethertype of header after popped MPLS header
6225 * @mac_len: length of the MAC header
6226 * @ethernet: flag to indicate if the packet is ethernet
6228 * Expects skb->data at mac header.
6230 * Returns 0 on success, -errno otherwise.
6232 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6237 if (unlikely(!eth_p_mpls(skb->protocol)))
6240 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6244 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6245 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6248 __skb_pull(skb, MPLS_HLEN);
6249 skb_reset_mac_header(skb);
6250 skb_set_network_header(skb, mac_len);
6252 if (ethernet && mac_len >= ETH_HLEN) {
6255 /* use mpls_hdr() to get ethertype to account for VLANs. */
6256 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6257 skb_mod_eth_type(skb, hdr, next_proto);
6259 skb->protocol = next_proto;
6263 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6266 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6269 * @mpls_lse: new MPLS label stack entry to update to
6271 * Expects skb->data at mac header.
6273 * Returns 0 on success, -errno otherwise.
6275 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6279 if (unlikely(!eth_p_mpls(skb->protocol)))
6282 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6286 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6287 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6289 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6292 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6296 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6299 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6303 * Expects skb->data at mac header.
6305 * Returns 0 on success, -errno otherwise.
6307 int skb_mpls_dec_ttl(struct sk_buff *skb)
6312 if (unlikely(!eth_p_mpls(skb->protocol)))
6315 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6318 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6319 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6323 lse &= ~MPLS_LS_TTL_MASK;
6324 lse |= ttl << MPLS_LS_TTL_SHIFT;
6326 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6328 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6331 * alloc_skb_with_frags - allocate skb with page frags
6333 * @header_len: size of linear part
6334 * @data_len: needed length in frags
6335 * @max_page_order: max page order desired.
6336 * @errcode: pointer to error code if any
6337 * @gfp_mask: allocation mask
6339 * This can be used to allocate a paged skb, given a maximal order for frags.
6341 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6342 unsigned long data_len,
6347 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6348 unsigned long chunk;
6349 struct sk_buff *skb;
6353 *errcode = -EMSGSIZE;
6354 /* Note this test could be relaxed, if we succeed to allocate
6355 * high order pages...
6357 if (npages > MAX_SKB_FRAGS)
6360 *errcode = -ENOBUFS;
6361 skb = alloc_skb(header_len, gfp_mask);
6365 skb->truesize += npages << PAGE_SHIFT;
6367 for (i = 0; npages > 0; i++) {
6368 int order = max_page_order;
6371 if (npages >= 1 << order) {
6372 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6378 /* Do not retry other high order allocations */
6384 page = alloc_page(gfp_mask);
6388 chunk = min_t(unsigned long, data_len,
6389 PAGE_SIZE << order);
6390 skb_fill_page_desc(skb, i, page, 0, chunk);
6392 npages -= 1 << order;
6400 EXPORT_SYMBOL(alloc_skb_with_frags);
6402 /* carve out the first off bytes from skb when off < headlen */
6403 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6404 const int headlen, gfp_t gfp_mask)
6407 unsigned int size = skb_end_offset(skb);
6408 int new_hlen = headlen - off;
6411 if (skb_pfmemalloc(skb))
6412 gfp_mask |= __GFP_MEMALLOC;
6414 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6417 size = SKB_WITH_OVERHEAD(size);
6419 /* Copy real data, and all frags */
6420 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6423 memcpy((struct skb_shared_info *)(data + size),
6425 offsetof(struct skb_shared_info,
6426 frags[skb_shinfo(skb)->nr_frags]));
6427 if (skb_cloned(skb)) {
6428 /* drop the old head gracefully */
6429 if (skb_orphan_frags(skb, gfp_mask)) {
6430 skb_kfree_head(data, size);
6433 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6434 skb_frag_ref(skb, i);
6435 if (skb_has_frag_list(skb))
6436 skb_clone_fraglist(skb);
6437 skb_release_data(skb, SKB_CONSUMED, false);
6439 /* we can reuse existing recount- all we did was
6442 skb_free_head(skb, false);
6448 skb_set_end_offset(skb, size);
6449 skb_set_tail_pointer(skb, skb_headlen(skb));
6450 skb_headers_offset_update(skb, 0);
6454 atomic_set(&skb_shinfo(skb)->dataref, 1);
6459 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6461 /* carve out the first eat bytes from skb's frag_list. May recurse into
6464 static int pskb_carve_frag_list(struct sk_buff *skb,
6465 struct skb_shared_info *shinfo, int eat,
6468 struct sk_buff *list = shinfo->frag_list;
6469 struct sk_buff *clone = NULL;
6470 struct sk_buff *insp = NULL;
6474 pr_err("Not enough bytes to eat. Want %d\n", eat);
6477 if (list->len <= eat) {
6478 /* Eaten as whole. */
6483 /* Eaten partially. */
6484 if (skb_shared(list)) {
6485 clone = skb_clone(list, gfp_mask);
6491 /* This may be pulled without problems. */
6494 if (pskb_carve(list, eat, gfp_mask) < 0) {
6502 /* Free pulled out fragments. */
6503 while ((list = shinfo->frag_list) != insp) {
6504 shinfo->frag_list = list->next;
6507 /* And insert new clone at head. */
6510 shinfo->frag_list = clone;
6515 /* carve off first len bytes from skb. Split line (off) is in the
6516 * non-linear part of skb
6518 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6519 int pos, gfp_t gfp_mask)
6522 unsigned int size = skb_end_offset(skb);
6524 const int nfrags = skb_shinfo(skb)->nr_frags;
6525 struct skb_shared_info *shinfo;
6527 if (skb_pfmemalloc(skb))
6528 gfp_mask |= __GFP_MEMALLOC;
6530 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6533 size = SKB_WITH_OVERHEAD(size);
6535 memcpy((struct skb_shared_info *)(data + size),
6536 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6537 if (skb_orphan_frags(skb, gfp_mask)) {
6538 skb_kfree_head(data, size);
6541 shinfo = (struct skb_shared_info *)(data + size);
6542 for (i = 0; i < nfrags; i++) {
6543 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6545 if (pos + fsize > off) {
6546 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6550 * We have two variants in this case:
6551 * 1. Move all the frag to the second
6552 * part, if it is possible. F.e.
6553 * this approach is mandatory for TUX,
6554 * where splitting is expensive.
6555 * 2. Split is accurately. We make this.
6557 skb_frag_off_add(&shinfo->frags[0], off - pos);
6558 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6560 skb_frag_ref(skb, i);
6565 shinfo->nr_frags = k;
6566 if (skb_has_frag_list(skb))
6567 skb_clone_fraglist(skb);
6569 /* split line is in frag list */
6570 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6571 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6572 if (skb_has_frag_list(skb))
6573 kfree_skb_list(skb_shinfo(skb)->frag_list);
6574 skb_kfree_head(data, size);
6577 skb_release_data(skb, SKB_CONSUMED, false);
6582 skb_set_end_offset(skb, size);
6583 skb_reset_tail_pointer(skb);
6584 skb_headers_offset_update(skb, 0);
6589 skb->data_len = skb->len;
6590 atomic_set(&skb_shinfo(skb)->dataref, 1);
6594 /* remove len bytes from the beginning of the skb */
6595 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6597 int headlen = skb_headlen(skb);
6600 return pskb_carve_inside_header(skb, len, headlen, gfp);
6602 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6605 /* Extract to_copy bytes starting at off from skb, and return this in
6608 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6609 int to_copy, gfp_t gfp)
6611 struct sk_buff *clone = skb_clone(skb, gfp);
6616 if (pskb_carve(clone, off, gfp) < 0 ||
6617 pskb_trim(clone, to_copy)) {
6623 EXPORT_SYMBOL(pskb_extract);
6626 * skb_condense - try to get rid of fragments/frag_list if possible
6629 * Can be used to save memory before skb is added to a busy queue.
6630 * If packet has bytes in frags and enough tail room in skb->head,
6631 * pull all of them, so that we can free the frags right now and adjust
6634 * We do not reallocate skb->head thus can not fail.
6635 * Caller must re-evaluate skb->truesize if needed.
6637 void skb_condense(struct sk_buff *skb)
6639 if (skb->data_len) {
6640 if (skb->data_len > skb->end - skb->tail ||
6644 /* Nice, we can free page frag(s) right now */
6645 __pskb_pull_tail(skb, skb->data_len);
6647 /* At this point, skb->truesize might be over estimated,
6648 * because skb had a fragment, and fragments do not tell
6650 * When we pulled its content into skb->head, fragment
6651 * was freed, but __pskb_pull_tail() could not possibly
6652 * adjust skb->truesize, not knowing the frag truesize.
6654 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6656 EXPORT_SYMBOL(skb_condense);
6658 #ifdef CONFIG_SKB_EXTENSIONS
6659 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6661 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6665 * __skb_ext_alloc - allocate a new skb extensions storage
6667 * @flags: See kmalloc().
6669 * Returns the newly allocated pointer. The pointer can later attached to a
6670 * skb via __skb_ext_set().
6671 * Note: caller must handle the skb_ext as an opaque data.
6673 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6675 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6678 memset(new->offset, 0, sizeof(new->offset));
6679 refcount_set(&new->refcnt, 1);
6685 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6686 unsigned int old_active)
6688 struct skb_ext *new;
6690 if (refcount_read(&old->refcnt) == 1)
6693 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6697 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6698 refcount_set(&new->refcnt, 1);
6701 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6702 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6705 for (i = 0; i < sp->len; i++)
6706 xfrm_state_hold(sp->xvec[i]);
6714 * __skb_ext_set - attach the specified extension storage to this skb
6717 * @ext: extension storage previously allocated via __skb_ext_alloc()
6719 * Existing extensions, if any, are cleared.
6721 * Returns the pointer to the extension.
6723 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6724 struct skb_ext *ext)
6726 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6729 newlen = newoff + skb_ext_type_len[id];
6730 ext->chunks = newlen;
6731 ext->offset[id] = newoff;
6732 skb->extensions = ext;
6733 skb->active_extensions = 1 << id;
6734 return skb_ext_get_ptr(ext, id);
6738 * skb_ext_add - allocate space for given extension, COW if needed
6740 * @id: extension to allocate space for
6742 * Allocates enough space for the given extension.
6743 * If the extension is already present, a pointer to that extension
6746 * If the skb was cloned, COW applies and the returned memory can be
6747 * modified without changing the extension space of clones buffers.
6749 * Returns pointer to the extension or NULL on allocation failure.
6751 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6753 struct skb_ext *new, *old = NULL;
6754 unsigned int newlen, newoff;
6756 if (skb->active_extensions) {
6757 old = skb->extensions;
6759 new = skb_ext_maybe_cow(old, skb->active_extensions);
6763 if (__skb_ext_exist(new, id))
6766 newoff = new->chunks;
6768 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6770 new = __skb_ext_alloc(GFP_ATOMIC);
6775 newlen = newoff + skb_ext_type_len[id];
6776 new->chunks = newlen;
6777 new->offset[id] = newoff;
6780 skb->extensions = new;
6781 skb->active_extensions |= 1 << id;
6782 return skb_ext_get_ptr(new, id);
6784 EXPORT_SYMBOL(skb_ext_add);
6787 static void skb_ext_put_sp(struct sec_path *sp)
6791 for (i = 0; i < sp->len; i++)
6792 xfrm_state_put(sp->xvec[i]);
6796 #ifdef CONFIG_MCTP_FLOWS
6797 static void skb_ext_put_mctp(struct mctp_flow *flow)
6800 mctp_key_unref(flow->key);
6804 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6806 struct skb_ext *ext = skb->extensions;
6808 skb->active_extensions &= ~(1 << id);
6809 if (skb->active_extensions == 0) {
6810 skb->extensions = NULL;
6813 } else if (id == SKB_EXT_SEC_PATH &&
6814 refcount_read(&ext->refcnt) == 1) {
6815 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6822 EXPORT_SYMBOL(__skb_ext_del);
6824 void __skb_ext_put(struct skb_ext *ext)
6826 /* If this is last clone, nothing can increment
6827 * it after check passes. Avoids one atomic op.
6829 if (refcount_read(&ext->refcnt) == 1)
6832 if (!refcount_dec_and_test(&ext->refcnt))
6836 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6837 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6839 #ifdef CONFIG_MCTP_FLOWS
6840 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6841 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6844 kmem_cache_free(skbuff_ext_cache, ext);
6846 EXPORT_SYMBOL(__skb_ext_put);
6847 #endif /* CONFIG_SKB_EXTENSIONS */
6850 * skb_attempt_defer_free - queue skb for remote freeing
6853 * Put @skb in a per-cpu list, using the cpu which
6854 * allocated the skb/pages to reduce false sharing
6855 * and memory zone spinlock contention.
6857 void skb_attempt_defer_free(struct sk_buff *skb)
6859 int cpu = skb->alloc_cpu;
6860 struct softnet_data *sd;
6861 unsigned int defer_max;
6864 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6866 cpu == raw_smp_processor_id()) {
6867 nodefer: __kfree_skb(skb);
6871 DEBUG_NET_WARN_ON_ONCE(skb_dst(skb));
6872 DEBUG_NET_WARN_ON_ONCE(skb->destructor);
6874 sd = &per_cpu(softnet_data, cpu);
6875 defer_max = READ_ONCE(sysctl_skb_defer_max);
6876 if (READ_ONCE(sd->defer_count) >= defer_max)
6879 spin_lock_bh(&sd->defer_lock);
6880 /* Send an IPI every time queue reaches half capacity. */
6881 kick = sd->defer_count == (defer_max >> 1);
6882 /* Paired with the READ_ONCE() few lines above */
6883 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6885 skb->next = sd->defer_list;
6886 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6887 WRITE_ONCE(sd->defer_list, skb);
6888 spin_unlock_bh(&sd->defer_lock);
6890 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6891 * if we are unlucky enough (this seems very unlikely).
6893 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6894 smp_call_function_single_async(cpu, &sd->defer_csd);