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>
84 #include "sock_destructor.h"
86 struct kmem_cache *skbuff_head_cache __ro_after_init;
87 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
88 #ifdef CONFIG_SKB_EXTENSIONS
89 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
91 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
92 EXPORT_SYMBOL(sysctl_max_skb_frags);
95 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
96 const char * const drop_reasons[] = {
97 DEFINE_DROP_REASON(FN, FN)
99 EXPORT_SYMBOL(drop_reasons);
102 * skb_panic - private function for out-of-line support
106 * @msg: skb_over_panic or skb_under_panic
108 * Out-of-line support for skb_put() and skb_push().
109 * Called via the wrapper skb_over_panic() or skb_under_panic().
110 * Keep out of line to prevent kernel bloat.
111 * __builtin_return_address is not used because it is not always reliable.
113 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
116 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
117 msg, addr, skb->len, sz, skb->head, skb->data,
118 (unsigned long)skb->tail, (unsigned long)skb->end,
119 skb->dev ? skb->dev->name : "<NULL>");
123 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
125 skb_panic(skb, sz, addr, __func__);
128 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
130 skb_panic(skb, sz, addr, __func__);
133 #define NAPI_SKB_CACHE_SIZE 64
134 #define NAPI_SKB_CACHE_BULK 16
135 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
137 #if PAGE_SIZE == SZ_4K
139 #define NAPI_HAS_SMALL_PAGE_FRAG 1
140 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) ((nc).pfmemalloc)
142 /* specialized page frag allocator using a single order 0 page
143 * and slicing it into 1K sized fragment. Constrained to systems
144 * with a very limited amount of 1K fragments fitting a single
145 * page - to avoid excessive truesize underestimation
148 struct page_frag_1k {
154 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
159 offset = nc->offset - SZ_1K;
160 if (likely(offset >= 0))
163 page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
167 nc->va = page_address(page);
168 nc->pfmemalloc = page_is_pfmemalloc(page);
169 offset = PAGE_SIZE - SZ_1K;
170 page_ref_add(page, offset / SZ_1K);
174 return nc->va + offset;
178 /* the small page is actually unused in this build; add dummy helpers
179 * to please the compiler and avoid later preprocessor's conditionals
181 #define NAPI_HAS_SMALL_PAGE_FRAG 0
182 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc) false
184 struct page_frag_1k {
187 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
194 struct napi_alloc_cache {
195 struct page_frag_cache page;
196 struct page_frag_1k page_small;
197 unsigned int skb_count;
198 void *skb_cache[NAPI_SKB_CACHE_SIZE];
201 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
202 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
204 /* Double check that napi_get_frags() allocates skbs with
205 * skb->head being backed by slab, not a page fragment.
206 * This is to make sure bug fixed in 3226b158e67c
207 * ("net: avoid 32 x truesize under-estimation for tiny skbs")
208 * does not accidentally come back.
210 void napi_get_frags_check(struct napi_struct *napi)
215 skb = napi_get_frags(napi);
216 WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
217 napi_free_frags(napi);
221 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
223 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
225 fragsz = SKB_DATA_ALIGN(fragsz);
227 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
229 EXPORT_SYMBOL(__napi_alloc_frag_align);
231 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
235 fragsz = SKB_DATA_ALIGN(fragsz);
236 if (in_hardirq() || irqs_disabled()) {
237 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
239 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
241 struct napi_alloc_cache *nc;
244 nc = this_cpu_ptr(&napi_alloc_cache);
245 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
250 EXPORT_SYMBOL(__netdev_alloc_frag_align);
252 static struct sk_buff *napi_skb_cache_get(void)
254 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
257 if (unlikely(!nc->skb_count)) {
258 nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
262 if (unlikely(!nc->skb_count))
266 skb = nc->skb_cache[--nc->skb_count];
267 kasan_unpoison_object_data(skbuff_head_cache, skb);
272 /* Caller must provide SKB that is memset cleared */
273 static void __build_skb_around(struct sk_buff *skb, void *data,
274 unsigned int frag_size)
276 struct skb_shared_info *shinfo;
277 unsigned int size = frag_size ? : ksize(data);
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());
300 * __build_skb - build a network buffer
301 * @data: data buffer provided by caller
302 * @frag_size: size of data, or 0 if head was kmalloced
304 * Allocate a new &sk_buff. Caller provides space holding head and
305 * skb_shared_info. @data must have been allocated by kmalloc() only if
306 * @frag_size is 0, otherwise data should come from the page allocator
308 * The return is the new skb buffer.
309 * On a failure the return is %NULL, and @data is not freed.
311 * Before IO, driver allocates only data buffer where NIC put incoming frame
312 * Driver should add room at head (NET_SKB_PAD) and
313 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
314 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
315 * before giving packet to stack.
316 * RX rings only contains data buffers, not full skbs.
318 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
322 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
326 memset(skb, 0, offsetof(struct sk_buff, tail));
327 __build_skb_around(skb, data, frag_size);
332 /* build_skb() is wrapper over __build_skb(), that specifically
333 * takes care of skb->head and skb->pfmemalloc
334 * This means that if @frag_size is not zero, then @data must be backed
335 * by a page fragment, not kmalloc() or vmalloc()
337 struct sk_buff *build_skb(void *data, unsigned int frag_size)
339 struct sk_buff *skb = __build_skb(data, frag_size);
341 if (skb && frag_size) {
343 if (page_is_pfmemalloc(virt_to_head_page(data)))
348 EXPORT_SYMBOL(build_skb);
351 * build_skb_around - build a network buffer around provided skb
352 * @skb: sk_buff provide by caller, must be memset cleared
353 * @data: data buffer provided by caller
354 * @frag_size: size of data, or 0 if head was kmalloced
356 struct sk_buff *build_skb_around(struct sk_buff *skb,
357 void *data, unsigned int frag_size)
362 __build_skb_around(skb, data, frag_size);
366 if (page_is_pfmemalloc(virt_to_head_page(data)))
371 EXPORT_SYMBOL(build_skb_around);
374 * __napi_build_skb - build a network buffer
375 * @data: data buffer provided by caller
376 * @frag_size: size of data, or 0 if head was kmalloced
378 * Version of __build_skb() that uses NAPI percpu caches to obtain
379 * skbuff_head instead of inplace allocation.
381 * Returns a new &sk_buff on success, %NULL on allocation failure.
383 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
387 skb = napi_skb_cache_get();
391 memset(skb, 0, offsetof(struct sk_buff, tail));
392 __build_skb_around(skb, data, frag_size);
398 * napi_build_skb - build a network buffer
399 * @data: data buffer provided by caller
400 * @frag_size: size of data, or 0 if head was kmalloced
402 * Version of __napi_build_skb() that takes care of skb->head_frag
403 * and skb->pfmemalloc when the data is a page or page fragment.
405 * Returns a new &sk_buff on success, %NULL on allocation failure.
407 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
409 struct sk_buff *skb = __napi_build_skb(data, frag_size);
411 if (likely(skb) && frag_size) {
413 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
418 EXPORT_SYMBOL(napi_build_skb);
421 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
422 * the caller if emergency pfmemalloc reserves are being used. If it is and
423 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
424 * may be used. Otherwise, the packet data may be discarded until enough
427 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
430 bool ret_pfmemalloc = false;
434 obj_size = SKB_HEAD_ALIGN(*size);
436 obj_size = kmalloc_size_roundup(obj_size);
437 /* The following cast might truncate high-order bits of obj_size, this
438 * is harmless because kmalloc(obj_size >= 2^32) will fail anyway.
440 *size = (unsigned int)obj_size;
443 * Try a regular allocation, when that fails and we're not entitled
444 * to the reserves, fail.
446 obj = kmalloc_node_track_caller(obj_size,
447 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
449 if (obj || !(gfp_pfmemalloc_allowed(flags)))
452 /* Try again but now we are using pfmemalloc reserves */
453 ret_pfmemalloc = true;
454 obj = kmalloc_node_track_caller(obj_size, flags, node);
458 *pfmemalloc = ret_pfmemalloc;
463 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
464 * 'private' fields and also do memory statistics to find all the
470 * __alloc_skb - allocate a network buffer
471 * @size: size to allocate
472 * @gfp_mask: allocation mask
473 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
474 * instead of head cache and allocate a cloned (child) skb.
475 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
476 * allocations in case the data is required for writeback
477 * @node: numa node to allocate memory on
479 * Allocate a new &sk_buff. The returned buffer has no headroom and a
480 * tail room of at least size bytes. The object has a reference count
481 * of one. The return is the buffer. On a failure the return is %NULL.
483 * Buffers may only be allocated from interrupts using a @gfp_mask of
486 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
489 struct kmem_cache *cache;
494 cache = (flags & SKB_ALLOC_FCLONE)
495 ? skbuff_fclone_cache : skbuff_head_cache;
497 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
498 gfp_mask |= __GFP_MEMALLOC;
501 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
502 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
503 skb = napi_skb_cache_get();
505 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
510 /* We do our best to align skb_shared_info on a separate cache
511 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
512 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
513 * Both skb->head and skb_shared_info are cache line aligned.
515 data = kmalloc_reserve(&size, gfp_mask, node, &pfmemalloc);
518 /* kmalloc_size_roundup() might give us more room than requested.
519 * Put skb_shared_info exactly at the end of allocated zone,
520 * to allow max possible filling before reallocation.
522 prefetchw(data + SKB_WITH_OVERHEAD(size));
525 * Only clear those fields we need to clear, not those that we will
526 * actually initialise below. Hence, don't put any more fields after
527 * the tail pointer in struct sk_buff!
529 memset(skb, 0, offsetof(struct sk_buff, tail));
530 __build_skb_around(skb, data, size);
531 skb->pfmemalloc = pfmemalloc;
533 if (flags & SKB_ALLOC_FCLONE) {
534 struct sk_buff_fclones *fclones;
536 fclones = container_of(skb, struct sk_buff_fclones, skb1);
538 skb->fclone = SKB_FCLONE_ORIG;
539 refcount_set(&fclones->fclone_ref, 1);
545 kmem_cache_free(cache, skb);
548 EXPORT_SYMBOL(__alloc_skb);
551 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
552 * @dev: network device to receive on
553 * @len: length to allocate
554 * @gfp_mask: get_free_pages mask, passed to alloc_skb
556 * Allocate a new &sk_buff and assign it a usage count of one. The
557 * buffer has NET_SKB_PAD headroom built in. Users should allocate
558 * the headroom they think they need without accounting for the
559 * built in space. The built in space is used for optimisations.
561 * %NULL is returned if there is no free memory.
563 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
566 struct page_frag_cache *nc;
573 /* If requested length is either too small or too big,
574 * we use kmalloc() for skb->head allocation.
576 if (len <= SKB_WITH_OVERHEAD(1024) ||
577 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
578 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
579 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
585 len = SKB_HEAD_ALIGN(len);
587 if (sk_memalloc_socks())
588 gfp_mask |= __GFP_MEMALLOC;
590 if (in_hardirq() || irqs_disabled()) {
591 nc = this_cpu_ptr(&netdev_alloc_cache);
592 data = page_frag_alloc(nc, len, gfp_mask);
593 pfmemalloc = nc->pfmemalloc;
596 nc = this_cpu_ptr(&napi_alloc_cache.page);
597 data = page_frag_alloc(nc, len, gfp_mask);
598 pfmemalloc = nc->pfmemalloc;
605 skb = __build_skb(data, len);
606 if (unlikely(!skb)) {
616 skb_reserve(skb, NET_SKB_PAD);
622 EXPORT_SYMBOL(__netdev_alloc_skb);
625 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
626 * @napi: napi instance this buffer was allocated for
627 * @len: length to allocate
628 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
630 * Allocate a new sk_buff for use in NAPI receive. This buffer will
631 * attempt to allocate the head from a special reserved region used
632 * only for NAPI Rx allocation. By doing this we can save several
633 * CPU cycles by avoiding having to disable and re-enable IRQs.
635 * %NULL is returned if there is no free memory.
637 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
640 struct napi_alloc_cache *nc;
645 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
646 len += NET_SKB_PAD + NET_IP_ALIGN;
648 /* If requested length is either too small or too big,
649 * we use kmalloc() for skb->head allocation.
650 * When the small frag allocator is available, prefer it over kmalloc
651 * for small fragments
653 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
654 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
655 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
656 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
663 nc = this_cpu_ptr(&napi_alloc_cache);
665 if (sk_memalloc_socks())
666 gfp_mask |= __GFP_MEMALLOC;
668 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
669 /* we are artificially inflating the allocation size, but
670 * that is not as bad as it may look like, as:
671 * - 'len' less than GRO_MAX_HEAD makes little sense
672 * - On most systems, larger 'len' values lead to fragment
673 * size above 512 bytes
674 * - kmalloc would use the kmalloc-1k slab for such values
675 * - Builds with smaller GRO_MAX_HEAD will very likely do
676 * little networking, as that implies no WiFi and no
677 * tunnels support, and 32 bits arches.
681 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
682 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
684 len = SKB_HEAD_ALIGN(len);
686 data = page_frag_alloc(&nc->page, len, gfp_mask);
687 pfmemalloc = nc->page.pfmemalloc;
693 skb = __napi_build_skb(data, len);
694 if (unlikely(!skb)) {
704 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
705 skb->dev = napi->dev;
710 EXPORT_SYMBOL(__napi_alloc_skb);
712 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
713 int size, unsigned int truesize)
715 skb_fill_page_desc(skb, i, page, off, size);
717 skb->data_len += size;
718 skb->truesize += truesize;
720 EXPORT_SYMBOL(skb_add_rx_frag);
722 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
723 unsigned int truesize)
725 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
727 skb_frag_size_add(frag, size);
729 skb->data_len += size;
730 skb->truesize += truesize;
732 EXPORT_SYMBOL(skb_coalesce_rx_frag);
734 static void skb_drop_list(struct sk_buff **listp)
736 kfree_skb_list(*listp);
740 static inline void skb_drop_fraglist(struct sk_buff *skb)
742 skb_drop_list(&skb_shinfo(skb)->frag_list);
745 static void skb_clone_fraglist(struct sk_buff *skb)
747 struct sk_buff *list;
749 skb_walk_frags(skb, list)
753 static void skb_free_head(struct sk_buff *skb)
755 unsigned char *head = skb->head;
757 if (skb->head_frag) {
758 if (skb_pp_recycle(skb, head))
766 static void skb_release_data(struct sk_buff *skb)
768 struct skb_shared_info *shinfo = skb_shinfo(skb);
772 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
776 if (skb_zcopy(skb)) {
777 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
779 skb_zcopy_clear(skb, true);
784 for (i = 0; i < shinfo->nr_frags; i++)
785 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
788 if (shinfo->frag_list)
789 kfree_skb_list(shinfo->frag_list);
793 /* When we clone an SKB we copy the reycling bit. The pp_recycle
794 * bit is only set on the head though, so in order to avoid races
795 * while trying to recycle fragments on __skb_frag_unref() we need
796 * to make one SKB responsible for triggering the recycle path.
797 * So disable the recycling bit if an SKB is cloned and we have
798 * additional references to the fragmented part of the SKB.
799 * Eventually the last SKB will have the recycling bit set and it's
800 * dataref set to 0, which will trigger the recycling
806 * Free an skbuff by memory without cleaning the state.
808 static void kfree_skbmem(struct sk_buff *skb)
810 struct sk_buff_fclones *fclones;
812 switch (skb->fclone) {
813 case SKB_FCLONE_UNAVAILABLE:
814 kmem_cache_free(skbuff_head_cache, skb);
817 case SKB_FCLONE_ORIG:
818 fclones = container_of(skb, struct sk_buff_fclones, skb1);
820 /* We usually free the clone (TX completion) before original skb
821 * This test would have no chance to be true for the clone,
822 * while here, branch prediction will be good.
824 if (refcount_read(&fclones->fclone_ref) == 1)
828 default: /* SKB_FCLONE_CLONE */
829 fclones = container_of(skb, struct sk_buff_fclones, skb2);
832 if (!refcount_dec_and_test(&fclones->fclone_ref))
835 kmem_cache_free(skbuff_fclone_cache, fclones);
838 void skb_release_head_state(struct sk_buff *skb)
841 if (skb->destructor) {
842 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
843 skb->destructor(skb);
845 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
846 nf_conntrack_put(skb_nfct(skb));
851 /* Free everything but the sk_buff shell. */
852 static void skb_release_all(struct sk_buff *skb)
854 skb_release_head_state(skb);
855 if (likely(skb->head))
856 skb_release_data(skb);
860 * __kfree_skb - private function
863 * Free an sk_buff. Release anything attached to the buffer.
864 * Clean the state. This is an internal helper function. Users should
865 * always call kfree_skb
868 void __kfree_skb(struct sk_buff *skb)
870 skb_release_all(skb);
873 EXPORT_SYMBOL(__kfree_skb);
876 * kfree_skb_reason - free an sk_buff with special reason
877 * @skb: buffer to free
878 * @reason: reason why this skb is dropped
880 * Drop a reference to the buffer and free it if the usage count has
881 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
885 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
887 if (unlikely(!skb_unref(skb)))
890 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
892 trace_kfree_skb(skb, __builtin_return_address(0), reason);
895 EXPORT_SYMBOL(kfree_skb_reason);
897 void kfree_skb_list_reason(struct sk_buff *segs,
898 enum skb_drop_reason reason)
901 struct sk_buff *next = segs->next;
903 kfree_skb_reason(segs, reason);
907 EXPORT_SYMBOL(kfree_skb_list_reason);
909 /* Dump skb information and contents.
911 * Must only be called from net_ratelimit()-ed paths.
913 * Dumps whole packets if full_pkt, only headers otherwise.
915 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
917 struct skb_shared_info *sh = skb_shinfo(skb);
918 struct net_device *dev = skb->dev;
919 struct sock *sk = skb->sk;
920 struct sk_buff *list_skb;
921 bool has_mac, has_trans;
922 int headroom, tailroom;
928 len = min_t(int, skb->len, MAX_HEADER + 128);
930 headroom = skb_headroom(skb);
931 tailroom = skb_tailroom(skb);
933 has_mac = skb_mac_header_was_set(skb);
934 has_trans = skb_transport_header_was_set(skb);
936 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
937 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
938 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
939 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
940 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
941 level, skb->len, headroom, skb_headlen(skb), tailroom,
942 has_mac ? skb->mac_header : -1,
943 has_mac ? skb_mac_header_len(skb) : -1,
945 has_trans ? skb_network_header_len(skb) : -1,
946 has_trans ? skb->transport_header : -1,
947 sh->tx_flags, sh->nr_frags,
948 sh->gso_size, sh->gso_type, sh->gso_segs,
949 skb->csum, skb->ip_summed, skb->csum_complete_sw,
950 skb->csum_valid, skb->csum_level,
951 skb->hash, skb->sw_hash, skb->l4_hash,
952 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
955 printk("%sdev name=%s feat=%pNF\n",
956 level, dev->name, &dev->features);
958 printk("%ssk family=%hu type=%u proto=%u\n",
959 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
961 if (full_pkt && headroom)
962 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
963 16, 1, skb->head, headroom, false);
965 seg_len = min_t(int, skb_headlen(skb), len);
967 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
968 16, 1, skb->data, seg_len, false);
971 if (full_pkt && tailroom)
972 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
973 16, 1, skb_tail_pointer(skb), tailroom, false);
975 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
976 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
977 u32 p_off, p_len, copied;
981 skb_frag_foreach_page(frag, skb_frag_off(frag),
982 skb_frag_size(frag), p, p_off, p_len,
984 seg_len = min_t(int, p_len, len);
985 vaddr = kmap_atomic(p);
986 print_hex_dump(level, "skb frag: ",
988 16, 1, vaddr + p_off, seg_len, false);
989 kunmap_atomic(vaddr);
996 if (full_pkt && skb_has_frag_list(skb)) {
997 printk("skb fraglist:\n");
998 skb_walk_frags(skb, list_skb)
999 skb_dump(level, list_skb, true);
1002 EXPORT_SYMBOL(skb_dump);
1005 * skb_tx_error - report an sk_buff xmit error
1006 * @skb: buffer that triggered an error
1008 * Report xmit error if a device callback is tracking this skb.
1009 * skb must be freed afterwards.
1011 void skb_tx_error(struct sk_buff *skb)
1014 skb_zcopy_downgrade_managed(skb);
1015 skb_zcopy_clear(skb, true);
1018 EXPORT_SYMBOL(skb_tx_error);
1020 #ifdef CONFIG_TRACEPOINTS
1022 * consume_skb - free an skbuff
1023 * @skb: buffer to free
1025 * Drop a ref to the buffer and free it if the usage count has hit zero
1026 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1027 * is being dropped after a failure and notes that
1029 void consume_skb(struct sk_buff *skb)
1031 if (!skb_unref(skb))
1034 trace_consume_skb(skb);
1037 EXPORT_SYMBOL(consume_skb);
1041 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1042 * @skb: buffer to free
1044 * Alike consume_skb(), but this variant assumes that this is the last
1045 * skb reference and all the head states have been already dropped
1047 void __consume_stateless_skb(struct sk_buff *skb)
1049 trace_consume_skb(skb);
1050 skb_release_data(skb);
1054 static void napi_skb_cache_put(struct sk_buff *skb)
1056 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1059 kasan_poison_object_data(skbuff_head_cache, skb);
1060 nc->skb_cache[nc->skb_count++] = skb;
1062 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1063 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1064 kasan_unpoison_object_data(skbuff_head_cache,
1067 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
1068 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1069 nc->skb_count = NAPI_SKB_CACHE_HALF;
1073 void __kfree_skb_defer(struct sk_buff *skb)
1075 skb_release_all(skb);
1076 napi_skb_cache_put(skb);
1079 void napi_skb_free_stolen_head(struct sk_buff *skb)
1081 if (unlikely(skb->slow_gro)) {
1088 napi_skb_cache_put(skb);
1091 void napi_consume_skb(struct sk_buff *skb, int budget)
1093 /* Zero budget indicate non-NAPI context called us, like netpoll */
1094 if (unlikely(!budget)) {
1095 dev_consume_skb_any(skb);
1099 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1101 if (!skb_unref(skb))
1104 /* if reaching here SKB is ready to free */
1105 trace_consume_skb(skb);
1107 /* if SKB is a clone, don't handle this case */
1108 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1113 skb_release_all(skb);
1114 napi_skb_cache_put(skb);
1116 EXPORT_SYMBOL(napi_consume_skb);
1118 /* Make sure a field is contained by headers group */
1119 #define CHECK_SKB_FIELD(field) \
1120 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1121 offsetof(struct sk_buff, headers.field)); \
1123 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1125 new->tstamp = old->tstamp;
1126 /* We do not copy old->sk */
1127 new->dev = old->dev;
1128 memcpy(new->cb, old->cb, sizeof(old->cb));
1129 skb_dst_copy(new, old);
1130 __skb_ext_copy(new, old);
1131 __nf_copy(new, old, false);
1133 /* Note : this field could be in the headers group.
1134 * It is not yet because we do not want to have a 16 bit hole
1136 new->queue_mapping = old->queue_mapping;
1138 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1139 CHECK_SKB_FIELD(protocol);
1140 CHECK_SKB_FIELD(csum);
1141 CHECK_SKB_FIELD(hash);
1142 CHECK_SKB_FIELD(priority);
1143 CHECK_SKB_FIELD(skb_iif);
1144 CHECK_SKB_FIELD(vlan_proto);
1145 CHECK_SKB_FIELD(vlan_tci);
1146 CHECK_SKB_FIELD(transport_header);
1147 CHECK_SKB_FIELD(network_header);
1148 CHECK_SKB_FIELD(mac_header);
1149 CHECK_SKB_FIELD(inner_protocol);
1150 CHECK_SKB_FIELD(inner_transport_header);
1151 CHECK_SKB_FIELD(inner_network_header);
1152 CHECK_SKB_FIELD(inner_mac_header);
1153 CHECK_SKB_FIELD(mark);
1154 #ifdef CONFIG_NETWORK_SECMARK
1155 CHECK_SKB_FIELD(secmark);
1157 #ifdef CONFIG_NET_RX_BUSY_POLL
1158 CHECK_SKB_FIELD(napi_id);
1160 CHECK_SKB_FIELD(alloc_cpu);
1162 CHECK_SKB_FIELD(sender_cpu);
1164 #ifdef CONFIG_NET_SCHED
1165 CHECK_SKB_FIELD(tc_index);
1171 * You should not add any new code to this function. Add it to
1172 * __copy_skb_header above instead.
1174 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1176 #define C(x) n->x = skb->x
1178 n->next = n->prev = NULL;
1180 __copy_skb_header(n, skb);
1185 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1191 n->destructor = NULL;
1198 refcount_set(&n->users, 1);
1200 atomic_inc(&(skb_shinfo(skb)->dataref));
1208 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1209 * @first: first sk_buff of the msg
1211 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1215 n = alloc_skb(0, GFP_ATOMIC);
1219 n->len = first->len;
1220 n->data_len = first->len;
1221 n->truesize = first->truesize;
1223 skb_shinfo(n)->frag_list = first;
1225 __copy_skb_header(n, first);
1226 n->destructor = NULL;
1230 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1233 * skb_morph - morph one skb into another
1234 * @dst: the skb to receive the contents
1235 * @src: the skb to supply the contents
1237 * This is identical to skb_clone except that the target skb is
1238 * supplied by the user.
1240 * The target skb is returned upon exit.
1242 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1244 skb_release_all(dst);
1245 return __skb_clone(dst, src);
1247 EXPORT_SYMBOL_GPL(skb_morph);
1249 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1251 unsigned long max_pg, num_pg, new_pg, old_pg;
1252 struct user_struct *user;
1254 if (capable(CAP_IPC_LOCK) || !size)
1257 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1258 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1259 user = mmp->user ? : current_user();
1262 old_pg = atomic_long_read(&user->locked_vm);
1263 new_pg = old_pg + num_pg;
1264 if (new_pg > max_pg)
1266 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1270 mmp->user = get_uid(user);
1271 mmp->num_pg = num_pg;
1273 mmp->num_pg += num_pg;
1278 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1280 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1283 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1284 free_uid(mmp->user);
1287 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1289 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1291 struct ubuf_info_msgzc *uarg;
1292 struct sk_buff *skb;
1294 WARN_ON_ONCE(!in_task());
1296 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1300 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1301 uarg = (void *)skb->cb;
1302 uarg->mmp.user = NULL;
1304 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1309 uarg->ubuf.callback = msg_zerocopy_callback;
1310 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1312 uarg->bytelen = size;
1314 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1315 refcount_set(&uarg->ubuf.refcnt, 1);
1321 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1323 return container_of((void *)uarg, struct sk_buff, cb);
1326 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1327 struct ubuf_info *uarg)
1330 struct ubuf_info_msgzc *uarg_zc;
1331 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1334 /* there might be non MSG_ZEROCOPY users */
1335 if (uarg->callback != msg_zerocopy_callback)
1338 /* realloc only when socket is locked (TCP, UDP cork),
1339 * so uarg->len and sk_zckey access is serialized
1341 if (!sock_owned_by_user(sk)) {
1346 uarg_zc = uarg_to_msgzc(uarg);
1347 bytelen = uarg_zc->bytelen + size;
1348 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1349 /* TCP can create new skb to attach new uarg */
1350 if (sk->sk_type == SOCK_STREAM)
1355 next = (u32)atomic_read(&sk->sk_zckey);
1356 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1357 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1360 uarg_zc->bytelen = bytelen;
1361 atomic_set(&sk->sk_zckey, ++next);
1363 /* no extra ref when appending to datagram (MSG_MORE) */
1364 if (sk->sk_type == SOCK_STREAM)
1365 net_zcopy_get(uarg);
1372 return msg_zerocopy_alloc(sk, size);
1374 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1376 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1378 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1382 old_lo = serr->ee.ee_info;
1383 old_hi = serr->ee.ee_data;
1384 sum_len = old_hi - old_lo + 1ULL + len;
1386 if (sum_len >= (1ULL << 32))
1389 if (lo != old_hi + 1)
1392 serr->ee.ee_data += len;
1396 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1398 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1399 struct sock_exterr_skb *serr;
1400 struct sock *sk = skb->sk;
1401 struct sk_buff_head *q;
1402 unsigned long flags;
1407 mm_unaccount_pinned_pages(&uarg->mmp);
1409 /* if !len, there was only 1 call, and it was aborted
1410 * so do not queue a completion notification
1412 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1417 hi = uarg->id + len - 1;
1418 is_zerocopy = uarg->zerocopy;
1420 serr = SKB_EXT_ERR(skb);
1421 memset(serr, 0, sizeof(*serr));
1422 serr->ee.ee_errno = 0;
1423 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1424 serr->ee.ee_data = hi;
1425 serr->ee.ee_info = lo;
1427 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1429 q = &sk->sk_error_queue;
1430 spin_lock_irqsave(&q->lock, flags);
1431 tail = skb_peek_tail(q);
1432 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1433 !skb_zerocopy_notify_extend(tail, lo, len)) {
1434 __skb_queue_tail(q, skb);
1437 spin_unlock_irqrestore(&q->lock, flags);
1439 sk_error_report(sk);
1446 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1449 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1451 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1453 if (refcount_dec_and_test(&uarg->refcnt))
1454 __msg_zerocopy_callback(uarg_zc);
1456 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1458 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1460 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1462 atomic_dec(&sk->sk_zckey);
1463 uarg_to_msgzc(uarg)->len--;
1466 msg_zerocopy_callback(NULL, uarg, true);
1468 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1470 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1471 struct msghdr *msg, int len,
1472 struct ubuf_info *uarg)
1474 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1475 int err, orig_len = skb->len;
1477 /* An skb can only point to one uarg. This edge case happens when
1478 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1480 if (orig_uarg && uarg != orig_uarg)
1483 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1484 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1485 struct sock *save_sk = skb->sk;
1487 /* Streams do not free skb on error. Reset to prev state. */
1488 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1490 ___pskb_trim(skb, orig_len);
1495 skb_zcopy_set(skb, uarg, NULL);
1496 return skb->len - orig_len;
1498 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1500 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1504 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1505 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1506 skb_frag_ref(skb, i);
1508 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1510 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1513 if (skb_zcopy(orig)) {
1514 if (skb_zcopy(nskb)) {
1515 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1520 if (skb_uarg(nskb) == skb_uarg(orig))
1522 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1525 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1531 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1532 * @skb: the skb to modify
1533 * @gfp_mask: allocation priority
1535 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1536 * It will copy all frags into kernel and drop the reference
1537 * to userspace pages.
1539 * If this function is called from an interrupt gfp_mask() must be
1542 * Returns 0 on success or a negative error code on failure
1543 * to allocate kernel memory to copy to.
1545 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1547 int num_frags = skb_shinfo(skb)->nr_frags;
1548 struct page *page, *head = NULL;
1549 int i, order, psize, new_frags;
1552 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1558 /* We might have to allocate high order pages, so compute what minimum
1559 * page order is needed.
1562 while ((PAGE_SIZE << order) * MAX_SKB_FRAGS < __skb_pagelen(skb))
1564 psize = (PAGE_SIZE << order);
1566 new_frags = (__skb_pagelen(skb) + psize - 1) >> (PAGE_SHIFT + order);
1567 for (i = 0; i < new_frags; i++) {
1568 page = alloc_pages(gfp_mask | __GFP_COMP, order);
1571 struct page *next = (struct page *)page_private(head);
1577 set_page_private(page, (unsigned long)head);
1583 for (i = 0; i < num_frags; i++) {
1584 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1585 u32 p_off, p_len, copied;
1589 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1590 p, p_off, p_len, copied) {
1592 vaddr = kmap_atomic(p);
1594 while (done < p_len) {
1595 if (d_off == psize) {
1597 page = (struct page *)page_private(page);
1599 copy = min_t(u32, psize - d_off, p_len - done);
1600 memcpy(page_address(page) + d_off,
1601 vaddr + p_off + done, copy);
1605 kunmap_atomic(vaddr);
1609 /* skb frags release userspace buffers */
1610 for (i = 0; i < num_frags; i++)
1611 skb_frag_unref(skb, i);
1613 /* skb frags point to kernel buffers */
1614 for (i = 0; i < new_frags - 1; i++) {
1615 __skb_fill_page_desc(skb, i, head, 0, psize);
1616 head = (struct page *)page_private(head);
1618 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1619 skb_shinfo(skb)->nr_frags = new_frags;
1622 skb_zcopy_clear(skb, false);
1625 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1628 * skb_clone - duplicate an sk_buff
1629 * @skb: buffer to clone
1630 * @gfp_mask: allocation priority
1632 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1633 * copies share the same packet data but not structure. The new
1634 * buffer has a reference count of 1. If the allocation fails the
1635 * function returns %NULL otherwise the new buffer is returned.
1637 * If this function is called from an interrupt gfp_mask() must be
1641 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1643 struct sk_buff_fclones *fclones = container_of(skb,
1644 struct sk_buff_fclones,
1648 if (skb_orphan_frags(skb, gfp_mask))
1651 if (skb->fclone == SKB_FCLONE_ORIG &&
1652 refcount_read(&fclones->fclone_ref) == 1) {
1654 refcount_set(&fclones->fclone_ref, 2);
1655 n->fclone = SKB_FCLONE_CLONE;
1657 if (skb_pfmemalloc(skb))
1658 gfp_mask |= __GFP_MEMALLOC;
1660 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1664 n->fclone = SKB_FCLONE_UNAVAILABLE;
1667 return __skb_clone(n, skb);
1669 EXPORT_SYMBOL(skb_clone);
1671 void skb_headers_offset_update(struct sk_buff *skb, int off)
1673 /* Only adjust this if it actually is csum_start rather than csum */
1674 if (skb->ip_summed == CHECKSUM_PARTIAL)
1675 skb->csum_start += off;
1676 /* {transport,network,mac}_header and tail are relative to skb->head */
1677 skb->transport_header += off;
1678 skb->network_header += off;
1679 if (skb_mac_header_was_set(skb))
1680 skb->mac_header += off;
1681 skb->inner_transport_header += off;
1682 skb->inner_network_header += off;
1683 skb->inner_mac_header += off;
1685 EXPORT_SYMBOL(skb_headers_offset_update);
1687 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1689 __copy_skb_header(new, old);
1691 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1692 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1693 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1695 EXPORT_SYMBOL(skb_copy_header);
1697 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1699 if (skb_pfmemalloc(skb))
1700 return SKB_ALLOC_RX;
1705 * skb_copy - create private copy of an sk_buff
1706 * @skb: buffer to copy
1707 * @gfp_mask: allocation priority
1709 * Make a copy of both an &sk_buff and its data. This is used when the
1710 * caller wishes to modify the data and needs a private copy of the
1711 * data to alter. Returns %NULL on failure or the pointer to the buffer
1712 * on success. The returned buffer has a reference count of 1.
1714 * As by-product this function converts non-linear &sk_buff to linear
1715 * one, so that &sk_buff becomes completely private and caller is allowed
1716 * to modify all the data of returned buffer. This means that this
1717 * function is not recommended for use in circumstances when only
1718 * header is going to be modified. Use pskb_copy() instead.
1721 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1723 int headerlen = skb_headroom(skb);
1724 unsigned int size = skb_end_offset(skb) + skb->data_len;
1725 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1726 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1731 /* Set the data pointer */
1732 skb_reserve(n, headerlen);
1733 /* Set the tail pointer and length */
1734 skb_put(n, skb->len);
1736 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1738 skb_copy_header(n, skb);
1741 EXPORT_SYMBOL(skb_copy);
1744 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1745 * @skb: buffer to copy
1746 * @headroom: headroom of new skb
1747 * @gfp_mask: allocation priority
1748 * @fclone: if true allocate the copy of the skb from the fclone
1749 * cache instead of the head cache; it is recommended to set this
1750 * to true for the cases where the copy will likely be cloned
1752 * Make a copy of both an &sk_buff and part of its data, located
1753 * in header. Fragmented data remain shared. This is used when
1754 * the caller wishes to modify only header of &sk_buff and needs
1755 * private copy of the header to alter. Returns %NULL on failure
1756 * or the pointer to the buffer on success.
1757 * The returned buffer has a reference count of 1.
1760 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1761 gfp_t gfp_mask, bool fclone)
1763 unsigned int size = skb_headlen(skb) + headroom;
1764 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1765 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1770 /* Set the data pointer */
1771 skb_reserve(n, headroom);
1772 /* Set the tail pointer and length */
1773 skb_put(n, skb_headlen(skb));
1774 /* Copy the bytes */
1775 skb_copy_from_linear_data(skb, n->data, n->len);
1777 n->truesize += skb->data_len;
1778 n->data_len = skb->data_len;
1781 if (skb_shinfo(skb)->nr_frags) {
1784 if (skb_orphan_frags(skb, gfp_mask) ||
1785 skb_zerocopy_clone(n, skb, gfp_mask)) {
1790 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1791 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1792 skb_frag_ref(skb, i);
1794 skb_shinfo(n)->nr_frags = i;
1797 if (skb_has_frag_list(skb)) {
1798 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1799 skb_clone_fraglist(n);
1802 skb_copy_header(n, skb);
1806 EXPORT_SYMBOL(__pskb_copy_fclone);
1809 * pskb_expand_head - reallocate header of &sk_buff
1810 * @skb: buffer to reallocate
1811 * @nhead: room to add at head
1812 * @ntail: room to add at tail
1813 * @gfp_mask: allocation priority
1815 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1816 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1817 * reference count of 1. Returns zero in the case of success or error,
1818 * if expansion failed. In the last case, &sk_buff is not changed.
1820 * All the pointers pointing into skb header may change and must be
1821 * reloaded after call to this function.
1824 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1827 unsigned int osize = skb_end_offset(skb);
1828 unsigned int size = osize + nhead + ntail;
1835 BUG_ON(skb_shared(skb));
1837 skb_zcopy_downgrade_managed(skb);
1839 if (skb_pfmemalloc(skb))
1840 gfp_mask |= __GFP_MEMALLOC;
1842 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
1845 size = SKB_WITH_OVERHEAD(size);
1847 /* Copy only real data... and, alas, header. This should be
1848 * optimized for the cases when header is void.
1850 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1852 memcpy((struct skb_shared_info *)(data + size),
1854 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1857 * if shinfo is shared we must drop the old head gracefully, but if it
1858 * is not we can just drop the old head and let the existing refcount
1859 * be since all we did is relocate the values
1861 if (skb_cloned(skb)) {
1862 if (skb_orphan_frags(skb, gfp_mask))
1865 refcount_inc(&skb_uarg(skb)->refcnt);
1866 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1867 skb_frag_ref(skb, i);
1869 if (skb_has_frag_list(skb))
1870 skb_clone_fraglist(skb);
1872 skb_release_data(skb);
1876 off = (data + nhead) - skb->head;
1882 skb_set_end_offset(skb, size);
1883 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1887 skb_headers_offset_update(skb, nhead);
1891 atomic_set(&skb_shinfo(skb)->dataref, 1);
1893 skb_metadata_clear(skb);
1895 /* It is not generally safe to change skb->truesize.
1896 * For the moment, we really care of rx path, or
1897 * when skb is orphaned (not attached to a socket).
1899 if (!skb->sk || skb->destructor == sock_edemux)
1900 skb->truesize += size - osize;
1909 EXPORT_SYMBOL(pskb_expand_head);
1911 /* Make private copy of skb with writable head and some headroom */
1913 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1915 struct sk_buff *skb2;
1916 int delta = headroom - skb_headroom(skb);
1919 skb2 = pskb_copy(skb, GFP_ATOMIC);
1921 skb2 = skb_clone(skb, GFP_ATOMIC);
1922 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1930 EXPORT_SYMBOL(skb_realloc_headroom);
1932 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1934 unsigned int saved_end_offset, saved_truesize;
1935 struct skb_shared_info *shinfo;
1938 saved_end_offset = skb_end_offset(skb);
1939 saved_truesize = skb->truesize;
1941 res = pskb_expand_head(skb, 0, 0, pri);
1945 skb->truesize = saved_truesize;
1947 if (likely(skb_end_offset(skb) == saved_end_offset))
1950 shinfo = skb_shinfo(skb);
1952 /* We are about to change back skb->end,
1953 * we need to move skb_shinfo() to its new location.
1955 memmove(skb->head + saved_end_offset,
1957 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1959 skb_set_end_offset(skb, saved_end_offset);
1965 * skb_expand_head - reallocate header of &sk_buff
1966 * @skb: buffer to reallocate
1967 * @headroom: needed headroom
1969 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1970 * if possible; copies skb->sk to new skb as needed
1971 * and frees original skb in case of failures.
1973 * It expect increased headroom and generates warning otherwise.
1976 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1978 int delta = headroom - skb_headroom(skb);
1979 int osize = skb_end_offset(skb);
1980 struct sock *sk = skb->sk;
1982 if (WARN_ONCE(delta <= 0,
1983 "%s is expecting an increase in the headroom", __func__))
1986 delta = SKB_DATA_ALIGN(delta);
1987 /* pskb_expand_head() might crash, if skb is shared. */
1988 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1989 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1991 if (unlikely(!nskb))
1995 skb_set_owner_w(nskb, sk);
1999 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2002 if (sk && is_skb_wmem(skb)) {
2003 delta = skb_end_offset(skb) - osize;
2004 refcount_add(delta, &sk->sk_wmem_alloc);
2005 skb->truesize += delta;
2013 EXPORT_SYMBOL(skb_expand_head);
2016 * skb_copy_expand - copy and expand sk_buff
2017 * @skb: buffer to copy
2018 * @newheadroom: new free bytes at head
2019 * @newtailroom: new free bytes at tail
2020 * @gfp_mask: allocation priority
2022 * Make a copy of both an &sk_buff and its data and while doing so
2023 * allocate additional space.
2025 * This is used when the caller wishes to modify the data and needs a
2026 * private copy of the data to alter as well as more space for new fields.
2027 * Returns %NULL on failure or the pointer to the buffer
2028 * on success. The returned buffer has a reference count of 1.
2030 * You must pass %GFP_ATOMIC as the allocation priority if this function
2031 * is called from an interrupt.
2033 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2034 int newheadroom, int newtailroom,
2038 * Allocate the copy buffer
2040 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2041 gfp_mask, skb_alloc_rx_flag(skb),
2043 int oldheadroom = skb_headroom(skb);
2044 int head_copy_len, head_copy_off;
2049 skb_reserve(n, newheadroom);
2051 /* Set the tail pointer and length */
2052 skb_put(n, skb->len);
2054 head_copy_len = oldheadroom;
2056 if (newheadroom <= head_copy_len)
2057 head_copy_len = newheadroom;
2059 head_copy_off = newheadroom - head_copy_len;
2061 /* Copy the linear header and data. */
2062 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2063 skb->len + head_copy_len));
2065 skb_copy_header(n, skb);
2067 skb_headers_offset_update(n, newheadroom - oldheadroom);
2071 EXPORT_SYMBOL(skb_copy_expand);
2074 * __skb_pad - zero pad the tail of an skb
2075 * @skb: buffer to pad
2076 * @pad: space to pad
2077 * @free_on_error: free buffer on error
2079 * Ensure that a buffer is followed by a padding area that is zero
2080 * filled. Used by network drivers which may DMA or transfer data
2081 * beyond the buffer end onto the wire.
2083 * May return error in out of memory cases. The skb is freed on error
2084 * if @free_on_error is true.
2087 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2092 /* If the skbuff is non linear tailroom is always zero.. */
2093 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2094 memset(skb->data+skb->len, 0, pad);
2098 ntail = skb->data_len + pad - (skb->end - skb->tail);
2099 if (likely(skb_cloned(skb) || ntail > 0)) {
2100 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2105 /* FIXME: The use of this function with non-linear skb's really needs
2108 err = skb_linearize(skb);
2112 memset(skb->data + skb->len, 0, pad);
2120 EXPORT_SYMBOL(__skb_pad);
2123 * pskb_put - add data to the tail of a potentially fragmented buffer
2124 * @skb: start of the buffer to use
2125 * @tail: tail fragment of the buffer to use
2126 * @len: amount of data to add
2128 * This function extends the used data area of the potentially
2129 * fragmented buffer. @tail must be the last fragment of @skb -- or
2130 * @skb itself. If this would exceed the total buffer size the kernel
2131 * will panic. A pointer to the first byte of the extra data is
2135 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2138 skb->data_len += len;
2141 return skb_put(tail, len);
2143 EXPORT_SYMBOL_GPL(pskb_put);
2146 * skb_put - add data to a buffer
2147 * @skb: buffer to use
2148 * @len: amount of data to add
2150 * This function extends the used data area of the buffer. If this would
2151 * exceed the total buffer size the kernel will panic. A pointer to the
2152 * first byte of the extra data is returned.
2154 void *skb_put(struct sk_buff *skb, unsigned int len)
2156 void *tmp = skb_tail_pointer(skb);
2157 SKB_LINEAR_ASSERT(skb);
2160 if (unlikely(skb->tail > skb->end))
2161 skb_over_panic(skb, len, __builtin_return_address(0));
2164 EXPORT_SYMBOL(skb_put);
2167 * skb_push - add data to the start of a buffer
2168 * @skb: buffer to use
2169 * @len: amount of data to add
2171 * This function extends the used data area of the buffer at the buffer
2172 * start. If this would exceed the total buffer headroom the kernel will
2173 * panic. A pointer to the first byte of the extra data is returned.
2175 void *skb_push(struct sk_buff *skb, unsigned int len)
2179 if (unlikely(skb->data < skb->head))
2180 skb_under_panic(skb, len, __builtin_return_address(0));
2183 EXPORT_SYMBOL(skb_push);
2186 * skb_pull - remove data from the start of a buffer
2187 * @skb: buffer to use
2188 * @len: amount of data to remove
2190 * This function removes data from the start of a buffer, returning
2191 * the memory to the headroom. A pointer to the next data in the buffer
2192 * is returned. Once the data has been pulled future pushes will overwrite
2195 void *skb_pull(struct sk_buff *skb, unsigned int len)
2197 return skb_pull_inline(skb, len);
2199 EXPORT_SYMBOL(skb_pull);
2202 * skb_pull_data - remove data from the start of a buffer returning its
2203 * original position.
2204 * @skb: buffer to use
2205 * @len: amount of data to remove
2207 * This function removes data from the start of a buffer, returning
2208 * the memory to the headroom. A pointer to the original data in the buffer
2209 * is returned after checking if there is enough data to pull. Once the
2210 * data has been pulled future pushes will overwrite the old data.
2212 void *skb_pull_data(struct sk_buff *skb, size_t len)
2214 void *data = skb->data;
2223 EXPORT_SYMBOL(skb_pull_data);
2226 * skb_trim - remove end from a buffer
2227 * @skb: buffer to alter
2230 * Cut the length of a buffer down by removing data from the tail. If
2231 * the buffer is already under the length specified it is not modified.
2232 * The skb must be linear.
2234 void skb_trim(struct sk_buff *skb, unsigned int len)
2237 __skb_trim(skb, len);
2239 EXPORT_SYMBOL(skb_trim);
2241 /* Trims skb to length len. It can change skb pointers.
2244 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2246 struct sk_buff **fragp;
2247 struct sk_buff *frag;
2248 int offset = skb_headlen(skb);
2249 int nfrags = skb_shinfo(skb)->nr_frags;
2253 if (skb_cloned(skb) &&
2254 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2261 for (; i < nfrags; i++) {
2262 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2269 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2272 skb_shinfo(skb)->nr_frags = i;
2274 for (; i < nfrags; i++)
2275 skb_frag_unref(skb, i);
2277 if (skb_has_frag_list(skb))
2278 skb_drop_fraglist(skb);
2282 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2283 fragp = &frag->next) {
2284 int end = offset + frag->len;
2286 if (skb_shared(frag)) {
2287 struct sk_buff *nfrag;
2289 nfrag = skb_clone(frag, GFP_ATOMIC);
2290 if (unlikely(!nfrag))
2293 nfrag->next = frag->next;
2305 unlikely((err = pskb_trim(frag, len - offset))))
2309 skb_drop_list(&frag->next);
2314 if (len > skb_headlen(skb)) {
2315 skb->data_len -= skb->len - len;
2320 skb_set_tail_pointer(skb, len);
2323 if (!skb->sk || skb->destructor == sock_edemux)
2327 EXPORT_SYMBOL(___pskb_trim);
2329 /* Note : use pskb_trim_rcsum() instead of calling this directly
2331 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2333 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2334 int delta = skb->len - len;
2336 skb->csum = csum_block_sub(skb->csum,
2337 skb_checksum(skb, len, delta, 0),
2339 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2340 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2341 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2343 if (offset + sizeof(__sum16) > hdlen)
2346 return __pskb_trim(skb, len);
2348 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2351 * __pskb_pull_tail - advance tail of skb header
2352 * @skb: buffer to reallocate
2353 * @delta: number of bytes to advance tail
2355 * The function makes a sense only on a fragmented &sk_buff,
2356 * it expands header moving its tail forward and copying necessary
2357 * data from fragmented part.
2359 * &sk_buff MUST have reference count of 1.
2361 * Returns %NULL (and &sk_buff does not change) if pull failed
2362 * or value of new tail of skb in the case of success.
2364 * All the pointers pointing into skb header may change and must be
2365 * reloaded after call to this function.
2368 /* Moves tail of skb head forward, copying data from fragmented part,
2369 * when it is necessary.
2370 * 1. It may fail due to malloc failure.
2371 * 2. It may change skb pointers.
2373 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2375 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2377 /* If skb has not enough free space at tail, get new one
2378 * plus 128 bytes for future expansions. If we have enough
2379 * room at tail, reallocate without expansion only if skb is cloned.
2381 int i, k, eat = (skb->tail + delta) - skb->end;
2383 if (eat > 0 || skb_cloned(skb)) {
2384 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2389 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2390 skb_tail_pointer(skb), delta));
2392 /* Optimization: no fragments, no reasons to preestimate
2393 * size of pulled pages. Superb.
2395 if (!skb_has_frag_list(skb))
2398 /* Estimate size of pulled pages. */
2400 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2401 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2408 /* If we need update frag list, we are in troubles.
2409 * Certainly, it is possible to add an offset to skb data,
2410 * but taking into account that pulling is expected to
2411 * be very rare operation, it is worth to fight against
2412 * further bloating skb head and crucify ourselves here instead.
2413 * Pure masohism, indeed. 8)8)
2416 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2417 struct sk_buff *clone = NULL;
2418 struct sk_buff *insp = NULL;
2421 if (list->len <= eat) {
2422 /* Eaten as whole. */
2427 /* Eaten partially. */
2428 if (skb_is_gso(skb) && !list->head_frag &&
2430 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2432 if (skb_shared(list)) {
2433 /* Sucks! We need to fork list. :-( */
2434 clone = skb_clone(list, GFP_ATOMIC);
2440 /* This may be pulled without
2444 if (!pskb_pull(list, eat)) {
2452 /* Free pulled out fragments. */
2453 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2454 skb_shinfo(skb)->frag_list = list->next;
2457 /* And insert new clone at head. */
2460 skb_shinfo(skb)->frag_list = clone;
2463 /* Success! Now we may commit changes to skb data. */
2468 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2469 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2472 skb_frag_unref(skb, i);
2475 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2477 *frag = skb_shinfo(skb)->frags[i];
2479 skb_frag_off_add(frag, eat);
2480 skb_frag_size_sub(frag, eat);
2488 skb_shinfo(skb)->nr_frags = k;
2492 skb->data_len -= delta;
2495 skb_zcopy_clear(skb, false);
2497 return skb_tail_pointer(skb);
2499 EXPORT_SYMBOL(__pskb_pull_tail);
2502 * skb_copy_bits - copy bits from skb to kernel buffer
2504 * @offset: offset in source
2505 * @to: destination buffer
2506 * @len: number of bytes to copy
2508 * Copy the specified number of bytes from the source skb to the
2509 * destination buffer.
2512 * If its prototype is ever changed,
2513 * check arch/{*}/net/{*}.S files,
2514 * since it is called from BPF assembly code.
2516 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2518 int start = skb_headlen(skb);
2519 struct sk_buff *frag_iter;
2522 if (offset > (int)skb->len - len)
2526 if ((copy = start - offset) > 0) {
2529 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2530 if ((len -= copy) == 0)
2536 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2538 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2540 WARN_ON(start > offset + len);
2542 end = start + skb_frag_size(f);
2543 if ((copy = end - offset) > 0) {
2544 u32 p_off, p_len, copied;
2551 skb_frag_foreach_page(f,
2552 skb_frag_off(f) + offset - start,
2553 copy, p, p_off, p_len, copied) {
2554 vaddr = kmap_atomic(p);
2555 memcpy(to + copied, vaddr + p_off, p_len);
2556 kunmap_atomic(vaddr);
2559 if ((len -= copy) == 0)
2567 skb_walk_frags(skb, frag_iter) {
2570 WARN_ON(start > offset + len);
2572 end = start + frag_iter->len;
2573 if ((copy = end - offset) > 0) {
2576 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2578 if ((len -= copy) == 0)
2592 EXPORT_SYMBOL(skb_copy_bits);
2595 * Callback from splice_to_pipe(), if we need to release some pages
2596 * at the end of the spd in case we error'ed out in filling the pipe.
2598 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2600 put_page(spd->pages[i]);
2603 static struct page *linear_to_page(struct page *page, unsigned int *len,
2604 unsigned int *offset,
2607 struct page_frag *pfrag = sk_page_frag(sk);
2609 if (!sk_page_frag_refill(sk, pfrag))
2612 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2614 memcpy(page_address(pfrag->page) + pfrag->offset,
2615 page_address(page) + *offset, *len);
2616 *offset = pfrag->offset;
2617 pfrag->offset += *len;
2622 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2624 unsigned int offset)
2626 return spd->nr_pages &&
2627 spd->pages[spd->nr_pages - 1] == page &&
2628 (spd->partial[spd->nr_pages - 1].offset +
2629 spd->partial[spd->nr_pages - 1].len == offset);
2633 * Fill page/offset/length into spd, if it can hold more pages.
2635 static bool spd_fill_page(struct splice_pipe_desc *spd,
2636 struct pipe_inode_info *pipe, struct page *page,
2637 unsigned int *len, unsigned int offset,
2641 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2645 page = linear_to_page(page, len, &offset, sk);
2649 if (spd_can_coalesce(spd, page, offset)) {
2650 spd->partial[spd->nr_pages - 1].len += *len;
2654 spd->pages[spd->nr_pages] = page;
2655 spd->partial[spd->nr_pages].len = *len;
2656 spd->partial[spd->nr_pages].offset = offset;
2662 static bool __splice_segment(struct page *page, unsigned int poff,
2663 unsigned int plen, unsigned int *off,
2665 struct splice_pipe_desc *spd, bool linear,
2667 struct pipe_inode_info *pipe)
2672 /* skip this segment if already processed */
2678 /* ignore any bits we already processed */
2684 unsigned int flen = min(*len, plen);
2686 if (spd_fill_page(spd, pipe, page, &flen, poff,
2692 } while (*len && plen);
2698 * Map linear and fragment data from the skb to spd. It reports true if the
2699 * pipe is full or if we already spliced the requested length.
2701 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2702 unsigned int *offset, unsigned int *len,
2703 struct splice_pipe_desc *spd, struct sock *sk)
2706 struct sk_buff *iter;
2708 /* map the linear part :
2709 * If skb->head_frag is set, this 'linear' part is backed by a
2710 * fragment, and if the head is not shared with any clones then
2711 * we can avoid a copy since we own the head portion of this page.
2713 if (__splice_segment(virt_to_page(skb->data),
2714 (unsigned long) skb->data & (PAGE_SIZE - 1),
2717 skb_head_is_locked(skb),
2722 * then map the fragments
2724 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2725 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2727 if (__splice_segment(skb_frag_page(f),
2728 skb_frag_off(f), skb_frag_size(f),
2729 offset, len, spd, false, sk, pipe))
2733 skb_walk_frags(skb, iter) {
2734 if (*offset >= iter->len) {
2735 *offset -= iter->len;
2738 /* __skb_splice_bits() only fails if the output has no room
2739 * left, so no point in going over the frag_list for the error
2742 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2750 * Map data from the skb to a pipe. Should handle both the linear part,
2751 * the fragments, and the frag list.
2753 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2754 struct pipe_inode_info *pipe, unsigned int tlen,
2757 struct partial_page partial[MAX_SKB_FRAGS];
2758 struct page *pages[MAX_SKB_FRAGS];
2759 struct splice_pipe_desc spd = {
2762 .nr_pages_max = MAX_SKB_FRAGS,
2763 .ops = &nosteal_pipe_buf_ops,
2764 .spd_release = sock_spd_release,
2768 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2771 ret = splice_to_pipe(pipe, &spd);
2775 EXPORT_SYMBOL_GPL(skb_splice_bits);
2777 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2778 struct kvec *vec, size_t num, size_t size)
2780 struct socket *sock = sk->sk_socket;
2784 return kernel_sendmsg(sock, msg, vec, num, size);
2787 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2788 size_t size, int flags)
2790 struct socket *sock = sk->sk_socket;
2794 return kernel_sendpage(sock, page, offset, size, flags);
2797 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2798 struct kvec *vec, size_t num, size_t size);
2799 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2800 size_t size, int flags);
2801 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2802 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2804 unsigned int orig_len = len;
2805 struct sk_buff *head = skb;
2806 unsigned short fragidx;
2811 /* Deal with head data */
2812 while (offset < skb_headlen(skb) && len) {
2816 slen = min_t(int, len, skb_headlen(skb) - offset);
2817 kv.iov_base = skb->data + offset;
2819 memset(&msg, 0, sizeof(msg));
2820 msg.msg_flags = MSG_DONTWAIT;
2822 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2823 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2831 /* All the data was skb head? */
2835 /* Make offset relative to start of frags */
2836 offset -= skb_headlen(skb);
2838 /* Find where we are in frag list */
2839 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2840 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2842 if (offset < skb_frag_size(frag))
2845 offset -= skb_frag_size(frag);
2848 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2849 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2851 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2854 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2855 sendpage_unlocked, sk,
2856 skb_frag_page(frag),
2857 skb_frag_off(frag) + offset,
2858 slen, MSG_DONTWAIT);
2871 /* Process any frag lists */
2874 if (skb_has_frag_list(skb)) {
2875 skb = skb_shinfo(skb)->frag_list;
2878 } else if (skb->next) {
2885 return orig_len - len;
2888 return orig_len == len ? ret : orig_len - len;
2891 /* Send skb data on a socket. Socket must be locked. */
2892 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2895 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2896 kernel_sendpage_locked);
2898 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2900 /* Send skb data on a socket. Socket must be unlocked. */
2901 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2903 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2908 * skb_store_bits - store bits from kernel buffer to skb
2909 * @skb: destination buffer
2910 * @offset: offset in destination
2911 * @from: source buffer
2912 * @len: number of bytes to copy
2914 * Copy the specified number of bytes from the source buffer to the
2915 * destination skb. This function handles all the messy bits of
2916 * traversing fragment lists and such.
2919 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2921 int start = skb_headlen(skb);
2922 struct sk_buff *frag_iter;
2925 if (offset > (int)skb->len - len)
2928 if ((copy = start - offset) > 0) {
2931 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2932 if ((len -= copy) == 0)
2938 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2939 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2942 WARN_ON(start > offset + len);
2944 end = start + skb_frag_size(frag);
2945 if ((copy = end - offset) > 0) {
2946 u32 p_off, p_len, copied;
2953 skb_frag_foreach_page(frag,
2954 skb_frag_off(frag) + offset - start,
2955 copy, p, p_off, p_len, copied) {
2956 vaddr = kmap_atomic(p);
2957 memcpy(vaddr + p_off, from + copied, p_len);
2958 kunmap_atomic(vaddr);
2961 if ((len -= copy) == 0)
2969 skb_walk_frags(skb, frag_iter) {
2972 WARN_ON(start > offset + len);
2974 end = start + frag_iter->len;
2975 if ((copy = end - offset) > 0) {
2978 if (skb_store_bits(frag_iter, offset - start,
2981 if ((len -= copy) == 0)
2994 EXPORT_SYMBOL(skb_store_bits);
2996 /* Checksum skb data. */
2997 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2998 __wsum csum, const struct skb_checksum_ops *ops)
3000 int start = skb_headlen(skb);
3001 int i, copy = start - offset;
3002 struct sk_buff *frag_iter;
3005 /* Checksum header. */
3009 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3010 skb->data + offset, copy, csum);
3011 if ((len -= copy) == 0)
3017 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3019 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3021 WARN_ON(start > offset + len);
3023 end = start + skb_frag_size(frag);
3024 if ((copy = end - offset) > 0) {
3025 u32 p_off, p_len, copied;
3033 skb_frag_foreach_page(frag,
3034 skb_frag_off(frag) + offset - start,
3035 copy, p, p_off, p_len, copied) {
3036 vaddr = kmap_atomic(p);
3037 csum2 = INDIRECT_CALL_1(ops->update,
3039 vaddr + p_off, p_len, 0);
3040 kunmap_atomic(vaddr);
3041 csum = INDIRECT_CALL_1(ops->combine,
3042 csum_block_add_ext, csum,
3054 skb_walk_frags(skb, frag_iter) {
3057 WARN_ON(start > offset + len);
3059 end = start + frag_iter->len;
3060 if ((copy = end - offset) > 0) {
3064 csum2 = __skb_checksum(frag_iter, offset - start,
3066 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3067 csum, csum2, pos, copy);
3068 if ((len -= copy) == 0)
3079 EXPORT_SYMBOL(__skb_checksum);
3081 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3082 int len, __wsum csum)
3084 const struct skb_checksum_ops ops = {
3085 .update = csum_partial_ext,
3086 .combine = csum_block_add_ext,
3089 return __skb_checksum(skb, offset, len, csum, &ops);
3091 EXPORT_SYMBOL(skb_checksum);
3093 /* Both of above in one bottle. */
3095 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3098 int start = skb_headlen(skb);
3099 int i, copy = start - offset;
3100 struct sk_buff *frag_iter;
3108 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3110 if ((len -= copy) == 0)
3117 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3120 WARN_ON(start > offset + len);
3122 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3123 if ((copy = end - offset) > 0) {
3124 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
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 = csum_partial_copy_nocheck(vaddr + p_off,
3140 kunmap_atomic(vaddr);
3141 csum = csum_block_add(csum, csum2, pos);
3153 skb_walk_frags(skb, frag_iter) {
3157 WARN_ON(start > offset + len);
3159 end = start + frag_iter->len;
3160 if ((copy = end - offset) > 0) {
3163 csum2 = skb_copy_and_csum_bits(frag_iter,
3166 csum = csum_block_add(csum, csum2, pos);
3167 if ((len -= copy) == 0)
3178 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3180 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3184 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3185 /* See comments in __skb_checksum_complete(). */
3187 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3188 !skb->csum_complete_sw)
3189 netdev_rx_csum_fault(skb->dev, skb);
3191 if (!skb_shared(skb))
3192 skb->csum_valid = !sum;
3195 EXPORT_SYMBOL(__skb_checksum_complete_head);
3197 /* This function assumes skb->csum already holds pseudo header's checksum,
3198 * which has been changed from the hardware checksum, for example, by
3199 * __skb_checksum_validate_complete(). And, the original skb->csum must
3200 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3202 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3203 * zero. The new checksum is stored back into skb->csum unless the skb is
3206 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3211 csum = skb_checksum(skb, 0, skb->len, 0);
3213 sum = csum_fold(csum_add(skb->csum, csum));
3214 /* This check is inverted, because we already knew the hardware
3215 * checksum is invalid before calling this function. So, if the
3216 * re-computed checksum is valid instead, then we have a mismatch
3217 * between the original skb->csum and skb_checksum(). This means either
3218 * the original hardware checksum is incorrect or we screw up skb->csum
3219 * when moving skb->data around.
3222 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3223 !skb->csum_complete_sw)
3224 netdev_rx_csum_fault(skb->dev, skb);
3227 if (!skb_shared(skb)) {
3228 /* Save full packet checksum */
3230 skb->ip_summed = CHECKSUM_COMPLETE;
3231 skb->csum_complete_sw = 1;
3232 skb->csum_valid = !sum;
3237 EXPORT_SYMBOL(__skb_checksum_complete);
3239 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3241 net_warn_ratelimited(
3242 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3247 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3248 int offset, int len)
3250 net_warn_ratelimited(
3251 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3256 static const struct skb_checksum_ops default_crc32c_ops = {
3257 .update = warn_crc32c_csum_update,
3258 .combine = warn_crc32c_csum_combine,
3261 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3262 &default_crc32c_ops;
3263 EXPORT_SYMBOL(crc32c_csum_stub);
3266 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3267 * @from: source buffer
3269 * Calculates the amount of linear headroom needed in the 'to' skb passed
3270 * into skb_zerocopy().
3273 skb_zerocopy_headlen(const struct sk_buff *from)
3275 unsigned int hlen = 0;
3277 if (!from->head_frag ||
3278 skb_headlen(from) < L1_CACHE_BYTES ||
3279 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3280 hlen = skb_headlen(from);
3285 if (skb_has_frag_list(from))
3290 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3293 * skb_zerocopy - Zero copy skb to skb
3294 * @to: destination buffer
3295 * @from: source buffer
3296 * @len: number of bytes to copy from source buffer
3297 * @hlen: size of linear headroom in destination buffer
3299 * Copies up to `len` bytes from `from` to `to` by creating references
3300 * to the frags in the source buffer.
3302 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3303 * headroom in the `to` buffer.
3306 * 0: everything is OK
3307 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3308 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3311 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3314 int plen = 0; /* length of skb->head fragment */
3317 unsigned int offset;
3319 BUG_ON(!from->head_frag && !hlen);
3321 /* dont bother with small payloads */
3322 if (len <= skb_tailroom(to))
3323 return skb_copy_bits(from, 0, skb_put(to, len), len);
3326 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3331 plen = min_t(int, skb_headlen(from), len);
3333 page = virt_to_head_page(from->head);
3334 offset = from->data - (unsigned char *)page_address(page);
3335 __skb_fill_page_desc(to, 0, page, offset, plen);
3342 skb_len_add(to, len + plen);
3344 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3348 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3350 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3355 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3356 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3358 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3360 skb_frag_ref(to, j);
3363 skb_shinfo(to)->nr_frags = j;
3367 EXPORT_SYMBOL_GPL(skb_zerocopy);
3369 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3374 if (skb->ip_summed == CHECKSUM_PARTIAL)
3375 csstart = skb_checksum_start_offset(skb);
3377 csstart = skb_headlen(skb);
3379 BUG_ON(csstart > skb_headlen(skb));
3381 skb_copy_from_linear_data(skb, to, csstart);
3384 if (csstart != skb->len)
3385 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3386 skb->len - csstart);
3388 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3389 long csstuff = csstart + skb->csum_offset;
3391 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3394 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3397 * skb_dequeue - remove from the head of the queue
3398 * @list: list to dequeue from
3400 * Remove the head of the list. The list lock is taken so the function
3401 * may be used safely with other locking list functions. The head item is
3402 * returned or %NULL if the list is empty.
3405 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3407 unsigned long flags;
3408 struct sk_buff *result;
3410 spin_lock_irqsave(&list->lock, flags);
3411 result = __skb_dequeue(list);
3412 spin_unlock_irqrestore(&list->lock, flags);
3415 EXPORT_SYMBOL(skb_dequeue);
3418 * skb_dequeue_tail - remove from the tail of the queue
3419 * @list: list to dequeue from
3421 * Remove the tail of the list. The list lock is taken so the function
3422 * may be used safely with other locking list functions. The tail item is
3423 * returned or %NULL if the list is empty.
3425 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3427 unsigned long flags;
3428 struct sk_buff *result;
3430 spin_lock_irqsave(&list->lock, flags);
3431 result = __skb_dequeue_tail(list);
3432 spin_unlock_irqrestore(&list->lock, flags);
3435 EXPORT_SYMBOL(skb_dequeue_tail);
3438 * skb_queue_purge - empty a list
3439 * @list: list to empty
3441 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3442 * the list and one reference dropped. This function takes the list
3443 * lock and is atomic with respect to other list locking functions.
3445 void skb_queue_purge(struct sk_buff_head *list)
3447 struct sk_buff *skb;
3448 while ((skb = skb_dequeue(list)) != NULL)
3451 EXPORT_SYMBOL(skb_queue_purge);
3454 * skb_rbtree_purge - empty a skb rbtree
3455 * @root: root of the rbtree to empty
3456 * Return value: the sum of truesizes of all purged skbs.
3458 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3459 * the list and one reference dropped. This function does not take
3460 * any lock. Synchronization should be handled by the caller (e.g., TCP
3461 * out-of-order queue is protected by the socket lock).
3463 unsigned int skb_rbtree_purge(struct rb_root *root)
3465 struct rb_node *p = rb_first(root);
3466 unsigned int sum = 0;
3469 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3472 rb_erase(&skb->rbnode, root);
3473 sum += skb->truesize;
3480 * skb_queue_head - queue a buffer at the list head
3481 * @list: list to use
3482 * @newsk: buffer to queue
3484 * Queue a buffer at the start of the list. This function takes the
3485 * list lock and can be used safely with other locking &sk_buff functions
3488 * A buffer cannot be placed on two lists at the same time.
3490 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3492 unsigned long flags;
3494 spin_lock_irqsave(&list->lock, flags);
3495 __skb_queue_head(list, newsk);
3496 spin_unlock_irqrestore(&list->lock, flags);
3498 EXPORT_SYMBOL(skb_queue_head);
3501 * skb_queue_tail - queue a buffer at the list tail
3502 * @list: list to use
3503 * @newsk: buffer to queue
3505 * Queue a buffer at the tail of the list. This function takes the
3506 * list lock and can be used safely with other locking &sk_buff functions
3509 * A buffer cannot be placed on two lists at the same time.
3511 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3513 unsigned long flags;
3515 spin_lock_irqsave(&list->lock, flags);
3516 __skb_queue_tail(list, newsk);
3517 spin_unlock_irqrestore(&list->lock, flags);
3519 EXPORT_SYMBOL(skb_queue_tail);
3522 * skb_unlink - remove a buffer from a list
3523 * @skb: buffer to remove
3524 * @list: list to use
3526 * Remove a packet from a list. The list locks are taken and this
3527 * function is atomic with respect to other list locked calls
3529 * You must know what list the SKB is on.
3531 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3533 unsigned long flags;
3535 spin_lock_irqsave(&list->lock, flags);
3536 __skb_unlink(skb, list);
3537 spin_unlock_irqrestore(&list->lock, flags);
3539 EXPORT_SYMBOL(skb_unlink);
3542 * skb_append - append a buffer
3543 * @old: buffer to insert after
3544 * @newsk: buffer to insert
3545 * @list: list to use
3547 * Place a packet after a given packet in a list. The list locks are taken
3548 * and this function is atomic with respect to other list locked calls.
3549 * A buffer cannot be placed on two lists at the same time.
3551 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3553 unsigned long flags;
3555 spin_lock_irqsave(&list->lock, flags);
3556 __skb_queue_after(list, old, newsk);
3557 spin_unlock_irqrestore(&list->lock, flags);
3559 EXPORT_SYMBOL(skb_append);
3561 static inline void skb_split_inside_header(struct sk_buff *skb,
3562 struct sk_buff* skb1,
3563 const u32 len, const int pos)
3567 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3569 /* And move data appendix as is. */
3570 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3571 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3573 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3574 skb_shinfo(skb)->nr_frags = 0;
3575 skb1->data_len = skb->data_len;
3576 skb1->len += skb1->data_len;
3579 skb_set_tail_pointer(skb, len);
3582 static inline void skb_split_no_header(struct sk_buff *skb,
3583 struct sk_buff* skb1,
3584 const u32 len, int pos)
3587 const int nfrags = skb_shinfo(skb)->nr_frags;
3589 skb_shinfo(skb)->nr_frags = 0;
3590 skb1->len = skb1->data_len = skb->len - len;
3592 skb->data_len = len - pos;
3594 for (i = 0; i < nfrags; i++) {
3595 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3597 if (pos + size > len) {
3598 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3602 * We have two variants in this case:
3603 * 1. Move all the frag to the second
3604 * part, if it is possible. F.e.
3605 * this approach is mandatory for TUX,
3606 * where splitting is expensive.
3607 * 2. Split is accurately. We make this.
3609 skb_frag_ref(skb, i);
3610 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3611 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3612 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3613 skb_shinfo(skb)->nr_frags++;
3617 skb_shinfo(skb)->nr_frags++;
3620 skb_shinfo(skb1)->nr_frags = k;
3624 * skb_split - Split fragmented skb to two parts at length len.
3625 * @skb: the buffer to split
3626 * @skb1: the buffer to receive the second part
3627 * @len: new length for skb
3629 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3631 int pos = skb_headlen(skb);
3632 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3634 skb_zcopy_downgrade_managed(skb);
3636 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3637 skb_zerocopy_clone(skb1, skb, 0);
3638 if (len < pos) /* Split line is inside header. */
3639 skb_split_inside_header(skb, skb1, len, pos);
3640 else /* Second chunk has no header, nothing to copy. */
3641 skb_split_no_header(skb, skb1, len, pos);
3643 EXPORT_SYMBOL(skb_split);
3645 /* Shifting from/to a cloned skb is a no-go.
3647 * Caller cannot keep skb_shinfo related pointers past calling here!
3649 static int skb_prepare_for_shift(struct sk_buff *skb)
3651 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3655 * skb_shift - Shifts paged data partially from skb to another
3656 * @tgt: buffer into which tail data gets added
3657 * @skb: buffer from which the paged data comes from
3658 * @shiftlen: shift up to this many bytes
3660 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3661 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3662 * It's up to caller to free skb if everything was shifted.
3664 * If @tgt runs out of frags, the whole operation is aborted.
3666 * Skb cannot include anything else but paged data while tgt is allowed
3667 * to have non-paged data as well.
3669 * TODO: full sized shift could be optimized but that would need
3670 * specialized skb free'er to handle frags without up-to-date nr_frags.
3672 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3674 int from, to, merge, todo;
3675 skb_frag_t *fragfrom, *fragto;
3677 BUG_ON(shiftlen > skb->len);
3679 if (skb_headlen(skb))
3681 if (skb_zcopy(tgt) || skb_zcopy(skb))
3686 to = skb_shinfo(tgt)->nr_frags;
3687 fragfrom = &skb_shinfo(skb)->frags[from];
3689 /* Actual merge is delayed until the point when we know we can
3690 * commit all, so that we don't have to undo partial changes
3693 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3694 skb_frag_off(fragfrom))) {
3699 todo -= skb_frag_size(fragfrom);
3701 if (skb_prepare_for_shift(skb) ||
3702 skb_prepare_for_shift(tgt))
3705 /* All previous frag pointers might be stale! */
3706 fragfrom = &skb_shinfo(skb)->frags[from];
3707 fragto = &skb_shinfo(tgt)->frags[merge];
3709 skb_frag_size_add(fragto, shiftlen);
3710 skb_frag_size_sub(fragfrom, shiftlen);
3711 skb_frag_off_add(fragfrom, shiftlen);
3719 /* Skip full, not-fitting skb to avoid expensive operations */
3720 if ((shiftlen == skb->len) &&
3721 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3724 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3727 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3728 if (to == MAX_SKB_FRAGS)
3731 fragfrom = &skb_shinfo(skb)->frags[from];
3732 fragto = &skb_shinfo(tgt)->frags[to];
3734 if (todo >= skb_frag_size(fragfrom)) {
3735 *fragto = *fragfrom;
3736 todo -= skb_frag_size(fragfrom);
3741 __skb_frag_ref(fragfrom);
3742 skb_frag_page_copy(fragto, fragfrom);
3743 skb_frag_off_copy(fragto, fragfrom);
3744 skb_frag_size_set(fragto, todo);
3746 skb_frag_off_add(fragfrom, todo);
3747 skb_frag_size_sub(fragfrom, todo);
3755 /* Ready to "commit" this state change to tgt */
3756 skb_shinfo(tgt)->nr_frags = to;
3759 fragfrom = &skb_shinfo(skb)->frags[0];
3760 fragto = &skb_shinfo(tgt)->frags[merge];
3762 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3763 __skb_frag_unref(fragfrom, skb->pp_recycle);
3766 /* Reposition in the original skb */
3768 while (from < skb_shinfo(skb)->nr_frags)
3769 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3770 skb_shinfo(skb)->nr_frags = to;
3772 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3775 /* Most likely the tgt won't ever need its checksum anymore, skb on
3776 * the other hand might need it if it needs to be resent
3778 tgt->ip_summed = CHECKSUM_PARTIAL;
3779 skb->ip_summed = CHECKSUM_PARTIAL;
3781 skb_len_add(skb, -shiftlen);
3782 skb_len_add(tgt, shiftlen);
3788 * skb_prepare_seq_read - Prepare a sequential read of skb data
3789 * @skb: the buffer to read
3790 * @from: lower offset of data to be read
3791 * @to: upper offset of data to be read
3792 * @st: state variable
3794 * Initializes the specified state variable. Must be called before
3795 * invoking skb_seq_read() for the first time.
3797 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3798 unsigned int to, struct skb_seq_state *st)
3800 st->lower_offset = from;
3801 st->upper_offset = to;
3802 st->root_skb = st->cur_skb = skb;
3803 st->frag_idx = st->stepped_offset = 0;
3804 st->frag_data = NULL;
3807 EXPORT_SYMBOL(skb_prepare_seq_read);
3810 * skb_seq_read - Sequentially read skb data
3811 * @consumed: number of bytes consumed by the caller so far
3812 * @data: destination pointer for data to be returned
3813 * @st: state variable
3815 * Reads a block of skb data at @consumed relative to the
3816 * lower offset specified to skb_prepare_seq_read(). Assigns
3817 * the head of the data block to @data and returns the length
3818 * of the block or 0 if the end of the skb data or the upper
3819 * offset has been reached.
3821 * The caller is not required to consume all of the data
3822 * returned, i.e. @consumed is typically set to the number
3823 * of bytes already consumed and the next call to
3824 * skb_seq_read() will return the remaining part of the block.
3826 * Note 1: The size of each block of data returned can be arbitrary,
3827 * this limitation is the cost for zerocopy sequential
3828 * reads of potentially non linear data.
3830 * Note 2: Fragment lists within fragments are not implemented
3831 * at the moment, state->root_skb could be replaced with
3832 * a stack for this purpose.
3834 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3835 struct skb_seq_state *st)
3837 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3840 if (unlikely(abs_offset >= st->upper_offset)) {
3841 if (st->frag_data) {
3842 kunmap_atomic(st->frag_data);
3843 st->frag_data = NULL;
3849 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3851 if (abs_offset < block_limit && !st->frag_data) {
3852 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3853 return block_limit - abs_offset;
3856 if (st->frag_idx == 0 && !st->frag_data)
3857 st->stepped_offset += skb_headlen(st->cur_skb);
3859 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3860 unsigned int pg_idx, pg_off, pg_sz;
3862 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3865 pg_off = skb_frag_off(frag);
3866 pg_sz = skb_frag_size(frag);
3868 if (skb_frag_must_loop(skb_frag_page(frag))) {
3869 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3870 pg_off = offset_in_page(pg_off + st->frag_off);
3871 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3872 PAGE_SIZE - pg_off);
3875 block_limit = pg_sz + st->stepped_offset;
3876 if (abs_offset < block_limit) {
3878 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3880 *data = (u8 *)st->frag_data + pg_off +
3881 (abs_offset - st->stepped_offset);
3883 return block_limit - abs_offset;
3886 if (st->frag_data) {
3887 kunmap_atomic(st->frag_data);
3888 st->frag_data = NULL;
3891 st->stepped_offset += pg_sz;
3892 st->frag_off += pg_sz;
3893 if (st->frag_off == skb_frag_size(frag)) {
3899 if (st->frag_data) {
3900 kunmap_atomic(st->frag_data);
3901 st->frag_data = NULL;
3904 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3905 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3908 } else if (st->cur_skb->next) {
3909 st->cur_skb = st->cur_skb->next;
3916 EXPORT_SYMBOL(skb_seq_read);
3919 * skb_abort_seq_read - Abort a sequential read of skb data
3920 * @st: state variable
3922 * Must be called if skb_seq_read() was not called until it
3925 void skb_abort_seq_read(struct skb_seq_state *st)
3928 kunmap_atomic(st->frag_data);
3930 EXPORT_SYMBOL(skb_abort_seq_read);
3932 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3934 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3935 struct ts_config *conf,
3936 struct ts_state *state)
3938 return skb_seq_read(offset, text, TS_SKB_CB(state));
3941 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3943 skb_abort_seq_read(TS_SKB_CB(state));
3947 * skb_find_text - Find a text pattern in skb data
3948 * @skb: the buffer to look in
3949 * @from: search offset
3951 * @config: textsearch configuration
3953 * Finds a pattern in the skb data according to the specified
3954 * textsearch configuration. Use textsearch_next() to retrieve
3955 * subsequent occurrences of the pattern. Returns the offset
3956 * to the first occurrence or UINT_MAX if no match was found.
3958 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3959 unsigned int to, struct ts_config *config)
3961 unsigned int patlen = config->ops->get_pattern_len(config);
3962 struct ts_state state;
3965 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3967 config->get_next_block = skb_ts_get_next_block;
3968 config->finish = skb_ts_finish;
3970 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3972 ret = textsearch_find(config, &state);
3973 return (ret + patlen <= to - from ? ret : UINT_MAX);
3975 EXPORT_SYMBOL(skb_find_text);
3977 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3978 int offset, size_t size)
3980 int i = skb_shinfo(skb)->nr_frags;
3982 if (skb_can_coalesce(skb, i, page, offset)) {
3983 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3984 } else if (i < MAX_SKB_FRAGS) {
3985 skb_zcopy_downgrade_managed(skb);
3987 skb_fill_page_desc_noacc(skb, i, page, offset, size);
3994 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3997 * skb_pull_rcsum - pull skb and update receive checksum
3998 * @skb: buffer to update
3999 * @len: length of data pulled
4001 * This function performs an skb_pull on the packet and updates
4002 * the CHECKSUM_COMPLETE checksum. It should be used on
4003 * receive path processing instead of skb_pull unless you know
4004 * that the checksum difference is zero (e.g., a valid IP header)
4005 * or you are setting ip_summed to CHECKSUM_NONE.
4007 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4009 unsigned char *data = skb->data;
4011 BUG_ON(len > skb->len);
4012 __skb_pull(skb, len);
4013 skb_postpull_rcsum(skb, data, len);
4016 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4018 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4020 skb_frag_t head_frag;
4023 page = virt_to_head_page(frag_skb->head);
4024 __skb_frag_set_page(&head_frag, page);
4025 skb_frag_off_set(&head_frag, frag_skb->data -
4026 (unsigned char *)page_address(page));
4027 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
4031 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4032 netdev_features_t features,
4033 unsigned int offset)
4035 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4036 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4037 unsigned int delta_truesize = 0;
4038 unsigned int delta_len = 0;
4039 struct sk_buff *tail = NULL;
4040 struct sk_buff *nskb, *tmp;
4043 skb_push(skb, -skb_network_offset(skb) + offset);
4045 /* Ensure the head is writeable before touching the shared info */
4046 err = skb_unclone(skb, GFP_ATOMIC);
4050 skb_shinfo(skb)->frag_list = NULL;
4054 list_skb = list_skb->next;
4057 delta_truesize += nskb->truesize;
4058 if (skb_shared(nskb)) {
4059 tmp = skb_clone(nskb, GFP_ATOMIC);
4063 err = skb_unclone(nskb, GFP_ATOMIC);
4074 if (unlikely(err)) {
4075 nskb->next = list_skb;
4081 delta_len += nskb->len;
4083 skb_push(nskb, -skb_network_offset(nskb) + offset);
4085 skb_release_head_state(nskb);
4086 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4087 __copy_skb_header(nskb, skb);
4089 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4090 nskb->transport_header += len_diff;
4091 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4092 nskb->data - tnl_hlen,
4095 if (skb_needs_linearize(nskb, features) &&
4096 __skb_linearize(nskb))
4100 skb->truesize = skb->truesize - delta_truesize;
4101 skb->data_len = skb->data_len - delta_len;
4102 skb->len = skb->len - delta_len;
4108 if (skb_needs_linearize(skb, features) &&
4109 __skb_linearize(skb))
4117 kfree_skb_list(skb->next);
4119 return ERR_PTR(-ENOMEM);
4121 EXPORT_SYMBOL_GPL(skb_segment_list);
4124 * skb_segment - Perform protocol segmentation on skb.
4125 * @head_skb: buffer to segment
4126 * @features: features for the output path (see dev->features)
4128 * This function performs segmentation on the given skb. It returns
4129 * a pointer to the first in a list of new skbs for the segments.
4130 * In case of error it returns ERR_PTR(err).
4132 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4133 netdev_features_t features)
4135 struct sk_buff *segs = NULL;
4136 struct sk_buff *tail = NULL;
4137 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4138 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4139 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4140 unsigned int offset = doffset;
4141 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4142 unsigned int partial_segs = 0;
4143 unsigned int headroom;
4144 unsigned int len = head_skb->len;
4145 struct sk_buff *frag_skb;
4153 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4154 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4155 struct sk_buff *check_skb;
4157 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4158 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4159 /* gso_size is untrusted, and we have a frag_list with
4160 * a linear non head_frag item.
4162 * If head_skb's headlen does not fit requested gso_size,
4163 * it means that the frag_list members do NOT terminate
4164 * on exact gso_size boundaries. Hence we cannot perform
4165 * skb_frag_t page sharing. Therefore we must fallback to
4166 * copying the frag_list skbs; we do so by disabling SG.
4168 features &= ~NETIF_F_SG;
4174 __skb_push(head_skb, doffset);
4175 proto = skb_network_protocol(head_skb, NULL);
4176 if (unlikely(!proto))
4177 return ERR_PTR(-EINVAL);
4179 sg = !!(features & NETIF_F_SG);
4180 csum = !!can_checksum_protocol(features, proto);
4182 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4183 if (!(features & NETIF_F_GSO_PARTIAL)) {
4184 struct sk_buff *iter;
4185 unsigned int frag_len;
4188 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4191 /* If we get here then all the required
4192 * GSO features except frag_list are supported.
4193 * Try to split the SKB to multiple GSO SKBs
4194 * with no frag_list.
4195 * Currently we can do that only when the buffers don't
4196 * have a linear part and all the buffers except
4197 * the last are of the same length.
4199 frag_len = list_skb->len;
4200 skb_walk_frags(head_skb, iter) {
4201 if (frag_len != iter->len && iter->next)
4203 if (skb_headlen(iter) && !iter->head_frag)
4209 if (len != frag_len)
4213 /* GSO partial only requires that we trim off any excess that
4214 * doesn't fit into an MSS sized block, so take care of that
4216 * Cap len to not accidentally hit GSO_BY_FRAGS.
4218 partial_segs = min(len, GSO_BY_FRAGS - 1U) / mss;
4219 if (partial_segs > 1)
4220 mss *= partial_segs;
4226 headroom = skb_headroom(head_skb);
4227 pos = skb_headlen(head_skb);
4229 if (skb_orphan_frags(head_skb, GFP_ATOMIC))
4230 return ERR_PTR(-ENOMEM);
4232 nfrags = skb_shinfo(head_skb)->nr_frags;
4233 frag = skb_shinfo(head_skb)->frags;
4234 frag_skb = head_skb;
4237 struct sk_buff *nskb;
4238 skb_frag_t *nskb_frag;
4242 if (unlikely(mss == GSO_BY_FRAGS)) {
4243 len = list_skb->len;
4245 len = head_skb->len - offset;
4250 hsize = skb_headlen(head_skb) - offset;
4252 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4253 (skb_headlen(list_skb) == len || sg)) {
4254 BUG_ON(skb_headlen(list_skb) > len);
4256 nskb = skb_clone(list_skb, GFP_ATOMIC);
4257 if (unlikely(!nskb))
4261 nfrags = skb_shinfo(list_skb)->nr_frags;
4262 frag = skb_shinfo(list_skb)->frags;
4263 frag_skb = list_skb;
4264 pos += skb_headlen(list_skb);
4266 while (pos < offset + len) {
4267 BUG_ON(i >= nfrags);
4269 size = skb_frag_size(frag);
4270 if (pos + size > offset + len)
4278 list_skb = list_skb->next;
4280 if (unlikely(pskb_trim(nskb, len))) {
4285 hsize = skb_end_offset(nskb);
4286 if (skb_cow_head(nskb, doffset + headroom)) {
4291 nskb->truesize += skb_end_offset(nskb) - hsize;
4292 skb_release_head_state(nskb);
4293 __skb_push(nskb, doffset);
4297 if (hsize > len || !sg)
4300 nskb = __alloc_skb(hsize + doffset + headroom,
4301 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4304 if (unlikely(!nskb))
4307 skb_reserve(nskb, headroom);
4308 __skb_put(nskb, doffset);
4317 __copy_skb_header(nskb, head_skb);
4319 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4320 skb_reset_mac_len(nskb);
4322 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4323 nskb->data - tnl_hlen,
4324 doffset + tnl_hlen);
4326 if (nskb->len == len + doffset)
4327 goto perform_csum_check;
4331 if (!nskb->remcsum_offload)
4332 nskb->ip_summed = CHECKSUM_NONE;
4333 SKB_GSO_CB(nskb)->csum =
4334 skb_copy_and_csum_bits(head_skb, offset,
4338 SKB_GSO_CB(nskb)->csum_start =
4339 skb_headroom(nskb) + doffset;
4341 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4347 nskb_frag = skb_shinfo(nskb)->frags;
4349 skb_copy_from_linear_data_offset(head_skb, offset,
4350 skb_put(nskb, hsize), hsize);
4352 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4355 if (skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4358 while (pos < offset + len) {
4360 if (skb_orphan_frags(list_skb, GFP_ATOMIC) ||
4361 skb_zerocopy_clone(nskb, list_skb,
4366 nfrags = skb_shinfo(list_skb)->nr_frags;
4367 frag = skb_shinfo(list_skb)->frags;
4368 frag_skb = list_skb;
4369 if (!skb_headlen(list_skb)) {
4372 BUG_ON(!list_skb->head_frag);
4374 /* to make room for head_frag. */
4379 list_skb = list_skb->next;
4382 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4384 net_warn_ratelimited(
4385 "skb_segment: too many frags: %u %u\n",
4391 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4392 __skb_frag_ref(nskb_frag);
4393 size = skb_frag_size(nskb_frag);
4396 skb_frag_off_add(nskb_frag, offset - pos);
4397 skb_frag_size_sub(nskb_frag, offset - pos);
4400 skb_shinfo(nskb)->nr_frags++;
4402 if (pos + size <= offset + len) {
4407 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4415 nskb->data_len = len - hsize;
4416 nskb->len += nskb->data_len;
4417 nskb->truesize += nskb->data_len;
4421 if (skb_has_shared_frag(nskb) &&
4422 __skb_linearize(nskb))
4425 if (!nskb->remcsum_offload)
4426 nskb->ip_summed = CHECKSUM_NONE;
4427 SKB_GSO_CB(nskb)->csum =
4428 skb_checksum(nskb, doffset,
4429 nskb->len - doffset, 0);
4430 SKB_GSO_CB(nskb)->csum_start =
4431 skb_headroom(nskb) + doffset;
4433 } while ((offset += len) < head_skb->len);
4435 /* Some callers want to get the end of the list.
4436 * Put it in segs->prev to avoid walking the list.
4437 * (see validate_xmit_skb_list() for example)
4442 struct sk_buff *iter;
4443 int type = skb_shinfo(head_skb)->gso_type;
4444 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4446 /* Update type to add partial and then remove dodgy if set */
4447 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4448 type &= ~SKB_GSO_DODGY;
4450 /* Update GSO info and prepare to start updating headers on
4451 * our way back down the stack of protocols.
4453 for (iter = segs; iter; iter = iter->next) {
4454 skb_shinfo(iter)->gso_size = gso_size;
4455 skb_shinfo(iter)->gso_segs = partial_segs;
4456 skb_shinfo(iter)->gso_type = type;
4457 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4460 if (tail->len - doffset <= gso_size)
4461 skb_shinfo(tail)->gso_size = 0;
4462 else if (tail != segs)
4463 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4466 /* Following permits correct backpressure, for protocols
4467 * using skb_set_owner_w().
4468 * Idea is to tranfert ownership from head_skb to last segment.
4470 if (head_skb->destructor == sock_wfree) {
4471 swap(tail->truesize, head_skb->truesize);
4472 swap(tail->destructor, head_skb->destructor);
4473 swap(tail->sk, head_skb->sk);
4478 kfree_skb_list(segs);
4479 return ERR_PTR(err);
4481 EXPORT_SYMBOL_GPL(skb_segment);
4483 #ifdef CONFIG_SKB_EXTENSIONS
4484 #define SKB_EXT_ALIGN_VALUE 8
4485 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4487 static const u8 skb_ext_type_len[] = {
4488 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4489 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4492 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4494 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4495 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4497 #if IS_ENABLED(CONFIG_MPTCP)
4498 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4500 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4501 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4505 static __always_inline unsigned int skb_ext_total_length(void)
4507 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4508 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4509 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4512 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4514 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4515 skb_ext_type_len[TC_SKB_EXT] +
4517 #if IS_ENABLED(CONFIG_MPTCP)
4518 skb_ext_type_len[SKB_EXT_MPTCP] +
4520 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4521 skb_ext_type_len[SKB_EXT_MCTP] +
4526 static void skb_extensions_init(void)
4528 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4529 BUILD_BUG_ON(skb_ext_total_length() > 255);
4531 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4532 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4534 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4538 static void skb_extensions_init(void) {}
4541 void __init skb_init(void)
4543 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4544 sizeof(struct sk_buff),
4546 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4547 offsetof(struct sk_buff, cb),
4548 sizeof_field(struct sk_buff, cb),
4550 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4551 sizeof(struct sk_buff_fclones),
4553 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4555 skb_extensions_init();
4559 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4560 unsigned int recursion_level)
4562 int start = skb_headlen(skb);
4563 int i, copy = start - offset;
4564 struct sk_buff *frag_iter;
4567 if (unlikely(recursion_level >= 24))
4573 sg_set_buf(sg, skb->data + offset, copy);
4575 if ((len -= copy) == 0)
4580 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4583 WARN_ON(start > offset + len);
4585 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4586 if ((copy = end - offset) > 0) {
4587 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4588 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4593 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4594 skb_frag_off(frag) + offset - start);
4603 skb_walk_frags(skb, frag_iter) {
4606 WARN_ON(start > offset + len);
4608 end = start + frag_iter->len;
4609 if ((copy = end - offset) > 0) {
4610 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4615 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4616 copy, recursion_level + 1);
4617 if (unlikely(ret < 0))
4620 if ((len -= copy) == 0)
4631 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4632 * @skb: Socket buffer containing the buffers to be mapped
4633 * @sg: The scatter-gather list to map into
4634 * @offset: The offset into the buffer's contents to start mapping
4635 * @len: Length of buffer space to be mapped
4637 * Fill the specified scatter-gather list with mappings/pointers into a
4638 * region of the buffer space attached to a socket buffer. Returns either
4639 * the number of scatterlist items used, or -EMSGSIZE if the contents
4642 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4644 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4649 sg_mark_end(&sg[nsg - 1]);
4653 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4655 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4656 * sglist without mark the sg which contain last skb data as the end.
4657 * So the caller can mannipulate sg list as will when padding new data after
4658 * the first call without calling sg_unmark_end to expend sg list.
4660 * Scenario to use skb_to_sgvec_nomark:
4662 * 2. skb_to_sgvec_nomark(payload1)
4663 * 3. skb_to_sgvec_nomark(payload2)
4665 * This is equivalent to:
4667 * 2. skb_to_sgvec(payload1)
4669 * 4. skb_to_sgvec(payload2)
4671 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4672 * is more preferable.
4674 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4675 int offset, int len)
4677 return __skb_to_sgvec(skb, sg, offset, len, 0);
4679 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4684 * skb_cow_data - Check that a socket buffer's data buffers are writable
4685 * @skb: The socket buffer to check.
4686 * @tailbits: Amount of trailing space to be added
4687 * @trailer: Returned pointer to the skb where the @tailbits space begins
4689 * Make sure that the data buffers attached to a socket buffer are
4690 * writable. If they are not, private copies are made of the data buffers
4691 * and the socket buffer is set to use these instead.
4693 * If @tailbits is given, make sure that there is space to write @tailbits
4694 * bytes of data beyond current end of socket buffer. @trailer will be
4695 * set to point to the skb in which this space begins.
4697 * The number of scatterlist elements required to completely map the
4698 * COW'd and extended socket buffer will be returned.
4700 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4704 struct sk_buff *skb1, **skb_p;
4706 /* If skb is cloned or its head is paged, reallocate
4707 * head pulling out all the pages (pages are considered not writable
4708 * at the moment even if they are anonymous).
4710 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4711 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4714 /* Easy case. Most of packets will go this way. */
4715 if (!skb_has_frag_list(skb)) {
4716 /* A little of trouble, not enough of space for trailer.
4717 * This should not happen, when stack is tuned to generate
4718 * good frames. OK, on miss we reallocate and reserve even more
4719 * space, 128 bytes is fair. */
4721 if (skb_tailroom(skb) < tailbits &&
4722 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4730 /* Misery. We are in troubles, going to mincer fragments... */
4733 skb_p = &skb_shinfo(skb)->frag_list;
4736 while ((skb1 = *skb_p) != NULL) {
4739 /* The fragment is partially pulled by someone,
4740 * this can happen on input. Copy it and everything
4743 if (skb_shared(skb1))
4746 /* If the skb is the last, worry about trailer. */
4748 if (skb1->next == NULL && tailbits) {
4749 if (skb_shinfo(skb1)->nr_frags ||
4750 skb_has_frag_list(skb1) ||
4751 skb_tailroom(skb1) < tailbits)
4752 ntail = tailbits + 128;
4758 skb_shinfo(skb1)->nr_frags ||
4759 skb_has_frag_list(skb1)) {
4760 struct sk_buff *skb2;
4762 /* Fuck, we are miserable poor guys... */
4764 skb2 = skb_copy(skb1, GFP_ATOMIC);
4766 skb2 = skb_copy_expand(skb1,
4770 if (unlikely(skb2 == NULL))
4774 skb_set_owner_w(skb2, skb1->sk);
4776 /* Looking around. Are we still alive?
4777 * OK, link new skb, drop old one */
4779 skb2->next = skb1->next;
4786 skb_p = &skb1->next;
4791 EXPORT_SYMBOL_GPL(skb_cow_data);
4793 static void sock_rmem_free(struct sk_buff *skb)
4795 struct sock *sk = skb->sk;
4797 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4800 static void skb_set_err_queue(struct sk_buff *skb)
4802 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4803 * So, it is safe to (mis)use it to mark skbs on the error queue.
4805 skb->pkt_type = PACKET_OUTGOING;
4806 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4810 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4812 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4814 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4815 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4820 skb->destructor = sock_rmem_free;
4821 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4822 skb_set_err_queue(skb);
4824 /* before exiting rcu section, make sure dst is refcounted */
4827 skb_queue_tail(&sk->sk_error_queue, skb);
4828 if (!sock_flag(sk, SOCK_DEAD))
4829 sk_error_report(sk);
4832 EXPORT_SYMBOL(sock_queue_err_skb);
4834 static bool is_icmp_err_skb(const struct sk_buff *skb)
4836 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4837 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4840 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4842 struct sk_buff_head *q = &sk->sk_error_queue;
4843 struct sk_buff *skb, *skb_next = NULL;
4844 bool icmp_next = false;
4845 unsigned long flags;
4847 spin_lock_irqsave(&q->lock, flags);
4848 skb = __skb_dequeue(q);
4849 if (skb && (skb_next = skb_peek(q))) {
4850 icmp_next = is_icmp_err_skb(skb_next);
4852 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4854 spin_unlock_irqrestore(&q->lock, flags);
4856 if (is_icmp_err_skb(skb) && !icmp_next)
4860 sk_error_report(sk);
4864 EXPORT_SYMBOL(sock_dequeue_err_skb);
4867 * skb_clone_sk - create clone of skb, and take reference to socket
4868 * @skb: the skb to clone
4870 * This function creates a clone of a buffer that holds a reference on
4871 * sk_refcnt. Buffers created via this function are meant to be
4872 * returned using sock_queue_err_skb, or free via kfree_skb.
4874 * When passing buffers allocated with this function to sock_queue_err_skb
4875 * it is necessary to wrap the call with sock_hold/sock_put in order to
4876 * prevent the socket from being released prior to being enqueued on
4877 * the sk_error_queue.
4879 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4881 struct sock *sk = skb->sk;
4882 struct sk_buff *clone;
4884 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4887 clone = skb_clone(skb, GFP_ATOMIC);
4894 clone->destructor = sock_efree;
4898 EXPORT_SYMBOL(skb_clone_sk);
4900 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4905 struct sock_exterr_skb *serr;
4908 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4910 serr = SKB_EXT_ERR(skb);
4911 memset(serr, 0, sizeof(*serr));
4912 serr->ee.ee_errno = ENOMSG;
4913 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4914 serr->ee.ee_info = tstype;
4915 serr->opt_stats = opt_stats;
4916 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4917 if (READ_ONCE(sk->sk_tsflags) & SOF_TIMESTAMPING_OPT_ID) {
4918 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4920 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4923 err = sock_queue_err_skb(sk, skb);
4929 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4933 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
4936 read_lock_bh(&sk->sk_callback_lock);
4937 ret = sk->sk_socket && sk->sk_socket->file &&
4938 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4939 read_unlock_bh(&sk->sk_callback_lock);
4943 void skb_complete_tx_timestamp(struct sk_buff *skb,
4944 struct skb_shared_hwtstamps *hwtstamps)
4946 struct sock *sk = skb->sk;
4948 if (!skb_may_tx_timestamp(sk, false))
4951 /* Take a reference to prevent skb_orphan() from freeing the socket,
4952 * but only if the socket refcount is not zero.
4954 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4955 *skb_hwtstamps(skb) = *hwtstamps;
4956 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4964 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4966 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4967 const struct sk_buff *ack_skb,
4968 struct skb_shared_hwtstamps *hwtstamps,
4969 struct sock *sk, int tstype)
4971 struct sk_buff *skb;
4972 bool tsonly, opt_stats = false;
4978 tsflags = READ_ONCE(sk->sk_tsflags);
4979 if (!hwtstamps && !(tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4980 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4983 tsonly = tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4984 if (!skb_may_tx_timestamp(sk, tsonly))
4989 if ((tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4991 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4996 skb = alloc_skb(0, GFP_ATOMIC);
4998 skb = skb_clone(orig_skb, GFP_ATOMIC);
5000 if (skb_orphan_frags_rx(skb, GFP_ATOMIC)) {
5009 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5011 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5015 *skb_hwtstamps(skb) = *hwtstamps;
5017 __net_timestamp(skb);
5019 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5021 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5023 void skb_tstamp_tx(struct sk_buff *orig_skb,
5024 struct skb_shared_hwtstamps *hwtstamps)
5026 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5029 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5031 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5033 struct sock *sk = skb->sk;
5034 struct sock_exterr_skb *serr;
5037 skb->wifi_acked_valid = 1;
5038 skb->wifi_acked = acked;
5040 serr = SKB_EXT_ERR(skb);
5041 memset(serr, 0, sizeof(*serr));
5042 serr->ee.ee_errno = ENOMSG;
5043 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5045 /* Take a reference to prevent skb_orphan() from freeing the socket,
5046 * but only if the socket refcount is not zero.
5048 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5049 err = sock_queue_err_skb(sk, skb);
5055 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5058 * skb_partial_csum_set - set up and verify partial csum values for packet
5059 * @skb: the skb to set
5060 * @start: the number of bytes after skb->data to start checksumming.
5061 * @off: the offset from start to place the checksum.
5063 * For untrusted partially-checksummed packets, we need to make sure the values
5064 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5066 * This function checks and sets those values and skb->ip_summed: if this
5067 * returns false you should drop the packet.
5069 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5071 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5072 u32 csum_start = skb_headroom(skb) + (u32)start;
5074 if (unlikely(csum_start >= U16_MAX || csum_end > skb_headlen(skb))) {
5075 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5076 start, off, skb_headroom(skb), skb_headlen(skb));
5079 skb->ip_summed = CHECKSUM_PARTIAL;
5080 skb->csum_start = csum_start;
5081 skb->csum_offset = off;
5082 skb->transport_header = csum_start;
5085 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5087 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5090 if (skb_headlen(skb) >= len)
5093 /* If we need to pullup then pullup to the max, so we
5094 * won't need to do it again.
5099 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5102 if (skb_headlen(skb) < len)
5108 #define MAX_TCP_HDR_LEN (15 * 4)
5110 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5111 typeof(IPPROTO_IP) proto,
5118 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5119 off + MAX_TCP_HDR_LEN);
5120 if (!err && !skb_partial_csum_set(skb, off,
5121 offsetof(struct tcphdr,
5124 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5127 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5128 off + sizeof(struct udphdr));
5129 if (!err && !skb_partial_csum_set(skb, off,
5130 offsetof(struct udphdr,
5133 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5136 return ERR_PTR(-EPROTO);
5139 /* This value should be large enough to cover a tagged ethernet header plus
5140 * maximally sized IP and TCP or UDP headers.
5142 #define MAX_IP_HDR_LEN 128
5144 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5153 err = skb_maybe_pull_tail(skb,
5154 sizeof(struct iphdr),
5159 if (ip_is_fragment(ip_hdr(skb)))
5162 off = ip_hdrlen(skb);
5169 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5171 return PTR_ERR(csum);
5174 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5177 ip_hdr(skb)->protocol, 0);
5184 /* This value should be large enough to cover a tagged ethernet header plus
5185 * an IPv6 header, all options, and a maximal TCP or UDP header.
5187 #define MAX_IPV6_HDR_LEN 256
5189 #define OPT_HDR(type, skb, off) \
5190 (type *)(skb_network_header(skb) + (off))
5192 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5205 off = sizeof(struct ipv6hdr);
5207 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5211 nexthdr = ipv6_hdr(skb)->nexthdr;
5213 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5214 while (off <= len && !done) {
5216 case IPPROTO_DSTOPTS:
5217 case IPPROTO_HOPOPTS:
5218 case IPPROTO_ROUTING: {
5219 struct ipv6_opt_hdr *hp;
5221 err = skb_maybe_pull_tail(skb,
5223 sizeof(struct ipv6_opt_hdr),
5228 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5229 nexthdr = hp->nexthdr;
5230 off += ipv6_optlen(hp);
5234 struct ip_auth_hdr *hp;
5236 err = skb_maybe_pull_tail(skb,
5238 sizeof(struct ip_auth_hdr),
5243 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5244 nexthdr = hp->nexthdr;
5245 off += ipv6_authlen(hp);
5248 case IPPROTO_FRAGMENT: {
5249 struct frag_hdr *hp;
5251 err = skb_maybe_pull_tail(skb,
5253 sizeof(struct frag_hdr),
5258 hp = OPT_HDR(struct frag_hdr, skb, off);
5260 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5263 nexthdr = hp->nexthdr;
5264 off += sizeof(struct frag_hdr);
5275 if (!done || fragment)
5278 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5280 return PTR_ERR(csum);
5283 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5284 &ipv6_hdr(skb)->daddr,
5285 skb->len - off, nexthdr, 0);
5293 * skb_checksum_setup - set up partial checksum offset
5294 * @skb: the skb to set up
5295 * @recalculate: if true the pseudo-header checksum will be recalculated
5297 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5301 switch (skb->protocol) {
5302 case htons(ETH_P_IP):
5303 err = skb_checksum_setup_ipv4(skb, recalculate);
5306 case htons(ETH_P_IPV6):
5307 err = skb_checksum_setup_ipv6(skb, recalculate);
5317 EXPORT_SYMBOL(skb_checksum_setup);
5320 * skb_checksum_maybe_trim - maybe trims the given skb
5321 * @skb: the skb to check
5322 * @transport_len: the data length beyond the network header
5324 * Checks whether the given skb has data beyond the given transport length.
5325 * If so, returns a cloned skb trimmed to this transport length.
5326 * Otherwise returns the provided skb. Returns NULL in error cases
5327 * (e.g. transport_len exceeds skb length or out-of-memory).
5329 * Caller needs to set the skb transport header and free any returned skb if it
5330 * differs from the provided skb.
5332 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5333 unsigned int transport_len)
5335 struct sk_buff *skb_chk;
5336 unsigned int len = skb_transport_offset(skb) + transport_len;
5341 else if (skb->len == len)
5344 skb_chk = skb_clone(skb, GFP_ATOMIC);
5348 ret = pskb_trim_rcsum(skb_chk, len);
5358 * skb_checksum_trimmed - validate checksum of an skb
5359 * @skb: the skb to check
5360 * @transport_len: the data length beyond the network header
5361 * @skb_chkf: checksum function to use
5363 * Applies the given checksum function skb_chkf to the provided skb.
5364 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5366 * If the skb has data beyond the given transport length, then a
5367 * trimmed & cloned skb is checked and returned.
5369 * Caller needs to set the skb transport header and free any returned skb if it
5370 * differs from the provided skb.
5372 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5373 unsigned int transport_len,
5374 __sum16(*skb_chkf)(struct sk_buff *skb))
5376 struct sk_buff *skb_chk;
5377 unsigned int offset = skb_transport_offset(skb);
5380 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5384 if (!pskb_may_pull(skb_chk, offset))
5387 skb_pull_rcsum(skb_chk, offset);
5388 ret = skb_chkf(skb_chk);
5389 skb_push_rcsum(skb_chk, offset);
5397 if (skb_chk && skb_chk != skb)
5403 EXPORT_SYMBOL(skb_checksum_trimmed);
5405 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5407 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5410 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5412 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5415 skb_release_head_state(skb);
5416 kmem_cache_free(skbuff_head_cache, skb);
5421 EXPORT_SYMBOL(kfree_skb_partial);
5424 * skb_try_coalesce - try to merge skb to prior one
5426 * @from: buffer to add
5427 * @fragstolen: pointer to boolean
5428 * @delta_truesize: how much more was allocated than was requested
5430 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5431 bool *fragstolen, int *delta_truesize)
5433 struct skb_shared_info *to_shinfo, *from_shinfo;
5434 int i, delta, len = from->len;
5436 *fragstolen = false;
5441 /* In general, avoid mixing page_pool and non-page_pool allocated
5442 * pages within the same SKB. Additionally avoid dealing with clones
5443 * with page_pool pages, in case the SKB is using page_pool fragment
5444 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5445 * references for cloned SKBs at the moment that would result in
5446 * inconsistent reference counts.
5447 * In theory we could take full references if @from is cloned and
5448 * !@to->pp_recycle but its tricky (due to potential race with
5449 * the clone disappearing) and rare, so not worth dealing with.
5451 if (to->pp_recycle != from->pp_recycle ||
5452 (from->pp_recycle && skb_cloned(from)))
5455 if (len <= skb_tailroom(to)) {
5457 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5458 *delta_truesize = 0;
5462 to_shinfo = skb_shinfo(to);
5463 from_shinfo = skb_shinfo(from);
5464 if (to_shinfo->frag_list || from_shinfo->frag_list)
5466 if (skb_zcopy(to) || skb_zcopy(from))
5469 if (skb_headlen(from) != 0) {
5471 unsigned int offset;
5473 if (to_shinfo->nr_frags +
5474 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5477 if (skb_head_is_locked(from))
5480 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5482 page = virt_to_head_page(from->head);
5483 offset = from->data - (unsigned char *)page_address(page);
5485 skb_fill_page_desc(to, to_shinfo->nr_frags,
5486 page, offset, skb_headlen(from));
5489 if (to_shinfo->nr_frags +
5490 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5493 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5496 WARN_ON_ONCE(delta < len);
5498 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5500 from_shinfo->nr_frags * sizeof(skb_frag_t));
5501 to_shinfo->nr_frags += from_shinfo->nr_frags;
5503 if (!skb_cloned(from))
5504 from_shinfo->nr_frags = 0;
5506 /* if the skb is not cloned this does nothing
5507 * since we set nr_frags to 0.
5509 for (i = 0; i < from_shinfo->nr_frags; i++)
5510 __skb_frag_ref(&from_shinfo->frags[i]);
5512 to->truesize += delta;
5514 to->data_len += len;
5516 *delta_truesize = delta;
5519 EXPORT_SYMBOL(skb_try_coalesce);
5522 * skb_scrub_packet - scrub an skb
5524 * @skb: buffer to clean
5525 * @xnet: packet is crossing netns
5527 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5528 * into/from a tunnel. Some information have to be cleared during these
5530 * skb_scrub_packet can also be used to clean a skb before injecting it in
5531 * another namespace (@xnet == true). We have to clear all information in the
5532 * skb that could impact namespace isolation.
5534 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5536 skb->pkt_type = PACKET_HOST;
5542 nf_reset_trace(skb);
5544 #ifdef CONFIG_NET_SWITCHDEV
5545 skb->offload_fwd_mark = 0;
5546 skb->offload_l3_fwd_mark = 0;
5554 skb_clear_tstamp(skb);
5556 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5559 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5563 * skb_gso_transport_seglen is used to determine the real size of the
5564 * individual segments, including Layer4 headers (TCP/UDP).
5566 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5568 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5570 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5571 unsigned int thlen = 0;
5573 if (skb->encapsulation) {
5574 thlen = skb_inner_transport_header(skb) -
5575 skb_transport_header(skb);
5577 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5578 thlen += inner_tcp_hdrlen(skb);
5579 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5580 thlen = tcp_hdrlen(skb);
5581 } else if (unlikely(skb_is_gso_sctp(skb))) {
5582 thlen = sizeof(struct sctphdr);
5583 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5584 thlen = sizeof(struct udphdr);
5586 /* UFO sets gso_size to the size of the fragmentation
5587 * payload, i.e. the size of the L4 (UDP) header is already
5590 return thlen + shinfo->gso_size;
5594 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5598 * skb_gso_network_seglen is used to determine the real size of the
5599 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5601 * The MAC/L2 header is not accounted for.
5603 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5605 unsigned int hdr_len = skb_transport_header(skb) -
5606 skb_network_header(skb);
5608 return hdr_len + skb_gso_transport_seglen(skb);
5612 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5616 * skb_gso_mac_seglen is used to determine the real size of the
5617 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5618 * headers (TCP/UDP).
5620 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5622 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5624 return hdr_len + skb_gso_transport_seglen(skb);
5628 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5630 * There are a couple of instances where we have a GSO skb, and we
5631 * want to determine what size it would be after it is segmented.
5633 * We might want to check:
5634 * - L3+L4+payload size (e.g. IP forwarding)
5635 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5637 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5641 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5642 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5644 * @max_len: The maximum permissible length.
5646 * Returns true if the segmented length <= max length.
5648 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5649 unsigned int seg_len,
5650 unsigned int max_len) {
5651 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5652 const struct sk_buff *iter;
5654 if (shinfo->gso_size != GSO_BY_FRAGS)
5655 return seg_len <= max_len;
5657 /* Undo this so we can re-use header sizes */
5658 seg_len -= GSO_BY_FRAGS;
5660 skb_walk_frags(skb, iter) {
5661 if (seg_len + skb_headlen(iter) > max_len)
5669 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5672 * @mtu: MTU to validate against
5674 * skb_gso_validate_network_len validates if a given skb will fit a
5675 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5678 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5680 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5682 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5685 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5688 * @len: length to validate against
5690 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5691 * length once split, including L2, L3 and L4 headers and the payload.
5693 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5695 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5697 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5699 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5701 int mac_len, meta_len;
5704 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5709 mac_len = skb->data - skb_mac_header(skb);
5710 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5711 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5712 mac_len - VLAN_HLEN - ETH_TLEN);
5715 meta_len = skb_metadata_len(skb);
5717 meta = skb_metadata_end(skb) - meta_len;
5718 memmove(meta + VLAN_HLEN, meta, meta_len);
5721 skb->mac_header += VLAN_HLEN;
5725 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5727 struct vlan_hdr *vhdr;
5730 if (unlikely(skb_vlan_tag_present(skb))) {
5731 /* vlan_tci is already set-up so leave this for another time */
5735 skb = skb_share_check(skb, GFP_ATOMIC);
5738 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5739 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5742 vhdr = (struct vlan_hdr *)skb->data;
5743 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5744 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5746 skb_pull_rcsum(skb, VLAN_HLEN);
5747 vlan_set_encap_proto(skb, vhdr);
5749 skb = skb_reorder_vlan_header(skb);
5753 skb_reset_network_header(skb);
5754 if (!skb_transport_header_was_set(skb))
5755 skb_reset_transport_header(skb);
5756 skb_reset_mac_len(skb);
5764 EXPORT_SYMBOL(skb_vlan_untag);
5766 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5768 if (!pskb_may_pull(skb, write_len))
5771 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5774 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5776 EXPORT_SYMBOL(skb_ensure_writable);
5778 /* remove VLAN header from packet and update csum accordingly.
5779 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5781 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5783 struct vlan_hdr *vhdr;
5784 int offset = skb->data - skb_mac_header(skb);
5787 if (WARN_ONCE(offset,
5788 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5793 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5797 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5799 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5800 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5802 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5803 __skb_pull(skb, VLAN_HLEN);
5805 vlan_set_encap_proto(skb, vhdr);
5806 skb->mac_header += VLAN_HLEN;
5808 if (skb_network_offset(skb) < ETH_HLEN)
5809 skb_set_network_header(skb, ETH_HLEN);
5811 skb_reset_mac_len(skb);
5815 EXPORT_SYMBOL(__skb_vlan_pop);
5817 /* Pop a vlan tag either from hwaccel or from payload.
5818 * Expects skb->data at mac header.
5820 int skb_vlan_pop(struct sk_buff *skb)
5826 if (likely(skb_vlan_tag_present(skb))) {
5827 __vlan_hwaccel_clear_tag(skb);
5829 if (unlikely(!eth_type_vlan(skb->protocol)))
5832 err = __skb_vlan_pop(skb, &vlan_tci);
5836 /* move next vlan tag to hw accel tag */
5837 if (likely(!eth_type_vlan(skb->protocol)))
5840 vlan_proto = skb->protocol;
5841 err = __skb_vlan_pop(skb, &vlan_tci);
5845 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5848 EXPORT_SYMBOL(skb_vlan_pop);
5850 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5851 * Expects skb->data at mac header.
5853 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5855 if (skb_vlan_tag_present(skb)) {
5856 int offset = skb->data - skb_mac_header(skb);
5859 if (WARN_ONCE(offset,
5860 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5865 err = __vlan_insert_tag(skb, skb->vlan_proto,
5866 skb_vlan_tag_get(skb));
5870 skb->protocol = skb->vlan_proto;
5871 skb->mac_len += VLAN_HLEN;
5873 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5875 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5878 EXPORT_SYMBOL(skb_vlan_push);
5881 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5883 * @skb: Socket buffer to modify
5885 * Drop the Ethernet header of @skb.
5887 * Expects that skb->data points to the mac header and that no VLAN tags are
5890 * Returns 0 on success, -errno otherwise.
5892 int skb_eth_pop(struct sk_buff *skb)
5894 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5895 skb_network_offset(skb) < ETH_HLEN)
5898 skb_pull_rcsum(skb, ETH_HLEN);
5899 skb_reset_mac_header(skb);
5900 skb_reset_mac_len(skb);
5904 EXPORT_SYMBOL(skb_eth_pop);
5907 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5909 * @skb: Socket buffer to modify
5910 * @dst: Destination MAC address of the new header
5911 * @src: Source MAC address of the new header
5913 * Prepend @skb with a new Ethernet header.
5915 * Expects that skb->data points to the mac header, which must be empty.
5917 * Returns 0 on success, -errno otherwise.
5919 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5920 const unsigned char *src)
5925 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5928 err = skb_cow_head(skb, sizeof(*eth));
5932 skb_push(skb, sizeof(*eth));
5933 skb_reset_mac_header(skb);
5934 skb_reset_mac_len(skb);
5937 ether_addr_copy(eth->h_dest, dst);
5938 ether_addr_copy(eth->h_source, src);
5939 eth->h_proto = skb->protocol;
5941 skb_postpush_rcsum(skb, eth, sizeof(*eth));
5945 EXPORT_SYMBOL(skb_eth_push);
5947 /* Update the ethertype of hdr and the skb csum value if required. */
5948 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5951 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5952 __be16 diff[] = { ~hdr->h_proto, ethertype };
5954 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5957 hdr->h_proto = ethertype;
5961 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5965 * @mpls_lse: MPLS label stack entry to push
5966 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5967 * @mac_len: length of the MAC header
5968 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5971 * Expects skb->data at mac header.
5973 * Returns 0 on success, -errno otherwise.
5975 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5976 int mac_len, bool ethernet)
5978 struct mpls_shim_hdr *lse;
5981 if (unlikely(!eth_p_mpls(mpls_proto)))
5984 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5985 if (skb->encapsulation)
5988 err = skb_cow_head(skb, MPLS_HLEN);
5992 if (!skb->inner_protocol) {
5993 skb_set_inner_network_header(skb, skb_network_offset(skb));
5994 skb_set_inner_protocol(skb, skb->protocol);
5997 skb_push(skb, MPLS_HLEN);
5998 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6000 skb_reset_mac_header(skb);
6001 skb_set_network_header(skb, mac_len);
6002 skb_reset_mac_len(skb);
6004 lse = mpls_hdr(skb);
6005 lse->label_stack_entry = mpls_lse;
6006 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6008 if (ethernet && mac_len >= ETH_HLEN)
6009 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6010 skb->protocol = mpls_proto;
6014 EXPORT_SYMBOL_GPL(skb_mpls_push);
6017 * skb_mpls_pop() - pop the outermost MPLS header
6020 * @next_proto: ethertype of header after popped MPLS header
6021 * @mac_len: length of the MAC header
6022 * @ethernet: flag to indicate if the packet is ethernet
6024 * Expects skb->data at mac header.
6026 * Returns 0 on success, -errno otherwise.
6028 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6033 if (unlikely(!eth_p_mpls(skb->protocol)))
6036 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6040 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6041 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6044 __skb_pull(skb, MPLS_HLEN);
6045 skb_reset_mac_header(skb);
6046 skb_set_network_header(skb, mac_len);
6048 if (ethernet && mac_len >= ETH_HLEN) {
6051 /* use mpls_hdr() to get ethertype to account for VLANs. */
6052 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6053 skb_mod_eth_type(skb, hdr, next_proto);
6055 skb->protocol = next_proto;
6059 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6062 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6065 * @mpls_lse: new MPLS label stack entry to update to
6067 * Expects skb->data at mac header.
6069 * Returns 0 on success, -errno otherwise.
6071 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6075 if (unlikely(!eth_p_mpls(skb->protocol)))
6078 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6082 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6083 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6085 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6088 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6092 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6095 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6099 * Expects skb->data at mac header.
6101 * Returns 0 on success, -errno otherwise.
6103 int skb_mpls_dec_ttl(struct sk_buff *skb)
6108 if (unlikely(!eth_p_mpls(skb->protocol)))
6111 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6114 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6115 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6119 lse &= ~MPLS_LS_TTL_MASK;
6120 lse |= ttl << MPLS_LS_TTL_SHIFT;
6122 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6124 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6127 * alloc_skb_with_frags - allocate skb with page frags
6129 * @header_len: size of linear part
6130 * @data_len: needed length in frags
6131 * @max_page_order: max page order desired.
6132 * @errcode: pointer to error code if any
6133 * @gfp_mask: allocation mask
6135 * This can be used to allocate a paged skb, given a maximal order for frags.
6137 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6138 unsigned long data_len,
6143 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6144 unsigned long chunk;
6145 struct sk_buff *skb;
6149 *errcode = -EMSGSIZE;
6150 /* Note this test could be relaxed, if we succeed to allocate
6151 * high order pages...
6153 if (npages > MAX_SKB_FRAGS)
6156 *errcode = -ENOBUFS;
6157 skb = alloc_skb(header_len, gfp_mask);
6161 skb->truesize += npages << PAGE_SHIFT;
6163 for (i = 0; npages > 0; i++) {
6164 int order = max_page_order;
6167 if (npages >= 1 << order) {
6168 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6174 /* Do not retry other high order allocations */
6180 page = alloc_page(gfp_mask);
6184 chunk = min_t(unsigned long, data_len,
6185 PAGE_SIZE << order);
6186 skb_fill_page_desc(skb, i, page, 0, chunk);
6188 npages -= 1 << order;
6196 EXPORT_SYMBOL(alloc_skb_with_frags);
6198 /* carve out the first off bytes from skb when off < headlen */
6199 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6200 const int headlen, gfp_t gfp_mask)
6203 unsigned int size = skb_end_offset(skb);
6204 int new_hlen = headlen - off;
6207 if (skb_pfmemalloc(skb))
6208 gfp_mask |= __GFP_MEMALLOC;
6210 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6213 size = SKB_WITH_OVERHEAD(size);
6215 /* Copy real data, and all frags */
6216 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6219 memcpy((struct skb_shared_info *)(data + size),
6221 offsetof(struct skb_shared_info,
6222 frags[skb_shinfo(skb)->nr_frags]));
6223 if (skb_cloned(skb)) {
6224 /* drop the old head gracefully */
6225 if (skb_orphan_frags(skb, gfp_mask)) {
6229 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6230 skb_frag_ref(skb, i);
6231 if (skb_has_frag_list(skb))
6232 skb_clone_fraglist(skb);
6233 skb_release_data(skb);
6235 /* we can reuse existing recount- all we did was
6244 skb_set_end_offset(skb, size);
6245 skb_set_tail_pointer(skb, skb_headlen(skb));
6246 skb_headers_offset_update(skb, 0);
6250 atomic_set(&skb_shinfo(skb)->dataref, 1);
6255 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6257 /* carve out the first eat bytes from skb's frag_list. May recurse into
6260 static int pskb_carve_frag_list(struct sk_buff *skb,
6261 struct skb_shared_info *shinfo, int eat,
6264 struct sk_buff *list = shinfo->frag_list;
6265 struct sk_buff *clone = NULL;
6266 struct sk_buff *insp = NULL;
6270 pr_err("Not enough bytes to eat. Want %d\n", eat);
6273 if (list->len <= eat) {
6274 /* Eaten as whole. */
6279 /* Eaten partially. */
6280 if (skb_shared(list)) {
6281 clone = skb_clone(list, gfp_mask);
6287 /* This may be pulled without problems. */
6290 if (pskb_carve(list, eat, gfp_mask) < 0) {
6298 /* Free pulled out fragments. */
6299 while ((list = shinfo->frag_list) != insp) {
6300 shinfo->frag_list = list->next;
6303 /* And insert new clone at head. */
6306 shinfo->frag_list = clone;
6311 /* carve off first len bytes from skb. Split line (off) is in the
6312 * non-linear part of skb
6314 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6315 int pos, gfp_t gfp_mask)
6318 unsigned int size = skb_end_offset(skb);
6320 const int nfrags = skb_shinfo(skb)->nr_frags;
6321 struct skb_shared_info *shinfo;
6323 if (skb_pfmemalloc(skb))
6324 gfp_mask |= __GFP_MEMALLOC;
6326 data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6329 size = SKB_WITH_OVERHEAD(size);
6331 memcpy((struct skb_shared_info *)(data + size),
6332 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6333 if (skb_orphan_frags(skb, gfp_mask)) {
6337 shinfo = (struct skb_shared_info *)(data + size);
6338 for (i = 0; i < nfrags; i++) {
6339 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6341 if (pos + fsize > off) {
6342 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6346 * We have two variants in this case:
6347 * 1. Move all the frag to the second
6348 * part, if it is possible. F.e.
6349 * this approach is mandatory for TUX,
6350 * where splitting is expensive.
6351 * 2. Split is accurately. We make this.
6353 skb_frag_off_add(&shinfo->frags[0], off - pos);
6354 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6356 skb_frag_ref(skb, i);
6361 shinfo->nr_frags = k;
6362 if (skb_has_frag_list(skb))
6363 skb_clone_fraglist(skb);
6365 /* split line is in frag list */
6366 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6367 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6368 if (skb_has_frag_list(skb))
6369 kfree_skb_list(skb_shinfo(skb)->frag_list);
6373 skb_release_data(skb);
6378 skb_set_end_offset(skb, size);
6379 skb_reset_tail_pointer(skb);
6380 skb_headers_offset_update(skb, 0);
6385 skb->data_len = skb->len;
6386 atomic_set(&skb_shinfo(skb)->dataref, 1);
6390 /* remove len bytes from the beginning of the skb */
6391 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6393 int headlen = skb_headlen(skb);
6396 return pskb_carve_inside_header(skb, len, headlen, gfp);
6398 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6401 /* Extract to_copy bytes starting at off from skb, and return this in
6404 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6405 int to_copy, gfp_t gfp)
6407 struct sk_buff *clone = skb_clone(skb, gfp);
6412 if (pskb_carve(clone, off, gfp) < 0 ||
6413 pskb_trim(clone, to_copy)) {
6419 EXPORT_SYMBOL(pskb_extract);
6422 * skb_condense - try to get rid of fragments/frag_list if possible
6425 * Can be used to save memory before skb is added to a busy queue.
6426 * If packet has bytes in frags and enough tail room in skb->head,
6427 * pull all of them, so that we can free the frags right now and adjust
6430 * We do not reallocate skb->head thus can not fail.
6431 * Caller must re-evaluate skb->truesize if needed.
6433 void skb_condense(struct sk_buff *skb)
6435 if (skb->data_len) {
6436 if (skb->data_len > skb->end - skb->tail ||
6440 /* Nice, we can free page frag(s) right now */
6441 __pskb_pull_tail(skb, skb->data_len);
6443 /* At this point, skb->truesize might be over estimated,
6444 * because skb had a fragment, and fragments do not tell
6446 * When we pulled its content into skb->head, fragment
6447 * was freed, but __pskb_pull_tail() could not possibly
6448 * adjust skb->truesize, not knowing the frag truesize.
6450 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6453 #ifdef CONFIG_SKB_EXTENSIONS
6454 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6456 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6460 * __skb_ext_alloc - allocate a new skb extensions storage
6462 * @flags: See kmalloc().
6464 * Returns the newly allocated pointer. The pointer can later attached to a
6465 * skb via __skb_ext_set().
6466 * Note: caller must handle the skb_ext as an opaque data.
6468 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6470 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6473 memset(new->offset, 0, sizeof(new->offset));
6474 refcount_set(&new->refcnt, 1);
6480 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6481 unsigned int old_active)
6483 struct skb_ext *new;
6485 if (refcount_read(&old->refcnt) == 1)
6488 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6492 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6493 refcount_set(&new->refcnt, 1);
6496 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6497 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6500 for (i = 0; i < sp->len; i++)
6501 xfrm_state_hold(sp->xvec[i]);
6504 #ifdef CONFIG_MCTP_FLOWS
6505 if (old_active & (1 << SKB_EXT_MCTP)) {
6506 struct mctp_flow *flow = skb_ext_get_ptr(old, SKB_EXT_MCTP);
6509 refcount_inc(&flow->key->refs);
6517 * __skb_ext_set - attach the specified extension storage to this skb
6520 * @ext: extension storage previously allocated via __skb_ext_alloc()
6522 * Existing extensions, if any, are cleared.
6524 * Returns the pointer to the extension.
6526 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6527 struct skb_ext *ext)
6529 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6532 newlen = newoff + skb_ext_type_len[id];
6533 ext->chunks = newlen;
6534 ext->offset[id] = newoff;
6535 skb->extensions = ext;
6536 skb->active_extensions = 1 << id;
6537 return skb_ext_get_ptr(ext, id);
6541 * skb_ext_add - allocate space for given extension, COW if needed
6543 * @id: extension to allocate space for
6545 * Allocates enough space for the given extension.
6546 * If the extension is already present, a pointer to that extension
6549 * If the skb was cloned, COW applies and the returned memory can be
6550 * modified without changing the extension space of clones buffers.
6552 * Returns pointer to the extension or NULL on allocation failure.
6554 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6556 struct skb_ext *new, *old = NULL;
6557 unsigned int newlen, newoff;
6559 if (skb->active_extensions) {
6560 old = skb->extensions;
6562 new = skb_ext_maybe_cow(old, skb->active_extensions);
6566 if (__skb_ext_exist(new, id))
6569 newoff = new->chunks;
6571 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6573 new = __skb_ext_alloc(GFP_ATOMIC);
6578 newlen = newoff + skb_ext_type_len[id];
6579 new->chunks = newlen;
6580 new->offset[id] = newoff;
6583 skb->extensions = new;
6584 skb->active_extensions |= 1 << id;
6585 return skb_ext_get_ptr(new, id);
6587 EXPORT_SYMBOL(skb_ext_add);
6590 static void skb_ext_put_sp(struct sec_path *sp)
6594 for (i = 0; i < sp->len; i++)
6595 xfrm_state_put(sp->xvec[i]);
6599 #ifdef CONFIG_MCTP_FLOWS
6600 static void skb_ext_put_mctp(struct mctp_flow *flow)
6603 mctp_key_unref(flow->key);
6607 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6609 struct skb_ext *ext = skb->extensions;
6611 skb->active_extensions &= ~(1 << id);
6612 if (skb->active_extensions == 0) {
6613 skb->extensions = NULL;
6616 } else if (id == SKB_EXT_SEC_PATH &&
6617 refcount_read(&ext->refcnt) == 1) {
6618 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6625 EXPORT_SYMBOL(__skb_ext_del);
6627 void __skb_ext_put(struct skb_ext *ext)
6629 /* If this is last clone, nothing can increment
6630 * it after check passes. Avoids one atomic op.
6632 if (refcount_read(&ext->refcnt) == 1)
6635 if (!refcount_dec_and_test(&ext->refcnt))
6639 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6640 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6642 #ifdef CONFIG_MCTP_FLOWS
6643 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6644 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6647 kmem_cache_free(skbuff_ext_cache, ext);
6649 EXPORT_SYMBOL(__skb_ext_put);
6650 #endif /* CONFIG_SKB_EXTENSIONS */
6653 * skb_attempt_defer_free - queue skb for remote freeing
6656 * Put @skb in a per-cpu list, using the cpu which
6657 * allocated the skb/pages to reduce false sharing
6658 * and memory zone spinlock contention.
6660 void skb_attempt_defer_free(struct sk_buff *skb)
6662 int cpu = skb->alloc_cpu;
6663 struct softnet_data *sd;
6664 unsigned long flags;
6665 unsigned int defer_max;
6668 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6670 cpu == raw_smp_processor_id()) {
6671 nodefer: __kfree_skb(skb);
6675 sd = &per_cpu(softnet_data, cpu);
6676 defer_max = READ_ONCE(sysctl_skb_defer_max);
6677 if (READ_ONCE(sd->defer_count) >= defer_max)
6680 spin_lock_irqsave(&sd->defer_lock, flags);
6681 /* Send an IPI every time queue reaches half capacity. */
6682 kick = sd->defer_count == (defer_max >> 1);
6683 /* Paired with the READ_ONCE() few lines above */
6684 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6686 skb->next = sd->defer_list;
6687 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6688 WRITE_ONCE(sd->defer_list, skb);
6689 spin_unlock_irqrestore(&sd->defer_lock, flags);
6691 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6692 * if we are unlucky enough (this seems very unlikely).
6694 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6695 smp_call_function_single_async(cpu, &sd->defer_csd);