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(size_t size, gfp_t flags, int node,
431 bool ret_pfmemalloc = false;
434 * Try a regular allocation, when that fails and we're not entitled
435 * to the reserves, fail.
437 obj = kmalloc_node_track_caller(size,
438 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
440 if (obj || !(gfp_pfmemalloc_allowed(flags)))
443 /* Try again but now we are using pfmemalloc reserves */
444 ret_pfmemalloc = true;
445 obj = kmalloc_node_track_caller(size, flags, node);
449 *pfmemalloc = ret_pfmemalloc;
454 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
455 * 'private' fields and also do memory statistics to find all the
461 * __alloc_skb - allocate a network buffer
462 * @size: size to allocate
463 * @gfp_mask: allocation mask
464 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
465 * instead of head cache and allocate a cloned (child) skb.
466 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
467 * allocations in case the data is required for writeback
468 * @node: numa node to allocate memory on
470 * Allocate a new &sk_buff. The returned buffer has no headroom and a
471 * tail room of at least size bytes. The object has a reference count
472 * of one. The return is the buffer. On a failure the return is %NULL.
474 * Buffers may only be allocated from interrupts using a @gfp_mask of
477 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
480 struct kmem_cache *cache;
486 cache = (flags & SKB_ALLOC_FCLONE)
487 ? skbuff_fclone_cache : skbuff_head_cache;
489 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
490 gfp_mask |= __GFP_MEMALLOC;
493 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
494 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
495 skb = napi_skb_cache_get();
497 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
502 /* We do our best to align skb_shared_info on a separate cache
503 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
504 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
505 * Both skb->head and skb_shared_info are cache line aligned.
507 size = SKB_DATA_ALIGN(size);
508 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
509 data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
512 /* kmalloc(size) might give us more room than requested.
513 * Put skb_shared_info exactly at the end of allocated zone,
514 * to allow max possible filling before reallocation.
517 size = SKB_WITH_OVERHEAD(osize);
518 prefetchw(data + size);
521 * Only clear those fields we need to clear, not those that we will
522 * actually initialise below. Hence, don't put any more fields after
523 * the tail pointer in struct sk_buff!
525 memset(skb, 0, offsetof(struct sk_buff, tail));
526 __build_skb_around(skb, data, osize);
527 skb->pfmemalloc = pfmemalloc;
529 if (flags & SKB_ALLOC_FCLONE) {
530 struct sk_buff_fclones *fclones;
532 fclones = container_of(skb, struct sk_buff_fclones, skb1);
534 skb->fclone = SKB_FCLONE_ORIG;
535 refcount_set(&fclones->fclone_ref, 1);
541 kmem_cache_free(cache, skb);
544 EXPORT_SYMBOL(__alloc_skb);
547 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
548 * @dev: network device to receive on
549 * @len: length to allocate
550 * @gfp_mask: get_free_pages mask, passed to alloc_skb
552 * Allocate a new &sk_buff and assign it a usage count of one. The
553 * buffer has NET_SKB_PAD headroom built in. Users should allocate
554 * the headroom they think they need without accounting for the
555 * built in space. The built in space is used for optimisations.
557 * %NULL is returned if there is no free memory.
559 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
562 struct page_frag_cache *nc;
569 /* If requested length is either too small or too big,
570 * we use kmalloc() for skb->head allocation.
572 if (len <= SKB_WITH_OVERHEAD(1024) ||
573 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
574 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
575 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
581 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
582 len = SKB_DATA_ALIGN(len);
584 if (sk_memalloc_socks())
585 gfp_mask |= __GFP_MEMALLOC;
587 if (in_hardirq() || irqs_disabled()) {
588 nc = this_cpu_ptr(&netdev_alloc_cache);
589 data = page_frag_alloc(nc, len, gfp_mask);
590 pfmemalloc = nc->pfmemalloc;
593 nc = this_cpu_ptr(&napi_alloc_cache.page);
594 data = page_frag_alloc(nc, len, gfp_mask);
595 pfmemalloc = nc->pfmemalloc;
602 skb = __build_skb(data, len);
603 if (unlikely(!skb)) {
613 skb_reserve(skb, NET_SKB_PAD);
619 EXPORT_SYMBOL(__netdev_alloc_skb);
622 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
623 * @napi: napi instance this buffer was allocated for
624 * @len: length to allocate
625 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
627 * Allocate a new sk_buff for use in NAPI receive. This buffer will
628 * attempt to allocate the head from a special reserved region used
629 * only for NAPI Rx allocation. By doing this we can save several
630 * CPU cycles by avoiding having to disable and re-enable IRQs.
632 * %NULL is returned if there is no free memory.
634 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
637 struct napi_alloc_cache *nc;
642 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
643 len += NET_SKB_PAD + NET_IP_ALIGN;
645 /* If requested length is either too small or too big,
646 * we use kmalloc() for skb->head allocation.
647 * When the small frag allocator is available, prefer it over kmalloc
648 * for small fragments
650 if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
651 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
652 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
653 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
660 nc = this_cpu_ptr(&napi_alloc_cache);
662 if (sk_memalloc_socks())
663 gfp_mask |= __GFP_MEMALLOC;
665 if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
666 /* we are artificially inflating the allocation size, but
667 * that is not as bad as it may look like, as:
668 * - 'len' less than GRO_MAX_HEAD makes little sense
669 * - On most systems, larger 'len' values lead to fragment
670 * size above 512 bytes
671 * - kmalloc would use the kmalloc-1k slab for such values
672 * - Builds with smaller GRO_MAX_HEAD will very likely do
673 * little networking, as that implies no WiFi and no
674 * tunnels support, and 32 bits arches.
678 data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
679 pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
681 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
682 len = SKB_DATA_ALIGN(len);
684 data = page_frag_alloc(&nc->page, len, gfp_mask);
685 pfmemalloc = nc->page.pfmemalloc;
691 skb = __napi_build_skb(data, len);
692 if (unlikely(!skb)) {
702 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
703 skb->dev = napi->dev;
708 EXPORT_SYMBOL(__napi_alloc_skb);
710 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
711 int size, unsigned int truesize)
713 skb_fill_page_desc(skb, i, page, off, size);
715 skb->data_len += size;
716 skb->truesize += truesize;
718 EXPORT_SYMBOL(skb_add_rx_frag);
720 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
721 unsigned int truesize)
723 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
725 skb_frag_size_add(frag, size);
727 skb->data_len += size;
728 skb->truesize += truesize;
730 EXPORT_SYMBOL(skb_coalesce_rx_frag);
732 static void skb_drop_list(struct sk_buff **listp)
734 kfree_skb_list(*listp);
738 static inline void skb_drop_fraglist(struct sk_buff *skb)
740 skb_drop_list(&skb_shinfo(skb)->frag_list);
743 static void skb_clone_fraglist(struct sk_buff *skb)
745 struct sk_buff *list;
747 skb_walk_frags(skb, list)
751 static void skb_free_head(struct sk_buff *skb)
753 unsigned char *head = skb->head;
755 if (skb->head_frag) {
756 if (skb_pp_recycle(skb, head))
764 static void skb_release_data(struct sk_buff *skb)
766 struct skb_shared_info *shinfo = skb_shinfo(skb);
770 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
774 if (skb_zcopy(skb)) {
775 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
777 skb_zcopy_clear(skb, true);
782 for (i = 0; i < shinfo->nr_frags; i++)
783 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
786 if (shinfo->frag_list)
787 kfree_skb_list(shinfo->frag_list);
791 /* When we clone an SKB we copy the reycling bit. The pp_recycle
792 * bit is only set on the head though, so in order to avoid races
793 * while trying to recycle fragments on __skb_frag_unref() we need
794 * to make one SKB responsible for triggering the recycle path.
795 * So disable the recycling bit if an SKB is cloned and we have
796 * additional references to the fragmented part of the SKB.
797 * Eventually the last SKB will have the recycling bit set and it's
798 * dataref set to 0, which will trigger the recycling
804 * Free an skbuff by memory without cleaning the state.
806 static void kfree_skbmem(struct sk_buff *skb)
808 struct sk_buff_fclones *fclones;
810 switch (skb->fclone) {
811 case SKB_FCLONE_UNAVAILABLE:
812 kmem_cache_free(skbuff_head_cache, skb);
815 case SKB_FCLONE_ORIG:
816 fclones = container_of(skb, struct sk_buff_fclones, skb1);
818 /* We usually free the clone (TX completion) before original skb
819 * This test would have no chance to be true for the clone,
820 * while here, branch prediction will be good.
822 if (refcount_read(&fclones->fclone_ref) == 1)
826 default: /* SKB_FCLONE_CLONE */
827 fclones = container_of(skb, struct sk_buff_fclones, skb2);
830 if (!refcount_dec_and_test(&fclones->fclone_ref))
833 kmem_cache_free(skbuff_fclone_cache, fclones);
836 void skb_release_head_state(struct sk_buff *skb)
839 if (skb->destructor) {
840 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
841 skb->destructor(skb);
843 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
844 nf_conntrack_put(skb_nfct(skb));
849 /* Free everything but the sk_buff shell. */
850 static void skb_release_all(struct sk_buff *skb)
852 skb_release_head_state(skb);
853 if (likely(skb->head))
854 skb_release_data(skb);
858 * __kfree_skb - private function
861 * Free an sk_buff. Release anything attached to the buffer.
862 * Clean the state. This is an internal helper function. Users should
863 * always call kfree_skb
866 void __kfree_skb(struct sk_buff *skb)
868 skb_release_all(skb);
871 EXPORT_SYMBOL(__kfree_skb);
874 * kfree_skb_reason - free an sk_buff with special reason
875 * @skb: buffer to free
876 * @reason: reason why this skb is dropped
878 * Drop a reference to the buffer and free it if the usage count has
879 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
883 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
885 if (unlikely(!skb_unref(skb)))
888 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
890 trace_kfree_skb(skb, __builtin_return_address(0), reason);
893 EXPORT_SYMBOL(kfree_skb_reason);
895 void kfree_skb_list_reason(struct sk_buff *segs,
896 enum skb_drop_reason reason)
899 struct sk_buff *next = segs->next;
901 kfree_skb_reason(segs, reason);
905 EXPORT_SYMBOL(kfree_skb_list_reason);
907 /* Dump skb information and contents.
909 * Must only be called from net_ratelimit()-ed paths.
911 * Dumps whole packets if full_pkt, only headers otherwise.
913 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
915 struct skb_shared_info *sh = skb_shinfo(skb);
916 struct net_device *dev = skb->dev;
917 struct sock *sk = skb->sk;
918 struct sk_buff *list_skb;
919 bool has_mac, has_trans;
920 int headroom, tailroom;
926 len = min_t(int, skb->len, MAX_HEADER + 128);
928 headroom = skb_headroom(skb);
929 tailroom = skb_tailroom(skb);
931 has_mac = skb_mac_header_was_set(skb);
932 has_trans = skb_transport_header_was_set(skb);
934 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
935 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
936 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
937 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
938 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
939 level, skb->len, headroom, skb_headlen(skb), tailroom,
940 has_mac ? skb->mac_header : -1,
941 has_mac ? skb_mac_header_len(skb) : -1,
943 has_trans ? skb_network_header_len(skb) : -1,
944 has_trans ? skb->transport_header : -1,
945 sh->tx_flags, sh->nr_frags,
946 sh->gso_size, sh->gso_type, sh->gso_segs,
947 skb->csum, skb->ip_summed, skb->csum_complete_sw,
948 skb->csum_valid, skb->csum_level,
949 skb->hash, skb->sw_hash, skb->l4_hash,
950 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
953 printk("%sdev name=%s feat=%pNF\n",
954 level, dev->name, &dev->features);
956 printk("%ssk family=%hu type=%u proto=%u\n",
957 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
959 if (full_pkt && headroom)
960 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
961 16, 1, skb->head, headroom, false);
963 seg_len = min_t(int, skb_headlen(skb), len);
965 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
966 16, 1, skb->data, seg_len, false);
969 if (full_pkt && tailroom)
970 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
971 16, 1, skb_tail_pointer(skb), tailroom, false);
973 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
974 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
975 u32 p_off, p_len, copied;
979 skb_frag_foreach_page(frag, skb_frag_off(frag),
980 skb_frag_size(frag), p, p_off, p_len,
982 seg_len = min_t(int, p_len, len);
983 vaddr = kmap_atomic(p);
984 print_hex_dump(level, "skb frag: ",
986 16, 1, vaddr + p_off, seg_len, false);
987 kunmap_atomic(vaddr);
994 if (full_pkt && skb_has_frag_list(skb)) {
995 printk("skb fraglist:\n");
996 skb_walk_frags(skb, list_skb)
997 skb_dump(level, list_skb, true);
1000 EXPORT_SYMBOL(skb_dump);
1003 * skb_tx_error - report an sk_buff xmit error
1004 * @skb: buffer that triggered an error
1006 * Report xmit error if a device callback is tracking this skb.
1007 * skb must be freed afterwards.
1009 void skb_tx_error(struct sk_buff *skb)
1012 skb_zcopy_downgrade_managed(skb);
1013 skb_zcopy_clear(skb, true);
1016 EXPORT_SYMBOL(skb_tx_error);
1018 #ifdef CONFIG_TRACEPOINTS
1020 * consume_skb - free an skbuff
1021 * @skb: buffer to free
1023 * Drop a ref to the buffer and free it if the usage count has hit zero
1024 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
1025 * is being dropped after a failure and notes that
1027 void consume_skb(struct sk_buff *skb)
1029 if (!skb_unref(skb))
1032 trace_consume_skb(skb);
1035 EXPORT_SYMBOL(consume_skb);
1039 * __consume_stateless_skb - free an skbuff, assuming it is stateless
1040 * @skb: buffer to free
1042 * Alike consume_skb(), but this variant assumes that this is the last
1043 * skb reference and all the head states have been already dropped
1045 void __consume_stateless_skb(struct sk_buff *skb)
1047 trace_consume_skb(skb);
1048 skb_release_data(skb);
1052 static void napi_skb_cache_put(struct sk_buff *skb)
1054 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1057 kasan_poison_object_data(skbuff_head_cache, skb);
1058 nc->skb_cache[nc->skb_count++] = skb;
1060 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1061 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1062 kasan_unpoison_object_data(skbuff_head_cache,
1065 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
1066 nc->skb_cache + NAPI_SKB_CACHE_HALF);
1067 nc->skb_count = NAPI_SKB_CACHE_HALF;
1071 void __kfree_skb_defer(struct sk_buff *skb)
1073 skb_release_all(skb);
1074 napi_skb_cache_put(skb);
1077 void napi_skb_free_stolen_head(struct sk_buff *skb)
1079 if (unlikely(skb->slow_gro)) {
1086 napi_skb_cache_put(skb);
1089 void napi_consume_skb(struct sk_buff *skb, int budget)
1091 /* Zero budget indicate non-NAPI context called us, like netpoll */
1092 if (unlikely(!budget)) {
1093 dev_consume_skb_any(skb);
1097 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1099 if (!skb_unref(skb))
1102 /* if reaching here SKB is ready to free */
1103 trace_consume_skb(skb);
1105 /* if SKB is a clone, don't handle this case */
1106 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1111 skb_release_all(skb);
1112 napi_skb_cache_put(skb);
1114 EXPORT_SYMBOL(napi_consume_skb);
1116 /* Make sure a field is contained by headers group */
1117 #define CHECK_SKB_FIELD(field) \
1118 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1119 offsetof(struct sk_buff, headers.field)); \
1121 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1123 new->tstamp = old->tstamp;
1124 /* We do not copy old->sk */
1125 new->dev = old->dev;
1126 memcpy(new->cb, old->cb, sizeof(old->cb));
1127 skb_dst_copy(new, old);
1128 __skb_ext_copy(new, old);
1129 __nf_copy(new, old, false);
1131 /* Note : this field could be in the headers group.
1132 * It is not yet because we do not want to have a 16 bit hole
1134 new->queue_mapping = old->queue_mapping;
1136 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1137 CHECK_SKB_FIELD(protocol);
1138 CHECK_SKB_FIELD(csum);
1139 CHECK_SKB_FIELD(hash);
1140 CHECK_SKB_FIELD(priority);
1141 CHECK_SKB_FIELD(skb_iif);
1142 CHECK_SKB_FIELD(vlan_proto);
1143 CHECK_SKB_FIELD(vlan_tci);
1144 CHECK_SKB_FIELD(transport_header);
1145 CHECK_SKB_FIELD(network_header);
1146 CHECK_SKB_FIELD(mac_header);
1147 CHECK_SKB_FIELD(inner_protocol);
1148 CHECK_SKB_FIELD(inner_transport_header);
1149 CHECK_SKB_FIELD(inner_network_header);
1150 CHECK_SKB_FIELD(inner_mac_header);
1151 CHECK_SKB_FIELD(mark);
1152 #ifdef CONFIG_NETWORK_SECMARK
1153 CHECK_SKB_FIELD(secmark);
1155 #ifdef CONFIG_NET_RX_BUSY_POLL
1156 CHECK_SKB_FIELD(napi_id);
1158 CHECK_SKB_FIELD(alloc_cpu);
1160 CHECK_SKB_FIELD(sender_cpu);
1162 #ifdef CONFIG_NET_SCHED
1163 CHECK_SKB_FIELD(tc_index);
1169 * You should not add any new code to this function. Add it to
1170 * __copy_skb_header above instead.
1172 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1174 #define C(x) n->x = skb->x
1176 n->next = n->prev = NULL;
1178 __copy_skb_header(n, skb);
1183 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1189 n->destructor = NULL;
1196 refcount_set(&n->users, 1);
1198 atomic_inc(&(skb_shinfo(skb)->dataref));
1206 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1207 * @first: first sk_buff of the msg
1209 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1213 n = alloc_skb(0, GFP_ATOMIC);
1217 n->len = first->len;
1218 n->data_len = first->len;
1219 n->truesize = first->truesize;
1221 skb_shinfo(n)->frag_list = first;
1223 __copy_skb_header(n, first);
1224 n->destructor = NULL;
1228 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1231 * skb_morph - morph one skb into another
1232 * @dst: the skb to receive the contents
1233 * @src: the skb to supply the contents
1235 * This is identical to skb_clone except that the target skb is
1236 * supplied by the user.
1238 * The target skb is returned upon exit.
1240 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1242 skb_release_all(dst);
1243 return __skb_clone(dst, src);
1245 EXPORT_SYMBOL_GPL(skb_morph);
1247 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1249 unsigned long max_pg, num_pg, new_pg, old_pg;
1250 struct user_struct *user;
1252 if (capable(CAP_IPC_LOCK) || !size)
1255 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1256 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1257 user = mmp->user ? : current_user();
1260 old_pg = atomic_long_read(&user->locked_vm);
1261 new_pg = old_pg + num_pg;
1262 if (new_pg > max_pg)
1264 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1268 mmp->user = get_uid(user);
1269 mmp->num_pg = num_pg;
1271 mmp->num_pg += num_pg;
1276 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1278 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1281 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1282 free_uid(mmp->user);
1285 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1287 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1289 struct ubuf_info_msgzc *uarg;
1290 struct sk_buff *skb;
1292 WARN_ON_ONCE(!in_task());
1294 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1298 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1299 uarg = (void *)skb->cb;
1300 uarg->mmp.user = NULL;
1302 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1307 uarg->ubuf.callback = msg_zerocopy_callback;
1308 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1310 uarg->bytelen = size;
1312 uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1313 refcount_set(&uarg->ubuf.refcnt, 1);
1319 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1321 return container_of((void *)uarg, struct sk_buff, cb);
1324 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1325 struct ubuf_info *uarg)
1328 struct ubuf_info_msgzc *uarg_zc;
1329 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1332 /* there might be non MSG_ZEROCOPY users */
1333 if (uarg->callback != msg_zerocopy_callback)
1336 /* realloc only when socket is locked (TCP, UDP cork),
1337 * so uarg->len and sk_zckey access is serialized
1339 if (!sock_owned_by_user(sk)) {
1344 uarg_zc = uarg_to_msgzc(uarg);
1345 bytelen = uarg_zc->bytelen + size;
1346 if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1347 /* TCP can create new skb to attach new uarg */
1348 if (sk->sk_type == SOCK_STREAM)
1353 next = (u32)atomic_read(&sk->sk_zckey);
1354 if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1355 if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1358 uarg_zc->bytelen = bytelen;
1359 atomic_set(&sk->sk_zckey, ++next);
1361 /* no extra ref when appending to datagram (MSG_MORE) */
1362 if (sk->sk_type == SOCK_STREAM)
1363 net_zcopy_get(uarg);
1370 return msg_zerocopy_alloc(sk, size);
1372 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1374 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1376 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1380 old_lo = serr->ee.ee_info;
1381 old_hi = serr->ee.ee_data;
1382 sum_len = old_hi - old_lo + 1ULL + len;
1384 if (sum_len >= (1ULL << 32))
1387 if (lo != old_hi + 1)
1390 serr->ee.ee_data += len;
1394 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1396 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1397 struct sock_exterr_skb *serr;
1398 struct sock *sk = skb->sk;
1399 struct sk_buff_head *q;
1400 unsigned long flags;
1405 mm_unaccount_pinned_pages(&uarg->mmp);
1407 /* if !len, there was only 1 call, and it was aborted
1408 * so do not queue a completion notification
1410 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1415 hi = uarg->id + len - 1;
1416 is_zerocopy = uarg->zerocopy;
1418 serr = SKB_EXT_ERR(skb);
1419 memset(serr, 0, sizeof(*serr));
1420 serr->ee.ee_errno = 0;
1421 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1422 serr->ee.ee_data = hi;
1423 serr->ee.ee_info = lo;
1425 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1427 q = &sk->sk_error_queue;
1428 spin_lock_irqsave(&q->lock, flags);
1429 tail = skb_peek_tail(q);
1430 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1431 !skb_zerocopy_notify_extend(tail, lo, len)) {
1432 __skb_queue_tail(q, skb);
1435 spin_unlock_irqrestore(&q->lock, flags);
1437 sk_error_report(sk);
1444 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1447 struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1449 uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1451 if (refcount_dec_and_test(&uarg->refcnt))
1452 __msg_zerocopy_callback(uarg_zc);
1454 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1456 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1458 struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1460 atomic_dec(&sk->sk_zckey);
1461 uarg_to_msgzc(uarg)->len--;
1464 msg_zerocopy_callback(NULL, uarg, true);
1466 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1468 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1469 struct msghdr *msg, int len,
1470 struct ubuf_info *uarg)
1472 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1473 int err, orig_len = skb->len;
1475 /* An skb can only point to one uarg. This edge case happens when
1476 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1478 if (orig_uarg && uarg != orig_uarg)
1481 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1482 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1483 struct sock *save_sk = skb->sk;
1485 /* Streams do not free skb on error. Reset to prev state. */
1486 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1488 ___pskb_trim(skb, orig_len);
1493 skb_zcopy_set(skb, uarg, NULL);
1494 return skb->len - orig_len;
1496 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1498 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1502 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1503 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1504 skb_frag_ref(skb, i);
1506 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1508 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1511 if (skb_zcopy(orig)) {
1512 if (skb_zcopy(nskb)) {
1513 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1518 if (skb_uarg(nskb) == skb_uarg(orig))
1520 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1523 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1529 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1530 * @skb: the skb to modify
1531 * @gfp_mask: allocation priority
1533 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1534 * It will copy all frags into kernel and drop the reference
1535 * to userspace pages.
1537 * If this function is called from an interrupt gfp_mask() must be
1540 * Returns 0 on success or a negative error code on failure
1541 * to allocate kernel memory to copy to.
1543 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1545 int num_frags = skb_shinfo(skb)->nr_frags;
1546 struct page *page, *head = NULL;
1547 int i, order, psize, new_frags;
1550 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1556 /* We might have to allocate high order pages, so compute what minimum
1557 * page order is needed.
1560 while ((PAGE_SIZE << order) * MAX_SKB_FRAGS < __skb_pagelen(skb))
1562 psize = (PAGE_SIZE << order);
1564 new_frags = (__skb_pagelen(skb) + psize - 1) >> (PAGE_SHIFT + order);
1565 for (i = 0; i < new_frags; i++) {
1566 page = alloc_pages(gfp_mask | __GFP_COMP, order);
1569 struct page *next = (struct page *)page_private(head);
1575 set_page_private(page, (unsigned long)head);
1581 for (i = 0; i < num_frags; i++) {
1582 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1583 u32 p_off, p_len, copied;
1587 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1588 p, p_off, p_len, copied) {
1590 vaddr = kmap_atomic(p);
1592 while (done < p_len) {
1593 if (d_off == psize) {
1595 page = (struct page *)page_private(page);
1597 copy = min_t(u32, psize - d_off, p_len - done);
1598 memcpy(page_address(page) + d_off,
1599 vaddr + p_off + done, copy);
1603 kunmap_atomic(vaddr);
1607 /* skb frags release userspace buffers */
1608 for (i = 0; i < num_frags; i++)
1609 skb_frag_unref(skb, i);
1611 /* skb frags point to kernel buffers */
1612 for (i = 0; i < new_frags - 1; i++) {
1613 __skb_fill_page_desc(skb, i, head, 0, psize);
1614 head = (struct page *)page_private(head);
1616 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1617 skb_shinfo(skb)->nr_frags = new_frags;
1620 skb_zcopy_clear(skb, false);
1623 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1626 * skb_clone - duplicate an sk_buff
1627 * @skb: buffer to clone
1628 * @gfp_mask: allocation priority
1630 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1631 * copies share the same packet data but not structure. The new
1632 * buffer has a reference count of 1. If the allocation fails the
1633 * function returns %NULL otherwise the new buffer is returned.
1635 * If this function is called from an interrupt gfp_mask() must be
1639 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1641 struct sk_buff_fclones *fclones = container_of(skb,
1642 struct sk_buff_fclones,
1646 if (skb_orphan_frags(skb, gfp_mask))
1649 if (skb->fclone == SKB_FCLONE_ORIG &&
1650 refcount_read(&fclones->fclone_ref) == 1) {
1652 refcount_set(&fclones->fclone_ref, 2);
1653 n->fclone = SKB_FCLONE_CLONE;
1655 if (skb_pfmemalloc(skb))
1656 gfp_mask |= __GFP_MEMALLOC;
1658 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1662 n->fclone = SKB_FCLONE_UNAVAILABLE;
1665 return __skb_clone(n, skb);
1667 EXPORT_SYMBOL(skb_clone);
1669 void skb_headers_offset_update(struct sk_buff *skb, int off)
1671 /* Only adjust this if it actually is csum_start rather than csum */
1672 if (skb->ip_summed == CHECKSUM_PARTIAL)
1673 skb->csum_start += off;
1674 /* {transport,network,mac}_header and tail are relative to skb->head */
1675 skb->transport_header += off;
1676 skb->network_header += off;
1677 if (skb_mac_header_was_set(skb))
1678 skb->mac_header += off;
1679 skb->inner_transport_header += off;
1680 skb->inner_network_header += off;
1681 skb->inner_mac_header += off;
1683 EXPORT_SYMBOL(skb_headers_offset_update);
1685 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1687 __copy_skb_header(new, old);
1689 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1690 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1691 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1693 EXPORT_SYMBOL(skb_copy_header);
1695 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1697 if (skb_pfmemalloc(skb))
1698 return SKB_ALLOC_RX;
1703 * skb_copy - create private copy of an sk_buff
1704 * @skb: buffer to copy
1705 * @gfp_mask: allocation priority
1707 * Make a copy of both an &sk_buff and its data. This is used when the
1708 * caller wishes to modify the data and needs a private copy of the
1709 * data to alter. Returns %NULL on failure or the pointer to the buffer
1710 * on success. The returned buffer has a reference count of 1.
1712 * As by-product this function converts non-linear &sk_buff to linear
1713 * one, so that &sk_buff becomes completely private and caller is allowed
1714 * to modify all the data of returned buffer. This means that this
1715 * function is not recommended for use in circumstances when only
1716 * header is going to be modified. Use pskb_copy() instead.
1719 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1721 int headerlen = skb_headroom(skb);
1722 unsigned int size = skb_end_offset(skb) + skb->data_len;
1723 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1724 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1729 /* Set the data pointer */
1730 skb_reserve(n, headerlen);
1731 /* Set the tail pointer and length */
1732 skb_put(n, skb->len);
1734 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1736 skb_copy_header(n, skb);
1739 EXPORT_SYMBOL(skb_copy);
1742 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1743 * @skb: buffer to copy
1744 * @headroom: headroom of new skb
1745 * @gfp_mask: allocation priority
1746 * @fclone: if true allocate the copy of the skb from the fclone
1747 * cache instead of the head cache; it is recommended to set this
1748 * to true for the cases where the copy will likely be cloned
1750 * Make a copy of both an &sk_buff and part of its data, located
1751 * in header. Fragmented data remain shared. This is used when
1752 * the caller wishes to modify only header of &sk_buff and needs
1753 * private copy of the header to alter. Returns %NULL on failure
1754 * or the pointer to the buffer on success.
1755 * The returned buffer has a reference count of 1.
1758 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1759 gfp_t gfp_mask, bool fclone)
1761 unsigned int size = skb_headlen(skb) + headroom;
1762 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1763 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1768 /* Set the data pointer */
1769 skb_reserve(n, headroom);
1770 /* Set the tail pointer and length */
1771 skb_put(n, skb_headlen(skb));
1772 /* Copy the bytes */
1773 skb_copy_from_linear_data(skb, n->data, n->len);
1775 n->truesize += skb->data_len;
1776 n->data_len = skb->data_len;
1779 if (skb_shinfo(skb)->nr_frags) {
1782 if (skb_orphan_frags(skb, gfp_mask) ||
1783 skb_zerocopy_clone(n, skb, gfp_mask)) {
1788 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1789 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1790 skb_frag_ref(skb, i);
1792 skb_shinfo(n)->nr_frags = i;
1795 if (skb_has_frag_list(skb)) {
1796 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1797 skb_clone_fraglist(n);
1800 skb_copy_header(n, skb);
1804 EXPORT_SYMBOL(__pskb_copy_fclone);
1807 * pskb_expand_head - reallocate header of &sk_buff
1808 * @skb: buffer to reallocate
1809 * @nhead: room to add at head
1810 * @ntail: room to add at tail
1811 * @gfp_mask: allocation priority
1813 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1814 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1815 * reference count of 1. Returns zero in the case of success or error,
1816 * if expansion failed. In the last case, &sk_buff is not changed.
1818 * All the pointers pointing into skb header may change and must be
1819 * reloaded after call to this function.
1822 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1825 int i, osize = skb_end_offset(skb);
1826 int size = osize + nhead + ntail;
1832 BUG_ON(skb_shared(skb));
1834 skb_zcopy_downgrade_managed(skb);
1836 size = SKB_DATA_ALIGN(size);
1838 if (skb_pfmemalloc(skb))
1839 gfp_mask |= __GFP_MEMALLOC;
1840 data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1841 gfp_mask, NUMA_NO_NODE, NULL);
1844 size = SKB_WITH_OVERHEAD(ksize(data));
1846 /* Copy only real data... and, alas, header. This should be
1847 * optimized for the cases when header is void.
1849 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1851 memcpy((struct skb_shared_info *)(data + size),
1853 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1856 * if shinfo is shared we must drop the old head gracefully, but if it
1857 * is not we can just drop the old head and let the existing refcount
1858 * be since all we did is relocate the values
1860 if (skb_cloned(skb)) {
1861 if (skb_orphan_frags(skb, gfp_mask))
1864 refcount_inc(&skb_uarg(skb)->refcnt);
1865 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1866 skb_frag_ref(skb, i);
1868 if (skb_has_frag_list(skb))
1869 skb_clone_fraglist(skb);
1871 skb_release_data(skb);
1875 off = (data + nhead) - skb->head;
1881 skb_set_end_offset(skb, size);
1882 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1886 skb_headers_offset_update(skb, nhead);
1890 atomic_set(&skb_shinfo(skb)->dataref, 1);
1892 skb_metadata_clear(skb);
1894 /* It is not generally safe to change skb->truesize.
1895 * For the moment, we really care of rx path, or
1896 * when skb is orphaned (not attached to a socket).
1898 if (!skb->sk || skb->destructor == sock_edemux)
1899 skb->truesize += size - osize;
1908 EXPORT_SYMBOL(pskb_expand_head);
1910 /* Make private copy of skb with writable head and some headroom */
1912 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1914 struct sk_buff *skb2;
1915 int delta = headroom - skb_headroom(skb);
1918 skb2 = pskb_copy(skb, GFP_ATOMIC);
1920 skb2 = skb_clone(skb, GFP_ATOMIC);
1921 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1929 EXPORT_SYMBOL(skb_realloc_headroom);
1931 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1933 unsigned int saved_end_offset, saved_truesize;
1934 struct skb_shared_info *shinfo;
1937 saved_end_offset = skb_end_offset(skb);
1938 saved_truesize = skb->truesize;
1940 res = pskb_expand_head(skb, 0, 0, pri);
1944 skb->truesize = saved_truesize;
1946 if (likely(skb_end_offset(skb) == saved_end_offset))
1949 shinfo = skb_shinfo(skb);
1951 /* We are about to change back skb->end,
1952 * we need to move skb_shinfo() to its new location.
1954 memmove(skb->head + saved_end_offset,
1956 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1958 skb_set_end_offset(skb, saved_end_offset);
1964 * skb_expand_head - reallocate header of &sk_buff
1965 * @skb: buffer to reallocate
1966 * @headroom: needed headroom
1968 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1969 * if possible; copies skb->sk to new skb as needed
1970 * and frees original skb in case of failures.
1972 * It expect increased headroom and generates warning otherwise.
1975 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1977 int delta = headroom - skb_headroom(skb);
1978 int osize = skb_end_offset(skb);
1979 struct sock *sk = skb->sk;
1981 if (WARN_ONCE(delta <= 0,
1982 "%s is expecting an increase in the headroom", __func__))
1985 delta = SKB_DATA_ALIGN(delta);
1986 /* pskb_expand_head() might crash, if skb is shared. */
1987 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1988 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1990 if (unlikely(!nskb))
1994 skb_set_owner_w(nskb, sk);
1998 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2001 if (sk && is_skb_wmem(skb)) {
2002 delta = skb_end_offset(skb) - osize;
2003 refcount_add(delta, &sk->sk_wmem_alloc);
2004 skb->truesize += delta;
2012 EXPORT_SYMBOL(skb_expand_head);
2015 * skb_copy_expand - copy and expand sk_buff
2016 * @skb: buffer to copy
2017 * @newheadroom: new free bytes at head
2018 * @newtailroom: new free bytes at tail
2019 * @gfp_mask: allocation priority
2021 * Make a copy of both an &sk_buff and its data and while doing so
2022 * allocate additional space.
2024 * This is used when the caller wishes to modify the data and needs a
2025 * private copy of the data to alter as well as more space for new fields.
2026 * Returns %NULL on failure or the pointer to the buffer
2027 * on success. The returned buffer has a reference count of 1.
2029 * You must pass %GFP_ATOMIC as the allocation priority if this function
2030 * is called from an interrupt.
2032 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2033 int newheadroom, int newtailroom,
2037 * Allocate the copy buffer
2039 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2040 gfp_mask, skb_alloc_rx_flag(skb),
2042 int oldheadroom = skb_headroom(skb);
2043 int head_copy_len, head_copy_off;
2048 skb_reserve(n, newheadroom);
2050 /* Set the tail pointer and length */
2051 skb_put(n, skb->len);
2053 head_copy_len = oldheadroom;
2055 if (newheadroom <= head_copy_len)
2056 head_copy_len = newheadroom;
2058 head_copy_off = newheadroom - head_copy_len;
2060 /* Copy the linear header and data. */
2061 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2062 skb->len + head_copy_len));
2064 skb_copy_header(n, skb);
2066 skb_headers_offset_update(n, newheadroom - oldheadroom);
2070 EXPORT_SYMBOL(skb_copy_expand);
2073 * __skb_pad - zero pad the tail of an skb
2074 * @skb: buffer to pad
2075 * @pad: space to pad
2076 * @free_on_error: free buffer on error
2078 * Ensure that a buffer is followed by a padding area that is zero
2079 * filled. Used by network drivers which may DMA or transfer data
2080 * beyond the buffer end onto the wire.
2082 * May return error in out of memory cases. The skb is freed on error
2083 * if @free_on_error is true.
2086 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2091 /* If the skbuff is non linear tailroom is always zero.. */
2092 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2093 memset(skb->data+skb->len, 0, pad);
2097 ntail = skb->data_len + pad - (skb->end - skb->tail);
2098 if (likely(skb_cloned(skb) || ntail > 0)) {
2099 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2104 /* FIXME: The use of this function with non-linear skb's really needs
2107 err = skb_linearize(skb);
2111 memset(skb->data + skb->len, 0, pad);
2119 EXPORT_SYMBOL(__skb_pad);
2122 * pskb_put - add data to the tail of a potentially fragmented buffer
2123 * @skb: start of the buffer to use
2124 * @tail: tail fragment of the buffer to use
2125 * @len: amount of data to add
2127 * This function extends the used data area of the potentially
2128 * fragmented buffer. @tail must be the last fragment of @skb -- or
2129 * @skb itself. If this would exceed the total buffer size the kernel
2130 * will panic. A pointer to the first byte of the extra data is
2134 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2137 skb->data_len += len;
2140 return skb_put(tail, len);
2142 EXPORT_SYMBOL_GPL(pskb_put);
2145 * skb_put - add data to a buffer
2146 * @skb: buffer to use
2147 * @len: amount of data to add
2149 * This function extends the used data area of the buffer. If this would
2150 * exceed the total buffer size the kernel will panic. A pointer to the
2151 * first byte of the extra data is returned.
2153 void *skb_put(struct sk_buff *skb, unsigned int len)
2155 void *tmp = skb_tail_pointer(skb);
2156 SKB_LINEAR_ASSERT(skb);
2159 if (unlikely(skb->tail > skb->end))
2160 skb_over_panic(skb, len, __builtin_return_address(0));
2163 EXPORT_SYMBOL(skb_put);
2166 * skb_push - add data to the start of a buffer
2167 * @skb: buffer to use
2168 * @len: amount of data to add
2170 * This function extends the used data area of the buffer at the buffer
2171 * start. If this would exceed the total buffer headroom the kernel will
2172 * panic. A pointer to the first byte of the extra data is returned.
2174 void *skb_push(struct sk_buff *skb, unsigned int len)
2178 if (unlikely(skb->data < skb->head))
2179 skb_under_panic(skb, len, __builtin_return_address(0));
2182 EXPORT_SYMBOL(skb_push);
2185 * skb_pull - remove data from the start of a buffer
2186 * @skb: buffer to use
2187 * @len: amount of data to remove
2189 * This function removes data from the start of a buffer, returning
2190 * the memory to the headroom. A pointer to the next data in the buffer
2191 * is returned. Once the data has been pulled future pushes will overwrite
2194 void *skb_pull(struct sk_buff *skb, unsigned int len)
2196 return skb_pull_inline(skb, len);
2198 EXPORT_SYMBOL(skb_pull);
2201 * skb_pull_data - remove data from the start of a buffer returning its
2202 * original position.
2203 * @skb: buffer to use
2204 * @len: amount of data to remove
2206 * This function removes data from the start of a buffer, returning
2207 * the memory to the headroom. A pointer to the original data in the buffer
2208 * is returned after checking if there is enough data to pull. Once the
2209 * data has been pulled future pushes will overwrite the old data.
2211 void *skb_pull_data(struct sk_buff *skb, size_t len)
2213 void *data = skb->data;
2222 EXPORT_SYMBOL(skb_pull_data);
2225 * skb_trim - remove end from a buffer
2226 * @skb: buffer to alter
2229 * Cut the length of a buffer down by removing data from the tail. If
2230 * the buffer is already under the length specified it is not modified.
2231 * The skb must be linear.
2233 void skb_trim(struct sk_buff *skb, unsigned int len)
2236 __skb_trim(skb, len);
2238 EXPORT_SYMBOL(skb_trim);
2240 /* Trims skb to length len. It can change skb pointers.
2243 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2245 struct sk_buff **fragp;
2246 struct sk_buff *frag;
2247 int offset = skb_headlen(skb);
2248 int nfrags = skb_shinfo(skb)->nr_frags;
2252 if (skb_cloned(skb) &&
2253 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2260 for (; i < nfrags; i++) {
2261 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2268 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2271 skb_shinfo(skb)->nr_frags = i;
2273 for (; i < nfrags; i++)
2274 skb_frag_unref(skb, i);
2276 if (skb_has_frag_list(skb))
2277 skb_drop_fraglist(skb);
2281 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2282 fragp = &frag->next) {
2283 int end = offset + frag->len;
2285 if (skb_shared(frag)) {
2286 struct sk_buff *nfrag;
2288 nfrag = skb_clone(frag, GFP_ATOMIC);
2289 if (unlikely(!nfrag))
2292 nfrag->next = frag->next;
2304 unlikely((err = pskb_trim(frag, len - offset))))
2308 skb_drop_list(&frag->next);
2313 if (len > skb_headlen(skb)) {
2314 skb->data_len -= skb->len - len;
2319 skb_set_tail_pointer(skb, len);
2322 if (!skb->sk || skb->destructor == sock_edemux)
2326 EXPORT_SYMBOL(___pskb_trim);
2328 /* Note : use pskb_trim_rcsum() instead of calling this directly
2330 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2332 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2333 int delta = skb->len - len;
2335 skb->csum = csum_block_sub(skb->csum,
2336 skb_checksum(skb, len, delta, 0),
2338 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2339 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2340 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2342 if (offset + sizeof(__sum16) > hdlen)
2345 return __pskb_trim(skb, len);
2347 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2350 * __pskb_pull_tail - advance tail of skb header
2351 * @skb: buffer to reallocate
2352 * @delta: number of bytes to advance tail
2354 * The function makes a sense only on a fragmented &sk_buff,
2355 * it expands header moving its tail forward and copying necessary
2356 * data from fragmented part.
2358 * &sk_buff MUST have reference count of 1.
2360 * Returns %NULL (and &sk_buff does not change) if pull failed
2361 * or value of new tail of skb in the case of success.
2363 * All the pointers pointing into skb header may change and must be
2364 * reloaded after call to this function.
2367 /* Moves tail of skb head forward, copying data from fragmented part,
2368 * when it is necessary.
2369 * 1. It may fail due to malloc failure.
2370 * 2. It may change skb pointers.
2372 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2374 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2376 /* If skb has not enough free space at tail, get new one
2377 * plus 128 bytes for future expansions. If we have enough
2378 * room at tail, reallocate without expansion only if skb is cloned.
2380 int i, k, eat = (skb->tail + delta) - skb->end;
2382 if (eat > 0 || skb_cloned(skb)) {
2383 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2388 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2389 skb_tail_pointer(skb), delta));
2391 /* Optimization: no fragments, no reasons to preestimate
2392 * size of pulled pages. Superb.
2394 if (!skb_has_frag_list(skb))
2397 /* Estimate size of pulled pages. */
2399 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2400 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2407 /* If we need update frag list, we are in troubles.
2408 * Certainly, it is possible to add an offset to skb data,
2409 * but taking into account that pulling is expected to
2410 * be very rare operation, it is worth to fight against
2411 * further bloating skb head and crucify ourselves here instead.
2412 * Pure masohism, indeed. 8)8)
2415 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2416 struct sk_buff *clone = NULL;
2417 struct sk_buff *insp = NULL;
2420 if (list->len <= eat) {
2421 /* Eaten as whole. */
2426 /* Eaten partially. */
2427 if (skb_is_gso(skb) && !list->head_frag &&
2429 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2431 if (skb_shared(list)) {
2432 /* Sucks! We need to fork list. :-( */
2433 clone = skb_clone(list, GFP_ATOMIC);
2439 /* This may be pulled without
2443 if (!pskb_pull(list, eat)) {
2451 /* Free pulled out fragments. */
2452 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2453 skb_shinfo(skb)->frag_list = list->next;
2456 /* And insert new clone at head. */
2459 skb_shinfo(skb)->frag_list = clone;
2462 /* Success! Now we may commit changes to skb data. */
2467 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2468 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2471 skb_frag_unref(skb, i);
2474 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2476 *frag = skb_shinfo(skb)->frags[i];
2478 skb_frag_off_add(frag, eat);
2479 skb_frag_size_sub(frag, eat);
2487 skb_shinfo(skb)->nr_frags = k;
2491 skb->data_len -= delta;
2494 skb_zcopy_clear(skb, false);
2496 return skb_tail_pointer(skb);
2498 EXPORT_SYMBOL(__pskb_pull_tail);
2501 * skb_copy_bits - copy bits from skb to kernel buffer
2503 * @offset: offset in source
2504 * @to: destination buffer
2505 * @len: number of bytes to copy
2507 * Copy the specified number of bytes from the source skb to the
2508 * destination buffer.
2511 * If its prototype is ever changed,
2512 * check arch/{*}/net/{*}.S files,
2513 * since it is called from BPF assembly code.
2515 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2517 int start = skb_headlen(skb);
2518 struct sk_buff *frag_iter;
2521 if (offset > (int)skb->len - len)
2525 if ((copy = start - offset) > 0) {
2528 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2529 if ((len -= copy) == 0)
2535 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2537 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2539 WARN_ON(start > offset + len);
2541 end = start + skb_frag_size(f);
2542 if ((copy = end - offset) > 0) {
2543 u32 p_off, p_len, copied;
2550 skb_frag_foreach_page(f,
2551 skb_frag_off(f) + offset - start,
2552 copy, p, p_off, p_len, copied) {
2553 vaddr = kmap_atomic(p);
2554 memcpy(to + copied, vaddr + p_off, p_len);
2555 kunmap_atomic(vaddr);
2558 if ((len -= copy) == 0)
2566 skb_walk_frags(skb, frag_iter) {
2569 WARN_ON(start > offset + len);
2571 end = start + frag_iter->len;
2572 if ((copy = end - offset) > 0) {
2575 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2577 if ((len -= copy) == 0)
2591 EXPORT_SYMBOL(skb_copy_bits);
2594 * Callback from splice_to_pipe(), if we need to release some pages
2595 * at the end of the spd in case we error'ed out in filling the pipe.
2597 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2599 put_page(spd->pages[i]);
2602 static struct page *linear_to_page(struct page *page, unsigned int *len,
2603 unsigned int *offset,
2606 struct page_frag *pfrag = sk_page_frag(sk);
2608 if (!sk_page_frag_refill(sk, pfrag))
2611 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2613 memcpy(page_address(pfrag->page) + pfrag->offset,
2614 page_address(page) + *offset, *len);
2615 *offset = pfrag->offset;
2616 pfrag->offset += *len;
2621 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2623 unsigned int offset)
2625 return spd->nr_pages &&
2626 spd->pages[spd->nr_pages - 1] == page &&
2627 (spd->partial[spd->nr_pages - 1].offset +
2628 spd->partial[spd->nr_pages - 1].len == offset);
2632 * Fill page/offset/length into spd, if it can hold more pages.
2634 static bool spd_fill_page(struct splice_pipe_desc *spd,
2635 struct pipe_inode_info *pipe, struct page *page,
2636 unsigned int *len, unsigned int offset,
2640 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2644 page = linear_to_page(page, len, &offset, sk);
2648 if (spd_can_coalesce(spd, page, offset)) {
2649 spd->partial[spd->nr_pages - 1].len += *len;
2653 spd->pages[spd->nr_pages] = page;
2654 spd->partial[spd->nr_pages].len = *len;
2655 spd->partial[spd->nr_pages].offset = offset;
2661 static bool __splice_segment(struct page *page, unsigned int poff,
2662 unsigned int plen, unsigned int *off,
2664 struct splice_pipe_desc *spd, bool linear,
2666 struct pipe_inode_info *pipe)
2671 /* skip this segment if already processed */
2677 /* ignore any bits we already processed */
2683 unsigned int flen = min(*len, plen);
2685 if (spd_fill_page(spd, pipe, page, &flen, poff,
2691 } while (*len && plen);
2697 * Map linear and fragment data from the skb to spd. It reports true if the
2698 * pipe is full or if we already spliced the requested length.
2700 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2701 unsigned int *offset, unsigned int *len,
2702 struct splice_pipe_desc *spd, struct sock *sk)
2705 struct sk_buff *iter;
2707 /* map the linear part :
2708 * If skb->head_frag is set, this 'linear' part is backed by a
2709 * fragment, and if the head is not shared with any clones then
2710 * we can avoid a copy since we own the head portion of this page.
2712 if (__splice_segment(virt_to_page(skb->data),
2713 (unsigned long) skb->data & (PAGE_SIZE - 1),
2716 skb_head_is_locked(skb),
2721 * then map the fragments
2723 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2724 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2726 if (__splice_segment(skb_frag_page(f),
2727 skb_frag_off(f), skb_frag_size(f),
2728 offset, len, spd, false, sk, pipe))
2732 skb_walk_frags(skb, iter) {
2733 if (*offset >= iter->len) {
2734 *offset -= iter->len;
2737 /* __skb_splice_bits() only fails if the output has no room
2738 * left, so no point in going over the frag_list for the error
2741 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2749 * Map data from the skb to a pipe. Should handle both the linear part,
2750 * the fragments, and the frag list.
2752 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2753 struct pipe_inode_info *pipe, unsigned int tlen,
2756 struct partial_page partial[MAX_SKB_FRAGS];
2757 struct page *pages[MAX_SKB_FRAGS];
2758 struct splice_pipe_desc spd = {
2761 .nr_pages_max = MAX_SKB_FRAGS,
2762 .ops = &nosteal_pipe_buf_ops,
2763 .spd_release = sock_spd_release,
2767 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2770 ret = splice_to_pipe(pipe, &spd);
2774 EXPORT_SYMBOL_GPL(skb_splice_bits);
2776 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2777 struct kvec *vec, size_t num, size_t size)
2779 struct socket *sock = sk->sk_socket;
2783 return kernel_sendmsg(sock, msg, vec, num, size);
2786 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2787 size_t size, int flags)
2789 struct socket *sock = sk->sk_socket;
2793 return kernel_sendpage(sock, page, offset, size, flags);
2796 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2797 struct kvec *vec, size_t num, size_t size);
2798 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2799 size_t size, int flags);
2800 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2801 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2803 unsigned int orig_len = len;
2804 struct sk_buff *head = skb;
2805 unsigned short fragidx;
2810 /* Deal with head data */
2811 while (offset < skb_headlen(skb) && len) {
2815 slen = min_t(int, len, skb_headlen(skb) - offset);
2816 kv.iov_base = skb->data + offset;
2818 memset(&msg, 0, sizeof(msg));
2819 msg.msg_flags = MSG_DONTWAIT;
2821 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2822 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2830 /* All the data was skb head? */
2834 /* Make offset relative to start of frags */
2835 offset -= skb_headlen(skb);
2837 /* Find where we are in frag list */
2838 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2839 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2841 if (offset < skb_frag_size(frag))
2844 offset -= skb_frag_size(frag);
2847 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2848 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2850 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2853 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2854 sendpage_unlocked, sk,
2855 skb_frag_page(frag),
2856 skb_frag_off(frag) + offset,
2857 slen, MSG_DONTWAIT);
2870 /* Process any frag lists */
2873 if (skb_has_frag_list(skb)) {
2874 skb = skb_shinfo(skb)->frag_list;
2877 } else if (skb->next) {
2884 return orig_len - len;
2887 return orig_len == len ? ret : orig_len - len;
2890 /* Send skb data on a socket. Socket must be locked. */
2891 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2894 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2895 kernel_sendpage_locked);
2897 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2899 /* Send skb data on a socket. Socket must be unlocked. */
2900 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2902 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2907 * skb_store_bits - store bits from kernel buffer to skb
2908 * @skb: destination buffer
2909 * @offset: offset in destination
2910 * @from: source buffer
2911 * @len: number of bytes to copy
2913 * Copy the specified number of bytes from the source buffer to the
2914 * destination skb. This function handles all the messy bits of
2915 * traversing fragment lists and such.
2918 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2920 int start = skb_headlen(skb);
2921 struct sk_buff *frag_iter;
2924 if (offset > (int)skb->len - len)
2927 if ((copy = start - offset) > 0) {
2930 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2931 if ((len -= copy) == 0)
2937 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2938 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2941 WARN_ON(start > offset + len);
2943 end = start + skb_frag_size(frag);
2944 if ((copy = end - offset) > 0) {
2945 u32 p_off, p_len, copied;
2952 skb_frag_foreach_page(frag,
2953 skb_frag_off(frag) + offset - start,
2954 copy, p, p_off, p_len, copied) {
2955 vaddr = kmap_atomic(p);
2956 memcpy(vaddr + p_off, from + copied, p_len);
2957 kunmap_atomic(vaddr);
2960 if ((len -= copy) == 0)
2968 skb_walk_frags(skb, frag_iter) {
2971 WARN_ON(start > offset + len);
2973 end = start + frag_iter->len;
2974 if ((copy = end - offset) > 0) {
2977 if (skb_store_bits(frag_iter, offset - start,
2980 if ((len -= copy) == 0)
2993 EXPORT_SYMBOL(skb_store_bits);
2995 /* Checksum skb data. */
2996 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2997 __wsum csum, const struct skb_checksum_ops *ops)
2999 int start = skb_headlen(skb);
3000 int i, copy = start - offset;
3001 struct sk_buff *frag_iter;
3004 /* Checksum header. */
3008 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3009 skb->data + offset, copy, csum);
3010 if ((len -= copy) == 0)
3016 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3018 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3020 WARN_ON(start > offset + len);
3022 end = start + skb_frag_size(frag);
3023 if ((copy = end - offset) > 0) {
3024 u32 p_off, p_len, copied;
3032 skb_frag_foreach_page(frag,
3033 skb_frag_off(frag) + offset - start,
3034 copy, p, p_off, p_len, copied) {
3035 vaddr = kmap_atomic(p);
3036 csum2 = INDIRECT_CALL_1(ops->update,
3038 vaddr + p_off, p_len, 0);
3039 kunmap_atomic(vaddr);
3040 csum = INDIRECT_CALL_1(ops->combine,
3041 csum_block_add_ext, csum,
3053 skb_walk_frags(skb, frag_iter) {
3056 WARN_ON(start > offset + len);
3058 end = start + frag_iter->len;
3059 if ((copy = end - offset) > 0) {
3063 csum2 = __skb_checksum(frag_iter, offset - start,
3065 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3066 csum, csum2, pos, copy);
3067 if ((len -= copy) == 0)
3078 EXPORT_SYMBOL(__skb_checksum);
3080 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3081 int len, __wsum csum)
3083 const struct skb_checksum_ops ops = {
3084 .update = csum_partial_ext,
3085 .combine = csum_block_add_ext,
3088 return __skb_checksum(skb, offset, len, csum, &ops);
3090 EXPORT_SYMBOL(skb_checksum);
3092 /* Both of above in one bottle. */
3094 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3097 int start = skb_headlen(skb);
3098 int i, copy = start - offset;
3099 struct sk_buff *frag_iter;
3107 csum = csum_partial_copy_nocheck(skb->data + offset, to,
3109 if ((len -= copy) == 0)
3116 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3119 WARN_ON(start > offset + len);
3121 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3122 if ((copy = end - offset) > 0) {
3123 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3124 u32 p_off, p_len, copied;
3132 skb_frag_foreach_page(frag,
3133 skb_frag_off(frag) + offset - start,
3134 copy, p, p_off, p_len, copied) {
3135 vaddr = kmap_atomic(p);
3136 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3139 kunmap_atomic(vaddr);
3140 csum = csum_block_add(csum, csum2, pos);
3152 skb_walk_frags(skb, frag_iter) {
3156 WARN_ON(start > offset + len);
3158 end = start + frag_iter->len;
3159 if ((copy = end - offset) > 0) {
3162 csum2 = skb_copy_and_csum_bits(frag_iter,
3165 csum = csum_block_add(csum, csum2, pos);
3166 if ((len -= copy) == 0)
3177 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3179 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3183 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3184 /* See comments in __skb_checksum_complete(). */
3186 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3187 !skb->csum_complete_sw)
3188 netdev_rx_csum_fault(skb->dev, skb);
3190 if (!skb_shared(skb))
3191 skb->csum_valid = !sum;
3194 EXPORT_SYMBOL(__skb_checksum_complete_head);
3196 /* This function assumes skb->csum already holds pseudo header's checksum,
3197 * which has been changed from the hardware checksum, for example, by
3198 * __skb_checksum_validate_complete(). And, the original skb->csum must
3199 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3201 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3202 * zero. The new checksum is stored back into skb->csum unless the skb is
3205 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3210 csum = skb_checksum(skb, 0, skb->len, 0);
3212 sum = csum_fold(csum_add(skb->csum, csum));
3213 /* This check is inverted, because we already knew the hardware
3214 * checksum is invalid before calling this function. So, if the
3215 * re-computed checksum is valid instead, then we have a mismatch
3216 * between the original skb->csum and skb_checksum(). This means either
3217 * the original hardware checksum is incorrect or we screw up skb->csum
3218 * when moving skb->data around.
3221 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3222 !skb->csum_complete_sw)
3223 netdev_rx_csum_fault(skb->dev, skb);
3226 if (!skb_shared(skb)) {
3227 /* Save full packet checksum */
3229 skb->ip_summed = CHECKSUM_COMPLETE;
3230 skb->csum_complete_sw = 1;
3231 skb->csum_valid = !sum;
3236 EXPORT_SYMBOL(__skb_checksum_complete);
3238 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3240 net_warn_ratelimited(
3241 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3246 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3247 int offset, int len)
3249 net_warn_ratelimited(
3250 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3255 static const struct skb_checksum_ops default_crc32c_ops = {
3256 .update = warn_crc32c_csum_update,
3257 .combine = warn_crc32c_csum_combine,
3260 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3261 &default_crc32c_ops;
3262 EXPORT_SYMBOL(crc32c_csum_stub);
3265 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3266 * @from: source buffer
3268 * Calculates the amount of linear headroom needed in the 'to' skb passed
3269 * into skb_zerocopy().
3272 skb_zerocopy_headlen(const struct sk_buff *from)
3274 unsigned int hlen = 0;
3276 if (!from->head_frag ||
3277 skb_headlen(from) < L1_CACHE_BYTES ||
3278 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3279 hlen = skb_headlen(from);
3284 if (skb_has_frag_list(from))
3289 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3292 * skb_zerocopy - Zero copy skb to skb
3293 * @to: destination buffer
3294 * @from: source buffer
3295 * @len: number of bytes to copy from source buffer
3296 * @hlen: size of linear headroom in destination buffer
3298 * Copies up to `len` bytes from `from` to `to` by creating references
3299 * to the frags in the source buffer.
3301 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3302 * headroom in the `to` buffer.
3305 * 0: everything is OK
3306 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3307 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3310 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3313 int plen = 0; /* length of skb->head fragment */
3316 unsigned int offset;
3318 BUG_ON(!from->head_frag && !hlen);
3320 /* dont bother with small payloads */
3321 if (len <= skb_tailroom(to))
3322 return skb_copy_bits(from, 0, skb_put(to, len), len);
3325 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3330 plen = min_t(int, skb_headlen(from), len);
3332 page = virt_to_head_page(from->head);
3333 offset = from->data - (unsigned char *)page_address(page);
3334 __skb_fill_page_desc(to, 0, page, offset, plen);
3341 skb_len_add(to, len + plen);
3343 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3347 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3349 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3354 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3355 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3357 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3359 skb_frag_ref(to, j);
3362 skb_shinfo(to)->nr_frags = j;
3366 EXPORT_SYMBOL_GPL(skb_zerocopy);
3368 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3373 if (skb->ip_summed == CHECKSUM_PARTIAL)
3374 csstart = skb_checksum_start_offset(skb);
3376 csstart = skb_headlen(skb);
3378 BUG_ON(csstart > skb_headlen(skb));
3380 skb_copy_from_linear_data(skb, to, csstart);
3383 if (csstart != skb->len)
3384 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3385 skb->len - csstart);
3387 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3388 long csstuff = csstart + skb->csum_offset;
3390 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3393 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3396 * skb_dequeue - remove from the head of the queue
3397 * @list: list to dequeue from
3399 * Remove the head of the list. The list lock is taken so the function
3400 * may be used safely with other locking list functions. The head item is
3401 * returned or %NULL if the list is empty.
3404 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3406 unsigned long flags;
3407 struct sk_buff *result;
3409 spin_lock_irqsave(&list->lock, flags);
3410 result = __skb_dequeue(list);
3411 spin_unlock_irqrestore(&list->lock, flags);
3414 EXPORT_SYMBOL(skb_dequeue);
3417 * skb_dequeue_tail - remove from the tail of the queue
3418 * @list: list to dequeue from
3420 * Remove the tail of the list. The list lock is taken so the function
3421 * may be used safely with other locking list functions. The tail item is
3422 * returned or %NULL if the list is empty.
3424 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3426 unsigned long flags;
3427 struct sk_buff *result;
3429 spin_lock_irqsave(&list->lock, flags);
3430 result = __skb_dequeue_tail(list);
3431 spin_unlock_irqrestore(&list->lock, flags);
3434 EXPORT_SYMBOL(skb_dequeue_tail);
3437 * skb_queue_purge - empty a list
3438 * @list: list to empty
3440 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3441 * the list and one reference dropped. This function takes the list
3442 * lock and is atomic with respect to other list locking functions.
3444 void skb_queue_purge(struct sk_buff_head *list)
3446 struct sk_buff *skb;
3447 while ((skb = skb_dequeue(list)) != NULL)
3450 EXPORT_SYMBOL(skb_queue_purge);
3453 * skb_rbtree_purge - empty a skb rbtree
3454 * @root: root of the rbtree to empty
3455 * Return value: the sum of truesizes of all purged skbs.
3457 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3458 * the list and one reference dropped. This function does not take
3459 * any lock. Synchronization should be handled by the caller (e.g., TCP
3460 * out-of-order queue is protected by the socket lock).
3462 unsigned int skb_rbtree_purge(struct rb_root *root)
3464 struct rb_node *p = rb_first(root);
3465 unsigned int sum = 0;
3468 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3471 rb_erase(&skb->rbnode, root);
3472 sum += skb->truesize;
3479 * skb_queue_head - queue a buffer at the list head
3480 * @list: list to use
3481 * @newsk: buffer to queue
3483 * Queue a buffer at the start of the list. This function takes the
3484 * list lock and can be used safely with other locking &sk_buff functions
3487 * A buffer cannot be placed on two lists at the same time.
3489 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3491 unsigned long flags;
3493 spin_lock_irqsave(&list->lock, flags);
3494 __skb_queue_head(list, newsk);
3495 spin_unlock_irqrestore(&list->lock, flags);
3497 EXPORT_SYMBOL(skb_queue_head);
3500 * skb_queue_tail - queue a buffer at the list tail
3501 * @list: list to use
3502 * @newsk: buffer to queue
3504 * Queue a buffer at the tail of the list. This function takes the
3505 * list lock and can be used safely with other locking &sk_buff functions
3508 * A buffer cannot be placed on two lists at the same time.
3510 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3512 unsigned long flags;
3514 spin_lock_irqsave(&list->lock, flags);
3515 __skb_queue_tail(list, newsk);
3516 spin_unlock_irqrestore(&list->lock, flags);
3518 EXPORT_SYMBOL(skb_queue_tail);
3521 * skb_unlink - remove a buffer from a list
3522 * @skb: buffer to remove
3523 * @list: list to use
3525 * Remove a packet from a list. The list locks are taken and this
3526 * function is atomic with respect to other list locked calls
3528 * You must know what list the SKB is on.
3530 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3532 unsigned long flags;
3534 spin_lock_irqsave(&list->lock, flags);
3535 __skb_unlink(skb, list);
3536 spin_unlock_irqrestore(&list->lock, flags);
3538 EXPORT_SYMBOL(skb_unlink);
3541 * skb_append - append a buffer
3542 * @old: buffer to insert after
3543 * @newsk: buffer to insert
3544 * @list: list to use
3546 * Place a packet after a given packet in a list. The list locks are taken
3547 * and this function is atomic with respect to other list locked calls.
3548 * A buffer cannot be placed on two lists at the same time.
3550 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3552 unsigned long flags;
3554 spin_lock_irqsave(&list->lock, flags);
3555 __skb_queue_after(list, old, newsk);
3556 spin_unlock_irqrestore(&list->lock, flags);
3558 EXPORT_SYMBOL(skb_append);
3560 static inline void skb_split_inside_header(struct sk_buff *skb,
3561 struct sk_buff* skb1,
3562 const u32 len, const int pos)
3566 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3568 /* And move data appendix as is. */
3569 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3570 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3572 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3573 skb_shinfo(skb)->nr_frags = 0;
3574 skb1->data_len = skb->data_len;
3575 skb1->len += skb1->data_len;
3578 skb_set_tail_pointer(skb, len);
3581 static inline void skb_split_no_header(struct sk_buff *skb,
3582 struct sk_buff* skb1,
3583 const u32 len, int pos)
3586 const int nfrags = skb_shinfo(skb)->nr_frags;
3588 skb_shinfo(skb)->nr_frags = 0;
3589 skb1->len = skb1->data_len = skb->len - len;
3591 skb->data_len = len - pos;
3593 for (i = 0; i < nfrags; i++) {
3594 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3596 if (pos + size > len) {
3597 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3601 * We have two variants in this case:
3602 * 1. Move all the frag to the second
3603 * part, if it is possible. F.e.
3604 * this approach is mandatory for TUX,
3605 * where splitting is expensive.
3606 * 2. Split is accurately. We make this.
3608 skb_frag_ref(skb, i);
3609 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3610 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3611 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3612 skb_shinfo(skb)->nr_frags++;
3616 skb_shinfo(skb)->nr_frags++;
3619 skb_shinfo(skb1)->nr_frags = k;
3623 * skb_split - Split fragmented skb to two parts at length len.
3624 * @skb: the buffer to split
3625 * @skb1: the buffer to receive the second part
3626 * @len: new length for skb
3628 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3630 int pos = skb_headlen(skb);
3631 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3633 skb_zcopy_downgrade_managed(skb);
3635 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3636 skb_zerocopy_clone(skb1, skb, 0);
3637 if (len < pos) /* Split line is inside header. */
3638 skb_split_inside_header(skb, skb1, len, pos);
3639 else /* Second chunk has no header, nothing to copy. */
3640 skb_split_no_header(skb, skb1, len, pos);
3642 EXPORT_SYMBOL(skb_split);
3644 /* Shifting from/to a cloned skb is a no-go.
3646 * Caller cannot keep skb_shinfo related pointers past calling here!
3648 static int skb_prepare_for_shift(struct sk_buff *skb)
3650 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3654 * skb_shift - Shifts paged data partially from skb to another
3655 * @tgt: buffer into which tail data gets added
3656 * @skb: buffer from which the paged data comes from
3657 * @shiftlen: shift up to this many bytes
3659 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3660 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3661 * It's up to caller to free skb if everything was shifted.
3663 * If @tgt runs out of frags, the whole operation is aborted.
3665 * Skb cannot include anything else but paged data while tgt is allowed
3666 * to have non-paged data as well.
3668 * TODO: full sized shift could be optimized but that would need
3669 * specialized skb free'er to handle frags without up-to-date nr_frags.
3671 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3673 int from, to, merge, todo;
3674 skb_frag_t *fragfrom, *fragto;
3676 BUG_ON(shiftlen > skb->len);
3678 if (skb_headlen(skb))
3680 if (skb_zcopy(tgt) || skb_zcopy(skb))
3685 to = skb_shinfo(tgt)->nr_frags;
3686 fragfrom = &skb_shinfo(skb)->frags[from];
3688 /* Actual merge is delayed until the point when we know we can
3689 * commit all, so that we don't have to undo partial changes
3692 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3693 skb_frag_off(fragfrom))) {
3698 todo -= skb_frag_size(fragfrom);
3700 if (skb_prepare_for_shift(skb) ||
3701 skb_prepare_for_shift(tgt))
3704 /* All previous frag pointers might be stale! */
3705 fragfrom = &skb_shinfo(skb)->frags[from];
3706 fragto = &skb_shinfo(tgt)->frags[merge];
3708 skb_frag_size_add(fragto, shiftlen);
3709 skb_frag_size_sub(fragfrom, shiftlen);
3710 skb_frag_off_add(fragfrom, shiftlen);
3718 /* Skip full, not-fitting skb to avoid expensive operations */
3719 if ((shiftlen == skb->len) &&
3720 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3723 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3726 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3727 if (to == MAX_SKB_FRAGS)
3730 fragfrom = &skb_shinfo(skb)->frags[from];
3731 fragto = &skb_shinfo(tgt)->frags[to];
3733 if (todo >= skb_frag_size(fragfrom)) {
3734 *fragto = *fragfrom;
3735 todo -= skb_frag_size(fragfrom);
3740 __skb_frag_ref(fragfrom);
3741 skb_frag_page_copy(fragto, fragfrom);
3742 skb_frag_off_copy(fragto, fragfrom);
3743 skb_frag_size_set(fragto, todo);
3745 skb_frag_off_add(fragfrom, todo);
3746 skb_frag_size_sub(fragfrom, todo);
3754 /* Ready to "commit" this state change to tgt */
3755 skb_shinfo(tgt)->nr_frags = to;
3758 fragfrom = &skb_shinfo(skb)->frags[0];
3759 fragto = &skb_shinfo(tgt)->frags[merge];
3761 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3762 __skb_frag_unref(fragfrom, skb->pp_recycle);
3765 /* Reposition in the original skb */
3767 while (from < skb_shinfo(skb)->nr_frags)
3768 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3769 skb_shinfo(skb)->nr_frags = to;
3771 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3774 /* Most likely the tgt won't ever need its checksum anymore, skb on
3775 * the other hand might need it if it needs to be resent
3777 tgt->ip_summed = CHECKSUM_PARTIAL;
3778 skb->ip_summed = CHECKSUM_PARTIAL;
3780 skb_len_add(skb, -shiftlen);
3781 skb_len_add(tgt, shiftlen);
3787 * skb_prepare_seq_read - Prepare a sequential read of skb data
3788 * @skb: the buffer to read
3789 * @from: lower offset of data to be read
3790 * @to: upper offset of data to be read
3791 * @st: state variable
3793 * Initializes the specified state variable. Must be called before
3794 * invoking skb_seq_read() for the first time.
3796 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3797 unsigned int to, struct skb_seq_state *st)
3799 st->lower_offset = from;
3800 st->upper_offset = to;
3801 st->root_skb = st->cur_skb = skb;
3802 st->frag_idx = st->stepped_offset = 0;
3803 st->frag_data = NULL;
3806 EXPORT_SYMBOL(skb_prepare_seq_read);
3809 * skb_seq_read - Sequentially read skb data
3810 * @consumed: number of bytes consumed by the caller so far
3811 * @data: destination pointer for data to be returned
3812 * @st: state variable
3814 * Reads a block of skb data at @consumed relative to the
3815 * lower offset specified to skb_prepare_seq_read(). Assigns
3816 * the head of the data block to @data and returns the length
3817 * of the block or 0 if the end of the skb data or the upper
3818 * offset has been reached.
3820 * The caller is not required to consume all of the data
3821 * returned, i.e. @consumed is typically set to the number
3822 * of bytes already consumed and the next call to
3823 * skb_seq_read() will return the remaining part of the block.
3825 * Note 1: The size of each block of data returned can be arbitrary,
3826 * this limitation is the cost for zerocopy sequential
3827 * reads of potentially non linear data.
3829 * Note 2: Fragment lists within fragments are not implemented
3830 * at the moment, state->root_skb could be replaced with
3831 * a stack for this purpose.
3833 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3834 struct skb_seq_state *st)
3836 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3839 if (unlikely(abs_offset >= st->upper_offset)) {
3840 if (st->frag_data) {
3841 kunmap_atomic(st->frag_data);
3842 st->frag_data = NULL;
3848 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3850 if (abs_offset < block_limit && !st->frag_data) {
3851 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3852 return block_limit - abs_offset;
3855 if (st->frag_idx == 0 && !st->frag_data)
3856 st->stepped_offset += skb_headlen(st->cur_skb);
3858 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3859 unsigned int pg_idx, pg_off, pg_sz;
3861 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3864 pg_off = skb_frag_off(frag);
3865 pg_sz = skb_frag_size(frag);
3867 if (skb_frag_must_loop(skb_frag_page(frag))) {
3868 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3869 pg_off = offset_in_page(pg_off + st->frag_off);
3870 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3871 PAGE_SIZE - pg_off);
3874 block_limit = pg_sz + st->stepped_offset;
3875 if (abs_offset < block_limit) {
3877 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3879 *data = (u8 *)st->frag_data + pg_off +
3880 (abs_offset - st->stepped_offset);
3882 return block_limit - abs_offset;
3885 if (st->frag_data) {
3886 kunmap_atomic(st->frag_data);
3887 st->frag_data = NULL;
3890 st->stepped_offset += pg_sz;
3891 st->frag_off += pg_sz;
3892 if (st->frag_off == skb_frag_size(frag)) {
3898 if (st->frag_data) {
3899 kunmap_atomic(st->frag_data);
3900 st->frag_data = NULL;
3903 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3904 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3907 } else if (st->cur_skb->next) {
3908 st->cur_skb = st->cur_skb->next;
3915 EXPORT_SYMBOL(skb_seq_read);
3918 * skb_abort_seq_read - Abort a sequential read of skb data
3919 * @st: state variable
3921 * Must be called if skb_seq_read() was not called until it
3924 void skb_abort_seq_read(struct skb_seq_state *st)
3927 kunmap_atomic(st->frag_data);
3929 EXPORT_SYMBOL(skb_abort_seq_read);
3931 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3933 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3934 struct ts_config *conf,
3935 struct ts_state *state)
3937 return skb_seq_read(offset, text, TS_SKB_CB(state));
3940 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3942 skb_abort_seq_read(TS_SKB_CB(state));
3946 * skb_find_text - Find a text pattern in skb data
3947 * @skb: the buffer to look in
3948 * @from: search offset
3950 * @config: textsearch configuration
3952 * Finds a pattern in the skb data according to the specified
3953 * textsearch configuration. Use textsearch_next() to retrieve
3954 * subsequent occurrences of the pattern. Returns the offset
3955 * to the first occurrence or UINT_MAX if no match was found.
3957 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3958 unsigned int to, struct ts_config *config)
3960 struct ts_state state;
3963 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3965 config->get_next_block = skb_ts_get_next_block;
3966 config->finish = skb_ts_finish;
3968 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3970 ret = textsearch_find(config, &state);
3971 return (ret <= to - from ? ret : UINT_MAX);
3973 EXPORT_SYMBOL(skb_find_text);
3975 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3976 int offset, size_t size)
3978 int i = skb_shinfo(skb)->nr_frags;
3980 if (skb_can_coalesce(skb, i, page, offset)) {
3981 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3982 } else if (i < MAX_SKB_FRAGS) {
3983 skb_zcopy_downgrade_managed(skb);
3985 skb_fill_page_desc_noacc(skb, i, page, offset, size);
3992 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3995 * skb_pull_rcsum - pull skb and update receive checksum
3996 * @skb: buffer to update
3997 * @len: length of data pulled
3999 * This function performs an skb_pull on the packet and updates
4000 * the CHECKSUM_COMPLETE checksum. It should be used on
4001 * receive path processing instead of skb_pull unless you know
4002 * that the checksum difference is zero (e.g., a valid IP header)
4003 * or you are setting ip_summed to CHECKSUM_NONE.
4005 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4007 unsigned char *data = skb->data;
4009 BUG_ON(len > skb->len);
4010 __skb_pull(skb, len);
4011 skb_postpull_rcsum(skb, data, len);
4014 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4016 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4018 skb_frag_t head_frag;
4021 page = virt_to_head_page(frag_skb->head);
4022 __skb_frag_set_page(&head_frag, page);
4023 skb_frag_off_set(&head_frag, frag_skb->data -
4024 (unsigned char *)page_address(page));
4025 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
4029 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4030 netdev_features_t features,
4031 unsigned int offset)
4033 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4034 unsigned int tnl_hlen = skb_tnl_header_len(skb);
4035 unsigned int delta_truesize = 0;
4036 unsigned int delta_len = 0;
4037 struct sk_buff *tail = NULL;
4038 struct sk_buff *nskb, *tmp;
4041 skb_push(skb, -skb_network_offset(skb) + offset);
4043 skb_shinfo(skb)->frag_list = NULL;
4047 list_skb = list_skb->next;
4050 delta_truesize += nskb->truesize;
4051 if (skb_shared(nskb)) {
4052 tmp = skb_clone(nskb, GFP_ATOMIC);
4056 err = skb_unclone(nskb, GFP_ATOMIC);
4067 if (unlikely(err)) {
4068 nskb->next = list_skb;
4074 delta_len += nskb->len;
4076 skb_push(nskb, -skb_network_offset(nskb) + offset);
4078 skb_release_head_state(nskb);
4079 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4080 __copy_skb_header(nskb, skb);
4082 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4083 nskb->transport_header += len_diff;
4084 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4085 nskb->data - tnl_hlen,
4088 if (skb_needs_linearize(nskb, features) &&
4089 __skb_linearize(nskb))
4093 skb->truesize = skb->truesize - delta_truesize;
4094 skb->data_len = skb->data_len - delta_len;
4095 skb->len = skb->len - delta_len;
4101 if (skb_needs_linearize(skb, features) &&
4102 __skb_linearize(skb))
4110 kfree_skb_list(skb->next);
4112 return ERR_PTR(-ENOMEM);
4114 EXPORT_SYMBOL_GPL(skb_segment_list);
4117 * skb_segment - Perform protocol segmentation on skb.
4118 * @head_skb: buffer to segment
4119 * @features: features for the output path (see dev->features)
4121 * This function performs segmentation on the given skb. It returns
4122 * a pointer to the first in a list of new skbs for the segments.
4123 * In case of error it returns ERR_PTR(err).
4125 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4126 netdev_features_t features)
4128 struct sk_buff *segs = NULL;
4129 struct sk_buff *tail = NULL;
4130 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4131 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4132 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4133 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4134 struct sk_buff *frag_skb = head_skb;
4135 unsigned int offset = doffset;
4136 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4137 unsigned int partial_segs = 0;
4138 unsigned int headroom;
4139 unsigned int len = head_skb->len;
4142 int nfrags = skb_shinfo(head_skb)->nr_frags;
4147 if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4148 mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4149 struct sk_buff *check_skb;
4151 for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4152 if (skb_headlen(check_skb) && !check_skb->head_frag) {
4153 /* gso_size is untrusted, and we have a frag_list with
4154 * a linear non head_frag item.
4156 * If head_skb's headlen does not fit requested gso_size,
4157 * it means that the frag_list members do NOT terminate
4158 * on exact gso_size boundaries. Hence we cannot perform
4159 * skb_frag_t page sharing. Therefore we must fallback to
4160 * copying the frag_list skbs; we do so by disabling SG.
4162 features &= ~NETIF_F_SG;
4168 __skb_push(head_skb, doffset);
4169 proto = skb_network_protocol(head_skb, NULL);
4170 if (unlikely(!proto))
4171 return ERR_PTR(-EINVAL);
4173 sg = !!(features & NETIF_F_SG);
4174 csum = !!can_checksum_protocol(features, proto);
4176 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4177 if (!(features & NETIF_F_GSO_PARTIAL)) {
4178 struct sk_buff *iter;
4179 unsigned int frag_len;
4182 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4185 /* If we get here then all the required
4186 * GSO features except frag_list are supported.
4187 * Try to split the SKB to multiple GSO SKBs
4188 * with no frag_list.
4189 * Currently we can do that only when the buffers don't
4190 * have a linear part and all the buffers except
4191 * the last are of the same length.
4193 frag_len = list_skb->len;
4194 skb_walk_frags(head_skb, iter) {
4195 if (frag_len != iter->len && iter->next)
4197 if (skb_headlen(iter) && !iter->head_frag)
4203 if (len != frag_len)
4207 /* GSO partial only requires that we trim off any excess that
4208 * doesn't fit into an MSS sized block, so take care of that
4211 partial_segs = len / mss;
4212 if (partial_segs > 1)
4213 mss *= partial_segs;
4219 headroom = skb_headroom(head_skb);
4220 pos = skb_headlen(head_skb);
4223 struct sk_buff *nskb;
4224 skb_frag_t *nskb_frag;
4228 if (unlikely(mss == GSO_BY_FRAGS)) {
4229 len = list_skb->len;
4231 len = head_skb->len - offset;
4236 hsize = skb_headlen(head_skb) - offset;
4238 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4239 (skb_headlen(list_skb) == len || sg)) {
4240 BUG_ON(skb_headlen(list_skb) > len);
4243 nfrags = skb_shinfo(list_skb)->nr_frags;
4244 frag = skb_shinfo(list_skb)->frags;
4245 frag_skb = list_skb;
4246 pos += skb_headlen(list_skb);
4248 while (pos < offset + len) {
4249 BUG_ON(i >= nfrags);
4251 size = skb_frag_size(frag);
4252 if (pos + size > offset + len)
4260 nskb = skb_clone(list_skb, GFP_ATOMIC);
4261 list_skb = list_skb->next;
4263 if (unlikely(!nskb))
4266 if (unlikely(pskb_trim(nskb, len))) {
4271 hsize = skb_end_offset(nskb);
4272 if (skb_cow_head(nskb, doffset + headroom)) {
4277 nskb->truesize += skb_end_offset(nskb) - hsize;
4278 skb_release_head_state(nskb);
4279 __skb_push(nskb, doffset);
4283 if (hsize > len || !sg)
4286 nskb = __alloc_skb(hsize + doffset + headroom,
4287 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4290 if (unlikely(!nskb))
4293 skb_reserve(nskb, headroom);
4294 __skb_put(nskb, doffset);
4303 __copy_skb_header(nskb, head_skb);
4305 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4306 skb_reset_mac_len(nskb);
4308 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4309 nskb->data - tnl_hlen,
4310 doffset + tnl_hlen);
4312 if (nskb->len == len + doffset)
4313 goto perform_csum_check;
4317 if (!nskb->remcsum_offload)
4318 nskb->ip_summed = CHECKSUM_NONE;
4319 SKB_GSO_CB(nskb)->csum =
4320 skb_copy_and_csum_bits(head_skb, offset,
4324 SKB_GSO_CB(nskb)->csum_start =
4325 skb_headroom(nskb) + doffset;
4327 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4333 nskb_frag = skb_shinfo(nskb)->frags;
4335 skb_copy_from_linear_data_offset(head_skb, offset,
4336 skb_put(nskb, hsize), hsize);
4338 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4341 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4342 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4345 while (pos < offset + len) {
4348 nfrags = skb_shinfo(list_skb)->nr_frags;
4349 frag = skb_shinfo(list_skb)->frags;
4350 frag_skb = list_skb;
4351 if (!skb_headlen(list_skb)) {
4354 BUG_ON(!list_skb->head_frag);
4356 /* to make room for head_frag. */
4360 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4361 skb_zerocopy_clone(nskb, frag_skb,
4365 list_skb = list_skb->next;
4368 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4370 net_warn_ratelimited(
4371 "skb_segment: too many frags: %u %u\n",
4377 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4378 __skb_frag_ref(nskb_frag);
4379 size = skb_frag_size(nskb_frag);
4382 skb_frag_off_add(nskb_frag, offset - pos);
4383 skb_frag_size_sub(nskb_frag, offset - pos);
4386 skb_shinfo(nskb)->nr_frags++;
4388 if (pos + size <= offset + len) {
4393 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4401 nskb->data_len = len - hsize;
4402 nskb->len += nskb->data_len;
4403 nskb->truesize += nskb->data_len;
4407 if (skb_has_shared_frag(nskb) &&
4408 __skb_linearize(nskb))
4411 if (!nskb->remcsum_offload)
4412 nskb->ip_summed = CHECKSUM_NONE;
4413 SKB_GSO_CB(nskb)->csum =
4414 skb_checksum(nskb, doffset,
4415 nskb->len - doffset, 0);
4416 SKB_GSO_CB(nskb)->csum_start =
4417 skb_headroom(nskb) + doffset;
4419 } while ((offset += len) < head_skb->len);
4421 /* Some callers want to get the end of the list.
4422 * Put it in segs->prev to avoid walking the list.
4423 * (see validate_xmit_skb_list() for example)
4428 struct sk_buff *iter;
4429 int type = skb_shinfo(head_skb)->gso_type;
4430 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4432 /* Update type to add partial and then remove dodgy if set */
4433 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4434 type &= ~SKB_GSO_DODGY;
4436 /* Update GSO info and prepare to start updating headers on
4437 * our way back down the stack of protocols.
4439 for (iter = segs; iter; iter = iter->next) {
4440 skb_shinfo(iter)->gso_size = gso_size;
4441 skb_shinfo(iter)->gso_segs = partial_segs;
4442 skb_shinfo(iter)->gso_type = type;
4443 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4446 if (tail->len - doffset <= gso_size)
4447 skb_shinfo(tail)->gso_size = 0;
4448 else if (tail != segs)
4449 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4452 /* Following permits correct backpressure, for protocols
4453 * using skb_set_owner_w().
4454 * Idea is to tranfert ownership from head_skb to last segment.
4456 if (head_skb->destructor == sock_wfree) {
4457 swap(tail->truesize, head_skb->truesize);
4458 swap(tail->destructor, head_skb->destructor);
4459 swap(tail->sk, head_skb->sk);
4464 kfree_skb_list(segs);
4465 return ERR_PTR(err);
4467 EXPORT_SYMBOL_GPL(skb_segment);
4469 #ifdef CONFIG_SKB_EXTENSIONS
4470 #define SKB_EXT_ALIGN_VALUE 8
4471 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4473 static const u8 skb_ext_type_len[] = {
4474 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4475 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4478 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4480 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4481 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4483 #if IS_ENABLED(CONFIG_MPTCP)
4484 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4486 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4487 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4491 static __always_inline unsigned int skb_ext_total_length(void)
4493 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4494 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4495 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4498 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4500 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4501 skb_ext_type_len[TC_SKB_EXT] +
4503 #if IS_ENABLED(CONFIG_MPTCP)
4504 skb_ext_type_len[SKB_EXT_MPTCP] +
4506 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4507 skb_ext_type_len[SKB_EXT_MCTP] +
4512 static void skb_extensions_init(void)
4514 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4515 BUILD_BUG_ON(skb_ext_total_length() > 255);
4517 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4518 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4520 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4524 static void skb_extensions_init(void) {}
4527 void __init skb_init(void)
4529 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4530 sizeof(struct sk_buff),
4532 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4533 offsetof(struct sk_buff, cb),
4534 sizeof_field(struct sk_buff, cb),
4536 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4537 sizeof(struct sk_buff_fclones),
4539 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4541 skb_extensions_init();
4545 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4546 unsigned int recursion_level)
4548 int start = skb_headlen(skb);
4549 int i, copy = start - offset;
4550 struct sk_buff *frag_iter;
4553 if (unlikely(recursion_level >= 24))
4559 sg_set_buf(sg, skb->data + offset, copy);
4561 if ((len -= copy) == 0)
4566 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4569 WARN_ON(start > offset + len);
4571 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4572 if ((copy = end - offset) > 0) {
4573 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4574 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4579 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4580 skb_frag_off(frag) + offset - start);
4589 skb_walk_frags(skb, frag_iter) {
4592 WARN_ON(start > offset + len);
4594 end = start + frag_iter->len;
4595 if ((copy = end - offset) > 0) {
4596 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4601 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4602 copy, recursion_level + 1);
4603 if (unlikely(ret < 0))
4606 if ((len -= copy) == 0)
4617 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4618 * @skb: Socket buffer containing the buffers to be mapped
4619 * @sg: The scatter-gather list to map into
4620 * @offset: The offset into the buffer's contents to start mapping
4621 * @len: Length of buffer space to be mapped
4623 * Fill the specified scatter-gather list with mappings/pointers into a
4624 * region of the buffer space attached to a socket buffer. Returns either
4625 * the number of scatterlist items used, or -EMSGSIZE if the contents
4628 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4630 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4635 sg_mark_end(&sg[nsg - 1]);
4639 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4641 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4642 * sglist without mark the sg which contain last skb data as the end.
4643 * So the caller can mannipulate sg list as will when padding new data after
4644 * the first call without calling sg_unmark_end to expend sg list.
4646 * Scenario to use skb_to_sgvec_nomark:
4648 * 2. skb_to_sgvec_nomark(payload1)
4649 * 3. skb_to_sgvec_nomark(payload2)
4651 * This is equivalent to:
4653 * 2. skb_to_sgvec(payload1)
4655 * 4. skb_to_sgvec(payload2)
4657 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4658 * is more preferable.
4660 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4661 int offset, int len)
4663 return __skb_to_sgvec(skb, sg, offset, len, 0);
4665 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4670 * skb_cow_data - Check that a socket buffer's data buffers are writable
4671 * @skb: The socket buffer to check.
4672 * @tailbits: Amount of trailing space to be added
4673 * @trailer: Returned pointer to the skb where the @tailbits space begins
4675 * Make sure that the data buffers attached to a socket buffer are
4676 * writable. If they are not, private copies are made of the data buffers
4677 * and the socket buffer is set to use these instead.
4679 * If @tailbits is given, make sure that there is space to write @tailbits
4680 * bytes of data beyond current end of socket buffer. @trailer will be
4681 * set to point to the skb in which this space begins.
4683 * The number of scatterlist elements required to completely map the
4684 * COW'd and extended socket buffer will be returned.
4686 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4690 struct sk_buff *skb1, **skb_p;
4692 /* If skb is cloned or its head is paged, reallocate
4693 * head pulling out all the pages (pages are considered not writable
4694 * at the moment even if they are anonymous).
4696 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4697 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4700 /* Easy case. Most of packets will go this way. */
4701 if (!skb_has_frag_list(skb)) {
4702 /* A little of trouble, not enough of space for trailer.
4703 * This should not happen, when stack is tuned to generate
4704 * good frames. OK, on miss we reallocate and reserve even more
4705 * space, 128 bytes is fair. */
4707 if (skb_tailroom(skb) < tailbits &&
4708 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4716 /* Misery. We are in troubles, going to mincer fragments... */
4719 skb_p = &skb_shinfo(skb)->frag_list;
4722 while ((skb1 = *skb_p) != NULL) {
4725 /* The fragment is partially pulled by someone,
4726 * this can happen on input. Copy it and everything
4729 if (skb_shared(skb1))
4732 /* If the skb is the last, worry about trailer. */
4734 if (skb1->next == NULL && tailbits) {
4735 if (skb_shinfo(skb1)->nr_frags ||
4736 skb_has_frag_list(skb1) ||
4737 skb_tailroom(skb1) < tailbits)
4738 ntail = tailbits + 128;
4744 skb_shinfo(skb1)->nr_frags ||
4745 skb_has_frag_list(skb1)) {
4746 struct sk_buff *skb2;
4748 /* Fuck, we are miserable poor guys... */
4750 skb2 = skb_copy(skb1, GFP_ATOMIC);
4752 skb2 = skb_copy_expand(skb1,
4756 if (unlikely(skb2 == NULL))
4760 skb_set_owner_w(skb2, skb1->sk);
4762 /* Looking around. Are we still alive?
4763 * OK, link new skb, drop old one */
4765 skb2->next = skb1->next;
4772 skb_p = &skb1->next;
4777 EXPORT_SYMBOL_GPL(skb_cow_data);
4779 static void sock_rmem_free(struct sk_buff *skb)
4781 struct sock *sk = skb->sk;
4783 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4786 static void skb_set_err_queue(struct sk_buff *skb)
4788 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4789 * So, it is safe to (mis)use it to mark skbs on the error queue.
4791 skb->pkt_type = PACKET_OUTGOING;
4792 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4796 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4798 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4800 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4801 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4806 skb->destructor = sock_rmem_free;
4807 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4808 skb_set_err_queue(skb);
4810 /* before exiting rcu section, make sure dst is refcounted */
4813 skb_queue_tail(&sk->sk_error_queue, skb);
4814 if (!sock_flag(sk, SOCK_DEAD))
4815 sk_error_report(sk);
4818 EXPORT_SYMBOL(sock_queue_err_skb);
4820 static bool is_icmp_err_skb(const struct sk_buff *skb)
4822 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4823 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4826 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4828 struct sk_buff_head *q = &sk->sk_error_queue;
4829 struct sk_buff *skb, *skb_next = NULL;
4830 bool icmp_next = false;
4831 unsigned long flags;
4833 spin_lock_irqsave(&q->lock, flags);
4834 skb = __skb_dequeue(q);
4835 if (skb && (skb_next = skb_peek(q))) {
4836 icmp_next = is_icmp_err_skb(skb_next);
4838 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4840 spin_unlock_irqrestore(&q->lock, flags);
4842 if (is_icmp_err_skb(skb) && !icmp_next)
4846 sk_error_report(sk);
4850 EXPORT_SYMBOL(sock_dequeue_err_skb);
4853 * skb_clone_sk - create clone of skb, and take reference to socket
4854 * @skb: the skb to clone
4856 * This function creates a clone of a buffer that holds a reference on
4857 * sk_refcnt. Buffers created via this function are meant to be
4858 * returned using sock_queue_err_skb, or free via kfree_skb.
4860 * When passing buffers allocated with this function to sock_queue_err_skb
4861 * it is necessary to wrap the call with sock_hold/sock_put in order to
4862 * prevent the socket from being released prior to being enqueued on
4863 * the sk_error_queue.
4865 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4867 struct sock *sk = skb->sk;
4868 struct sk_buff *clone;
4870 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4873 clone = skb_clone(skb, GFP_ATOMIC);
4880 clone->destructor = sock_efree;
4884 EXPORT_SYMBOL(skb_clone_sk);
4886 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4891 struct sock_exterr_skb *serr;
4894 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4896 serr = SKB_EXT_ERR(skb);
4897 memset(serr, 0, sizeof(*serr));
4898 serr->ee.ee_errno = ENOMSG;
4899 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4900 serr->ee.ee_info = tstype;
4901 serr->opt_stats = opt_stats;
4902 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4903 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4904 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4906 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4909 err = sock_queue_err_skb(sk, skb);
4915 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4919 if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
4922 read_lock_bh(&sk->sk_callback_lock);
4923 ret = sk->sk_socket && sk->sk_socket->file &&
4924 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4925 read_unlock_bh(&sk->sk_callback_lock);
4929 void skb_complete_tx_timestamp(struct sk_buff *skb,
4930 struct skb_shared_hwtstamps *hwtstamps)
4932 struct sock *sk = skb->sk;
4934 if (!skb_may_tx_timestamp(sk, false))
4937 /* Take a reference to prevent skb_orphan() from freeing the socket,
4938 * but only if the socket refcount is not zero.
4940 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4941 *skb_hwtstamps(skb) = *hwtstamps;
4942 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4950 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4952 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4953 const struct sk_buff *ack_skb,
4954 struct skb_shared_hwtstamps *hwtstamps,
4955 struct sock *sk, int tstype)
4957 struct sk_buff *skb;
4958 bool tsonly, opt_stats = false;
4963 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4964 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4967 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4968 if (!skb_may_tx_timestamp(sk, tsonly))
4973 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4975 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4980 skb = alloc_skb(0, GFP_ATOMIC);
4982 skb = skb_clone(orig_skb, GFP_ATOMIC);
4984 if (skb_orphan_frags_rx(skb, GFP_ATOMIC))
4991 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4993 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4997 *skb_hwtstamps(skb) = *hwtstamps;
4999 __net_timestamp(skb);
5001 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5003 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5005 void skb_tstamp_tx(struct sk_buff *orig_skb,
5006 struct skb_shared_hwtstamps *hwtstamps)
5008 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5011 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5013 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5015 struct sock *sk = skb->sk;
5016 struct sock_exterr_skb *serr;
5019 skb->wifi_acked_valid = 1;
5020 skb->wifi_acked = acked;
5022 serr = SKB_EXT_ERR(skb);
5023 memset(serr, 0, sizeof(*serr));
5024 serr->ee.ee_errno = ENOMSG;
5025 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5027 /* Take a reference to prevent skb_orphan() from freeing the socket,
5028 * but only if the socket refcount is not zero.
5030 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5031 err = sock_queue_err_skb(sk, skb);
5037 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5040 * skb_partial_csum_set - set up and verify partial csum values for packet
5041 * @skb: the skb to set
5042 * @start: the number of bytes after skb->data to start checksumming.
5043 * @off: the offset from start to place the checksum.
5045 * For untrusted partially-checksummed packets, we need to make sure the values
5046 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5048 * This function checks and sets those values and skb->ip_summed: if this
5049 * returns false you should drop the packet.
5051 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5053 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5054 u32 csum_start = skb_headroom(skb) + (u32)start;
5056 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
5057 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5058 start, off, skb_headroom(skb), skb_headlen(skb));
5061 skb->ip_summed = CHECKSUM_PARTIAL;
5062 skb->csum_start = csum_start;
5063 skb->csum_offset = off;
5064 skb_set_transport_header(skb, start);
5067 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5069 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5072 if (skb_headlen(skb) >= len)
5075 /* If we need to pullup then pullup to the max, so we
5076 * won't need to do it again.
5081 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5084 if (skb_headlen(skb) < len)
5090 #define MAX_TCP_HDR_LEN (15 * 4)
5092 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5093 typeof(IPPROTO_IP) proto,
5100 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5101 off + MAX_TCP_HDR_LEN);
5102 if (!err && !skb_partial_csum_set(skb, off,
5103 offsetof(struct tcphdr,
5106 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5109 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5110 off + sizeof(struct udphdr));
5111 if (!err && !skb_partial_csum_set(skb, off,
5112 offsetof(struct udphdr,
5115 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5118 return ERR_PTR(-EPROTO);
5121 /* This value should be large enough to cover a tagged ethernet header plus
5122 * maximally sized IP and TCP or UDP headers.
5124 #define MAX_IP_HDR_LEN 128
5126 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5135 err = skb_maybe_pull_tail(skb,
5136 sizeof(struct iphdr),
5141 if (ip_is_fragment(ip_hdr(skb)))
5144 off = ip_hdrlen(skb);
5151 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5153 return PTR_ERR(csum);
5156 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5159 ip_hdr(skb)->protocol, 0);
5166 /* This value should be large enough to cover a tagged ethernet header plus
5167 * an IPv6 header, all options, and a maximal TCP or UDP header.
5169 #define MAX_IPV6_HDR_LEN 256
5171 #define OPT_HDR(type, skb, off) \
5172 (type *)(skb_network_header(skb) + (off))
5174 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5187 off = sizeof(struct ipv6hdr);
5189 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5193 nexthdr = ipv6_hdr(skb)->nexthdr;
5195 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5196 while (off <= len && !done) {
5198 case IPPROTO_DSTOPTS:
5199 case IPPROTO_HOPOPTS:
5200 case IPPROTO_ROUTING: {
5201 struct ipv6_opt_hdr *hp;
5203 err = skb_maybe_pull_tail(skb,
5205 sizeof(struct ipv6_opt_hdr),
5210 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5211 nexthdr = hp->nexthdr;
5212 off += ipv6_optlen(hp);
5216 struct ip_auth_hdr *hp;
5218 err = skb_maybe_pull_tail(skb,
5220 sizeof(struct ip_auth_hdr),
5225 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5226 nexthdr = hp->nexthdr;
5227 off += ipv6_authlen(hp);
5230 case IPPROTO_FRAGMENT: {
5231 struct frag_hdr *hp;
5233 err = skb_maybe_pull_tail(skb,
5235 sizeof(struct frag_hdr),
5240 hp = OPT_HDR(struct frag_hdr, skb, off);
5242 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5245 nexthdr = hp->nexthdr;
5246 off += sizeof(struct frag_hdr);
5257 if (!done || fragment)
5260 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5262 return PTR_ERR(csum);
5265 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5266 &ipv6_hdr(skb)->daddr,
5267 skb->len - off, nexthdr, 0);
5275 * skb_checksum_setup - set up partial checksum offset
5276 * @skb: the skb to set up
5277 * @recalculate: if true the pseudo-header checksum will be recalculated
5279 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5283 switch (skb->protocol) {
5284 case htons(ETH_P_IP):
5285 err = skb_checksum_setup_ipv4(skb, recalculate);
5288 case htons(ETH_P_IPV6):
5289 err = skb_checksum_setup_ipv6(skb, recalculate);
5299 EXPORT_SYMBOL(skb_checksum_setup);
5302 * skb_checksum_maybe_trim - maybe trims the given skb
5303 * @skb: the skb to check
5304 * @transport_len: the data length beyond the network header
5306 * Checks whether the given skb has data beyond the given transport length.
5307 * If so, returns a cloned skb trimmed to this transport length.
5308 * Otherwise returns the provided skb. Returns NULL in error cases
5309 * (e.g. transport_len exceeds skb length or out-of-memory).
5311 * Caller needs to set the skb transport header and free any returned skb if it
5312 * differs from the provided skb.
5314 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5315 unsigned int transport_len)
5317 struct sk_buff *skb_chk;
5318 unsigned int len = skb_transport_offset(skb) + transport_len;
5323 else if (skb->len == len)
5326 skb_chk = skb_clone(skb, GFP_ATOMIC);
5330 ret = pskb_trim_rcsum(skb_chk, len);
5340 * skb_checksum_trimmed - validate checksum of an skb
5341 * @skb: the skb to check
5342 * @transport_len: the data length beyond the network header
5343 * @skb_chkf: checksum function to use
5345 * Applies the given checksum function skb_chkf to the provided skb.
5346 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5348 * If the skb has data beyond the given transport length, then a
5349 * trimmed & cloned skb is checked and returned.
5351 * Caller needs to set the skb transport header and free any returned skb if it
5352 * differs from the provided skb.
5354 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5355 unsigned int transport_len,
5356 __sum16(*skb_chkf)(struct sk_buff *skb))
5358 struct sk_buff *skb_chk;
5359 unsigned int offset = skb_transport_offset(skb);
5362 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5366 if (!pskb_may_pull(skb_chk, offset))
5369 skb_pull_rcsum(skb_chk, offset);
5370 ret = skb_chkf(skb_chk);
5371 skb_push_rcsum(skb_chk, offset);
5379 if (skb_chk && skb_chk != skb)
5385 EXPORT_SYMBOL(skb_checksum_trimmed);
5387 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5389 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5392 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5394 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5397 skb_release_head_state(skb);
5398 kmem_cache_free(skbuff_head_cache, skb);
5403 EXPORT_SYMBOL(kfree_skb_partial);
5406 * skb_try_coalesce - try to merge skb to prior one
5408 * @from: buffer to add
5409 * @fragstolen: pointer to boolean
5410 * @delta_truesize: how much more was allocated than was requested
5412 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5413 bool *fragstolen, int *delta_truesize)
5415 struct skb_shared_info *to_shinfo, *from_shinfo;
5416 int i, delta, len = from->len;
5418 *fragstolen = false;
5423 /* In general, avoid mixing page_pool and non-page_pool allocated
5424 * pages within the same SKB. Additionally avoid dealing with clones
5425 * with page_pool pages, in case the SKB is using page_pool fragment
5426 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5427 * references for cloned SKBs at the moment that would result in
5428 * inconsistent reference counts.
5429 * In theory we could take full references if @from is cloned and
5430 * !@to->pp_recycle but its tricky (due to potential race with
5431 * the clone disappearing) and rare, so not worth dealing with.
5433 if (to->pp_recycle != from->pp_recycle ||
5434 (from->pp_recycle && skb_cloned(from)))
5437 if (len <= skb_tailroom(to)) {
5439 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5440 *delta_truesize = 0;
5444 to_shinfo = skb_shinfo(to);
5445 from_shinfo = skb_shinfo(from);
5446 if (to_shinfo->frag_list || from_shinfo->frag_list)
5448 if (skb_zcopy(to) || skb_zcopy(from))
5451 if (skb_headlen(from) != 0) {
5453 unsigned int offset;
5455 if (to_shinfo->nr_frags +
5456 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5459 if (skb_head_is_locked(from))
5462 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5464 page = virt_to_head_page(from->head);
5465 offset = from->data - (unsigned char *)page_address(page);
5467 skb_fill_page_desc(to, to_shinfo->nr_frags,
5468 page, offset, skb_headlen(from));
5471 if (to_shinfo->nr_frags +
5472 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5475 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5478 WARN_ON_ONCE(delta < len);
5480 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5482 from_shinfo->nr_frags * sizeof(skb_frag_t));
5483 to_shinfo->nr_frags += from_shinfo->nr_frags;
5485 if (!skb_cloned(from))
5486 from_shinfo->nr_frags = 0;
5488 /* if the skb is not cloned this does nothing
5489 * since we set nr_frags to 0.
5491 for (i = 0; i < from_shinfo->nr_frags; i++)
5492 __skb_frag_ref(&from_shinfo->frags[i]);
5494 to->truesize += delta;
5496 to->data_len += len;
5498 *delta_truesize = delta;
5501 EXPORT_SYMBOL(skb_try_coalesce);
5504 * skb_scrub_packet - scrub an skb
5506 * @skb: buffer to clean
5507 * @xnet: packet is crossing netns
5509 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5510 * into/from a tunnel. Some information have to be cleared during these
5512 * skb_scrub_packet can also be used to clean a skb before injecting it in
5513 * another namespace (@xnet == true). We have to clear all information in the
5514 * skb that could impact namespace isolation.
5516 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5518 skb->pkt_type = PACKET_HOST;
5524 nf_reset_trace(skb);
5526 #ifdef CONFIG_NET_SWITCHDEV
5527 skb->offload_fwd_mark = 0;
5528 skb->offload_l3_fwd_mark = 0;
5536 skb_clear_tstamp(skb);
5538 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5541 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5545 * skb_gso_transport_seglen is used to determine the real size of the
5546 * individual segments, including Layer4 headers (TCP/UDP).
5548 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5550 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5552 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5553 unsigned int thlen = 0;
5555 if (skb->encapsulation) {
5556 thlen = skb_inner_transport_header(skb) -
5557 skb_transport_header(skb);
5559 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5560 thlen += inner_tcp_hdrlen(skb);
5561 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5562 thlen = tcp_hdrlen(skb);
5563 } else if (unlikely(skb_is_gso_sctp(skb))) {
5564 thlen = sizeof(struct sctphdr);
5565 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5566 thlen = sizeof(struct udphdr);
5568 /* UFO sets gso_size to the size of the fragmentation
5569 * payload, i.e. the size of the L4 (UDP) header is already
5572 return thlen + shinfo->gso_size;
5576 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5580 * skb_gso_network_seglen is used to determine the real size of the
5581 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5583 * The MAC/L2 header is not accounted for.
5585 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5587 unsigned int hdr_len = skb_transport_header(skb) -
5588 skb_network_header(skb);
5590 return hdr_len + skb_gso_transport_seglen(skb);
5594 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5598 * skb_gso_mac_seglen is used to determine the real size of the
5599 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5600 * headers (TCP/UDP).
5602 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5604 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5606 return hdr_len + skb_gso_transport_seglen(skb);
5610 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5612 * There are a couple of instances where we have a GSO skb, and we
5613 * want to determine what size it would be after it is segmented.
5615 * We might want to check:
5616 * - L3+L4+payload size (e.g. IP forwarding)
5617 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5619 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5623 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5624 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5626 * @max_len: The maximum permissible length.
5628 * Returns true if the segmented length <= max length.
5630 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5631 unsigned int seg_len,
5632 unsigned int max_len) {
5633 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5634 const struct sk_buff *iter;
5636 if (shinfo->gso_size != GSO_BY_FRAGS)
5637 return seg_len <= max_len;
5639 /* Undo this so we can re-use header sizes */
5640 seg_len -= GSO_BY_FRAGS;
5642 skb_walk_frags(skb, iter) {
5643 if (seg_len + skb_headlen(iter) > max_len)
5651 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5654 * @mtu: MTU to validate against
5656 * skb_gso_validate_network_len validates if a given skb will fit a
5657 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5660 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5662 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5664 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5667 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5670 * @len: length to validate against
5672 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5673 * length once split, including L2, L3 and L4 headers and the payload.
5675 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5677 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5679 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5681 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5683 int mac_len, meta_len;
5686 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5691 mac_len = skb->data - skb_mac_header(skb);
5692 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5693 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5694 mac_len - VLAN_HLEN - ETH_TLEN);
5697 meta_len = skb_metadata_len(skb);
5699 meta = skb_metadata_end(skb) - meta_len;
5700 memmove(meta + VLAN_HLEN, meta, meta_len);
5703 skb->mac_header += VLAN_HLEN;
5707 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5709 struct vlan_hdr *vhdr;
5712 if (unlikely(skb_vlan_tag_present(skb))) {
5713 /* vlan_tci is already set-up so leave this for another time */
5717 skb = skb_share_check(skb, GFP_ATOMIC);
5720 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5721 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5724 vhdr = (struct vlan_hdr *)skb->data;
5725 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5726 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5728 skb_pull_rcsum(skb, VLAN_HLEN);
5729 vlan_set_encap_proto(skb, vhdr);
5731 skb = skb_reorder_vlan_header(skb);
5735 skb_reset_network_header(skb);
5736 if (!skb_transport_header_was_set(skb))
5737 skb_reset_transport_header(skb);
5738 skb_reset_mac_len(skb);
5746 EXPORT_SYMBOL(skb_vlan_untag);
5748 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5750 if (!pskb_may_pull(skb, write_len))
5753 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5756 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5758 EXPORT_SYMBOL(skb_ensure_writable);
5760 /* remove VLAN header from packet and update csum accordingly.
5761 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5763 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5765 struct vlan_hdr *vhdr;
5766 int offset = skb->data - skb_mac_header(skb);
5769 if (WARN_ONCE(offset,
5770 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5775 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5779 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5781 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5782 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5784 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5785 __skb_pull(skb, VLAN_HLEN);
5787 vlan_set_encap_proto(skb, vhdr);
5788 skb->mac_header += VLAN_HLEN;
5790 if (skb_network_offset(skb) < ETH_HLEN)
5791 skb_set_network_header(skb, ETH_HLEN);
5793 skb_reset_mac_len(skb);
5797 EXPORT_SYMBOL(__skb_vlan_pop);
5799 /* Pop a vlan tag either from hwaccel or from payload.
5800 * Expects skb->data at mac header.
5802 int skb_vlan_pop(struct sk_buff *skb)
5808 if (likely(skb_vlan_tag_present(skb))) {
5809 __vlan_hwaccel_clear_tag(skb);
5811 if (unlikely(!eth_type_vlan(skb->protocol)))
5814 err = __skb_vlan_pop(skb, &vlan_tci);
5818 /* move next vlan tag to hw accel tag */
5819 if (likely(!eth_type_vlan(skb->protocol)))
5822 vlan_proto = skb->protocol;
5823 err = __skb_vlan_pop(skb, &vlan_tci);
5827 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5830 EXPORT_SYMBOL(skb_vlan_pop);
5832 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5833 * Expects skb->data at mac header.
5835 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5837 if (skb_vlan_tag_present(skb)) {
5838 int offset = skb->data - skb_mac_header(skb);
5841 if (WARN_ONCE(offset,
5842 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5847 err = __vlan_insert_tag(skb, skb->vlan_proto,
5848 skb_vlan_tag_get(skb));
5852 skb->protocol = skb->vlan_proto;
5853 skb->mac_len += VLAN_HLEN;
5855 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5857 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5860 EXPORT_SYMBOL(skb_vlan_push);
5863 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5865 * @skb: Socket buffer to modify
5867 * Drop the Ethernet header of @skb.
5869 * Expects that skb->data points to the mac header and that no VLAN tags are
5872 * Returns 0 on success, -errno otherwise.
5874 int skb_eth_pop(struct sk_buff *skb)
5876 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5877 skb_network_offset(skb) < ETH_HLEN)
5880 skb_pull_rcsum(skb, ETH_HLEN);
5881 skb_reset_mac_header(skb);
5882 skb_reset_mac_len(skb);
5886 EXPORT_SYMBOL(skb_eth_pop);
5889 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5891 * @skb: Socket buffer to modify
5892 * @dst: Destination MAC address of the new header
5893 * @src: Source MAC address of the new header
5895 * Prepend @skb with a new Ethernet header.
5897 * Expects that skb->data points to the mac header, which must be empty.
5899 * Returns 0 on success, -errno otherwise.
5901 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5902 const unsigned char *src)
5907 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5910 err = skb_cow_head(skb, sizeof(*eth));
5914 skb_push(skb, sizeof(*eth));
5915 skb_reset_mac_header(skb);
5916 skb_reset_mac_len(skb);
5919 ether_addr_copy(eth->h_dest, dst);
5920 ether_addr_copy(eth->h_source, src);
5921 eth->h_proto = skb->protocol;
5923 skb_postpush_rcsum(skb, eth, sizeof(*eth));
5927 EXPORT_SYMBOL(skb_eth_push);
5929 /* Update the ethertype of hdr and the skb csum value if required. */
5930 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5933 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5934 __be16 diff[] = { ~hdr->h_proto, ethertype };
5936 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5939 hdr->h_proto = ethertype;
5943 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5947 * @mpls_lse: MPLS label stack entry to push
5948 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5949 * @mac_len: length of the MAC header
5950 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5953 * Expects skb->data at mac header.
5955 * Returns 0 on success, -errno otherwise.
5957 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5958 int mac_len, bool ethernet)
5960 struct mpls_shim_hdr *lse;
5963 if (unlikely(!eth_p_mpls(mpls_proto)))
5966 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5967 if (skb->encapsulation)
5970 err = skb_cow_head(skb, MPLS_HLEN);
5974 if (!skb->inner_protocol) {
5975 skb_set_inner_network_header(skb, skb_network_offset(skb));
5976 skb_set_inner_protocol(skb, skb->protocol);
5979 skb_push(skb, MPLS_HLEN);
5980 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5982 skb_reset_mac_header(skb);
5983 skb_set_network_header(skb, mac_len);
5984 skb_reset_mac_len(skb);
5986 lse = mpls_hdr(skb);
5987 lse->label_stack_entry = mpls_lse;
5988 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5990 if (ethernet && mac_len >= ETH_HLEN)
5991 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5992 skb->protocol = mpls_proto;
5996 EXPORT_SYMBOL_GPL(skb_mpls_push);
5999 * skb_mpls_pop() - pop the outermost MPLS header
6002 * @next_proto: ethertype of header after popped MPLS header
6003 * @mac_len: length of the MAC header
6004 * @ethernet: flag to indicate if the packet is ethernet
6006 * Expects skb->data at mac header.
6008 * Returns 0 on success, -errno otherwise.
6010 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6015 if (unlikely(!eth_p_mpls(skb->protocol)))
6018 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6022 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6023 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6026 __skb_pull(skb, MPLS_HLEN);
6027 skb_reset_mac_header(skb);
6028 skb_set_network_header(skb, mac_len);
6030 if (ethernet && mac_len >= ETH_HLEN) {
6033 /* use mpls_hdr() to get ethertype to account for VLANs. */
6034 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6035 skb_mod_eth_type(skb, hdr, next_proto);
6037 skb->protocol = next_proto;
6041 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6044 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6047 * @mpls_lse: new MPLS label stack entry to update to
6049 * Expects skb->data at mac header.
6051 * Returns 0 on success, -errno otherwise.
6053 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6057 if (unlikely(!eth_p_mpls(skb->protocol)))
6060 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6064 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6065 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6067 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6070 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6074 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6077 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6081 * Expects skb->data at mac header.
6083 * Returns 0 on success, -errno otherwise.
6085 int skb_mpls_dec_ttl(struct sk_buff *skb)
6090 if (unlikely(!eth_p_mpls(skb->protocol)))
6093 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6096 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6097 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6101 lse &= ~MPLS_LS_TTL_MASK;
6102 lse |= ttl << MPLS_LS_TTL_SHIFT;
6104 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6106 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6109 * alloc_skb_with_frags - allocate skb with page frags
6111 * @header_len: size of linear part
6112 * @data_len: needed length in frags
6113 * @max_page_order: max page order desired.
6114 * @errcode: pointer to error code if any
6115 * @gfp_mask: allocation mask
6117 * This can be used to allocate a paged skb, given a maximal order for frags.
6119 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6120 unsigned long data_len,
6125 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6126 unsigned long chunk;
6127 struct sk_buff *skb;
6131 *errcode = -EMSGSIZE;
6132 /* Note this test could be relaxed, if we succeed to allocate
6133 * high order pages...
6135 if (npages > MAX_SKB_FRAGS)
6138 *errcode = -ENOBUFS;
6139 skb = alloc_skb(header_len, gfp_mask);
6143 skb->truesize += npages << PAGE_SHIFT;
6145 for (i = 0; npages > 0; i++) {
6146 int order = max_page_order;
6149 if (npages >= 1 << order) {
6150 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6156 /* Do not retry other high order allocations */
6162 page = alloc_page(gfp_mask);
6166 chunk = min_t(unsigned long, data_len,
6167 PAGE_SIZE << order);
6168 skb_fill_page_desc(skb, i, page, 0, chunk);
6170 npages -= 1 << order;
6178 EXPORT_SYMBOL(alloc_skb_with_frags);
6180 /* carve out the first off bytes from skb when off < headlen */
6181 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6182 const int headlen, gfp_t gfp_mask)
6185 int size = skb_end_offset(skb);
6186 int new_hlen = headlen - off;
6189 size = SKB_DATA_ALIGN(size);
6191 if (skb_pfmemalloc(skb))
6192 gfp_mask |= __GFP_MEMALLOC;
6193 data = kmalloc_reserve(size +
6194 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6195 gfp_mask, NUMA_NO_NODE, NULL);
6199 size = SKB_WITH_OVERHEAD(ksize(data));
6201 /* Copy real data, and all frags */
6202 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6205 memcpy((struct skb_shared_info *)(data + size),
6207 offsetof(struct skb_shared_info,
6208 frags[skb_shinfo(skb)->nr_frags]));
6209 if (skb_cloned(skb)) {
6210 /* drop the old head gracefully */
6211 if (skb_orphan_frags(skb, gfp_mask)) {
6215 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6216 skb_frag_ref(skb, i);
6217 if (skb_has_frag_list(skb))
6218 skb_clone_fraglist(skb);
6219 skb_release_data(skb);
6221 /* we can reuse existing recount- all we did was
6230 skb_set_end_offset(skb, size);
6231 skb_set_tail_pointer(skb, skb_headlen(skb));
6232 skb_headers_offset_update(skb, 0);
6236 atomic_set(&skb_shinfo(skb)->dataref, 1);
6241 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6243 /* carve out the first eat bytes from skb's frag_list. May recurse into
6246 static int pskb_carve_frag_list(struct sk_buff *skb,
6247 struct skb_shared_info *shinfo, int eat,
6250 struct sk_buff *list = shinfo->frag_list;
6251 struct sk_buff *clone = NULL;
6252 struct sk_buff *insp = NULL;
6256 pr_err("Not enough bytes to eat. Want %d\n", eat);
6259 if (list->len <= eat) {
6260 /* Eaten as whole. */
6265 /* Eaten partially. */
6266 if (skb_shared(list)) {
6267 clone = skb_clone(list, gfp_mask);
6273 /* This may be pulled without problems. */
6276 if (pskb_carve(list, eat, gfp_mask) < 0) {
6284 /* Free pulled out fragments. */
6285 while ((list = shinfo->frag_list) != insp) {
6286 shinfo->frag_list = list->next;
6289 /* And insert new clone at head. */
6292 shinfo->frag_list = clone;
6297 /* carve off first len bytes from skb. Split line (off) is in the
6298 * non-linear part of skb
6300 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6301 int pos, gfp_t gfp_mask)
6304 int size = skb_end_offset(skb);
6306 const int nfrags = skb_shinfo(skb)->nr_frags;
6307 struct skb_shared_info *shinfo;
6309 size = SKB_DATA_ALIGN(size);
6311 if (skb_pfmemalloc(skb))
6312 gfp_mask |= __GFP_MEMALLOC;
6313 data = kmalloc_reserve(size +
6314 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6315 gfp_mask, NUMA_NO_NODE, NULL);
6319 size = SKB_WITH_OVERHEAD(ksize(data));
6321 memcpy((struct skb_shared_info *)(data + size),
6322 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6323 if (skb_orphan_frags(skb, gfp_mask)) {
6327 shinfo = (struct skb_shared_info *)(data + size);
6328 for (i = 0; i < nfrags; i++) {
6329 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6331 if (pos + fsize > off) {
6332 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6336 * We have two variants in this case:
6337 * 1. Move all the frag to the second
6338 * part, if it is possible. F.e.
6339 * this approach is mandatory for TUX,
6340 * where splitting is expensive.
6341 * 2. Split is accurately. We make this.
6343 skb_frag_off_add(&shinfo->frags[0], off - pos);
6344 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6346 skb_frag_ref(skb, i);
6351 shinfo->nr_frags = k;
6352 if (skb_has_frag_list(skb))
6353 skb_clone_fraglist(skb);
6355 /* split line is in frag list */
6356 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6357 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6358 if (skb_has_frag_list(skb))
6359 kfree_skb_list(skb_shinfo(skb)->frag_list);
6363 skb_release_data(skb);
6368 skb_set_end_offset(skb, size);
6369 skb_reset_tail_pointer(skb);
6370 skb_headers_offset_update(skb, 0);
6375 skb->data_len = skb->len;
6376 atomic_set(&skb_shinfo(skb)->dataref, 1);
6380 /* remove len bytes from the beginning of the skb */
6381 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6383 int headlen = skb_headlen(skb);
6386 return pskb_carve_inside_header(skb, len, headlen, gfp);
6388 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6391 /* Extract to_copy bytes starting at off from skb, and return this in
6394 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6395 int to_copy, gfp_t gfp)
6397 struct sk_buff *clone = skb_clone(skb, gfp);
6402 if (pskb_carve(clone, off, gfp) < 0 ||
6403 pskb_trim(clone, to_copy)) {
6409 EXPORT_SYMBOL(pskb_extract);
6412 * skb_condense - try to get rid of fragments/frag_list if possible
6415 * Can be used to save memory before skb is added to a busy queue.
6416 * If packet has bytes in frags and enough tail room in skb->head,
6417 * pull all of them, so that we can free the frags right now and adjust
6420 * We do not reallocate skb->head thus can not fail.
6421 * Caller must re-evaluate skb->truesize if needed.
6423 void skb_condense(struct sk_buff *skb)
6425 if (skb->data_len) {
6426 if (skb->data_len > skb->end - skb->tail ||
6430 /* Nice, we can free page frag(s) right now */
6431 __pskb_pull_tail(skb, skb->data_len);
6433 /* At this point, skb->truesize might be over estimated,
6434 * because skb had a fragment, and fragments do not tell
6436 * When we pulled its content into skb->head, fragment
6437 * was freed, but __pskb_pull_tail() could not possibly
6438 * adjust skb->truesize, not knowing the frag truesize.
6440 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6443 #ifdef CONFIG_SKB_EXTENSIONS
6444 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6446 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6450 * __skb_ext_alloc - allocate a new skb extensions storage
6452 * @flags: See kmalloc().
6454 * Returns the newly allocated pointer. The pointer can later attached to a
6455 * skb via __skb_ext_set().
6456 * Note: caller must handle the skb_ext as an opaque data.
6458 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6460 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6463 memset(new->offset, 0, sizeof(new->offset));
6464 refcount_set(&new->refcnt, 1);
6470 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6471 unsigned int old_active)
6473 struct skb_ext *new;
6475 if (refcount_read(&old->refcnt) == 1)
6478 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6482 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6483 refcount_set(&new->refcnt, 1);
6486 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6487 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6490 for (i = 0; i < sp->len; i++)
6491 xfrm_state_hold(sp->xvec[i]);
6499 * __skb_ext_set - attach the specified extension storage to this skb
6502 * @ext: extension storage previously allocated via __skb_ext_alloc()
6504 * Existing extensions, if any, are cleared.
6506 * Returns the pointer to the extension.
6508 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6509 struct skb_ext *ext)
6511 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6514 newlen = newoff + skb_ext_type_len[id];
6515 ext->chunks = newlen;
6516 ext->offset[id] = newoff;
6517 skb->extensions = ext;
6518 skb->active_extensions = 1 << id;
6519 return skb_ext_get_ptr(ext, id);
6523 * skb_ext_add - allocate space for given extension, COW if needed
6525 * @id: extension to allocate space for
6527 * Allocates enough space for the given extension.
6528 * If the extension is already present, a pointer to that extension
6531 * If the skb was cloned, COW applies and the returned memory can be
6532 * modified without changing the extension space of clones buffers.
6534 * Returns pointer to the extension or NULL on allocation failure.
6536 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6538 struct skb_ext *new, *old = NULL;
6539 unsigned int newlen, newoff;
6541 if (skb->active_extensions) {
6542 old = skb->extensions;
6544 new = skb_ext_maybe_cow(old, skb->active_extensions);
6548 if (__skb_ext_exist(new, id))
6551 newoff = new->chunks;
6553 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6555 new = __skb_ext_alloc(GFP_ATOMIC);
6560 newlen = newoff + skb_ext_type_len[id];
6561 new->chunks = newlen;
6562 new->offset[id] = newoff;
6565 skb->extensions = new;
6566 skb->active_extensions |= 1 << id;
6567 return skb_ext_get_ptr(new, id);
6569 EXPORT_SYMBOL(skb_ext_add);
6572 static void skb_ext_put_sp(struct sec_path *sp)
6576 for (i = 0; i < sp->len; i++)
6577 xfrm_state_put(sp->xvec[i]);
6581 #ifdef CONFIG_MCTP_FLOWS
6582 static void skb_ext_put_mctp(struct mctp_flow *flow)
6585 mctp_key_unref(flow->key);
6589 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6591 struct skb_ext *ext = skb->extensions;
6593 skb->active_extensions &= ~(1 << id);
6594 if (skb->active_extensions == 0) {
6595 skb->extensions = NULL;
6598 } else if (id == SKB_EXT_SEC_PATH &&
6599 refcount_read(&ext->refcnt) == 1) {
6600 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6607 EXPORT_SYMBOL(__skb_ext_del);
6609 void __skb_ext_put(struct skb_ext *ext)
6611 /* If this is last clone, nothing can increment
6612 * it after check passes. Avoids one atomic op.
6614 if (refcount_read(&ext->refcnt) == 1)
6617 if (!refcount_dec_and_test(&ext->refcnt))
6621 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6622 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6624 #ifdef CONFIG_MCTP_FLOWS
6625 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6626 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6629 kmem_cache_free(skbuff_ext_cache, ext);
6631 EXPORT_SYMBOL(__skb_ext_put);
6632 #endif /* CONFIG_SKB_EXTENSIONS */
6635 * skb_attempt_defer_free - queue skb for remote freeing
6638 * Put @skb in a per-cpu list, using the cpu which
6639 * allocated the skb/pages to reduce false sharing
6640 * and memory zone spinlock contention.
6642 void skb_attempt_defer_free(struct sk_buff *skb)
6644 int cpu = skb->alloc_cpu;
6645 struct softnet_data *sd;
6646 unsigned long flags;
6647 unsigned int defer_max;
6650 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6652 cpu == raw_smp_processor_id()) {
6653 nodefer: __kfree_skb(skb);
6657 sd = &per_cpu(softnet_data, cpu);
6658 defer_max = READ_ONCE(sysctl_skb_defer_max);
6659 if (READ_ONCE(sd->defer_count) >= defer_max)
6662 spin_lock_irqsave(&sd->defer_lock, flags);
6663 /* Send an IPI every time queue reaches half capacity. */
6664 kick = sd->defer_count == (defer_max >> 1);
6665 /* Paired with the READ_ONCE() few lines above */
6666 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6668 skb->next = sd->defer_list;
6669 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6670 WRITE_ONCE(sd->defer_list, skb);
6671 spin_unlock_irqrestore(&sd->defer_lock, flags);
6673 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6674 * if we are unlucky enough (this seems very unlikely).
6676 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6677 smp_call_function_single_async(cpu, &sd->defer_csd);