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);
94 /* The array 'drop_reasons' is auto-generated in dropreason_str.c */
95 EXPORT_SYMBOL(drop_reasons);
98 * skb_panic - private function for out-of-line support
102 * @msg: skb_over_panic or skb_under_panic
104 * Out-of-line support for skb_put() and skb_push().
105 * Called via the wrapper skb_over_panic() or skb_under_panic().
106 * Keep out of line to prevent kernel bloat.
107 * __builtin_return_address is not used because it is not always reliable.
109 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
112 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
113 msg, addr, skb->len, sz, skb->head, skb->data,
114 (unsigned long)skb->tail, (unsigned long)skb->end,
115 skb->dev ? skb->dev->name : "<NULL>");
119 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
121 skb_panic(skb, sz, addr, __func__);
124 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
126 skb_panic(skb, sz, addr, __func__);
129 #define NAPI_SKB_CACHE_SIZE 64
130 #define NAPI_SKB_CACHE_BULK 16
131 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
133 struct napi_alloc_cache {
134 struct page_frag_cache page;
135 unsigned int skb_count;
136 void *skb_cache[NAPI_SKB_CACHE_SIZE];
139 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
140 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
142 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
144 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
146 fragsz = SKB_DATA_ALIGN(fragsz);
148 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
150 EXPORT_SYMBOL(__napi_alloc_frag_align);
152 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
156 fragsz = SKB_DATA_ALIGN(fragsz);
157 if (in_hardirq() || irqs_disabled()) {
158 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
160 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
162 struct napi_alloc_cache *nc;
165 nc = this_cpu_ptr(&napi_alloc_cache);
166 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
171 EXPORT_SYMBOL(__netdev_alloc_frag_align);
173 static struct sk_buff *napi_skb_cache_get(void)
175 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
178 if (unlikely(!nc->skb_count))
179 nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
183 if (unlikely(!nc->skb_count))
186 skb = nc->skb_cache[--nc->skb_count];
187 kasan_unpoison_object_data(skbuff_head_cache, skb);
192 /* Caller must provide SKB that is memset cleared */
193 static void __build_skb_around(struct sk_buff *skb, void *data,
194 unsigned int frag_size)
196 struct skb_shared_info *shinfo;
197 unsigned int size = frag_size ? : ksize(data);
199 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
201 /* Assumes caller memset cleared SKB */
202 skb->truesize = SKB_TRUESIZE(size);
203 refcount_set(&skb->users, 1);
206 skb_reset_tail_pointer(skb);
207 skb_set_end_offset(skb, size);
208 skb->mac_header = (typeof(skb->mac_header))~0U;
209 skb->transport_header = (typeof(skb->transport_header))~0U;
210 skb->alloc_cpu = raw_smp_processor_id();
211 /* make sure we initialize shinfo sequentially */
212 shinfo = skb_shinfo(skb);
213 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
214 atomic_set(&shinfo->dataref, 1);
216 skb_set_kcov_handle(skb, kcov_common_handle());
220 * __build_skb - build a network buffer
221 * @data: data buffer provided by caller
222 * @frag_size: size of data, or 0 if head was kmalloced
224 * Allocate a new &sk_buff. Caller provides space holding head and
225 * skb_shared_info. @data must have been allocated by kmalloc() only if
226 * @frag_size is 0, otherwise data should come from the page allocator
228 * The return is the new skb buffer.
229 * On a failure the return is %NULL, and @data is not freed.
231 * Before IO, driver allocates only data buffer where NIC put incoming frame
232 * Driver should add room at head (NET_SKB_PAD) and
233 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
234 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
235 * before giving packet to stack.
236 * RX rings only contains data buffers, not full skbs.
238 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
242 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
246 memset(skb, 0, offsetof(struct sk_buff, tail));
247 __build_skb_around(skb, data, frag_size);
252 /* build_skb() is wrapper over __build_skb(), that specifically
253 * takes care of skb->head and skb->pfmemalloc
254 * This means that if @frag_size is not zero, then @data must be backed
255 * by a page fragment, not kmalloc() or vmalloc()
257 struct sk_buff *build_skb(void *data, unsigned int frag_size)
259 struct sk_buff *skb = __build_skb(data, frag_size);
261 if (skb && frag_size) {
263 if (page_is_pfmemalloc(virt_to_head_page(data)))
268 EXPORT_SYMBOL(build_skb);
271 * build_skb_around - build a network buffer around provided skb
272 * @skb: sk_buff provide by caller, must be memset cleared
273 * @data: data buffer provided by caller
274 * @frag_size: size of data, or 0 if head was kmalloced
276 struct sk_buff *build_skb_around(struct sk_buff *skb,
277 void *data, unsigned int frag_size)
282 __build_skb_around(skb, data, frag_size);
286 if (page_is_pfmemalloc(virt_to_head_page(data)))
291 EXPORT_SYMBOL(build_skb_around);
294 * __napi_build_skb - build a network buffer
295 * @data: data buffer provided by caller
296 * @frag_size: size of data, or 0 if head was kmalloced
298 * Version of __build_skb() that uses NAPI percpu caches to obtain
299 * skbuff_head instead of inplace allocation.
301 * Returns a new &sk_buff on success, %NULL on allocation failure.
303 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
307 skb = napi_skb_cache_get();
311 memset(skb, 0, offsetof(struct sk_buff, tail));
312 __build_skb_around(skb, data, frag_size);
318 * napi_build_skb - build a network buffer
319 * @data: data buffer provided by caller
320 * @frag_size: size of data, or 0 if head was kmalloced
322 * Version of __napi_build_skb() that takes care of skb->head_frag
323 * and skb->pfmemalloc when the data is a page or page fragment.
325 * Returns a new &sk_buff on success, %NULL on allocation failure.
327 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
329 struct sk_buff *skb = __napi_build_skb(data, frag_size);
331 if (likely(skb) && frag_size) {
333 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
338 EXPORT_SYMBOL(napi_build_skb);
341 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
342 * the caller if emergency pfmemalloc reserves are being used. If it is and
343 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
344 * may be used. Otherwise, the packet data may be discarded until enough
347 static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
351 bool ret_pfmemalloc = false;
354 * Try a regular allocation, when that fails and we're not entitled
355 * to the reserves, fail.
357 obj = kmalloc_node_track_caller(size,
358 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
360 if (obj || !(gfp_pfmemalloc_allowed(flags)))
363 /* Try again but now we are using pfmemalloc reserves */
364 ret_pfmemalloc = true;
365 obj = kmalloc_node_track_caller(size, flags, node);
369 *pfmemalloc = ret_pfmemalloc;
374 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
375 * 'private' fields and also do memory statistics to find all the
381 * __alloc_skb - allocate a network buffer
382 * @size: size to allocate
383 * @gfp_mask: allocation mask
384 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
385 * instead of head cache and allocate a cloned (child) skb.
386 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
387 * allocations in case the data is required for writeback
388 * @node: numa node to allocate memory on
390 * Allocate a new &sk_buff. The returned buffer has no headroom and a
391 * tail room of at least size bytes. The object has a reference count
392 * of one. The return is the buffer. On a failure the return is %NULL.
394 * Buffers may only be allocated from interrupts using a @gfp_mask of
397 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
400 struct kmem_cache *cache;
406 cache = (flags & SKB_ALLOC_FCLONE)
407 ? skbuff_fclone_cache : skbuff_head_cache;
409 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
410 gfp_mask |= __GFP_MEMALLOC;
413 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
414 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
415 skb = napi_skb_cache_get();
417 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
422 /* We do our best to align skb_shared_info on a separate cache
423 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
424 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
425 * Both skb->head and skb_shared_info are cache line aligned.
427 size = SKB_DATA_ALIGN(size);
428 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
429 data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
432 /* kmalloc(size) might give us more room than requested.
433 * Put skb_shared_info exactly at the end of allocated zone,
434 * to allow max possible filling before reallocation.
437 size = SKB_WITH_OVERHEAD(osize);
438 prefetchw(data + size);
441 * Only clear those fields we need to clear, not those that we will
442 * actually initialise below. Hence, don't put any more fields after
443 * the tail pointer in struct sk_buff!
445 memset(skb, 0, offsetof(struct sk_buff, tail));
446 __build_skb_around(skb, data, osize);
447 skb->pfmemalloc = pfmemalloc;
449 if (flags & SKB_ALLOC_FCLONE) {
450 struct sk_buff_fclones *fclones;
452 fclones = container_of(skb, struct sk_buff_fclones, skb1);
454 skb->fclone = SKB_FCLONE_ORIG;
455 refcount_set(&fclones->fclone_ref, 1);
457 fclones->skb2.fclone = SKB_FCLONE_CLONE;
463 kmem_cache_free(cache, skb);
466 EXPORT_SYMBOL(__alloc_skb);
469 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
470 * @dev: network device to receive on
471 * @len: length to allocate
472 * @gfp_mask: get_free_pages mask, passed to alloc_skb
474 * Allocate a new &sk_buff and assign it a usage count of one. The
475 * buffer has NET_SKB_PAD headroom built in. Users should allocate
476 * the headroom they think they need without accounting for the
477 * built in space. The built in space is used for optimisations.
479 * %NULL is returned if there is no free memory.
481 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
484 struct page_frag_cache *nc;
491 /* If requested length is either too small or too big,
492 * we use kmalloc() for skb->head allocation.
494 if (len <= SKB_WITH_OVERHEAD(1024) ||
495 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
496 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
497 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
503 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
504 len = SKB_DATA_ALIGN(len);
506 if (sk_memalloc_socks())
507 gfp_mask |= __GFP_MEMALLOC;
509 if (in_hardirq() || irqs_disabled()) {
510 nc = this_cpu_ptr(&netdev_alloc_cache);
511 data = page_frag_alloc(nc, len, gfp_mask);
512 pfmemalloc = nc->pfmemalloc;
515 nc = this_cpu_ptr(&napi_alloc_cache.page);
516 data = page_frag_alloc(nc, len, gfp_mask);
517 pfmemalloc = nc->pfmemalloc;
524 skb = __build_skb(data, len);
525 if (unlikely(!skb)) {
535 skb_reserve(skb, NET_SKB_PAD);
541 EXPORT_SYMBOL(__netdev_alloc_skb);
544 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
545 * @napi: napi instance this buffer was allocated for
546 * @len: length to allocate
547 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
549 * Allocate a new sk_buff for use in NAPI receive. This buffer will
550 * attempt to allocate the head from a special reserved region used
551 * only for NAPI Rx allocation. By doing this we can save several
552 * CPU cycles by avoiding having to disable and re-enable IRQs.
554 * %NULL is returned if there is no free memory.
556 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
559 struct napi_alloc_cache *nc;
563 len += NET_SKB_PAD + NET_IP_ALIGN;
565 /* If requested length is either too small or too big,
566 * we use kmalloc() for skb->head allocation.
568 if (len <= SKB_WITH_OVERHEAD(1024) ||
569 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
570 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
571 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
578 nc = this_cpu_ptr(&napi_alloc_cache);
579 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
580 len = SKB_DATA_ALIGN(len);
582 if (sk_memalloc_socks())
583 gfp_mask |= __GFP_MEMALLOC;
585 data = page_frag_alloc(&nc->page, len, gfp_mask);
589 skb = __napi_build_skb(data, len);
590 if (unlikely(!skb)) {
595 if (nc->page.pfmemalloc)
600 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
601 skb->dev = napi->dev;
606 EXPORT_SYMBOL(__napi_alloc_skb);
608 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
609 int size, unsigned int truesize)
611 skb_fill_page_desc(skb, i, page, off, size);
613 skb->data_len += size;
614 skb->truesize += truesize;
616 EXPORT_SYMBOL(skb_add_rx_frag);
618 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
619 unsigned int truesize)
621 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
623 skb_frag_size_add(frag, size);
625 skb->data_len += size;
626 skb->truesize += truesize;
628 EXPORT_SYMBOL(skb_coalesce_rx_frag);
630 static void skb_drop_list(struct sk_buff **listp)
632 kfree_skb_list(*listp);
636 static inline void skb_drop_fraglist(struct sk_buff *skb)
638 skb_drop_list(&skb_shinfo(skb)->frag_list);
641 static void skb_clone_fraglist(struct sk_buff *skb)
643 struct sk_buff *list;
645 skb_walk_frags(skb, list)
649 static void skb_free_head(struct sk_buff *skb)
651 unsigned char *head = skb->head;
653 if (skb->head_frag) {
654 if (skb_pp_recycle(skb, head))
662 static void skb_release_data(struct sk_buff *skb)
664 struct skb_shared_info *shinfo = skb_shinfo(skb);
668 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
672 skb_zcopy_clear(skb, true);
674 for (i = 0; i < shinfo->nr_frags; i++)
675 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
677 if (shinfo->frag_list)
678 kfree_skb_list(shinfo->frag_list);
682 /* When we clone an SKB we copy the reycling bit. The pp_recycle
683 * bit is only set on the head though, so in order to avoid races
684 * while trying to recycle fragments on __skb_frag_unref() we need
685 * to make one SKB responsible for triggering the recycle path.
686 * So disable the recycling bit if an SKB is cloned and we have
687 * additional references to the fragmented part of the SKB.
688 * Eventually the last SKB will have the recycling bit set and it's
689 * dataref set to 0, which will trigger the recycling
695 * Free an skbuff by memory without cleaning the state.
697 static void kfree_skbmem(struct sk_buff *skb)
699 struct sk_buff_fclones *fclones;
701 switch (skb->fclone) {
702 case SKB_FCLONE_UNAVAILABLE:
703 kmem_cache_free(skbuff_head_cache, skb);
706 case SKB_FCLONE_ORIG:
707 fclones = container_of(skb, struct sk_buff_fclones, skb1);
709 /* We usually free the clone (TX completion) before original skb
710 * This test would have no chance to be true for the clone,
711 * while here, branch prediction will be good.
713 if (refcount_read(&fclones->fclone_ref) == 1)
717 default: /* SKB_FCLONE_CLONE */
718 fclones = container_of(skb, struct sk_buff_fclones, skb2);
721 if (!refcount_dec_and_test(&fclones->fclone_ref))
724 kmem_cache_free(skbuff_fclone_cache, fclones);
727 void skb_release_head_state(struct sk_buff *skb)
730 if (skb->destructor) {
731 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
732 skb->destructor(skb);
734 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
735 nf_conntrack_put(skb_nfct(skb));
740 /* Free everything but the sk_buff shell. */
741 static void skb_release_all(struct sk_buff *skb)
743 skb_release_head_state(skb);
744 if (likely(skb->head))
745 skb_release_data(skb);
749 * __kfree_skb - private function
752 * Free an sk_buff. Release anything attached to the buffer.
753 * Clean the state. This is an internal helper function. Users should
754 * always call kfree_skb
757 void __kfree_skb(struct sk_buff *skb)
759 skb_release_all(skb);
762 EXPORT_SYMBOL(__kfree_skb);
765 * kfree_skb_reason - free an sk_buff with special reason
766 * @skb: buffer to free
767 * @reason: reason why this skb is dropped
769 * Drop a reference to the buffer and free it if the usage count has
770 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
773 void kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
778 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
780 trace_kfree_skb(skb, __builtin_return_address(0), reason);
783 EXPORT_SYMBOL(kfree_skb_reason);
785 void kfree_skb_list_reason(struct sk_buff *segs,
786 enum skb_drop_reason reason)
789 struct sk_buff *next = segs->next;
791 kfree_skb_reason(segs, reason);
795 EXPORT_SYMBOL(kfree_skb_list_reason);
797 /* Dump skb information and contents.
799 * Must only be called from net_ratelimit()-ed paths.
801 * Dumps whole packets if full_pkt, only headers otherwise.
803 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
805 struct skb_shared_info *sh = skb_shinfo(skb);
806 struct net_device *dev = skb->dev;
807 struct sock *sk = skb->sk;
808 struct sk_buff *list_skb;
809 bool has_mac, has_trans;
810 int headroom, tailroom;
816 len = min_t(int, skb->len, MAX_HEADER + 128);
818 headroom = skb_headroom(skb);
819 tailroom = skb_tailroom(skb);
821 has_mac = skb_mac_header_was_set(skb);
822 has_trans = skb_transport_header_was_set(skb);
824 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
825 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
826 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
827 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
828 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
829 level, skb->len, headroom, skb_headlen(skb), tailroom,
830 has_mac ? skb->mac_header : -1,
831 has_mac ? skb_mac_header_len(skb) : -1,
833 has_trans ? skb_network_header_len(skb) : -1,
834 has_trans ? skb->transport_header : -1,
835 sh->tx_flags, sh->nr_frags,
836 sh->gso_size, sh->gso_type, sh->gso_segs,
837 skb->csum, skb->ip_summed, skb->csum_complete_sw,
838 skb->csum_valid, skb->csum_level,
839 skb->hash, skb->sw_hash, skb->l4_hash,
840 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
843 printk("%sdev name=%s feat=%pNF\n",
844 level, dev->name, &dev->features);
846 printk("%ssk family=%hu type=%u proto=%u\n",
847 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
849 if (full_pkt && headroom)
850 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
851 16, 1, skb->head, headroom, false);
853 seg_len = min_t(int, skb_headlen(skb), len);
855 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
856 16, 1, skb->data, seg_len, false);
859 if (full_pkt && tailroom)
860 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
861 16, 1, skb_tail_pointer(skb), tailroom, false);
863 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
864 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
865 u32 p_off, p_len, copied;
869 skb_frag_foreach_page(frag, skb_frag_off(frag),
870 skb_frag_size(frag), p, p_off, p_len,
872 seg_len = min_t(int, p_len, len);
873 vaddr = kmap_atomic(p);
874 print_hex_dump(level, "skb frag: ",
876 16, 1, vaddr + p_off, seg_len, false);
877 kunmap_atomic(vaddr);
884 if (full_pkt && skb_has_frag_list(skb)) {
885 printk("skb fraglist:\n");
886 skb_walk_frags(skb, list_skb)
887 skb_dump(level, list_skb, true);
890 EXPORT_SYMBOL(skb_dump);
893 * skb_tx_error - report an sk_buff xmit error
894 * @skb: buffer that triggered an error
896 * Report xmit error if a device callback is tracking this skb.
897 * skb must be freed afterwards.
899 void skb_tx_error(struct sk_buff *skb)
901 skb_zcopy_clear(skb, true);
903 EXPORT_SYMBOL(skb_tx_error);
905 #ifdef CONFIG_TRACEPOINTS
907 * consume_skb - free an skbuff
908 * @skb: buffer to free
910 * Drop a ref to the buffer and free it if the usage count has hit zero
911 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
912 * is being dropped after a failure and notes that
914 void consume_skb(struct sk_buff *skb)
919 trace_consume_skb(skb);
922 EXPORT_SYMBOL(consume_skb);
926 * __consume_stateless_skb - free an skbuff, assuming it is stateless
927 * @skb: buffer to free
929 * Alike consume_skb(), but this variant assumes that this is the last
930 * skb reference and all the head states have been already dropped
932 void __consume_stateless_skb(struct sk_buff *skb)
934 trace_consume_skb(skb);
935 skb_release_data(skb);
939 static void napi_skb_cache_put(struct sk_buff *skb)
941 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
944 kasan_poison_object_data(skbuff_head_cache, skb);
945 nc->skb_cache[nc->skb_count++] = skb;
947 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
948 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
949 kasan_unpoison_object_data(skbuff_head_cache,
952 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
953 nc->skb_cache + NAPI_SKB_CACHE_HALF);
954 nc->skb_count = NAPI_SKB_CACHE_HALF;
958 void __kfree_skb_defer(struct sk_buff *skb)
960 skb_release_all(skb);
961 napi_skb_cache_put(skb);
964 void napi_skb_free_stolen_head(struct sk_buff *skb)
966 if (unlikely(skb->slow_gro)) {
973 napi_skb_cache_put(skb);
976 void napi_consume_skb(struct sk_buff *skb, int budget)
978 /* Zero budget indicate non-NAPI context called us, like netpoll */
979 if (unlikely(!budget)) {
980 dev_consume_skb_any(skb);
984 lockdep_assert_in_softirq();
989 /* if reaching here SKB is ready to free */
990 trace_consume_skb(skb);
992 /* if SKB is a clone, don't handle this case */
993 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
998 skb_release_all(skb);
999 napi_skb_cache_put(skb);
1001 EXPORT_SYMBOL(napi_consume_skb);
1003 /* Make sure a field is contained by headers group */
1004 #define CHECK_SKB_FIELD(field) \
1005 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1006 offsetof(struct sk_buff, headers.field)); \
1008 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1010 new->tstamp = old->tstamp;
1011 /* We do not copy old->sk */
1012 new->dev = old->dev;
1013 memcpy(new->cb, old->cb, sizeof(old->cb));
1014 skb_dst_copy(new, old);
1015 __skb_ext_copy(new, old);
1016 __nf_copy(new, old, false);
1018 /* Note : this field could be in the headers group.
1019 * It is not yet because we do not want to have a 16 bit hole
1021 new->queue_mapping = old->queue_mapping;
1023 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1024 CHECK_SKB_FIELD(protocol);
1025 CHECK_SKB_FIELD(csum);
1026 CHECK_SKB_FIELD(hash);
1027 CHECK_SKB_FIELD(priority);
1028 CHECK_SKB_FIELD(skb_iif);
1029 CHECK_SKB_FIELD(vlan_proto);
1030 CHECK_SKB_FIELD(vlan_tci);
1031 CHECK_SKB_FIELD(transport_header);
1032 CHECK_SKB_FIELD(network_header);
1033 CHECK_SKB_FIELD(mac_header);
1034 CHECK_SKB_FIELD(inner_protocol);
1035 CHECK_SKB_FIELD(inner_transport_header);
1036 CHECK_SKB_FIELD(inner_network_header);
1037 CHECK_SKB_FIELD(inner_mac_header);
1038 CHECK_SKB_FIELD(mark);
1039 #ifdef CONFIG_NETWORK_SECMARK
1040 CHECK_SKB_FIELD(secmark);
1042 #ifdef CONFIG_NET_RX_BUSY_POLL
1043 CHECK_SKB_FIELD(napi_id);
1045 CHECK_SKB_FIELD(alloc_cpu);
1047 CHECK_SKB_FIELD(sender_cpu);
1049 #ifdef CONFIG_NET_SCHED
1050 CHECK_SKB_FIELD(tc_index);
1056 * You should not add any new code to this function. Add it to
1057 * __copy_skb_header above instead.
1059 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1061 #define C(x) n->x = skb->x
1063 n->next = n->prev = NULL;
1065 __copy_skb_header(n, skb);
1070 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1076 n->destructor = NULL;
1083 refcount_set(&n->users, 1);
1085 atomic_inc(&(skb_shinfo(skb)->dataref));
1093 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1094 * @first: first sk_buff of the msg
1096 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1100 n = alloc_skb(0, GFP_ATOMIC);
1104 n->len = first->len;
1105 n->data_len = first->len;
1106 n->truesize = first->truesize;
1108 skb_shinfo(n)->frag_list = first;
1110 __copy_skb_header(n, first);
1111 n->destructor = NULL;
1115 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1118 * skb_morph - morph one skb into another
1119 * @dst: the skb to receive the contents
1120 * @src: the skb to supply the contents
1122 * This is identical to skb_clone except that the target skb is
1123 * supplied by the user.
1125 * The target skb is returned upon exit.
1127 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1129 skb_release_all(dst);
1130 return __skb_clone(dst, src);
1132 EXPORT_SYMBOL_GPL(skb_morph);
1134 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1136 unsigned long max_pg, num_pg, new_pg, old_pg;
1137 struct user_struct *user;
1139 if (capable(CAP_IPC_LOCK) || !size)
1142 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1143 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1144 user = mmp->user ? : current_user();
1147 old_pg = atomic_long_read(&user->locked_vm);
1148 new_pg = old_pg + num_pg;
1149 if (new_pg > max_pg)
1151 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1155 mmp->user = get_uid(user);
1156 mmp->num_pg = num_pg;
1158 mmp->num_pg += num_pg;
1163 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1165 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1168 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1169 free_uid(mmp->user);
1172 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1174 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1176 struct ubuf_info *uarg;
1177 struct sk_buff *skb;
1179 WARN_ON_ONCE(!in_task());
1181 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1185 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1186 uarg = (void *)skb->cb;
1187 uarg->mmp.user = NULL;
1189 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1194 uarg->callback = msg_zerocopy_callback;
1195 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1197 uarg->bytelen = size;
1199 uarg->flags = SKBFL_ZEROCOPY_FRAG;
1200 refcount_set(&uarg->refcnt, 1);
1206 static inline struct sk_buff *skb_from_uarg(struct ubuf_info *uarg)
1208 return container_of((void *)uarg, struct sk_buff, cb);
1211 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1212 struct ubuf_info *uarg)
1215 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1218 /* realloc only when socket is locked (TCP, UDP cork),
1219 * so uarg->len and sk_zckey access is serialized
1221 if (!sock_owned_by_user(sk)) {
1226 bytelen = uarg->bytelen + size;
1227 if (uarg->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1228 /* TCP can create new skb to attach new uarg */
1229 if (sk->sk_type == SOCK_STREAM)
1234 next = (u32)atomic_read(&sk->sk_zckey);
1235 if ((u32)(uarg->id + uarg->len) == next) {
1236 if (mm_account_pinned_pages(&uarg->mmp, size))
1239 uarg->bytelen = bytelen;
1240 atomic_set(&sk->sk_zckey, ++next);
1242 /* no extra ref when appending to datagram (MSG_MORE) */
1243 if (sk->sk_type == SOCK_STREAM)
1244 net_zcopy_get(uarg);
1251 return msg_zerocopy_alloc(sk, size);
1253 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1255 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1257 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1261 old_lo = serr->ee.ee_info;
1262 old_hi = serr->ee.ee_data;
1263 sum_len = old_hi - old_lo + 1ULL + len;
1265 if (sum_len >= (1ULL << 32))
1268 if (lo != old_hi + 1)
1271 serr->ee.ee_data += len;
1275 static void __msg_zerocopy_callback(struct ubuf_info *uarg)
1277 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1278 struct sock_exterr_skb *serr;
1279 struct sock *sk = skb->sk;
1280 struct sk_buff_head *q;
1281 unsigned long flags;
1286 mm_unaccount_pinned_pages(&uarg->mmp);
1288 /* if !len, there was only 1 call, and it was aborted
1289 * so do not queue a completion notification
1291 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1296 hi = uarg->id + len - 1;
1297 is_zerocopy = uarg->zerocopy;
1299 serr = SKB_EXT_ERR(skb);
1300 memset(serr, 0, sizeof(*serr));
1301 serr->ee.ee_errno = 0;
1302 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1303 serr->ee.ee_data = hi;
1304 serr->ee.ee_info = lo;
1306 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1308 q = &sk->sk_error_queue;
1309 spin_lock_irqsave(&q->lock, flags);
1310 tail = skb_peek_tail(q);
1311 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1312 !skb_zerocopy_notify_extend(tail, lo, len)) {
1313 __skb_queue_tail(q, skb);
1316 spin_unlock_irqrestore(&q->lock, flags);
1318 sk_error_report(sk);
1325 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1328 uarg->zerocopy = uarg->zerocopy & success;
1330 if (refcount_dec_and_test(&uarg->refcnt))
1331 __msg_zerocopy_callback(uarg);
1333 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1335 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1337 struct sock *sk = skb_from_uarg(uarg)->sk;
1339 atomic_dec(&sk->sk_zckey);
1343 msg_zerocopy_callback(NULL, uarg, true);
1345 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1347 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1348 struct msghdr *msg, int len,
1349 struct ubuf_info *uarg)
1351 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1352 int err, orig_len = skb->len;
1354 /* An skb can only point to one uarg. This edge case happens when
1355 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1357 if (orig_uarg && uarg != orig_uarg)
1360 err = __zerocopy_sg_from_iter(sk, skb, &msg->msg_iter, len);
1361 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1362 struct sock *save_sk = skb->sk;
1364 /* Streams do not free skb on error. Reset to prev state. */
1365 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1367 ___pskb_trim(skb, orig_len);
1372 skb_zcopy_set(skb, uarg, NULL);
1373 return skb->len - orig_len;
1375 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1377 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1380 if (skb_zcopy(orig)) {
1381 if (skb_zcopy(nskb)) {
1382 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1387 if (skb_uarg(nskb) == skb_uarg(orig))
1389 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1392 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1398 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1399 * @skb: the skb to modify
1400 * @gfp_mask: allocation priority
1402 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1403 * It will copy all frags into kernel and drop the reference
1404 * to userspace pages.
1406 * If this function is called from an interrupt gfp_mask() must be
1409 * Returns 0 on success or a negative error code on failure
1410 * to allocate kernel memory to copy to.
1412 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1414 int num_frags = skb_shinfo(skb)->nr_frags;
1415 struct page *page, *head = NULL;
1419 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1425 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1426 for (i = 0; i < new_frags; i++) {
1427 page = alloc_page(gfp_mask);
1430 struct page *next = (struct page *)page_private(head);
1436 set_page_private(page, (unsigned long)head);
1442 for (i = 0; i < num_frags; i++) {
1443 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1444 u32 p_off, p_len, copied;
1448 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1449 p, p_off, p_len, copied) {
1451 vaddr = kmap_atomic(p);
1453 while (done < p_len) {
1454 if (d_off == PAGE_SIZE) {
1456 page = (struct page *)page_private(page);
1458 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1459 memcpy(page_address(page) + d_off,
1460 vaddr + p_off + done, copy);
1464 kunmap_atomic(vaddr);
1468 /* skb frags release userspace buffers */
1469 for (i = 0; i < num_frags; i++)
1470 skb_frag_unref(skb, i);
1472 /* skb frags point to kernel buffers */
1473 for (i = 0; i < new_frags - 1; i++) {
1474 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1475 head = (struct page *)page_private(head);
1477 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1478 skb_shinfo(skb)->nr_frags = new_frags;
1481 skb_zcopy_clear(skb, false);
1484 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1487 * skb_clone - duplicate an sk_buff
1488 * @skb: buffer to clone
1489 * @gfp_mask: allocation priority
1491 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1492 * copies share the same packet data but not structure. The new
1493 * buffer has a reference count of 1. If the allocation fails the
1494 * function returns %NULL otherwise the new buffer is returned.
1496 * If this function is called from an interrupt gfp_mask() must be
1500 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1502 struct sk_buff_fclones *fclones = container_of(skb,
1503 struct sk_buff_fclones,
1507 if (skb_orphan_frags(skb, gfp_mask))
1510 if (skb->fclone == SKB_FCLONE_ORIG &&
1511 refcount_read(&fclones->fclone_ref) == 1) {
1513 refcount_set(&fclones->fclone_ref, 2);
1515 if (skb_pfmemalloc(skb))
1516 gfp_mask |= __GFP_MEMALLOC;
1518 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1522 n->fclone = SKB_FCLONE_UNAVAILABLE;
1525 return __skb_clone(n, skb);
1527 EXPORT_SYMBOL(skb_clone);
1529 void skb_headers_offset_update(struct sk_buff *skb, int off)
1531 /* Only adjust this if it actually is csum_start rather than csum */
1532 if (skb->ip_summed == CHECKSUM_PARTIAL)
1533 skb->csum_start += off;
1534 /* {transport,network,mac}_header and tail are relative to skb->head */
1535 skb->transport_header += off;
1536 skb->network_header += off;
1537 if (skb_mac_header_was_set(skb))
1538 skb->mac_header += off;
1539 skb->inner_transport_header += off;
1540 skb->inner_network_header += off;
1541 skb->inner_mac_header += off;
1543 EXPORT_SYMBOL(skb_headers_offset_update);
1545 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1547 __copy_skb_header(new, old);
1549 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1550 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1551 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1553 EXPORT_SYMBOL(skb_copy_header);
1555 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1557 if (skb_pfmemalloc(skb))
1558 return SKB_ALLOC_RX;
1563 * skb_copy - create private copy of an sk_buff
1564 * @skb: buffer to copy
1565 * @gfp_mask: allocation priority
1567 * Make a copy of both an &sk_buff and its data. This is used when the
1568 * caller wishes to modify the data and needs a private copy of the
1569 * data to alter. Returns %NULL on failure or the pointer to the buffer
1570 * on success. The returned buffer has a reference count of 1.
1572 * As by-product this function converts non-linear &sk_buff to linear
1573 * one, so that &sk_buff becomes completely private and caller is allowed
1574 * to modify all the data of returned buffer. This means that this
1575 * function is not recommended for use in circumstances when only
1576 * header is going to be modified. Use pskb_copy() instead.
1579 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1581 int headerlen = skb_headroom(skb);
1582 unsigned int size = skb_end_offset(skb) + skb->data_len;
1583 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1584 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1589 /* Set the data pointer */
1590 skb_reserve(n, headerlen);
1591 /* Set the tail pointer and length */
1592 skb_put(n, skb->len);
1594 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1596 skb_copy_header(n, skb);
1599 EXPORT_SYMBOL(skb_copy);
1602 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1603 * @skb: buffer to copy
1604 * @headroom: headroom of new skb
1605 * @gfp_mask: allocation priority
1606 * @fclone: if true allocate the copy of the skb from the fclone
1607 * cache instead of the head cache; it is recommended to set this
1608 * to true for the cases where the copy will likely be cloned
1610 * Make a copy of both an &sk_buff and part of its data, located
1611 * in header. Fragmented data remain shared. This is used when
1612 * the caller wishes to modify only header of &sk_buff and needs
1613 * private copy of the header to alter. Returns %NULL on failure
1614 * or the pointer to the buffer on success.
1615 * The returned buffer has a reference count of 1.
1618 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1619 gfp_t gfp_mask, bool fclone)
1621 unsigned int size = skb_headlen(skb) + headroom;
1622 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1623 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1628 /* Set the data pointer */
1629 skb_reserve(n, headroom);
1630 /* Set the tail pointer and length */
1631 skb_put(n, skb_headlen(skb));
1632 /* Copy the bytes */
1633 skb_copy_from_linear_data(skb, n->data, n->len);
1635 n->truesize += skb->data_len;
1636 n->data_len = skb->data_len;
1639 if (skb_shinfo(skb)->nr_frags) {
1642 if (skb_orphan_frags(skb, gfp_mask) ||
1643 skb_zerocopy_clone(n, skb, gfp_mask)) {
1648 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1649 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1650 skb_frag_ref(skb, i);
1652 skb_shinfo(n)->nr_frags = i;
1655 if (skb_has_frag_list(skb)) {
1656 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1657 skb_clone_fraglist(n);
1660 skb_copy_header(n, skb);
1664 EXPORT_SYMBOL(__pskb_copy_fclone);
1667 * pskb_expand_head - reallocate header of &sk_buff
1668 * @skb: buffer to reallocate
1669 * @nhead: room to add at head
1670 * @ntail: room to add at tail
1671 * @gfp_mask: allocation priority
1673 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1674 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1675 * reference count of 1. Returns zero in the case of success or error,
1676 * if expansion failed. In the last case, &sk_buff is not changed.
1678 * All the pointers pointing into skb header may change and must be
1679 * reloaded after call to this function.
1682 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1685 int i, osize = skb_end_offset(skb);
1686 int size = osize + nhead + ntail;
1692 BUG_ON(skb_shared(skb));
1694 size = SKB_DATA_ALIGN(size);
1696 if (skb_pfmemalloc(skb))
1697 gfp_mask |= __GFP_MEMALLOC;
1698 data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1699 gfp_mask, NUMA_NO_NODE, NULL);
1702 size = SKB_WITH_OVERHEAD(ksize(data));
1704 /* Copy only real data... and, alas, header. This should be
1705 * optimized for the cases when header is void.
1707 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1709 memcpy((struct skb_shared_info *)(data + size),
1711 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1714 * if shinfo is shared we must drop the old head gracefully, but if it
1715 * is not we can just drop the old head and let the existing refcount
1716 * be since all we did is relocate the values
1718 if (skb_cloned(skb)) {
1719 if (skb_orphan_frags(skb, gfp_mask))
1722 refcount_inc(&skb_uarg(skb)->refcnt);
1723 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1724 skb_frag_ref(skb, i);
1726 if (skb_has_frag_list(skb))
1727 skb_clone_fraglist(skb);
1729 skb_release_data(skb);
1733 off = (data + nhead) - skb->head;
1739 skb_set_end_offset(skb, size);
1740 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1744 skb_headers_offset_update(skb, nhead);
1748 atomic_set(&skb_shinfo(skb)->dataref, 1);
1750 skb_metadata_clear(skb);
1752 /* It is not generally safe to change skb->truesize.
1753 * For the moment, we really care of rx path, or
1754 * when skb is orphaned (not attached to a socket).
1756 if (!skb->sk || skb->destructor == sock_edemux)
1757 skb->truesize += size - osize;
1766 EXPORT_SYMBOL(pskb_expand_head);
1768 /* Make private copy of skb with writable head and some headroom */
1770 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1772 struct sk_buff *skb2;
1773 int delta = headroom - skb_headroom(skb);
1776 skb2 = pskb_copy(skb, GFP_ATOMIC);
1778 skb2 = skb_clone(skb, GFP_ATOMIC);
1779 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1787 EXPORT_SYMBOL(skb_realloc_headroom);
1789 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1791 unsigned int saved_end_offset, saved_truesize;
1792 struct skb_shared_info *shinfo;
1795 saved_end_offset = skb_end_offset(skb);
1796 saved_truesize = skb->truesize;
1798 res = pskb_expand_head(skb, 0, 0, pri);
1802 skb->truesize = saved_truesize;
1804 if (likely(skb_end_offset(skb) == saved_end_offset))
1807 shinfo = skb_shinfo(skb);
1809 /* We are about to change back skb->end,
1810 * we need to move skb_shinfo() to its new location.
1812 memmove(skb->head + saved_end_offset,
1814 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1816 skb_set_end_offset(skb, saved_end_offset);
1822 * skb_expand_head - reallocate header of &sk_buff
1823 * @skb: buffer to reallocate
1824 * @headroom: needed headroom
1826 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1827 * if possible; copies skb->sk to new skb as needed
1828 * and frees original skb in case of failures.
1830 * It expect increased headroom and generates warning otherwise.
1833 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1835 int delta = headroom - skb_headroom(skb);
1836 int osize = skb_end_offset(skb);
1837 struct sock *sk = skb->sk;
1839 if (WARN_ONCE(delta <= 0,
1840 "%s is expecting an increase in the headroom", __func__))
1843 delta = SKB_DATA_ALIGN(delta);
1844 /* pskb_expand_head() might crash, if skb is shared. */
1845 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1846 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1848 if (unlikely(!nskb))
1852 skb_set_owner_w(nskb, sk);
1856 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
1859 if (sk && is_skb_wmem(skb)) {
1860 delta = skb_end_offset(skb) - osize;
1861 refcount_add(delta, &sk->sk_wmem_alloc);
1862 skb->truesize += delta;
1870 EXPORT_SYMBOL(skb_expand_head);
1873 * skb_copy_expand - copy and expand sk_buff
1874 * @skb: buffer to copy
1875 * @newheadroom: new free bytes at head
1876 * @newtailroom: new free bytes at tail
1877 * @gfp_mask: allocation priority
1879 * Make a copy of both an &sk_buff and its data and while doing so
1880 * allocate additional space.
1882 * This is used when the caller wishes to modify the data and needs a
1883 * private copy of the data to alter as well as more space for new fields.
1884 * Returns %NULL on failure or the pointer to the buffer
1885 * on success. The returned buffer has a reference count of 1.
1887 * You must pass %GFP_ATOMIC as the allocation priority if this function
1888 * is called from an interrupt.
1890 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1891 int newheadroom, int newtailroom,
1895 * Allocate the copy buffer
1897 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1898 gfp_mask, skb_alloc_rx_flag(skb),
1900 int oldheadroom = skb_headroom(skb);
1901 int head_copy_len, head_copy_off;
1906 skb_reserve(n, newheadroom);
1908 /* Set the tail pointer and length */
1909 skb_put(n, skb->len);
1911 head_copy_len = oldheadroom;
1913 if (newheadroom <= head_copy_len)
1914 head_copy_len = newheadroom;
1916 head_copy_off = newheadroom - head_copy_len;
1918 /* Copy the linear header and data. */
1919 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1920 skb->len + head_copy_len));
1922 skb_copy_header(n, skb);
1924 skb_headers_offset_update(n, newheadroom - oldheadroom);
1928 EXPORT_SYMBOL(skb_copy_expand);
1931 * __skb_pad - zero pad the tail of an skb
1932 * @skb: buffer to pad
1933 * @pad: space to pad
1934 * @free_on_error: free buffer on error
1936 * Ensure that a buffer is followed by a padding area that is zero
1937 * filled. Used by network drivers which may DMA or transfer data
1938 * beyond the buffer end onto the wire.
1940 * May return error in out of memory cases. The skb is freed on error
1941 * if @free_on_error is true.
1944 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
1949 /* If the skbuff is non linear tailroom is always zero.. */
1950 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1951 memset(skb->data+skb->len, 0, pad);
1955 ntail = skb->data_len + pad - (skb->end - skb->tail);
1956 if (likely(skb_cloned(skb) || ntail > 0)) {
1957 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1962 /* FIXME: The use of this function with non-linear skb's really needs
1965 err = skb_linearize(skb);
1969 memset(skb->data + skb->len, 0, pad);
1977 EXPORT_SYMBOL(__skb_pad);
1980 * pskb_put - add data to the tail of a potentially fragmented buffer
1981 * @skb: start of the buffer to use
1982 * @tail: tail fragment of the buffer to use
1983 * @len: amount of data to add
1985 * This function extends the used data area of the potentially
1986 * fragmented buffer. @tail must be the last fragment of @skb -- or
1987 * @skb itself. If this would exceed the total buffer size the kernel
1988 * will panic. A pointer to the first byte of the extra data is
1992 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
1995 skb->data_len += len;
1998 return skb_put(tail, len);
2000 EXPORT_SYMBOL_GPL(pskb_put);
2003 * skb_put - add data to a buffer
2004 * @skb: buffer to use
2005 * @len: amount of data to add
2007 * This function extends the used data area of the buffer. If this would
2008 * exceed the total buffer size the kernel will panic. A pointer to the
2009 * first byte of the extra data is returned.
2011 void *skb_put(struct sk_buff *skb, unsigned int len)
2013 void *tmp = skb_tail_pointer(skb);
2014 SKB_LINEAR_ASSERT(skb);
2017 if (unlikely(skb->tail > skb->end))
2018 skb_over_panic(skb, len, __builtin_return_address(0));
2021 EXPORT_SYMBOL(skb_put);
2024 * skb_push - add data to the start of a buffer
2025 * @skb: buffer to use
2026 * @len: amount of data to add
2028 * This function extends the used data area of the buffer at the buffer
2029 * start. If this would exceed the total buffer headroom the kernel will
2030 * panic. A pointer to the first byte of the extra data is returned.
2032 void *skb_push(struct sk_buff *skb, unsigned int len)
2036 if (unlikely(skb->data < skb->head))
2037 skb_under_panic(skb, len, __builtin_return_address(0));
2040 EXPORT_SYMBOL(skb_push);
2043 * skb_pull - remove data from the start of a buffer
2044 * @skb: buffer to use
2045 * @len: amount of data to remove
2047 * This function removes data from the start of a buffer, returning
2048 * the memory to the headroom. A pointer to the next data in the buffer
2049 * is returned. Once the data has been pulled future pushes will overwrite
2052 void *skb_pull(struct sk_buff *skb, unsigned int len)
2054 return skb_pull_inline(skb, len);
2056 EXPORT_SYMBOL(skb_pull);
2059 * skb_pull_data - remove data from the start of a buffer returning its
2060 * original position.
2061 * @skb: buffer to use
2062 * @len: amount of data to remove
2064 * This function removes data from the start of a buffer, returning
2065 * the memory to the headroom. A pointer to the original data in the buffer
2066 * is returned after checking if there is enough data to pull. Once the
2067 * data has been pulled future pushes will overwrite the old data.
2069 void *skb_pull_data(struct sk_buff *skb, size_t len)
2071 void *data = skb->data;
2080 EXPORT_SYMBOL(skb_pull_data);
2083 * skb_trim - remove end from a buffer
2084 * @skb: buffer to alter
2087 * Cut the length of a buffer down by removing data from the tail. If
2088 * the buffer is already under the length specified it is not modified.
2089 * The skb must be linear.
2091 void skb_trim(struct sk_buff *skb, unsigned int len)
2094 __skb_trim(skb, len);
2096 EXPORT_SYMBOL(skb_trim);
2098 /* Trims skb to length len. It can change skb pointers.
2101 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2103 struct sk_buff **fragp;
2104 struct sk_buff *frag;
2105 int offset = skb_headlen(skb);
2106 int nfrags = skb_shinfo(skb)->nr_frags;
2110 if (skb_cloned(skb) &&
2111 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2118 for (; i < nfrags; i++) {
2119 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2126 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2129 skb_shinfo(skb)->nr_frags = i;
2131 for (; i < nfrags; i++)
2132 skb_frag_unref(skb, i);
2134 if (skb_has_frag_list(skb))
2135 skb_drop_fraglist(skb);
2139 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2140 fragp = &frag->next) {
2141 int end = offset + frag->len;
2143 if (skb_shared(frag)) {
2144 struct sk_buff *nfrag;
2146 nfrag = skb_clone(frag, GFP_ATOMIC);
2147 if (unlikely(!nfrag))
2150 nfrag->next = frag->next;
2162 unlikely((err = pskb_trim(frag, len - offset))))
2166 skb_drop_list(&frag->next);
2171 if (len > skb_headlen(skb)) {
2172 skb->data_len -= skb->len - len;
2177 skb_set_tail_pointer(skb, len);
2180 if (!skb->sk || skb->destructor == sock_edemux)
2184 EXPORT_SYMBOL(___pskb_trim);
2186 /* Note : use pskb_trim_rcsum() instead of calling this directly
2188 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2190 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2191 int delta = skb->len - len;
2193 skb->csum = csum_block_sub(skb->csum,
2194 skb_checksum(skb, len, delta, 0),
2196 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2197 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2198 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2200 if (offset + sizeof(__sum16) > hdlen)
2203 return __pskb_trim(skb, len);
2205 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2208 * __pskb_pull_tail - advance tail of skb header
2209 * @skb: buffer to reallocate
2210 * @delta: number of bytes to advance tail
2212 * The function makes a sense only on a fragmented &sk_buff,
2213 * it expands header moving its tail forward and copying necessary
2214 * data from fragmented part.
2216 * &sk_buff MUST have reference count of 1.
2218 * Returns %NULL (and &sk_buff does not change) if pull failed
2219 * or value of new tail of skb in the case of success.
2221 * All the pointers pointing into skb header may change and must be
2222 * reloaded after call to this function.
2225 /* Moves tail of skb head forward, copying data from fragmented part,
2226 * when it is necessary.
2227 * 1. It may fail due to malloc failure.
2228 * 2. It may change skb pointers.
2230 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2232 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2234 /* If skb has not enough free space at tail, get new one
2235 * plus 128 bytes for future expansions. If we have enough
2236 * room at tail, reallocate without expansion only if skb is cloned.
2238 int i, k, eat = (skb->tail + delta) - skb->end;
2240 if (eat > 0 || skb_cloned(skb)) {
2241 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2246 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2247 skb_tail_pointer(skb), delta));
2249 /* Optimization: no fragments, no reasons to preestimate
2250 * size of pulled pages. Superb.
2252 if (!skb_has_frag_list(skb))
2255 /* Estimate size of pulled pages. */
2257 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2258 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2265 /* If we need update frag list, we are in troubles.
2266 * Certainly, it is possible to add an offset to skb data,
2267 * but taking into account that pulling is expected to
2268 * be very rare operation, it is worth to fight against
2269 * further bloating skb head and crucify ourselves here instead.
2270 * Pure masohism, indeed. 8)8)
2273 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2274 struct sk_buff *clone = NULL;
2275 struct sk_buff *insp = NULL;
2278 if (list->len <= eat) {
2279 /* Eaten as whole. */
2284 /* Eaten partially. */
2286 if (skb_shared(list)) {
2287 /* Sucks! We need to fork list. :-( */
2288 clone = skb_clone(list, GFP_ATOMIC);
2294 /* This may be pulled without
2298 if (!pskb_pull(list, eat)) {
2306 /* Free pulled out fragments. */
2307 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2308 skb_shinfo(skb)->frag_list = list->next;
2311 /* And insert new clone at head. */
2314 skb_shinfo(skb)->frag_list = clone;
2317 /* Success! Now we may commit changes to skb data. */
2322 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2323 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2326 skb_frag_unref(skb, i);
2329 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2331 *frag = skb_shinfo(skb)->frags[i];
2333 skb_frag_off_add(frag, eat);
2334 skb_frag_size_sub(frag, eat);
2342 skb_shinfo(skb)->nr_frags = k;
2346 skb->data_len -= delta;
2349 skb_zcopy_clear(skb, false);
2351 return skb_tail_pointer(skb);
2353 EXPORT_SYMBOL(__pskb_pull_tail);
2356 * skb_copy_bits - copy bits from skb to kernel buffer
2358 * @offset: offset in source
2359 * @to: destination buffer
2360 * @len: number of bytes to copy
2362 * Copy the specified number of bytes from the source skb to the
2363 * destination buffer.
2366 * If its prototype is ever changed,
2367 * check arch/{*}/net/{*}.S files,
2368 * since it is called from BPF assembly code.
2370 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2372 int start = skb_headlen(skb);
2373 struct sk_buff *frag_iter;
2376 if (offset > (int)skb->len - len)
2380 if ((copy = start - offset) > 0) {
2383 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2384 if ((len -= copy) == 0)
2390 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2392 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2394 WARN_ON(start > offset + len);
2396 end = start + skb_frag_size(f);
2397 if ((copy = end - offset) > 0) {
2398 u32 p_off, p_len, copied;
2405 skb_frag_foreach_page(f,
2406 skb_frag_off(f) + offset - start,
2407 copy, p, p_off, p_len, copied) {
2408 vaddr = kmap_atomic(p);
2409 memcpy(to + copied, vaddr + p_off, p_len);
2410 kunmap_atomic(vaddr);
2413 if ((len -= copy) == 0)
2421 skb_walk_frags(skb, frag_iter) {
2424 WARN_ON(start > offset + len);
2426 end = start + frag_iter->len;
2427 if ((copy = end - offset) > 0) {
2430 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2432 if ((len -= copy) == 0)
2446 EXPORT_SYMBOL(skb_copy_bits);
2449 * Callback from splice_to_pipe(), if we need to release some pages
2450 * at the end of the spd in case we error'ed out in filling the pipe.
2452 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2454 put_page(spd->pages[i]);
2457 static struct page *linear_to_page(struct page *page, unsigned int *len,
2458 unsigned int *offset,
2461 struct page_frag *pfrag = sk_page_frag(sk);
2463 if (!sk_page_frag_refill(sk, pfrag))
2466 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2468 memcpy(page_address(pfrag->page) + pfrag->offset,
2469 page_address(page) + *offset, *len);
2470 *offset = pfrag->offset;
2471 pfrag->offset += *len;
2476 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2478 unsigned int offset)
2480 return spd->nr_pages &&
2481 spd->pages[spd->nr_pages - 1] == page &&
2482 (spd->partial[spd->nr_pages - 1].offset +
2483 spd->partial[spd->nr_pages - 1].len == offset);
2487 * Fill page/offset/length into spd, if it can hold more pages.
2489 static bool spd_fill_page(struct splice_pipe_desc *spd,
2490 struct pipe_inode_info *pipe, struct page *page,
2491 unsigned int *len, unsigned int offset,
2495 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2499 page = linear_to_page(page, len, &offset, sk);
2503 if (spd_can_coalesce(spd, page, offset)) {
2504 spd->partial[spd->nr_pages - 1].len += *len;
2508 spd->pages[spd->nr_pages] = page;
2509 spd->partial[spd->nr_pages].len = *len;
2510 spd->partial[spd->nr_pages].offset = offset;
2516 static bool __splice_segment(struct page *page, unsigned int poff,
2517 unsigned int plen, unsigned int *off,
2519 struct splice_pipe_desc *spd, bool linear,
2521 struct pipe_inode_info *pipe)
2526 /* skip this segment if already processed */
2532 /* ignore any bits we already processed */
2538 unsigned int flen = min(*len, plen);
2540 if (spd_fill_page(spd, pipe, page, &flen, poff,
2546 } while (*len && plen);
2552 * Map linear and fragment data from the skb to spd. It reports true if the
2553 * pipe is full or if we already spliced the requested length.
2555 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2556 unsigned int *offset, unsigned int *len,
2557 struct splice_pipe_desc *spd, struct sock *sk)
2560 struct sk_buff *iter;
2562 /* map the linear part :
2563 * If skb->head_frag is set, this 'linear' part is backed by a
2564 * fragment, and if the head is not shared with any clones then
2565 * we can avoid a copy since we own the head portion of this page.
2567 if (__splice_segment(virt_to_page(skb->data),
2568 (unsigned long) skb->data & (PAGE_SIZE - 1),
2571 skb_head_is_locked(skb),
2576 * then map the fragments
2578 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2579 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2581 if (__splice_segment(skb_frag_page(f),
2582 skb_frag_off(f), skb_frag_size(f),
2583 offset, len, spd, false, sk, pipe))
2587 skb_walk_frags(skb, iter) {
2588 if (*offset >= iter->len) {
2589 *offset -= iter->len;
2592 /* __skb_splice_bits() only fails if the output has no room
2593 * left, so no point in going over the frag_list for the error
2596 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2604 * Map data from the skb to a pipe. Should handle both the linear part,
2605 * the fragments, and the frag list.
2607 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2608 struct pipe_inode_info *pipe, unsigned int tlen,
2611 struct partial_page partial[MAX_SKB_FRAGS];
2612 struct page *pages[MAX_SKB_FRAGS];
2613 struct splice_pipe_desc spd = {
2616 .nr_pages_max = MAX_SKB_FRAGS,
2617 .ops = &nosteal_pipe_buf_ops,
2618 .spd_release = sock_spd_release,
2622 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2625 ret = splice_to_pipe(pipe, &spd);
2629 EXPORT_SYMBOL_GPL(skb_splice_bits);
2631 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2632 struct kvec *vec, size_t num, size_t size)
2634 struct socket *sock = sk->sk_socket;
2638 return kernel_sendmsg(sock, msg, vec, num, size);
2641 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2642 size_t size, int flags)
2644 struct socket *sock = sk->sk_socket;
2648 return kernel_sendpage(sock, page, offset, size, flags);
2651 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2652 struct kvec *vec, size_t num, size_t size);
2653 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2654 size_t size, int flags);
2655 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2656 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2658 unsigned int orig_len = len;
2659 struct sk_buff *head = skb;
2660 unsigned short fragidx;
2665 /* Deal with head data */
2666 while (offset < skb_headlen(skb) && len) {
2670 slen = min_t(int, len, skb_headlen(skb) - offset);
2671 kv.iov_base = skb->data + offset;
2673 memset(&msg, 0, sizeof(msg));
2674 msg.msg_flags = MSG_DONTWAIT;
2676 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2677 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2685 /* All the data was skb head? */
2689 /* Make offset relative to start of frags */
2690 offset -= skb_headlen(skb);
2692 /* Find where we are in frag list */
2693 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2694 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2696 if (offset < skb_frag_size(frag))
2699 offset -= skb_frag_size(frag);
2702 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2703 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2705 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2708 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2709 sendpage_unlocked, sk,
2710 skb_frag_page(frag),
2711 skb_frag_off(frag) + offset,
2712 slen, MSG_DONTWAIT);
2725 /* Process any frag lists */
2728 if (skb_has_frag_list(skb)) {
2729 skb = skb_shinfo(skb)->frag_list;
2732 } else if (skb->next) {
2739 return orig_len - len;
2742 return orig_len == len ? ret : orig_len - len;
2745 /* Send skb data on a socket. Socket must be locked. */
2746 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2749 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2750 kernel_sendpage_locked);
2752 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2754 /* Send skb data on a socket. Socket must be unlocked. */
2755 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2757 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2762 * skb_store_bits - store bits from kernel buffer to skb
2763 * @skb: destination buffer
2764 * @offset: offset in destination
2765 * @from: source buffer
2766 * @len: number of bytes to copy
2768 * Copy the specified number of bytes from the source buffer to the
2769 * destination skb. This function handles all the messy bits of
2770 * traversing fragment lists and such.
2773 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2775 int start = skb_headlen(skb);
2776 struct sk_buff *frag_iter;
2779 if (offset > (int)skb->len - len)
2782 if ((copy = start - offset) > 0) {
2785 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2786 if ((len -= copy) == 0)
2792 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2793 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2796 WARN_ON(start > offset + len);
2798 end = start + skb_frag_size(frag);
2799 if ((copy = end - offset) > 0) {
2800 u32 p_off, p_len, copied;
2807 skb_frag_foreach_page(frag,
2808 skb_frag_off(frag) + offset - start,
2809 copy, p, p_off, p_len, copied) {
2810 vaddr = kmap_atomic(p);
2811 memcpy(vaddr + p_off, from + copied, p_len);
2812 kunmap_atomic(vaddr);
2815 if ((len -= copy) == 0)
2823 skb_walk_frags(skb, frag_iter) {
2826 WARN_ON(start > offset + len);
2828 end = start + frag_iter->len;
2829 if ((copy = end - offset) > 0) {
2832 if (skb_store_bits(frag_iter, offset - start,
2835 if ((len -= copy) == 0)
2848 EXPORT_SYMBOL(skb_store_bits);
2850 /* Checksum skb data. */
2851 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2852 __wsum csum, const struct skb_checksum_ops *ops)
2854 int start = skb_headlen(skb);
2855 int i, copy = start - offset;
2856 struct sk_buff *frag_iter;
2859 /* Checksum header. */
2863 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
2864 skb->data + offset, copy, csum);
2865 if ((len -= copy) == 0)
2871 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2873 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2875 WARN_ON(start > offset + len);
2877 end = start + skb_frag_size(frag);
2878 if ((copy = end - offset) > 0) {
2879 u32 p_off, p_len, copied;
2887 skb_frag_foreach_page(frag,
2888 skb_frag_off(frag) + offset - start,
2889 copy, p, p_off, p_len, copied) {
2890 vaddr = kmap_atomic(p);
2891 csum2 = INDIRECT_CALL_1(ops->update,
2893 vaddr + p_off, p_len, 0);
2894 kunmap_atomic(vaddr);
2895 csum = INDIRECT_CALL_1(ops->combine,
2896 csum_block_add_ext, csum,
2908 skb_walk_frags(skb, frag_iter) {
2911 WARN_ON(start > offset + len);
2913 end = start + frag_iter->len;
2914 if ((copy = end - offset) > 0) {
2918 csum2 = __skb_checksum(frag_iter, offset - start,
2920 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
2921 csum, csum2, pos, copy);
2922 if ((len -= copy) == 0)
2933 EXPORT_SYMBOL(__skb_checksum);
2935 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2936 int len, __wsum csum)
2938 const struct skb_checksum_ops ops = {
2939 .update = csum_partial_ext,
2940 .combine = csum_block_add_ext,
2943 return __skb_checksum(skb, offset, len, csum, &ops);
2945 EXPORT_SYMBOL(skb_checksum);
2947 /* Both of above in one bottle. */
2949 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2952 int start = skb_headlen(skb);
2953 int i, copy = start - offset;
2954 struct sk_buff *frag_iter;
2962 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2964 if ((len -= copy) == 0)
2971 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2974 WARN_ON(start > offset + len);
2976 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2977 if ((copy = end - offset) > 0) {
2978 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2979 u32 p_off, p_len, copied;
2987 skb_frag_foreach_page(frag,
2988 skb_frag_off(frag) + offset - start,
2989 copy, p, p_off, p_len, copied) {
2990 vaddr = kmap_atomic(p);
2991 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
2994 kunmap_atomic(vaddr);
2995 csum = csum_block_add(csum, csum2, pos);
3007 skb_walk_frags(skb, frag_iter) {
3011 WARN_ON(start > offset + len);
3013 end = start + frag_iter->len;
3014 if ((copy = end - offset) > 0) {
3017 csum2 = skb_copy_and_csum_bits(frag_iter,
3020 csum = csum_block_add(csum, csum2, pos);
3021 if ((len -= copy) == 0)
3032 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3034 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3038 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3039 /* See comments in __skb_checksum_complete(). */
3041 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3042 !skb->csum_complete_sw)
3043 netdev_rx_csum_fault(skb->dev, skb);
3045 if (!skb_shared(skb))
3046 skb->csum_valid = !sum;
3049 EXPORT_SYMBOL(__skb_checksum_complete_head);
3051 /* This function assumes skb->csum already holds pseudo header's checksum,
3052 * which has been changed from the hardware checksum, for example, by
3053 * __skb_checksum_validate_complete(). And, the original skb->csum must
3054 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3056 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3057 * zero. The new checksum is stored back into skb->csum unless the skb is
3060 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3065 csum = skb_checksum(skb, 0, skb->len, 0);
3067 sum = csum_fold(csum_add(skb->csum, csum));
3068 /* This check is inverted, because we already knew the hardware
3069 * checksum is invalid before calling this function. So, if the
3070 * re-computed checksum is valid instead, then we have a mismatch
3071 * between the original skb->csum and skb_checksum(). This means either
3072 * the original hardware checksum is incorrect or we screw up skb->csum
3073 * when moving skb->data around.
3076 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3077 !skb->csum_complete_sw)
3078 netdev_rx_csum_fault(skb->dev, skb);
3081 if (!skb_shared(skb)) {
3082 /* Save full packet checksum */
3084 skb->ip_summed = CHECKSUM_COMPLETE;
3085 skb->csum_complete_sw = 1;
3086 skb->csum_valid = !sum;
3091 EXPORT_SYMBOL(__skb_checksum_complete);
3093 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3095 net_warn_ratelimited(
3096 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3101 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3102 int offset, int len)
3104 net_warn_ratelimited(
3105 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3110 static const struct skb_checksum_ops default_crc32c_ops = {
3111 .update = warn_crc32c_csum_update,
3112 .combine = warn_crc32c_csum_combine,
3115 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3116 &default_crc32c_ops;
3117 EXPORT_SYMBOL(crc32c_csum_stub);
3120 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3121 * @from: source buffer
3123 * Calculates the amount of linear headroom needed in the 'to' skb passed
3124 * into skb_zerocopy().
3127 skb_zerocopy_headlen(const struct sk_buff *from)
3129 unsigned int hlen = 0;
3131 if (!from->head_frag ||
3132 skb_headlen(from) < L1_CACHE_BYTES ||
3133 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3134 hlen = skb_headlen(from);
3139 if (skb_has_frag_list(from))
3144 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3147 * skb_zerocopy - Zero copy skb to skb
3148 * @to: destination buffer
3149 * @from: source buffer
3150 * @len: number of bytes to copy from source buffer
3151 * @hlen: size of linear headroom in destination buffer
3153 * Copies up to `len` bytes from `from` to `to` by creating references
3154 * to the frags in the source buffer.
3156 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3157 * headroom in the `to` buffer.
3160 * 0: everything is OK
3161 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3162 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3165 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3168 int plen = 0; /* length of skb->head fragment */
3171 unsigned int offset;
3173 BUG_ON(!from->head_frag && !hlen);
3175 /* dont bother with small payloads */
3176 if (len <= skb_tailroom(to))
3177 return skb_copy_bits(from, 0, skb_put(to, len), len);
3180 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3185 plen = min_t(int, skb_headlen(from), len);
3187 page = virt_to_head_page(from->head);
3188 offset = from->data - (unsigned char *)page_address(page);
3189 __skb_fill_page_desc(to, 0, page, offset, plen);
3196 to->truesize += len + plen;
3197 to->len += len + plen;
3198 to->data_len += len + plen;
3200 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3204 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3206 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3211 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3212 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3214 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3216 skb_frag_ref(to, j);
3219 skb_shinfo(to)->nr_frags = j;
3223 EXPORT_SYMBOL_GPL(skb_zerocopy);
3225 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3230 if (skb->ip_summed == CHECKSUM_PARTIAL)
3231 csstart = skb_checksum_start_offset(skb);
3233 csstart = skb_headlen(skb);
3235 BUG_ON(csstart > skb_headlen(skb));
3237 skb_copy_from_linear_data(skb, to, csstart);
3240 if (csstart != skb->len)
3241 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3242 skb->len - csstart);
3244 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3245 long csstuff = csstart + skb->csum_offset;
3247 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3250 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3253 * skb_dequeue - remove from the head of the queue
3254 * @list: list to dequeue from
3256 * Remove the head of the list. The list lock is taken so the function
3257 * may be used safely with other locking list functions. The head item is
3258 * returned or %NULL if the list is empty.
3261 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3263 unsigned long flags;
3264 struct sk_buff *result;
3266 spin_lock_irqsave(&list->lock, flags);
3267 result = __skb_dequeue(list);
3268 spin_unlock_irqrestore(&list->lock, flags);
3271 EXPORT_SYMBOL(skb_dequeue);
3274 * skb_dequeue_tail - remove from the tail of the queue
3275 * @list: list to dequeue from
3277 * Remove the tail of the list. The list lock is taken so the function
3278 * may be used safely with other locking list functions. The tail item is
3279 * returned or %NULL if the list is empty.
3281 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3283 unsigned long flags;
3284 struct sk_buff *result;
3286 spin_lock_irqsave(&list->lock, flags);
3287 result = __skb_dequeue_tail(list);
3288 spin_unlock_irqrestore(&list->lock, flags);
3291 EXPORT_SYMBOL(skb_dequeue_tail);
3294 * skb_queue_purge - empty a list
3295 * @list: list to empty
3297 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3298 * the list and one reference dropped. This function takes the list
3299 * lock and is atomic with respect to other list locking functions.
3301 void skb_queue_purge(struct sk_buff_head *list)
3303 struct sk_buff *skb;
3304 while ((skb = skb_dequeue(list)) != NULL)
3307 EXPORT_SYMBOL(skb_queue_purge);
3310 * skb_rbtree_purge - empty a skb rbtree
3311 * @root: root of the rbtree to empty
3312 * Return value: the sum of truesizes of all purged skbs.
3314 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3315 * the list and one reference dropped. This function does not take
3316 * any lock. Synchronization should be handled by the caller (e.g., TCP
3317 * out-of-order queue is protected by the socket lock).
3319 unsigned int skb_rbtree_purge(struct rb_root *root)
3321 struct rb_node *p = rb_first(root);
3322 unsigned int sum = 0;
3325 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3328 rb_erase(&skb->rbnode, root);
3329 sum += skb->truesize;
3336 * skb_queue_head - queue a buffer at the list head
3337 * @list: list to use
3338 * @newsk: buffer to queue
3340 * Queue a buffer at the start of the list. This function takes the
3341 * list lock and can be used safely with other locking &sk_buff functions
3344 * A buffer cannot be placed on two lists at the same time.
3346 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3348 unsigned long flags;
3350 spin_lock_irqsave(&list->lock, flags);
3351 __skb_queue_head(list, newsk);
3352 spin_unlock_irqrestore(&list->lock, flags);
3354 EXPORT_SYMBOL(skb_queue_head);
3357 * skb_queue_tail - queue a buffer at the list tail
3358 * @list: list to use
3359 * @newsk: buffer to queue
3361 * Queue a buffer at the tail of the list. This function takes the
3362 * list lock and can be used safely with other locking &sk_buff functions
3365 * A buffer cannot be placed on two lists at the same time.
3367 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3369 unsigned long flags;
3371 spin_lock_irqsave(&list->lock, flags);
3372 __skb_queue_tail(list, newsk);
3373 spin_unlock_irqrestore(&list->lock, flags);
3375 EXPORT_SYMBOL(skb_queue_tail);
3378 * skb_unlink - remove a buffer from a list
3379 * @skb: buffer to remove
3380 * @list: list to use
3382 * Remove a packet from a list. The list locks are taken and this
3383 * function is atomic with respect to other list locked calls
3385 * You must know what list the SKB is on.
3387 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3389 unsigned long flags;
3391 spin_lock_irqsave(&list->lock, flags);
3392 __skb_unlink(skb, list);
3393 spin_unlock_irqrestore(&list->lock, flags);
3395 EXPORT_SYMBOL(skb_unlink);
3398 * skb_append - append a buffer
3399 * @old: buffer to insert after
3400 * @newsk: buffer to insert
3401 * @list: list to use
3403 * Place a packet after a given packet in a list. The list locks are taken
3404 * and this function is atomic with respect to other list locked calls.
3405 * A buffer cannot be placed on two lists at the same time.
3407 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3409 unsigned long flags;
3411 spin_lock_irqsave(&list->lock, flags);
3412 __skb_queue_after(list, old, newsk);
3413 spin_unlock_irqrestore(&list->lock, flags);
3415 EXPORT_SYMBOL(skb_append);
3417 static inline void skb_split_inside_header(struct sk_buff *skb,
3418 struct sk_buff* skb1,
3419 const u32 len, const int pos)
3423 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3425 /* And move data appendix as is. */
3426 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3427 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3429 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3430 skb_shinfo(skb)->nr_frags = 0;
3431 skb1->data_len = skb->data_len;
3432 skb1->len += skb1->data_len;
3435 skb_set_tail_pointer(skb, len);
3438 static inline void skb_split_no_header(struct sk_buff *skb,
3439 struct sk_buff* skb1,
3440 const u32 len, int pos)
3443 const int nfrags = skb_shinfo(skb)->nr_frags;
3445 skb_shinfo(skb)->nr_frags = 0;
3446 skb1->len = skb1->data_len = skb->len - len;
3448 skb->data_len = len - pos;
3450 for (i = 0; i < nfrags; i++) {
3451 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3453 if (pos + size > len) {
3454 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3458 * We have two variants in this case:
3459 * 1. Move all the frag to the second
3460 * part, if it is possible. F.e.
3461 * this approach is mandatory for TUX,
3462 * where splitting is expensive.
3463 * 2. Split is accurately. We make this.
3465 skb_frag_ref(skb, i);
3466 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3467 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3468 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3469 skb_shinfo(skb)->nr_frags++;
3473 skb_shinfo(skb)->nr_frags++;
3476 skb_shinfo(skb1)->nr_frags = k;
3480 * skb_split - Split fragmented skb to two parts at length len.
3481 * @skb: the buffer to split
3482 * @skb1: the buffer to receive the second part
3483 * @len: new length for skb
3485 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3487 int pos = skb_headlen(skb);
3488 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3490 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3491 skb_zerocopy_clone(skb1, skb, 0);
3492 if (len < pos) /* Split line is inside header. */
3493 skb_split_inside_header(skb, skb1, len, pos);
3494 else /* Second chunk has no header, nothing to copy. */
3495 skb_split_no_header(skb, skb1, len, pos);
3497 EXPORT_SYMBOL(skb_split);
3499 /* Shifting from/to a cloned skb is a no-go.
3501 * Caller cannot keep skb_shinfo related pointers past calling here!
3503 static int skb_prepare_for_shift(struct sk_buff *skb)
3505 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3509 * skb_shift - Shifts paged data partially from skb to another
3510 * @tgt: buffer into which tail data gets added
3511 * @skb: buffer from which the paged data comes from
3512 * @shiftlen: shift up to this many bytes
3514 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3515 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3516 * It's up to caller to free skb if everything was shifted.
3518 * If @tgt runs out of frags, the whole operation is aborted.
3520 * Skb cannot include anything else but paged data while tgt is allowed
3521 * to have non-paged data as well.
3523 * TODO: full sized shift could be optimized but that would need
3524 * specialized skb free'er to handle frags without up-to-date nr_frags.
3526 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3528 int from, to, merge, todo;
3529 skb_frag_t *fragfrom, *fragto;
3531 BUG_ON(shiftlen > skb->len);
3533 if (skb_headlen(skb))
3535 if (skb_zcopy(tgt) || skb_zcopy(skb))
3540 to = skb_shinfo(tgt)->nr_frags;
3541 fragfrom = &skb_shinfo(skb)->frags[from];
3543 /* Actual merge is delayed until the point when we know we can
3544 * commit all, so that we don't have to undo partial changes
3547 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3548 skb_frag_off(fragfrom))) {
3553 todo -= skb_frag_size(fragfrom);
3555 if (skb_prepare_for_shift(skb) ||
3556 skb_prepare_for_shift(tgt))
3559 /* All previous frag pointers might be stale! */
3560 fragfrom = &skb_shinfo(skb)->frags[from];
3561 fragto = &skb_shinfo(tgt)->frags[merge];
3563 skb_frag_size_add(fragto, shiftlen);
3564 skb_frag_size_sub(fragfrom, shiftlen);
3565 skb_frag_off_add(fragfrom, shiftlen);
3573 /* Skip full, not-fitting skb to avoid expensive operations */
3574 if ((shiftlen == skb->len) &&
3575 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3578 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3581 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3582 if (to == MAX_SKB_FRAGS)
3585 fragfrom = &skb_shinfo(skb)->frags[from];
3586 fragto = &skb_shinfo(tgt)->frags[to];
3588 if (todo >= skb_frag_size(fragfrom)) {
3589 *fragto = *fragfrom;
3590 todo -= skb_frag_size(fragfrom);
3595 __skb_frag_ref(fragfrom);
3596 skb_frag_page_copy(fragto, fragfrom);
3597 skb_frag_off_copy(fragto, fragfrom);
3598 skb_frag_size_set(fragto, todo);
3600 skb_frag_off_add(fragfrom, todo);
3601 skb_frag_size_sub(fragfrom, todo);
3609 /* Ready to "commit" this state change to tgt */
3610 skb_shinfo(tgt)->nr_frags = to;
3613 fragfrom = &skb_shinfo(skb)->frags[0];
3614 fragto = &skb_shinfo(tgt)->frags[merge];
3616 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3617 __skb_frag_unref(fragfrom, skb->pp_recycle);
3620 /* Reposition in the original skb */
3622 while (from < skb_shinfo(skb)->nr_frags)
3623 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3624 skb_shinfo(skb)->nr_frags = to;
3626 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3629 /* Most likely the tgt won't ever need its checksum anymore, skb on
3630 * the other hand might need it if it needs to be resent
3632 tgt->ip_summed = CHECKSUM_PARTIAL;
3633 skb->ip_summed = CHECKSUM_PARTIAL;
3635 /* Yak, is it really working this way? Some helper please? */
3636 skb->len -= shiftlen;
3637 skb->data_len -= shiftlen;
3638 skb->truesize -= shiftlen;
3639 tgt->len += shiftlen;
3640 tgt->data_len += shiftlen;
3641 tgt->truesize += shiftlen;
3647 * skb_prepare_seq_read - Prepare a sequential read of skb data
3648 * @skb: the buffer to read
3649 * @from: lower offset of data to be read
3650 * @to: upper offset of data to be read
3651 * @st: state variable
3653 * Initializes the specified state variable. Must be called before
3654 * invoking skb_seq_read() for the first time.
3656 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3657 unsigned int to, struct skb_seq_state *st)
3659 st->lower_offset = from;
3660 st->upper_offset = to;
3661 st->root_skb = st->cur_skb = skb;
3662 st->frag_idx = st->stepped_offset = 0;
3663 st->frag_data = NULL;
3666 EXPORT_SYMBOL(skb_prepare_seq_read);
3669 * skb_seq_read - Sequentially read skb data
3670 * @consumed: number of bytes consumed by the caller so far
3671 * @data: destination pointer for data to be returned
3672 * @st: state variable
3674 * Reads a block of skb data at @consumed relative to the
3675 * lower offset specified to skb_prepare_seq_read(). Assigns
3676 * the head of the data block to @data and returns the length
3677 * of the block or 0 if the end of the skb data or the upper
3678 * offset has been reached.
3680 * The caller is not required to consume all of the data
3681 * returned, i.e. @consumed is typically set to the number
3682 * of bytes already consumed and the next call to
3683 * skb_seq_read() will return the remaining part of the block.
3685 * Note 1: The size of each block of data returned can be arbitrary,
3686 * this limitation is the cost for zerocopy sequential
3687 * reads of potentially non linear data.
3689 * Note 2: Fragment lists within fragments are not implemented
3690 * at the moment, state->root_skb could be replaced with
3691 * a stack for this purpose.
3693 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3694 struct skb_seq_state *st)
3696 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3699 if (unlikely(abs_offset >= st->upper_offset)) {
3700 if (st->frag_data) {
3701 kunmap_atomic(st->frag_data);
3702 st->frag_data = NULL;
3708 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3710 if (abs_offset < block_limit && !st->frag_data) {
3711 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3712 return block_limit - abs_offset;
3715 if (st->frag_idx == 0 && !st->frag_data)
3716 st->stepped_offset += skb_headlen(st->cur_skb);
3718 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3719 unsigned int pg_idx, pg_off, pg_sz;
3721 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3724 pg_off = skb_frag_off(frag);
3725 pg_sz = skb_frag_size(frag);
3727 if (skb_frag_must_loop(skb_frag_page(frag))) {
3728 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3729 pg_off = offset_in_page(pg_off + st->frag_off);
3730 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3731 PAGE_SIZE - pg_off);
3734 block_limit = pg_sz + st->stepped_offset;
3735 if (abs_offset < block_limit) {
3737 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3739 *data = (u8 *)st->frag_data + pg_off +
3740 (abs_offset - st->stepped_offset);
3742 return block_limit - abs_offset;
3745 if (st->frag_data) {
3746 kunmap_atomic(st->frag_data);
3747 st->frag_data = NULL;
3750 st->stepped_offset += pg_sz;
3751 st->frag_off += pg_sz;
3752 if (st->frag_off == skb_frag_size(frag)) {
3758 if (st->frag_data) {
3759 kunmap_atomic(st->frag_data);
3760 st->frag_data = NULL;
3763 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3764 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3767 } else if (st->cur_skb->next) {
3768 st->cur_skb = st->cur_skb->next;
3775 EXPORT_SYMBOL(skb_seq_read);
3778 * skb_abort_seq_read - Abort a sequential read of skb data
3779 * @st: state variable
3781 * Must be called if skb_seq_read() was not called until it
3784 void skb_abort_seq_read(struct skb_seq_state *st)
3787 kunmap_atomic(st->frag_data);
3789 EXPORT_SYMBOL(skb_abort_seq_read);
3791 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3793 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3794 struct ts_config *conf,
3795 struct ts_state *state)
3797 return skb_seq_read(offset, text, TS_SKB_CB(state));
3800 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3802 skb_abort_seq_read(TS_SKB_CB(state));
3806 * skb_find_text - Find a text pattern in skb data
3807 * @skb: the buffer to look in
3808 * @from: search offset
3810 * @config: textsearch configuration
3812 * Finds a pattern in the skb data according to the specified
3813 * textsearch configuration. Use textsearch_next() to retrieve
3814 * subsequent occurrences of the pattern. Returns the offset
3815 * to the first occurrence or UINT_MAX if no match was found.
3817 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3818 unsigned int to, struct ts_config *config)
3820 struct ts_state state;
3823 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3825 config->get_next_block = skb_ts_get_next_block;
3826 config->finish = skb_ts_finish;
3828 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3830 ret = textsearch_find(config, &state);
3831 return (ret <= to - from ? ret : UINT_MAX);
3833 EXPORT_SYMBOL(skb_find_text);
3835 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3836 int offset, size_t size)
3838 int i = skb_shinfo(skb)->nr_frags;
3840 if (skb_can_coalesce(skb, i, page, offset)) {
3841 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3842 } else if (i < MAX_SKB_FRAGS) {
3844 skb_fill_page_desc(skb, i, page, offset, size);
3851 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3854 * skb_pull_rcsum - pull skb and update receive checksum
3855 * @skb: buffer to update
3856 * @len: length of data pulled
3858 * This function performs an skb_pull on the packet and updates
3859 * the CHECKSUM_COMPLETE checksum. It should be used on
3860 * receive path processing instead of skb_pull unless you know
3861 * that the checksum difference is zero (e.g., a valid IP header)
3862 * or you are setting ip_summed to CHECKSUM_NONE.
3864 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3866 unsigned char *data = skb->data;
3868 BUG_ON(len > skb->len);
3869 __skb_pull(skb, len);
3870 skb_postpull_rcsum(skb, data, len);
3873 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3875 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
3877 skb_frag_t head_frag;
3880 page = virt_to_head_page(frag_skb->head);
3881 __skb_frag_set_page(&head_frag, page);
3882 skb_frag_off_set(&head_frag, frag_skb->data -
3883 (unsigned char *)page_address(page));
3884 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
3888 struct sk_buff *skb_segment_list(struct sk_buff *skb,
3889 netdev_features_t features,
3890 unsigned int offset)
3892 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
3893 unsigned int tnl_hlen = skb_tnl_header_len(skb);
3894 unsigned int delta_truesize = 0;
3895 unsigned int delta_len = 0;
3896 struct sk_buff *tail = NULL;
3897 struct sk_buff *nskb, *tmp;
3900 skb_push(skb, -skb_network_offset(skb) + offset);
3902 skb_shinfo(skb)->frag_list = NULL;
3906 list_skb = list_skb->next;
3909 delta_truesize += nskb->truesize;
3910 if (skb_shared(nskb)) {
3911 tmp = skb_clone(nskb, GFP_ATOMIC);
3915 err = skb_unclone(nskb, GFP_ATOMIC);
3926 if (unlikely(err)) {
3927 nskb->next = list_skb;
3933 delta_len += nskb->len;
3935 skb_push(nskb, -skb_network_offset(nskb) + offset);
3937 skb_release_head_state(nskb);
3938 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
3939 __copy_skb_header(nskb, skb);
3941 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
3942 nskb->transport_header += len_diff;
3943 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
3944 nskb->data - tnl_hlen,
3947 if (skb_needs_linearize(nskb, features) &&
3948 __skb_linearize(nskb))
3953 skb->truesize = skb->truesize - delta_truesize;
3954 skb->data_len = skb->data_len - delta_len;
3955 skb->len = skb->len - delta_len;
3961 if (skb_needs_linearize(skb, features) &&
3962 __skb_linearize(skb))
3970 kfree_skb_list(skb->next);
3972 return ERR_PTR(-ENOMEM);
3974 EXPORT_SYMBOL_GPL(skb_segment_list);
3977 * skb_segment - Perform protocol segmentation on skb.
3978 * @head_skb: buffer to segment
3979 * @features: features for the output path (see dev->features)
3981 * This function performs segmentation on the given skb. It returns
3982 * a pointer to the first in a list of new skbs for the segments.
3983 * In case of error it returns ERR_PTR(err).
3985 struct sk_buff *skb_segment(struct sk_buff *head_skb,
3986 netdev_features_t features)
3988 struct sk_buff *segs = NULL;
3989 struct sk_buff *tail = NULL;
3990 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3991 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3992 unsigned int mss = skb_shinfo(head_skb)->gso_size;
3993 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
3994 struct sk_buff *frag_skb = head_skb;
3995 unsigned int offset = doffset;
3996 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3997 unsigned int partial_segs = 0;
3998 unsigned int headroom;
3999 unsigned int len = head_skb->len;
4002 int nfrags = skb_shinfo(head_skb)->nr_frags;
4007 if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
4008 (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
4009 /* gso_size is untrusted, and we have a frag_list with a linear
4010 * non head_frag head.
4012 * (we assume checking the first list_skb member suffices;
4013 * i.e if either of the list_skb members have non head_frag
4014 * head, then the first one has too).
4016 * If head_skb's headlen does not fit requested gso_size, it
4017 * means that the frag_list members do NOT terminate on exact
4018 * gso_size boundaries. Hence we cannot perform skb_frag_t page
4019 * sharing. Therefore we must fallback to copying the frag_list
4020 * skbs; we do so by disabling SG.
4022 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
4023 features &= ~NETIF_F_SG;
4026 __skb_push(head_skb, doffset);
4027 proto = skb_network_protocol(head_skb, NULL);
4028 if (unlikely(!proto))
4029 return ERR_PTR(-EINVAL);
4031 sg = !!(features & NETIF_F_SG);
4032 csum = !!can_checksum_protocol(features, proto);
4034 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4035 if (!(features & NETIF_F_GSO_PARTIAL)) {
4036 struct sk_buff *iter;
4037 unsigned int frag_len;
4040 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4043 /* If we get here then all the required
4044 * GSO features except frag_list are supported.
4045 * Try to split the SKB to multiple GSO SKBs
4046 * with no frag_list.
4047 * Currently we can do that only when the buffers don't
4048 * have a linear part and all the buffers except
4049 * the last are of the same length.
4051 frag_len = list_skb->len;
4052 skb_walk_frags(head_skb, iter) {
4053 if (frag_len != iter->len && iter->next)
4055 if (skb_headlen(iter) && !iter->head_frag)
4061 if (len != frag_len)
4065 /* GSO partial only requires that we trim off any excess that
4066 * doesn't fit into an MSS sized block, so take care of that
4069 partial_segs = len / mss;
4070 if (partial_segs > 1)
4071 mss *= partial_segs;
4077 headroom = skb_headroom(head_skb);
4078 pos = skb_headlen(head_skb);
4081 struct sk_buff *nskb;
4082 skb_frag_t *nskb_frag;
4086 if (unlikely(mss == GSO_BY_FRAGS)) {
4087 len = list_skb->len;
4089 len = head_skb->len - offset;
4094 hsize = skb_headlen(head_skb) - offset;
4096 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4097 (skb_headlen(list_skb) == len || sg)) {
4098 BUG_ON(skb_headlen(list_skb) > len);
4101 nfrags = skb_shinfo(list_skb)->nr_frags;
4102 frag = skb_shinfo(list_skb)->frags;
4103 frag_skb = list_skb;
4104 pos += skb_headlen(list_skb);
4106 while (pos < offset + len) {
4107 BUG_ON(i >= nfrags);
4109 size = skb_frag_size(frag);
4110 if (pos + size > offset + len)
4118 nskb = skb_clone(list_skb, GFP_ATOMIC);
4119 list_skb = list_skb->next;
4121 if (unlikely(!nskb))
4124 if (unlikely(pskb_trim(nskb, len))) {
4129 hsize = skb_end_offset(nskb);
4130 if (skb_cow_head(nskb, doffset + headroom)) {
4135 nskb->truesize += skb_end_offset(nskb) - hsize;
4136 skb_release_head_state(nskb);
4137 __skb_push(nskb, doffset);
4141 if (hsize > len || !sg)
4144 nskb = __alloc_skb(hsize + doffset + headroom,
4145 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4148 if (unlikely(!nskb))
4151 skb_reserve(nskb, headroom);
4152 __skb_put(nskb, doffset);
4161 __copy_skb_header(nskb, head_skb);
4163 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4164 skb_reset_mac_len(nskb);
4166 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4167 nskb->data - tnl_hlen,
4168 doffset + tnl_hlen);
4170 if (nskb->len == len + doffset)
4171 goto perform_csum_check;
4175 if (!nskb->remcsum_offload)
4176 nskb->ip_summed = CHECKSUM_NONE;
4177 SKB_GSO_CB(nskb)->csum =
4178 skb_copy_and_csum_bits(head_skb, offset,
4182 SKB_GSO_CB(nskb)->csum_start =
4183 skb_headroom(nskb) + doffset;
4185 skb_copy_bits(head_skb, offset,
4192 nskb_frag = skb_shinfo(nskb)->frags;
4194 skb_copy_from_linear_data_offset(head_skb, offset,
4195 skb_put(nskb, hsize), hsize);
4197 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4200 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4201 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4204 while (pos < offset + len) {
4207 nfrags = skb_shinfo(list_skb)->nr_frags;
4208 frag = skb_shinfo(list_skb)->frags;
4209 frag_skb = list_skb;
4210 if (!skb_headlen(list_skb)) {
4213 BUG_ON(!list_skb->head_frag);
4215 /* to make room for head_frag. */
4219 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4220 skb_zerocopy_clone(nskb, frag_skb,
4224 list_skb = list_skb->next;
4227 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4229 net_warn_ratelimited(
4230 "skb_segment: too many frags: %u %u\n",
4236 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4237 __skb_frag_ref(nskb_frag);
4238 size = skb_frag_size(nskb_frag);
4241 skb_frag_off_add(nskb_frag, offset - pos);
4242 skb_frag_size_sub(nskb_frag, offset - pos);
4245 skb_shinfo(nskb)->nr_frags++;
4247 if (pos + size <= offset + len) {
4252 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4260 nskb->data_len = len - hsize;
4261 nskb->len += nskb->data_len;
4262 nskb->truesize += nskb->data_len;
4266 if (skb_has_shared_frag(nskb) &&
4267 __skb_linearize(nskb))
4270 if (!nskb->remcsum_offload)
4271 nskb->ip_summed = CHECKSUM_NONE;
4272 SKB_GSO_CB(nskb)->csum =
4273 skb_checksum(nskb, doffset,
4274 nskb->len - doffset, 0);
4275 SKB_GSO_CB(nskb)->csum_start =
4276 skb_headroom(nskb) + doffset;
4278 } while ((offset += len) < head_skb->len);
4280 /* Some callers want to get the end of the list.
4281 * Put it in segs->prev to avoid walking the list.
4282 * (see validate_xmit_skb_list() for example)
4287 struct sk_buff *iter;
4288 int type = skb_shinfo(head_skb)->gso_type;
4289 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4291 /* Update type to add partial and then remove dodgy if set */
4292 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4293 type &= ~SKB_GSO_DODGY;
4295 /* Update GSO info and prepare to start updating headers on
4296 * our way back down the stack of protocols.
4298 for (iter = segs; iter; iter = iter->next) {
4299 skb_shinfo(iter)->gso_size = gso_size;
4300 skb_shinfo(iter)->gso_segs = partial_segs;
4301 skb_shinfo(iter)->gso_type = type;
4302 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4305 if (tail->len - doffset <= gso_size)
4306 skb_shinfo(tail)->gso_size = 0;
4307 else if (tail != segs)
4308 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4311 /* Following permits correct backpressure, for protocols
4312 * using skb_set_owner_w().
4313 * Idea is to tranfert ownership from head_skb to last segment.
4315 if (head_skb->destructor == sock_wfree) {
4316 swap(tail->truesize, head_skb->truesize);
4317 swap(tail->destructor, head_skb->destructor);
4318 swap(tail->sk, head_skb->sk);
4323 kfree_skb_list(segs);
4324 return ERR_PTR(err);
4326 EXPORT_SYMBOL_GPL(skb_segment);
4328 #ifdef CONFIG_SKB_EXTENSIONS
4329 #define SKB_EXT_ALIGN_VALUE 8
4330 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4332 static const u8 skb_ext_type_len[] = {
4333 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4334 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4337 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4339 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4340 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4342 #if IS_ENABLED(CONFIG_MPTCP)
4343 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4345 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4346 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4350 static __always_inline unsigned int skb_ext_total_length(void)
4352 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4353 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4354 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4357 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4359 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4360 skb_ext_type_len[TC_SKB_EXT] +
4362 #if IS_ENABLED(CONFIG_MPTCP)
4363 skb_ext_type_len[SKB_EXT_MPTCP] +
4365 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4366 skb_ext_type_len[SKB_EXT_MCTP] +
4371 static void skb_extensions_init(void)
4373 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4374 BUILD_BUG_ON(skb_ext_total_length() > 255);
4376 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4377 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4379 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4383 static void skb_extensions_init(void) {}
4386 void __init skb_init(void)
4388 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4389 sizeof(struct sk_buff),
4391 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4392 offsetof(struct sk_buff, cb),
4393 sizeof_field(struct sk_buff, cb),
4395 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4396 sizeof(struct sk_buff_fclones),
4398 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4400 skb_extensions_init();
4404 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4405 unsigned int recursion_level)
4407 int start = skb_headlen(skb);
4408 int i, copy = start - offset;
4409 struct sk_buff *frag_iter;
4412 if (unlikely(recursion_level >= 24))
4418 sg_set_buf(sg, skb->data + offset, copy);
4420 if ((len -= copy) == 0)
4425 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4428 WARN_ON(start > offset + len);
4430 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4431 if ((copy = end - offset) > 0) {
4432 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4433 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4438 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4439 skb_frag_off(frag) + offset - start);
4448 skb_walk_frags(skb, frag_iter) {
4451 WARN_ON(start > offset + len);
4453 end = start + frag_iter->len;
4454 if ((copy = end - offset) > 0) {
4455 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4460 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4461 copy, recursion_level + 1);
4462 if (unlikely(ret < 0))
4465 if ((len -= copy) == 0)
4476 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4477 * @skb: Socket buffer containing the buffers to be mapped
4478 * @sg: The scatter-gather list to map into
4479 * @offset: The offset into the buffer's contents to start mapping
4480 * @len: Length of buffer space to be mapped
4482 * Fill the specified scatter-gather list with mappings/pointers into a
4483 * region of the buffer space attached to a socket buffer. Returns either
4484 * the number of scatterlist items used, or -EMSGSIZE if the contents
4487 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4489 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4494 sg_mark_end(&sg[nsg - 1]);
4498 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4500 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4501 * sglist without mark the sg which contain last skb data as the end.
4502 * So the caller can mannipulate sg list as will when padding new data after
4503 * the first call without calling sg_unmark_end to expend sg list.
4505 * Scenario to use skb_to_sgvec_nomark:
4507 * 2. skb_to_sgvec_nomark(payload1)
4508 * 3. skb_to_sgvec_nomark(payload2)
4510 * This is equivalent to:
4512 * 2. skb_to_sgvec(payload1)
4514 * 4. skb_to_sgvec(payload2)
4516 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4517 * is more preferable.
4519 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4520 int offset, int len)
4522 return __skb_to_sgvec(skb, sg, offset, len, 0);
4524 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4529 * skb_cow_data - Check that a socket buffer's data buffers are writable
4530 * @skb: The socket buffer to check.
4531 * @tailbits: Amount of trailing space to be added
4532 * @trailer: Returned pointer to the skb where the @tailbits space begins
4534 * Make sure that the data buffers attached to a socket buffer are
4535 * writable. If they are not, private copies are made of the data buffers
4536 * and the socket buffer is set to use these instead.
4538 * If @tailbits is given, make sure that there is space to write @tailbits
4539 * bytes of data beyond current end of socket buffer. @trailer will be
4540 * set to point to the skb in which this space begins.
4542 * The number of scatterlist elements required to completely map the
4543 * COW'd and extended socket buffer will be returned.
4545 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4549 struct sk_buff *skb1, **skb_p;
4551 /* If skb is cloned or its head is paged, reallocate
4552 * head pulling out all the pages (pages are considered not writable
4553 * at the moment even if they are anonymous).
4555 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4556 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4559 /* Easy case. Most of packets will go this way. */
4560 if (!skb_has_frag_list(skb)) {
4561 /* A little of trouble, not enough of space for trailer.
4562 * This should not happen, when stack is tuned to generate
4563 * good frames. OK, on miss we reallocate and reserve even more
4564 * space, 128 bytes is fair. */
4566 if (skb_tailroom(skb) < tailbits &&
4567 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4575 /* Misery. We are in troubles, going to mincer fragments... */
4578 skb_p = &skb_shinfo(skb)->frag_list;
4581 while ((skb1 = *skb_p) != NULL) {
4584 /* The fragment is partially pulled by someone,
4585 * this can happen on input. Copy it and everything
4588 if (skb_shared(skb1))
4591 /* If the skb is the last, worry about trailer. */
4593 if (skb1->next == NULL && tailbits) {
4594 if (skb_shinfo(skb1)->nr_frags ||
4595 skb_has_frag_list(skb1) ||
4596 skb_tailroom(skb1) < tailbits)
4597 ntail = tailbits + 128;
4603 skb_shinfo(skb1)->nr_frags ||
4604 skb_has_frag_list(skb1)) {
4605 struct sk_buff *skb2;
4607 /* Fuck, we are miserable poor guys... */
4609 skb2 = skb_copy(skb1, GFP_ATOMIC);
4611 skb2 = skb_copy_expand(skb1,
4615 if (unlikely(skb2 == NULL))
4619 skb_set_owner_w(skb2, skb1->sk);
4621 /* Looking around. Are we still alive?
4622 * OK, link new skb, drop old one */
4624 skb2->next = skb1->next;
4631 skb_p = &skb1->next;
4636 EXPORT_SYMBOL_GPL(skb_cow_data);
4638 static void sock_rmem_free(struct sk_buff *skb)
4640 struct sock *sk = skb->sk;
4642 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4645 static void skb_set_err_queue(struct sk_buff *skb)
4647 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4648 * So, it is safe to (mis)use it to mark skbs on the error queue.
4650 skb->pkt_type = PACKET_OUTGOING;
4651 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4655 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4657 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4659 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4660 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4665 skb->destructor = sock_rmem_free;
4666 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4667 skb_set_err_queue(skb);
4669 /* before exiting rcu section, make sure dst is refcounted */
4672 skb_queue_tail(&sk->sk_error_queue, skb);
4673 if (!sock_flag(sk, SOCK_DEAD))
4674 sk_error_report(sk);
4677 EXPORT_SYMBOL(sock_queue_err_skb);
4679 static bool is_icmp_err_skb(const struct sk_buff *skb)
4681 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4682 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4685 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4687 struct sk_buff_head *q = &sk->sk_error_queue;
4688 struct sk_buff *skb, *skb_next = NULL;
4689 bool icmp_next = false;
4690 unsigned long flags;
4692 spin_lock_irqsave(&q->lock, flags);
4693 skb = __skb_dequeue(q);
4694 if (skb && (skb_next = skb_peek(q))) {
4695 icmp_next = is_icmp_err_skb(skb_next);
4697 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4699 spin_unlock_irqrestore(&q->lock, flags);
4701 if (is_icmp_err_skb(skb) && !icmp_next)
4705 sk_error_report(sk);
4709 EXPORT_SYMBOL(sock_dequeue_err_skb);
4712 * skb_clone_sk - create clone of skb, and take reference to socket
4713 * @skb: the skb to clone
4715 * This function creates a clone of a buffer that holds a reference on
4716 * sk_refcnt. Buffers created via this function are meant to be
4717 * returned using sock_queue_err_skb, or free via kfree_skb.
4719 * When passing buffers allocated with this function to sock_queue_err_skb
4720 * it is necessary to wrap the call with sock_hold/sock_put in order to
4721 * prevent the socket from being released prior to being enqueued on
4722 * the sk_error_queue.
4724 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4726 struct sock *sk = skb->sk;
4727 struct sk_buff *clone;
4729 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4732 clone = skb_clone(skb, GFP_ATOMIC);
4739 clone->destructor = sock_efree;
4743 EXPORT_SYMBOL(skb_clone_sk);
4745 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4750 struct sock_exterr_skb *serr;
4753 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4755 serr = SKB_EXT_ERR(skb);
4756 memset(serr, 0, sizeof(*serr));
4757 serr->ee.ee_errno = ENOMSG;
4758 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4759 serr->ee.ee_info = tstype;
4760 serr->opt_stats = opt_stats;
4761 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4762 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4763 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4765 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4768 err = sock_queue_err_skb(sk, skb);
4774 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4778 if (likely(sysctl_tstamp_allow_data || tsonly))
4781 read_lock_bh(&sk->sk_callback_lock);
4782 ret = sk->sk_socket && sk->sk_socket->file &&
4783 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4784 read_unlock_bh(&sk->sk_callback_lock);
4788 void skb_complete_tx_timestamp(struct sk_buff *skb,
4789 struct skb_shared_hwtstamps *hwtstamps)
4791 struct sock *sk = skb->sk;
4793 if (!skb_may_tx_timestamp(sk, false))
4796 /* Take a reference to prevent skb_orphan() from freeing the socket,
4797 * but only if the socket refcount is not zero.
4799 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4800 *skb_hwtstamps(skb) = *hwtstamps;
4801 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4809 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4811 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4812 const struct sk_buff *ack_skb,
4813 struct skb_shared_hwtstamps *hwtstamps,
4814 struct sock *sk, int tstype)
4816 struct sk_buff *skb;
4817 bool tsonly, opt_stats = false;
4822 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4823 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4826 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4827 if (!skb_may_tx_timestamp(sk, tsonly))
4832 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4834 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4839 skb = alloc_skb(0, GFP_ATOMIC);
4841 skb = skb_clone(orig_skb, GFP_ATOMIC);
4847 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4849 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4853 *skb_hwtstamps(skb) = *hwtstamps;
4855 __net_timestamp(skb);
4857 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
4859 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4861 void skb_tstamp_tx(struct sk_buff *orig_skb,
4862 struct skb_shared_hwtstamps *hwtstamps)
4864 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4867 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4869 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
4871 struct sock *sk = skb->sk;
4872 struct sock_exterr_skb *serr;
4875 skb->wifi_acked_valid = 1;
4876 skb->wifi_acked = acked;
4878 serr = SKB_EXT_ERR(skb);
4879 memset(serr, 0, sizeof(*serr));
4880 serr->ee.ee_errno = ENOMSG;
4881 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
4883 /* Take a reference to prevent skb_orphan() from freeing the socket,
4884 * but only if the socket refcount is not zero.
4886 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4887 err = sock_queue_err_skb(sk, skb);
4893 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4896 * skb_partial_csum_set - set up and verify partial csum values for packet
4897 * @skb: the skb to set
4898 * @start: the number of bytes after skb->data to start checksumming.
4899 * @off: the offset from start to place the checksum.
4901 * For untrusted partially-checksummed packets, we need to make sure the values
4902 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4904 * This function checks and sets those values and skb->ip_summed: if this
4905 * returns false you should drop the packet.
4907 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4909 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
4910 u32 csum_start = skb_headroom(skb) + (u32)start;
4912 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
4913 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
4914 start, off, skb_headroom(skb), skb_headlen(skb));
4917 skb->ip_summed = CHECKSUM_PARTIAL;
4918 skb->csum_start = csum_start;
4919 skb->csum_offset = off;
4920 skb_set_transport_header(skb, start);
4923 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4925 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4928 if (skb_headlen(skb) >= len)
4931 /* If we need to pullup then pullup to the max, so we
4932 * won't need to do it again.
4937 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4940 if (skb_headlen(skb) < len)
4946 #define MAX_TCP_HDR_LEN (15 * 4)
4948 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4949 typeof(IPPROTO_IP) proto,
4956 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4957 off + MAX_TCP_HDR_LEN);
4958 if (!err && !skb_partial_csum_set(skb, off,
4959 offsetof(struct tcphdr,
4962 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4965 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4966 off + sizeof(struct udphdr));
4967 if (!err && !skb_partial_csum_set(skb, off,
4968 offsetof(struct udphdr,
4971 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4974 return ERR_PTR(-EPROTO);
4977 /* This value should be large enough to cover a tagged ethernet header plus
4978 * maximally sized IP and TCP or UDP headers.
4980 #define MAX_IP_HDR_LEN 128
4982 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
4991 err = skb_maybe_pull_tail(skb,
4992 sizeof(struct iphdr),
4997 if (ip_is_fragment(ip_hdr(skb)))
5000 off = ip_hdrlen(skb);
5007 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5009 return PTR_ERR(csum);
5012 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5015 ip_hdr(skb)->protocol, 0);
5022 /* This value should be large enough to cover a tagged ethernet header plus
5023 * an IPv6 header, all options, and a maximal TCP or UDP header.
5025 #define MAX_IPV6_HDR_LEN 256
5027 #define OPT_HDR(type, skb, off) \
5028 (type *)(skb_network_header(skb) + (off))
5030 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5043 off = sizeof(struct ipv6hdr);
5045 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5049 nexthdr = ipv6_hdr(skb)->nexthdr;
5051 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5052 while (off <= len && !done) {
5054 case IPPROTO_DSTOPTS:
5055 case IPPROTO_HOPOPTS:
5056 case IPPROTO_ROUTING: {
5057 struct ipv6_opt_hdr *hp;
5059 err = skb_maybe_pull_tail(skb,
5061 sizeof(struct ipv6_opt_hdr),
5066 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5067 nexthdr = hp->nexthdr;
5068 off += ipv6_optlen(hp);
5072 struct ip_auth_hdr *hp;
5074 err = skb_maybe_pull_tail(skb,
5076 sizeof(struct ip_auth_hdr),
5081 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5082 nexthdr = hp->nexthdr;
5083 off += ipv6_authlen(hp);
5086 case IPPROTO_FRAGMENT: {
5087 struct frag_hdr *hp;
5089 err = skb_maybe_pull_tail(skb,
5091 sizeof(struct frag_hdr),
5096 hp = OPT_HDR(struct frag_hdr, skb, off);
5098 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5101 nexthdr = hp->nexthdr;
5102 off += sizeof(struct frag_hdr);
5113 if (!done || fragment)
5116 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5118 return PTR_ERR(csum);
5121 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5122 &ipv6_hdr(skb)->daddr,
5123 skb->len - off, nexthdr, 0);
5131 * skb_checksum_setup - set up partial checksum offset
5132 * @skb: the skb to set up
5133 * @recalculate: if true the pseudo-header checksum will be recalculated
5135 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5139 switch (skb->protocol) {
5140 case htons(ETH_P_IP):
5141 err = skb_checksum_setup_ipv4(skb, recalculate);
5144 case htons(ETH_P_IPV6):
5145 err = skb_checksum_setup_ipv6(skb, recalculate);
5155 EXPORT_SYMBOL(skb_checksum_setup);
5158 * skb_checksum_maybe_trim - maybe trims the given skb
5159 * @skb: the skb to check
5160 * @transport_len: the data length beyond the network header
5162 * Checks whether the given skb has data beyond the given transport length.
5163 * If so, returns a cloned skb trimmed to this transport length.
5164 * Otherwise returns the provided skb. Returns NULL in error cases
5165 * (e.g. transport_len exceeds skb length or out-of-memory).
5167 * Caller needs to set the skb transport header and free any returned skb if it
5168 * differs from the provided skb.
5170 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5171 unsigned int transport_len)
5173 struct sk_buff *skb_chk;
5174 unsigned int len = skb_transport_offset(skb) + transport_len;
5179 else if (skb->len == len)
5182 skb_chk = skb_clone(skb, GFP_ATOMIC);
5186 ret = pskb_trim_rcsum(skb_chk, len);
5196 * skb_checksum_trimmed - validate checksum of an skb
5197 * @skb: the skb to check
5198 * @transport_len: the data length beyond the network header
5199 * @skb_chkf: checksum function to use
5201 * Applies the given checksum function skb_chkf to the provided skb.
5202 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5204 * If the skb has data beyond the given transport length, then a
5205 * trimmed & cloned skb is checked and returned.
5207 * Caller needs to set the skb transport header and free any returned skb if it
5208 * differs from the provided skb.
5210 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5211 unsigned int transport_len,
5212 __sum16(*skb_chkf)(struct sk_buff *skb))
5214 struct sk_buff *skb_chk;
5215 unsigned int offset = skb_transport_offset(skb);
5218 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5222 if (!pskb_may_pull(skb_chk, offset))
5225 skb_pull_rcsum(skb_chk, offset);
5226 ret = skb_chkf(skb_chk);
5227 skb_push_rcsum(skb_chk, offset);
5235 if (skb_chk && skb_chk != skb)
5241 EXPORT_SYMBOL(skb_checksum_trimmed);
5243 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5245 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5248 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5250 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5253 skb_release_head_state(skb);
5254 kmem_cache_free(skbuff_head_cache, skb);
5259 EXPORT_SYMBOL(kfree_skb_partial);
5262 * skb_try_coalesce - try to merge skb to prior one
5264 * @from: buffer to add
5265 * @fragstolen: pointer to boolean
5266 * @delta_truesize: how much more was allocated than was requested
5268 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5269 bool *fragstolen, int *delta_truesize)
5271 struct skb_shared_info *to_shinfo, *from_shinfo;
5272 int i, delta, len = from->len;
5274 *fragstolen = false;
5279 /* In general, avoid mixing slab allocated and page_pool allocated
5280 * pages within the same SKB. However when @to is not pp_recycle and
5281 * @from is cloned, we can transition frag pages from page_pool to
5282 * reference counted.
5284 * On the other hand, don't allow coalescing two pp_recycle SKBs if
5285 * @from is cloned, in case the SKB is using page_pool fragment
5286 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5287 * references for cloned SKBs at the moment that would result in
5288 * inconsistent reference counts.
5290 if (to->pp_recycle != (from->pp_recycle && !skb_cloned(from)))
5293 if (len <= skb_tailroom(to)) {
5295 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5296 *delta_truesize = 0;
5300 to_shinfo = skb_shinfo(to);
5301 from_shinfo = skb_shinfo(from);
5302 if (to_shinfo->frag_list || from_shinfo->frag_list)
5304 if (skb_zcopy(to) || skb_zcopy(from))
5307 if (skb_headlen(from) != 0) {
5309 unsigned int offset;
5311 if (to_shinfo->nr_frags +
5312 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5315 if (skb_head_is_locked(from))
5318 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5320 page = virt_to_head_page(from->head);
5321 offset = from->data - (unsigned char *)page_address(page);
5323 skb_fill_page_desc(to, to_shinfo->nr_frags,
5324 page, offset, skb_headlen(from));
5327 if (to_shinfo->nr_frags +
5328 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5331 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5334 WARN_ON_ONCE(delta < len);
5336 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5338 from_shinfo->nr_frags * sizeof(skb_frag_t));
5339 to_shinfo->nr_frags += from_shinfo->nr_frags;
5341 if (!skb_cloned(from))
5342 from_shinfo->nr_frags = 0;
5344 /* if the skb is not cloned this does nothing
5345 * since we set nr_frags to 0.
5347 for (i = 0; i < from_shinfo->nr_frags; i++)
5348 __skb_frag_ref(&from_shinfo->frags[i]);
5350 to->truesize += delta;
5352 to->data_len += len;
5354 *delta_truesize = delta;
5357 EXPORT_SYMBOL(skb_try_coalesce);
5360 * skb_scrub_packet - scrub an skb
5362 * @skb: buffer to clean
5363 * @xnet: packet is crossing netns
5365 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5366 * into/from a tunnel. Some information have to be cleared during these
5368 * skb_scrub_packet can also be used to clean a skb before injecting it in
5369 * another namespace (@xnet == true). We have to clear all information in the
5370 * skb that could impact namespace isolation.
5372 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5374 skb->pkt_type = PACKET_HOST;
5380 nf_reset_trace(skb);
5382 #ifdef CONFIG_NET_SWITCHDEV
5383 skb->offload_fwd_mark = 0;
5384 skb->offload_l3_fwd_mark = 0;
5392 skb_clear_tstamp(skb);
5394 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5397 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5401 * skb_gso_transport_seglen is used to determine the real size of the
5402 * individual segments, including Layer4 headers (TCP/UDP).
5404 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5406 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5408 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5409 unsigned int thlen = 0;
5411 if (skb->encapsulation) {
5412 thlen = skb_inner_transport_header(skb) -
5413 skb_transport_header(skb);
5415 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5416 thlen += inner_tcp_hdrlen(skb);
5417 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5418 thlen = tcp_hdrlen(skb);
5419 } else if (unlikely(skb_is_gso_sctp(skb))) {
5420 thlen = sizeof(struct sctphdr);
5421 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5422 thlen = sizeof(struct udphdr);
5424 /* UFO sets gso_size to the size of the fragmentation
5425 * payload, i.e. the size of the L4 (UDP) header is already
5428 return thlen + shinfo->gso_size;
5432 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5436 * skb_gso_network_seglen is used to determine the real size of the
5437 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5439 * The MAC/L2 header is not accounted for.
5441 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5443 unsigned int hdr_len = skb_transport_header(skb) -
5444 skb_network_header(skb);
5446 return hdr_len + skb_gso_transport_seglen(skb);
5450 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5454 * skb_gso_mac_seglen is used to determine the real size of the
5455 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5456 * headers (TCP/UDP).
5458 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5460 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5462 return hdr_len + skb_gso_transport_seglen(skb);
5466 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5468 * There are a couple of instances where we have a GSO skb, and we
5469 * want to determine what size it would be after it is segmented.
5471 * We might want to check:
5472 * - L3+L4+payload size (e.g. IP forwarding)
5473 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5475 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5479 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5480 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5482 * @max_len: The maximum permissible length.
5484 * Returns true if the segmented length <= max length.
5486 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5487 unsigned int seg_len,
5488 unsigned int max_len) {
5489 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5490 const struct sk_buff *iter;
5492 if (shinfo->gso_size != GSO_BY_FRAGS)
5493 return seg_len <= max_len;
5495 /* Undo this so we can re-use header sizes */
5496 seg_len -= GSO_BY_FRAGS;
5498 skb_walk_frags(skb, iter) {
5499 if (seg_len + skb_headlen(iter) > max_len)
5507 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5510 * @mtu: MTU to validate against
5512 * skb_gso_validate_network_len validates if a given skb will fit a
5513 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5516 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5518 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5520 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5523 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5526 * @len: length to validate against
5528 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5529 * length once split, including L2, L3 and L4 headers and the payload.
5531 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5533 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5535 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5537 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5539 int mac_len, meta_len;
5542 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5547 mac_len = skb->data - skb_mac_header(skb);
5548 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5549 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5550 mac_len - VLAN_HLEN - ETH_TLEN);
5553 meta_len = skb_metadata_len(skb);
5555 meta = skb_metadata_end(skb) - meta_len;
5556 memmove(meta + VLAN_HLEN, meta, meta_len);
5559 skb->mac_header += VLAN_HLEN;
5563 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5565 struct vlan_hdr *vhdr;
5568 if (unlikely(skb_vlan_tag_present(skb))) {
5569 /* vlan_tci is already set-up so leave this for another time */
5573 skb = skb_share_check(skb, GFP_ATOMIC);
5576 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5577 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5580 vhdr = (struct vlan_hdr *)skb->data;
5581 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5582 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5584 skb_pull_rcsum(skb, VLAN_HLEN);
5585 vlan_set_encap_proto(skb, vhdr);
5587 skb = skb_reorder_vlan_header(skb);
5591 skb_reset_network_header(skb);
5592 if (!skb_transport_header_was_set(skb))
5593 skb_reset_transport_header(skb);
5594 skb_reset_mac_len(skb);
5602 EXPORT_SYMBOL(skb_vlan_untag);
5604 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5606 if (!pskb_may_pull(skb, write_len))
5609 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5612 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5614 EXPORT_SYMBOL(skb_ensure_writable);
5616 /* remove VLAN header from packet and update csum accordingly.
5617 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5619 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5621 struct vlan_hdr *vhdr;
5622 int offset = skb->data - skb_mac_header(skb);
5625 if (WARN_ONCE(offset,
5626 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5631 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5635 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5637 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5638 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5640 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5641 __skb_pull(skb, VLAN_HLEN);
5643 vlan_set_encap_proto(skb, vhdr);
5644 skb->mac_header += VLAN_HLEN;
5646 if (skb_network_offset(skb) < ETH_HLEN)
5647 skb_set_network_header(skb, ETH_HLEN);
5649 skb_reset_mac_len(skb);
5653 EXPORT_SYMBOL(__skb_vlan_pop);
5655 /* Pop a vlan tag either from hwaccel or from payload.
5656 * Expects skb->data at mac header.
5658 int skb_vlan_pop(struct sk_buff *skb)
5664 if (likely(skb_vlan_tag_present(skb))) {
5665 __vlan_hwaccel_clear_tag(skb);
5667 if (unlikely(!eth_type_vlan(skb->protocol)))
5670 err = __skb_vlan_pop(skb, &vlan_tci);
5674 /* move next vlan tag to hw accel tag */
5675 if (likely(!eth_type_vlan(skb->protocol)))
5678 vlan_proto = skb->protocol;
5679 err = __skb_vlan_pop(skb, &vlan_tci);
5683 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5686 EXPORT_SYMBOL(skb_vlan_pop);
5688 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5689 * Expects skb->data at mac header.
5691 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5693 if (skb_vlan_tag_present(skb)) {
5694 int offset = skb->data - skb_mac_header(skb);
5697 if (WARN_ONCE(offset,
5698 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5703 err = __vlan_insert_tag(skb, skb->vlan_proto,
5704 skb_vlan_tag_get(skb));
5708 skb->protocol = skb->vlan_proto;
5709 skb->mac_len += VLAN_HLEN;
5711 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5713 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5716 EXPORT_SYMBOL(skb_vlan_push);
5719 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5721 * @skb: Socket buffer to modify
5723 * Drop the Ethernet header of @skb.
5725 * Expects that skb->data points to the mac header and that no VLAN tags are
5728 * Returns 0 on success, -errno otherwise.
5730 int skb_eth_pop(struct sk_buff *skb)
5732 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5733 skb_network_offset(skb) < ETH_HLEN)
5736 skb_pull_rcsum(skb, ETH_HLEN);
5737 skb_reset_mac_header(skb);
5738 skb_reset_mac_len(skb);
5742 EXPORT_SYMBOL(skb_eth_pop);
5745 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5747 * @skb: Socket buffer to modify
5748 * @dst: Destination MAC address of the new header
5749 * @src: Source MAC address of the new header
5751 * Prepend @skb with a new Ethernet header.
5753 * Expects that skb->data points to the mac header, which must be empty.
5755 * Returns 0 on success, -errno otherwise.
5757 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5758 const unsigned char *src)
5763 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5766 err = skb_cow_head(skb, sizeof(*eth));
5770 skb_push(skb, sizeof(*eth));
5771 skb_reset_mac_header(skb);
5772 skb_reset_mac_len(skb);
5775 ether_addr_copy(eth->h_dest, dst);
5776 ether_addr_copy(eth->h_source, src);
5777 eth->h_proto = skb->protocol;
5779 skb_postpush_rcsum(skb, eth, sizeof(*eth));
5783 EXPORT_SYMBOL(skb_eth_push);
5785 /* Update the ethertype of hdr and the skb csum value if required. */
5786 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5789 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5790 __be16 diff[] = { ~hdr->h_proto, ethertype };
5792 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5795 hdr->h_proto = ethertype;
5799 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5803 * @mpls_lse: MPLS label stack entry to push
5804 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5805 * @mac_len: length of the MAC header
5806 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5809 * Expects skb->data at mac header.
5811 * Returns 0 on success, -errno otherwise.
5813 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5814 int mac_len, bool ethernet)
5816 struct mpls_shim_hdr *lse;
5819 if (unlikely(!eth_p_mpls(mpls_proto)))
5822 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5823 if (skb->encapsulation)
5826 err = skb_cow_head(skb, MPLS_HLEN);
5830 if (!skb->inner_protocol) {
5831 skb_set_inner_network_header(skb, skb_network_offset(skb));
5832 skb_set_inner_protocol(skb, skb->protocol);
5835 skb_push(skb, MPLS_HLEN);
5836 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5838 skb_reset_mac_header(skb);
5839 skb_set_network_header(skb, mac_len);
5840 skb_reset_mac_len(skb);
5842 lse = mpls_hdr(skb);
5843 lse->label_stack_entry = mpls_lse;
5844 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5846 if (ethernet && mac_len >= ETH_HLEN)
5847 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5848 skb->protocol = mpls_proto;
5852 EXPORT_SYMBOL_GPL(skb_mpls_push);
5855 * skb_mpls_pop() - pop the outermost MPLS header
5858 * @next_proto: ethertype of header after popped MPLS header
5859 * @mac_len: length of the MAC header
5860 * @ethernet: flag to indicate if the packet is ethernet
5862 * Expects skb->data at mac header.
5864 * Returns 0 on success, -errno otherwise.
5866 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5871 if (unlikely(!eth_p_mpls(skb->protocol)))
5874 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5878 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5879 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5882 __skb_pull(skb, MPLS_HLEN);
5883 skb_reset_mac_header(skb);
5884 skb_set_network_header(skb, mac_len);
5886 if (ethernet && mac_len >= ETH_HLEN) {
5889 /* use mpls_hdr() to get ethertype to account for VLANs. */
5890 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5891 skb_mod_eth_type(skb, hdr, next_proto);
5893 skb->protocol = next_proto;
5897 EXPORT_SYMBOL_GPL(skb_mpls_pop);
5900 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
5903 * @mpls_lse: new MPLS label stack entry to update to
5905 * Expects skb->data at mac header.
5907 * Returns 0 on success, -errno otherwise.
5909 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
5913 if (unlikely(!eth_p_mpls(skb->protocol)))
5916 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
5920 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5921 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
5923 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5926 mpls_hdr(skb)->label_stack_entry = mpls_lse;
5930 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
5933 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
5937 * Expects skb->data at mac header.
5939 * Returns 0 on success, -errno otherwise.
5941 int skb_mpls_dec_ttl(struct sk_buff *skb)
5946 if (unlikely(!eth_p_mpls(skb->protocol)))
5949 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
5952 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
5953 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
5957 lse &= ~MPLS_LS_TTL_MASK;
5958 lse |= ttl << MPLS_LS_TTL_SHIFT;
5960 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
5962 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
5965 * alloc_skb_with_frags - allocate skb with page frags
5967 * @header_len: size of linear part
5968 * @data_len: needed length in frags
5969 * @max_page_order: max page order desired.
5970 * @errcode: pointer to error code if any
5971 * @gfp_mask: allocation mask
5973 * This can be used to allocate a paged skb, given a maximal order for frags.
5975 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
5976 unsigned long data_len,
5981 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
5982 unsigned long chunk;
5983 struct sk_buff *skb;
5987 *errcode = -EMSGSIZE;
5988 /* Note this test could be relaxed, if we succeed to allocate
5989 * high order pages...
5991 if (npages > MAX_SKB_FRAGS)
5994 *errcode = -ENOBUFS;
5995 skb = alloc_skb(header_len, gfp_mask);
5999 skb->truesize += npages << PAGE_SHIFT;
6001 for (i = 0; npages > 0; i++) {
6002 int order = max_page_order;
6005 if (npages >= 1 << order) {
6006 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6012 /* Do not retry other high order allocations */
6018 page = alloc_page(gfp_mask);
6022 chunk = min_t(unsigned long, data_len,
6023 PAGE_SIZE << order);
6024 skb_fill_page_desc(skb, i, page, 0, chunk);
6026 npages -= 1 << order;
6034 EXPORT_SYMBOL(alloc_skb_with_frags);
6036 /* carve out the first off bytes from skb when off < headlen */
6037 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6038 const int headlen, gfp_t gfp_mask)
6041 int size = skb_end_offset(skb);
6042 int new_hlen = headlen - off;
6045 size = SKB_DATA_ALIGN(size);
6047 if (skb_pfmemalloc(skb))
6048 gfp_mask |= __GFP_MEMALLOC;
6049 data = kmalloc_reserve(size +
6050 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6051 gfp_mask, NUMA_NO_NODE, NULL);
6055 size = SKB_WITH_OVERHEAD(ksize(data));
6057 /* Copy real data, and all frags */
6058 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6061 memcpy((struct skb_shared_info *)(data + size),
6063 offsetof(struct skb_shared_info,
6064 frags[skb_shinfo(skb)->nr_frags]));
6065 if (skb_cloned(skb)) {
6066 /* drop the old head gracefully */
6067 if (skb_orphan_frags(skb, gfp_mask)) {
6071 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6072 skb_frag_ref(skb, i);
6073 if (skb_has_frag_list(skb))
6074 skb_clone_fraglist(skb);
6075 skb_release_data(skb);
6077 /* we can reuse existing recount- all we did was
6086 skb_set_end_offset(skb, size);
6087 skb_set_tail_pointer(skb, skb_headlen(skb));
6088 skb_headers_offset_update(skb, 0);
6092 atomic_set(&skb_shinfo(skb)->dataref, 1);
6097 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6099 /* carve out the first eat bytes from skb's frag_list. May recurse into
6102 static int pskb_carve_frag_list(struct sk_buff *skb,
6103 struct skb_shared_info *shinfo, int eat,
6106 struct sk_buff *list = shinfo->frag_list;
6107 struct sk_buff *clone = NULL;
6108 struct sk_buff *insp = NULL;
6112 pr_err("Not enough bytes to eat. Want %d\n", eat);
6115 if (list->len <= eat) {
6116 /* Eaten as whole. */
6121 /* Eaten partially. */
6122 if (skb_shared(list)) {
6123 clone = skb_clone(list, gfp_mask);
6129 /* This may be pulled without problems. */
6132 if (pskb_carve(list, eat, gfp_mask) < 0) {
6140 /* Free pulled out fragments. */
6141 while ((list = shinfo->frag_list) != insp) {
6142 shinfo->frag_list = list->next;
6145 /* And insert new clone at head. */
6148 shinfo->frag_list = clone;
6153 /* carve off first len bytes from skb. Split line (off) is in the
6154 * non-linear part of skb
6156 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6157 int pos, gfp_t gfp_mask)
6160 int size = skb_end_offset(skb);
6162 const int nfrags = skb_shinfo(skb)->nr_frags;
6163 struct skb_shared_info *shinfo;
6165 size = SKB_DATA_ALIGN(size);
6167 if (skb_pfmemalloc(skb))
6168 gfp_mask |= __GFP_MEMALLOC;
6169 data = kmalloc_reserve(size +
6170 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6171 gfp_mask, NUMA_NO_NODE, NULL);
6175 size = SKB_WITH_OVERHEAD(ksize(data));
6177 memcpy((struct skb_shared_info *)(data + size),
6178 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6179 if (skb_orphan_frags(skb, gfp_mask)) {
6183 shinfo = (struct skb_shared_info *)(data + size);
6184 for (i = 0; i < nfrags; i++) {
6185 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6187 if (pos + fsize > off) {
6188 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6192 * We have two variants in this case:
6193 * 1. Move all the frag to the second
6194 * part, if it is possible. F.e.
6195 * this approach is mandatory for TUX,
6196 * where splitting is expensive.
6197 * 2. Split is accurately. We make this.
6199 skb_frag_off_add(&shinfo->frags[0], off - pos);
6200 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6202 skb_frag_ref(skb, i);
6207 shinfo->nr_frags = k;
6208 if (skb_has_frag_list(skb))
6209 skb_clone_fraglist(skb);
6211 /* split line is in frag list */
6212 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6213 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6214 if (skb_has_frag_list(skb))
6215 kfree_skb_list(skb_shinfo(skb)->frag_list);
6219 skb_release_data(skb);
6224 skb_set_end_offset(skb, size);
6225 skb_reset_tail_pointer(skb);
6226 skb_headers_offset_update(skb, 0);
6231 skb->data_len = skb->len;
6232 atomic_set(&skb_shinfo(skb)->dataref, 1);
6236 /* remove len bytes from the beginning of the skb */
6237 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6239 int headlen = skb_headlen(skb);
6242 return pskb_carve_inside_header(skb, len, headlen, gfp);
6244 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6247 /* Extract to_copy bytes starting at off from skb, and return this in
6250 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6251 int to_copy, gfp_t gfp)
6253 struct sk_buff *clone = skb_clone(skb, gfp);
6258 if (pskb_carve(clone, off, gfp) < 0 ||
6259 pskb_trim(clone, to_copy)) {
6265 EXPORT_SYMBOL(pskb_extract);
6268 * skb_condense - try to get rid of fragments/frag_list if possible
6271 * Can be used to save memory before skb is added to a busy queue.
6272 * If packet has bytes in frags and enough tail room in skb->head,
6273 * pull all of them, so that we can free the frags right now and adjust
6276 * We do not reallocate skb->head thus can not fail.
6277 * Caller must re-evaluate skb->truesize if needed.
6279 void skb_condense(struct sk_buff *skb)
6281 if (skb->data_len) {
6282 if (skb->data_len > skb->end - skb->tail ||
6286 /* Nice, we can free page frag(s) right now */
6287 __pskb_pull_tail(skb, skb->data_len);
6289 /* At this point, skb->truesize might be over estimated,
6290 * because skb had a fragment, and fragments do not tell
6292 * When we pulled its content into skb->head, fragment
6293 * was freed, but __pskb_pull_tail() could not possibly
6294 * adjust skb->truesize, not knowing the frag truesize.
6296 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6299 #ifdef CONFIG_SKB_EXTENSIONS
6300 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6302 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6306 * __skb_ext_alloc - allocate a new skb extensions storage
6308 * @flags: See kmalloc().
6310 * Returns the newly allocated pointer. The pointer can later attached to a
6311 * skb via __skb_ext_set().
6312 * Note: caller must handle the skb_ext as an opaque data.
6314 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6316 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6319 memset(new->offset, 0, sizeof(new->offset));
6320 refcount_set(&new->refcnt, 1);
6326 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6327 unsigned int old_active)
6329 struct skb_ext *new;
6331 if (refcount_read(&old->refcnt) == 1)
6334 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6338 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6339 refcount_set(&new->refcnt, 1);
6342 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6343 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6346 for (i = 0; i < sp->len; i++)
6347 xfrm_state_hold(sp->xvec[i]);
6355 * __skb_ext_set - attach the specified extension storage to this skb
6358 * @ext: extension storage previously allocated via __skb_ext_alloc()
6360 * Existing extensions, if any, are cleared.
6362 * Returns the pointer to the extension.
6364 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6365 struct skb_ext *ext)
6367 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6370 newlen = newoff + skb_ext_type_len[id];
6371 ext->chunks = newlen;
6372 ext->offset[id] = newoff;
6373 skb->extensions = ext;
6374 skb->active_extensions = 1 << id;
6375 return skb_ext_get_ptr(ext, id);
6379 * skb_ext_add - allocate space for given extension, COW if needed
6381 * @id: extension to allocate space for
6383 * Allocates enough space for the given extension.
6384 * If the extension is already present, a pointer to that extension
6387 * If the skb was cloned, COW applies and the returned memory can be
6388 * modified without changing the extension space of clones buffers.
6390 * Returns pointer to the extension or NULL on allocation failure.
6392 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6394 struct skb_ext *new, *old = NULL;
6395 unsigned int newlen, newoff;
6397 if (skb->active_extensions) {
6398 old = skb->extensions;
6400 new = skb_ext_maybe_cow(old, skb->active_extensions);
6404 if (__skb_ext_exist(new, id))
6407 newoff = new->chunks;
6409 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6411 new = __skb_ext_alloc(GFP_ATOMIC);
6416 newlen = newoff + skb_ext_type_len[id];
6417 new->chunks = newlen;
6418 new->offset[id] = newoff;
6421 skb->extensions = new;
6422 skb->active_extensions |= 1 << id;
6423 return skb_ext_get_ptr(new, id);
6425 EXPORT_SYMBOL(skb_ext_add);
6428 static void skb_ext_put_sp(struct sec_path *sp)
6432 for (i = 0; i < sp->len; i++)
6433 xfrm_state_put(sp->xvec[i]);
6437 #ifdef CONFIG_MCTP_FLOWS
6438 static void skb_ext_put_mctp(struct mctp_flow *flow)
6441 mctp_key_unref(flow->key);
6445 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6447 struct skb_ext *ext = skb->extensions;
6449 skb->active_extensions &= ~(1 << id);
6450 if (skb->active_extensions == 0) {
6451 skb->extensions = NULL;
6454 } else if (id == SKB_EXT_SEC_PATH &&
6455 refcount_read(&ext->refcnt) == 1) {
6456 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6463 EXPORT_SYMBOL(__skb_ext_del);
6465 void __skb_ext_put(struct skb_ext *ext)
6467 /* If this is last clone, nothing can increment
6468 * it after check passes. Avoids one atomic op.
6470 if (refcount_read(&ext->refcnt) == 1)
6473 if (!refcount_dec_and_test(&ext->refcnt))
6477 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6478 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6480 #ifdef CONFIG_MCTP_FLOWS
6481 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6482 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6485 kmem_cache_free(skbuff_ext_cache, ext);
6487 EXPORT_SYMBOL(__skb_ext_put);
6488 #endif /* CONFIG_SKB_EXTENSIONS */
6491 * skb_attempt_defer_free - queue skb for remote freeing
6494 * Put @skb in a per-cpu list, using the cpu which
6495 * allocated the skb/pages to reduce false sharing
6496 * and memory zone spinlock contention.
6498 void skb_attempt_defer_free(struct sk_buff *skb)
6500 int cpu = skb->alloc_cpu;
6501 struct softnet_data *sd;
6502 unsigned long flags;
6503 unsigned int defer_max;
6506 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6508 cpu == raw_smp_processor_id()) {
6509 nodefer: __kfree_skb(skb);
6513 sd = &per_cpu(softnet_data, cpu);
6514 defer_max = READ_ONCE(sysctl_skb_defer_max);
6515 if (READ_ONCE(sd->defer_count) >= defer_max)
6518 spin_lock_irqsave(&sd->defer_lock, flags);
6519 /* Send an IPI every time queue reaches half capacity. */
6520 kick = sd->defer_count == (defer_max >> 1);
6521 /* Paired with the READ_ONCE() few lines above */
6522 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6524 skb->next = sd->defer_list;
6525 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6526 WRITE_ONCE(sd->defer_list, skb);
6527 spin_unlock_irqrestore(&sd->defer_lock, flags);
6529 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6530 * if we are unlucky enough (this seems very unlikely).
6532 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6533 smp_call_function_single_async(cpu, &sd->defer_csd);