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, size_t max_frags)
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_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_fill_page_desc(&head_frag, page, frag_skb->data -
4238 (unsigned char *)page_address(page),
4239 skb_headlen(frag_skb));
4243 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4244 netdev_features_t features,
4245 unsigned int offset)
4247 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4248 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4249 unsigned int delta_truesize = 0;
4250 unsigned int delta_len = 0;
4251 struct sk_buff *tail = NULL;
4252 struct sk_buff *nskb, *tmp;
4255 skb_push(skb, -skb_network_offset(skb) + offset);
4257 skb_shinfo(skb)->frag_list = NULL;
4261 list_skb = list_skb->next;
4264 delta_truesize += nskb->truesize;
4265 if (skb_shared(nskb)) {
4266 tmp = skb_clone(nskb, GFP_ATOMIC);
4270 err = skb_unclone(nskb, GFP_ATOMIC);
4281 if (unlikely(err)) {
4282 nskb->next = list_skb;
4288 delta_len += nskb->len;
4290 skb_push(nskb, -skb_network_offset(nskb) + offset);
4292 skb_release_head_state(nskb);
4293 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4294 __copy_skb_header(nskb, skb);
4296 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4297 nskb->transport_header += len_diff;
4298 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4299 nskb->data - tnl_hlen,
4302 if (skb_needs_linearize(nskb, features) &&
4303 __skb_linearize(nskb))
4307 skb->truesize = skb->truesize - delta_truesize;
4308 skb->data_len = skb->data_len - delta_len;
4309 skb->len = skb->len - delta_len;
4315 if (skb_needs_linearize(skb, features) &&
4316 __skb_linearize(skb))
4324 kfree_skb_list(skb->next);
4326 return ERR_PTR(-ENOMEM);
4328 EXPORT_SYMBOL_GPL(skb_segment_list);
4331 * skb_segment - Perform protocol segmentation on skb.
4332 * @head_skb: buffer to segment
4333 * @features: features for the output path (see dev->features)
4335 * This function performs segmentation on the given skb. It returns
4336 * a pointer to the first in a list of new skbs for the segments.
4337 * In case of error it returns ERR_PTR(err).
4339 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4340 netdev_features_t features)
4342 struct sk_buff *segs = NULL;
4343 struct sk_buff *tail = NULL;
4344 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4345 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4346 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4347 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4348 struct sk_buff *frag_skb = head_skb;
4349 unsigned int offset = doffset;
4350 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4351 unsigned int partial_segs = 0;
4352 unsigned int headroom;
4353 unsigned int len = head_skb->len;
4356 int nfrags = skb_shinfo(head_skb)->nr_frags;
4361 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4362 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4363 struct sk_buff *check_skb;
4365 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4366 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4367 /* gso_size is untrusted, and we have a frag_list with
4368 * a linear non head_frag item.
4370 * If head_skb's headlen does not fit requested gso_size,
4371 * it means that the frag_list members do NOT terminate
4372 * on exact gso_size boundaries. Hence we cannot perform
4373 * skb_frag_t page sharing. Therefore we must fallback to
4374 * copying the frag_list skbs; we do so by disabling SG.
4376 features &= ~NETIF_F_SG;
4382 __skb_push(head_skb, doffset);
4383 proto = skb_network_protocol(head_skb, NULL);
4384 if (unlikely(!proto))
4385 return ERR_PTR(-EINVAL);
4387 sg = !!(features & NETIF_F_SG);
4388 csum = !!can_checksum_protocol(features, proto);
4390 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4391 if (!(features & NETIF_F_GSO_PARTIAL)) {
4392 struct sk_buff *iter;
4393 unsigned int frag_len;
4396 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4399 /* If we get here then all the required
4400 * GSO features except frag_list are supported.
4401 * Try to split the SKB to multiple GSO SKBs
4402 * with no frag_list.
4403 * Currently we can do that only when the buffers don't
4404 * have a linear part and all the buffers except
4405 * the last are of the same length.
4407 frag_len = list_skb->len;
4408 skb_walk_frags(head_skb, iter) {
4409 if (frag_len != iter->len && iter->next)
4411 if (skb_headlen(iter) && !iter->head_frag)
4417 if (len != frag_len)
4421 /* GSO partial only requires that we trim off any excess that
4422 * doesn't fit into an MSS sized block, so take care of that
4425 partial_segs = len / mss;
4426 if (partial_segs > 1)
4427 mss *= partial_segs;
4433 headroom = skb_headroom(head_skb);
4434 pos = skb_headlen(head_skb);
4437 struct sk_buff *nskb;
4438 skb_frag_t *nskb_frag;
4442 if (unlikely(mss == GSO_BY_FRAGS)) {
4443 len = list_skb->len;
4445 len = head_skb->len - offset;
4450 hsize = skb_headlen(head_skb) - offset;
4452 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4453 (skb_headlen(list_skb) == len || sg)) {
4454 BUG_ON(skb_headlen(list_skb) > len);
4457 nfrags = skb_shinfo(list_skb)->nr_frags;
4458 frag = skb_shinfo(list_skb)->frags;
4459 frag_skb = list_skb;
4460 pos += skb_headlen(list_skb);
4462 while (pos < offset + len) {
4463 BUG_ON(i >= nfrags);
4465 size = skb_frag_size(frag);
4466 if (pos + size > offset + len)
4474 nskb = skb_clone(list_skb, GFP_ATOMIC);
4475 list_skb = list_skb->next;
4477 if (unlikely(!nskb))
4480 if (unlikely(pskb_trim(nskb, len))) {
4485 hsize = skb_end_offset(nskb);
4486 if (skb_cow_head(nskb, doffset + headroom)) {
4491 nskb->truesize += skb_end_offset(nskb) - hsize;
4492 skb_release_head_state(nskb);
4493 __skb_push(nskb, doffset);
4497 if (hsize > len || !sg)
4500 nskb = __alloc_skb(hsize + doffset + headroom,
4501 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4504 if (unlikely(!nskb))
4507 skb_reserve(nskb, headroom);
4508 __skb_put(nskb, doffset);
4517 __copy_skb_header(nskb, head_skb);
4519 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4520 skb_reset_mac_len(nskb);
4522 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4523 nskb->data - tnl_hlen,
4524 doffset + tnl_hlen);
4526 if (nskb->len == len + doffset)
4527 goto perform_csum_check;
4531 if (!nskb->remcsum_offload)
4532 nskb->ip_summed = CHECKSUM_NONE;
4533 SKB_GSO_CB(nskb)->csum =
4534 skb_copy_and_csum_bits(head_skb, offset,
4538 SKB_GSO_CB(nskb)->csum_start =
4539 skb_headroom(nskb) + doffset;
4541 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4547 nskb_frag = skb_shinfo(nskb)->frags;
4549 skb_copy_from_linear_data_offset(head_skb, offset,
4550 skb_put(nskb, hsize), hsize);
4552 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4555 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4556 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4559 while (pos < offset + len) {
4562 nfrags = skb_shinfo(list_skb)->nr_frags;
4563 frag = skb_shinfo(list_skb)->frags;
4564 frag_skb = list_skb;
4565 if (!skb_headlen(list_skb)) {
4568 BUG_ON(!list_skb->head_frag);
4570 /* to make room for head_frag. */
4574 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4575 skb_zerocopy_clone(nskb, frag_skb,
4579 list_skb = list_skb->next;
4582 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4584 net_warn_ratelimited(
4585 "skb_segment: too many frags: %u %u\n",
4591 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4592 __skb_frag_ref(nskb_frag);
4593 size = skb_frag_size(nskb_frag);
4596 skb_frag_off_add(nskb_frag, offset - pos);
4597 skb_frag_size_sub(nskb_frag, offset - pos);
4600 skb_shinfo(nskb)->nr_frags++;
4602 if (pos + size <= offset + len) {
4607 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4615 nskb->data_len = len - hsize;
4616 nskb->len += nskb->data_len;
4617 nskb->truesize += nskb->data_len;
4621 if (skb_has_shared_frag(nskb) &&
4622 __skb_linearize(nskb))
4625 if (!nskb->remcsum_offload)
4626 nskb->ip_summed = CHECKSUM_NONE;
4627 SKB_GSO_CB(nskb)->csum =
4628 skb_checksum(nskb, doffset,
4629 nskb->len - doffset, 0);
4630 SKB_GSO_CB(nskb)->csum_start =
4631 skb_headroom(nskb) + doffset;
4633 } while ((offset += len) < head_skb->len);
4635 /* Some callers want to get the end of the list.
4636 * Put it in segs->prev to avoid walking the list.
4637 * (see validate_xmit_skb_list() for example)
4642 struct sk_buff *iter;
4643 int type = skb_shinfo(head_skb)->gso_type;
4644 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4646 /* Update type to add partial and then remove dodgy if set */
4647 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4648 type &= ~SKB_GSO_DODGY;
4650 /* Update GSO info and prepare to start updating headers on
4651 * our way back down the stack of protocols.
4653 for (iter = segs; iter; iter = iter->next) {
4654 skb_shinfo(iter)->gso_size = gso_size;
4655 skb_shinfo(iter)->gso_segs = partial_segs;
4656 skb_shinfo(iter)->gso_type = type;
4657 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4660 if (tail->len - doffset <= gso_size)
4661 skb_shinfo(tail)->gso_size = 0;
4662 else if (tail != segs)
4663 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4666 /* Following permits correct backpressure, for protocols
4667 * using skb_set_owner_w().
4668 * Idea is to tranfert ownership from head_skb to last segment.
4670 if (head_skb->destructor == sock_wfree) {
4671 swap(tail->truesize, head_skb->truesize);
4672 swap(tail->destructor, head_skb->destructor);
4673 swap(tail->sk, head_skb->sk);
4678 kfree_skb_list(segs);
4679 return ERR_PTR(err);
4681 EXPORT_SYMBOL_GPL(skb_segment);
4683 #ifdef CONFIG_SKB_EXTENSIONS
4684 #define SKB_EXT_ALIGN_VALUE 8
4685 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4687 static const u8 skb_ext_type_len[] = {
4688 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4689 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4692 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4694 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4695 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4697 #if IS_ENABLED(CONFIG_MPTCP)
4698 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4700 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4701 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4705 static __always_inline unsigned int skb_ext_total_length(void)
4707 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4708 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4709 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4712 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4714 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4715 skb_ext_type_len[TC_SKB_EXT] +
4717 #if IS_ENABLED(CONFIG_MPTCP)
4718 skb_ext_type_len[SKB_EXT_MPTCP] +
4720 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4721 skb_ext_type_len[SKB_EXT_MCTP] +
4726 static void skb_extensions_init(void)
4728 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4729 BUILD_BUG_ON(skb_ext_total_length() > 255);
4731 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4732 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4734 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4738 static void skb_extensions_init(void) {}
4741 void __init skb_init(void)
4743 skbuff_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4744 sizeof(struct sk_buff),
4746 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4747 offsetof(struct sk_buff, cb),
4748 sizeof_field(struct sk_buff, cb),
4750 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4751 sizeof(struct sk_buff_fclones),
4753 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4755 /* usercopy should only access first SKB_SMALL_HEAD_HEADROOM bytes.
4756 * struct skb_shared_info is located at the end of skb->head,
4757 * and should not be copied to/from user.
4759 skb_small_head_cache = kmem_cache_create_usercopy("skbuff_small_head",
4760 SKB_SMALL_HEAD_CACHE_SIZE,
4762 SLAB_HWCACHE_ALIGN | SLAB_PANIC,
4764 SKB_SMALL_HEAD_HEADROOM,
4766 skb_extensions_init();
4770 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4771 unsigned int recursion_level)
4773 int start = skb_headlen(skb);
4774 int i, copy = start - offset;
4775 struct sk_buff *frag_iter;
4778 if (unlikely(recursion_level >= 24))
4784 sg_set_buf(sg, skb->data + offset, copy);
4786 if ((len -= copy) == 0)
4791 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4794 WARN_ON(start > offset + len);
4796 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4797 if ((copy = end - offset) > 0) {
4798 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4799 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4804 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4805 skb_frag_off(frag) + offset - start);
4814 skb_walk_frags(skb, frag_iter) {
4817 WARN_ON(start > offset + len);
4819 end = start + frag_iter->len;
4820 if ((copy = end - offset) > 0) {
4821 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4826 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4827 copy, recursion_level + 1);
4828 if (unlikely(ret < 0))
4831 if ((len -= copy) == 0)
4842 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4843 * @skb: Socket buffer containing the buffers to be mapped
4844 * @sg: The scatter-gather list to map into
4845 * @offset: The offset into the buffer's contents to start mapping
4846 * @len: Length of buffer space to be mapped
4848 * Fill the specified scatter-gather list with mappings/pointers into a
4849 * region of the buffer space attached to a socket buffer. Returns either
4850 * the number of scatterlist items used, or -EMSGSIZE if the contents
4853 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4855 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4860 sg_mark_end(&sg[nsg - 1]);
4864 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4866 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4867 * sglist without mark the sg which contain last skb data as the end.
4868 * So the caller can mannipulate sg list as will when padding new data after
4869 * the first call without calling sg_unmark_end to expend sg list.
4871 * Scenario to use skb_to_sgvec_nomark:
4873 * 2. skb_to_sgvec_nomark(payload1)
4874 * 3. skb_to_sgvec_nomark(payload2)
4876 * This is equivalent to:
4878 * 2. skb_to_sgvec(payload1)
4880 * 4. skb_to_sgvec(payload2)
4882 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4883 * is more preferable.
4885 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4886 int offset, int len)
4888 return __skb_to_sgvec(skb, sg, offset, len, 0);
4890 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4895 * skb_cow_data - Check that a socket buffer's data buffers are writable
4896 * @skb: The socket buffer to check.
4897 * @tailbits: Amount of trailing space to be added
4898 * @trailer: Returned pointer to the skb where the @tailbits space begins
4900 * Make sure that the data buffers attached to a socket buffer are
4901 * writable. If they are not, private copies are made of the data buffers
4902 * and the socket buffer is set to use these instead.
4904 * If @tailbits is given, make sure that there is space to write @tailbits
4905 * bytes of data beyond current end of socket buffer. @trailer will be
4906 * set to point to the skb in which this space begins.
4908 * The number of scatterlist elements required to completely map the
4909 * COW'd and extended socket buffer will be returned.
4911 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4915 struct sk_buff *skb1, **skb_p;
4917 /* If skb is cloned or its head is paged, reallocate
4918 * head pulling out all the pages (pages are considered not writable
4919 * at the moment even if they are anonymous).
4921 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4922 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4925 /* Easy case. Most of packets will go this way. */
4926 if (!skb_has_frag_list(skb)) {
4927 /* A little of trouble, not enough of space for trailer.
4928 * This should not happen, when stack is tuned to generate
4929 * good frames. OK, on miss we reallocate and reserve even more
4930 * space, 128 bytes is fair. */
4932 if (skb_tailroom(skb) < tailbits &&
4933 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4941 /* Misery. We are in troubles, going to mincer fragments... */
4944 skb_p = &skb_shinfo(skb)->frag_list;
4947 while ((skb1 = *skb_p) != NULL) {
4950 /* The fragment is partially pulled by someone,
4951 * this can happen on input. Copy it and everything
4954 if (skb_shared(skb1))
4957 /* If the skb is the last, worry about trailer. */
4959 if (skb1->next == NULL && tailbits) {
4960 if (skb_shinfo(skb1)->nr_frags ||
4961 skb_has_frag_list(skb1) ||
4962 skb_tailroom(skb1) < tailbits)
4963 ntail = tailbits + 128;
4969 skb_shinfo(skb1)->nr_frags ||
4970 skb_has_frag_list(skb1)) {
4971 struct sk_buff *skb2;
4973 /* Fuck, we are miserable poor guys... */
4975 skb2 = skb_copy(skb1, GFP_ATOMIC);
4977 skb2 = skb_copy_expand(skb1,
4981 if (unlikely(skb2 == NULL))
4985 skb_set_owner_w(skb2, skb1->sk);
4987 /* Looking around. Are we still alive?
4988 * OK, link new skb, drop old one */
4990 skb2->next = skb1->next;
4997 skb_p = &skb1->next;
5002 EXPORT_SYMBOL_GPL(skb_cow_data);
5004 static void sock_rmem_free(struct sk_buff *skb)
5006 struct sock *sk = skb->sk;
5008 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
5011 static void skb_set_err_queue(struct sk_buff *skb)
5013 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
5014 * So, it is safe to (mis)use it to mark skbs on the error queue.
5016 skb->pkt_type = PACKET_OUTGOING;
5017 BUILD_BUG_ON(PACKET_OUTGOING == 0);
5021 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
5023 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
5025 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
5026 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
5031 skb->destructor = sock_rmem_free;
5032 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
5033 skb_set_err_queue(skb);
5035 /* before exiting rcu section, make sure dst is refcounted */
5038 skb_queue_tail(&sk->sk_error_queue, skb);
5039 if (!sock_flag(sk, SOCK_DEAD))
5040 sk_error_report(sk);
5043 EXPORT_SYMBOL(sock_queue_err_skb);
5045 static bool is_icmp_err_skb(const struct sk_buff *skb)
5047 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
5048 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
5051 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
5053 struct sk_buff_head *q = &sk->sk_error_queue;
5054 struct sk_buff *skb, *skb_next = NULL;
5055 bool icmp_next = false;
5056 unsigned long flags;
5058 spin_lock_irqsave(&q->lock, flags);
5059 skb = __skb_dequeue(q);
5060 if (skb && (skb_next = skb_peek(q))) {
5061 icmp_next = is_icmp_err_skb(skb_next);
5063 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
5065 spin_unlock_irqrestore(&q->lock, flags);
5067 if (is_icmp_err_skb(skb) && !icmp_next)
5071 sk_error_report(sk);
5075 EXPORT_SYMBOL(sock_dequeue_err_skb);
5078 * skb_clone_sk - create clone of skb, and take reference to socket
5079 * @skb: the skb to clone
5081 * This function creates a clone of a buffer that holds a reference on
5082 * sk_refcnt. Buffers created via this function are meant to be
5083 * returned using sock_queue_err_skb, or free via kfree_skb.
5085 * When passing buffers allocated with this function to sock_queue_err_skb
5086 * it is necessary to wrap the call with sock_hold/sock_put in order to
5087 * prevent the socket from being released prior to being enqueued on
5088 * the sk_error_queue.
5090 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
5092 struct sock *sk = skb->sk;
5093 struct sk_buff *clone;
5095 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
5098 clone = skb_clone(skb, GFP_ATOMIC);
5105 clone->destructor = sock_efree;
5109 EXPORT_SYMBOL(skb_clone_sk);
5111 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
5116 struct sock_exterr_skb *serr;
5119 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
5121 serr = SKB_EXT_ERR(skb);
5122 memset(serr, 0, sizeof(*serr));
5123 serr->ee.ee_errno = ENOMSG;
5124 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5125 serr->ee.ee_info = tstype;
5126 serr->opt_stats = opt_stats;
5127 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5128 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
5129 serr->ee.ee_data = skb_shinfo(skb)->tskey;
5131 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5134 err = sock_queue_err_skb(sk, skb);
5140 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5144 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5147 read_lock_bh(&sk->sk_callback_lock);
5148 ret = sk->sk_socket && sk->sk_socket->file &&
5149 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5150 read_unlock_bh(&sk->sk_callback_lock);
5154 void skb_complete_tx_timestamp(struct sk_buff *skb,
5155 struct skb_shared_hwtstamps *hwtstamps)
5157 struct sock *sk = skb->sk;
5159 if (!skb_may_tx_timestamp(sk, false))
5162 /* Take a reference to prevent skb_orphan() from freeing the socket,
5163 * but only if the socket refcount is not zero.
5165 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5166 *skb_hwtstamps(skb) = *hwtstamps;
5167 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5175 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5177 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5178 const struct sk_buff *ack_skb,
5179 struct skb_shared_hwtstamps *hwtstamps,
5180 struct sock *sk, int tstype)
5182 struct sk_buff *skb;
5183 bool tsonly, opt_stats = false;
5188 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5189 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5192 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5193 if (!skb_may_tx_timestamp(sk, tsonly))
5198 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5200 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5205 skb = alloc_skb(0, GFP_ATOMIC);
5207 skb = skb_clone(orig_skb, GFP_ATOMIC);
5209 if (skb_orphan_frags_rx(skb, GFP_ATOMIC))
5216 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5218 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5222 *skb_hwtstamps(skb) = *hwtstamps;
5224 __net_timestamp(skb);
5226 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5228 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5230 void skb_tstamp_tx(struct sk_buff *orig_skb,
5231 struct skb_shared_hwtstamps *hwtstamps)
5233 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5236 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5238 #ifdef CONFIG_WIRELESS
5239 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5241 struct sock *sk = skb->sk;
5242 struct sock_exterr_skb *serr;
5245 skb->wifi_acked_valid = 1;
5246 skb->wifi_acked = acked;
5248 serr = SKB_EXT_ERR(skb);
5249 memset(serr, 0, sizeof(*serr));
5250 serr->ee.ee_errno = ENOMSG;
5251 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5253 /* Take a reference to prevent skb_orphan() from freeing the socket,
5254 * but only if the socket refcount is not zero.
5256 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5257 err = sock_queue_err_skb(sk, skb);
5263 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5264 #endif /* CONFIG_WIRELESS */
5267 * skb_partial_csum_set - set up and verify partial csum values for packet
5268 * @skb: the skb to set
5269 * @start: the number of bytes after skb->data to start checksumming.
5270 * @off: the offset from start to place the checksum.
5272 * For untrusted partially-checksummed packets, we need to make sure the values
5273 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5275 * This function checks and sets those values and skb->ip_summed: if this
5276 * returns false you should drop the packet.
5278 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5280 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5281 u32 csum_start = skb_headroom(skb) + (u32)start;
5283 if (unlikely(csum_start >= U16_MAX || csum_end > skb_headlen(skb))) {
5284 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5285 start, off, skb_headroom(skb), skb_headlen(skb));
5288 skb->ip_summed = CHECKSUM_PARTIAL;
5289 skb->csum_start = csum_start;
5290 skb->csum_offset = off;
5291 skb->transport_header = csum_start;
5294 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5296 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5299 if (skb_headlen(skb) >= len)
5302 /* If we need to pullup then pullup to the max, so we
5303 * won't need to do it again.
5308 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5311 if (skb_headlen(skb) < len)
5317 #define MAX_TCP_HDR_LEN (15 * 4)
5319 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5320 typeof(IPPROTO_IP) proto,
5327 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5328 off + MAX_TCP_HDR_LEN);
5329 if (!err && !skb_partial_csum_set(skb, off,
5330 offsetof(struct tcphdr,
5333 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5336 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5337 off + sizeof(struct udphdr));
5338 if (!err && !skb_partial_csum_set(skb, off,
5339 offsetof(struct udphdr,
5342 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5345 return ERR_PTR(-EPROTO);
5348 /* This value should be large enough to cover a tagged ethernet header plus
5349 * maximally sized IP and TCP or UDP headers.
5351 #define MAX_IP_HDR_LEN 128
5353 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5362 err = skb_maybe_pull_tail(skb,
5363 sizeof(struct iphdr),
5368 if (ip_is_fragment(ip_hdr(skb)))
5371 off = ip_hdrlen(skb);
5378 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5380 return PTR_ERR(csum);
5383 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5386 ip_hdr(skb)->protocol, 0);
5393 /* This value should be large enough to cover a tagged ethernet header plus
5394 * an IPv6 header, all options, and a maximal TCP or UDP header.
5396 #define MAX_IPV6_HDR_LEN 256
5398 #define OPT_HDR(type, skb, off) \
5399 (type *)(skb_network_header(skb) + (off))
5401 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5414 off = sizeof(struct ipv6hdr);
5416 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5420 nexthdr = ipv6_hdr(skb)->nexthdr;
5422 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5423 while (off <= len && !done) {
5425 case IPPROTO_DSTOPTS:
5426 case IPPROTO_HOPOPTS:
5427 case IPPROTO_ROUTING: {
5428 struct ipv6_opt_hdr *hp;
5430 err = skb_maybe_pull_tail(skb,
5432 sizeof(struct ipv6_opt_hdr),
5437 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5438 nexthdr = hp->nexthdr;
5439 off += ipv6_optlen(hp);
5443 struct ip_auth_hdr *hp;
5445 err = skb_maybe_pull_tail(skb,
5447 sizeof(struct ip_auth_hdr),
5452 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5453 nexthdr = hp->nexthdr;
5454 off += ipv6_authlen(hp);
5457 case IPPROTO_FRAGMENT: {
5458 struct frag_hdr *hp;
5460 err = skb_maybe_pull_tail(skb,
5462 sizeof(struct frag_hdr),
5467 hp = OPT_HDR(struct frag_hdr, skb, off);
5469 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5472 nexthdr = hp->nexthdr;
5473 off += sizeof(struct frag_hdr);
5484 if (!done || fragment)
5487 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5489 return PTR_ERR(csum);
5492 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5493 &ipv6_hdr(skb)->daddr,
5494 skb->len - off, nexthdr, 0);
5502 * skb_checksum_setup - set up partial checksum offset
5503 * @skb: the skb to set up
5504 * @recalculate: if true the pseudo-header checksum will be recalculated
5506 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5510 switch (skb->protocol) {
5511 case htons(ETH_P_IP):
5512 err = skb_checksum_setup_ipv4(skb, recalculate);
5515 case htons(ETH_P_IPV6):
5516 err = skb_checksum_setup_ipv6(skb, recalculate);
5526 EXPORT_SYMBOL(skb_checksum_setup);
5529 * skb_checksum_maybe_trim - maybe trims the given skb
5530 * @skb: the skb to check
5531 * @transport_len: the data length beyond the network header
5533 * Checks whether the given skb has data beyond the given transport length.
5534 * If so, returns a cloned skb trimmed to this transport length.
5535 * Otherwise returns the provided skb. Returns NULL in error cases
5536 * (e.g. transport_len exceeds skb length or out-of-memory).
5538 * Caller needs to set the skb transport header and free any returned skb if it
5539 * differs from the provided skb.
5541 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5542 unsigned int transport_len)
5544 struct sk_buff *skb_chk;
5545 unsigned int len = skb_transport_offset(skb) + transport_len;
5550 else if (skb->len == len)
5553 skb_chk = skb_clone(skb, GFP_ATOMIC);
5557 ret = pskb_trim_rcsum(skb_chk, len);
5567 * skb_checksum_trimmed - validate checksum of an skb
5568 * @skb: the skb to check
5569 * @transport_len: the data length beyond the network header
5570 * @skb_chkf: checksum function to use
5572 * Applies the given checksum function skb_chkf to the provided skb.
5573 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5575 * If the skb has data beyond the given transport length, then a
5576 * trimmed & cloned skb is checked and returned.
5578 * Caller needs to set the skb transport header and free any returned skb if it
5579 * differs from the provided skb.
5581 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5582 unsigned int transport_len,
5583 __sum16(*skb_chkf)(struct sk_buff *skb))
5585 struct sk_buff *skb_chk;
5586 unsigned int offset = skb_transport_offset(skb);
5589 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5593 if (!pskb_may_pull(skb_chk, offset))
5596 skb_pull_rcsum(skb_chk, offset);
5597 ret = skb_chkf(skb_chk);
5598 skb_push_rcsum(skb_chk, offset);
5606 if (skb_chk && skb_chk != skb)
5612 EXPORT_SYMBOL(skb_checksum_trimmed);
5614 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5616 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5619 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5621 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5624 skb_release_head_state(skb);
5625 kmem_cache_free(skbuff_cache, skb);
5630 EXPORT_SYMBOL(kfree_skb_partial);
5633 * skb_try_coalesce - try to merge skb to prior one
5635 * @from: buffer to add
5636 * @fragstolen: pointer to boolean
5637 * @delta_truesize: how much more was allocated than was requested
5639 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5640 bool *fragstolen, int *delta_truesize)
5642 struct skb_shared_info *to_shinfo, *from_shinfo;
5643 int i, delta, len = from->len;
5645 *fragstolen = false;
5650 /* In general, avoid mixing page_pool and non-page_pool allocated
5651 * pages within the same SKB. Additionally avoid dealing with clones
5652 * with page_pool pages, in case the SKB is using page_pool fragment
5653 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5654 * references for cloned SKBs at the moment that would result in
5655 * inconsistent reference counts.
5656 * In theory we could take full references if @from is cloned and
5657 * !@to->pp_recycle but its tricky (due to potential race with
5658 * the clone disappearing) and rare, so not worth dealing with.
5660 if (to->pp_recycle != from->pp_recycle ||
5661 (from->pp_recycle && skb_cloned(from)))
5664 if (len <= skb_tailroom(to)) {
5666 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5667 *delta_truesize = 0;
5671 to_shinfo = skb_shinfo(to);
5672 from_shinfo = skb_shinfo(from);
5673 if (to_shinfo->frag_list || from_shinfo->frag_list)
5675 if (skb_zcopy(to) || skb_zcopy(from))
5678 if (skb_headlen(from) != 0) {
5680 unsigned int offset;
5682 if (to_shinfo->nr_frags +
5683 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5686 if (skb_head_is_locked(from))
5689 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5691 page = virt_to_head_page(from->head);
5692 offset = from->data - (unsigned char *)page_address(page);
5694 skb_fill_page_desc(to, to_shinfo->nr_frags,
5695 page, offset, skb_headlen(from));
5698 if (to_shinfo->nr_frags +
5699 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5702 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5705 WARN_ON_ONCE(delta < len);
5707 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5709 from_shinfo->nr_frags * sizeof(skb_frag_t));
5710 to_shinfo->nr_frags += from_shinfo->nr_frags;
5712 if (!skb_cloned(from))
5713 from_shinfo->nr_frags = 0;
5715 /* if the skb is not cloned this does nothing
5716 * since we set nr_frags to 0.
5718 for (i = 0; i < from_shinfo->nr_frags; i++)
5719 __skb_frag_ref(&from_shinfo->frags[i]);
5721 to->truesize += delta;
5723 to->data_len += len;
5725 *delta_truesize = delta;
5728 EXPORT_SYMBOL(skb_try_coalesce);
5731 * skb_scrub_packet - scrub an skb
5733 * @skb: buffer to clean
5734 * @xnet: packet is crossing netns
5736 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5737 * into/from a tunnel. Some information have to be cleared during these
5739 * skb_scrub_packet can also be used to clean a skb before injecting it in
5740 * another namespace (@xnet == true). We have to clear all information in the
5741 * skb that could impact namespace isolation.
5743 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5745 skb->pkt_type = PACKET_HOST;
5751 nf_reset_trace(skb);
5753 #ifdef CONFIG_NET_SWITCHDEV
5754 skb->offload_fwd_mark = 0;
5755 skb->offload_l3_fwd_mark = 0;
5763 skb_clear_tstamp(skb);
5765 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5768 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5772 * skb_gso_transport_seglen is used to determine the real size of the
5773 * individual segments, including Layer4 headers (TCP/UDP).
5775 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5777 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5779 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5780 unsigned int thlen = 0;
5782 if (skb->encapsulation) {
5783 thlen = skb_inner_transport_header(skb) -
5784 skb_transport_header(skb);
5786 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5787 thlen += inner_tcp_hdrlen(skb);
5788 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5789 thlen = tcp_hdrlen(skb);
5790 } else if (unlikely(skb_is_gso_sctp(skb))) {
5791 thlen = sizeof(struct sctphdr);
5792 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5793 thlen = sizeof(struct udphdr);
5795 /* UFO sets gso_size to the size of the fragmentation
5796 * payload, i.e. the size of the L4 (UDP) header is already
5799 return thlen + shinfo->gso_size;
5803 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5807 * skb_gso_network_seglen is used to determine the real size of the
5808 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5810 * The MAC/L2 header is not accounted for.
5812 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5814 unsigned int hdr_len = skb_transport_header(skb) -
5815 skb_network_header(skb);
5817 return hdr_len + skb_gso_transport_seglen(skb);
5821 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5825 * skb_gso_mac_seglen is used to determine the real size of the
5826 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5827 * headers (TCP/UDP).
5829 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5831 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5833 return hdr_len + skb_gso_transport_seglen(skb);
5837 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5839 * There are a couple of instances where we have a GSO skb, and we
5840 * want to determine what size it would be after it is segmented.
5842 * We might want to check:
5843 * - L3+L4+payload size (e.g. IP forwarding)
5844 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5846 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5850 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5851 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5853 * @max_len: The maximum permissible length.
5855 * Returns true if the segmented length <= max length.
5857 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5858 unsigned int seg_len,
5859 unsigned int max_len) {
5860 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5861 const struct sk_buff *iter;
5863 if (shinfo->gso_size != GSO_BY_FRAGS)
5864 return seg_len <= max_len;
5866 /* Undo this so we can re-use header sizes */
5867 seg_len -= GSO_BY_FRAGS;
5869 skb_walk_frags(skb, iter) {
5870 if (seg_len + skb_headlen(iter) > max_len)
5878 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5881 * @mtu: MTU to validate against
5883 * skb_gso_validate_network_len validates if a given skb will fit a
5884 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5887 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5889 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5891 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5894 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5897 * @len: length to validate against
5899 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5900 * length once split, including L2, L3 and L4 headers and the payload.
5902 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5904 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5906 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5908 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5910 int mac_len, meta_len;
5913 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5918 mac_len = skb->data - skb_mac_header(skb);
5919 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5920 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5921 mac_len - VLAN_HLEN - ETH_TLEN);
5924 meta_len = skb_metadata_len(skb);
5926 meta = skb_metadata_end(skb) - meta_len;
5927 memmove(meta + VLAN_HLEN, meta, meta_len);
5930 skb->mac_header += VLAN_HLEN;
5934 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5936 struct vlan_hdr *vhdr;
5939 if (unlikely(skb_vlan_tag_present(skb))) {
5940 /* vlan_tci is already set-up so leave this for another time */
5944 skb = skb_share_check(skb, GFP_ATOMIC);
5947 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5948 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5951 vhdr = (struct vlan_hdr *)skb->data;
5952 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5953 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5955 skb_pull_rcsum(skb, VLAN_HLEN);
5956 vlan_set_encap_proto(skb, vhdr);
5958 skb = skb_reorder_vlan_header(skb);
5962 skb_reset_network_header(skb);
5963 if (!skb_transport_header_was_set(skb))
5964 skb_reset_transport_header(skb);
5965 skb_reset_mac_len(skb);
5973 EXPORT_SYMBOL(skb_vlan_untag);
5975 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5977 if (!pskb_may_pull(skb, write_len))
5980 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5983 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5985 EXPORT_SYMBOL(skb_ensure_writable);
5987 /* remove VLAN header from packet and update csum accordingly.
5988 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5990 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5992 int offset = skb->data - skb_mac_header(skb);
5995 if (WARN_ONCE(offset,
5996 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
6001 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
6005 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6007 vlan_remove_tag(skb, vlan_tci);
6009 skb->mac_header += VLAN_HLEN;
6011 if (skb_network_offset(skb) < ETH_HLEN)
6012 skb_set_network_header(skb, ETH_HLEN);
6014 skb_reset_mac_len(skb);
6018 EXPORT_SYMBOL(__skb_vlan_pop);
6020 /* Pop a vlan tag either from hwaccel or from payload.
6021 * Expects skb->data at mac header.
6023 int skb_vlan_pop(struct sk_buff *skb)
6029 if (likely(skb_vlan_tag_present(skb))) {
6030 __vlan_hwaccel_clear_tag(skb);
6032 if (unlikely(!eth_type_vlan(skb->protocol)))
6035 err = __skb_vlan_pop(skb, &vlan_tci);
6039 /* move next vlan tag to hw accel tag */
6040 if (likely(!eth_type_vlan(skb->protocol)))
6043 vlan_proto = skb->protocol;
6044 err = __skb_vlan_pop(skb, &vlan_tci);
6048 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6051 EXPORT_SYMBOL(skb_vlan_pop);
6053 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
6054 * Expects skb->data at mac header.
6056 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
6058 if (skb_vlan_tag_present(skb)) {
6059 int offset = skb->data - skb_mac_header(skb);
6062 if (WARN_ONCE(offset,
6063 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
6068 err = __vlan_insert_tag(skb, skb->vlan_proto,
6069 skb_vlan_tag_get(skb));
6073 skb->protocol = skb->vlan_proto;
6074 skb->mac_len += VLAN_HLEN;
6076 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6078 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6081 EXPORT_SYMBOL(skb_vlan_push);
6084 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
6086 * @skb: Socket buffer to modify
6088 * Drop the Ethernet header of @skb.
6090 * Expects that skb->data points to the mac header and that no VLAN tags are
6093 * Returns 0 on success, -errno otherwise.
6095 int skb_eth_pop(struct sk_buff *skb)
6097 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
6098 skb_network_offset(skb) < ETH_HLEN)
6101 skb_pull_rcsum(skb, ETH_HLEN);
6102 skb_reset_mac_header(skb);
6103 skb_reset_mac_len(skb);
6107 EXPORT_SYMBOL(skb_eth_pop);
6110 * skb_eth_push() - Add a new Ethernet header at the head of a packet
6112 * @skb: Socket buffer to modify
6113 * @dst: Destination MAC address of the new header
6114 * @src: Source MAC address of the new header
6116 * Prepend @skb with a new Ethernet header.
6118 * Expects that skb->data points to the mac header, which must be empty.
6120 * Returns 0 on success, -errno otherwise.
6122 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6123 const unsigned char *src)
6128 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6131 err = skb_cow_head(skb, sizeof(*eth));
6135 skb_push(skb, sizeof(*eth));
6136 skb_reset_mac_header(skb);
6137 skb_reset_mac_len(skb);
6140 ether_addr_copy(eth->h_dest, dst);
6141 ether_addr_copy(eth->h_source, src);
6142 eth->h_proto = skb->protocol;
6144 skb_postpush_rcsum(skb, eth, sizeof(*eth));
6148 EXPORT_SYMBOL(skb_eth_push);
6150 /* Update the ethertype of hdr and the skb csum value if required. */
6151 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6154 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6155 __be16 diff[] = { ~hdr->h_proto, ethertype };
6157 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6160 hdr->h_proto = ethertype;
6164 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6168 * @mpls_lse: MPLS label stack entry to push
6169 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6170 * @mac_len: length of the MAC header
6171 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6174 * Expects skb->data at mac header.
6176 * Returns 0 on success, -errno otherwise.
6178 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6179 int mac_len, bool ethernet)
6181 struct mpls_shim_hdr *lse;
6184 if (unlikely(!eth_p_mpls(mpls_proto)))
6187 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6188 if (skb->encapsulation)
6191 err = skb_cow_head(skb, MPLS_HLEN);
6195 if (!skb->inner_protocol) {
6196 skb_set_inner_network_header(skb, skb_network_offset(skb));
6197 skb_set_inner_protocol(skb, skb->protocol);
6200 skb_push(skb, MPLS_HLEN);
6201 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6203 skb_reset_mac_header(skb);
6204 skb_set_network_header(skb, mac_len);
6205 skb_reset_mac_len(skb);
6207 lse = mpls_hdr(skb);
6208 lse->label_stack_entry = mpls_lse;
6209 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6211 if (ethernet && mac_len >= ETH_HLEN)
6212 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6213 skb->protocol = mpls_proto;
6217 EXPORT_SYMBOL_GPL(skb_mpls_push);
6220 * skb_mpls_pop() - pop the outermost MPLS header
6223 * @next_proto: ethertype of header after popped MPLS header
6224 * @mac_len: length of the MAC header
6225 * @ethernet: flag to indicate if the packet is ethernet
6227 * Expects skb->data at mac header.
6229 * Returns 0 on success, -errno otherwise.
6231 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6236 if (unlikely(!eth_p_mpls(skb->protocol)))
6239 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6243 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6244 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6247 __skb_pull(skb, MPLS_HLEN);
6248 skb_reset_mac_header(skb);
6249 skb_set_network_header(skb, mac_len);
6251 if (ethernet && mac_len >= ETH_HLEN) {
6254 /* use mpls_hdr() to get ethertype to account for VLANs. */
6255 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6256 skb_mod_eth_type(skb, hdr, next_proto);
6258 skb->protocol = next_proto;
6262 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6265 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6268 * @mpls_lse: new MPLS label stack entry to update to
6270 * Expects skb->data at mac header.
6272 * Returns 0 on success, -errno otherwise.
6274 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6278 if (unlikely(!eth_p_mpls(skb->protocol)))
6281 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6285 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6286 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6288 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6291 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6295 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6298 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6302 * Expects skb->data at mac header.
6304 * Returns 0 on success, -errno otherwise.
6306 int skb_mpls_dec_ttl(struct sk_buff *skb)
6311 if (unlikely(!eth_p_mpls(skb->protocol)))
6314 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6317 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6318 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6322 lse &= ~MPLS_LS_TTL_MASK;
6323 lse |= ttl << MPLS_LS_TTL_SHIFT;
6325 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6327 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6330 * alloc_skb_with_frags - allocate skb with page frags
6332 * @header_len: size of linear part
6333 * @data_len: needed length in frags
6334 * @max_page_order: max page order desired.
6335 * @errcode: pointer to error code if any
6336 * @gfp_mask: allocation mask
6338 * This can be used to allocate a paged skb, given a maximal order for frags.
6340 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6341 unsigned long data_len,
6346 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6347 unsigned long chunk;
6348 struct sk_buff *skb;
6352 *errcode = -EMSGSIZE;
6353 /* Note this test could be relaxed, if we succeed to allocate
6354 * high order pages...
6356 if (npages > MAX_SKB_FRAGS)
6359 *errcode = -ENOBUFS;
6360 skb = alloc_skb(header_len, gfp_mask);
6364 skb->truesize += npages << PAGE_SHIFT;
6366 for (i = 0; npages > 0; i++) {
6367 int order = max_page_order;
6370 if (npages >= 1 << order) {
6371 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6377 /* Do not retry other high order allocations */
6383 page = alloc_page(gfp_mask);
6387 chunk = min_t(unsigned long, data_len,
6388 PAGE_SIZE << order);
6389 skb_fill_page_desc(skb, i, page, 0, chunk);
6391 npages -= 1 << order;
6399 EXPORT_SYMBOL(alloc_skb_with_frags);
6401 /* carve out the first off bytes from skb when off < headlen */
6402 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6403 const int headlen, gfp_t gfp_mask)
6406 unsigned int size = skb_end_offset(skb);
6407 int new_hlen = headlen - off;
6410 if (skb_pfmemalloc(skb))
6411 gfp_mask |= __GFP_MEMALLOC;
6413 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6416 size = SKB_WITH_OVERHEAD(size);
6418 /* Copy real data, and all frags */
6419 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6422 memcpy((struct skb_shared_info *)(data + size),
6424 offsetof(struct skb_shared_info,
6425 frags[skb_shinfo(skb)->nr_frags]));
6426 if (skb_cloned(skb)) {
6427 /* drop the old head gracefully */
6428 if (skb_orphan_frags(skb, gfp_mask)) {
6429 skb_kfree_head(data, size);
6432 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6433 skb_frag_ref(skb, i);
6434 if (skb_has_frag_list(skb))
6435 skb_clone_fraglist(skb);
6436 skb_release_data(skb, SKB_CONSUMED, false);
6438 /* we can reuse existing recount- all we did was
6441 skb_free_head(skb, false);
6447 skb_set_end_offset(skb, size);
6448 skb_set_tail_pointer(skb, skb_headlen(skb));
6449 skb_headers_offset_update(skb, 0);
6453 atomic_set(&skb_shinfo(skb)->dataref, 1);
6458 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6460 /* carve out the first eat bytes from skb's frag_list. May recurse into
6463 static int pskb_carve_frag_list(struct sk_buff *skb,
6464 struct skb_shared_info *shinfo, int eat,
6467 struct sk_buff *list = shinfo->frag_list;
6468 struct sk_buff *clone = NULL;
6469 struct sk_buff *insp = NULL;
6473 pr_err("Not enough bytes to eat. Want %d\n", eat);
6476 if (list->len <= eat) {
6477 /* Eaten as whole. */
6482 /* Eaten partially. */
6483 if (skb_shared(list)) {
6484 clone = skb_clone(list, gfp_mask);
6490 /* This may be pulled without problems. */
6493 if (pskb_carve(list, eat, gfp_mask) < 0) {
6501 /* Free pulled out fragments. */
6502 while ((list = shinfo->frag_list) != insp) {
6503 shinfo->frag_list = list->next;
6506 /* And insert new clone at head. */
6509 shinfo->frag_list = clone;
6514 /* carve off first len bytes from skb. Split line (off) is in the
6515 * non-linear part of skb
6517 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6518 int pos, gfp_t gfp_mask)
6521 unsigned int size = skb_end_offset(skb);
6523 const int nfrags = skb_shinfo(skb)->nr_frags;
6524 struct skb_shared_info *shinfo;
6526 if (skb_pfmemalloc(skb))
6527 gfp_mask |= __GFP_MEMALLOC;
6529 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6532 size = SKB_WITH_OVERHEAD(size);
6534 memcpy((struct skb_shared_info *)(data + size),
6535 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6536 if (skb_orphan_frags(skb, gfp_mask)) {
6537 skb_kfree_head(data, size);
6540 shinfo = (struct skb_shared_info *)(data + size);
6541 for (i = 0; i < nfrags; i++) {
6542 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6544 if (pos + fsize > off) {
6545 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6549 * We have two variants in this case:
6550 * 1. Move all the frag to the second
6551 * part, if it is possible. F.e.
6552 * this approach is mandatory for TUX,
6553 * where splitting is expensive.
6554 * 2. Split is accurately. We make this.
6556 skb_frag_off_add(&shinfo->frags[0], off - pos);
6557 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6559 skb_frag_ref(skb, i);
6564 shinfo->nr_frags = k;
6565 if (skb_has_frag_list(skb))
6566 skb_clone_fraglist(skb);
6568 /* split line is in frag list */
6569 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6570 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6571 if (skb_has_frag_list(skb))
6572 kfree_skb_list(skb_shinfo(skb)->frag_list);
6573 skb_kfree_head(data, size);
6576 skb_release_data(skb, SKB_CONSUMED, false);
6581 skb_set_end_offset(skb, size);
6582 skb_reset_tail_pointer(skb);
6583 skb_headers_offset_update(skb, 0);
6588 skb->data_len = skb->len;
6589 atomic_set(&skb_shinfo(skb)->dataref, 1);
6593 /* remove len bytes from the beginning of the skb */
6594 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6596 int headlen = skb_headlen(skb);
6599 return pskb_carve_inside_header(skb, len, headlen, gfp);
6601 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6604 /* Extract to_copy bytes starting at off from skb, and return this in
6607 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6608 int to_copy, gfp_t gfp)
6610 struct sk_buff *clone = skb_clone(skb, gfp);
6615 if (pskb_carve(clone, off, gfp) < 0 ||
6616 pskb_trim(clone, to_copy)) {
6622 EXPORT_SYMBOL(pskb_extract);
6625 * skb_condense - try to get rid of fragments/frag_list if possible
6628 * Can be used to save memory before skb is added to a busy queue.
6629 * If packet has bytes in frags and enough tail room in skb->head,
6630 * pull all of them, so that we can free the frags right now and adjust
6633 * We do not reallocate skb->head thus can not fail.
6634 * Caller must re-evaluate skb->truesize if needed.
6636 void skb_condense(struct sk_buff *skb)
6638 if (skb->data_len) {
6639 if (skb->data_len > skb->end - skb->tail ||
6643 /* Nice, we can free page frag(s) right now */
6644 __pskb_pull_tail(skb, skb->data_len);
6646 /* At this point, skb->truesize might be over estimated,
6647 * because skb had a fragment, and fragments do not tell
6649 * When we pulled its content into skb->head, fragment
6650 * was freed, but __pskb_pull_tail() could not possibly
6651 * adjust skb->truesize, not knowing the frag truesize.
6653 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6655 EXPORT_SYMBOL(skb_condense);
6657 #ifdef CONFIG_SKB_EXTENSIONS
6658 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6660 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6664 * __skb_ext_alloc - allocate a new skb extensions storage
6666 * @flags: See kmalloc().
6668 * Returns the newly allocated pointer. The pointer can later attached to a
6669 * skb via __skb_ext_set().
6670 * Note: caller must handle the skb_ext as an opaque data.
6672 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6674 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6677 memset(new->offset, 0, sizeof(new->offset));
6678 refcount_set(&new->refcnt, 1);
6684 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6685 unsigned int old_active)
6687 struct skb_ext *new;
6689 if (refcount_read(&old->refcnt) == 1)
6692 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6696 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6697 refcount_set(&new->refcnt, 1);
6700 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6701 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6704 for (i = 0; i < sp->len; i++)
6705 xfrm_state_hold(sp->xvec[i]);
6713 * __skb_ext_set - attach the specified extension storage to this skb
6716 * @ext: extension storage previously allocated via __skb_ext_alloc()
6718 * Existing extensions, if any, are cleared.
6720 * Returns the pointer to the extension.
6722 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6723 struct skb_ext *ext)
6725 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6728 newlen = newoff + skb_ext_type_len[id];
6729 ext->chunks = newlen;
6730 ext->offset[id] = newoff;
6731 skb->extensions = ext;
6732 skb->active_extensions = 1 << id;
6733 return skb_ext_get_ptr(ext, id);
6737 * skb_ext_add - allocate space for given extension, COW if needed
6739 * @id: extension to allocate space for
6741 * Allocates enough space for the given extension.
6742 * If the extension is already present, a pointer to that extension
6745 * If the skb was cloned, COW applies and the returned memory can be
6746 * modified without changing the extension space of clones buffers.
6748 * Returns pointer to the extension or NULL on allocation failure.
6750 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6752 struct skb_ext *new, *old = NULL;
6753 unsigned int newlen, newoff;
6755 if (skb->active_extensions) {
6756 old = skb->extensions;
6758 new = skb_ext_maybe_cow(old, skb->active_extensions);
6762 if (__skb_ext_exist(new, id))
6765 newoff = new->chunks;
6767 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6769 new = __skb_ext_alloc(GFP_ATOMIC);
6774 newlen = newoff + skb_ext_type_len[id];
6775 new->chunks = newlen;
6776 new->offset[id] = newoff;
6779 skb->extensions = new;
6780 skb->active_extensions |= 1 << id;
6781 return skb_ext_get_ptr(new, id);
6783 EXPORT_SYMBOL(skb_ext_add);
6786 static void skb_ext_put_sp(struct sec_path *sp)
6790 for (i = 0; i < sp->len; i++)
6791 xfrm_state_put(sp->xvec[i]);
6795 #ifdef CONFIG_MCTP_FLOWS
6796 static void skb_ext_put_mctp(struct mctp_flow *flow)
6799 mctp_key_unref(flow->key);
6803 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6805 struct skb_ext *ext = skb->extensions;
6807 skb->active_extensions &= ~(1 << id);
6808 if (skb->active_extensions == 0) {
6809 skb->extensions = NULL;
6812 } else if (id == SKB_EXT_SEC_PATH &&
6813 refcount_read(&ext->refcnt) == 1) {
6814 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6821 EXPORT_SYMBOL(__skb_ext_del);
6823 void __skb_ext_put(struct skb_ext *ext)
6825 /* If this is last clone, nothing can increment
6826 * it after check passes. Avoids one atomic op.
6828 if (refcount_read(&ext->refcnt) == 1)
6831 if (!refcount_dec_and_test(&ext->refcnt))
6835 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6836 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6838 #ifdef CONFIG_MCTP_FLOWS
6839 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6840 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6843 kmem_cache_free(skbuff_ext_cache, ext);
6845 EXPORT_SYMBOL(__skb_ext_put);
6846 #endif /* CONFIG_SKB_EXTENSIONS */
6849 * skb_attempt_defer_free - queue skb for remote freeing
6852 * Put @skb in a per-cpu list, using the cpu which
6853 * allocated the skb/pages to reduce false sharing
6854 * and memory zone spinlock contention.
6856 void skb_attempt_defer_free(struct sk_buff *skb)
6858 int cpu = skb->alloc_cpu;
6859 struct softnet_data *sd;
6860 unsigned int defer_max;
6863 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6865 cpu == raw_smp_processor_id()) {
6866 nodefer: __kfree_skb(skb);
6870 DEBUG_NET_WARN_ON_ONCE(skb_dst(skb));
6871 DEBUG_NET_WARN_ON_ONCE(skb->destructor);
6873 sd = &per_cpu(softnet_data, cpu);
6874 defer_max = READ_ONCE(sysctl_skb_defer_max);
6875 if (READ_ONCE(sd->defer_count) >= defer_max)
6878 spin_lock_bh(&sd->defer_lock);
6879 /* Send an IPI every time queue reaches half capacity. */
6880 kick = sd->defer_count == (defer_max >> 1);
6881 /* Paired with the READ_ONCE() few lines above */
6882 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6884 skb->next = sd->defer_list;
6885 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6886 WRITE_ONCE(sd->defer_list, skb);
6887 spin_unlock_bh(&sd->defer_lock);
6889 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6890 * if we are unlucky enough (this seems very unlikely).
6892 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6893 smp_call_function_single_async(cpu, &sd->defer_csd);
6896 static void skb_splice_csum_page(struct sk_buff *skb, struct page *page,
6897 size_t offset, size_t len)
6902 kaddr = kmap_local_page(page);
6903 csum = csum_partial(kaddr + offset, len, 0);
6904 kunmap_local(kaddr);
6905 skb->csum = csum_block_add(skb->csum, csum, skb->len);
6909 * skb_splice_from_iter - Splice (or copy) pages to skbuff
6910 * @skb: The buffer to add pages to
6911 * @iter: Iterator representing the pages to be added
6912 * @maxsize: Maximum amount of pages to be added
6913 * @gfp: Allocation flags
6915 * This is a common helper function for supporting MSG_SPLICE_PAGES. It
6916 * extracts pages from an iterator and adds them to the socket buffer if
6917 * possible, copying them to fragments if not possible (such as if they're slab
6920 * Returns the amount of data spliced/copied or -EMSGSIZE if there's
6921 * insufficient space in the buffer to transfer anything.
6923 ssize_t skb_splice_from_iter(struct sk_buff *skb, struct iov_iter *iter,
6924 ssize_t maxsize, gfp_t gfp)
6926 size_t frag_limit = READ_ONCE(sysctl_max_skb_frags);
6927 struct page *pages[8], **ppages = pages;
6928 ssize_t spliced = 0, ret = 0;
6931 while (iter->count > 0) {
6936 space = frag_limit - skb_shinfo(skb)->nr_frags;
6940 /* We might be able to coalesce without increasing nr_frags */
6941 nr = clamp_t(size_t, space, 1, ARRAY_SIZE(pages));
6943 len = iov_iter_extract_pages(iter, &ppages, maxsize, nr, 0, &off);
6951 struct page *page = pages[i++];
6952 size_t part = min_t(size_t, PAGE_SIZE - off, len);
6955 if (WARN_ON_ONCE(!sendpage_ok(page)))
6958 ret = skb_append_pagefrags(skb, page, off, part,
6961 iov_iter_revert(iter, len);
6965 if (skb->ip_summed == CHECKSUM_NONE)
6966 skb_splice_csum_page(skb, page, off, part);
6979 skb_len_add(skb, spliced);
6980 return spliced ?: ret;
6982 EXPORT_SYMBOL(skb_splice_from_iter);