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>
71 #include <net/ip6_checksum.h>
74 #include <net/mptcp.h>
76 #include <net/page_pool/helpers.h>
77 #include <net/dropreason.h>
79 #include <linux/uaccess.h>
80 #include <trace/events/skb.h>
81 #include <linux/highmem.h>
82 #include <linux/capability.h>
83 #include <linux/user_namespace.h>
84 #include <linux/indirect_call_wrapper.h>
85 #include <linux/textsearch.h>
88 #include "sock_destructor.h"
90 struct kmem_cache *skbuff_cache __ro_after_init;
91 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
92 #ifdef CONFIG_SKB_EXTENSIONS
93 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
97 static struct kmem_cache *skb_small_head_cache __ro_after_init;
99 #define SKB_SMALL_HEAD_SIZE SKB_HEAD_ALIGN(MAX_TCP_HEADER)
101 /* We want SKB_SMALL_HEAD_CACHE_SIZE to not be a power of two.
102 * This should ensure that SKB_SMALL_HEAD_HEADROOM is a unique
103 * size, and we can differentiate heads from skb_small_head_cache
104 * vs system slabs by looking at their size (skb_end_offset()).
106 #define SKB_SMALL_HEAD_CACHE_SIZE \
107 (is_power_of_2(SKB_SMALL_HEAD_SIZE) ? \
108 (SKB_SMALL_HEAD_SIZE + L1_CACHE_BYTES) : \
111 #define SKB_SMALL_HEAD_HEADROOM \
112 SKB_WITH_OVERHEAD(SKB_SMALL_HEAD_CACHE_SIZE)
114 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
115 EXPORT_SYMBOL(sysctl_max_skb_frags);
118 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
119 static const char * const drop_reasons[] = {
120 [SKB_CONSUMED] = "CONSUMED",
121 DEFINE_DROP_REASON(FN, FN)
124 static const struct drop_reason_list drop_reasons_core = {
125 .reasons = drop_reasons,
126 .n_reasons = ARRAY_SIZE(drop_reasons),
129 const struct drop_reason_list __rcu *
130 drop_reasons_by_subsys[SKB_DROP_REASON_SUBSYS_NUM] = {
131 [SKB_DROP_REASON_SUBSYS_CORE] = RCU_INITIALIZER(&drop_reasons_core),
133 EXPORT_SYMBOL(drop_reasons_by_subsys);
136 * drop_reasons_register_subsys - register another drop reason subsystem
137 * @subsys: the subsystem to register, must not be the core
138 * @list: the list of drop reasons within the subsystem, must point to
139 * a statically initialized list
141 void drop_reasons_register_subsys(enum skb_drop_reason_subsys subsys,
142 const struct drop_reason_list *list)
144 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
145 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
146 "invalid subsystem %d\n", subsys))
149 /* must point to statically allocated memory, so INIT is OK */
150 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], list);
152 EXPORT_SYMBOL_GPL(drop_reasons_register_subsys);
155 * drop_reasons_unregister_subsys - unregister a drop reason subsystem
156 * @subsys: the subsystem to remove, must not be the core
158 * Note: This will synchronize_rcu() to ensure no users when it returns.
160 void drop_reasons_unregister_subsys(enum skb_drop_reason_subsys subsys)
162 if (WARN(subsys <= SKB_DROP_REASON_SUBSYS_CORE ||
163 subsys >= ARRAY_SIZE(drop_reasons_by_subsys),
164 "invalid subsystem %d\n", subsys))
167 RCU_INIT_POINTER(drop_reasons_by_subsys[subsys], NULL);
171 EXPORT_SYMBOL_GPL(drop_reasons_unregister_subsys);
174 * skb_panic - private function for out-of-line support
178 * @msg: skb_over_panic or skb_under_panic
180 * Out-of-line support for skb_put() and skb_push().
181 * Called via the wrapper skb_over_panic() or skb_under_panic().
182 * Keep out of line to prevent kernel bloat.
183 * __builtin_return_address is not used because it is not always reliable.
185 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
188 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
189 msg, addr, skb->len, sz, skb->head, skb->data,
190 (unsigned long)skb->tail, (unsigned long)skb->end,
191 skb->dev ? skb->dev->name : "<NULL>");
195 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
197 skb_panic(skb, sz, addr, __func__);
200 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
202 skb_panic(skb, sz, addr, __func__);
205 #define NAPI_SKB_CACHE_SIZE 64
206 #define NAPI_SKB_CACHE_BULK 16
207 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
209 #if PAGE_SIZE == SZ_4K
211 #define NAPI_HAS_SMALL_PAGE_FRAG 1
212 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) ((nc).pfmemalloc)
214 /* specialized page frag allocator using a single order 0 page
215 * and slicing it into 1K sized fragment. Constrained to systems
216 * with a very limited amount of 1K fragments fitting a single
217 * page - to avoid excessive truesize underestimation
220 struct page_frag_1k {
226 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
231 offset = nc->offset - SZ_1K;
232 if (likely(offset >= 0))
235 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
239 nc->va = page_address(page);
240 nc->pfmemalloc = page_is_pfmemalloc(page);
241 offset = PAGE_SIZE - SZ_1K;
242 page_ref_add(page, offset / SZ_1K);
246 return nc->va + offset;
250 /* the small page is actually unused in this build; add dummy helpers
251 * to please the compiler and avoid later preprocessor's conditionals
253 #define NAPI_HAS_SMALL_PAGE_FRAG 0
254 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) false
256 struct page_frag_1k {
259 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
266 struct napi_alloc_cache {
267 struct page_frag_cache page;
268 struct page_frag_1k page_small;
269 unsigned int skb_count;
270 void *skb_cache[NAPI_SKB_CACHE_SIZE];
273 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
274 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
276 /* Double check that napi_get_frags() allocates skbs with
277 * skb->head being backed by slab, not a page fragment.
278 * This is to make sure bug fixed in 3226b158e67c
279 * ("net: avoid 32 x truesize under-estimation for tiny skbs")
280 * does not accidentally come back.
282 void napi_get_frags_check(struct napi_struct *napi)
287 skb = napi_get_frags(napi);
288 WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
289 napi_free_frags(napi);
293 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
295 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
297 fragsz = SKB_DATA_ALIGN(fragsz);
299 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
301 EXPORT_SYMBOL(__napi_alloc_frag_align);
303 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
307 fragsz = SKB_DATA_ALIGN(fragsz);
308 if (in_hardirq() || irqs_disabled()) {
309 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
311 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
313 struct napi_alloc_cache *nc;
316 nc = this_cpu_ptr(&napi_alloc_cache);
317 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
322 EXPORT_SYMBOL(__netdev_alloc_frag_align);
324 static struct sk_buff *napi_skb_cache_get(void)
326 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
329 if (unlikely(!nc->skb_count)) {
330 nc->skb_count = kmem_cache_alloc_bulk(skbuff_cache,
334 if (unlikely(!nc->skb_count))
338 skb = nc->skb_cache[--nc->skb_count];
339 kasan_unpoison_object_data(skbuff_cache, skb);
344 static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
347 struct skb_shared_info *shinfo;
349 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
351 /* Assumes caller memset cleared SKB */
352 skb->truesize = SKB_TRUESIZE(size);
353 refcount_set(&skb->users, 1);
356 skb_reset_tail_pointer(skb);
357 skb_set_end_offset(skb, size);
358 skb->mac_header = (typeof(skb->mac_header))~0U;
359 skb->transport_header = (typeof(skb->transport_header))~0U;
360 skb->alloc_cpu = raw_smp_processor_id();
361 /* make sure we initialize shinfo sequentially */
362 shinfo = skb_shinfo(skb);
363 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
364 atomic_set(&shinfo->dataref, 1);
366 skb_set_kcov_handle(skb, kcov_common_handle());
369 static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
374 /* Must find the allocation size (and grow it to match). */
376 /* krealloc() will immediately return "data" when
377 * "ksize(data)" is requested: it is the existing upper
378 * bounds. As a result, GFP_ATOMIC will be ignored. Note
379 * that this "new" pointer needs to be passed back to the
380 * caller for use so the __alloc_size hinting will be
383 resized = krealloc(data, *size, GFP_ATOMIC);
384 WARN_ON_ONCE(resized != data);
388 /* build_skb() variant which can operate on slab buffers.
389 * Note that this should be used sparingly as slab buffers
390 * cannot be combined efficiently by GRO!
392 struct sk_buff *slab_build_skb(void *data)
397 skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
401 memset(skb, 0, offsetof(struct sk_buff, tail));
402 data = __slab_build_skb(skb, data, &size);
403 __finalize_skb_around(skb, data, size);
407 EXPORT_SYMBOL(slab_build_skb);
409 /* Caller must provide SKB that is memset cleared */
410 static void __build_skb_around(struct sk_buff *skb, void *data,
411 unsigned int frag_size)
413 unsigned int size = frag_size;
415 /* frag_size == 0 is considered deprecated now. Callers
416 * using slab buffer should use slab_build_skb() instead.
418 if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
419 data = __slab_build_skb(skb, data, &size);
421 __finalize_skb_around(skb, data, size);
425 * __build_skb - build a network buffer
426 * @data: data buffer provided by caller
427 * @frag_size: size of data (must not be 0)
429 * Allocate a new &sk_buff. Caller provides space holding head and
430 * skb_shared_info. @data must have been allocated from the page
431 * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
432 * allocation is deprecated, and callers should use slab_build_skb()
434 * The return is the new skb buffer.
435 * On a failure the return is %NULL, and @data is not freed.
437 * Before IO, driver allocates only data buffer where NIC put incoming frame
438 * Driver should add room at head (NET_SKB_PAD) and
439 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
440 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
441 * before giving packet to stack.
442 * RX rings only contains data buffers, not full skbs.
444 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
448 skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
452 memset(skb, 0, offsetof(struct sk_buff, tail));
453 __build_skb_around(skb, data, frag_size);
458 /* build_skb() is wrapper over __build_skb(), that specifically
459 * takes care of skb->head and skb->pfmemalloc
461 struct sk_buff *build_skb(void *data, unsigned int frag_size)
463 struct sk_buff *skb = __build_skb(data, frag_size);
465 if (likely(skb && frag_size)) {
467 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
471 EXPORT_SYMBOL(build_skb);
474 * build_skb_around - build a network buffer around provided skb
475 * @skb: sk_buff provide by caller, must be memset cleared
476 * @data: data buffer provided by caller
477 * @frag_size: size of data
479 struct sk_buff *build_skb_around(struct sk_buff *skb,
480 void *data, unsigned int frag_size)
485 __build_skb_around(skb, data, frag_size);
489 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
493 EXPORT_SYMBOL(build_skb_around);
496 * __napi_build_skb - build a network buffer
497 * @data: data buffer provided by caller
498 * @frag_size: size of data
500 * Version of __build_skb() that uses NAPI percpu caches to obtain
501 * skbuff_head instead of inplace allocation.
503 * Returns a new &sk_buff on success, %NULL on allocation failure.
505 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
509 skb = napi_skb_cache_get();
513 memset(skb, 0, offsetof(struct sk_buff, tail));
514 __build_skb_around(skb, data, frag_size);
520 * napi_build_skb - build a network buffer
521 * @data: data buffer provided by caller
522 * @frag_size: size of data
524 * Version of __napi_build_skb() that takes care of skb->head_frag
525 * and skb->pfmemalloc when the data is a page or page fragment.
527 * Returns a new &sk_buff on success, %NULL on allocation failure.
529 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
531 struct sk_buff *skb = __napi_build_skb(data, frag_size);
533 if (likely(skb) && frag_size) {
535 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
540 EXPORT_SYMBOL(napi_build_skb);
543 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
544 * the caller if emergency pfmemalloc reserves are being used. If it is and
545 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
546 * may be used. Otherwise, the packet data may be discarded until enough
549 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
552 bool ret_pfmemalloc = false;
556 obj_size = SKB_HEAD_ALIGN(*size);
557 if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
558 !(flags & KMALLOC_NOT_NORMAL_BITS)) {
559 obj = kmem_cache_alloc_node(skb_small_head_cache,
560 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
562 *size = SKB_SMALL_HEAD_CACHE_SIZE;
563 if (obj || !(gfp_pfmemalloc_allowed(flags)))
565 /* Try again but now we are using pfmemalloc reserves */
566 ret_pfmemalloc = true;
567 obj = kmem_cache_alloc_node(skb_small_head_cache, flags, node);
571 obj_size = kmalloc_size_roundup(obj_size);
572 /* The following cast might truncate high-order bits of obj_size, this
573 * is harmless because kmalloc(obj_size >= 2^32) will fail anyway.
575 *size = (unsigned int)obj_size;
578 * Try a regular allocation, when that fails and we're not entitled
579 * to the reserves, fail.
581 obj = kmalloc_node_track_caller(obj_size,
582 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
584 if (obj || !(gfp_pfmemalloc_allowed(flags)))
587 /* Try again but now we are using pfmemalloc reserves */
588 ret_pfmemalloc = true;
589 obj = kmalloc_node_track_caller(obj_size, flags, node);
593 *pfmemalloc = ret_pfmemalloc;
598 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
599 * 'private' fields and also do memory statistics to find all the
605 * __alloc_skb - allocate a network buffer
606 * @size: size to allocate
607 * @gfp_mask: allocation mask
608 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
609 * instead of head cache and allocate a cloned (child) skb.
610 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
611 * allocations in case the data is required for writeback
612 * @node: numa node to allocate memory on
614 * Allocate a new &sk_buff. The returned buffer has no headroom and a
615 * tail room of at least size bytes. The object has a reference count
616 * of one. The return is the buffer. On a failure the return is %NULL.
618 * Buffers may only be allocated from interrupts using a @gfp_mask of
621 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
624 struct kmem_cache *cache;
629 cache = (flags & SKB_ALLOC_FCLONE)
630 ? skbuff_fclone_cache : skbuff_cache;
632 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
633 gfp_mask |= __GFP_MEMALLOC;
636 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
637 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
638 skb = napi_skb_cache_get();
640 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
645 /* We do our best to align skb_shared_info on a separate cache
646 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
647 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
648 * Both skb->head and skb_shared_info are cache line aligned.
650 data = kmalloc_reserve(&size, gfp_mask, node, &pfmemalloc);
653 /* kmalloc_size_roundup() might give us more room than requested.
654 * Put skb_shared_info exactly at the end of allocated zone,
655 * to allow max possible filling before reallocation.
657 prefetchw(data + SKB_WITH_OVERHEAD(size));
660 * Only clear those fields we need to clear, not those that we will
661 * actually initialise below. Hence, don't put any more fields after
662 * the tail pointer in struct sk_buff!
664 memset(skb, 0, offsetof(struct sk_buff, tail));
665 __build_skb_around(skb, data, size);
666 skb->pfmemalloc = pfmemalloc;
668 if (flags & SKB_ALLOC_FCLONE) {
669 struct sk_buff_fclones *fclones;
671 fclones = container_of(skb, struct sk_buff_fclones, skb1);
673 skb->fclone = SKB_FCLONE_ORIG;
674 refcount_set(&fclones->fclone_ref, 1);
680 kmem_cache_free(cache, skb);
683 EXPORT_SYMBOL(__alloc_skb);
686 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
687 * @dev: network device to receive on
688 * @len: length to allocate
689 * @gfp_mask: get_free_pages mask, passed to alloc_skb
691 * Allocate a new &sk_buff and assign it a usage count of one. The
692 * buffer has NET_SKB_PAD headroom built in. Users should allocate
693 * the headroom they think they need without accounting for the
694 * built in space. The built in space is used for optimisations.
696 * %NULL is returned if there is no free memory.
698 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
701 struct page_frag_cache *nc;
708 /* If requested length is either too small or too big,
709 * we use kmalloc() for skb->head allocation.
711 if (len <= SKB_WITH_OVERHEAD(1024) ||
712 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
713 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
714 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
720 len = SKB_HEAD_ALIGN(len);
722 if (sk_memalloc_socks())
723 gfp_mask |= __GFP_MEMALLOC;
725 if (in_hardirq() || irqs_disabled()) {
726 nc = this_cpu_ptr(&netdev_alloc_cache);
727 data = page_frag_alloc(nc, len, gfp_mask);
728 pfmemalloc = nc->pfmemalloc;
731 nc = this_cpu_ptr(&napi_alloc_cache.page);
732 data = page_frag_alloc(nc, len, gfp_mask);
733 pfmemalloc = nc->pfmemalloc;
740 skb = __build_skb(data, len);
741 if (unlikely(!skb)) {
751 skb_reserve(skb, NET_SKB_PAD);
757 EXPORT_SYMBOL(__netdev_alloc_skb);
760 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
761 * @napi: napi instance this buffer was allocated for
762 * @len: length to allocate
763 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
765 * Allocate a new sk_buff for use in NAPI receive. This buffer will
766 * attempt to allocate the head from a special reserved region used
767 * only for NAPI Rx allocation. By doing this we can save several
768 * CPU cycles by avoiding having to disable and re-enable IRQs.
770 * %NULL is returned if there is no free memory.
772 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
775 struct napi_alloc_cache *nc;
780 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
781 len += NET_SKB_PAD + NET_IP_ALIGN;
783 /* If requested length is either too small or too big,
784 * we use kmalloc() for skb->head allocation.
785 * When the small frag allocator is available, prefer it over kmalloc
786 * for small fragments
788 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
789 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
790 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
791 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
798 nc = this_cpu_ptr(&napi_alloc_cache);
800 if (sk_memalloc_socks())
801 gfp_mask |= __GFP_MEMALLOC;
803 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
804 /* we are artificially inflating the allocation size, but
805 * that is not as bad as it may look like, as:
806 * - 'len' less than GRO_MAX_HEAD makes little sense
807 * - On most systems, larger 'len' values lead to fragment
808 * size above 512 bytes
809 * - kmalloc would use the kmalloc-1k slab for such values
810 * - Builds with smaller GRO_MAX_HEAD will very likely do
811 * little networking, as that implies no WiFi and no
812 * tunnels support, and 32 bits arches.
816 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
817 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
819 len = SKB_HEAD_ALIGN(len);
821 data = page_frag_alloc(&nc->page, len, gfp_mask);
822 pfmemalloc = nc->page.pfmemalloc;
828 skb = __napi_build_skb(data, len);
829 if (unlikely(!skb)) {
839 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
840 skb->dev = napi->dev;
845 EXPORT_SYMBOL(__napi_alloc_skb);
847 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
848 int size, unsigned int truesize)
850 skb_fill_page_desc(skb, i, page, off, size);
852 skb->data_len += size;
853 skb->truesize += truesize;
855 EXPORT_SYMBOL(skb_add_rx_frag);
857 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
858 unsigned int truesize)
860 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
862 skb_frag_size_add(frag, size);
864 skb->data_len += size;
865 skb->truesize += truesize;
867 EXPORT_SYMBOL(skb_coalesce_rx_frag);
869 static void skb_drop_list(struct sk_buff **listp)
871 kfree_skb_list(*listp);
875 static inline void skb_drop_fraglist(struct sk_buff *skb)
877 skb_drop_list(&skb_shinfo(skb)->frag_list);
880 static void skb_clone_fraglist(struct sk_buff *skb)
882 struct sk_buff *list;
884 skb_walk_frags(skb, list)
888 #if IS_ENABLED(CONFIG_PAGE_POOL)
889 bool napi_pp_put_page(struct page *page, bool napi_safe)
891 bool allow_direct = false;
892 struct page_pool *pp;
894 page = compound_head(page);
896 /* page->pp_magic is OR'ed with PP_SIGNATURE after the allocation
897 * in order to preserve any existing bits, such as bit 0 for the
898 * head page of compound page and bit 1 for pfmemalloc page, so
899 * mask those bits for freeing side when doing below checking,
900 * and page_is_pfmemalloc() is checked in __page_pool_put_page()
901 * to avoid recycling the pfmemalloc page.
903 if (unlikely((page->pp_magic & ~0x3UL) != PP_SIGNATURE))
908 /* Allow direct recycle if we have reasons to believe that we are
909 * in the same context as the consumer would run, so there's
911 * __page_pool_put_page() makes sure we're not in hardirq context
912 * and interrupts are enabled prior to accessing the cache.
914 if (napi_safe || in_softirq()) {
915 const struct napi_struct *napi = READ_ONCE(pp->p.napi);
917 allow_direct = napi &&
918 READ_ONCE(napi->list_owner) == smp_processor_id();
921 /* Driver set this to memory recycling info. Reset it on recycle.
922 * This will *not* work for NIC using a split-page memory model.
923 * The page will be returned to the pool here regardless of the
924 * 'flipped' fragment being in use or not.
926 page_pool_put_full_page(pp, page, allow_direct);
930 EXPORT_SYMBOL(napi_pp_put_page);
933 static bool skb_pp_recycle(struct sk_buff *skb, void *data, bool napi_safe)
935 if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
937 return napi_pp_put_page(virt_to_page(data), napi_safe);
940 static void skb_kfree_head(void *head, unsigned int end_offset)
942 if (end_offset == SKB_SMALL_HEAD_HEADROOM)
943 kmem_cache_free(skb_small_head_cache, head);
948 static void skb_free_head(struct sk_buff *skb, bool napi_safe)
950 unsigned char *head = skb->head;
952 if (skb->head_frag) {
953 if (skb_pp_recycle(skb, head, napi_safe))
957 skb_kfree_head(head, skb_end_offset(skb));
961 static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason,
964 struct skb_shared_info *shinfo = skb_shinfo(skb);
968 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
972 if (skb_zcopy(skb)) {
973 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
975 skb_zcopy_clear(skb, true);
980 for (i = 0; i < shinfo->nr_frags; i++)
981 napi_frag_unref(&shinfo->frags[i], skb->pp_recycle, napi_safe);
984 if (shinfo->frag_list)
985 kfree_skb_list_reason(shinfo->frag_list, reason);
987 skb_free_head(skb, napi_safe);
989 /* When we clone an SKB we copy the reycling bit. The pp_recycle
990 * bit is only set on the head though, so in order to avoid races
991 * while trying to recycle fragments on __skb_frag_unref() we need
992 * to make one SKB responsible for triggering the recycle path.
993 * So disable the recycling bit if an SKB is cloned and we have
994 * additional references to the fragmented part of the SKB.
995 * Eventually the last SKB will have the recycling bit set and it's
996 * dataref set to 0, which will trigger the recycling
1002 * Free an skbuff by memory without cleaning the state.
1004 static void kfree_skbmem(struct sk_buff *skb)
1006 struct sk_buff_fclones *fclones;
1008 switch (skb->fclone) {
1009 case SKB_FCLONE_UNAVAILABLE:
1010 kmem_cache_free(skbuff_cache, skb);
1013 case SKB_FCLONE_ORIG:
1014 fclones = container_of(skb, struct sk_buff_fclones, skb1);
1016 /* We usually free the clone (TX completion) before original skb
1017 * This test would have no chance to be true for the clone,
1018 * while here, branch prediction will be good.
1020 if (refcount_read(&fclones->fclone_ref) == 1)
1024 default: /* SKB_FCLONE_CLONE */
1025 fclones = container_of(skb, struct sk_buff_fclones, skb2);
1028 if (!refcount_dec_and_test(&fclones->fclone_ref))
1031 kmem_cache_free(skbuff_fclone_cache, fclones);
1034 void skb_release_head_state(struct sk_buff *skb)
1037 if (skb->destructor) {
1038 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
1039 skb->destructor(skb);
1041 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
1042 nf_conntrack_put(skb_nfct(skb));
1047 /* Free everything but the sk_buff shell. */
1048 static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason,
1051 skb_release_head_state(skb);
1052 if (likely(skb->head))
1053 skb_release_data(skb, reason, napi_safe);
1057 * __kfree_skb - private function
1060 * Free an sk_buff. Release anything attached to the buffer.
1061 * Clean the state. This is an internal helper function. Users should
1062 * always call kfree_skb
1065 void __kfree_skb(struct sk_buff *skb)
1067 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED, false);
1070 EXPORT_SYMBOL(__kfree_skb);
1072 static __always_inline
1073 bool __kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1075 if (unlikely(!skb_unref(skb)))
1078 DEBUG_NET_WARN_ON_ONCE(reason == SKB_NOT_DROPPED_YET ||
1079 u32_get_bits(reason,
1080 SKB_DROP_REASON_SUBSYS_MASK) >=
1081 SKB_DROP_REASON_SUBSYS_NUM);
1083 if (reason == SKB_CONSUMED)
1084 trace_consume_skb(skb, __builtin_return_address(0));
1086 trace_kfree_skb(skb, __builtin_return_address(0), reason);
1091 * kfree_skb_reason - free an sk_buff with special reason
1092 * @skb: buffer to free
1093 * @reason: reason why this skb is dropped
1095 * Drop a reference to the buffer and free it if the usage count has
1096 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
1100 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1102 if (__kfree_skb_reason(skb, reason))
1105 EXPORT_SYMBOL(kfree_skb_reason);
1107 #define KFREE_SKB_BULK_SIZE 16
1109 struct skb_free_array {
1110 unsigned int skb_count;
1111 void *skb_array[KFREE_SKB_BULK_SIZE];
1114 static void kfree_skb_add_bulk(struct sk_buff *skb,
1115 struct skb_free_array *sa,
1116 enum skb_drop_reason reason)
1118 /* if SKB is a clone, don't handle this case */
1119 if (unlikely(skb->fclone != SKB_FCLONE_UNAVAILABLE)) {
1124 skb_release_all(skb, reason, false);
1125 sa->skb_array[sa->skb_count++] = skb;
1127 if (unlikely(sa->skb_count == KFREE_SKB_BULK_SIZE)) {
1128 kmem_cache_free_bulk(skbuff_cache, KFREE_SKB_BULK_SIZE,
1135 kfree_skb_list_reason(struct sk_buff *segs, enum skb_drop_reason reason)
1137 struct skb_free_array sa;
1142 struct sk_buff *next = segs->next;
1144 if (__kfree_skb_reason(segs, reason)) {
1145 skb_poison_list(segs);
1146 kfree_skb_add_bulk(segs, &sa, reason);
1153 kmem_cache_free_bulk(skbuff_cache, sa.skb_count, sa.skb_array);
1155 EXPORT_SYMBOL(kfree_skb_list_reason);
1157 /* Dump skb information and contents.
1159 * Must only be called from net_ratelimit()-ed paths.
1161 * Dumps whole packets if full_pkt, only headers otherwise.
1163 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
1165 struct skb_shared_info *sh = skb_shinfo(skb);
1166 struct net_device *dev = skb->dev;
1167 struct sock *sk = skb->sk;
1168 struct sk_buff *list_skb;
1169 bool has_mac, has_trans;
1170 int headroom, tailroom;
1171 int i, len, seg_len;
1176 len = min_t(int, skb->len, MAX_HEADER + 128);
1178 headroom = skb_headroom(skb);
1179 tailroom = skb_tailroom(skb);
1181 has_mac = skb_mac_header_was_set(skb);
1182 has_trans = skb_transport_header_was_set(skb);
1184 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
1185 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
1186 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
1187 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
1188 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
1189 level, skb->len, headroom, skb_headlen(skb), tailroom,
1190 has_mac ? skb->mac_header : -1,
1191 has_mac ? skb_mac_header_len(skb) : -1,
1192 skb->network_header,
1193 has_trans ? skb_network_header_len(skb) : -1,
1194 has_trans ? skb->transport_header : -1,
1195 sh->tx_flags, sh->nr_frags,
1196 sh->gso_size, sh->gso_type, sh->gso_segs,
1197 skb->csum, skb->ip_summed, skb->csum_complete_sw,
1198 skb->csum_valid, skb->csum_level,
1199 skb->hash, skb->sw_hash, skb->l4_hash,
1200 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
1203 printk("%sdev name=%s feat=%pNF\n",
1204 level, dev->name, &dev->features);
1206 printk("%ssk family=%hu type=%u proto=%u\n",
1207 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
1209 if (full_pkt && headroom)
1210 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
1211 16, 1, skb->head, headroom, false);
1213 seg_len = min_t(int, skb_headlen(skb), len);
1215 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
1216 16, 1, skb->data, seg_len, false);
1219 if (full_pkt && tailroom)
1220 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
1221 16, 1, skb_tail_pointer(skb), tailroom, false);
1223 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
1224 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1225 u32 p_off, p_len, copied;
1229 skb_frag_foreach_page(frag, skb_frag_off(frag),
1230 skb_frag_size(frag), p, p_off, p_len,
1232 seg_len = min_t(int, p_len, len);
1233 vaddr = kmap_atomic(p);
1234 print_hex_dump(level, "skb frag: ",
1236 16, 1, vaddr + p_off, seg_len, false);
1237 kunmap_atomic(vaddr);
1244 if (full_pkt && skb_has_frag_list(skb)) {
1245 printk("skb fraglist:\n");
1246 skb_walk_frags(skb, list_skb)
1247 skb_dump(level, list_skb, true);
1250 EXPORT_SYMBOL(skb_dump);
1253 * skb_tx_error - report an sk_buff xmit error
1254 * @skb: buffer that triggered an error
1256 * Report xmit error if a device callback is tracking this skb.
1257 * skb must be freed afterwards.
1259 void skb_tx_error(struct sk_buff *skb)
1262 skb_zcopy_downgrade_managed(skb);
1263 skb_zcopy_clear(skb, true);
1266 EXPORT_SYMBOL(skb_tx_error);
1268 #ifdef CONFIG_TRACEPOINTS
1270 * consume_skb - free an skbuff
1271 * @skb: buffer to free
1273 * Drop a ref to the buffer and free it if the usage count has hit zero
1274 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1275 * is being dropped after a failure and notes that
1277 void consume_skb(struct sk_buff *skb)
1279 if (!skb_unref(skb))
1282 trace_consume_skb(skb, __builtin_return_address(0));
1285 EXPORT_SYMBOL(consume_skb);
1289 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1290 * @skb: buffer to free
1292 * Alike consume_skb(), but this variant assumes that this is the last
1293 * skb reference and all the head states have been already dropped
1295 void __consume_stateless_skb(struct sk_buff *skb)
1297 trace_consume_skb(skb, __builtin_return_address(0));
1298 skb_release_data(skb, SKB_CONSUMED, false);
1302 static void napi_skb_cache_put(struct sk_buff *skb)
1304 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1307 kasan_poison_object_data(skbuff_cache, skb);
1308 nc->skb_cache[nc->skb_count++] = skb;
1310 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1311 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1312 kasan_unpoison_object_data(skbuff_cache,
1315 kmem_cache_free_bulk(skbuff_cache, NAPI_SKB_CACHE_HALF,
1316 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1317 nc->skb_count = NAPI_SKB_CACHE_HALF;
1321 void __napi_kfree_skb(struct sk_buff *skb, enum skb_drop_reason reason)
1323 skb_release_all(skb, reason, true);
1324 napi_skb_cache_put(skb);
1327 void napi_skb_free_stolen_head(struct sk_buff *skb)
1329 if (unlikely(skb->slow_gro)) {
1336 napi_skb_cache_put(skb);
1339 void napi_consume_skb(struct sk_buff *skb, int budget)
1341 /* Zero budget indicate non-NAPI context called us, like netpoll */
1342 if (unlikely(!budget)) {
1343 dev_consume_skb_any(skb);
1347 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1349 if (!skb_unref(skb))
1352 /* if reaching here SKB is ready to free */
1353 trace_consume_skb(skb, __builtin_return_address(0));
1355 /* if SKB is a clone, don't handle this case */
1356 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1361 skb_release_all(skb, SKB_CONSUMED, !!budget);
1362 napi_skb_cache_put(skb);
1364 EXPORT_SYMBOL(napi_consume_skb);
1366 /* Make sure a field is contained by headers group */
1367 #define CHECK_SKB_FIELD(field) \
1368 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1369 offsetof(struct sk_buff, headers.field)); \
1371 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1373 new->tstamp = old->tstamp;
1374 /* We do not copy old->sk */
1375 new->dev = old->dev;
1376 memcpy(new->cb, old->cb, sizeof(old->cb));
1377 skb_dst_copy(new, old);
1378 __skb_ext_copy(new, old);
1379 __nf_copy(new, old, false);
1381 /* Note : this field could be in the headers group.
1382 * It is not yet because we do not want to have a 16 bit hole
1384 new->queue_mapping = old->queue_mapping;
1386 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1387 CHECK_SKB_FIELD(protocol);
1388 CHECK_SKB_FIELD(csum);
1389 CHECK_SKB_FIELD(hash);
1390 CHECK_SKB_FIELD(priority);
1391 CHECK_SKB_FIELD(skb_iif);
1392 CHECK_SKB_FIELD(vlan_proto);
1393 CHECK_SKB_FIELD(vlan_tci);
1394 CHECK_SKB_FIELD(transport_header);
1395 CHECK_SKB_FIELD(network_header);
1396 CHECK_SKB_FIELD(mac_header);
1397 CHECK_SKB_FIELD(inner_protocol);
1398 CHECK_SKB_FIELD(inner_transport_header);
1399 CHECK_SKB_FIELD(inner_network_header);
1400 CHECK_SKB_FIELD(inner_mac_header);
1401 CHECK_SKB_FIELD(mark);
1402 #ifdef CONFIG_NETWORK_SECMARK
1403 CHECK_SKB_FIELD(secmark);
1405 #ifdef CONFIG_NET_RX_BUSY_POLL
1406 CHECK_SKB_FIELD(napi_id);
1408 CHECK_SKB_FIELD(alloc_cpu);
1410 CHECK_SKB_FIELD(sender_cpu);
1412 #ifdef CONFIG_NET_SCHED
1413 CHECK_SKB_FIELD(tc_index);
1419 * You should not add any new code to this function. Add it to
1420 * __copy_skb_header above instead.
1422 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1424 #define C(x) n->x = skb->x
1426 n->next = n->prev = NULL;
1428 __copy_skb_header(n, skb);
1433 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1439 n->destructor = NULL;
1446 refcount_set(&n->users, 1);
1448 atomic_inc(&(skb_shinfo(skb)->dataref));
1456 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1457 * @first: first sk_buff of the msg
1459 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1463 n = alloc_skb(0, GFP_ATOMIC);
1467 n->len = first->len;
1468 n->data_len = first->len;
1469 n->truesize = first->truesize;
1471 skb_shinfo(n)->frag_list = first;
1473 __copy_skb_header(n, first);
1474 n->destructor = NULL;
1478 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1481 * skb_morph - morph one skb into another
1482 * @dst: the skb to receive the contents
1483 * @src: the skb to supply the contents
1485 * This is identical to skb_clone except that the target skb is
1486 * supplied by the user.
1488 * The target skb is returned upon exit.
1490 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1492 skb_release_all(dst, SKB_CONSUMED, false);
1493 return __skb_clone(dst, src);
1495 EXPORT_SYMBOL_GPL(skb_morph);
1497 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1499 unsigned long max_pg, num_pg, new_pg, old_pg, rlim;
1500 struct user_struct *user;
1502 if (capable(CAP_IPC_LOCK) || !size)
1505 rlim = rlimit(RLIMIT_MEMLOCK);
1506 if (rlim == RLIM_INFINITY)
1509 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1510 max_pg = rlim >> PAGE_SHIFT;
1511 user = mmp->user ? : current_user();
1513 old_pg = atomic_long_read(&user->locked_vm);
1515 new_pg = old_pg + num_pg;
1516 if (new_pg > max_pg)
1518 } while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1521 mmp->user = get_uid(user);
1522 mmp->num_pg = num_pg;
1524 mmp->num_pg += num_pg;
1529 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1531 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1534 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1535 free_uid(mmp->user);
1538 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1540 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1542 struct ubuf_info_msgzc *uarg;
1543 struct sk_buff *skb;
1545 WARN_ON_ONCE(!in_task());
1547 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1551 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1552 uarg = (void *)skb->cb;
1553 uarg->mmp.user = NULL;
1555 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1560 uarg->ubuf.callback = msg_zerocopy_callback;
1561 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1563 uarg->bytelen = size;
1565 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1566 refcount_set(&uarg->ubuf.refcnt, 1);
1572 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1574 return container_of((void *)uarg, struct sk_buff, cb);
1577 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1578 struct ubuf_info *uarg)
1581 struct ubuf_info_msgzc *uarg_zc;
1582 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1585 /* there might be non MSG_ZEROCOPY users */
1586 if (uarg->callback != msg_zerocopy_callback)
1589 /* realloc only when socket is locked (TCP, UDP cork),
1590 * so uarg->len and sk_zckey access is serialized
1592 if (!sock_owned_by_user(sk)) {
1597 uarg_zc = uarg_to_msgzc(uarg);
1598 bytelen = uarg_zc->bytelen + size;
1599 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1600 /* TCP can create new skb to attach new uarg */
1601 if (sk->sk_type == SOCK_STREAM)
1606 next = (u32)atomic_read(&sk->sk_zckey);
1607 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1608 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1611 uarg_zc->bytelen = bytelen;
1612 atomic_set(&sk->sk_zckey, ++next);
1614 /* no extra ref when appending to datagram (MSG_MORE) */
1615 if (sk->sk_type == SOCK_STREAM)
1616 net_zcopy_get(uarg);
1623 return msg_zerocopy_alloc(sk, size);
1625 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1627 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1629 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1633 old_lo = serr->ee.ee_info;
1634 old_hi = serr->ee.ee_data;
1635 sum_len = old_hi - old_lo + 1ULL + len;
1637 if (sum_len >= (1ULL << 32))
1640 if (lo != old_hi + 1)
1643 serr->ee.ee_data += len;
1647 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1649 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1650 struct sock_exterr_skb *serr;
1651 struct sock *sk = skb->sk;
1652 struct sk_buff_head *q;
1653 unsigned long flags;
1658 mm_unaccount_pinned_pages(&uarg->mmp);
1660 /* if !len, there was only 1 call, and it was aborted
1661 * so do not queue a completion notification
1663 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1668 hi = uarg->id + len - 1;
1669 is_zerocopy = uarg->zerocopy;
1671 serr = SKB_EXT_ERR(skb);
1672 memset(serr, 0, sizeof(*serr));
1673 serr->ee.ee_errno = 0;
1674 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1675 serr->ee.ee_data = hi;
1676 serr->ee.ee_info = lo;
1678 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1680 q = &sk->sk_error_queue;
1681 spin_lock_irqsave(&q->lock, flags);
1682 tail = skb_peek_tail(q);
1683 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1684 !skb_zerocopy_notify_extend(tail, lo, len)) {
1685 __skb_queue_tail(q, skb);
1688 spin_unlock_irqrestore(&q->lock, flags);
1690 sk_error_report(sk);
1697 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1700 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1702 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1704 if (refcount_dec_and_test(&uarg->refcnt))
1705 __msg_zerocopy_callback(uarg_zc);
1707 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1709 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1711 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1713 atomic_dec(&sk->sk_zckey);
1714 uarg_to_msgzc(uarg)->len--;
1717 msg_zerocopy_callback(NULL, uarg, true);
1719 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1721 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1722 struct msghdr *msg, int len,
1723 struct ubuf_info *uarg)
1725 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1726 int err, orig_len = skb->len;
1728 /* An skb can only point to one uarg. This edge case happens when
1729 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1731 if (orig_uarg && uarg != orig_uarg)
1734 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1735 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1736 struct sock *save_sk = skb->sk;
1738 /* Streams do not free skb on error. Reset to prev state. */
1739 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1741 ___pskb_trim(skb, orig_len);
1746 skb_zcopy_set(skb, uarg, NULL);
1747 return skb->len - orig_len;
1749 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1751 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1755 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1756 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1757 skb_frag_ref(skb, i);
1759 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1761 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1764 if (skb_zcopy(orig)) {
1765 if (skb_zcopy(nskb)) {
1766 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1771 if (skb_uarg(nskb) == skb_uarg(orig))
1773 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1776 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1782 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1783 * @skb: the skb to modify
1784 * @gfp_mask: allocation priority
1786 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1787 * It will copy all frags into kernel and drop the reference
1788 * to userspace pages.
1790 * If this function is called from an interrupt gfp_mask() must be
1793 * Returns 0 on success or a negative error code on failure
1794 * to allocate kernel memory to copy to.
1796 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1798 int num_frags = skb_shinfo(skb)->nr_frags;
1799 struct page *page, *head = NULL;
1800 int i, order, psize, new_frags;
1803 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1809 /* We might have to allocate high order pages, so compute what minimum
1810 * page order is needed.
1813 while ((PAGE_SIZE << order) * MAX_SKB_FRAGS < __skb_pagelen(skb))
1815 psize = (PAGE_SIZE << order);
1817 new_frags = (__skb_pagelen(skb) + psize - 1) >> (PAGE_SHIFT + order);
1818 for (i = 0; i < new_frags; i++) {
1819 page = alloc_pages(gfp_mask | __GFP_COMP, order);
1822 struct page *next = (struct page *)page_private(head);
1828 set_page_private(page, (unsigned long)head);
1834 for (i = 0; i < num_frags; i++) {
1835 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1836 u32 p_off, p_len, copied;
1840 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1841 p, p_off, p_len, copied) {
1843 vaddr = kmap_atomic(p);
1845 while (done < p_len) {
1846 if (d_off == psize) {
1848 page = (struct page *)page_private(page);
1850 copy = min_t(u32, psize - d_off, p_len - done);
1851 memcpy(page_address(page) + d_off,
1852 vaddr + p_off + done, copy);
1856 kunmap_atomic(vaddr);
1860 /* skb frags release userspace buffers */
1861 for (i = 0; i < num_frags; i++)
1862 skb_frag_unref(skb, i);
1864 /* skb frags point to kernel buffers */
1865 for (i = 0; i < new_frags - 1; i++) {
1866 __skb_fill_page_desc(skb, i, head, 0, psize);
1867 head = (struct page *)page_private(head);
1869 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1870 skb_shinfo(skb)->nr_frags = new_frags;
1873 skb_zcopy_clear(skb, false);
1876 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1879 * skb_clone - duplicate an sk_buff
1880 * @skb: buffer to clone
1881 * @gfp_mask: allocation priority
1883 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1884 * copies share the same packet data but not structure. The new
1885 * buffer has a reference count of 1. If the allocation fails the
1886 * function returns %NULL otherwise the new buffer is returned.
1888 * If this function is called from an interrupt gfp_mask() must be
1892 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1894 struct sk_buff_fclones *fclones = container_of(skb,
1895 struct sk_buff_fclones,
1899 if (skb_orphan_frags(skb, gfp_mask))
1902 if (skb->fclone == SKB_FCLONE_ORIG &&
1903 refcount_read(&fclones->fclone_ref) == 1) {
1905 refcount_set(&fclones->fclone_ref, 2);
1906 n->fclone = SKB_FCLONE_CLONE;
1908 if (skb_pfmemalloc(skb))
1909 gfp_mask |= __GFP_MEMALLOC;
1911 n = kmem_cache_alloc(skbuff_cache, gfp_mask);
1915 n->fclone = SKB_FCLONE_UNAVAILABLE;
1918 return __skb_clone(n, skb);
1920 EXPORT_SYMBOL(skb_clone);
1922 void skb_headers_offset_update(struct sk_buff *skb, int off)
1924 /* Only adjust this if it actually is csum_start rather than csum */
1925 if (skb->ip_summed == CHECKSUM_PARTIAL)
1926 skb->csum_start += off;
1927 /* {transport,network,mac}_header and tail are relative to skb->head */
1928 skb->transport_header += off;
1929 skb->network_header += off;
1930 if (skb_mac_header_was_set(skb))
1931 skb->mac_header += off;
1932 skb->inner_transport_header += off;
1933 skb->inner_network_header += off;
1934 skb->inner_mac_header += off;
1936 EXPORT_SYMBOL(skb_headers_offset_update);
1938 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1940 __copy_skb_header(new, old);
1942 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1943 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1944 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1946 EXPORT_SYMBOL(skb_copy_header);
1948 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1950 if (skb_pfmemalloc(skb))
1951 return SKB_ALLOC_RX;
1956 * skb_copy - create private copy of an sk_buff
1957 * @skb: buffer to copy
1958 * @gfp_mask: allocation priority
1960 * Make a copy of both an &sk_buff and its data. This is used when the
1961 * caller wishes to modify the data and needs a private copy of the
1962 * data to alter. Returns %NULL on failure or the pointer to the buffer
1963 * on success. The returned buffer has a reference count of 1.
1965 * As by-product this function converts non-linear &sk_buff to linear
1966 * one, so that &sk_buff becomes completely private and caller is allowed
1967 * to modify all the data of returned buffer. This means that this
1968 * function is not recommended for use in circumstances when only
1969 * header is going to be modified. Use pskb_copy() instead.
1972 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1974 int headerlen = skb_headroom(skb);
1975 unsigned int size = skb_end_offset(skb) + skb->data_len;
1976 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1977 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1982 /* Set the data pointer */
1983 skb_reserve(n, headerlen);
1984 /* Set the tail pointer and length */
1985 skb_put(n, skb->len);
1987 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1989 skb_copy_header(n, skb);
1992 EXPORT_SYMBOL(skb_copy);
1995 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1996 * @skb: buffer to copy
1997 * @headroom: headroom of new skb
1998 * @gfp_mask: allocation priority
1999 * @fclone: if true allocate the copy of the skb from the fclone
2000 * cache instead of the head cache; it is recommended to set this
2001 * to true for the cases where the copy will likely be cloned
2003 * Make a copy of both an &sk_buff and part of its data, located
2004 * in header. Fragmented data remain shared. This is used when
2005 * the caller wishes to modify only header of &sk_buff and needs
2006 * private copy of the header to alter. Returns %NULL on failure
2007 * or the pointer to the buffer on success.
2008 * The returned buffer has a reference count of 1.
2011 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
2012 gfp_t gfp_mask, bool fclone)
2014 unsigned int size = skb_headlen(skb) + headroom;
2015 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
2016 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
2021 /* Set the data pointer */
2022 skb_reserve(n, headroom);
2023 /* Set the tail pointer and length */
2024 skb_put(n, skb_headlen(skb));
2025 /* Copy the bytes */
2026 skb_copy_from_linear_data(skb, n->data, n->len);
2028 n->truesize += skb->data_len;
2029 n->data_len = skb->data_len;
2032 if (skb_shinfo(skb)->nr_frags) {
2035 if (skb_orphan_frags(skb, gfp_mask) ||
2036 skb_zerocopy_clone(n, skb, gfp_mask)) {
2041 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2042 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
2043 skb_frag_ref(skb, i);
2045 skb_shinfo(n)->nr_frags = i;
2048 if (skb_has_frag_list(skb)) {
2049 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
2050 skb_clone_fraglist(n);
2053 skb_copy_header(n, skb);
2057 EXPORT_SYMBOL(__pskb_copy_fclone);
2060 * pskb_expand_head - reallocate header of &sk_buff
2061 * @skb: buffer to reallocate
2062 * @nhead: room to add at head
2063 * @ntail: room to add at tail
2064 * @gfp_mask: allocation priority
2066 * Expands (or creates identical copy, if @nhead and @ntail are zero)
2067 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
2068 * reference count of 1. Returns zero in the case of success or error,
2069 * if expansion failed. In the last case, &sk_buff is not changed.
2071 * All the pointers pointing into skb header may change and must be
2072 * reloaded after call to this function.
2075 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
2078 unsigned int osize = skb_end_offset(skb);
2079 unsigned int size = osize + nhead + ntail;
2086 BUG_ON(skb_shared(skb));
2088 skb_zcopy_downgrade_managed(skb);
2090 if (skb_pfmemalloc(skb))
2091 gfp_mask |= __GFP_MEMALLOC;
2093 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
2096 size = SKB_WITH_OVERHEAD(size);
2098 /* Copy only real data... and, alas, header. This should be
2099 * optimized for the cases when header is void.
2101 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
2103 memcpy((struct skb_shared_info *)(data + size),
2105 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
2108 * if shinfo is shared we must drop the old head gracefully, but if it
2109 * is not we can just drop the old head and let the existing refcount
2110 * be since all we did is relocate the values
2112 if (skb_cloned(skb)) {
2113 if (skb_orphan_frags(skb, gfp_mask))
2116 refcount_inc(&skb_uarg(skb)->refcnt);
2117 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2118 skb_frag_ref(skb, i);
2120 if (skb_has_frag_list(skb))
2121 skb_clone_fraglist(skb);
2123 skb_release_data(skb, SKB_CONSUMED, false);
2125 skb_free_head(skb, false);
2127 off = (data + nhead) - skb->head;
2133 skb_set_end_offset(skb, size);
2134 #ifdef NET_SKBUFF_DATA_USES_OFFSET
2138 skb_headers_offset_update(skb, nhead);
2142 atomic_set(&skb_shinfo(skb)->dataref, 1);
2144 skb_metadata_clear(skb);
2146 /* It is not generally safe to change skb->truesize.
2147 * For the moment, we really care of rx path, or
2148 * when skb is orphaned (not attached to a socket).
2150 if (!skb->sk || skb->destructor == sock_edemux)
2151 skb->truesize += size - osize;
2156 skb_kfree_head(data, size);
2160 EXPORT_SYMBOL(pskb_expand_head);
2162 /* Make private copy of skb with writable head and some headroom */
2164 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
2166 struct sk_buff *skb2;
2167 int delta = headroom - skb_headroom(skb);
2170 skb2 = pskb_copy(skb, GFP_ATOMIC);
2172 skb2 = skb_clone(skb, GFP_ATOMIC);
2173 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
2181 EXPORT_SYMBOL(skb_realloc_headroom);
2183 /* Note: We plan to rework this in linux-6.4 */
2184 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
2186 unsigned int saved_end_offset, saved_truesize;
2187 struct skb_shared_info *shinfo;
2190 saved_end_offset = skb_end_offset(skb);
2191 saved_truesize = skb->truesize;
2193 res = pskb_expand_head(skb, 0, 0, pri);
2197 skb->truesize = saved_truesize;
2199 if (likely(skb_end_offset(skb) == saved_end_offset))
2202 /* We can not change skb->end if the original or new value
2203 * is SKB_SMALL_HEAD_HEADROOM, as it might break skb_kfree_head().
2205 if (saved_end_offset == SKB_SMALL_HEAD_HEADROOM ||
2206 skb_end_offset(skb) == SKB_SMALL_HEAD_HEADROOM) {
2207 /* We think this path should not be taken.
2208 * Add a temporary trace to warn us just in case.
2210 pr_err_once("__skb_unclone_keeptruesize() skb_end_offset() %u -> %u\n",
2211 saved_end_offset, skb_end_offset(skb));
2216 shinfo = skb_shinfo(skb);
2218 /* We are about to change back skb->end,
2219 * we need to move skb_shinfo() to its new location.
2221 memmove(skb->head + saved_end_offset,
2223 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
2225 skb_set_end_offset(skb, saved_end_offset);
2231 * skb_expand_head - reallocate header of &sk_buff
2232 * @skb: buffer to reallocate
2233 * @headroom: needed headroom
2235 * Unlike skb_realloc_headroom, this one does not allocate a new skb
2236 * if possible; copies skb->sk to new skb as needed
2237 * and frees original skb in case of failures.
2239 * It expect increased headroom and generates warning otherwise.
2242 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2244 int delta = headroom - skb_headroom(skb);
2245 int osize = skb_end_offset(skb);
2246 struct sock *sk = skb->sk;
2248 if (WARN_ONCE(delta <= 0,
2249 "%s is expecting an increase in the headroom", __func__))
2252 delta = SKB_DATA_ALIGN(delta);
2253 /* pskb_expand_head() might crash, if skb is shared. */
2254 if (skb_shared(skb) || !is_skb_wmem(skb)) {
2255 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2257 if (unlikely(!nskb))
2261 skb_set_owner_w(nskb, sk);
2265 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2268 if (sk && is_skb_wmem(skb)) {
2269 delta = skb_end_offset(skb) - osize;
2270 refcount_add(delta, &sk->sk_wmem_alloc);
2271 skb->truesize += delta;
2279 EXPORT_SYMBOL(skb_expand_head);
2282 * skb_copy_expand - copy and expand sk_buff
2283 * @skb: buffer to copy
2284 * @newheadroom: new free bytes at head
2285 * @newtailroom: new free bytes at tail
2286 * @gfp_mask: allocation priority
2288 * Make a copy of both an &sk_buff and its data and while doing so
2289 * allocate additional space.
2291 * This is used when the caller wishes to modify the data and needs a
2292 * private copy of the data to alter as well as more space for new fields.
2293 * Returns %NULL on failure or the pointer to the buffer
2294 * on success. The returned buffer has a reference count of 1.
2296 * You must pass %GFP_ATOMIC as the allocation priority if this function
2297 * is called from an interrupt.
2299 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2300 int newheadroom, int newtailroom,
2304 * Allocate the copy buffer
2306 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2307 gfp_mask, skb_alloc_rx_flag(skb),
2309 int oldheadroom = skb_headroom(skb);
2310 int head_copy_len, head_copy_off;
2315 skb_reserve(n, newheadroom);
2317 /* Set the tail pointer and length */
2318 skb_put(n, skb->len);
2320 head_copy_len = oldheadroom;
2322 if (newheadroom <= head_copy_len)
2323 head_copy_len = newheadroom;
2325 head_copy_off = newheadroom - head_copy_len;
2327 /* Copy the linear header and data. */
2328 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2329 skb->len + head_copy_len));
2331 skb_copy_header(n, skb);
2333 skb_headers_offset_update(n, newheadroom - oldheadroom);
2337 EXPORT_SYMBOL(skb_copy_expand);
2340 * __skb_pad - zero pad the tail of an skb
2341 * @skb: buffer to pad
2342 * @pad: space to pad
2343 * @free_on_error: free buffer on error
2345 * Ensure that a buffer is followed by a padding area that is zero
2346 * filled. Used by network drivers which may DMA or transfer data
2347 * beyond the buffer end onto the wire.
2349 * May return error in out of memory cases. The skb is freed on error
2350 * if @free_on_error is true.
2353 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2358 /* If the skbuff is non linear tailroom is always zero.. */
2359 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2360 memset(skb->data+skb->len, 0, pad);
2364 ntail = skb->data_len + pad - (skb->end - skb->tail);
2365 if (likely(skb_cloned(skb) || ntail > 0)) {
2366 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2371 /* FIXME: The use of this function with non-linear skb's really needs
2374 err = skb_linearize(skb);
2378 memset(skb->data + skb->len, 0, pad);
2386 EXPORT_SYMBOL(__skb_pad);
2389 * pskb_put - add data to the tail of a potentially fragmented buffer
2390 * @skb: start of the buffer to use
2391 * @tail: tail fragment of the buffer to use
2392 * @len: amount of data to add
2394 * This function extends the used data area of the potentially
2395 * fragmented buffer. @tail must be the last fragment of @skb -- or
2396 * @skb itself. If this would exceed the total buffer size the kernel
2397 * will panic. A pointer to the first byte of the extra data is
2401 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2404 skb->data_len += len;
2407 return skb_put(tail, len);
2409 EXPORT_SYMBOL_GPL(pskb_put);
2412 * skb_put - add data to a buffer
2413 * @skb: buffer to use
2414 * @len: amount of data to add
2416 * This function extends the used data area of the buffer. If this would
2417 * exceed the total buffer size the kernel will panic. A pointer to the
2418 * first byte of the extra data is returned.
2420 void *skb_put(struct sk_buff *skb, unsigned int len)
2422 void *tmp = skb_tail_pointer(skb);
2423 SKB_LINEAR_ASSERT(skb);
2426 if (unlikely(skb->tail > skb->end))
2427 skb_over_panic(skb, len, __builtin_return_address(0));
2430 EXPORT_SYMBOL(skb_put);
2433 * skb_push - add data to the start of a buffer
2434 * @skb: buffer to use
2435 * @len: amount of data to add
2437 * This function extends the used data area of the buffer at the buffer
2438 * start. If this would exceed the total buffer headroom the kernel will
2439 * panic. A pointer to the first byte of the extra data is returned.
2441 void *skb_push(struct sk_buff *skb, unsigned int len)
2445 if (unlikely(skb->data < skb->head))
2446 skb_under_panic(skb, len, __builtin_return_address(0));
2449 EXPORT_SYMBOL(skb_push);
2452 * skb_pull - remove data from the start of a buffer
2453 * @skb: buffer to use
2454 * @len: amount of data to remove
2456 * This function removes data from the start of a buffer, returning
2457 * the memory to the headroom. A pointer to the next data in the buffer
2458 * is returned. Once the data has been pulled future pushes will overwrite
2461 void *skb_pull(struct sk_buff *skb, unsigned int len)
2463 return skb_pull_inline(skb, len);
2465 EXPORT_SYMBOL(skb_pull);
2468 * skb_pull_data - remove data from the start of a buffer returning its
2469 * original position.
2470 * @skb: buffer to use
2471 * @len: amount of data to remove
2473 * This function removes data from the start of a buffer, returning
2474 * the memory to the headroom. A pointer to the original data in the buffer
2475 * is returned after checking if there is enough data to pull. Once the
2476 * data has been pulled future pushes will overwrite the old data.
2478 void *skb_pull_data(struct sk_buff *skb, size_t len)
2480 void *data = skb->data;
2489 EXPORT_SYMBOL(skb_pull_data);
2492 * skb_trim - remove end from a buffer
2493 * @skb: buffer to alter
2496 * Cut the length of a buffer down by removing data from the tail. If
2497 * the buffer is already under the length specified it is not modified.
2498 * The skb must be linear.
2500 void skb_trim(struct sk_buff *skb, unsigned int len)
2503 __skb_trim(skb, len);
2505 EXPORT_SYMBOL(skb_trim);
2507 /* Trims skb to length len. It can change skb pointers.
2510 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2512 struct sk_buff **fragp;
2513 struct sk_buff *frag;
2514 int offset = skb_headlen(skb);
2515 int nfrags = skb_shinfo(skb)->nr_frags;
2519 if (skb_cloned(skb) &&
2520 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2527 for (; i < nfrags; i++) {
2528 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2535 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2538 skb_shinfo(skb)->nr_frags = i;
2540 for (; i < nfrags; i++)
2541 skb_frag_unref(skb, i);
2543 if (skb_has_frag_list(skb))
2544 skb_drop_fraglist(skb);
2548 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2549 fragp = &frag->next) {
2550 int end = offset + frag->len;
2552 if (skb_shared(frag)) {
2553 struct sk_buff *nfrag;
2555 nfrag = skb_clone(frag, GFP_ATOMIC);
2556 if (unlikely(!nfrag))
2559 nfrag->next = frag->next;
2571 unlikely((err = pskb_trim(frag, len - offset))))
2575 skb_drop_list(&frag->next);
2580 if (len > skb_headlen(skb)) {
2581 skb->data_len -= skb->len - len;
2586 skb_set_tail_pointer(skb, len);
2589 if (!skb->sk || skb->destructor == sock_edemux)
2593 EXPORT_SYMBOL(___pskb_trim);
2595 /* Note : use pskb_trim_rcsum() instead of calling this directly
2597 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2599 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2600 int delta = skb->len - len;
2602 skb->csum = csum_block_sub(skb->csum,
2603 skb_checksum(skb, len, delta, 0),
2605 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2606 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2607 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2609 if (offset + sizeof(__sum16) > hdlen)
2612 return __pskb_trim(skb, len);
2614 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2617 * __pskb_pull_tail - advance tail of skb header
2618 * @skb: buffer to reallocate
2619 * @delta: number of bytes to advance tail
2621 * The function makes a sense only on a fragmented &sk_buff,
2622 * it expands header moving its tail forward and copying necessary
2623 * data from fragmented part.
2625 * &sk_buff MUST have reference count of 1.
2627 * Returns %NULL (and &sk_buff does not change) if pull failed
2628 * or value of new tail of skb in the case of success.
2630 * All the pointers pointing into skb header may change and must be
2631 * reloaded after call to this function.
2634 /* Moves tail of skb head forward, copying data from fragmented part,
2635 * when it is necessary.
2636 * 1. It may fail due to malloc failure.
2637 * 2. It may change skb pointers.
2639 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2641 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2643 /* If skb has not enough free space at tail, get new one
2644 * plus 128 bytes for future expansions. If we have enough
2645 * room at tail, reallocate without expansion only if skb is cloned.
2647 int i, k, eat = (skb->tail + delta) - skb->end;
2649 if (eat > 0 || skb_cloned(skb)) {
2650 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2655 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2656 skb_tail_pointer(skb), delta));
2658 /* Optimization: no fragments, no reasons to preestimate
2659 * size of pulled pages. Superb.
2661 if (!skb_has_frag_list(skb))
2664 /* Estimate size of pulled pages. */
2666 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2667 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2674 /* If we need update frag list, we are in troubles.
2675 * Certainly, it is possible to add an offset to skb data,
2676 * but taking into account that pulling is expected to
2677 * be very rare operation, it is worth to fight against
2678 * further bloating skb head and crucify ourselves here instead.
2679 * Pure masohism, indeed. 8)8)
2682 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2683 struct sk_buff *clone = NULL;
2684 struct sk_buff *insp = NULL;
2687 if (list->len <= eat) {
2688 /* Eaten as whole. */
2693 /* Eaten partially. */
2694 if (skb_is_gso(skb) && !list->head_frag &&
2696 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2698 if (skb_shared(list)) {
2699 /* Sucks! We need to fork list. :-( */
2700 clone = skb_clone(list, GFP_ATOMIC);
2706 /* This may be pulled without
2710 if (!pskb_pull(list, eat)) {
2718 /* Free pulled out fragments. */
2719 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2720 skb_shinfo(skb)->frag_list = list->next;
2723 /* And insert new clone at head. */
2726 skb_shinfo(skb)->frag_list = clone;
2729 /* Success! Now we may commit changes to skb data. */
2734 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2735 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2738 skb_frag_unref(skb, i);
2741 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2743 *frag = skb_shinfo(skb)->frags[i];
2745 skb_frag_off_add(frag, eat);
2746 skb_frag_size_sub(frag, eat);
2754 skb_shinfo(skb)->nr_frags = k;
2758 skb->data_len -= delta;
2761 skb_zcopy_clear(skb, false);
2763 return skb_tail_pointer(skb);
2765 EXPORT_SYMBOL(__pskb_pull_tail);
2768 * skb_copy_bits - copy bits from skb to kernel buffer
2770 * @offset: offset in source
2771 * @to: destination buffer
2772 * @len: number of bytes to copy
2774 * Copy the specified number of bytes from the source skb to the
2775 * destination buffer.
2778 * If its prototype is ever changed,
2779 * check arch/{*}/net/{*}.S files,
2780 * since it is called from BPF assembly code.
2782 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2784 int start = skb_headlen(skb);
2785 struct sk_buff *frag_iter;
2788 if (offset > (int)skb->len - len)
2792 if ((copy = start - offset) > 0) {
2795 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2796 if ((len -= copy) == 0)
2802 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2804 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2806 WARN_ON(start > offset + len);
2808 end = start + skb_frag_size(f);
2809 if ((copy = end - offset) > 0) {
2810 u32 p_off, p_len, copied;
2817 skb_frag_foreach_page(f,
2818 skb_frag_off(f) + offset - start,
2819 copy, p, p_off, p_len, copied) {
2820 vaddr = kmap_atomic(p);
2821 memcpy(to + copied, vaddr + p_off, p_len);
2822 kunmap_atomic(vaddr);
2825 if ((len -= copy) == 0)
2833 skb_walk_frags(skb, frag_iter) {
2836 WARN_ON(start > offset + len);
2838 end = start + frag_iter->len;
2839 if ((copy = end - offset) > 0) {
2842 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2844 if ((len -= copy) == 0)
2858 EXPORT_SYMBOL(skb_copy_bits);
2861 * Callback from splice_to_pipe(), if we need to release some pages
2862 * at the end of the spd in case we error'ed out in filling the pipe.
2864 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2866 put_page(spd->pages[i]);
2869 static struct page *linear_to_page(struct page *page, unsigned int *len,
2870 unsigned int *offset,
2873 struct page_frag *pfrag = sk_page_frag(sk);
2875 if (!sk_page_frag_refill(sk, pfrag))
2878 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2880 memcpy(page_address(pfrag->page) + pfrag->offset,
2881 page_address(page) + *offset, *len);
2882 *offset = pfrag->offset;
2883 pfrag->offset += *len;
2888 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2890 unsigned int offset)
2892 return spd->nr_pages &&
2893 spd->pages[spd->nr_pages - 1] == page &&
2894 (spd->partial[spd->nr_pages - 1].offset +
2895 spd->partial[spd->nr_pages - 1].len == offset);
2899 * Fill page/offset/length into spd, if it can hold more pages.
2901 static bool spd_fill_page(struct splice_pipe_desc *spd,
2902 struct pipe_inode_info *pipe, struct page *page,
2903 unsigned int *len, unsigned int offset,
2907 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2911 page = linear_to_page(page, len, &offset, sk);
2915 if (spd_can_coalesce(spd, page, offset)) {
2916 spd->partial[spd->nr_pages - 1].len += *len;
2920 spd->pages[spd->nr_pages] = page;
2921 spd->partial[spd->nr_pages].len = *len;
2922 spd->partial[spd->nr_pages].offset = offset;
2928 static bool __splice_segment(struct page *page, unsigned int poff,
2929 unsigned int plen, unsigned int *off,
2931 struct splice_pipe_desc *spd, bool linear,
2933 struct pipe_inode_info *pipe)
2938 /* skip this segment if already processed */
2944 /* ignore any bits we already processed */
2950 unsigned int flen = min(*len, plen);
2952 if (spd_fill_page(spd, pipe, page, &flen, poff,
2958 } while (*len && plen);
2964 * Map linear and fragment data from the skb to spd. It reports true if the
2965 * pipe is full or if we already spliced the requested length.
2967 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2968 unsigned int *offset, unsigned int *len,
2969 struct splice_pipe_desc *spd, struct sock *sk)
2972 struct sk_buff *iter;
2974 /* map the linear part :
2975 * If skb->head_frag is set, this 'linear' part is backed by a
2976 * fragment, and if the head is not shared with any clones then
2977 * we can avoid a copy since we own the head portion of this page.
2979 if (__splice_segment(virt_to_page(skb->data),
2980 (unsigned long) skb->data & (PAGE_SIZE - 1),
2983 skb_head_is_locked(skb),
2988 * then map the fragments
2990 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2991 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2993 if (__splice_segment(skb_frag_page(f),
2994 skb_frag_off(f), skb_frag_size(f),
2995 offset, len, spd, false, sk, pipe))
2999 skb_walk_frags(skb, iter) {
3000 if (*offset >= iter->len) {
3001 *offset -= iter->len;
3004 /* __skb_splice_bits() only fails if the output has no room
3005 * left, so no point in going over the frag_list for the error
3008 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
3016 * Map data from the skb to a pipe. Should handle both the linear part,
3017 * the fragments, and the frag list.
3019 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
3020 struct pipe_inode_info *pipe, unsigned int tlen,
3023 struct partial_page partial[MAX_SKB_FRAGS];
3024 struct page *pages[MAX_SKB_FRAGS];
3025 struct splice_pipe_desc spd = {
3028 .nr_pages_max = MAX_SKB_FRAGS,
3029 .ops = &nosteal_pipe_buf_ops,
3030 .spd_release = sock_spd_release,
3034 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
3037 ret = splice_to_pipe(pipe, &spd);
3041 EXPORT_SYMBOL_GPL(skb_splice_bits);
3043 static int sendmsg_locked(struct sock *sk, struct msghdr *msg)
3045 struct socket *sock = sk->sk_socket;
3046 size_t size = msg_data_left(msg);
3051 if (!sock->ops->sendmsg_locked)
3052 return sock_no_sendmsg_locked(sk, msg, size);
3054 return sock->ops->sendmsg_locked(sk, msg, size);
3057 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg)
3059 struct socket *sock = sk->sk_socket;
3063 return sock_sendmsg(sock, msg);
3066 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg);
3067 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
3068 int len, sendmsg_func sendmsg)
3070 unsigned int orig_len = len;
3071 struct sk_buff *head = skb;
3072 unsigned short fragidx;
3077 /* Deal with head data */
3078 while (offset < skb_headlen(skb) && len) {
3082 slen = min_t(int, len, skb_headlen(skb) - offset);
3083 kv.iov_base = skb->data + offset;
3085 memset(&msg, 0, sizeof(msg));
3086 msg.msg_flags = MSG_DONTWAIT;
3088 iov_iter_kvec(&msg.msg_iter, ITER_SOURCE, &kv, 1, slen);
3089 ret = INDIRECT_CALL_2(sendmsg, sendmsg_locked,
3090 sendmsg_unlocked, sk, &msg);
3098 /* All the data was skb head? */
3102 /* Make offset relative to start of frags */
3103 offset -= skb_headlen(skb);
3105 /* Find where we are in frag list */
3106 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3107 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3109 if (offset < skb_frag_size(frag))
3112 offset -= skb_frag_size(frag);
3115 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3116 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
3118 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
3121 struct bio_vec bvec;
3122 struct msghdr msg = {
3123 .msg_flags = MSG_SPLICE_PAGES | MSG_DONTWAIT,
3126 bvec_set_page(&bvec, skb_frag_page(frag), slen,
3127 skb_frag_off(frag) + offset);
3128 iov_iter_bvec(&msg.msg_iter, ITER_SOURCE, &bvec, 1,
3131 ret = INDIRECT_CALL_2(sendmsg, sendmsg_locked,
3132 sendmsg_unlocked, sk, &msg);
3145 /* Process any frag lists */
3148 if (skb_has_frag_list(skb)) {
3149 skb = skb_shinfo(skb)->frag_list;
3152 } else if (skb->next) {
3159 return orig_len - len;
3162 return orig_len == len ? ret : orig_len - len;
3165 /* Send skb data on a socket. Socket must be locked. */
3166 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
3169 return __skb_send_sock(sk, skb, offset, len, sendmsg_locked);
3171 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
3173 /* Send skb data on a socket. Socket must be unlocked. */
3174 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
3176 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked);
3180 * skb_store_bits - store bits from kernel buffer to skb
3181 * @skb: destination buffer
3182 * @offset: offset in destination
3183 * @from: source buffer
3184 * @len: number of bytes to copy
3186 * Copy the specified number of bytes from the source buffer to the
3187 * destination skb. This function handles all the messy bits of
3188 * traversing fragment lists and such.
3191 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
3193 int start = skb_headlen(skb);
3194 struct sk_buff *frag_iter;
3197 if (offset > (int)skb->len - len)
3200 if ((copy = start - offset) > 0) {
3203 skb_copy_to_linear_data_offset(skb, offset, from, copy);
3204 if ((len -= copy) == 0)
3210 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3211 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3214 WARN_ON(start > offset + len);
3216 end = start + skb_frag_size(frag);
3217 if ((copy = end - offset) > 0) {
3218 u32 p_off, p_len, copied;
3225 skb_frag_foreach_page(frag,
3226 skb_frag_off(frag) + offset - start,
3227 copy, p, p_off, p_len, copied) {
3228 vaddr = kmap_atomic(p);
3229 memcpy(vaddr + p_off, from + copied, p_len);
3230 kunmap_atomic(vaddr);
3233 if ((len -= copy) == 0)
3241 skb_walk_frags(skb, frag_iter) {
3244 WARN_ON(start > offset + len);
3246 end = start + frag_iter->len;
3247 if ((copy = end - offset) > 0) {
3250 if (skb_store_bits(frag_iter, offset - start,
3253 if ((len -= copy) == 0)
3266 EXPORT_SYMBOL(skb_store_bits);
3268 /* Checksum skb data. */
3269 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
3270 __wsum csum, const struct skb_checksum_ops *ops)
3272 int start = skb_headlen(skb);
3273 int i, copy = start - offset;
3274 struct sk_buff *frag_iter;
3277 /* Checksum header. */
3281 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3282 skb->data + offset, copy, csum);
3283 if ((len -= copy) == 0)
3289 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3291 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3293 WARN_ON(start > offset + len);
3295 end = start + skb_frag_size(frag);
3296 if ((copy = end - offset) > 0) {
3297 u32 p_off, p_len, copied;
3305 skb_frag_foreach_page(frag,
3306 skb_frag_off(frag) + offset - start,
3307 copy, p, p_off, p_len, copied) {
3308 vaddr = kmap_atomic(p);
3309 csum2 = INDIRECT_CALL_1(ops->update,
3311 vaddr + p_off, p_len, 0);
3312 kunmap_atomic(vaddr);
3313 csum = INDIRECT_CALL_1(ops->combine,
3314 csum_block_add_ext, csum,
3326 skb_walk_frags(skb, frag_iter) {
3329 WARN_ON(start > offset + len);
3331 end = start + frag_iter->len;
3332 if ((copy = end - offset) > 0) {
3336 csum2 = __skb_checksum(frag_iter, offset - start,
3338 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3339 csum, csum2, pos, copy);
3340 if ((len -= copy) == 0)
3351 EXPORT_SYMBOL(__skb_checksum);
3353 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3354 int len, __wsum csum)
3356 const struct skb_checksum_ops ops = {
3357 .update = csum_partial_ext,
3358 .combine = csum_block_add_ext,
3361 return __skb_checksum(skb, offset, len, csum, &ops);
3363 EXPORT_SYMBOL(skb_checksum);
3365 /* Both of above in one bottle. */
3367 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3370 int start = skb_headlen(skb);
3371 int i, copy = start - offset;
3372 struct sk_buff *frag_iter;
3380 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3382 if ((len -= copy) == 0)
3389 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3392 WARN_ON(start > offset + len);
3394 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3395 if ((copy = end - offset) > 0) {
3396 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3397 u32 p_off, p_len, copied;
3405 skb_frag_foreach_page(frag,
3406 skb_frag_off(frag) + offset - start,
3407 copy, p, p_off, p_len, copied) {
3408 vaddr = kmap_atomic(p);
3409 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3412 kunmap_atomic(vaddr);
3413 csum = csum_block_add(csum, csum2, pos);
3425 skb_walk_frags(skb, frag_iter) {
3429 WARN_ON(start > offset + len);
3431 end = start + frag_iter->len;
3432 if ((copy = end - offset) > 0) {
3435 csum2 = skb_copy_and_csum_bits(frag_iter,
3438 csum = csum_block_add(csum, csum2, pos);
3439 if ((len -= copy) == 0)
3450 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3452 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3456 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3457 /* See comments in __skb_checksum_complete(). */
3459 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3460 !skb->csum_complete_sw)
3461 netdev_rx_csum_fault(skb->dev, skb);
3463 if (!skb_shared(skb))
3464 skb->csum_valid = !sum;
3467 EXPORT_SYMBOL(__skb_checksum_complete_head);
3469 /* This function assumes skb->csum already holds pseudo header's checksum,
3470 * which has been changed from the hardware checksum, for example, by
3471 * __skb_checksum_validate_complete(). And, the original skb->csum must
3472 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3474 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3475 * zero. The new checksum is stored back into skb->csum unless the skb is
3478 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3483 csum = skb_checksum(skb, 0, skb->len, 0);
3485 sum = csum_fold(csum_add(skb->csum, csum));
3486 /* This check is inverted, because we already knew the hardware
3487 * checksum is invalid before calling this function. So, if the
3488 * re-computed checksum is valid instead, then we have a mismatch
3489 * between the original skb->csum and skb_checksum(). This means either
3490 * the original hardware checksum is incorrect or we screw up skb->csum
3491 * when moving skb->data around.
3494 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3495 !skb->csum_complete_sw)
3496 netdev_rx_csum_fault(skb->dev, skb);
3499 if (!skb_shared(skb)) {
3500 /* Save full packet checksum */
3502 skb->ip_summed = CHECKSUM_COMPLETE;
3503 skb->csum_complete_sw = 1;
3504 skb->csum_valid = !sum;
3509 EXPORT_SYMBOL(__skb_checksum_complete);
3511 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3513 net_warn_ratelimited(
3514 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3519 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3520 int offset, int len)
3522 net_warn_ratelimited(
3523 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3528 static const struct skb_checksum_ops default_crc32c_ops = {
3529 .update = warn_crc32c_csum_update,
3530 .combine = warn_crc32c_csum_combine,
3533 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3534 &default_crc32c_ops;
3535 EXPORT_SYMBOL(crc32c_csum_stub);
3538 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3539 * @from: source buffer
3541 * Calculates the amount of linear headroom needed in the 'to' skb passed
3542 * into skb_zerocopy().
3545 skb_zerocopy_headlen(const struct sk_buff *from)
3547 unsigned int hlen = 0;
3549 if (!from->head_frag ||
3550 skb_headlen(from) < L1_CACHE_BYTES ||
3551 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3552 hlen = skb_headlen(from);
3557 if (skb_has_frag_list(from))
3562 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3565 * skb_zerocopy - Zero copy skb to skb
3566 * @to: destination buffer
3567 * @from: source buffer
3568 * @len: number of bytes to copy from source buffer
3569 * @hlen: size of linear headroom in destination buffer
3571 * Copies up to `len` bytes from `from` to `to` by creating references
3572 * to the frags in the source buffer.
3574 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3575 * headroom in the `to` buffer.
3578 * 0: everything is OK
3579 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3580 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3583 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3586 int plen = 0; /* length of skb->head fragment */
3589 unsigned int offset;
3591 BUG_ON(!from->head_frag && !hlen);
3593 /* dont bother with small payloads */
3594 if (len <= skb_tailroom(to))
3595 return skb_copy_bits(from, 0, skb_put(to, len), len);
3598 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3603 plen = min_t(int, skb_headlen(from), len);
3605 page = virt_to_head_page(from->head);
3606 offset = from->data - (unsigned char *)page_address(page);
3607 __skb_fill_page_desc(to, 0, page, offset, plen);
3614 skb_len_add(to, len + plen);
3616 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3620 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3622 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3627 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3628 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3630 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3632 skb_frag_ref(to, j);
3635 skb_shinfo(to)->nr_frags = j;
3639 EXPORT_SYMBOL_GPL(skb_zerocopy);
3641 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3646 if (skb->ip_summed == CHECKSUM_PARTIAL)
3647 csstart = skb_checksum_start_offset(skb);
3649 csstart = skb_headlen(skb);
3651 BUG_ON(csstart > skb_headlen(skb));
3653 skb_copy_from_linear_data(skb, to, csstart);
3656 if (csstart != skb->len)
3657 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3658 skb->len - csstart);
3660 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3661 long csstuff = csstart + skb->csum_offset;
3663 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3666 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3669 * skb_dequeue - remove from the head of the queue
3670 * @list: list to dequeue from
3672 * Remove the head of the list. The list lock is taken so the function
3673 * may be used safely with other locking list functions. The head item is
3674 * returned or %NULL if the list is empty.
3677 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3679 unsigned long flags;
3680 struct sk_buff *result;
3682 spin_lock_irqsave(&list->lock, flags);
3683 result = __skb_dequeue(list);
3684 spin_unlock_irqrestore(&list->lock, flags);
3687 EXPORT_SYMBOL(skb_dequeue);
3690 * skb_dequeue_tail - remove from the tail of the queue
3691 * @list: list to dequeue from
3693 * Remove the tail of the list. The list lock is taken so the function
3694 * may be used safely with other locking list functions. The tail item is
3695 * returned or %NULL if the list is empty.
3697 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3699 unsigned long flags;
3700 struct sk_buff *result;
3702 spin_lock_irqsave(&list->lock, flags);
3703 result = __skb_dequeue_tail(list);
3704 spin_unlock_irqrestore(&list->lock, flags);
3707 EXPORT_SYMBOL(skb_dequeue_tail);
3710 * skb_queue_purge_reason - empty a list
3711 * @list: list to empty
3712 * @reason: drop reason
3714 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3715 * the list and one reference dropped. This function takes the list
3716 * lock and is atomic with respect to other list locking functions.
3718 void skb_queue_purge_reason(struct sk_buff_head *list,
3719 enum skb_drop_reason reason)
3721 struct sk_buff *skb;
3723 while ((skb = skb_dequeue(list)) != NULL)
3724 kfree_skb_reason(skb, reason);
3726 EXPORT_SYMBOL(skb_queue_purge_reason);
3729 * skb_rbtree_purge - empty a skb rbtree
3730 * @root: root of the rbtree to empty
3731 * Return value: the sum of truesizes of all purged skbs.
3733 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3734 * the list and one reference dropped. This function does not take
3735 * any lock. Synchronization should be handled by the caller (e.g., TCP
3736 * out-of-order queue is protected by the socket lock).
3738 unsigned int skb_rbtree_purge(struct rb_root *root)
3740 struct rb_node *p = rb_first(root);
3741 unsigned int sum = 0;
3744 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3747 rb_erase(&skb->rbnode, root);
3748 sum += skb->truesize;
3754 void skb_errqueue_purge(struct sk_buff_head *list)
3756 struct sk_buff *skb, *next;
3757 struct sk_buff_head kill;
3758 unsigned long flags;
3760 __skb_queue_head_init(&kill);
3762 spin_lock_irqsave(&list->lock, flags);
3763 skb_queue_walk_safe(list, skb, next) {
3764 if (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ZEROCOPY ||
3765 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_TIMESTAMPING)
3767 __skb_unlink(skb, list);
3768 __skb_queue_tail(&kill, skb);
3770 spin_unlock_irqrestore(&list->lock, flags);
3771 __skb_queue_purge(&kill);
3773 EXPORT_SYMBOL(skb_errqueue_purge);
3776 * skb_queue_head - queue a buffer at the list head
3777 * @list: list to use
3778 * @newsk: buffer to queue
3780 * Queue a buffer at the start of the list. This function takes the
3781 * list lock and can be used safely with other locking &sk_buff functions
3784 * A buffer cannot be placed on two lists at the same time.
3786 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3788 unsigned long flags;
3790 spin_lock_irqsave(&list->lock, flags);
3791 __skb_queue_head(list, newsk);
3792 spin_unlock_irqrestore(&list->lock, flags);
3794 EXPORT_SYMBOL(skb_queue_head);
3797 * skb_queue_tail - queue a buffer at the list tail
3798 * @list: list to use
3799 * @newsk: buffer to queue
3801 * Queue a buffer at the tail of the list. This function takes the
3802 * list lock and can be used safely with other locking &sk_buff functions
3805 * A buffer cannot be placed on two lists at the same time.
3807 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3809 unsigned long flags;
3811 spin_lock_irqsave(&list->lock, flags);
3812 __skb_queue_tail(list, newsk);
3813 spin_unlock_irqrestore(&list->lock, flags);
3815 EXPORT_SYMBOL(skb_queue_tail);
3818 * skb_unlink - remove a buffer from a list
3819 * @skb: buffer to remove
3820 * @list: list to use
3822 * Remove a packet from a list. The list locks are taken and this
3823 * function is atomic with respect to other list locked calls
3825 * You must know what list the SKB is on.
3827 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3829 unsigned long flags;
3831 spin_lock_irqsave(&list->lock, flags);
3832 __skb_unlink(skb, list);
3833 spin_unlock_irqrestore(&list->lock, flags);
3835 EXPORT_SYMBOL(skb_unlink);
3838 * skb_append - append a buffer
3839 * @old: buffer to insert after
3840 * @newsk: buffer to insert
3841 * @list: list to use
3843 * Place a packet after a given packet in a list. The list locks are taken
3844 * and this function is atomic with respect to other list locked calls.
3845 * A buffer cannot be placed on two lists at the same time.
3847 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3849 unsigned long flags;
3851 spin_lock_irqsave(&list->lock, flags);
3852 __skb_queue_after(list, old, newsk);
3853 spin_unlock_irqrestore(&list->lock, flags);
3855 EXPORT_SYMBOL(skb_append);
3857 static inline void skb_split_inside_header(struct sk_buff *skb,
3858 struct sk_buff* skb1,
3859 const u32 len, const int pos)
3863 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3865 /* And move data appendix as is. */
3866 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3867 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3869 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3870 skb_shinfo(skb)->nr_frags = 0;
3871 skb1->data_len = skb->data_len;
3872 skb1->len += skb1->data_len;
3875 skb_set_tail_pointer(skb, len);
3878 static inline void skb_split_no_header(struct sk_buff *skb,
3879 struct sk_buff* skb1,
3880 const u32 len, int pos)
3883 const int nfrags = skb_shinfo(skb)->nr_frags;
3885 skb_shinfo(skb)->nr_frags = 0;
3886 skb1->len = skb1->data_len = skb->len - len;
3888 skb->data_len = len - pos;
3890 for (i = 0; i < nfrags; i++) {
3891 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3893 if (pos + size > len) {
3894 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3898 * We have two variants in this case:
3899 * 1. Move all the frag to the second
3900 * part, if it is possible. F.e.
3901 * this approach is mandatory for TUX,
3902 * where splitting is expensive.
3903 * 2. Split is accurately. We make this.
3905 skb_frag_ref(skb, i);
3906 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3907 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3908 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3909 skb_shinfo(skb)->nr_frags++;
3913 skb_shinfo(skb)->nr_frags++;
3916 skb_shinfo(skb1)->nr_frags = k;
3920 * skb_split - Split fragmented skb to two parts at length len.
3921 * @skb: the buffer to split
3922 * @skb1: the buffer to receive the second part
3923 * @len: new length for skb
3925 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3927 int pos = skb_headlen(skb);
3928 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3930 skb_zcopy_downgrade_managed(skb);
3932 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3933 skb_zerocopy_clone(skb1, skb, 0);
3934 if (len < pos) /* Split line is inside header. */
3935 skb_split_inside_header(skb, skb1, len, pos);
3936 else /* Second chunk has no header, nothing to copy. */
3937 skb_split_no_header(skb, skb1, len, pos);
3939 EXPORT_SYMBOL(skb_split);
3941 /* Shifting from/to a cloned skb is a no-go.
3943 * Caller cannot keep skb_shinfo related pointers past calling here!
3945 static int skb_prepare_for_shift(struct sk_buff *skb)
3947 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3951 * skb_shift - Shifts paged data partially from skb to another
3952 * @tgt: buffer into which tail data gets added
3953 * @skb: buffer from which the paged data comes from
3954 * @shiftlen: shift up to this many bytes
3956 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3957 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3958 * It's up to caller to free skb if everything was shifted.
3960 * If @tgt runs out of frags, the whole operation is aborted.
3962 * Skb cannot include anything else but paged data while tgt is allowed
3963 * to have non-paged data as well.
3965 * TODO: full sized shift could be optimized but that would need
3966 * specialized skb free'er to handle frags without up-to-date nr_frags.
3968 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3970 int from, to, merge, todo;
3971 skb_frag_t *fragfrom, *fragto;
3973 BUG_ON(shiftlen > skb->len);
3975 if (skb_headlen(skb))
3977 if (skb_zcopy(tgt) || skb_zcopy(skb))
3982 to = skb_shinfo(tgt)->nr_frags;
3983 fragfrom = &skb_shinfo(skb)->frags[from];
3985 /* Actual merge is delayed until the point when we know we can
3986 * commit all, so that we don't have to undo partial changes
3989 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3990 skb_frag_off(fragfrom))) {
3995 todo -= skb_frag_size(fragfrom);
3997 if (skb_prepare_for_shift(skb) ||
3998 skb_prepare_for_shift(tgt))
4001 /* All previous frag pointers might be stale! */
4002 fragfrom = &skb_shinfo(skb)->frags[from];
4003 fragto = &skb_shinfo(tgt)->frags[merge];
4005 skb_frag_size_add(fragto, shiftlen);
4006 skb_frag_size_sub(fragfrom, shiftlen);
4007 skb_frag_off_add(fragfrom, shiftlen);
4015 /* Skip full, not-fitting skb to avoid expensive operations */
4016 if ((shiftlen == skb->len) &&
4017 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
4020 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
4023 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
4024 if (to == MAX_SKB_FRAGS)
4027 fragfrom = &skb_shinfo(skb)->frags[from];
4028 fragto = &skb_shinfo(tgt)->frags[to];
4030 if (todo >= skb_frag_size(fragfrom)) {
4031 *fragto = *fragfrom;
4032 todo -= skb_frag_size(fragfrom);
4037 __skb_frag_ref(fragfrom);
4038 skb_frag_page_copy(fragto, fragfrom);
4039 skb_frag_off_copy(fragto, fragfrom);
4040 skb_frag_size_set(fragto, todo);
4042 skb_frag_off_add(fragfrom, todo);
4043 skb_frag_size_sub(fragfrom, todo);
4051 /* Ready to "commit" this state change to tgt */
4052 skb_shinfo(tgt)->nr_frags = to;
4055 fragfrom = &skb_shinfo(skb)->frags[0];
4056 fragto = &skb_shinfo(tgt)->frags[merge];
4058 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
4059 __skb_frag_unref(fragfrom, skb->pp_recycle);
4062 /* Reposition in the original skb */
4064 while (from < skb_shinfo(skb)->nr_frags)
4065 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
4066 skb_shinfo(skb)->nr_frags = to;
4068 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
4071 /* Most likely the tgt won't ever need its checksum anymore, skb on
4072 * the other hand might need it if it needs to be resent
4074 tgt->ip_summed = CHECKSUM_PARTIAL;
4075 skb->ip_summed = CHECKSUM_PARTIAL;
4077 skb_len_add(skb, -shiftlen);
4078 skb_len_add(tgt, shiftlen);
4084 * skb_prepare_seq_read - Prepare a sequential read of skb data
4085 * @skb: the buffer to read
4086 * @from: lower offset of data to be read
4087 * @to: upper offset of data to be read
4088 * @st: state variable
4090 * Initializes the specified state variable. Must be called before
4091 * invoking skb_seq_read() for the first time.
4093 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
4094 unsigned int to, struct skb_seq_state *st)
4096 st->lower_offset = from;
4097 st->upper_offset = to;
4098 st->root_skb = st->cur_skb = skb;
4099 st->frag_idx = st->stepped_offset = 0;
4100 st->frag_data = NULL;
4103 EXPORT_SYMBOL(skb_prepare_seq_read);
4106 * skb_seq_read - Sequentially read skb data
4107 * @consumed: number of bytes consumed by the caller so far
4108 * @data: destination pointer for data to be returned
4109 * @st: state variable
4111 * Reads a block of skb data at @consumed relative to the
4112 * lower offset specified to skb_prepare_seq_read(). Assigns
4113 * the head of the data block to @data and returns the length
4114 * of the block or 0 if the end of the skb data or the upper
4115 * offset has been reached.
4117 * The caller is not required to consume all of the data
4118 * returned, i.e. @consumed is typically set to the number
4119 * of bytes already consumed and the next call to
4120 * skb_seq_read() will return the remaining part of the block.
4122 * Note 1: The size of each block of data returned can be arbitrary,
4123 * this limitation is the cost for zerocopy sequential
4124 * reads of potentially non linear data.
4126 * Note 2: Fragment lists within fragments are not implemented
4127 * at the moment, state->root_skb could be replaced with
4128 * a stack for this purpose.
4130 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
4131 struct skb_seq_state *st)
4133 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
4136 if (unlikely(abs_offset >= st->upper_offset)) {
4137 if (st->frag_data) {
4138 kunmap_atomic(st->frag_data);
4139 st->frag_data = NULL;
4145 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
4147 if (abs_offset < block_limit && !st->frag_data) {
4148 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
4149 return block_limit - abs_offset;
4152 if (st->frag_idx == 0 && !st->frag_data)
4153 st->stepped_offset += skb_headlen(st->cur_skb);
4155 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
4156 unsigned int pg_idx, pg_off, pg_sz;
4158 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
4161 pg_off = skb_frag_off(frag);
4162 pg_sz = skb_frag_size(frag);
4164 if (skb_frag_must_loop(skb_frag_page(frag))) {
4165 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
4166 pg_off = offset_in_page(pg_off + st->frag_off);
4167 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
4168 PAGE_SIZE - pg_off);
4171 block_limit = pg_sz + st->stepped_offset;
4172 if (abs_offset < block_limit) {
4174 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
4176 *data = (u8 *)st->frag_data + pg_off +
4177 (abs_offset - st->stepped_offset);
4179 return block_limit - abs_offset;
4182 if (st->frag_data) {
4183 kunmap_atomic(st->frag_data);
4184 st->frag_data = NULL;
4187 st->stepped_offset += pg_sz;
4188 st->frag_off += pg_sz;
4189 if (st->frag_off == skb_frag_size(frag)) {
4195 if (st->frag_data) {
4196 kunmap_atomic(st->frag_data);
4197 st->frag_data = NULL;
4200 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
4201 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
4204 } else if (st->cur_skb->next) {
4205 st->cur_skb = st->cur_skb->next;
4212 EXPORT_SYMBOL(skb_seq_read);
4215 * skb_abort_seq_read - Abort a sequential read of skb data
4216 * @st: state variable
4218 * Must be called if skb_seq_read() was not called until it
4221 void skb_abort_seq_read(struct skb_seq_state *st)
4224 kunmap_atomic(st->frag_data);
4226 EXPORT_SYMBOL(skb_abort_seq_read);
4228 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
4230 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
4231 struct ts_config *conf,
4232 struct ts_state *state)
4234 return skb_seq_read(offset, text, TS_SKB_CB(state));
4237 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
4239 skb_abort_seq_read(TS_SKB_CB(state));
4243 * skb_find_text - Find a text pattern in skb data
4244 * @skb: the buffer to look in
4245 * @from: search offset
4247 * @config: textsearch configuration
4249 * Finds a pattern in the skb data according to the specified
4250 * textsearch configuration. Use textsearch_next() to retrieve
4251 * subsequent occurrences of the pattern. Returns the offset
4252 * to the first occurrence or UINT_MAX if no match was found.
4254 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4255 unsigned int to, struct ts_config *config)
4257 unsigned int patlen = config->ops->get_pattern_len(config);
4258 struct ts_state state;
4261 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4263 config->get_next_block = skb_ts_get_next_block;
4264 config->finish = skb_ts_finish;
4266 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
4268 ret = textsearch_find(config, &state);
4269 return (ret + patlen <= to - from ? ret : UINT_MAX);
4271 EXPORT_SYMBOL(skb_find_text);
4273 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4274 int offset, size_t size, size_t max_frags)
4276 int i = skb_shinfo(skb)->nr_frags;
4278 if (skb_can_coalesce(skb, i, page, offset)) {
4279 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4280 } else if (i < max_frags) {
4281 skb_zcopy_downgrade_managed(skb);
4283 skb_fill_page_desc_noacc(skb, i, page, offset, size);
4290 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4293 * skb_pull_rcsum - pull skb and update receive checksum
4294 * @skb: buffer to update
4295 * @len: length of data pulled
4297 * This function performs an skb_pull on the packet and updates
4298 * the CHECKSUM_COMPLETE checksum. It should be used on
4299 * receive path processing instead of skb_pull unless you know
4300 * that the checksum difference is zero (e.g., a valid IP header)
4301 * or you are setting ip_summed to CHECKSUM_NONE.
4303 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4305 unsigned char *data = skb->data;
4307 BUG_ON(len > skb->len);
4308 __skb_pull(skb, len);
4309 skb_postpull_rcsum(skb, data, len);
4312 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4314 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4316 skb_frag_t head_frag;
4319 page = virt_to_head_page(frag_skb->head);
4320 skb_frag_fill_page_desc(&head_frag, page, frag_skb->data -
4321 (unsigned char *)page_address(page),
4322 skb_headlen(frag_skb));
4326 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4327 netdev_features_t features,
4328 unsigned int offset)
4330 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4331 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4332 unsigned int delta_truesize = 0;
4333 unsigned int delta_len = 0;
4334 struct sk_buff *tail = NULL;
4335 struct sk_buff *nskb, *tmp;
4338 skb_push(skb, -skb_network_offset(skb) + offset);
4340 /* Ensure the head is writeable before touching the shared info */
4341 err = skb_unclone(skb, GFP_ATOMIC);
4345 skb_shinfo(skb)->frag_list = NULL;
4349 list_skb = list_skb->next;
4352 delta_truesize += nskb->truesize;
4353 if (skb_shared(nskb)) {
4354 tmp = skb_clone(nskb, GFP_ATOMIC);
4358 err = skb_unclone(nskb, GFP_ATOMIC);
4369 if (unlikely(err)) {
4370 nskb->next = list_skb;
4376 delta_len += nskb->len;
4378 skb_push(nskb, -skb_network_offset(nskb) + offset);
4380 skb_release_head_state(nskb);
4381 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4382 __copy_skb_header(nskb, skb);
4384 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4385 nskb->transport_header += len_diff;
4386 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4387 nskb->data - tnl_hlen,
4390 if (skb_needs_linearize(nskb, features) &&
4391 __skb_linearize(nskb))
4395 skb->truesize = skb->truesize - delta_truesize;
4396 skb->data_len = skb->data_len - delta_len;
4397 skb->len = skb->len - delta_len;
4403 if (skb_needs_linearize(skb, features) &&
4404 __skb_linearize(skb))
4412 kfree_skb_list(skb->next);
4414 return ERR_PTR(-ENOMEM);
4416 EXPORT_SYMBOL_GPL(skb_segment_list);
4419 * skb_segment - Perform protocol segmentation on skb.
4420 * @head_skb: buffer to segment
4421 * @features: features for the output path (see dev->features)
4423 * This function performs segmentation on the given skb. It returns
4424 * a pointer to the first in a list of new skbs for the segments.
4425 * In case of error it returns ERR_PTR(err).
4427 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4428 netdev_features_t features)
4430 struct sk_buff *segs = NULL;
4431 struct sk_buff *tail = NULL;
4432 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4433 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4434 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4435 unsigned int offset = doffset;
4436 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4437 unsigned int partial_segs = 0;
4438 unsigned int headroom;
4439 unsigned int len = head_skb->len;
4440 struct sk_buff *frag_skb;
4448 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4449 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4450 struct sk_buff *check_skb;
4452 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4453 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4454 /* gso_size is untrusted, and we have a frag_list with
4455 * a linear non head_frag item.
4457 * If head_skb's headlen does not fit requested gso_size,
4458 * it means that the frag_list members do NOT terminate
4459 * on exact gso_size boundaries. Hence we cannot perform
4460 * skb_frag_t page sharing. Therefore we must fallback to
4461 * copying the frag_list skbs; we do so by disabling SG.
4463 features &= ~NETIF_F_SG;
4469 __skb_push(head_skb, doffset);
4470 proto = skb_network_protocol(head_skb, NULL);
4471 if (unlikely(!proto))
4472 return ERR_PTR(-EINVAL);
4474 sg = !!(features & NETIF_F_SG);
4475 csum = !!can_checksum_protocol(features, proto);
4477 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4478 if (!(features & NETIF_F_GSO_PARTIAL)) {
4479 struct sk_buff *iter;
4480 unsigned int frag_len;
4483 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4486 /* If we get here then all the required
4487 * GSO features except frag_list are supported.
4488 * Try to split the SKB to multiple GSO SKBs
4489 * with no frag_list.
4490 * Currently we can do that only when the buffers don't
4491 * have a linear part and all the buffers except
4492 * the last are of the same length.
4494 frag_len = list_skb->len;
4495 skb_walk_frags(head_skb, iter) {
4496 if (frag_len != iter->len && iter->next)
4498 if (skb_headlen(iter) && !iter->head_frag)
4504 if (len != frag_len)
4508 /* GSO partial only requires that we trim off any excess that
4509 * doesn't fit into an MSS sized block, so take care of that
4511 * Cap len to not accidentally hit GSO_BY_FRAGS.
4513 partial_segs = min(len, GSO_BY_FRAGS - 1U) / mss;
4514 if (partial_segs > 1)
4515 mss *= partial_segs;
4521 headroom = skb_headroom(head_skb);
4522 pos = skb_headlen(head_skb);
4524 if (skb_orphan_frags(head_skb, GFP_ATOMIC))
4525 return ERR_PTR(-ENOMEM);
4527 nfrags = skb_shinfo(head_skb)->nr_frags;
4528 frag = skb_shinfo(head_skb)->frags;
4529 frag_skb = head_skb;
4532 struct sk_buff *nskb;
4533 skb_frag_t *nskb_frag;
4537 if (unlikely(mss == GSO_BY_FRAGS)) {
4538 len = list_skb->len;
4540 len = head_skb->len - offset;
4545 hsize = skb_headlen(head_skb) - offset;
4547 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4548 (skb_headlen(list_skb) == len || sg)) {
4549 BUG_ON(skb_headlen(list_skb) > len);
4551 nskb = skb_clone(list_skb, GFP_ATOMIC);
4552 if (unlikely(!nskb))
4556 nfrags = skb_shinfo(list_skb)->nr_frags;
4557 frag = skb_shinfo(list_skb)->frags;
4558 frag_skb = list_skb;
4559 pos += skb_headlen(list_skb);
4561 while (pos < offset + len) {
4562 BUG_ON(i >= nfrags);
4564 size = skb_frag_size(frag);
4565 if (pos + size > offset + len)
4573 list_skb = list_skb->next;
4575 if (unlikely(pskb_trim(nskb, len))) {
4580 hsize = skb_end_offset(nskb);
4581 if (skb_cow_head(nskb, doffset + headroom)) {
4586 nskb->truesize += skb_end_offset(nskb) - hsize;
4587 skb_release_head_state(nskb);
4588 __skb_push(nskb, doffset);
4592 if (hsize > len || !sg)
4595 nskb = __alloc_skb(hsize + doffset + headroom,
4596 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4599 if (unlikely(!nskb))
4602 skb_reserve(nskb, headroom);
4603 __skb_put(nskb, doffset);
4612 __copy_skb_header(nskb, head_skb);
4614 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4615 skb_reset_mac_len(nskb);
4617 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4618 nskb->data - tnl_hlen,
4619 doffset + tnl_hlen);
4621 if (nskb->len == len + doffset)
4622 goto perform_csum_check;
4626 if (!nskb->remcsum_offload)
4627 nskb->ip_summed = CHECKSUM_NONE;
4628 SKB_GSO_CB(nskb)->csum =
4629 skb_copy_and_csum_bits(head_skb, offset,
4633 SKB_GSO_CB(nskb)->csum_start =
4634 skb_headroom(nskb) + doffset;
4636 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4642 nskb_frag = skb_shinfo(nskb)->frags;
4644 skb_copy_from_linear_data_offset(head_skb, offset,
4645 skb_put(nskb, hsize), hsize);
4647 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4650 if (skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4653 while (pos < offset + len) {
4655 if (skb_orphan_frags(list_skb, GFP_ATOMIC) ||
4656 skb_zerocopy_clone(nskb, list_skb,
4661 nfrags = skb_shinfo(list_skb)->nr_frags;
4662 frag = skb_shinfo(list_skb)->frags;
4663 frag_skb = list_skb;
4664 if (!skb_headlen(list_skb)) {
4667 BUG_ON(!list_skb->head_frag);
4669 /* to make room for head_frag. */
4674 list_skb = list_skb->next;
4677 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4679 net_warn_ratelimited(
4680 "skb_segment: too many frags: %u %u\n",
4686 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4687 __skb_frag_ref(nskb_frag);
4688 size = skb_frag_size(nskb_frag);
4691 skb_frag_off_add(nskb_frag, offset - pos);
4692 skb_frag_size_sub(nskb_frag, offset - pos);
4695 skb_shinfo(nskb)->nr_frags++;
4697 if (pos + size <= offset + len) {
4702 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4710 nskb->data_len = len - hsize;
4711 nskb->len += nskb->data_len;
4712 nskb->truesize += nskb->data_len;
4716 if (skb_has_shared_frag(nskb) &&
4717 __skb_linearize(nskb))
4720 if (!nskb->remcsum_offload)
4721 nskb->ip_summed = CHECKSUM_NONE;
4722 SKB_GSO_CB(nskb)->csum =
4723 skb_checksum(nskb, doffset,
4724 nskb->len - doffset, 0);
4725 SKB_GSO_CB(nskb)->csum_start =
4726 skb_headroom(nskb) + doffset;
4728 } while ((offset += len) < head_skb->len);
4730 /* Some callers want to get the end of the list.
4731 * Put it in segs->prev to avoid walking the list.
4732 * (see validate_xmit_skb_list() for example)
4737 struct sk_buff *iter;
4738 int type = skb_shinfo(head_skb)->gso_type;
4739 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4741 /* Update type to add partial and then remove dodgy if set */
4742 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4743 type &= ~SKB_GSO_DODGY;
4745 /* Update GSO info and prepare to start updating headers on
4746 * our way back down the stack of protocols.
4748 for (iter = segs; iter; iter = iter->next) {
4749 skb_shinfo(iter)->gso_size = gso_size;
4750 skb_shinfo(iter)->gso_segs = partial_segs;
4751 skb_shinfo(iter)->gso_type = type;
4752 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4755 if (tail->len - doffset <= gso_size)
4756 skb_shinfo(tail)->gso_size = 0;
4757 else if (tail != segs)
4758 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4761 /* Following permits correct backpressure, for protocols
4762 * using skb_set_owner_w().
4763 * Idea is to tranfert ownership from head_skb to last segment.
4765 if (head_skb->destructor == sock_wfree) {
4766 swap(tail->truesize, head_skb->truesize);
4767 swap(tail->destructor, head_skb->destructor);
4768 swap(tail->sk, head_skb->sk);
4773 kfree_skb_list(segs);
4774 return ERR_PTR(err);
4776 EXPORT_SYMBOL_GPL(skb_segment);
4778 #ifdef CONFIG_SKB_EXTENSIONS
4779 #define SKB_EXT_ALIGN_VALUE 8
4780 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4782 static const u8 skb_ext_type_len[] = {
4783 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4784 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4787 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4789 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4790 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4792 #if IS_ENABLED(CONFIG_MPTCP)
4793 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4795 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4796 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4800 static __always_inline unsigned int skb_ext_total_length(void)
4802 unsigned int l = SKB_EXT_CHUNKSIZEOF(struct skb_ext);
4805 for (i = 0; i < ARRAY_SIZE(skb_ext_type_len); i++)
4806 l += skb_ext_type_len[i];
4811 static void skb_extensions_init(void)
4813 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4814 #if !IS_ENABLED(CONFIG_KCOV_INSTRUMENT_ALL)
4815 BUILD_BUG_ON(skb_ext_total_length() > 255);
4818 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4819 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4821 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4825 static void skb_extensions_init(void) {}
4828 /* The SKB kmem_cache slab is critical for network performance. Never
4829 * merge/alias the slab with similar sized objects. This avoids fragmentation
4830 * that hurts performance of kmem_cache_{alloc,free}_bulk APIs.
4832 #ifndef CONFIG_SLUB_TINY
4833 #define FLAG_SKB_NO_MERGE SLAB_NO_MERGE
4834 #else /* CONFIG_SLUB_TINY - simple loop in kmem_cache_alloc_bulk */
4835 #define FLAG_SKB_NO_MERGE 0
4838 void __init skb_init(void)
4840 skbuff_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4841 sizeof(struct sk_buff),
4843 SLAB_HWCACHE_ALIGN|SLAB_PANIC|
4845 offsetof(struct sk_buff, cb),
4846 sizeof_field(struct sk_buff, cb),
4848 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4849 sizeof(struct sk_buff_fclones),
4851 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4853 /* usercopy should only access first SKB_SMALL_HEAD_HEADROOM bytes.
4854 * struct skb_shared_info is located at the end of skb->head,
4855 * and should not be copied to/from user.
4857 skb_small_head_cache = kmem_cache_create_usercopy("skbuff_small_head",
4858 SKB_SMALL_HEAD_CACHE_SIZE,
4860 SLAB_HWCACHE_ALIGN | SLAB_PANIC,
4862 SKB_SMALL_HEAD_HEADROOM,
4864 skb_extensions_init();
4868 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4869 unsigned int recursion_level)
4871 int start = skb_headlen(skb);
4872 int i, copy = start - offset;
4873 struct sk_buff *frag_iter;
4876 if (unlikely(recursion_level >= 24))
4882 sg_set_buf(sg, skb->data + offset, copy);
4884 if ((len -= copy) == 0)
4889 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4892 WARN_ON(start > offset + len);
4894 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4895 if ((copy = end - offset) > 0) {
4896 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4897 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4902 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4903 skb_frag_off(frag) + offset - start);
4912 skb_walk_frags(skb, frag_iter) {
4915 WARN_ON(start > offset + len);
4917 end = start + frag_iter->len;
4918 if ((copy = end - offset) > 0) {
4919 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4924 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4925 copy, recursion_level + 1);
4926 if (unlikely(ret < 0))
4929 if ((len -= copy) == 0)
4940 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4941 * @skb: Socket buffer containing the buffers to be mapped
4942 * @sg: The scatter-gather list to map into
4943 * @offset: The offset into the buffer's contents to start mapping
4944 * @len: Length of buffer space to be mapped
4946 * Fill the specified scatter-gather list with mappings/pointers into a
4947 * region of the buffer space attached to a socket buffer. Returns either
4948 * the number of scatterlist items used, or -EMSGSIZE if the contents
4951 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4953 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4958 sg_mark_end(&sg[nsg - 1]);
4962 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4964 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4965 * sglist without mark the sg which contain last skb data as the end.
4966 * So the caller can mannipulate sg list as will when padding new data after
4967 * the first call without calling sg_unmark_end to expend sg list.
4969 * Scenario to use skb_to_sgvec_nomark:
4971 * 2. skb_to_sgvec_nomark(payload1)
4972 * 3. skb_to_sgvec_nomark(payload2)
4974 * This is equivalent to:
4976 * 2. skb_to_sgvec(payload1)
4978 * 4. skb_to_sgvec(payload2)
4980 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4981 * is more preferable.
4983 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4984 int offset, int len)
4986 return __skb_to_sgvec(skb, sg, offset, len, 0);
4988 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4993 * skb_cow_data - Check that a socket buffer's data buffers are writable
4994 * @skb: The socket buffer to check.
4995 * @tailbits: Amount of trailing space to be added
4996 * @trailer: Returned pointer to the skb where the @tailbits space begins
4998 * Make sure that the data buffers attached to a socket buffer are
4999 * writable. If they are not, private copies are made of the data buffers
5000 * and the socket buffer is set to use these instead.
5002 * If @tailbits is given, make sure that there is space to write @tailbits
5003 * bytes of data beyond current end of socket buffer. @trailer will be
5004 * set to point to the skb in which this space begins.
5006 * The number of scatterlist elements required to completely map the
5007 * COW'd and extended socket buffer will be returned.
5009 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
5013 struct sk_buff *skb1, **skb_p;
5015 /* If skb is cloned or its head is paged, reallocate
5016 * head pulling out all the pages (pages are considered not writable
5017 * at the moment even if they are anonymous).
5019 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
5020 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
5023 /* Easy case. Most of packets will go this way. */
5024 if (!skb_has_frag_list(skb)) {
5025 /* A little of trouble, not enough of space for trailer.
5026 * This should not happen, when stack is tuned to generate
5027 * good frames. OK, on miss we reallocate and reserve even more
5028 * space, 128 bytes is fair. */
5030 if (skb_tailroom(skb) < tailbits &&
5031 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
5039 /* Misery. We are in troubles, going to mincer fragments... */
5042 skb_p = &skb_shinfo(skb)->frag_list;
5045 while ((skb1 = *skb_p) != NULL) {
5048 /* The fragment is partially pulled by someone,
5049 * this can happen on input. Copy it and everything
5052 if (skb_shared(skb1))
5055 /* If the skb is the last, worry about trailer. */
5057 if (skb1->next == NULL && tailbits) {
5058 if (skb_shinfo(skb1)->nr_frags ||
5059 skb_has_frag_list(skb1) ||
5060 skb_tailroom(skb1) < tailbits)
5061 ntail = tailbits + 128;
5067 skb_shinfo(skb1)->nr_frags ||
5068 skb_has_frag_list(skb1)) {
5069 struct sk_buff *skb2;
5071 /* Fuck, we are miserable poor guys... */
5073 skb2 = skb_copy(skb1, GFP_ATOMIC);
5075 skb2 = skb_copy_expand(skb1,
5079 if (unlikely(skb2 == NULL))
5083 skb_set_owner_w(skb2, skb1->sk);
5085 /* Looking around. Are we still alive?
5086 * OK, link new skb, drop old one */
5088 skb2->next = skb1->next;
5095 skb_p = &skb1->next;
5100 EXPORT_SYMBOL_GPL(skb_cow_data);
5102 static void sock_rmem_free(struct sk_buff *skb)
5104 struct sock *sk = skb->sk;
5106 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
5109 static void skb_set_err_queue(struct sk_buff *skb)
5111 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
5112 * So, it is safe to (mis)use it to mark skbs on the error queue.
5114 skb->pkt_type = PACKET_OUTGOING;
5115 BUILD_BUG_ON(PACKET_OUTGOING == 0);
5119 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
5121 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
5123 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
5124 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
5129 skb->destructor = sock_rmem_free;
5130 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
5131 skb_set_err_queue(skb);
5133 /* before exiting rcu section, make sure dst is refcounted */
5136 skb_queue_tail(&sk->sk_error_queue, skb);
5137 if (!sock_flag(sk, SOCK_DEAD))
5138 sk_error_report(sk);
5141 EXPORT_SYMBOL(sock_queue_err_skb);
5143 static bool is_icmp_err_skb(const struct sk_buff *skb)
5145 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
5146 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
5149 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
5151 struct sk_buff_head *q = &sk->sk_error_queue;
5152 struct sk_buff *skb, *skb_next = NULL;
5153 bool icmp_next = false;
5154 unsigned long flags;
5156 spin_lock_irqsave(&q->lock, flags);
5157 skb = __skb_dequeue(q);
5158 if (skb && (skb_next = skb_peek(q))) {
5159 icmp_next = is_icmp_err_skb(skb_next);
5161 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
5163 spin_unlock_irqrestore(&q->lock, flags);
5165 if (is_icmp_err_skb(skb) && !icmp_next)
5169 sk_error_report(sk);
5173 EXPORT_SYMBOL(sock_dequeue_err_skb);
5176 * skb_clone_sk - create clone of skb, and take reference to socket
5177 * @skb: the skb to clone
5179 * This function creates a clone of a buffer that holds a reference on
5180 * sk_refcnt. Buffers created via this function are meant to be
5181 * returned using sock_queue_err_skb, or free via kfree_skb.
5183 * When passing buffers allocated with this function to sock_queue_err_skb
5184 * it is necessary to wrap the call with sock_hold/sock_put in order to
5185 * prevent the socket from being released prior to being enqueued on
5186 * the sk_error_queue.
5188 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
5190 struct sock *sk = skb->sk;
5191 struct sk_buff *clone;
5193 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
5196 clone = skb_clone(skb, GFP_ATOMIC);
5203 clone->destructor = sock_efree;
5207 EXPORT_SYMBOL(skb_clone_sk);
5209 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
5214 struct sock_exterr_skb *serr;
5217 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
5219 serr = SKB_EXT_ERR(skb);
5220 memset(serr, 0, sizeof(*serr));
5221 serr->ee.ee_errno = ENOMSG;
5222 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5223 serr->ee.ee_info = tstype;
5224 serr->opt_stats = opt_stats;
5225 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5226 if (READ_ONCE(sk->sk_tsflags) & SOF_TIMESTAMPING_OPT_ID) {
5227 serr->ee.ee_data = skb_shinfo(skb)->tskey;
5229 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5232 err = sock_queue_err_skb(sk, skb);
5238 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5242 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5245 read_lock_bh(&sk->sk_callback_lock);
5246 ret = sk->sk_socket && sk->sk_socket->file &&
5247 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5248 read_unlock_bh(&sk->sk_callback_lock);
5252 void skb_complete_tx_timestamp(struct sk_buff *skb,
5253 struct skb_shared_hwtstamps *hwtstamps)
5255 struct sock *sk = skb->sk;
5257 if (!skb_may_tx_timestamp(sk, false))
5260 /* Take a reference to prevent skb_orphan() from freeing the socket,
5261 * but only if the socket refcount is not zero.
5263 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5264 *skb_hwtstamps(skb) = *hwtstamps;
5265 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5273 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5275 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5276 const struct sk_buff *ack_skb,
5277 struct skb_shared_hwtstamps *hwtstamps,
5278 struct sock *sk, int tstype)
5280 struct sk_buff *skb;
5281 bool tsonly, opt_stats = false;
5287 tsflags = READ_ONCE(sk->sk_tsflags);
5288 if (!hwtstamps && !(tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5289 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5292 tsonly = tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5293 if (!skb_may_tx_timestamp(sk, tsonly))
5298 if ((tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5300 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5305 skb = alloc_skb(0, GFP_ATOMIC);
5307 skb = skb_clone(orig_skb, GFP_ATOMIC);
5309 if (skb_orphan_frags_rx(skb, GFP_ATOMIC)) {
5318 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5320 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5324 *skb_hwtstamps(skb) = *hwtstamps;
5326 __net_timestamp(skb);
5328 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5330 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5332 void skb_tstamp_tx(struct sk_buff *orig_skb,
5333 struct skb_shared_hwtstamps *hwtstamps)
5335 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5338 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5340 #ifdef CONFIG_WIRELESS
5341 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5343 struct sock *sk = skb->sk;
5344 struct sock_exterr_skb *serr;
5347 skb->wifi_acked_valid = 1;
5348 skb->wifi_acked = acked;
5350 serr = SKB_EXT_ERR(skb);
5351 memset(serr, 0, sizeof(*serr));
5352 serr->ee.ee_errno = ENOMSG;
5353 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5355 /* Take a reference to prevent skb_orphan() from freeing the socket,
5356 * but only if the socket refcount is not zero.
5358 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5359 err = sock_queue_err_skb(sk, skb);
5365 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5366 #endif /* CONFIG_WIRELESS */
5369 * skb_partial_csum_set - set up and verify partial csum values for packet
5370 * @skb: the skb to set
5371 * @start: the number of bytes after skb->data to start checksumming.
5372 * @off: the offset from start to place the checksum.
5374 * For untrusted partially-checksummed packets, we need to make sure the values
5375 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5377 * This function checks and sets those values and skb->ip_summed: if this
5378 * returns false you should drop the packet.
5380 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5382 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5383 u32 csum_start = skb_headroom(skb) + (u32)start;
5385 if (unlikely(csum_start >= U16_MAX || csum_end > skb_headlen(skb))) {
5386 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5387 start, off, skb_headroom(skb), skb_headlen(skb));
5390 skb->ip_summed = CHECKSUM_PARTIAL;
5391 skb->csum_start = csum_start;
5392 skb->csum_offset = off;
5393 skb->transport_header = csum_start;
5396 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5398 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5401 if (skb_headlen(skb) >= len)
5404 /* If we need to pullup then pullup to the max, so we
5405 * won't need to do it again.
5410 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5413 if (skb_headlen(skb) < len)
5419 #define MAX_TCP_HDR_LEN (15 * 4)
5421 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5422 typeof(IPPROTO_IP) proto,
5429 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5430 off + MAX_TCP_HDR_LEN);
5431 if (!err && !skb_partial_csum_set(skb, off,
5432 offsetof(struct tcphdr,
5435 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5438 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5439 off + sizeof(struct udphdr));
5440 if (!err && !skb_partial_csum_set(skb, off,
5441 offsetof(struct udphdr,
5444 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5447 return ERR_PTR(-EPROTO);
5450 /* This value should be large enough to cover a tagged ethernet header plus
5451 * maximally sized IP and TCP or UDP headers.
5453 #define MAX_IP_HDR_LEN 128
5455 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5464 err = skb_maybe_pull_tail(skb,
5465 sizeof(struct iphdr),
5470 if (ip_is_fragment(ip_hdr(skb)))
5473 off = ip_hdrlen(skb);
5480 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5482 return PTR_ERR(csum);
5485 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5488 ip_hdr(skb)->protocol, 0);
5495 /* This value should be large enough to cover a tagged ethernet header plus
5496 * an IPv6 header, all options, and a maximal TCP or UDP header.
5498 #define MAX_IPV6_HDR_LEN 256
5500 #define OPT_HDR(type, skb, off) \
5501 (type *)(skb_network_header(skb) + (off))
5503 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5516 off = sizeof(struct ipv6hdr);
5518 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5522 nexthdr = ipv6_hdr(skb)->nexthdr;
5524 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5525 while (off <= len && !done) {
5527 case IPPROTO_DSTOPTS:
5528 case IPPROTO_HOPOPTS:
5529 case IPPROTO_ROUTING: {
5530 struct ipv6_opt_hdr *hp;
5532 err = skb_maybe_pull_tail(skb,
5534 sizeof(struct ipv6_opt_hdr),
5539 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5540 nexthdr = hp->nexthdr;
5541 off += ipv6_optlen(hp);
5545 struct ip_auth_hdr *hp;
5547 err = skb_maybe_pull_tail(skb,
5549 sizeof(struct ip_auth_hdr),
5554 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5555 nexthdr = hp->nexthdr;
5556 off += ipv6_authlen(hp);
5559 case IPPROTO_FRAGMENT: {
5560 struct frag_hdr *hp;
5562 err = skb_maybe_pull_tail(skb,
5564 sizeof(struct frag_hdr),
5569 hp = OPT_HDR(struct frag_hdr, skb, off);
5571 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5574 nexthdr = hp->nexthdr;
5575 off += sizeof(struct frag_hdr);
5586 if (!done || fragment)
5589 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5591 return PTR_ERR(csum);
5594 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5595 &ipv6_hdr(skb)->daddr,
5596 skb->len - off, nexthdr, 0);
5604 * skb_checksum_setup - set up partial checksum offset
5605 * @skb: the skb to set up
5606 * @recalculate: if true the pseudo-header checksum will be recalculated
5608 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5612 switch (skb->protocol) {
5613 case htons(ETH_P_IP):
5614 err = skb_checksum_setup_ipv4(skb, recalculate);
5617 case htons(ETH_P_IPV6):
5618 err = skb_checksum_setup_ipv6(skb, recalculate);
5628 EXPORT_SYMBOL(skb_checksum_setup);
5631 * skb_checksum_maybe_trim - maybe trims the given skb
5632 * @skb: the skb to check
5633 * @transport_len: the data length beyond the network header
5635 * Checks whether the given skb has data beyond the given transport length.
5636 * If so, returns a cloned skb trimmed to this transport length.
5637 * Otherwise returns the provided skb. Returns NULL in error cases
5638 * (e.g. transport_len exceeds skb length or out-of-memory).
5640 * Caller needs to set the skb transport header and free any returned skb if it
5641 * differs from the provided skb.
5643 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5644 unsigned int transport_len)
5646 struct sk_buff *skb_chk;
5647 unsigned int len = skb_transport_offset(skb) + transport_len;
5652 else if (skb->len == len)
5655 skb_chk = skb_clone(skb, GFP_ATOMIC);
5659 ret = pskb_trim_rcsum(skb_chk, len);
5669 * skb_checksum_trimmed - validate checksum of an skb
5670 * @skb: the skb to check
5671 * @transport_len: the data length beyond the network header
5672 * @skb_chkf: checksum function to use
5674 * Applies the given checksum function skb_chkf to the provided skb.
5675 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5677 * If the skb has data beyond the given transport length, then a
5678 * trimmed & cloned skb is checked and returned.
5680 * Caller needs to set the skb transport header and free any returned skb if it
5681 * differs from the provided skb.
5683 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5684 unsigned int transport_len,
5685 __sum16(*skb_chkf)(struct sk_buff *skb))
5687 struct sk_buff *skb_chk;
5688 unsigned int offset = skb_transport_offset(skb);
5691 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5695 if (!pskb_may_pull(skb_chk, offset))
5698 skb_pull_rcsum(skb_chk, offset);
5699 ret = skb_chkf(skb_chk);
5700 skb_push_rcsum(skb_chk, offset);
5708 if (skb_chk && skb_chk != skb)
5714 EXPORT_SYMBOL(skb_checksum_trimmed);
5716 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5718 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5721 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5723 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5726 skb_release_head_state(skb);
5727 kmem_cache_free(skbuff_cache, skb);
5732 EXPORT_SYMBOL(kfree_skb_partial);
5735 * skb_try_coalesce - try to merge skb to prior one
5737 * @from: buffer to add
5738 * @fragstolen: pointer to boolean
5739 * @delta_truesize: how much more was allocated than was requested
5741 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5742 bool *fragstolen, int *delta_truesize)
5744 struct skb_shared_info *to_shinfo, *from_shinfo;
5745 int i, delta, len = from->len;
5747 *fragstolen = false;
5752 /* In general, avoid mixing page_pool and non-page_pool allocated
5753 * pages within the same SKB. Additionally avoid dealing with clones
5754 * with page_pool pages, in case the SKB is using page_pool fragment
5755 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5756 * references for cloned SKBs at the moment that would result in
5757 * inconsistent reference counts.
5758 * In theory we could take full references if @from is cloned and
5759 * !@to->pp_recycle but its tricky (due to potential race with
5760 * the clone disappearing) and rare, so not worth dealing with.
5762 if (to->pp_recycle != from->pp_recycle ||
5763 (from->pp_recycle && skb_cloned(from)))
5766 if (len <= skb_tailroom(to)) {
5768 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5769 *delta_truesize = 0;
5773 to_shinfo = skb_shinfo(to);
5774 from_shinfo = skb_shinfo(from);
5775 if (to_shinfo->frag_list || from_shinfo->frag_list)
5777 if (skb_zcopy(to) || skb_zcopy(from))
5780 if (skb_headlen(from) != 0) {
5782 unsigned int offset;
5784 if (to_shinfo->nr_frags +
5785 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5788 if (skb_head_is_locked(from))
5791 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5793 page = virt_to_head_page(from->head);
5794 offset = from->data - (unsigned char *)page_address(page);
5796 skb_fill_page_desc(to, to_shinfo->nr_frags,
5797 page, offset, skb_headlen(from));
5800 if (to_shinfo->nr_frags +
5801 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5804 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5807 WARN_ON_ONCE(delta < len);
5809 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5811 from_shinfo->nr_frags * sizeof(skb_frag_t));
5812 to_shinfo->nr_frags += from_shinfo->nr_frags;
5814 if (!skb_cloned(from))
5815 from_shinfo->nr_frags = 0;
5817 /* if the skb is not cloned this does nothing
5818 * since we set nr_frags to 0.
5820 for (i = 0; i < from_shinfo->nr_frags; i++)
5821 __skb_frag_ref(&from_shinfo->frags[i]);
5823 to->truesize += delta;
5825 to->data_len += len;
5827 *delta_truesize = delta;
5830 EXPORT_SYMBOL(skb_try_coalesce);
5833 * skb_scrub_packet - scrub an skb
5835 * @skb: buffer to clean
5836 * @xnet: packet is crossing netns
5838 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5839 * into/from a tunnel. Some information have to be cleared during these
5841 * skb_scrub_packet can also be used to clean a skb before injecting it in
5842 * another namespace (@xnet == true). We have to clear all information in the
5843 * skb that could impact namespace isolation.
5845 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5847 skb->pkt_type = PACKET_HOST;
5853 nf_reset_trace(skb);
5855 #ifdef CONFIG_NET_SWITCHDEV
5856 skb->offload_fwd_mark = 0;
5857 skb->offload_l3_fwd_mark = 0;
5865 skb_clear_tstamp(skb);
5867 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5869 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5871 int mac_len, meta_len;
5874 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5879 mac_len = skb->data - skb_mac_header(skb);
5880 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5881 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5882 mac_len - VLAN_HLEN - ETH_TLEN);
5885 meta_len = skb_metadata_len(skb);
5887 meta = skb_metadata_end(skb) - meta_len;
5888 memmove(meta + VLAN_HLEN, meta, meta_len);
5891 skb->mac_header += VLAN_HLEN;
5895 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5897 struct vlan_hdr *vhdr;
5900 if (unlikely(skb_vlan_tag_present(skb))) {
5901 /* vlan_tci is already set-up so leave this for another time */
5905 skb = skb_share_check(skb, GFP_ATOMIC);
5908 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5909 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5912 vhdr = (struct vlan_hdr *)skb->data;
5913 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5914 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5916 skb_pull_rcsum(skb, VLAN_HLEN);
5917 vlan_set_encap_proto(skb, vhdr);
5919 skb = skb_reorder_vlan_header(skb);
5923 skb_reset_network_header(skb);
5924 if (!skb_transport_header_was_set(skb))
5925 skb_reset_transport_header(skb);
5926 skb_reset_mac_len(skb);
5934 EXPORT_SYMBOL(skb_vlan_untag);
5936 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5938 if (!pskb_may_pull(skb, write_len))
5941 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5944 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5946 EXPORT_SYMBOL(skb_ensure_writable);
5948 /* remove VLAN header from packet and update csum accordingly.
5949 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5951 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5953 int offset = skb->data - skb_mac_header(skb);
5956 if (WARN_ONCE(offset,
5957 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5962 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5966 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5968 vlan_remove_tag(skb, vlan_tci);
5970 skb->mac_header += VLAN_HLEN;
5972 if (skb_network_offset(skb) < ETH_HLEN)
5973 skb_set_network_header(skb, ETH_HLEN);
5975 skb_reset_mac_len(skb);
5979 EXPORT_SYMBOL(__skb_vlan_pop);
5981 /* Pop a vlan tag either from hwaccel or from payload.
5982 * Expects skb->data at mac header.
5984 int skb_vlan_pop(struct sk_buff *skb)
5990 if (likely(skb_vlan_tag_present(skb))) {
5991 __vlan_hwaccel_clear_tag(skb);
5993 if (unlikely(!eth_type_vlan(skb->protocol)))
5996 err = __skb_vlan_pop(skb, &vlan_tci);
6000 /* move next vlan tag to hw accel tag */
6001 if (likely(!eth_type_vlan(skb->protocol)))
6004 vlan_proto = skb->protocol;
6005 err = __skb_vlan_pop(skb, &vlan_tci);
6009 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6012 EXPORT_SYMBOL(skb_vlan_pop);
6014 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
6015 * Expects skb->data at mac header.
6017 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
6019 if (skb_vlan_tag_present(skb)) {
6020 int offset = skb->data - skb_mac_header(skb);
6023 if (WARN_ONCE(offset,
6024 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
6029 err = __vlan_insert_tag(skb, skb->vlan_proto,
6030 skb_vlan_tag_get(skb));
6034 skb->protocol = skb->vlan_proto;
6035 skb->mac_len += VLAN_HLEN;
6037 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6039 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6042 EXPORT_SYMBOL(skb_vlan_push);
6045 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
6047 * @skb: Socket buffer to modify
6049 * Drop the Ethernet header of @skb.
6051 * Expects that skb->data points to the mac header and that no VLAN tags are
6054 * Returns 0 on success, -errno otherwise.
6056 int skb_eth_pop(struct sk_buff *skb)
6058 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
6059 skb_network_offset(skb) < ETH_HLEN)
6062 skb_pull_rcsum(skb, ETH_HLEN);
6063 skb_reset_mac_header(skb);
6064 skb_reset_mac_len(skb);
6068 EXPORT_SYMBOL(skb_eth_pop);
6071 * skb_eth_push() - Add a new Ethernet header at the head of a packet
6073 * @skb: Socket buffer to modify
6074 * @dst: Destination MAC address of the new header
6075 * @src: Source MAC address of the new header
6077 * Prepend @skb with a new Ethernet header.
6079 * Expects that skb->data points to the mac header, which must be empty.
6081 * Returns 0 on success, -errno otherwise.
6083 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6084 const unsigned char *src)
6089 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6092 err = skb_cow_head(skb, sizeof(*eth));
6096 skb_push(skb, sizeof(*eth));
6097 skb_reset_mac_header(skb);
6098 skb_reset_mac_len(skb);
6101 ether_addr_copy(eth->h_dest, dst);
6102 ether_addr_copy(eth->h_source, src);
6103 eth->h_proto = skb->protocol;
6105 skb_postpush_rcsum(skb, eth, sizeof(*eth));
6109 EXPORT_SYMBOL(skb_eth_push);
6111 /* Update the ethertype of hdr and the skb csum value if required. */
6112 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6115 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6116 __be16 diff[] = { ~hdr->h_proto, ethertype };
6118 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6121 hdr->h_proto = ethertype;
6125 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6129 * @mpls_lse: MPLS label stack entry to push
6130 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6131 * @mac_len: length of the MAC header
6132 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6135 * Expects skb->data at mac header.
6137 * Returns 0 on success, -errno otherwise.
6139 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6140 int mac_len, bool ethernet)
6142 struct mpls_shim_hdr *lse;
6145 if (unlikely(!eth_p_mpls(mpls_proto)))
6148 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6149 if (skb->encapsulation)
6152 err = skb_cow_head(skb, MPLS_HLEN);
6156 if (!skb->inner_protocol) {
6157 skb_set_inner_network_header(skb, skb_network_offset(skb));
6158 skb_set_inner_protocol(skb, skb->protocol);
6161 skb_push(skb, MPLS_HLEN);
6162 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6164 skb_reset_mac_header(skb);
6165 skb_set_network_header(skb, mac_len);
6166 skb_reset_mac_len(skb);
6168 lse = mpls_hdr(skb);
6169 lse->label_stack_entry = mpls_lse;
6170 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6172 if (ethernet && mac_len >= ETH_HLEN)
6173 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6174 skb->protocol = mpls_proto;
6178 EXPORT_SYMBOL_GPL(skb_mpls_push);
6181 * skb_mpls_pop() - pop the outermost MPLS header
6184 * @next_proto: ethertype of header after popped MPLS header
6185 * @mac_len: length of the MAC header
6186 * @ethernet: flag to indicate if the packet is ethernet
6188 * Expects skb->data at mac header.
6190 * Returns 0 on success, -errno otherwise.
6192 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6197 if (unlikely(!eth_p_mpls(skb->protocol)))
6200 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6204 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6205 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6208 __skb_pull(skb, MPLS_HLEN);
6209 skb_reset_mac_header(skb);
6210 skb_set_network_header(skb, mac_len);
6212 if (ethernet && mac_len >= ETH_HLEN) {
6215 /* use mpls_hdr() to get ethertype to account for VLANs. */
6216 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6217 skb_mod_eth_type(skb, hdr, next_proto);
6219 skb->protocol = next_proto;
6223 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6226 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6229 * @mpls_lse: new MPLS label stack entry to update to
6231 * Expects skb->data at mac header.
6233 * Returns 0 on success, -errno otherwise.
6235 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6239 if (unlikely(!eth_p_mpls(skb->protocol)))
6242 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6246 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6247 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6249 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6252 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6256 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6259 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6263 * Expects skb->data at mac header.
6265 * Returns 0 on success, -errno otherwise.
6267 int skb_mpls_dec_ttl(struct sk_buff *skb)
6272 if (unlikely(!eth_p_mpls(skb->protocol)))
6275 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6278 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6279 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6283 lse &= ~MPLS_LS_TTL_MASK;
6284 lse |= ttl << MPLS_LS_TTL_SHIFT;
6286 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6288 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6291 * alloc_skb_with_frags - allocate skb with page frags
6293 * @header_len: size of linear part
6294 * @data_len: needed length in frags
6295 * @order: max page order desired.
6296 * @errcode: pointer to error code if any
6297 * @gfp_mask: allocation mask
6299 * This can be used to allocate a paged skb, given a maximal order for frags.
6301 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6302 unsigned long data_len,
6307 unsigned long chunk;
6308 struct sk_buff *skb;
6312 *errcode = -EMSGSIZE;
6313 if (unlikely(data_len > MAX_SKB_FRAGS * (PAGE_SIZE << order)))
6316 *errcode = -ENOBUFS;
6317 skb = alloc_skb(header_len, gfp_mask);
6322 if (nr_frags == MAX_SKB_FRAGS - 1)
6324 while (order && PAGE_ALIGN(data_len) < (PAGE_SIZE << order))
6328 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6337 page = alloc_page(gfp_mask);
6341 chunk = min_t(unsigned long, data_len,
6342 PAGE_SIZE << order);
6343 skb_fill_page_desc(skb, nr_frags, page, 0, chunk);
6345 skb->truesize += (PAGE_SIZE << order);
6354 EXPORT_SYMBOL(alloc_skb_with_frags);
6356 /* carve out the first off bytes from skb when off < headlen */
6357 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6358 const int headlen, gfp_t gfp_mask)
6361 unsigned int size = skb_end_offset(skb);
6362 int new_hlen = headlen - off;
6365 if (skb_pfmemalloc(skb))
6366 gfp_mask |= __GFP_MEMALLOC;
6368 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6371 size = SKB_WITH_OVERHEAD(size);
6373 /* Copy real data, and all frags */
6374 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6377 memcpy((struct skb_shared_info *)(data + size),
6379 offsetof(struct skb_shared_info,
6380 frags[skb_shinfo(skb)->nr_frags]));
6381 if (skb_cloned(skb)) {
6382 /* drop the old head gracefully */
6383 if (skb_orphan_frags(skb, gfp_mask)) {
6384 skb_kfree_head(data, size);
6387 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6388 skb_frag_ref(skb, i);
6389 if (skb_has_frag_list(skb))
6390 skb_clone_fraglist(skb);
6391 skb_release_data(skb, SKB_CONSUMED, false);
6393 /* we can reuse existing recount- all we did was
6396 skb_free_head(skb, false);
6402 skb_set_end_offset(skb, size);
6403 skb_set_tail_pointer(skb, skb_headlen(skb));
6404 skb_headers_offset_update(skb, 0);
6408 atomic_set(&skb_shinfo(skb)->dataref, 1);
6413 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6415 /* carve out the first eat bytes from skb's frag_list. May recurse into
6418 static int pskb_carve_frag_list(struct sk_buff *skb,
6419 struct skb_shared_info *shinfo, int eat,
6422 struct sk_buff *list = shinfo->frag_list;
6423 struct sk_buff *clone = NULL;
6424 struct sk_buff *insp = NULL;
6428 pr_err("Not enough bytes to eat. Want %d\n", eat);
6431 if (list->len <= eat) {
6432 /* Eaten as whole. */
6437 /* Eaten partially. */
6438 if (skb_shared(list)) {
6439 clone = skb_clone(list, gfp_mask);
6445 /* This may be pulled without problems. */
6448 if (pskb_carve(list, eat, gfp_mask) < 0) {
6456 /* Free pulled out fragments. */
6457 while ((list = shinfo->frag_list) != insp) {
6458 shinfo->frag_list = list->next;
6461 /* And insert new clone at head. */
6464 shinfo->frag_list = clone;
6469 /* carve off first len bytes from skb. Split line (off) is in the
6470 * non-linear part of skb
6472 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6473 int pos, gfp_t gfp_mask)
6476 unsigned int size = skb_end_offset(skb);
6478 const int nfrags = skb_shinfo(skb)->nr_frags;
6479 struct skb_shared_info *shinfo;
6481 if (skb_pfmemalloc(skb))
6482 gfp_mask |= __GFP_MEMALLOC;
6484 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6487 size = SKB_WITH_OVERHEAD(size);
6489 memcpy((struct skb_shared_info *)(data + size),
6490 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6491 if (skb_orphan_frags(skb, gfp_mask)) {
6492 skb_kfree_head(data, size);
6495 shinfo = (struct skb_shared_info *)(data + size);
6496 for (i = 0; i < nfrags; i++) {
6497 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6499 if (pos + fsize > off) {
6500 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6504 * We have two variants in this case:
6505 * 1. Move all the frag to the second
6506 * part, if it is possible. F.e.
6507 * this approach is mandatory for TUX,
6508 * where splitting is expensive.
6509 * 2. Split is accurately. We make this.
6511 skb_frag_off_add(&shinfo->frags[0], off - pos);
6512 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6514 skb_frag_ref(skb, i);
6519 shinfo->nr_frags = k;
6520 if (skb_has_frag_list(skb))
6521 skb_clone_fraglist(skb);
6523 /* split line is in frag list */
6524 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6525 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6526 if (skb_has_frag_list(skb))
6527 kfree_skb_list(skb_shinfo(skb)->frag_list);
6528 skb_kfree_head(data, size);
6531 skb_release_data(skb, SKB_CONSUMED, false);
6536 skb_set_end_offset(skb, size);
6537 skb_reset_tail_pointer(skb);
6538 skb_headers_offset_update(skb, 0);
6543 skb->data_len = skb->len;
6544 atomic_set(&skb_shinfo(skb)->dataref, 1);
6548 /* remove len bytes from the beginning of the skb */
6549 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6551 int headlen = skb_headlen(skb);
6554 return pskb_carve_inside_header(skb, len, headlen, gfp);
6556 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6559 /* Extract to_copy bytes starting at off from skb, and return this in
6562 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6563 int to_copy, gfp_t gfp)
6565 struct sk_buff *clone = skb_clone(skb, gfp);
6570 if (pskb_carve(clone, off, gfp) < 0 ||
6571 pskb_trim(clone, to_copy)) {
6577 EXPORT_SYMBOL(pskb_extract);
6580 * skb_condense - try to get rid of fragments/frag_list if possible
6583 * Can be used to save memory before skb is added to a busy queue.
6584 * If packet has bytes in frags and enough tail room in skb->head,
6585 * pull all of them, so that we can free the frags right now and adjust
6588 * We do not reallocate skb->head thus can not fail.
6589 * Caller must re-evaluate skb->truesize if needed.
6591 void skb_condense(struct sk_buff *skb)
6593 if (skb->data_len) {
6594 if (skb->data_len > skb->end - skb->tail ||
6598 /* Nice, we can free page frag(s) right now */
6599 __pskb_pull_tail(skb, skb->data_len);
6601 /* At this point, skb->truesize might be over estimated,
6602 * because skb had a fragment, and fragments do not tell
6604 * When we pulled its content into skb->head, fragment
6605 * was freed, but __pskb_pull_tail() could not possibly
6606 * adjust skb->truesize, not knowing the frag truesize.
6608 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6610 EXPORT_SYMBOL(skb_condense);
6612 #ifdef CONFIG_SKB_EXTENSIONS
6613 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6615 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6619 * __skb_ext_alloc - allocate a new skb extensions storage
6621 * @flags: See kmalloc().
6623 * Returns the newly allocated pointer. The pointer can later attached to a
6624 * skb via __skb_ext_set().
6625 * Note: caller must handle the skb_ext as an opaque data.
6627 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6629 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6632 memset(new->offset, 0, sizeof(new->offset));
6633 refcount_set(&new->refcnt, 1);
6639 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6640 unsigned int old_active)
6642 struct skb_ext *new;
6644 if (refcount_read(&old->refcnt) == 1)
6647 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6651 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6652 refcount_set(&new->refcnt, 1);
6655 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6656 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6659 for (i = 0; i < sp->len; i++)
6660 xfrm_state_hold(sp->xvec[i]);
6668 * __skb_ext_set - attach the specified extension storage to this skb
6671 * @ext: extension storage previously allocated via __skb_ext_alloc()
6673 * Existing extensions, if any, are cleared.
6675 * Returns the pointer to the extension.
6677 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6678 struct skb_ext *ext)
6680 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6683 newlen = newoff + skb_ext_type_len[id];
6684 ext->chunks = newlen;
6685 ext->offset[id] = newoff;
6686 skb->extensions = ext;
6687 skb->active_extensions = 1 << id;
6688 return skb_ext_get_ptr(ext, id);
6692 * skb_ext_add - allocate space for given extension, COW if needed
6694 * @id: extension to allocate space for
6696 * Allocates enough space for the given extension.
6697 * If the extension is already present, a pointer to that extension
6700 * If the skb was cloned, COW applies and the returned memory can be
6701 * modified without changing the extension space of clones buffers.
6703 * Returns pointer to the extension or NULL on allocation failure.
6705 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6707 struct skb_ext *new, *old = NULL;
6708 unsigned int newlen, newoff;
6710 if (skb->active_extensions) {
6711 old = skb->extensions;
6713 new = skb_ext_maybe_cow(old, skb->active_extensions);
6717 if (__skb_ext_exist(new, id))
6720 newoff = new->chunks;
6722 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6724 new = __skb_ext_alloc(GFP_ATOMIC);
6729 newlen = newoff + skb_ext_type_len[id];
6730 new->chunks = newlen;
6731 new->offset[id] = newoff;
6734 skb->extensions = new;
6735 skb->active_extensions |= 1 << id;
6736 return skb_ext_get_ptr(new, id);
6738 EXPORT_SYMBOL(skb_ext_add);
6741 static void skb_ext_put_sp(struct sec_path *sp)
6745 for (i = 0; i < sp->len; i++)
6746 xfrm_state_put(sp->xvec[i]);
6750 #ifdef CONFIG_MCTP_FLOWS
6751 static void skb_ext_put_mctp(struct mctp_flow *flow)
6754 mctp_key_unref(flow->key);
6758 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6760 struct skb_ext *ext = skb->extensions;
6762 skb->active_extensions &= ~(1 << id);
6763 if (skb->active_extensions == 0) {
6764 skb->extensions = NULL;
6767 } else if (id == SKB_EXT_SEC_PATH &&
6768 refcount_read(&ext->refcnt) == 1) {
6769 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6776 EXPORT_SYMBOL(__skb_ext_del);
6778 void __skb_ext_put(struct skb_ext *ext)
6780 /* If this is last clone, nothing can increment
6781 * it after check passes. Avoids one atomic op.
6783 if (refcount_read(&ext->refcnt) == 1)
6786 if (!refcount_dec_and_test(&ext->refcnt))
6790 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6791 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6793 #ifdef CONFIG_MCTP_FLOWS
6794 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6795 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6798 kmem_cache_free(skbuff_ext_cache, ext);
6800 EXPORT_SYMBOL(__skb_ext_put);
6801 #endif /* CONFIG_SKB_EXTENSIONS */
6804 * skb_attempt_defer_free - queue skb for remote freeing
6807 * Put @skb in a per-cpu list, using the cpu which
6808 * allocated the skb/pages to reduce false sharing
6809 * and memory zone spinlock contention.
6811 void skb_attempt_defer_free(struct sk_buff *skb)
6813 int cpu = skb->alloc_cpu;
6814 struct softnet_data *sd;
6815 unsigned int defer_max;
6818 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6820 cpu == raw_smp_processor_id()) {
6821 nodefer: __kfree_skb(skb);
6825 DEBUG_NET_WARN_ON_ONCE(skb_dst(skb));
6826 DEBUG_NET_WARN_ON_ONCE(skb->destructor);
6828 sd = &per_cpu(softnet_data, cpu);
6829 defer_max = READ_ONCE(sysctl_skb_defer_max);
6830 if (READ_ONCE(sd->defer_count) >= defer_max)
6833 spin_lock_bh(&sd->defer_lock);
6834 /* Send an IPI every time queue reaches half capacity. */
6835 kick = sd->defer_count == (defer_max >> 1);
6836 /* Paired with the READ_ONCE() few lines above */
6837 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6839 skb->next = sd->defer_list;
6840 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6841 WRITE_ONCE(sd->defer_list, skb);
6842 spin_unlock_bh(&sd->defer_lock);
6844 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6845 * if we are unlucky enough (this seems very unlikely).
6847 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1)) {
6848 #ifndef CONFIG_PREEMPT_RT
6849 smp_call_function_single_async(cpu, &sd->defer_csd);
6851 schedule_work_on(cpu, &sd->defer_work);
6856 static void skb_splice_csum_page(struct sk_buff *skb, struct page *page,
6857 size_t offset, size_t len)
6862 kaddr = kmap_local_page(page);
6863 csum = csum_partial(kaddr + offset, len, 0);
6864 kunmap_local(kaddr);
6865 skb->csum = csum_block_add(skb->csum, csum, skb->len);
6869 * skb_splice_from_iter - Splice (or copy) pages to skbuff
6870 * @skb: The buffer to add pages to
6871 * @iter: Iterator representing the pages to be added
6872 * @maxsize: Maximum amount of pages to be added
6873 * @gfp: Allocation flags
6875 * This is a common helper function for supporting MSG_SPLICE_PAGES. It
6876 * extracts pages from an iterator and adds them to the socket buffer if
6877 * possible, copying them to fragments if not possible (such as if they're slab
6880 * Returns the amount of data spliced/copied or -EMSGSIZE if there's
6881 * insufficient space in the buffer to transfer anything.
6883 ssize_t skb_splice_from_iter(struct sk_buff *skb, struct iov_iter *iter,
6884 ssize_t maxsize, gfp_t gfp)
6886 size_t frag_limit = READ_ONCE(sysctl_max_skb_frags);
6887 struct page *pages[8], **ppages = pages;
6888 ssize_t spliced = 0, ret = 0;
6891 while (iter->count > 0) {
6892 ssize_t space, nr, len;
6896 space = frag_limit - skb_shinfo(skb)->nr_frags;
6900 /* We might be able to coalesce without increasing nr_frags */
6901 nr = clamp_t(size_t, space, 1, ARRAY_SIZE(pages));
6903 len = iov_iter_extract_pages(iter, &ppages, maxsize, nr, 0, &off);
6911 struct page *page = pages[i++];
6912 size_t part = min_t(size_t, PAGE_SIZE - off, len);
6915 if (WARN_ON_ONCE(!sendpage_ok(page)))
6918 ret = skb_append_pagefrags(skb, page, off, part,
6921 iov_iter_revert(iter, len);
6925 if (skb->ip_summed == CHECKSUM_NONE)
6926 skb_splice_csum_page(skb, page, off, part);
6939 skb_len_add(skb, spliced);
6940 return spliced ?: ret;
6942 EXPORT_SYMBOL(skb_splice_from_iter);