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/if_vlan.h>
62 #include <linux/mpls.h>
63 #include <linux/kcov.h>
65 #include <net/protocol.h>
68 #include <net/checksum.h>
69 #include <net/ip6_checksum.h>
72 #include <net/mptcp.h>
74 #include <net/page_pool.h>
76 #include <linux/uaccess.h>
77 #include <trace/events/skb.h>
78 #include <linux/highmem.h>
79 #include <linux/capability.h>
80 #include <linux/user_namespace.h>
81 #include <linux/indirect_call_wrapper.h>
82 #include <linux/textsearch.h>
85 #include "sock_destructor.h"
87 struct kmem_cache *skbuff_head_cache __ro_after_init;
88 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
89 #ifdef CONFIG_SKB_EXTENSIONS
90 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
92 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
93 EXPORT_SYMBOL(sysctl_max_skb_frags);
96 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
97 const char * const drop_reasons[] = {
98 [SKB_CONSUMED] = "CONSUMED",
99 DEFINE_DROP_REASON(FN, FN)
101 EXPORT_SYMBOL(drop_reasons);
104 * skb_panic - private function for out-of-line support
108 * @msg: skb_over_panic or skb_under_panic
110 * Out-of-line support for skb_put() and skb_push().
111 * Called via the wrapper skb_over_panic() or skb_under_panic().
112 * Keep out of line to prevent kernel bloat.
113 * __builtin_return_address is not used because it is not always reliable.
115 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
118 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
119 msg, addr, skb->len, sz, skb->head, skb->data,
120 (unsigned long)skb->tail, (unsigned long)skb->end,
121 skb->dev ? skb->dev->name : "<NULL>");
125 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
127 skb_panic(skb, sz, addr, __func__);
130 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
132 skb_panic(skb, sz, addr, __func__);
135 #define NAPI_SKB_CACHE_SIZE 64
136 #define NAPI_SKB_CACHE_BULK 16
137 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
139 #if PAGE_SIZE == SZ_4K
141 #define NAPI_HAS_SMALL_PAGE_FRAG 1
142 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) ((nc).pfmemalloc)
144 /* specialized page frag allocator using a single order 0 page
145 * and slicing it into 1K sized fragment. Constrained to systems
146 * with a very limited amount of 1K fragments fitting a single
147 * page - to avoid excessive truesize underestimation
150 struct page_frag_1k {
156 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
161 offset = nc->offset - SZ_1K;
162 if (likely(offset >= 0))
165 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
169 nc->va = page_address(page);
170 nc->pfmemalloc = page_is_pfmemalloc(page);
171 offset = PAGE_SIZE - SZ_1K;
172 page_ref_add(page, offset / SZ_1K);
176 return nc->va + offset;
180 /* the small page is actually unused in this build; add dummy helpers
181 * to please the compiler and avoid later preprocessor's conditionals
183 #define NAPI_HAS_SMALL_PAGE_FRAG 0
184 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) false
186 struct page_frag_1k {
189 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
196 struct napi_alloc_cache {
197 struct page_frag_cache page;
198 struct page_frag_1k page_small;
199 unsigned int skb_count;
200 void *skb_cache[NAPI_SKB_CACHE_SIZE];
203 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
204 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
206 /* Double check that napi_get_frags() allocates skbs with
207 * skb->head being backed by slab, not a page fragment.
208 * This is to make sure bug fixed in 3226b158e67c
209 * ("net: avoid 32 x truesize under-estimation for tiny skbs")
210 * does not accidentally come back.
212 void napi_get_frags_check(struct napi_struct *napi)
217 skb = napi_get_frags(napi);
218 WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
219 napi_free_frags(napi);
223 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
225 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
227 fragsz = SKB_DATA_ALIGN(fragsz);
229 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
231 EXPORT_SYMBOL(__napi_alloc_frag_align);
233 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
237 fragsz = SKB_DATA_ALIGN(fragsz);
238 if (in_hardirq() || irqs_disabled()) {
239 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
241 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
243 struct napi_alloc_cache *nc;
246 nc = this_cpu_ptr(&napi_alloc_cache);
247 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
252 EXPORT_SYMBOL(__netdev_alloc_frag_align);
254 static struct sk_buff *napi_skb_cache_get(void)
256 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
259 if (unlikely(!nc->skb_count)) {
260 nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
264 if (unlikely(!nc->skb_count))
268 skb = nc->skb_cache[--nc->skb_count];
269 kasan_unpoison_object_data(skbuff_head_cache, skb);
274 static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
277 struct skb_shared_info *shinfo;
279 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
281 /* Assumes caller memset cleared SKB */
282 skb->truesize = SKB_TRUESIZE(size);
283 refcount_set(&skb->users, 1);
286 skb_reset_tail_pointer(skb);
287 skb_set_end_offset(skb, size);
288 skb->mac_header = (typeof(skb->mac_header))~0U;
289 skb->transport_header = (typeof(skb->transport_header))~0U;
290 skb->alloc_cpu = raw_smp_processor_id();
291 /* make sure we initialize shinfo sequentially */
292 shinfo = skb_shinfo(skb);
293 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
294 atomic_set(&shinfo->dataref, 1);
296 skb_set_kcov_handle(skb, kcov_common_handle());
299 static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
304 /* Must find the allocation size (and grow it to match). */
306 /* krealloc() will immediately return "data" when
307 * "ksize(data)" is requested: it is the existing upper
308 * bounds. As a result, GFP_ATOMIC will be ignored. Note
309 * that this "new" pointer needs to be passed back to the
310 * caller for use so the __alloc_size hinting will be
313 resized = krealloc(data, *size, GFP_ATOMIC);
314 WARN_ON_ONCE(resized != data);
318 /* build_skb() variant which can operate on slab buffers.
319 * Note that this should be used sparingly as slab buffers
320 * cannot be combined efficiently by GRO!
322 struct sk_buff *slab_build_skb(void *data)
327 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
331 memset(skb, 0, offsetof(struct sk_buff, tail));
332 data = __slab_build_skb(skb, data, &size);
333 __finalize_skb_around(skb, data, size);
337 EXPORT_SYMBOL(slab_build_skb);
339 /* Caller must provide SKB that is memset cleared */
340 static void __build_skb_around(struct sk_buff *skb, void *data,
341 unsigned int frag_size)
343 unsigned int size = frag_size;
345 /* frag_size == 0 is considered deprecated now. Callers
346 * using slab buffer should use slab_build_skb() instead.
348 if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
349 data = __slab_build_skb(skb, data, &size);
351 __finalize_skb_around(skb, data, size);
355 * __build_skb - build a network buffer
356 * @data: data buffer provided by caller
357 * @frag_size: size of data (must not be 0)
359 * Allocate a new &sk_buff. Caller provides space holding head and
360 * skb_shared_info. @data must have been allocated from the page
361 * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
362 * allocation is deprecated, and callers should use slab_build_skb()
364 * The return is the new skb buffer.
365 * On a failure the return is %NULL, and @data is not freed.
367 * Before IO, driver allocates only data buffer where NIC put incoming frame
368 * Driver should add room at head (NET_SKB_PAD) and
369 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
370 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
371 * before giving packet to stack.
372 * RX rings only contains data buffers, not full skbs.
374 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
378 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
382 memset(skb, 0, offsetof(struct sk_buff, tail));
383 __build_skb_around(skb, data, frag_size);
388 /* build_skb() is wrapper over __build_skb(), that specifically
389 * takes care of skb->head and skb->pfmemalloc
391 struct sk_buff *build_skb(void *data, unsigned int frag_size)
393 struct sk_buff *skb = __build_skb(data, frag_size);
395 if (skb && frag_size) {
397 if (page_is_pfmemalloc(virt_to_head_page(data)))
402 EXPORT_SYMBOL(build_skb);
405 * build_skb_around - build a network buffer around provided skb
406 * @skb: sk_buff provide by caller, must be memset cleared
407 * @data: data buffer provided by caller
408 * @frag_size: size of data
410 struct sk_buff *build_skb_around(struct sk_buff *skb,
411 void *data, unsigned int frag_size)
416 __build_skb_around(skb, data, frag_size);
420 if (page_is_pfmemalloc(virt_to_head_page(data)))
425 EXPORT_SYMBOL(build_skb_around);
428 * __napi_build_skb - build a network buffer
429 * @data: data buffer provided by caller
430 * @frag_size: size of data
432 * Version of __build_skb() that uses NAPI percpu caches to obtain
433 * skbuff_head instead of inplace allocation.
435 * Returns a new &sk_buff on success, %NULL on allocation failure.
437 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
441 skb = napi_skb_cache_get();
445 memset(skb, 0, offsetof(struct sk_buff, tail));
446 __build_skb_around(skb, data, frag_size);
452 * napi_build_skb - build a network buffer
453 * @data: data buffer provided by caller
454 * @frag_size: size of data
456 * Version of __napi_build_skb() that takes care of skb->head_frag
457 * and skb->pfmemalloc when the data is a page or page fragment.
459 * Returns a new &sk_buff on success, %NULL on allocation failure.
461 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
463 struct sk_buff *skb = __napi_build_skb(data, frag_size);
465 if (likely(skb) && frag_size) {
467 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
472 EXPORT_SYMBOL(napi_build_skb);
475 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
476 * the caller if emergency pfmemalloc reserves are being used. If it is and
477 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
478 * may be used. Otherwise, the packet data may be discarded until enough
481 static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
485 bool ret_pfmemalloc = false;
488 * Try a regular allocation, when that fails and we're not entitled
489 * to the reserves, fail.
491 obj = kmalloc_node_track_caller(size,
492 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
494 if (obj || !(gfp_pfmemalloc_allowed(flags)))
497 /* Try again but now we are using pfmemalloc reserves */
498 ret_pfmemalloc = true;
499 obj = kmalloc_node_track_caller(size, flags, node);
503 *pfmemalloc = ret_pfmemalloc;
508 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
509 * 'private' fields and also do memory statistics to find all the
515 * __alloc_skb - allocate a network buffer
516 * @size: size to allocate
517 * @gfp_mask: allocation mask
518 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
519 * instead of head cache and allocate a cloned (child) skb.
520 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
521 * allocations in case the data is required for writeback
522 * @node: numa node to allocate memory on
524 * Allocate a new &sk_buff. The returned buffer has no headroom and a
525 * tail room of at least size bytes. The object has a reference count
526 * of one. The return is the buffer. On a failure the return is %NULL.
528 * Buffers may only be allocated from interrupts using a @gfp_mask of
531 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
534 struct kmem_cache *cache;
540 cache = (flags & SKB_ALLOC_FCLONE)
541 ? skbuff_fclone_cache : skbuff_head_cache;
543 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
544 gfp_mask |= __GFP_MEMALLOC;
547 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
548 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
549 skb = napi_skb_cache_get();
551 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
556 /* We do our best to align skb_shared_info on a separate cache
557 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
558 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
559 * Both skb->head and skb_shared_info are cache line aligned.
561 size = SKB_DATA_ALIGN(size);
562 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
563 osize = kmalloc_size_roundup(size);
564 data = kmalloc_reserve(osize, gfp_mask, node, &pfmemalloc);
567 /* kmalloc_size_roundup() might give us more room than requested.
568 * Put skb_shared_info exactly at the end of allocated zone,
569 * to allow max possible filling before reallocation.
571 size = SKB_WITH_OVERHEAD(osize);
572 prefetchw(data + size);
575 * Only clear those fields we need to clear, not those that we will
576 * actually initialise below. Hence, don't put any more fields after
577 * the tail pointer in struct sk_buff!
579 memset(skb, 0, offsetof(struct sk_buff, tail));
580 __build_skb_around(skb, data, osize);
581 skb->pfmemalloc = pfmemalloc;
583 if (flags & SKB_ALLOC_FCLONE) {
584 struct sk_buff_fclones *fclones;
586 fclones = container_of(skb, struct sk_buff_fclones, skb1);
588 skb->fclone = SKB_FCLONE_ORIG;
589 refcount_set(&fclones->fclone_ref, 1);
595 kmem_cache_free(cache, skb);
598 EXPORT_SYMBOL(__alloc_skb);
601 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
602 * @dev: network device to receive on
603 * @len: length to allocate
604 * @gfp_mask: get_free_pages mask, passed to alloc_skb
606 * Allocate a new &sk_buff and assign it a usage count of one. The
607 * buffer has NET_SKB_PAD headroom built in. Users should allocate
608 * the headroom they think they need without accounting for the
609 * built in space. The built in space is used for optimisations.
611 * %NULL is returned if there is no free memory.
613 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
616 struct page_frag_cache *nc;
623 /* If requested length is either too small or too big,
624 * we use kmalloc() for skb->head allocation.
626 if (len <= SKB_WITH_OVERHEAD(1024) ||
627 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
628 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
629 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
635 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
636 len = SKB_DATA_ALIGN(len);
638 if (sk_memalloc_socks())
639 gfp_mask |= __GFP_MEMALLOC;
641 if (in_hardirq() || irqs_disabled()) {
642 nc = this_cpu_ptr(&netdev_alloc_cache);
643 data = page_frag_alloc(nc, len, gfp_mask);
644 pfmemalloc = nc->pfmemalloc;
647 nc = this_cpu_ptr(&napi_alloc_cache.page);
648 data = page_frag_alloc(nc, len, gfp_mask);
649 pfmemalloc = nc->pfmemalloc;
656 skb = __build_skb(data, len);
657 if (unlikely(!skb)) {
667 skb_reserve(skb, NET_SKB_PAD);
673 EXPORT_SYMBOL(__netdev_alloc_skb);
676 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
677 * @napi: napi instance this buffer was allocated for
678 * @len: length to allocate
679 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
681 * Allocate a new sk_buff for use in NAPI receive. This buffer will
682 * attempt to allocate the head from a special reserved region used
683 * only for NAPI Rx allocation. By doing this we can save several
684 * CPU cycles by avoiding having to disable and re-enable IRQs.
686 * %NULL is returned if there is no free memory.
688 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
691 struct napi_alloc_cache *nc;
696 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
697 len += NET_SKB_PAD + NET_IP_ALIGN;
699 /* If requested length is either too small or too big,
700 * we use kmalloc() for skb->head allocation.
701 * When the small frag allocator is available, prefer it over kmalloc
702 * for small fragments
704 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
705 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
706 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
707 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
714 nc = this_cpu_ptr(&napi_alloc_cache);
716 if (sk_memalloc_socks())
717 gfp_mask |= __GFP_MEMALLOC;
719 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
720 /* we are artificially inflating the allocation size, but
721 * that is not as bad as it may look like, as:
722 * - 'len' less than GRO_MAX_HEAD makes little sense
723 * - On most systems, larger 'len' values lead to fragment
724 * size above 512 bytes
725 * - kmalloc would use the kmalloc-1k slab for such values
726 * - Builds with smaller GRO_MAX_HEAD will very likely do
727 * little networking, as that implies no WiFi and no
728 * tunnels support, and 32 bits arches.
732 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
733 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
735 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
736 len = SKB_DATA_ALIGN(len);
738 data = page_frag_alloc(&nc->page, len, gfp_mask);
739 pfmemalloc = nc->page.pfmemalloc;
745 skb = __napi_build_skb(data, len);
746 if (unlikely(!skb)) {
756 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
757 skb->dev = napi->dev;
762 EXPORT_SYMBOL(__napi_alloc_skb);
764 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
765 int size, unsigned int truesize)
767 skb_fill_page_desc(skb, i, page, off, size);
769 skb->data_len += size;
770 skb->truesize += truesize;
772 EXPORT_SYMBOL(skb_add_rx_frag);
774 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
775 unsigned int truesize)
777 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
779 skb_frag_size_add(frag, size);
781 skb->data_len += size;
782 skb->truesize += truesize;
784 EXPORT_SYMBOL(skb_coalesce_rx_frag);
786 static void skb_drop_list(struct sk_buff **listp)
788 kfree_skb_list(*listp);
792 static inline void skb_drop_fraglist(struct sk_buff *skb)
794 skb_drop_list(&skb_shinfo(skb)->frag_list);
797 static void skb_clone_fraglist(struct sk_buff *skb)
799 struct sk_buff *list;
801 skb_walk_frags(skb, list)
805 static bool skb_pp_recycle(struct sk_buff *skb, void *data)
807 if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
809 return page_pool_return_skb_page(virt_to_page(data));
812 static void skb_free_head(struct sk_buff *skb)
814 unsigned char *head = skb->head;
816 if (skb->head_frag) {
817 if (skb_pp_recycle(skb, head))
825 static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason)
827 struct skb_shared_info *shinfo = skb_shinfo(skb);
831 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
835 if (skb_zcopy(skb)) {
836 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
838 skb_zcopy_clear(skb, true);
843 for (i = 0; i < shinfo->nr_frags; i++)
844 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
847 if (shinfo->frag_list)
848 kfree_skb_list_reason(shinfo->frag_list, reason);
852 /* When we clone an SKB we copy the reycling bit. The pp_recycle
853 * bit is only set on the head though, so in order to avoid races
854 * while trying to recycle fragments on __skb_frag_unref() we need
855 * to make one SKB responsible for triggering the recycle path.
856 * So disable the recycling bit if an SKB is cloned and we have
857 * additional references to the fragmented part of the SKB.
858 * Eventually the last SKB will have the recycling bit set and it's
859 * dataref set to 0, which will trigger the recycling
865 * Free an skbuff by memory without cleaning the state.
867 static void kfree_skbmem(struct sk_buff *skb)
869 struct sk_buff_fclones *fclones;
871 switch (skb->fclone) {
872 case SKB_FCLONE_UNAVAILABLE:
873 kmem_cache_free(skbuff_head_cache, skb);
876 case SKB_FCLONE_ORIG:
877 fclones = container_of(skb, struct sk_buff_fclones, skb1);
879 /* We usually free the clone (TX completion) before original skb
880 * This test would have no chance to be true for the clone,
881 * while here, branch prediction will be good.
883 if (refcount_read(&fclones->fclone_ref) == 1)
887 default: /* SKB_FCLONE_CLONE */
888 fclones = container_of(skb, struct sk_buff_fclones, skb2);
891 if (!refcount_dec_and_test(&fclones->fclone_ref))
894 kmem_cache_free(skbuff_fclone_cache, fclones);
897 void skb_release_head_state(struct sk_buff *skb)
900 if (skb->destructor) {
901 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
902 skb->destructor(skb);
904 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
905 nf_conntrack_put(skb_nfct(skb));
910 /* Free everything but the sk_buff shell. */
911 static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason)
913 skb_release_head_state(skb);
914 if (likely(skb->head))
915 skb_release_data(skb, reason);
919 * __kfree_skb - private function
922 * Free an sk_buff. Release anything attached to the buffer.
923 * Clean the state. This is an internal helper function. Users should
924 * always call kfree_skb
927 void __kfree_skb(struct sk_buff *skb)
929 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
932 EXPORT_SYMBOL(__kfree_skb);
934 static __always_inline
935 bool __kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
937 if (unlikely(!skb_unref(skb)))
940 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
942 if (reason == SKB_CONSUMED)
943 trace_consume_skb(skb);
945 trace_kfree_skb(skb, __builtin_return_address(0), reason);
950 * kfree_skb_reason - free an sk_buff with special reason
951 * @skb: buffer to free
952 * @reason: reason why this skb is dropped
954 * Drop a reference to the buffer and free it if the usage count has
955 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
959 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
961 if (__kfree_skb_reason(skb, reason))
964 EXPORT_SYMBOL(kfree_skb_reason);
966 #define KFREE_SKB_BULK_SIZE 16
968 struct skb_free_array {
969 unsigned int skb_count;
970 void *skb_array[KFREE_SKB_BULK_SIZE];
973 static void kfree_skb_add_bulk(struct sk_buff *skb,
974 struct skb_free_array *sa,
975 enum skb_drop_reason reason)
977 /* if SKB is a clone, don't handle this case */
978 if (unlikely(skb->fclone != SKB_FCLONE_UNAVAILABLE)) {
983 skb_release_all(skb, reason);
984 sa->skb_array[sa->skb_count++] = skb;
986 if (unlikely(sa->skb_count == KFREE_SKB_BULK_SIZE)) {
987 kmem_cache_free_bulk(skbuff_head_cache, KFREE_SKB_BULK_SIZE,
994 kfree_skb_list_reason(struct sk_buff *segs, enum skb_drop_reason reason)
996 struct skb_free_array sa;
1001 struct sk_buff *next = segs->next;
1003 if (__kfree_skb_reason(segs, reason))
1004 kfree_skb_add_bulk(segs, &sa, reason);
1010 kmem_cache_free_bulk(skbuff_head_cache, sa.skb_count,
1013 EXPORT_SYMBOL(kfree_skb_list_reason);
1015 /* Dump skb information and contents.
1017 * Must only be called from net_ratelimit()-ed paths.
1019 * Dumps whole packets if full_pkt, only headers otherwise.
1021 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
1023 struct skb_shared_info *sh = skb_shinfo(skb);
1024 struct net_device *dev = skb->dev;
1025 struct sock *sk = skb->sk;
1026 struct sk_buff *list_skb;
1027 bool has_mac, has_trans;
1028 int headroom, tailroom;
1029 int i, len, seg_len;
1034 len = min_t(int, skb->len, MAX_HEADER + 128);
1036 headroom = skb_headroom(skb);
1037 tailroom = skb_tailroom(skb);
1039 has_mac = skb_mac_header_was_set(skb);
1040 has_trans = skb_transport_header_was_set(skb);
1042 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
1043 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
1044 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
1045 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
1046 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
1047 level, skb->len, headroom, skb_headlen(skb), tailroom,
1048 has_mac ? skb->mac_header : -1,
1049 has_mac ? skb_mac_header_len(skb) : -1,
1050 skb->network_header,
1051 has_trans ? skb_network_header_len(skb) : -1,
1052 has_trans ? skb->transport_header : -1,
1053 sh->tx_flags, sh->nr_frags,
1054 sh->gso_size, sh->gso_type, sh->gso_segs,
1055 skb->csum, skb->ip_summed, skb->csum_complete_sw,
1056 skb->csum_valid, skb->csum_level,
1057 skb->hash, skb->sw_hash, skb->l4_hash,
1058 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
1061 printk("%sdev name=%s feat=%pNF\n",
1062 level, dev->name, &dev->features);
1064 printk("%ssk family=%hu type=%u proto=%u\n",
1065 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
1067 if (full_pkt && headroom)
1068 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
1069 16, 1, skb->head, headroom, false);
1071 seg_len = min_t(int, skb_headlen(skb), len);
1073 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
1074 16, 1, skb->data, seg_len, false);
1077 if (full_pkt && tailroom)
1078 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
1079 16, 1, skb_tail_pointer(skb), tailroom, false);
1081 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
1082 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1083 u32 p_off, p_len, copied;
1087 skb_frag_foreach_page(frag, skb_frag_off(frag),
1088 skb_frag_size(frag), p, p_off, p_len,
1090 seg_len = min_t(int, p_len, len);
1091 vaddr = kmap_atomic(p);
1092 print_hex_dump(level, "skb frag: ",
1094 16, 1, vaddr + p_off, seg_len, false);
1095 kunmap_atomic(vaddr);
1102 if (full_pkt && skb_has_frag_list(skb)) {
1103 printk("skb fraglist:\n");
1104 skb_walk_frags(skb, list_skb)
1105 skb_dump(level, list_skb, true);
1108 EXPORT_SYMBOL(skb_dump);
1111 * skb_tx_error - report an sk_buff xmit error
1112 * @skb: buffer that triggered an error
1114 * Report xmit error if a device callback is tracking this skb.
1115 * skb must be freed afterwards.
1117 void skb_tx_error(struct sk_buff *skb)
1120 skb_zcopy_downgrade_managed(skb);
1121 skb_zcopy_clear(skb, true);
1124 EXPORT_SYMBOL(skb_tx_error);
1126 #ifdef CONFIG_TRACEPOINTS
1128 * consume_skb - free an skbuff
1129 * @skb: buffer to free
1131 * Drop a ref to the buffer and free it if the usage count has hit zero
1132 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1133 * is being dropped after a failure and notes that
1135 void consume_skb(struct sk_buff *skb)
1137 if (!skb_unref(skb))
1140 trace_consume_skb(skb);
1143 EXPORT_SYMBOL(consume_skb);
1147 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1148 * @skb: buffer to free
1150 * Alike consume_skb(), but this variant assumes that this is the last
1151 * skb reference and all the head states have been already dropped
1153 void __consume_stateless_skb(struct sk_buff *skb)
1155 trace_consume_skb(skb);
1156 skb_release_data(skb, SKB_CONSUMED);
1160 static void napi_skb_cache_put(struct sk_buff *skb)
1162 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1165 kasan_poison_object_data(skbuff_head_cache, skb);
1166 nc->skb_cache[nc->skb_count++] = skb;
1168 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1169 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1170 kasan_unpoison_object_data(skbuff_head_cache,
1173 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
1174 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1175 nc->skb_count = NAPI_SKB_CACHE_HALF;
1179 void __kfree_skb_defer(struct sk_buff *skb)
1181 skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
1182 napi_skb_cache_put(skb);
1185 void napi_skb_free_stolen_head(struct sk_buff *skb)
1187 if (unlikely(skb->slow_gro)) {
1194 napi_skb_cache_put(skb);
1197 void napi_consume_skb(struct sk_buff *skb, int budget)
1199 /* Zero budget indicate non-NAPI context called us, like netpoll */
1200 if (unlikely(!budget)) {
1201 dev_consume_skb_any(skb);
1205 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1207 if (!skb_unref(skb))
1210 /* if reaching here SKB is ready to free */
1211 trace_consume_skb(skb);
1213 /* if SKB is a clone, don't handle this case */
1214 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1219 skb_release_all(skb, SKB_CONSUMED);
1220 napi_skb_cache_put(skb);
1222 EXPORT_SYMBOL(napi_consume_skb);
1224 /* Make sure a field is contained by headers group */
1225 #define CHECK_SKB_FIELD(field) \
1226 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1227 offsetof(struct sk_buff, headers.field)); \
1229 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1231 new->tstamp = old->tstamp;
1232 /* We do not copy old->sk */
1233 new->dev = old->dev;
1234 memcpy(new->cb, old->cb, sizeof(old->cb));
1235 skb_dst_copy(new, old);
1236 __skb_ext_copy(new, old);
1237 __nf_copy(new, old, false);
1239 /* Note : this field could be in the headers group.
1240 * It is not yet because we do not want to have a 16 bit hole
1242 new->queue_mapping = old->queue_mapping;
1244 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1245 CHECK_SKB_FIELD(protocol);
1246 CHECK_SKB_FIELD(csum);
1247 CHECK_SKB_FIELD(hash);
1248 CHECK_SKB_FIELD(priority);
1249 CHECK_SKB_FIELD(skb_iif);
1250 CHECK_SKB_FIELD(vlan_proto);
1251 CHECK_SKB_FIELD(vlan_tci);
1252 CHECK_SKB_FIELD(transport_header);
1253 CHECK_SKB_FIELD(network_header);
1254 CHECK_SKB_FIELD(mac_header);
1255 CHECK_SKB_FIELD(inner_protocol);
1256 CHECK_SKB_FIELD(inner_transport_header);
1257 CHECK_SKB_FIELD(inner_network_header);
1258 CHECK_SKB_FIELD(inner_mac_header);
1259 CHECK_SKB_FIELD(mark);
1260 #ifdef CONFIG_NETWORK_SECMARK
1261 CHECK_SKB_FIELD(secmark);
1263 #ifdef CONFIG_NET_RX_BUSY_POLL
1264 CHECK_SKB_FIELD(napi_id);
1266 CHECK_SKB_FIELD(alloc_cpu);
1268 CHECK_SKB_FIELD(sender_cpu);
1270 #ifdef CONFIG_NET_SCHED
1271 CHECK_SKB_FIELD(tc_index);
1277 * You should not add any new code to this function. Add it to
1278 * __copy_skb_header above instead.
1280 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1282 #define C(x) n->x = skb->x
1284 n->next = n->prev = NULL;
1286 __copy_skb_header(n, skb);
1291 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1297 n->destructor = NULL;
1304 refcount_set(&n->users, 1);
1306 atomic_inc(&(skb_shinfo(skb)->dataref));
1314 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1315 * @first: first sk_buff of the msg
1317 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1321 n = alloc_skb(0, GFP_ATOMIC);
1325 n->len = first->len;
1326 n->data_len = first->len;
1327 n->truesize = first->truesize;
1329 skb_shinfo(n)->frag_list = first;
1331 __copy_skb_header(n, first);
1332 n->destructor = NULL;
1336 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1339 * skb_morph - morph one skb into another
1340 * @dst: the skb to receive the contents
1341 * @src: the skb to supply the contents
1343 * This is identical to skb_clone except that the target skb is
1344 * supplied by the user.
1346 * The target skb is returned upon exit.
1348 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1350 skb_release_all(dst, SKB_CONSUMED);
1351 return __skb_clone(dst, src);
1353 EXPORT_SYMBOL_GPL(skb_morph);
1355 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1357 unsigned long max_pg, num_pg, new_pg, old_pg;
1358 struct user_struct *user;
1360 if (capable(CAP_IPC_LOCK) || !size)
1363 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1364 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1365 user = mmp->user ? : current_user();
1367 old_pg = atomic_long_read(&user->locked_vm);
1369 new_pg = old_pg + num_pg;
1370 if (new_pg > max_pg)
1372 } while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1375 mmp->user = get_uid(user);
1376 mmp->num_pg = num_pg;
1378 mmp->num_pg += num_pg;
1383 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1385 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1388 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1389 free_uid(mmp->user);
1392 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1394 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1396 struct ubuf_info_msgzc *uarg;
1397 struct sk_buff *skb;
1399 WARN_ON_ONCE(!in_task());
1401 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1405 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1406 uarg = (void *)skb->cb;
1407 uarg->mmp.user = NULL;
1409 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1414 uarg->ubuf.callback = msg_zerocopy_callback;
1415 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1417 uarg->bytelen = size;
1419 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1420 refcount_set(&uarg->ubuf.refcnt, 1);
1426 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1428 return container_of((void *)uarg, struct sk_buff, cb);
1431 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1432 struct ubuf_info *uarg)
1435 struct ubuf_info_msgzc *uarg_zc;
1436 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1439 /* there might be non MSG_ZEROCOPY users */
1440 if (uarg->callback != msg_zerocopy_callback)
1443 /* realloc only when socket is locked (TCP, UDP cork),
1444 * so uarg->len and sk_zckey access is serialized
1446 if (!sock_owned_by_user(sk)) {
1451 uarg_zc = uarg_to_msgzc(uarg);
1452 bytelen = uarg_zc->bytelen + size;
1453 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1454 /* TCP can create new skb to attach new uarg */
1455 if (sk->sk_type == SOCK_STREAM)
1460 next = (u32)atomic_read(&sk->sk_zckey);
1461 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1462 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1465 uarg_zc->bytelen = bytelen;
1466 atomic_set(&sk->sk_zckey, ++next);
1468 /* no extra ref when appending to datagram (MSG_MORE) */
1469 if (sk->sk_type == SOCK_STREAM)
1470 net_zcopy_get(uarg);
1477 return msg_zerocopy_alloc(sk, size);
1479 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1481 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1483 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1487 old_lo = serr->ee.ee_info;
1488 old_hi = serr->ee.ee_data;
1489 sum_len = old_hi - old_lo + 1ULL + len;
1491 if (sum_len >= (1ULL << 32))
1494 if (lo != old_hi + 1)
1497 serr->ee.ee_data += len;
1501 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1503 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1504 struct sock_exterr_skb *serr;
1505 struct sock *sk = skb->sk;
1506 struct sk_buff_head *q;
1507 unsigned long flags;
1512 mm_unaccount_pinned_pages(&uarg->mmp);
1514 /* if !len, there was only 1 call, and it was aborted
1515 * so do not queue a completion notification
1517 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1522 hi = uarg->id + len - 1;
1523 is_zerocopy = uarg->zerocopy;
1525 serr = SKB_EXT_ERR(skb);
1526 memset(serr, 0, sizeof(*serr));
1527 serr->ee.ee_errno = 0;
1528 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1529 serr->ee.ee_data = hi;
1530 serr->ee.ee_info = lo;
1532 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1534 q = &sk->sk_error_queue;
1535 spin_lock_irqsave(&q->lock, flags);
1536 tail = skb_peek_tail(q);
1537 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1538 !skb_zerocopy_notify_extend(tail, lo, len)) {
1539 __skb_queue_tail(q, skb);
1542 spin_unlock_irqrestore(&q->lock, flags);
1544 sk_error_report(sk);
1551 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1554 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1556 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1558 if (refcount_dec_and_test(&uarg->refcnt))
1559 __msg_zerocopy_callback(uarg_zc);
1561 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1563 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1565 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1567 atomic_dec(&sk->sk_zckey);
1568 uarg_to_msgzc(uarg)->len--;
1571 msg_zerocopy_callback(NULL, uarg, true);
1573 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1575 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1576 struct msghdr *msg, int len,
1577 struct ubuf_info *uarg)
1579 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1580 int err, orig_len = skb->len;
1582 /* An skb can only point to one uarg. This edge case happens when
1583 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1585 if (orig_uarg && uarg != orig_uarg)
1588 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1589 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1590 struct sock *save_sk = skb->sk;
1592 /* Streams do not free skb on error. Reset to prev state. */
1593 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1595 ___pskb_trim(skb, orig_len);
1600 skb_zcopy_set(skb, uarg, NULL);
1601 return skb->len - orig_len;
1603 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1605 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1609 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1610 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1611 skb_frag_ref(skb, i);
1613 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1615 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1618 if (skb_zcopy(orig)) {
1619 if (skb_zcopy(nskb)) {
1620 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1625 if (skb_uarg(nskb) == skb_uarg(orig))
1627 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1630 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1636 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1637 * @skb: the skb to modify
1638 * @gfp_mask: allocation priority
1640 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1641 * It will copy all frags into kernel and drop the reference
1642 * to userspace pages.
1644 * If this function is called from an interrupt gfp_mask() must be
1647 * Returns 0 on success or a negative error code on failure
1648 * to allocate kernel memory to copy to.
1650 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1652 int num_frags = skb_shinfo(skb)->nr_frags;
1653 struct page *page, *head = NULL;
1657 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1663 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1664 for (i = 0; i < new_frags; i++) {
1665 page = alloc_page(gfp_mask);
1668 struct page *next = (struct page *)page_private(head);
1674 set_page_private(page, (unsigned long)head);
1680 for (i = 0; i < num_frags; i++) {
1681 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1682 u32 p_off, p_len, copied;
1686 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1687 p, p_off, p_len, copied) {
1689 vaddr = kmap_atomic(p);
1691 while (done < p_len) {
1692 if (d_off == PAGE_SIZE) {
1694 page = (struct page *)page_private(page);
1696 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1697 memcpy(page_address(page) + d_off,
1698 vaddr + p_off + done, copy);
1702 kunmap_atomic(vaddr);
1706 /* skb frags release userspace buffers */
1707 for (i = 0; i < num_frags; i++)
1708 skb_frag_unref(skb, i);
1710 /* skb frags point to kernel buffers */
1711 for (i = 0; i < new_frags - 1; i++) {
1712 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1713 head = (struct page *)page_private(head);
1715 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1716 skb_shinfo(skb)->nr_frags = new_frags;
1719 skb_zcopy_clear(skb, false);
1722 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1725 * skb_clone - duplicate an sk_buff
1726 * @skb: buffer to clone
1727 * @gfp_mask: allocation priority
1729 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1730 * copies share the same packet data but not structure. The new
1731 * buffer has a reference count of 1. If the allocation fails the
1732 * function returns %NULL otherwise the new buffer is returned.
1734 * If this function is called from an interrupt gfp_mask() must be
1738 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1740 struct sk_buff_fclones *fclones = container_of(skb,
1741 struct sk_buff_fclones,
1745 if (skb_orphan_frags(skb, gfp_mask))
1748 if (skb->fclone == SKB_FCLONE_ORIG &&
1749 refcount_read(&fclones->fclone_ref) == 1) {
1751 refcount_set(&fclones->fclone_ref, 2);
1752 n->fclone = SKB_FCLONE_CLONE;
1754 if (skb_pfmemalloc(skb))
1755 gfp_mask |= __GFP_MEMALLOC;
1757 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1761 n->fclone = SKB_FCLONE_UNAVAILABLE;
1764 return __skb_clone(n, skb);
1766 EXPORT_SYMBOL(skb_clone);
1768 void skb_headers_offset_update(struct sk_buff *skb, int off)
1770 /* Only adjust this if it actually is csum_start rather than csum */
1771 if (skb->ip_summed == CHECKSUM_PARTIAL)
1772 skb->csum_start += off;
1773 /* {transport,network,mac}_header and tail are relative to skb->head */
1774 skb->transport_header += off;
1775 skb->network_header += off;
1776 if (skb_mac_header_was_set(skb))
1777 skb->mac_header += off;
1778 skb->inner_transport_header += off;
1779 skb->inner_network_header += off;
1780 skb->inner_mac_header += off;
1782 EXPORT_SYMBOL(skb_headers_offset_update);
1784 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1786 __copy_skb_header(new, old);
1788 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1789 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1790 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1792 EXPORT_SYMBOL(skb_copy_header);
1794 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1796 if (skb_pfmemalloc(skb))
1797 return SKB_ALLOC_RX;
1802 * skb_copy - create private copy of an sk_buff
1803 * @skb: buffer to copy
1804 * @gfp_mask: allocation priority
1806 * Make a copy of both an &sk_buff and its data. This is used when the
1807 * caller wishes to modify the data and needs a private copy of the
1808 * data to alter. Returns %NULL on failure or the pointer to the buffer
1809 * on success. The returned buffer has a reference count of 1.
1811 * As by-product this function converts non-linear &sk_buff to linear
1812 * one, so that &sk_buff becomes completely private and caller is allowed
1813 * to modify all the data of returned buffer. This means that this
1814 * function is not recommended for use in circumstances when only
1815 * header is going to be modified. Use pskb_copy() instead.
1818 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1820 int headerlen = skb_headroom(skb);
1821 unsigned int size = skb_end_offset(skb) + skb->data_len;
1822 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1823 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1828 /* Set the data pointer */
1829 skb_reserve(n, headerlen);
1830 /* Set the tail pointer and length */
1831 skb_put(n, skb->len);
1833 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1835 skb_copy_header(n, skb);
1838 EXPORT_SYMBOL(skb_copy);
1841 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1842 * @skb: buffer to copy
1843 * @headroom: headroom of new skb
1844 * @gfp_mask: allocation priority
1845 * @fclone: if true allocate the copy of the skb from the fclone
1846 * cache instead of the head cache; it is recommended to set this
1847 * to true for the cases where the copy will likely be cloned
1849 * Make a copy of both an &sk_buff and part of its data, located
1850 * in header. Fragmented data remain shared. This is used when
1851 * the caller wishes to modify only header of &sk_buff and needs
1852 * private copy of the header to alter. Returns %NULL on failure
1853 * or the pointer to the buffer on success.
1854 * The returned buffer has a reference count of 1.
1857 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1858 gfp_t gfp_mask, bool fclone)
1860 unsigned int size = skb_headlen(skb) + headroom;
1861 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1862 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1867 /* Set the data pointer */
1868 skb_reserve(n, headroom);
1869 /* Set the tail pointer and length */
1870 skb_put(n, skb_headlen(skb));
1871 /* Copy the bytes */
1872 skb_copy_from_linear_data(skb, n->data, n->len);
1874 n->truesize += skb->data_len;
1875 n->data_len = skb->data_len;
1878 if (skb_shinfo(skb)->nr_frags) {
1881 if (skb_orphan_frags(skb, gfp_mask) ||
1882 skb_zerocopy_clone(n, skb, gfp_mask)) {
1887 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1888 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1889 skb_frag_ref(skb, i);
1891 skb_shinfo(n)->nr_frags = i;
1894 if (skb_has_frag_list(skb)) {
1895 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1896 skb_clone_fraglist(n);
1899 skb_copy_header(n, skb);
1903 EXPORT_SYMBOL(__pskb_copy_fclone);
1906 * pskb_expand_head - reallocate header of &sk_buff
1907 * @skb: buffer to reallocate
1908 * @nhead: room to add at head
1909 * @ntail: room to add at tail
1910 * @gfp_mask: allocation priority
1912 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1913 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1914 * reference count of 1. Returns zero in the case of success or error,
1915 * if expansion failed. In the last case, &sk_buff is not changed.
1917 * All the pointers pointing into skb header may change and must be
1918 * reloaded after call to this function.
1921 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1924 unsigned int osize = skb_end_offset(skb);
1925 unsigned int size = osize + nhead + ntail;
1932 BUG_ON(skb_shared(skb));
1934 skb_zcopy_downgrade_managed(skb);
1936 if (skb_pfmemalloc(skb))
1937 gfp_mask |= __GFP_MEMALLOC;
1939 size = SKB_DATA_ALIGN(size);
1940 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1941 size = kmalloc_size_roundup(size);
1942 data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
1945 size = SKB_WITH_OVERHEAD(size);
1947 /* Copy only real data... and, alas, header. This should be
1948 * optimized for the cases when header is void.
1950 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1952 memcpy((struct skb_shared_info *)(data + size),
1954 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1957 * if shinfo is shared we must drop the old head gracefully, but if it
1958 * is not we can just drop the old head and let the existing refcount
1959 * be since all we did is relocate the values
1961 if (skb_cloned(skb)) {
1962 if (skb_orphan_frags(skb, gfp_mask))
1965 refcount_inc(&skb_uarg(skb)->refcnt);
1966 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1967 skb_frag_ref(skb, i);
1969 if (skb_has_frag_list(skb))
1970 skb_clone_fraglist(skb);
1972 skb_release_data(skb, SKB_CONSUMED);
1976 off = (data + nhead) - skb->head;
1982 skb_set_end_offset(skb, size);
1983 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1987 skb_headers_offset_update(skb, nhead);
1991 atomic_set(&skb_shinfo(skb)->dataref, 1);
1993 skb_metadata_clear(skb);
1995 /* It is not generally safe to change skb->truesize.
1996 * For the moment, we really care of rx path, or
1997 * when skb is orphaned (not attached to a socket).
1999 if (!skb->sk || skb->destructor == sock_edemux)
2000 skb->truesize += size - osize;
2009 EXPORT_SYMBOL(pskb_expand_head);
2011 /* Make private copy of skb with writable head and some headroom */
2013 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
2015 struct sk_buff *skb2;
2016 int delta = headroom - skb_headroom(skb);
2019 skb2 = pskb_copy(skb, GFP_ATOMIC);
2021 skb2 = skb_clone(skb, GFP_ATOMIC);
2022 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
2030 EXPORT_SYMBOL(skb_realloc_headroom);
2032 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
2034 unsigned int saved_end_offset, saved_truesize;
2035 struct skb_shared_info *shinfo;
2038 saved_end_offset = skb_end_offset(skb);
2039 saved_truesize = skb->truesize;
2041 res = pskb_expand_head(skb, 0, 0, pri);
2045 skb->truesize = saved_truesize;
2047 if (likely(skb_end_offset(skb) == saved_end_offset))
2050 shinfo = skb_shinfo(skb);
2052 /* We are about to change back skb->end,
2053 * we need to move skb_shinfo() to its new location.
2055 memmove(skb->head + saved_end_offset,
2057 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
2059 skb_set_end_offset(skb, saved_end_offset);
2065 * skb_expand_head - reallocate header of &sk_buff
2066 * @skb: buffer to reallocate
2067 * @headroom: needed headroom
2069 * Unlike skb_realloc_headroom, this one does not allocate a new skb
2070 * if possible; copies skb->sk to new skb as needed
2071 * and frees original skb in case of failures.
2073 * It expect increased headroom and generates warning otherwise.
2076 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2078 int delta = headroom - skb_headroom(skb);
2079 int osize = skb_end_offset(skb);
2080 struct sock *sk = skb->sk;
2082 if (WARN_ONCE(delta <= 0,
2083 "%s is expecting an increase in the headroom", __func__))
2086 delta = SKB_DATA_ALIGN(delta);
2087 /* pskb_expand_head() might crash, if skb is shared. */
2088 if (skb_shared(skb) || !is_skb_wmem(skb)) {
2089 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2091 if (unlikely(!nskb))
2095 skb_set_owner_w(nskb, sk);
2099 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2102 if (sk && is_skb_wmem(skb)) {
2103 delta = skb_end_offset(skb) - osize;
2104 refcount_add(delta, &sk->sk_wmem_alloc);
2105 skb->truesize += delta;
2113 EXPORT_SYMBOL(skb_expand_head);
2116 * skb_copy_expand - copy and expand sk_buff
2117 * @skb: buffer to copy
2118 * @newheadroom: new free bytes at head
2119 * @newtailroom: new free bytes at tail
2120 * @gfp_mask: allocation priority
2122 * Make a copy of both an &sk_buff and its data and while doing so
2123 * allocate additional space.
2125 * This is used when the caller wishes to modify the data and needs a
2126 * private copy of the data to alter as well as more space for new fields.
2127 * Returns %NULL on failure or the pointer to the buffer
2128 * on success. The returned buffer has a reference count of 1.
2130 * You must pass %GFP_ATOMIC as the allocation priority if this function
2131 * is called from an interrupt.
2133 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2134 int newheadroom, int newtailroom,
2138 * Allocate the copy buffer
2140 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2141 gfp_mask, skb_alloc_rx_flag(skb),
2143 int oldheadroom = skb_headroom(skb);
2144 int head_copy_len, head_copy_off;
2149 skb_reserve(n, newheadroom);
2151 /* Set the tail pointer and length */
2152 skb_put(n, skb->len);
2154 head_copy_len = oldheadroom;
2156 if (newheadroom <= head_copy_len)
2157 head_copy_len = newheadroom;
2159 head_copy_off = newheadroom - head_copy_len;
2161 /* Copy the linear header and data. */
2162 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2163 skb->len + head_copy_len));
2165 skb_copy_header(n, skb);
2167 skb_headers_offset_update(n, newheadroom - oldheadroom);
2171 EXPORT_SYMBOL(skb_copy_expand);
2174 * __skb_pad - zero pad the tail of an skb
2175 * @skb: buffer to pad
2176 * @pad: space to pad
2177 * @free_on_error: free buffer on error
2179 * Ensure that a buffer is followed by a padding area that is zero
2180 * filled. Used by network drivers which may DMA or transfer data
2181 * beyond the buffer end onto the wire.
2183 * May return error in out of memory cases. The skb is freed on error
2184 * if @free_on_error is true.
2187 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2192 /* If the skbuff is non linear tailroom is always zero.. */
2193 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2194 memset(skb->data+skb->len, 0, pad);
2198 ntail = skb->data_len + pad - (skb->end - skb->tail);
2199 if (likely(skb_cloned(skb) || ntail > 0)) {
2200 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2205 /* FIXME: The use of this function with non-linear skb's really needs
2208 err = skb_linearize(skb);
2212 memset(skb->data + skb->len, 0, pad);
2220 EXPORT_SYMBOL(__skb_pad);
2223 * pskb_put - add data to the tail of a potentially fragmented buffer
2224 * @skb: start of the buffer to use
2225 * @tail: tail fragment of the buffer to use
2226 * @len: amount of data to add
2228 * This function extends the used data area of the potentially
2229 * fragmented buffer. @tail must be the last fragment of @skb -- or
2230 * @skb itself. If this would exceed the total buffer size the kernel
2231 * will panic. A pointer to the first byte of the extra data is
2235 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2238 skb->data_len += len;
2241 return skb_put(tail, len);
2243 EXPORT_SYMBOL_GPL(pskb_put);
2246 * skb_put - add data to a buffer
2247 * @skb: buffer to use
2248 * @len: amount of data to add
2250 * This function extends the used data area of the buffer. If this would
2251 * exceed the total buffer size the kernel will panic. A pointer to the
2252 * first byte of the extra data is returned.
2254 void *skb_put(struct sk_buff *skb, unsigned int len)
2256 void *tmp = skb_tail_pointer(skb);
2257 SKB_LINEAR_ASSERT(skb);
2260 if (unlikely(skb->tail > skb->end))
2261 skb_over_panic(skb, len, __builtin_return_address(0));
2264 EXPORT_SYMBOL(skb_put);
2267 * skb_push - add data to the start of a buffer
2268 * @skb: buffer to use
2269 * @len: amount of data to add
2271 * This function extends the used data area of the buffer at the buffer
2272 * start. If this would exceed the total buffer headroom the kernel will
2273 * panic. A pointer to the first byte of the extra data is returned.
2275 void *skb_push(struct sk_buff *skb, unsigned int len)
2279 if (unlikely(skb->data < skb->head))
2280 skb_under_panic(skb, len, __builtin_return_address(0));
2283 EXPORT_SYMBOL(skb_push);
2286 * skb_pull - remove data from the start of a buffer
2287 * @skb: buffer to use
2288 * @len: amount of data to remove
2290 * This function removes data from the start of a buffer, returning
2291 * the memory to the headroom. A pointer to the next data in the buffer
2292 * is returned. Once the data has been pulled future pushes will overwrite
2295 void *skb_pull(struct sk_buff *skb, unsigned int len)
2297 return skb_pull_inline(skb, len);
2299 EXPORT_SYMBOL(skb_pull);
2302 * skb_pull_data - remove data from the start of a buffer returning its
2303 * original position.
2304 * @skb: buffer to use
2305 * @len: amount of data to remove
2307 * This function removes data from the start of a buffer, returning
2308 * the memory to the headroom. A pointer to the original data in the buffer
2309 * is returned after checking if there is enough data to pull. Once the
2310 * data has been pulled future pushes will overwrite the old data.
2312 void *skb_pull_data(struct sk_buff *skb, size_t len)
2314 void *data = skb->data;
2323 EXPORT_SYMBOL(skb_pull_data);
2326 * skb_trim - remove end from a buffer
2327 * @skb: buffer to alter
2330 * Cut the length of a buffer down by removing data from the tail. If
2331 * the buffer is already under the length specified it is not modified.
2332 * The skb must be linear.
2334 void skb_trim(struct sk_buff *skb, unsigned int len)
2337 __skb_trim(skb, len);
2339 EXPORT_SYMBOL(skb_trim);
2341 /* Trims skb to length len. It can change skb pointers.
2344 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2346 struct sk_buff **fragp;
2347 struct sk_buff *frag;
2348 int offset = skb_headlen(skb);
2349 int nfrags = skb_shinfo(skb)->nr_frags;
2353 if (skb_cloned(skb) &&
2354 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2361 for (; i < nfrags; i++) {
2362 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2369 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2372 skb_shinfo(skb)->nr_frags = i;
2374 for (; i < nfrags; i++)
2375 skb_frag_unref(skb, i);
2377 if (skb_has_frag_list(skb))
2378 skb_drop_fraglist(skb);
2382 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2383 fragp = &frag->next) {
2384 int end = offset + frag->len;
2386 if (skb_shared(frag)) {
2387 struct sk_buff *nfrag;
2389 nfrag = skb_clone(frag, GFP_ATOMIC);
2390 if (unlikely(!nfrag))
2393 nfrag->next = frag->next;
2405 unlikely((err = pskb_trim(frag, len - offset))))
2409 skb_drop_list(&frag->next);
2414 if (len > skb_headlen(skb)) {
2415 skb->data_len -= skb->len - len;
2420 skb_set_tail_pointer(skb, len);
2423 if (!skb->sk || skb->destructor == sock_edemux)
2427 EXPORT_SYMBOL(___pskb_trim);
2429 /* Note : use pskb_trim_rcsum() instead of calling this directly
2431 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2433 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2434 int delta = skb->len - len;
2436 skb->csum = csum_block_sub(skb->csum,
2437 skb_checksum(skb, len, delta, 0),
2439 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2440 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2441 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2443 if (offset + sizeof(__sum16) > hdlen)
2446 return __pskb_trim(skb, len);
2448 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2451 * __pskb_pull_tail - advance tail of skb header
2452 * @skb: buffer to reallocate
2453 * @delta: number of bytes to advance tail
2455 * The function makes a sense only on a fragmented &sk_buff,
2456 * it expands header moving its tail forward and copying necessary
2457 * data from fragmented part.
2459 * &sk_buff MUST have reference count of 1.
2461 * Returns %NULL (and &sk_buff does not change) if pull failed
2462 * or value of new tail of skb in the case of success.
2464 * All the pointers pointing into skb header may change and must be
2465 * reloaded after call to this function.
2468 /* Moves tail of skb head forward, copying data from fragmented part,
2469 * when it is necessary.
2470 * 1. It may fail due to malloc failure.
2471 * 2. It may change skb pointers.
2473 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2475 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2477 /* If skb has not enough free space at tail, get new one
2478 * plus 128 bytes for future expansions. If we have enough
2479 * room at tail, reallocate without expansion only if skb is cloned.
2481 int i, k, eat = (skb->tail + delta) - skb->end;
2483 if (eat > 0 || skb_cloned(skb)) {
2484 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2489 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2490 skb_tail_pointer(skb), delta));
2492 /* Optimization: no fragments, no reasons to preestimate
2493 * size of pulled pages. Superb.
2495 if (!skb_has_frag_list(skb))
2498 /* Estimate size of pulled pages. */
2500 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2501 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2508 /* If we need update frag list, we are in troubles.
2509 * Certainly, it is possible to add an offset to skb data,
2510 * but taking into account that pulling is expected to
2511 * be very rare operation, it is worth to fight against
2512 * further bloating skb head and crucify ourselves here instead.
2513 * Pure masohism, indeed. 8)8)
2516 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2517 struct sk_buff *clone = NULL;
2518 struct sk_buff *insp = NULL;
2521 if (list->len <= eat) {
2522 /* Eaten as whole. */
2527 /* Eaten partially. */
2528 if (skb_is_gso(skb) && !list->head_frag &&
2530 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2532 if (skb_shared(list)) {
2533 /* Sucks! We need to fork list. :-( */
2534 clone = skb_clone(list, GFP_ATOMIC);
2540 /* This may be pulled without
2544 if (!pskb_pull(list, eat)) {
2552 /* Free pulled out fragments. */
2553 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2554 skb_shinfo(skb)->frag_list = list->next;
2557 /* And insert new clone at head. */
2560 skb_shinfo(skb)->frag_list = clone;
2563 /* Success! Now we may commit changes to skb data. */
2568 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2569 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2572 skb_frag_unref(skb, i);
2575 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2577 *frag = skb_shinfo(skb)->frags[i];
2579 skb_frag_off_add(frag, eat);
2580 skb_frag_size_sub(frag, eat);
2588 skb_shinfo(skb)->nr_frags = k;
2592 skb->data_len -= delta;
2595 skb_zcopy_clear(skb, false);
2597 return skb_tail_pointer(skb);
2599 EXPORT_SYMBOL(__pskb_pull_tail);
2602 * skb_copy_bits - copy bits from skb to kernel buffer
2604 * @offset: offset in source
2605 * @to: destination buffer
2606 * @len: number of bytes to copy
2608 * Copy the specified number of bytes from the source skb to the
2609 * destination buffer.
2612 * If its prototype is ever changed,
2613 * check arch/{*}/net/{*}.S files,
2614 * since it is called from BPF assembly code.
2616 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2618 int start = skb_headlen(skb);
2619 struct sk_buff *frag_iter;
2622 if (offset > (int)skb->len - len)
2626 if ((copy = start - offset) > 0) {
2629 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2630 if ((len -= copy) == 0)
2636 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2638 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2640 WARN_ON(start > offset + len);
2642 end = start + skb_frag_size(f);
2643 if ((copy = end - offset) > 0) {
2644 u32 p_off, p_len, copied;
2651 skb_frag_foreach_page(f,
2652 skb_frag_off(f) + offset - start,
2653 copy, p, p_off, p_len, copied) {
2654 vaddr = kmap_atomic(p);
2655 memcpy(to + copied, vaddr + p_off, p_len);
2656 kunmap_atomic(vaddr);
2659 if ((len -= copy) == 0)
2667 skb_walk_frags(skb, frag_iter) {
2670 WARN_ON(start > offset + len);
2672 end = start + frag_iter->len;
2673 if ((copy = end - offset) > 0) {
2676 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2678 if ((len -= copy) == 0)
2692 EXPORT_SYMBOL(skb_copy_bits);
2695 * Callback from splice_to_pipe(), if we need to release some pages
2696 * at the end of the spd in case we error'ed out in filling the pipe.
2698 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2700 put_page(spd->pages[i]);
2703 static struct page *linear_to_page(struct page *page, unsigned int *len,
2704 unsigned int *offset,
2707 struct page_frag *pfrag = sk_page_frag(sk);
2709 if (!sk_page_frag_refill(sk, pfrag))
2712 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2714 memcpy(page_address(pfrag->page) + pfrag->offset,
2715 page_address(page) + *offset, *len);
2716 *offset = pfrag->offset;
2717 pfrag->offset += *len;
2722 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2724 unsigned int offset)
2726 return spd->nr_pages &&
2727 spd->pages[spd->nr_pages - 1] == page &&
2728 (spd->partial[spd->nr_pages - 1].offset +
2729 spd->partial[spd->nr_pages - 1].len == offset);
2733 * Fill page/offset/length into spd, if it can hold more pages.
2735 static bool spd_fill_page(struct splice_pipe_desc *spd,
2736 struct pipe_inode_info *pipe, struct page *page,
2737 unsigned int *len, unsigned int offset,
2741 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2745 page = linear_to_page(page, len, &offset, sk);
2749 if (spd_can_coalesce(spd, page, offset)) {
2750 spd->partial[spd->nr_pages - 1].len += *len;
2754 spd->pages[spd->nr_pages] = page;
2755 spd->partial[spd->nr_pages].len = *len;
2756 spd->partial[spd->nr_pages].offset = offset;
2762 static bool __splice_segment(struct page *page, unsigned int poff,
2763 unsigned int plen, unsigned int *off,
2765 struct splice_pipe_desc *spd, bool linear,
2767 struct pipe_inode_info *pipe)
2772 /* skip this segment if already processed */
2778 /* ignore any bits we already processed */
2784 unsigned int flen = min(*len, plen);
2786 if (spd_fill_page(spd, pipe, page, &flen, poff,
2792 } while (*len && plen);
2798 * Map linear and fragment data from the skb to spd. It reports true if the
2799 * pipe is full or if we already spliced the requested length.
2801 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2802 unsigned int *offset, unsigned int *len,
2803 struct splice_pipe_desc *spd, struct sock *sk)
2806 struct sk_buff *iter;
2808 /* map the linear part :
2809 * If skb->head_frag is set, this 'linear' part is backed by a
2810 * fragment, and if the head is not shared with any clones then
2811 * we can avoid a copy since we own the head portion of this page.
2813 if (__splice_segment(virt_to_page(skb->data),
2814 (unsigned long) skb->data & (PAGE_SIZE - 1),
2817 skb_head_is_locked(skb),
2822 * then map the fragments
2824 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2825 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2827 if (__splice_segment(skb_frag_page(f),
2828 skb_frag_off(f), skb_frag_size(f),
2829 offset, len, spd, false, sk, pipe))
2833 skb_walk_frags(skb, iter) {
2834 if (*offset >= iter->len) {
2835 *offset -= iter->len;
2838 /* __skb_splice_bits() only fails if the output has no room
2839 * left, so no point in going over the frag_list for the error
2842 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2850 * Map data from the skb to a pipe. Should handle both the linear part,
2851 * the fragments, and the frag list.
2853 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2854 struct pipe_inode_info *pipe, unsigned int tlen,
2857 struct partial_page partial[MAX_SKB_FRAGS];
2858 struct page *pages[MAX_SKB_FRAGS];
2859 struct splice_pipe_desc spd = {
2862 .nr_pages_max = MAX_SKB_FRAGS,
2863 .ops = &nosteal_pipe_buf_ops,
2864 .spd_release = sock_spd_release,
2868 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2871 ret = splice_to_pipe(pipe, &spd);
2875 EXPORT_SYMBOL_GPL(skb_splice_bits);
2877 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2878 struct kvec *vec, size_t num, size_t size)
2880 struct socket *sock = sk->sk_socket;
2884 return kernel_sendmsg(sock, msg, vec, num, size);
2887 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2888 size_t size, int flags)
2890 struct socket *sock = sk->sk_socket;
2894 return kernel_sendpage(sock, page, offset, size, flags);
2897 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2898 struct kvec *vec, size_t num, size_t size);
2899 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2900 size_t size, int flags);
2901 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2902 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2904 unsigned int orig_len = len;
2905 struct sk_buff *head = skb;
2906 unsigned short fragidx;
2911 /* Deal with head data */
2912 while (offset < skb_headlen(skb) && len) {
2916 slen = min_t(int, len, skb_headlen(skb) - offset);
2917 kv.iov_base = skb->data + offset;
2919 memset(&msg, 0, sizeof(msg));
2920 msg.msg_flags = MSG_DONTWAIT;
2922 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2923 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2931 /* All the data was skb head? */
2935 /* Make offset relative to start of frags */
2936 offset -= skb_headlen(skb);
2938 /* Find where we are in frag list */
2939 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2940 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2942 if (offset < skb_frag_size(frag))
2945 offset -= skb_frag_size(frag);
2948 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2949 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2951 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2954 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2955 sendpage_unlocked, sk,
2956 skb_frag_page(frag),
2957 skb_frag_off(frag) + offset,
2958 slen, MSG_DONTWAIT);
2971 /* Process any frag lists */
2974 if (skb_has_frag_list(skb)) {
2975 skb = skb_shinfo(skb)->frag_list;
2978 } else if (skb->next) {
2985 return orig_len - len;
2988 return orig_len == len ? ret : orig_len - len;
2991 /* Send skb data on a socket. Socket must be locked. */
2992 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2995 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2996 kernel_sendpage_locked);
2998 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
3000 /* Send skb data on a socket. Socket must be unlocked. */
3001 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
3003 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
3008 * skb_store_bits - store bits from kernel buffer to skb
3009 * @skb: destination buffer
3010 * @offset: offset in destination
3011 * @from: source buffer
3012 * @len: number of bytes to copy
3014 * Copy the specified number of bytes from the source buffer to the
3015 * destination skb. This function handles all the messy bits of
3016 * traversing fragment lists and such.
3019 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
3021 int start = skb_headlen(skb);
3022 struct sk_buff *frag_iter;
3025 if (offset > (int)skb->len - len)
3028 if ((copy = start - offset) > 0) {
3031 skb_copy_to_linear_data_offset(skb, offset, from, copy);
3032 if ((len -= copy) == 0)
3038 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3039 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3042 WARN_ON(start > offset + len);
3044 end = start + skb_frag_size(frag);
3045 if ((copy = end - offset) > 0) {
3046 u32 p_off, p_len, copied;
3053 skb_frag_foreach_page(frag,
3054 skb_frag_off(frag) + offset - start,
3055 copy, p, p_off, p_len, copied) {
3056 vaddr = kmap_atomic(p);
3057 memcpy(vaddr + p_off, from + copied, p_len);
3058 kunmap_atomic(vaddr);
3061 if ((len -= copy) == 0)
3069 skb_walk_frags(skb, frag_iter) {
3072 WARN_ON(start > offset + len);
3074 end = start + frag_iter->len;
3075 if ((copy = end - offset) > 0) {
3078 if (skb_store_bits(frag_iter, offset - start,
3081 if ((len -= copy) == 0)
3094 EXPORT_SYMBOL(skb_store_bits);
3096 /* Checksum skb data. */
3097 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
3098 __wsum csum, const struct skb_checksum_ops *ops)
3100 int start = skb_headlen(skb);
3101 int i, copy = start - offset;
3102 struct sk_buff *frag_iter;
3105 /* Checksum header. */
3109 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3110 skb->data + offset, copy, csum);
3111 if ((len -= copy) == 0)
3117 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3119 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3121 WARN_ON(start > offset + len);
3123 end = start + skb_frag_size(frag);
3124 if ((copy = end - offset) > 0) {
3125 u32 p_off, p_len, copied;
3133 skb_frag_foreach_page(frag,
3134 skb_frag_off(frag) + offset - start,
3135 copy, p, p_off, p_len, copied) {
3136 vaddr = kmap_atomic(p);
3137 csum2 = INDIRECT_CALL_1(ops->update,
3139 vaddr + p_off, p_len, 0);
3140 kunmap_atomic(vaddr);
3141 csum = INDIRECT_CALL_1(ops->combine,
3142 csum_block_add_ext, csum,
3154 skb_walk_frags(skb, frag_iter) {
3157 WARN_ON(start > offset + len);
3159 end = start + frag_iter->len;
3160 if ((copy = end - offset) > 0) {
3164 csum2 = __skb_checksum(frag_iter, offset - start,
3166 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3167 csum, csum2, pos, copy);
3168 if ((len -= copy) == 0)
3179 EXPORT_SYMBOL(__skb_checksum);
3181 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3182 int len, __wsum csum)
3184 const struct skb_checksum_ops ops = {
3185 .update = csum_partial_ext,
3186 .combine = csum_block_add_ext,
3189 return __skb_checksum(skb, offset, len, csum, &ops);
3191 EXPORT_SYMBOL(skb_checksum);
3193 /* Both of above in one bottle. */
3195 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3198 int start = skb_headlen(skb);
3199 int i, copy = start - offset;
3200 struct sk_buff *frag_iter;
3208 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3210 if ((len -= copy) == 0)
3217 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3220 WARN_ON(start > offset + len);
3222 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3223 if ((copy = end - offset) > 0) {
3224 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3225 u32 p_off, p_len, copied;
3233 skb_frag_foreach_page(frag,
3234 skb_frag_off(frag) + offset - start,
3235 copy, p, p_off, p_len, copied) {
3236 vaddr = kmap_atomic(p);
3237 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3240 kunmap_atomic(vaddr);
3241 csum = csum_block_add(csum, csum2, pos);
3253 skb_walk_frags(skb, frag_iter) {
3257 WARN_ON(start > offset + len);
3259 end = start + frag_iter->len;
3260 if ((copy = end - offset) > 0) {
3263 csum2 = skb_copy_and_csum_bits(frag_iter,
3266 csum = csum_block_add(csum, csum2, pos);
3267 if ((len -= copy) == 0)
3278 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3280 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3284 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3285 /* See comments in __skb_checksum_complete(). */
3287 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3288 !skb->csum_complete_sw)
3289 netdev_rx_csum_fault(skb->dev, skb);
3291 if (!skb_shared(skb))
3292 skb->csum_valid = !sum;
3295 EXPORT_SYMBOL(__skb_checksum_complete_head);
3297 /* This function assumes skb->csum already holds pseudo header's checksum,
3298 * which has been changed from the hardware checksum, for example, by
3299 * __skb_checksum_validate_complete(). And, the original skb->csum must
3300 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3302 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3303 * zero. The new checksum is stored back into skb->csum unless the skb is
3306 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3311 csum = skb_checksum(skb, 0, skb->len, 0);
3313 sum = csum_fold(csum_add(skb->csum, csum));
3314 /* This check is inverted, because we already knew the hardware
3315 * checksum is invalid before calling this function. So, if the
3316 * re-computed checksum is valid instead, then we have a mismatch
3317 * between the original skb->csum and skb_checksum(). This means either
3318 * the original hardware checksum is incorrect or we screw up skb->csum
3319 * when moving skb->data around.
3322 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3323 !skb->csum_complete_sw)
3324 netdev_rx_csum_fault(skb->dev, skb);
3327 if (!skb_shared(skb)) {
3328 /* Save full packet checksum */
3330 skb->ip_summed = CHECKSUM_COMPLETE;
3331 skb->csum_complete_sw = 1;
3332 skb->csum_valid = !sum;
3337 EXPORT_SYMBOL(__skb_checksum_complete);
3339 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3341 net_warn_ratelimited(
3342 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3347 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3348 int offset, int len)
3350 net_warn_ratelimited(
3351 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3356 static const struct skb_checksum_ops default_crc32c_ops = {
3357 .update = warn_crc32c_csum_update,
3358 .combine = warn_crc32c_csum_combine,
3361 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3362 &default_crc32c_ops;
3363 EXPORT_SYMBOL(crc32c_csum_stub);
3366 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3367 * @from: source buffer
3369 * Calculates the amount of linear headroom needed in the 'to' skb passed
3370 * into skb_zerocopy().
3373 skb_zerocopy_headlen(const struct sk_buff *from)
3375 unsigned int hlen = 0;
3377 if (!from->head_frag ||
3378 skb_headlen(from) < L1_CACHE_BYTES ||
3379 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3380 hlen = skb_headlen(from);
3385 if (skb_has_frag_list(from))
3390 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3393 * skb_zerocopy - Zero copy skb to skb
3394 * @to: destination buffer
3395 * @from: source buffer
3396 * @len: number of bytes to copy from source buffer
3397 * @hlen: size of linear headroom in destination buffer
3399 * Copies up to `len` bytes from `from` to `to` by creating references
3400 * to the frags in the source buffer.
3402 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3403 * headroom in the `to` buffer.
3406 * 0: everything is OK
3407 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3408 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3411 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3414 int plen = 0; /* length of skb->head fragment */
3417 unsigned int offset;
3419 BUG_ON(!from->head_frag && !hlen);
3421 /* dont bother with small payloads */
3422 if (len <= skb_tailroom(to))
3423 return skb_copy_bits(from, 0, skb_put(to, len), len);
3426 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3431 plen = min_t(int, skb_headlen(from), len);
3433 page = virt_to_head_page(from->head);
3434 offset = from->data - (unsigned char *)page_address(page);
3435 __skb_fill_page_desc(to, 0, page, offset, plen);
3442 skb_len_add(to, len + plen);
3444 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3448 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3450 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3455 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3456 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3458 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3460 skb_frag_ref(to, j);
3463 skb_shinfo(to)->nr_frags = j;
3467 EXPORT_SYMBOL_GPL(skb_zerocopy);
3469 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3474 if (skb->ip_summed == CHECKSUM_PARTIAL)
3475 csstart = skb_checksum_start_offset(skb);
3477 csstart = skb_headlen(skb);
3479 BUG_ON(csstart > skb_headlen(skb));
3481 skb_copy_from_linear_data(skb, to, csstart);
3484 if (csstart != skb->len)
3485 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3486 skb->len - csstart);
3488 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3489 long csstuff = csstart + skb->csum_offset;
3491 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3494 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3497 * skb_dequeue - remove from the head of the queue
3498 * @list: list to dequeue from
3500 * Remove the head of the list. The list lock is taken so the function
3501 * may be used safely with other locking list functions. The head item is
3502 * returned or %NULL if the list is empty.
3505 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3507 unsigned long flags;
3508 struct sk_buff *result;
3510 spin_lock_irqsave(&list->lock, flags);
3511 result = __skb_dequeue(list);
3512 spin_unlock_irqrestore(&list->lock, flags);
3515 EXPORT_SYMBOL(skb_dequeue);
3518 * skb_dequeue_tail - remove from the tail of the queue
3519 * @list: list to dequeue from
3521 * Remove the tail of the list. The list lock is taken so the function
3522 * may be used safely with other locking list functions. The tail item is
3523 * returned or %NULL if the list is empty.
3525 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3527 unsigned long flags;
3528 struct sk_buff *result;
3530 spin_lock_irqsave(&list->lock, flags);
3531 result = __skb_dequeue_tail(list);
3532 spin_unlock_irqrestore(&list->lock, flags);
3535 EXPORT_SYMBOL(skb_dequeue_tail);
3538 * skb_queue_purge - empty a list
3539 * @list: list to empty
3541 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3542 * the list and one reference dropped. This function takes the list
3543 * lock and is atomic with respect to other list locking functions.
3545 void skb_queue_purge(struct sk_buff_head *list)
3547 struct sk_buff *skb;
3548 while ((skb = skb_dequeue(list)) != NULL)
3551 EXPORT_SYMBOL(skb_queue_purge);
3554 * skb_rbtree_purge - empty a skb rbtree
3555 * @root: root of the rbtree to empty
3556 * Return value: the sum of truesizes of all purged skbs.
3558 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3559 * the list and one reference dropped. This function does not take
3560 * any lock. Synchronization should be handled by the caller (e.g., TCP
3561 * out-of-order queue is protected by the socket lock).
3563 unsigned int skb_rbtree_purge(struct rb_root *root)
3565 struct rb_node *p = rb_first(root);
3566 unsigned int sum = 0;
3569 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3572 rb_erase(&skb->rbnode, root);
3573 sum += skb->truesize;
3580 * skb_queue_head - queue a buffer at the list head
3581 * @list: list to use
3582 * @newsk: buffer to queue
3584 * Queue a buffer at the start of the list. This function takes the
3585 * list lock and can be used safely with other locking &sk_buff functions
3588 * A buffer cannot be placed on two lists at the same time.
3590 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3592 unsigned long flags;
3594 spin_lock_irqsave(&list->lock, flags);
3595 __skb_queue_head(list, newsk);
3596 spin_unlock_irqrestore(&list->lock, flags);
3598 EXPORT_SYMBOL(skb_queue_head);
3601 * skb_queue_tail - queue a buffer at the list tail
3602 * @list: list to use
3603 * @newsk: buffer to queue
3605 * Queue a buffer at the tail of the list. This function takes the
3606 * list lock and can be used safely with other locking &sk_buff functions
3609 * A buffer cannot be placed on two lists at the same time.
3611 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3613 unsigned long flags;
3615 spin_lock_irqsave(&list->lock, flags);
3616 __skb_queue_tail(list, newsk);
3617 spin_unlock_irqrestore(&list->lock, flags);
3619 EXPORT_SYMBOL(skb_queue_tail);
3622 * skb_unlink - remove a buffer from a list
3623 * @skb: buffer to remove
3624 * @list: list to use
3626 * Remove a packet from a list. The list locks are taken and this
3627 * function is atomic with respect to other list locked calls
3629 * You must know what list the SKB is on.
3631 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3633 unsigned long flags;
3635 spin_lock_irqsave(&list->lock, flags);
3636 __skb_unlink(skb, list);
3637 spin_unlock_irqrestore(&list->lock, flags);
3639 EXPORT_SYMBOL(skb_unlink);
3642 * skb_append - append a buffer
3643 * @old: buffer to insert after
3644 * @newsk: buffer to insert
3645 * @list: list to use
3647 * Place a packet after a given packet in a list. The list locks are taken
3648 * and this function is atomic with respect to other list locked calls.
3649 * A buffer cannot be placed on two lists at the same time.
3651 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3653 unsigned long flags;
3655 spin_lock_irqsave(&list->lock, flags);
3656 __skb_queue_after(list, old, newsk);
3657 spin_unlock_irqrestore(&list->lock, flags);
3659 EXPORT_SYMBOL(skb_append);
3661 static inline void skb_split_inside_header(struct sk_buff *skb,
3662 struct sk_buff* skb1,
3663 const u32 len, const int pos)
3667 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3669 /* And move data appendix as is. */
3670 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3671 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3673 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3674 skb_shinfo(skb)->nr_frags = 0;
3675 skb1->data_len = skb->data_len;
3676 skb1->len += skb1->data_len;
3679 skb_set_tail_pointer(skb, len);
3682 static inline void skb_split_no_header(struct sk_buff *skb,
3683 struct sk_buff* skb1,
3684 const u32 len, int pos)
3687 const int nfrags = skb_shinfo(skb)->nr_frags;
3689 skb_shinfo(skb)->nr_frags = 0;
3690 skb1->len = skb1->data_len = skb->len - len;
3692 skb->data_len = len - pos;
3694 for (i = 0; i < nfrags; i++) {
3695 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3697 if (pos + size > len) {
3698 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3702 * We have two variants in this case:
3703 * 1. Move all the frag to the second
3704 * part, if it is possible. F.e.
3705 * this approach is mandatory for TUX,
3706 * where splitting is expensive.
3707 * 2. Split is accurately. We make this.
3709 skb_frag_ref(skb, i);
3710 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3711 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3712 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3713 skb_shinfo(skb)->nr_frags++;
3717 skb_shinfo(skb)->nr_frags++;
3720 skb_shinfo(skb1)->nr_frags = k;
3724 * skb_split - Split fragmented skb to two parts at length len.
3725 * @skb: the buffer to split
3726 * @skb1: the buffer to receive the second part
3727 * @len: new length for skb
3729 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3731 int pos = skb_headlen(skb);
3732 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3734 skb_zcopy_downgrade_managed(skb);
3736 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3737 skb_zerocopy_clone(skb1, skb, 0);
3738 if (len < pos) /* Split line is inside header. */
3739 skb_split_inside_header(skb, skb1, len, pos);
3740 else /* Second chunk has no header, nothing to copy. */
3741 skb_split_no_header(skb, skb1, len, pos);
3743 EXPORT_SYMBOL(skb_split);
3745 /* Shifting from/to a cloned skb is a no-go.
3747 * Caller cannot keep skb_shinfo related pointers past calling here!
3749 static int skb_prepare_for_shift(struct sk_buff *skb)
3751 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3755 * skb_shift - Shifts paged data partially from skb to another
3756 * @tgt: buffer into which tail data gets added
3757 * @skb: buffer from which the paged data comes from
3758 * @shiftlen: shift up to this many bytes
3760 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3761 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3762 * It's up to caller to free skb if everything was shifted.
3764 * If @tgt runs out of frags, the whole operation is aborted.
3766 * Skb cannot include anything else but paged data while tgt is allowed
3767 * to have non-paged data as well.
3769 * TODO: full sized shift could be optimized but that would need
3770 * specialized skb free'er to handle frags without up-to-date nr_frags.
3772 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3774 int from, to, merge, todo;
3775 skb_frag_t *fragfrom, *fragto;
3777 BUG_ON(shiftlen > skb->len);
3779 if (skb_headlen(skb))
3781 if (skb_zcopy(tgt) || skb_zcopy(skb))
3786 to = skb_shinfo(tgt)->nr_frags;
3787 fragfrom = &skb_shinfo(skb)->frags[from];
3789 /* Actual merge is delayed until the point when we know we can
3790 * commit all, so that we don't have to undo partial changes
3793 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3794 skb_frag_off(fragfrom))) {
3799 todo -= skb_frag_size(fragfrom);
3801 if (skb_prepare_for_shift(skb) ||
3802 skb_prepare_for_shift(tgt))
3805 /* All previous frag pointers might be stale! */
3806 fragfrom = &skb_shinfo(skb)->frags[from];
3807 fragto = &skb_shinfo(tgt)->frags[merge];
3809 skb_frag_size_add(fragto, shiftlen);
3810 skb_frag_size_sub(fragfrom, shiftlen);
3811 skb_frag_off_add(fragfrom, shiftlen);
3819 /* Skip full, not-fitting skb to avoid expensive operations */
3820 if ((shiftlen == skb->len) &&
3821 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3824 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3827 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3828 if (to == MAX_SKB_FRAGS)
3831 fragfrom = &skb_shinfo(skb)->frags[from];
3832 fragto = &skb_shinfo(tgt)->frags[to];
3834 if (todo >= skb_frag_size(fragfrom)) {
3835 *fragto = *fragfrom;
3836 todo -= skb_frag_size(fragfrom);
3841 __skb_frag_ref(fragfrom);
3842 skb_frag_page_copy(fragto, fragfrom);
3843 skb_frag_off_copy(fragto, fragfrom);
3844 skb_frag_size_set(fragto, todo);
3846 skb_frag_off_add(fragfrom, todo);
3847 skb_frag_size_sub(fragfrom, todo);
3855 /* Ready to "commit" this state change to tgt */
3856 skb_shinfo(tgt)->nr_frags = to;
3859 fragfrom = &skb_shinfo(skb)->frags[0];
3860 fragto = &skb_shinfo(tgt)->frags[merge];
3862 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3863 __skb_frag_unref(fragfrom, skb->pp_recycle);
3866 /* Reposition in the original skb */
3868 while (from < skb_shinfo(skb)->nr_frags)
3869 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3870 skb_shinfo(skb)->nr_frags = to;
3872 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3875 /* Most likely the tgt won't ever need its checksum anymore, skb on
3876 * the other hand might need it if it needs to be resent
3878 tgt->ip_summed = CHECKSUM_PARTIAL;
3879 skb->ip_summed = CHECKSUM_PARTIAL;
3881 skb_len_add(skb, -shiftlen);
3882 skb_len_add(tgt, shiftlen);
3888 * skb_prepare_seq_read - Prepare a sequential read of skb data
3889 * @skb: the buffer to read
3890 * @from: lower offset of data to be read
3891 * @to: upper offset of data to be read
3892 * @st: state variable
3894 * Initializes the specified state variable. Must be called before
3895 * invoking skb_seq_read() for the first time.
3897 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3898 unsigned int to, struct skb_seq_state *st)
3900 st->lower_offset = from;
3901 st->upper_offset = to;
3902 st->root_skb = st->cur_skb = skb;
3903 st->frag_idx = st->stepped_offset = 0;
3904 st->frag_data = NULL;
3907 EXPORT_SYMBOL(skb_prepare_seq_read);
3910 * skb_seq_read - Sequentially read skb data
3911 * @consumed: number of bytes consumed by the caller so far
3912 * @data: destination pointer for data to be returned
3913 * @st: state variable
3915 * Reads a block of skb data at @consumed relative to the
3916 * lower offset specified to skb_prepare_seq_read(). Assigns
3917 * the head of the data block to @data and returns the length
3918 * of the block or 0 if the end of the skb data or the upper
3919 * offset has been reached.
3921 * The caller is not required to consume all of the data
3922 * returned, i.e. @consumed is typically set to the number
3923 * of bytes already consumed and the next call to
3924 * skb_seq_read() will return the remaining part of the block.
3926 * Note 1: The size of each block of data returned can be arbitrary,
3927 * this limitation is the cost for zerocopy sequential
3928 * reads of potentially non linear data.
3930 * Note 2: Fragment lists within fragments are not implemented
3931 * at the moment, state->root_skb could be replaced with
3932 * a stack for this purpose.
3934 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3935 struct skb_seq_state *st)
3937 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3940 if (unlikely(abs_offset >= st->upper_offset)) {
3941 if (st->frag_data) {
3942 kunmap_atomic(st->frag_data);
3943 st->frag_data = NULL;
3949 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3951 if (abs_offset < block_limit && !st->frag_data) {
3952 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3953 return block_limit - abs_offset;
3956 if (st->frag_idx == 0 && !st->frag_data)
3957 st->stepped_offset += skb_headlen(st->cur_skb);
3959 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3960 unsigned int pg_idx, pg_off, pg_sz;
3962 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3965 pg_off = skb_frag_off(frag);
3966 pg_sz = skb_frag_size(frag);
3968 if (skb_frag_must_loop(skb_frag_page(frag))) {
3969 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3970 pg_off = offset_in_page(pg_off + st->frag_off);
3971 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3972 PAGE_SIZE - pg_off);
3975 block_limit = pg_sz + st->stepped_offset;
3976 if (abs_offset < block_limit) {
3978 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3980 *data = (u8 *)st->frag_data + pg_off +
3981 (abs_offset - st->stepped_offset);
3983 return block_limit - abs_offset;
3986 if (st->frag_data) {
3987 kunmap_atomic(st->frag_data);
3988 st->frag_data = NULL;
3991 st->stepped_offset += pg_sz;
3992 st->frag_off += pg_sz;
3993 if (st->frag_off == skb_frag_size(frag)) {
3999 if (st->frag_data) {
4000 kunmap_atomic(st->frag_data);
4001 st->frag_data = NULL;
4004 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
4005 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
4008 } else if (st->cur_skb->next) {
4009 st->cur_skb = st->cur_skb->next;
4016 EXPORT_SYMBOL(skb_seq_read);
4019 * skb_abort_seq_read - Abort a sequential read of skb data
4020 * @st: state variable
4022 * Must be called if skb_seq_read() was not called until it
4025 void skb_abort_seq_read(struct skb_seq_state *st)
4028 kunmap_atomic(st->frag_data);
4030 EXPORT_SYMBOL(skb_abort_seq_read);
4032 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
4034 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
4035 struct ts_config *conf,
4036 struct ts_state *state)
4038 return skb_seq_read(offset, text, TS_SKB_CB(state));
4041 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
4043 skb_abort_seq_read(TS_SKB_CB(state));
4047 * skb_find_text - Find a text pattern in skb data
4048 * @skb: the buffer to look in
4049 * @from: search offset
4051 * @config: textsearch configuration
4053 * Finds a pattern in the skb data according to the specified
4054 * textsearch configuration. Use textsearch_next() to retrieve
4055 * subsequent occurrences of the pattern. Returns the offset
4056 * to the first occurrence or UINT_MAX if no match was found.
4058 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4059 unsigned int to, struct ts_config *config)
4061 struct ts_state state;
4064 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4066 config->get_next_block = skb_ts_get_next_block;
4067 config->finish = skb_ts_finish;
4069 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
4071 ret = textsearch_find(config, &state);
4072 return (ret <= to - from ? ret : UINT_MAX);
4074 EXPORT_SYMBOL(skb_find_text);
4076 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4077 int offset, size_t size)
4079 int i = skb_shinfo(skb)->nr_frags;
4081 if (skb_can_coalesce(skb, i, page, offset)) {
4082 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4083 } else if (i < MAX_SKB_FRAGS) {
4084 skb_zcopy_downgrade_managed(skb);
4086 skb_fill_page_desc_noacc(skb, i, page, offset, size);
4093 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4096 * skb_pull_rcsum - pull skb and update receive checksum
4097 * @skb: buffer to update
4098 * @len: length of data pulled
4100 * This function performs an skb_pull on the packet and updates
4101 * the CHECKSUM_COMPLETE checksum. It should be used on
4102 * receive path processing instead of skb_pull unless you know
4103 * that the checksum difference is zero (e.g., a valid IP header)
4104 * or you are setting ip_summed to CHECKSUM_NONE.
4106 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4108 unsigned char *data = skb->data;
4110 BUG_ON(len > skb->len);
4111 __skb_pull(skb, len);
4112 skb_postpull_rcsum(skb, data, len);
4115 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4117 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4119 skb_frag_t head_frag;
4122 page = virt_to_head_page(frag_skb->head);
4123 __skb_frag_set_page(&head_frag, page);
4124 skb_frag_off_set(&head_frag, frag_skb->data -
4125 (unsigned char *)page_address(page));
4126 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
4130 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4131 netdev_features_t features,
4132 unsigned int offset)
4134 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4135 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4136 unsigned int delta_truesize = 0;
4137 unsigned int delta_len = 0;
4138 struct sk_buff *tail = NULL;
4139 struct sk_buff *nskb, *tmp;
4142 skb_push(skb, -skb_network_offset(skb) + offset);
4144 skb_shinfo(skb)->frag_list = NULL;
4148 list_skb = list_skb->next;
4151 delta_truesize += nskb->truesize;
4152 if (skb_shared(nskb)) {
4153 tmp = skb_clone(nskb, GFP_ATOMIC);
4157 err = skb_unclone(nskb, GFP_ATOMIC);
4168 if (unlikely(err)) {
4169 nskb->next = list_skb;
4175 delta_len += nskb->len;
4177 skb_push(nskb, -skb_network_offset(nskb) + offset);
4179 skb_release_head_state(nskb);
4180 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4181 __copy_skb_header(nskb, skb);
4183 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4184 nskb->transport_header += len_diff;
4185 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4186 nskb->data - tnl_hlen,
4189 if (skb_needs_linearize(nskb, features) &&
4190 __skb_linearize(nskb))
4194 skb->truesize = skb->truesize - delta_truesize;
4195 skb->data_len = skb->data_len - delta_len;
4196 skb->len = skb->len - delta_len;
4202 if (skb_needs_linearize(skb, features) &&
4203 __skb_linearize(skb))
4211 kfree_skb_list(skb->next);
4213 return ERR_PTR(-ENOMEM);
4215 EXPORT_SYMBOL_GPL(skb_segment_list);
4218 * skb_segment - Perform protocol segmentation on skb.
4219 * @head_skb: buffer to segment
4220 * @features: features for the output path (see dev->features)
4222 * This function performs segmentation on the given skb. It returns
4223 * a pointer to the first in a list of new skbs for the segments.
4224 * In case of error it returns ERR_PTR(err).
4226 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4227 netdev_features_t features)
4229 struct sk_buff *segs = NULL;
4230 struct sk_buff *tail = NULL;
4231 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4232 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4233 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4234 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4235 struct sk_buff *frag_skb = head_skb;
4236 unsigned int offset = doffset;
4237 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4238 unsigned int partial_segs = 0;
4239 unsigned int headroom;
4240 unsigned int len = head_skb->len;
4243 int nfrags = skb_shinfo(head_skb)->nr_frags;
4248 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4249 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4250 struct sk_buff *check_skb;
4252 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4253 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4254 /* gso_size is untrusted, and we have a frag_list with
4255 * a linear non head_frag item.
4257 * If head_skb's headlen does not fit requested gso_size,
4258 * it means that the frag_list members do NOT terminate
4259 * on exact gso_size boundaries. Hence we cannot perform
4260 * skb_frag_t page sharing. Therefore we must fallback to
4261 * copying the frag_list skbs; we do so by disabling SG.
4263 features &= ~NETIF_F_SG;
4269 __skb_push(head_skb, doffset);
4270 proto = skb_network_protocol(head_skb, NULL);
4271 if (unlikely(!proto))
4272 return ERR_PTR(-EINVAL);
4274 sg = !!(features & NETIF_F_SG);
4275 csum = !!can_checksum_protocol(features, proto);
4277 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4278 if (!(features & NETIF_F_GSO_PARTIAL)) {
4279 struct sk_buff *iter;
4280 unsigned int frag_len;
4283 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4286 /* If we get here then all the required
4287 * GSO features except frag_list are supported.
4288 * Try to split the SKB to multiple GSO SKBs
4289 * with no frag_list.
4290 * Currently we can do that only when the buffers don't
4291 * have a linear part and all the buffers except
4292 * the last are of the same length.
4294 frag_len = list_skb->len;
4295 skb_walk_frags(head_skb, iter) {
4296 if (frag_len != iter->len && iter->next)
4298 if (skb_headlen(iter) && !iter->head_frag)
4304 if (len != frag_len)
4308 /* GSO partial only requires that we trim off any excess that
4309 * doesn't fit into an MSS sized block, so take care of that
4312 partial_segs = len / mss;
4313 if (partial_segs > 1)
4314 mss *= partial_segs;
4320 headroom = skb_headroom(head_skb);
4321 pos = skb_headlen(head_skb);
4324 struct sk_buff *nskb;
4325 skb_frag_t *nskb_frag;
4329 if (unlikely(mss == GSO_BY_FRAGS)) {
4330 len = list_skb->len;
4332 len = head_skb->len - offset;
4337 hsize = skb_headlen(head_skb) - offset;
4339 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4340 (skb_headlen(list_skb) == len || sg)) {
4341 BUG_ON(skb_headlen(list_skb) > len);
4344 nfrags = skb_shinfo(list_skb)->nr_frags;
4345 frag = skb_shinfo(list_skb)->frags;
4346 frag_skb = list_skb;
4347 pos += skb_headlen(list_skb);
4349 while (pos < offset + len) {
4350 BUG_ON(i >= nfrags);
4352 size = skb_frag_size(frag);
4353 if (pos + size > offset + len)
4361 nskb = skb_clone(list_skb, GFP_ATOMIC);
4362 list_skb = list_skb->next;
4364 if (unlikely(!nskb))
4367 if (unlikely(pskb_trim(nskb, len))) {
4372 hsize = skb_end_offset(nskb);
4373 if (skb_cow_head(nskb, doffset + headroom)) {
4378 nskb->truesize += skb_end_offset(nskb) - hsize;
4379 skb_release_head_state(nskb);
4380 __skb_push(nskb, doffset);
4384 if (hsize > len || !sg)
4387 nskb = __alloc_skb(hsize + doffset + headroom,
4388 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4391 if (unlikely(!nskb))
4394 skb_reserve(nskb, headroom);
4395 __skb_put(nskb, doffset);
4404 __copy_skb_header(nskb, head_skb);
4406 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4407 skb_reset_mac_len(nskb);
4409 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4410 nskb->data - tnl_hlen,
4411 doffset + tnl_hlen);
4413 if (nskb->len == len + doffset)
4414 goto perform_csum_check;
4418 if (!nskb->remcsum_offload)
4419 nskb->ip_summed = CHECKSUM_NONE;
4420 SKB_GSO_CB(nskb)->csum =
4421 skb_copy_and_csum_bits(head_skb, offset,
4425 SKB_GSO_CB(nskb)->csum_start =
4426 skb_headroom(nskb) + doffset;
4428 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4434 nskb_frag = skb_shinfo(nskb)->frags;
4436 skb_copy_from_linear_data_offset(head_skb, offset,
4437 skb_put(nskb, hsize), hsize);
4439 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4442 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4443 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4446 while (pos < offset + len) {
4449 nfrags = skb_shinfo(list_skb)->nr_frags;
4450 frag = skb_shinfo(list_skb)->frags;
4451 frag_skb = list_skb;
4452 if (!skb_headlen(list_skb)) {
4455 BUG_ON(!list_skb->head_frag);
4457 /* to make room for head_frag. */
4461 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4462 skb_zerocopy_clone(nskb, frag_skb,
4466 list_skb = list_skb->next;
4469 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4471 net_warn_ratelimited(
4472 "skb_segment: too many frags: %u %u\n",
4478 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4479 __skb_frag_ref(nskb_frag);
4480 size = skb_frag_size(nskb_frag);
4483 skb_frag_off_add(nskb_frag, offset - pos);
4484 skb_frag_size_sub(nskb_frag, offset - pos);
4487 skb_shinfo(nskb)->nr_frags++;
4489 if (pos + size <= offset + len) {
4494 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4502 nskb->data_len = len - hsize;
4503 nskb->len += nskb->data_len;
4504 nskb->truesize += nskb->data_len;
4508 if (skb_has_shared_frag(nskb) &&
4509 __skb_linearize(nskb))
4512 if (!nskb->remcsum_offload)
4513 nskb->ip_summed = CHECKSUM_NONE;
4514 SKB_GSO_CB(nskb)->csum =
4515 skb_checksum(nskb, doffset,
4516 nskb->len - doffset, 0);
4517 SKB_GSO_CB(nskb)->csum_start =
4518 skb_headroom(nskb) + doffset;
4520 } while ((offset += len) < head_skb->len);
4522 /* Some callers want to get the end of the list.
4523 * Put it in segs->prev to avoid walking the list.
4524 * (see validate_xmit_skb_list() for example)
4529 struct sk_buff *iter;
4530 int type = skb_shinfo(head_skb)->gso_type;
4531 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4533 /* Update type to add partial and then remove dodgy if set */
4534 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4535 type &= ~SKB_GSO_DODGY;
4537 /* Update GSO info and prepare to start updating headers on
4538 * our way back down the stack of protocols.
4540 for (iter = segs; iter; iter = iter->next) {
4541 skb_shinfo(iter)->gso_size = gso_size;
4542 skb_shinfo(iter)->gso_segs = partial_segs;
4543 skb_shinfo(iter)->gso_type = type;
4544 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4547 if (tail->len - doffset <= gso_size)
4548 skb_shinfo(tail)->gso_size = 0;
4549 else if (tail != segs)
4550 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4553 /* Following permits correct backpressure, for protocols
4554 * using skb_set_owner_w().
4555 * Idea is to tranfert ownership from head_skb to last segment.
4557 if (head_skb->destructor == sock_wfree) {
4558 swap(tail->truesize, head_skb->truesize);
4559 swap(tail->destructor, head_skb->destructor);
4560 swap(tail->sk, head_skb->sk);
4565 kfree_skb_list(segs);
4566 return ERR_PTR(err);
4568 EXPORT_SYMBOL_GPL(skb_segment);
4570 #ifdef CONFIG_SKB_EXTENSIONS
4571 #define SKB_EXT_ALIGN_VALUE 8
4572 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4574 static const u8 skb_ext_type_len[] = {
4575 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4576 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4579 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4581 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4582 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4584 #if IS_ENABLED(CONFIG_MPTCP)
4585 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4587 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4588 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4592 static __always_inline unsigned int skb_ext_total_length(void)
4594 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4595 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4596 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4599 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4601 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4602 skb_ext_type_len[TC_SKB_EXT] +
4604 #if IS_ENABLED(CONFIG_MPTCP)
4605 skb_ext_type_len[SKB_EXT_MPTCP] +
4607 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4608 skb_ext_type_len[SKB_EXT_MCTP] +
4613 static void skb_extensions_init(void)
4615 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4616 BUILD_BUG_ON(skb_ext_total_length() > 255);
4618 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4619 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4621 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4625 static void skb_extensions_init(void) {}
4628 void __init skb_init(void)
4630 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4631 sizeof(struct sk_buff),
4633 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4634 offsetof(struct sk_buff, cb),
4635 sizeof_field(struct sk_buff, cb),
4637 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4638 sizeof(struct sk_buff_fclones),
4640 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4642 skb_extensions_init();
4646 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4647 unsigned int recursion_level)
4649 int start = skb_headlen(skb);
4650 int i, copy = start - offset;
4651 struct sk_buff *frag_iter;
4654 if (unlikely(recursion_level >= 24))
4660 sg_set_buf(sg, skb->data + offset, copy);
4662 if ((len -= copy) == 0)
4667 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4670 WARN_ON(start > offset + len);
4672 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4673 if ((copy = end - offset) > 0) {
4674 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4675 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4680 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4681 skb_frag_off(frag) + offset - start);
4690 skb_walk_frags(skb, frag_iter) {
4693 WARN_ON(start > offset + len);
4695 end = start + frag_iter->len;
4696 if ((copy = end - offset) > 0) {
4697 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4702 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4703 copy, recursion_level + 1);
4704 if (unlikely(ret < 0))
4707 if ((len -= copy) == 0)
4718 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4719 * @skb: Socket buffer containing the buffers to be mapped
4720 * @sg: The scatter-gather list to map into
4721 * @offset: The offset into the buffer's contents to start mapping
4722 * @len: Length of buffer space to be mapped
4724 * Fill the specified scatter-gather list with mappings/pointers into a
4725 * region of the buffer space attached to a socket buffer. Returns either
4726 * the number of scatterlist items used, or -EMSGSIZE if the contents
4729 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4731 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4736 sg_mark_end(&sg[nsg - 1]);
4740 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4742 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4743 * sglist without mark the sg which contain last skb data as the end.
4744 * So the caller can mannipulate sg list as will when padding new data after
4745 * the first call without calling sg_unmark_end to expend sg list.
4747 * Scenario to use skb_to_sgvec_nomark:
4749 * 2. skb_to_sgvec_nomark(payload1)
4750 * 3. skb_to_sgvec_nomark(payload2)
4752 * This is equivalent to:
4754 * 2. skb_to_sgvec(payload1)
4756 * 4. skb_to_sgvec(payload2)
4758 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4759 * is more preferable.
4761 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4762 int offset, int len)
4764 return __skb_to_sgvec(skb, sg, offset, len, 0);
4766 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4771 * skb_cow_data - Check that a socket buffer's data buffers are writable
4772 * @skb: The socket buffer to check.
4773 * @tailbits: Amount of trailing space to be added
4774 * @trailer: Returned pointer to the skb where the @tailbits space begins
4776 * Make sure that the data buffers attached to a socket buffer are
4777 * writable. If they are not, private copies are made of the data buffers
4778 * and the socket buffer is set to use these instead.
4780 * If @tailbits is given, make sure that there is space to write @tailbits
4781 * bytes of data beyond current end of socket buffer. @trailer will be
4782 * set to point to the skb in which this space begins.
4784 * The number of scatterlist elements required to completely map the
4785 * COW'd and extended socket buffer will be returned.
4787 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4791 struct sk_buff *skb1, **skb_p;
4793 /* If skb is cloned or its head is paged, reallocate
4794 * head pulling out all the pages (pages are considered not writable
4795 * at the moment even if they are anonymous).
4797 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4798 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4801 /* Easy case. Most of packets will go this way. */
4802 if (!skb_has_frag_list(skb)) {
4803 /* A little of trouble, not enough of space for trailer.
4804 * This should not happen, when stack is tuned to generate
4805 * good frames. OK, on miss we reallocate and reserve even more
4806 * space, 128 bytes is fair. */
4808 if (skb_tailroom(skb) < tailbits &&
4809 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4817 /* Misery. We are in troubles, going to mincer fragments... */
4820 skb_p = &skb_shinfo(skb)->frag_list;
4823 while ((skb1 = *skb_p) != NULL) {
4826 /* The fragment is partially pulled by someone,
4827 * this can happen on input. Copy it and everything
4830 if (skb_shared(skb1))
4833 /* If the skb is the last, worry about trailer. */
4835 if (skb1->next == NULL && tailbits) {
4836 if (skb_shinfo(skb1)->nr_frags ||
4837 skb_has_frag_list(skb1) ||
4838 skb_tailroom(skb1) < tailbits)
4839 ntail = tailbits + 128;
4845 skb_shinfo(skb1)->nr_frags ||
4846 skb_has_frag_list(skb1)) {
4847 struct sk_buff *skb2;
4849 /* Fuck, we are miserable poor guys... */
4851 skb2 = skb_copy(skb1, GFP_ATOMIC);
4853 skb2 = skb_copy_expand(skb1,
4857 if (unlikely(skb2 == NULL))
4861 skb_set_owner_w(skb2, skb1->sk);
4863 /* Looking around. Are we still alive?
4864 * OK, link new skb, drop old one */
4866 skb2->next = skb1->next;
4873 skb_p = &skb1->next;
4878 EXPORT_SYMBOL_GPL(skb_cow_data);
4880 static void sock_rmem_free(struct sk_buff *skb)
4882 struct sock *sk = skb->sk;
4884 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4887 static void skb_set_err_queue(struct sk_buff *skb)
4889 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4890 * So, it is safe to (mis)use it to mark skbs on the error queue.
4892 skb->pkt_type = PACKET_OUTGOING;
4893 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4897 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4899 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4901 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4902 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4907 skb->destructor = sock_rmem_free;
4908 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4909 skb_set_err_queue(skb);
4911 /* before exiting rcu section, make sure dst is refcounted */
4914 skb_queue_tail(&sk->sk_error_queue, skb);
4915 if (!sock_flag(sk, SOCK_DEAD))
4916 sk_error_report(sk);
4919 EXPORT_SYMBOL(sock_queue_err_skb);
4921 static bool is_icmp_err_skb(const struct sk_buff *skb)
4923 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4924 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4927 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4929 struct sk_buff_head *q = &sk->sk_error_queue;
4930 struct sk_buff *skb, *skb_next = NULL;
4931 bool icmp_next = false;
4932 unsigned long flags;
4934 spin_lock_irqsave(&q->lock, flags);
4935 skb = __skb_dequeue(q);
4936 if (skb && (skb_next = skb_peek(q))) {
4937 icmp_next = is_icmp_err_skb(skb_next);
4939 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4941 spin_unlock_irqrestore(&q->lock, flags);
4943 if (is_icmp_err_skb(skb) && !icmp_next)
4947 sk_error_report(sk);
4951 EXPORT_SYMBOL(sock_dequeue_err_skb);
4954 * skb_clone_sk - create clone of skb, and take reference to socket
4955 * @skb: the skb to clone
4957 * This function creates a clone of a buffer that holds a reference on
4958 * sk_refcnt. Buffers created via this function are meant to be
4959 * returned using sock_queue_err_skb, or free via kfree_skb.
4961 * When passing buffers allocated with this function to sock_queue_err_skb
4962 * it is necessary to wrap the call with sock_hold/sock_put in order to
4963 * prevent the socket from being released prior to being enqueued on
4964 * the sk_error_queue.
4966 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4968 struct sock *sk = skb->sk;
4969 struct sk_buff *clone;
4971 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4974 clone = skb_clone(skb, GFP_ATOMIC);
4981 clone->destructor = sock_efree;
4985 EXPORT_SYMBOL(skb_clone_sk);
4987 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4992 struct sock_exterr_skb *serr;
4995 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4997 serr = SKB_EXT_ERR(skb);
4998 memset(serr, 0, sizeof(*serr));
4999 serr->ee.ee_errno = ENOMSG;
5000 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5001 serr->ee.ee_info = tstype;
5002 serr->opt_stats = opt_stats;
5003 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5004 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
5005 serr->ee.ee_data = skb_shinfo(skb)->tskey;
5007 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5010 err = sock_queue_err_skb(sk, skb);
5016 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5020 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5023 read_lock_bh(&sk->sk_callback_lock);
5024 ret = sk->sk_socket && sk->sk_socket->file &&
5025 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5026 read_unlock_bh(&sk->sk_callback_lock);
5030 void skb_complete_tx_timestamp(struct sk_buff *skb,
5031 struct skb_shared_hwtstamps *hwtstamps)
5033 struct sock *sk = skb->sk;
5035 if (!skb_may_tx_timestamp(sk, false))
5038 /* Take a reference to prevent skb_orphan() from freeing the socket,
5039 * but only if the socket refcount is not zero.
5041 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5042 *skb_hwtstamps(skb) = *hwtstamps;
5043 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5051 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5053 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5054 const struct sk_buff *ack_skb,
5055 struct skb_shared_hwtstamps *hwtstamps,
5056 struct sock *sk, int tstype)
5058 struct sk_buff *skb;
5059 bool tsonly, opt_stats = false;
5064 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5065 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5068 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5069 if (!skb_may_tx_timestamp(sk, tsonly))
5074 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5076 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5081 skb = alloc_skb(0, GFP_ATOMIC);
5083 skb = skb_clone(orig_skb, GFP_ATOMIC);
5089 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5091 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5095 *skb_hwtstamps(skb) = *hwtstamps;
5097 __net_timestamp(skb);
5099 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5101 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5103 void skb_tstamp_tx(struct sk_buff *orig_skb,
5104 struct skb_shared_hwtstamps *hwtstamps)
5106 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5109 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5111 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5113 struct sock *sk = skb->sk;
5114 struct sock_exterr_skb *serr;
5117 skb->wifi_acked_valid = 1;
5118 skb->wifi_acked = acked;
5120 serr = SKB_EXT_ERR(skb);
5121 memset(serr, 0, sizeof(*serr));
5122 serr->ee.ee_errno = ENOMSG;
5123 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5125 /* Take a reference to prevent skb_orphan() from freeing the socket,
5126 * but only if the socket refcount is not zero.
5128 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5129 err = sock_queue_err_skb(sk, skb);
5135 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5138 * skb_partial_csum_set - set up and verify partial csum values for packet
5139 * @skb: the skb to set
5140 * @start: the number of bytes after skb->data to start checksumming.
5141 * @off: the offset from start to place the checksum.
5143 * For untrusted partially-checksummed packets, we need to make sure the values
5144 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5146 * This function checks and sets those values and skb->ip_summed: if this
5147 * returns false you should drop the packet.
5149 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5151 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5152 u32 csum_start = skb_headroom(skb) + (u32)start;
5154 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
5155 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5156 start, off, skb_headroom(skb), skb_headlen(skb));
5159 skb->ip_summed = CHECKSUM_PARTIAL;
5160 skb->csum_start = csum_start;
5161 skb->csum_offset = off;
5162 skb_set_transport_header(skb, start);
5165 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5167 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5170 if (skb_headlen(skb) >= len)
5173 /* If we need to pullup then pullup to the max, so we
5174 * won't need to do it again.
5179 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5182 if (skb_headlen(skb) < len)
5188 #define MAX_TCP_HDR_LEN (15 * 4)
5190 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5191 typeof(IPPROTO_IP) proto,
5198 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5199 off + MAX_TCP_HDR_LEN);
5200 if (!err && !skb_partial_csum_set(skb, off,
5201 offsetof(struct tcphdr,
5204 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5207 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5208 off + sizeof(struct udphdr));
5209 if (!err && !skb_partial_csum_set(skb, off,
5210 offsetof(struct udphdr,
5213 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5216 return ERR_PTR(-EPROTO);
5219 /* This value should be large enough to cover a tagged ethernet header plus
5220 * maximally sized IP and TCP or UDP headers.
5222 #define MAX_IP_HDR_LEN 128
5224 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5233 err = skb_maybe_pull_tail(skb,
5234 sizeof(struct iphdr),
5239 if (ip_is_fragment(ip_hdr(skb)))
5242 off = ip_hdrlen(skb);
5249 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5251 return PTR_ERR(csum);
5254 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5257 ip_hdr(skb)->protocol, 0);
5264 /* This value should be large enough to cover a tagged ethernet header plus
5265 * an IPv6 header, all options, and a maximal TCP or UDP header.
5267 #define MAX_IPV6_HDR_LEN 256
5269 #define OPT_HDR(type, skb, off) \
5270 (type *)(skb_network_header(skb) + (off))
5272 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5285 off = sizeof(struct ipv6hdr);
5287 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5291 nexthdr = ipv6_hdr(skb)->nexthdr;
5293 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5294 while (off <= len && !done) {
5296 case IPPROTO_DSTOPTS:
5297 case IPPROTO_HOPOPTS:
5298 case IPPROTO_ROUTING: {
5299 struct ipv6_opt_hdr *hp;
5301 err = skb_maybe_pull_tail(skb,
5303 sizeof(struct ipv6_opt_hdr),
5308 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5309 nexthdr = hp->nexthdr;
5310 off += ipv6_optlen(hp);
5314 struct ip_auth_hdr *hp;
5316 err = skb_maybe_pull_tail(skb,
5318 sizeof(struct ip_auth_hdr),
5323 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5324 nexthdr = hp->nexthdr;
5325 off += ipv6_authlen(hp);
5328 case IPPROTO_FRAGMENT: {
5329 struct frag_hdr *hp;
5331 err = skb_maybe_pull_tail(skb,
5333 sizeof(struct frag_hdr),
5338 hp = OPT_HDR(struct frag_hdr, skb, off);
5340 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5343 nexthdr = hp->nexthdr;
5344 off += sizeof(struct frag_hdr);
5355 if (!done || fragment)
5358 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5360 return PTR_ERR(csum);
5363 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5364 &ipv6_hdr(skb)->daddr,
5365 skb->len - off, nexthdr, 0);
5373 * skb_checksum_setup - set up partial checksum offset
5374 * @skb: the skb to set up
5375 * @recalculate: if true the pseudo-header checksum will be recalculated
5377 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5381 switch (skb->protocol) {
5382 case htons(ETH_P_IP):
5383 err = skb_checksum_setup_ipv4(skb, recalculate);
5386 case htons(ETH_P_IPV6):
5387 err = skb_checksum_setup_ipv6(skb, recalculate);
5397 EXPORT_SYMBOL(skb_checksum_setup);
5400 * skb_checksum_maybe_trim - maybe trims the given skb
5401 * @skb: the skb to check
5402 * @transport_len: the data length beyond the network header
5404 * Checks whether the given skb has data beyond the given transport length.
5405 * If so, returns a cloned skb trimmed to this transport length.
5406 * Otherwise returns the provided skb. Returns NULL in error cases
5407 * (e.g. transport_len exceeds skb length or out-of-memory).
5409 * Caller needs to set the skb transport header and free any returned skb if it
5410 * differs from the provided skb.
5412 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5413 unsigned int transport_len)
5415 struct sk_buff *skb_chk;
5416 unsigned int len = skb_transport_offset(skb) + transport_len;
5421 else if (skb->len == len)
5424 skb_chk = skb_clone(skb, GFP_ATOMIC);
5428 ret = pskb_trim_rcsum(skb_chk, len);
5438 * skb_checksum_trimmed - validate checksum of an skb
5439 * @skb: the skb to check
5440 * @transport_len: the data length beyond the network header
5441 * @skb_chkf: checksum function to use
5443 * Applies the given checksum function skb_chkf to the provided skb.
5444 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5446 * If the skb has data beyond the given transport length, then a
5447 * trimmed & cloned skb is checked and returned.
5449 * Caller needs to set the skb transport header and free any returned skb if it
5450 * differs from the provided skb.
5452 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5453 unsigned int transport_len,
5454 __sum16(*skb_chkf)(struct sk_buff *skb))
5456 struct sk_buff *skb_chk;
5457 unsigned int offset = skb_transport_offset(skb);
5460 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5464 if (!pskb_may_pull(skb_chk, offset))
5467 skb_pull_rcsum(skb_chk, offset);
5468 ret = skb_chkf(skb_chk);
5469 skb_push_rcsum(skb_chk, offset);
5477 if (skb_chk && skb_chk != skb)
5483 EXPORT_SYMBOL(skb_checksum_trimmed);
5485 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5487 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5490 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5492 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5495 skb_release_head_state(skb);
5496 kmem_cache_free(skbuff_head_cache, skb);
5501 EXPORT_SYMBOL(kfree_skb_partial);
5504 * skb_try_coalesce - try to merge skb to prior one
5506 * @from: buffer to add
5507 * @fragstolen: pointer to boolean
5508 * @delta_truesize: how much more was allocated than was requested
5510 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5511 bool *fragstolen, int *delta_truesize)
5513 struct skb_shared_info *to_shinfo, *from_shinfo;
5514 int i, delta, len = from->len;
5516 *fragstolen = false;
5521 /* In general, avoid mixing slab allocated and page_pool allocated
5522 * pages within the same SKB. However when @to is not pp_recycle and
5523 * @from is cloned, we can transition frag pages from page_pool to
5524 * reference counted.
5526 * On the other hand, don't allow coalescing two pp_recycle SKBs if
5527 * @from is cloned, in case the SKB is using page_pool fragment
5528 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5529 * references for cloned SKBs at the moment that would result in
5530 * inconsistent reference counts.
5532 if (to->pp_recycle != (from->pp_recycle && !skb_cloned(from)))
5535 if (len <= skb_tailroom(to)) {
5537 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5538 *delta_truesize = 0;
5542 to_shinfo = skb_shinfo(to);
5543 from_shinfo = skb_shinfo(from);
5544 if (to_shinfo->frag_list || from_shinfo->frag_list)
5546 if (skb_zcopy(to) || skb_zcopy(from))
5549 if (skb_headlen(from) != 0) {
5551 unsigned int offset;
5553 if (to_shinfo->nr_frags +
5554 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5557 if (skb_head_is_locked(from))
5560 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5562 page = virt_to_head_page(from->head);
5563 offset = from->data - (unsigned char *)page_address(page);
5565 skb_fill_page_desc(to, to_shinfo->nr_frags,
5566 page, offset, skb_headlen(from));
5569 if (to_shinfo->nr_frags +
5570 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5573 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5576 WARN_ON_ONCE(delta < len);
5578 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5580 from_shinfo->nr_frags * sizeof(skb_frag_t));
5581 to_shinfo->nr_frags += from_shinfo->nr_frags;
5583 if (!skb_cloned(from))
5584 from_shinfo->nr_frags = 0;
5586 /* if the skb is not cloned this does nothing
5587 * since we set nr_frags to 0.
5589 for (i = 0; i < from_shinfo->nr_frags; i++)
5590 __skb_frag_ref(&from_shinfo->frags[i]);
5592 to->truesize += delta;
5594 to->data_len += len;
5596 *delta_truesize = delta;
5599 EXPORT_SYMBOL(skb_try_coalesce);
5602 * skb_scrub_packet - scrub an skb
5604 * @skb: buffer to clean
5605 * @xnet: packet is crossing netns
5607 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5608 * into/from a tunnel. Some information have to be cleared during these
5610 * skb_scrub_packet can also be used to clean a skb before injecting it in
5611 * another namespace (@xnet == true). We have to clear all information in the
5612 * skb that could impact namespace isolation.
5614 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5616 skb->pkt_type = PACKET_HOST;
5622 nf_reset_trace(skb);
5624 #ifdef CONFIG_NET_SWITCHDEV
5625 skb->offload_fwd_mark = 0;
5626 skb->offload_l3_fwd_mark = 0;
5634 skb_clear_tstamp(skb);
5636 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5639 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5643 * skb_gso_transport_seglen is used to determine the real size of the
5644 * individual segments, including Layer4 headers (TCP/UDP).
5646 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5648 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5650 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5651 unsigned int thlen = 0;
5653 if (skb->encapsulation) {
5654 thlen = skb_inner_transport_header(skb) -
5655 skb_transport_header(skb);
5657 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5658 thlen += inner_tcp_hdrlen(skb);
5659 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5660 thlen = tcp_hdrlen(skb);
5661 } else if (unlikely(skb_is_gso_sctp(skb))) {
5662 thlen = sizeof(struct sctphdr);
5663 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5664 thlen = sizeof(struct udphdr);
5666 /* UFO sets gso_size to the size of the fragmentation
5667 * payload, i.e. the size of the L4 (UDP) header is already
5670 return thlen + shinfo->gso_size;
5674 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5678 * skb_gso_network_seglen is used to determine the real size of the
5679 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5681 * The MAC/L2 header is not accounted for.
5683 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5685 unsigned int hdr_len = skb_transport_header(skb) -
5686 skb_network_header(skb);
5688 return hdr_len + skb_gso_transport_seglen(skb);
5692 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5696 * skb_gso_mac_seglen is used to determine the real size of the
5697 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5698 * headers (TCP/UDP).
5700 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5702 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5704 return hdr_len + skb_gso_transport_seglen(skb);
5708 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5710 * There are a couple of instances where we have a GSO skb, and we
5711 * want to determine what size it would be after it is segmented.
5713 * We might want to check:
5714 * - L3+L4+payload size (e.g. IP forwarding)
5715 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5717 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5721 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5722 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5724 * @max_len: The maximum permissible length.
5726 * Returns true if the segmented length <= max length.
5728 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5729 unsigned int seg_len,
5730 unsigned int max_len) {
5731 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5732 const struct sk_buff *iter;
5734 if (shinfo->gso_size != GSO_BY_FRAGS)
5735 return seg_len <= max_len;
5737 /* Undo this so we can re-use header sizes */
5738 seg_len -= GSO_BY_FRAGS;
5740 skb_walk_frags(skb, iter) {
5741 if (seg_len + skb_headlen(iter) > max_len)
5749 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5752 * @mtu: MTU to validate against
5754 * skb_gso_validate_network_len validates if a given skb will fit a
5755 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5758 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5760 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5762 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5765 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5768 * @len: length to validate against
5770 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5771 * length once split, including L2, L3 and L4 headers and the payload.
5773 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5775 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5777 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5779 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5781 int mac_len, meta_len;
5784 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5789 mac_len = skb->data - skb_mac_header(skb);
5790 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5791 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5792 mac_len - VLAN_HLEN - ETH_TLEN);
5795 meta_len = skb_metadata_len(skb);
5797 meta = skb_metadata_end(skb) - meta_len;
5798 memmove(meta + VLAN_HLEN, meta, meta_len);
5801 skb->mac_header += VLAN_HLEN;
5805 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5807 struct vlan_hdr *vhdr;
5810 if (unlikely(skb_vlan_tag_present(skb))) {
5811 /* vlan_tci is already set-up so leave this for another time */
5815 skb = skb_share_check(skb, GFP_ATOMIC);
5818 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5819 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5822 vhdr = (struct vlan_hdr *)skb->data;
5823 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5824 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5826 skb_pull_rcsum(skb, VLAN_HLEN);
5827 vlan_set_encap_proto(skb, vhdr);
5829 skb = skb_reorder_vlan_header(skb);
5833 skb_reset_network_header(skb);
5834 if (!skb_transport_header_was_set(skb))
5835 skb_reset_transport_header(skb);
5836 skb_reset_mac_len(skb);
5844 EXPORT_SYMBOL(skb_vlan_untag);
5846 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5848 if (!pskb_may_pull(skb, write_len))
5851 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5854 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5856 EXPORT_SYMBOL(skb_ensure_writable);
5858 /* remove VLAN header from packet and update csum accordingly.
5859 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5861 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5863 struct vlan_hdr *vhdr;
5864 int offset = skb->data - skb_mac_header(skb);
5867 if (WARN_ONCE(offset,
5868 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5873 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5877 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5879 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5880 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5882 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5883 __skb_pull(skb, VLAN_HLEN);
5885 vlan_set_encap_proto(skb, vhdr);
5886 skb->mac_header += VLAN_HLEN;
5888 if (skb_network_offset(skb) < ETH_HLEN)
5889 skb_set_network_header(skb, ETH_HLEN);
5891 skb_reset_mac_len(skb);
5895 EXPORT_SYMBOL(__skb_vlan_pop);
5897 /* Pop a vlan tag either from hwaccel or from payload.
5898 * Expects skb->data at mac header.
5900 int skb_vlan_pop(struct sk_buff *skb)
5906 if (likely(skb_vlan_tag_present(skb))) {
5907 __vlan_hwaccel_clear_tag(skb);
5909 if (unlikely(!eth_type_vlan(skb->protocol)))
5912 err = __skb_vlan_pop(skb, &vlan_tci);
5916 /* move next vlan tag to hw accel tag */
5917 if (likely(!eth_type_vlan(skb->protocol)))
5920 vlan_proto = skb->protocol;
5921 err = __skb_vlan_pop(skb, &vlan_tci);
5925 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5928 EXPORT_SYMBOL(skb_vlan_pop);
5930 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5931 * Expects skb->data at mac header.
5933 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5935 if (skb_vlan_tag_present(skb)) {
5936 int offset = skb->data - skb_mac_header(skb);
5939 if (WARN_ONCE(offset,
5940 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5945 err = __vlan_insert_tag(skb, skb->vlan_proto,
5946 skb_vlan_tag_get(skb));
5950 skb->protocol = skb->vlan_proto;
5951 skb->mac_len += VLAN_HLEN;
5953 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5955 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5958 EXPORT_SYMBOL(skb_vlan_push);
5961 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5963 * @skb: Socket buffer to modify
5965 * Drop the Ethernet header of @skb.
5967 * Expects that skb->data points to the mac header and that no VLAN tags are
5970 * Returns 0 on success, -errno otherwise.
5972 int skb_eth_pop(struct sk_buff *skb)
5974 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5975 skb_network_offset(skb) < ETH_HLEN)
5978 skb_pull_rcsum(skb, ETH_HLEN);
5979 skb_reset_mac_header(skb);
5980 skb_reset_mac_len(skb);
5984 EXPORT_SYMBOL(skb_eth_pop);
5987 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5989 * @skb: Socket buffer to modify
5990 * @dst: Destination MAC address of the new header
5991 * @src: Source MAC address of the new header
5993 * Prepend @skb with a new Ethernet header.
5995 * Expects that skb->data points to the mac header, which must be empty.
5997 * Returns 0 on success, -errno otherwise.
5999 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6000 const unsigned char *src)
6005 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6008 err = skb_cow_head(skb, sizeof(*eth));
6012 skb_push(skb, sizeof(*eth));
6013 skb_reset_mac_header(skb);
6014 skb_reset_mac_len(skb);
6017 ether_addr_copy(eth->h_dest, dst);
6018 ether_addr_copy(eth->h_source, src);
6019 eth->h_proto = skb->protocol;
6021 skb_postpush_rcsum(skb, eth, sizeof(*eth));
6025 EXPORT_SYMBOL(skb_eth_push);
6027 /* Update the ethertype of hdr and the skb csum value if required. */
6028 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6031 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6032 __be16 diff[] = { ~hdr->h_proto, ethertype };
6034 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6037 hdr->h_proto = ethertype;
6041 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6045 * @mpls_lse: MPLS label stack entry to push
6046 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6047 * @mac_len: length of the MAC header
6048 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6051 * Expects skb->data at mac header.
6053 * Returns 0 on success, -errno otherwise.
6055 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6056 int mac_len, bool ethernet)
6058 struct mpls_shim_hdr *lse;
6061 if (unlikely(!eth_p_mpls(mpls_proto)))
6064 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6065 if (skb->encapsulation)
6068 err = skb_cow_head(skb, MPLS_HLEN);
6072 if (!skb->inner_protocol) {
6073 skb_set_inner_network_header(skb, skb_network_offset(skb));
6074 skb_set_inner_protocol(skb, skb->protocol);
6077 skb_push(skb, MPLS_HLEN);
6078 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6080 skb_reset_mac_header(skb);
6081 skb_set_network_header(skb, mac_len);
6082 skb_reset_mac_len(skb);
6084 lse = mpls_hdr(skb);
6085 lse->label_stack_entry = mpls_lse;
6086 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6088 if (ethernet && mac_len >= ETH_HLEN)
6089 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6090 skb->protocol = mpls_proto;
6094 EXPORT_SYMBOL_GPL(skb_mpls_push);
6097 * skb_mpls_pop() - pop the outermost MPLS header
6100 * @next_proto: ethertype of header after popped MPLS header
6101 * @mac_len: length of the MAC header
6102 * @ethernet: flag to indicate if the packet is ethernet
6104 * Expects skb->data at mac header.
6106 * Returns 0 on success, -errno otherwise.
6108 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6113 if (unlikely(!eth_p_mpls(skb->protocol)))
6116 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6120 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6121 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6124 __skb_pull(skb, MPLS_HLEN);
6125 skb_reset_mac_header(skb);
6126 skb_set_network_header(skb, mac_len);
6128 if (ethernet && mac_len >= ETH_HLEN) {
6131 /* use mpls_hdr() to get ethertype to account for VLANs. */
6132 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6133 skb_mod_eth_type(skb, hdr, next_proto);
6135 skb->protocol = next_proto;
6139 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6142 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6145 * @mpls_lse: new MPLS label stack entry to update to
6147 * Expects skb->data at mac header.
6149 * Returns 0 on success, -errno otherwise.
6151 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6155 if (unlikely(!eth_p_mpls(skb->protocol)))
6158 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6162 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6163 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6165 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6168 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6172 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6175 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6179 * Expects skb->data at mac header.
6181 * Returns 0 on success, -errno otherwise.
6183 int skb_mpls_dec_ttl(struct sk_buff *skb)
6188 if (unlikely(!eth_p_mpls(skb->protocol)))
6191 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6194 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6195 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6199 lse &= ~MPLS_LS_TTL_MASK;
6200 lse |= ttl << MPLS_LS_TTL_SHIFT;
6202 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6204 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6207 * alloc_skb_with_frags - allocate skb with page frags
6209 * @header_len: size of linear part
6210 * @data_len: needed length in frags
6211 * @max_page_order: max page order desired.
6212 * @errcode: pointer to error code if any
6213 * @gfp_mask: allocation mask
6215 * This can be used to allocate a paged skb, given a maximal order for frags.
6217 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6218 unsigned long data_len,
6223 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6224 unsigned long chunk;
6225 struct sk_buff *skb;
6229 *errcode = -EMSGSIZE;
6230 /* Note this test could be relaxed, if we succeed to allocate
6231 * high order pages...
6233 if (npages > MAX_SKB_FRAGS)
6236 *errcode = -ENOBUFS;
6237 skb = alloc_skb(header_len, gfp_mask);
6241 skb->truesize += npages << PAGE_SHIFT;
6243 for (i = 0; npages > 0; i++) {
6244 int order = max_page_order;
6247 if (npages >= 1 << order) {
6248 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6254 /* Do not retry other high order allocations */
6260 page = alloc_page(gfp_mask);
6264 chunk = min_t(unsigned long, data_len,
6265 PAGE_SIZE << order);
6266 skb_fill_page_desc(skb, i, page, 0, chunk);
6268 npages -= 1 << order;
6276 EXPORT_SYMBOL(alloc_skb_with_frags);
6278 /* carve out the first off bytes from skb when off < headlen */
6279 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6280 const int headlen, gfp_t gfp_mask)
6283 unsigned int size = skb_end_offset(skb);
6284 int new_hlen = headlen - off;
6287 if (skb_pfmemalloc(skb))
6288 gfp_mask |= __GFP_MEMALLOC;
6290 size = SKB_DATA_ALIGN(size);
6291 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
6292 size = kmalloc_size_roundup(size);
6293 data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
6296 size = SKB_WITH_OVERHEAD(size);
6298 /* Copy real data, and all frags */
6299 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6302 memcpy((struct skb_shared_info *)(data + size),
6304 offsetof(struct skb_shared_info,
6305 frags[skb_shinfo(skb)->nr_frags]));
6306 if (skb_cloned(skb)) {
6307 /* drop the old head gracefully */
6308 if (skb_orphan_frags(skb, gfp_mask)) {
6312 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6313 skb_frag_ref(skb, i);
6314 if (skb_has_frag_list(skb))
6315 skb_clone_fraglist(skb);
6316 skb_release_data(skb, SKB_CONSUMED);
6318 /* we can reuse existing recount- all we did was
6327 skb_set_end_offset(skb, size);
6328 skb_set_tail_pointer(skb, skb_headlen(skb));
6329 skb_headers_offset_update(skb, 0);
6333 atomic_set(&skb_shinfo(skb)->dataref, 1);
6338 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6340 /* carve out the first eat bytes from skb's frag_list. May recurse into
6343 static int pskb_carve_frag_list(struct sk_buff *skb,
6344 struct skb_shared_info *shinfo, int eat,
6347 struct sk_buff *list = shinfo->frag_list;
6348 struct sk_buff *clone = NULL;
6349 struct sk_buff *insp = NULL;
6353 pr_err("Not enough bytes to eat. Want %d\n", eat);
6356 if (list->len <= eat) {
6357 /* Eaten as whole. */
6362 /* Eaten partially. */
6363 if (skb_shared(list)) {
6364 clone = skb_clone(list, gfp_mask);
6370 /* This may be pulled without problems. */
6373 if (pskb_carve(list, eat, gfp_mask) < 0) {
6381 /* Free pulled out fragments. */
6382 while ((list = shinfo->frag_list) != insp) {
6383 shinfo->frag_list = list->next;
6386 /* And insert new clone at head. */
6389 shinfo->frag_list = clone;
6394 /* carve off first len bytes from skb. Split line (off) is in the
6395 * non-linear part of skb
6397 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6398 int pos, gfp_t gfp_mask)
6401 unsigned int size = skb_end_offset(skb);
6403 const int nfrags = skb_shinfo(skb)->nr_frags;
6404 struct skb_shared_info *shinfo;
6406 if (skb_pfmemalloc(skb))
6407 gfp_mask |= __GFP_MEMALLOC;
6409 size = SKB_DATA_ALIGN(size);
6410 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
6411 size = kmalloc_size_roundup(size);
6412 data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
6415 size = SKB_WITH_OVERHEAD(size);
6417 memcpy((struct skb_shared_info *)(data + size),
6418 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6419 if (skb_orphan_frags(skb, gfp_mask)) {
6423 shinfo = (struct skb_shared_info *)(data + size);
6424 for (i = 0; i < nfrags; i++) {
6425 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6427 if (pos + fsize > off) {
6428 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6432 * We have two variants in this case:
6433 * 1. Move all the frag to the second
6434 * part, if it is possible. F.e.
6435 * this approach is mandatory for TUX,
6436 * where splitting is expensive.
6437 * 2. Split is accurately. We make this.
6439 skb_frag_off_add(&shinfo->frags[0], off - pos);
6440 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6442 skb_frag_ref(skb, i);
6447 shinfo->nr_frags = k;
6448 if (skb_has_frag_list(skb))
6449 skb_clone_fraglist(skb);
6451 /* split line is in frag list */
6452 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6453 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6454 if (skb_has_frag_list(skb))
6455 kfree_skb_list(skb_shinfo(skb)->frag_list);
6459 skb_release_data(skb, SKB_CONSUMED);
6464 skb_set_end_offset(skb, size);
6465 skb_reset_tail_pointer(skb);
6466 skb_headers_offset_update(skb, 0);
6471 skb->data_len = skb->len;
6472 atomic_set(&skb_shinfo(skb)->dataref, 1);
6476 /* remove len bytes from the beginning of the skb */
6477 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6479 int headlen = skb_headlen(skb);
6482 return pskb_carve_inside_header(skb, len, headlen, gfp);
6484 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6487 /* Extract to_copy bytes starting at off from skb, and return this in
6490 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6491 int to_copy, gfp_t gfp)
6493 struct sk_buff *clone = skb_clone(skb, gfp);
6498 if (pskb_carve(clone, off, gfp) < 0 ||
6499 pskb_trim(clone, to_copy)) {
6505 EXPORT_SYMBOL(pskb_extract);
6508 * skb_condense - try to get rid of fragments/frag_list if possible
6511 * Can be used to save memory before skb is added to a busy queue.
6512 * If packet has bytes in frags and enough tail room in skb->head,
6513 * pull all of them, so that we can free the frags right now and adjust
6516 * We do not reallocate skb->head thus can not fail.
6517 * Caller must re-evaluate skb->truesize if needed.
6519 void skb_condense(struct sk_buff *skb)
6521 if (skb->data_len) {
6522 if (skb->data_len > skb->end - skb->tail ||
6526 /* Nice, we can free page frag(s) right now */
6527 __pskb_pull_tail(skb, skb->data_len);
6529 /* At this point, skb->truesize might be over estimated,
6530 * because skb had a fragment, and fragments do not tell
6532 * When we pulled its content into skb->head, fragment
6533 * was freed, but __pskb_pull_tail() could not possibly
6534 * adjust skb->truesize, not knowing the frag truesize.
6536 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6538 EXPORT_SYMBOL(skb_condense);
6540 #ifdef CONFIG_SKB_EXTENSIONS
6541 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6543 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6547 * __skb_ext_alloc - allocate a new skb extensions storage
6549 * @flags: See kmalloc().
6551 * Returns the newly allocated pointer. The pointer can later attached to a
6552 * skb via __skb_ext_set().
6553 * Note: caller must handle the skb_ext as an opaque data.
6555 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6557 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6560 memset(new->offset, 0, sizeof(new->offset));
6561 refcount_set(&new->refcnt, 1);
6567 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6568 unsigned int old_active)
6570 struct skb_ext *new;
6572 if (refcount_read(&old->refcnt) == 1)
6575 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6579 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6580 refcount_set(&new->refcnt, 1);
6583 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6584 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6587 for (i = 0; i < sp->len; i++)
6588 xfrm_state_hold(sp->xvec[i]);
6596 * __skb_ext_set - attach the specified extension storage to this skb
6599 * @ext: extension storage previously allocated via __skb_ext_alloc()
6601 * Existing extensions, if any, are cleared.
6603 * Returns the pointer to the extension.
6605 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6606 struct skb_ext *ext)
6608 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6611 newlen = newoff + skb_ext_type_len[id];
6612 ext->chunks = newlen;
6613 ext->offset[id] = newoff;
6614 skb->extensions = ext;
6615 skb->active_extensions = 1 << id;
6616 return skb_ext_get_ptr(ext, id);
6620 * skb_ext_add - allocate space for given extension, COW if needed
6622 * @id: extension to allocate space for
6624 * Allocates enough space for the given extension.
6625 * If the extension is already present, a pointer to that extension
6628 * If the skb was cloned, COW applies and the returned memory can be
6629 * modified without changing the extension space of clones buffers.
6631 * Returns pointer to the extension or NULL on allocation failure.
6633 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6635 struct skb_ext *new, *old = NULL;
6636 unsigned int newlen, newoff;
6638 if (skb->active_extensions) {
6639 old = skb->extensions;
6641 new = skb_ext_maybe_cow(old, skb->active_extensions);
6645 if (__skb_ext_exist(new, id))
6648 newoff = new->chunks;
6650 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6652 new = __skb_ext_alloc(GFP_ATOMIC);
6657 newlen = newoff + skb_ext_type_len[id];
6658 new->chunks = newlen;
6659 new->offset[id] = newoff;
6662 skb->extensions = new;
6663 skb->active_extensions |= 1 << id;
6664 return skb_ext_get_ptr(new, id);
6666 EXPORT_SYMBOL(skb_ext_add);
6669 static void skb_ext_put_sp(struct sec_path *sp)
6673 for (i = 0; i < sp->len; i++)
6674 xfrm_state_put(sp->xvec[i]);
6678 #ifdef CONFIG_MCTP_FLOWS
6679 static void skb_ext_put_mctp(struct mctp_flow *flow)
6682 mctp_key_unref(flow->key);
6686 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6688 struct skb_ext *ext = skb->extensions;
6690 skb->active_extensions &= ~(1 << id);
6691 if (skb->active_extensions == 0) {
6692 skb->extensions = NULL;
6695 } else if (id == SKB_EXT_SEC_PATH &&
6696 refcount_read(&ext->refcnt) == 1) {
6697 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6704 EXPORT_SYMBOL(__skb_ext_del);
6706 void __skb_ext_put(struct skb_ext *ext)
6708 /* If this is last clone, nothing can increment
6709 * it after check passes. Avoids one atomic op.
6711 if (refcount_read(&ext->refcnt) == 1)
6714 if (!refcount_dec_and_test(&ext->refcnt))
6718 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6719 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6721 #ifdef CONFIG_MCTP_FLOWS
6722 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6723 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6726 kmem_cache_free(skbuff_ext_cache, ext);
6728 EXPORT_SYMBOL(__skb_ext_put);
6729 #endif /* CONFIG_SKB_EXTENSIONS */
6732 * skb_attempt_defer_free - queue skb for remote freeing
6735 * Put @skb in a per-cpu list, using the cpu which
6736 * allocated the skb/pages to reduce false sharing
6737 * and memory zone spinlock contention.
6739 void skb_attempt_defer_free(struct sk_buff *skb)
6741 int cpu = skb->alloc_cpu;
6742 struct softnet_data *sd;
6743 unsigned long flags;
6744 unsigned int defer_max;
6747 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6749 cpu == raw_smp_processor_id()) {
6750 nodefer: __kfree_skb(skb);
6754 sd = &per_cpu(softnet_data, cpu);
6755 defer_max = READ_ONCE(sysctl_skb_defer_max);
6756 if (READ_ONCE(sd->defer_count) >= defer_max)
6759 spin_lock_irqsave(&sd->defer_lock, flags);
6760 /* Send an IPI every time queue reaches half capacity. */
6761 kick = sd->defer_count == (defer_max >> 1);
6762 /* Paired with the READ_ONCE() few lines above */
6763 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6765 skb->next = sd->defer_list;
6766 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6767 WRITE_ONCE(sd->defer_list, skb);
6768 spin_unlock_irqrestore(&sd->defer_lock, flags);
6770 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6771 * if we are unlucky enough (this seems very unlikely).
6773 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6774 smp_call_function_single_async(cpu, &sd->defer_csd);