1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Routines having to do with the 'struct sk_buff' memory handlers.
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))
187 skb = nc->skb_cache[--nc->skb_count];
188 kasan_unpoison_object_data(skbuff_head_cache, skb);
193 /* Caller must provide SKB that is memset cleared */
194 static void __build_skb_around(struct sk_buff *skb, void *data,
195 unsigned int frag_size)
197 struct skb_shared_info *shinfo;
198 unsigned int size = frag_size ? : ksize(data);
200 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
202 /* Assumes caller memset cleared SKB */
203 skb->truesize = SKB_TRUESIZE(size);
204 refcount_set(&skb->users, 1);
207 skb_reset_tail_pointer(skb);
208 skb_set_end_offset(skb, size);
209 skb->mac_header = (typeof(skb->mac_header))~0U;
210 skb->transport_header = (typeof(skb->transport_header))~0U;
211 skb->alloc_cpu = raw_smp_processor_id();
212 /* make sure we initialize shinfo sequentially */
213 shinfo = skb_shinfo(skb);
214 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
215 atomic_set(&shinfo->dataref, 1);
217 skb_set_kcov_handle(skb, kcov_common_handle());
221 * __build_skb - build a network buffer
222 * @data: data buffer provided by caller
223 * @frag_size: size of data, or 0 if head was kmalloced
225 * Allocate a new &sk_buff. Caller provides space holding head and
226 * skb_shared_info. @data must have been allocated by kmalloc() only if
227 * @frag_size is 0, otherwise data should come from the page allocator
229 * The return is the new skb buffer.
230 * On a failure the return is %NULL, and @data is not freed.
232 * Before IO, driver allocates only data buffer where NIC put incoming frame
233 * Driver should add room at head (NET_SKB_PAD) and
234 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
235 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
236 * before giving packet to stack.
237 * RX rings only contains data buffers, not full skbs.
239 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
243 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
247 memset(skb, 0, offsetof(struct sk_buff, tail));
248 __build_skb_around(skb, data, frag_size);
253 /* build_skb() is wrapper over __build_skb(), that specifically
254 * takes care of skb->head and skb->pfmemalloc
255 * This means that if @frag_size is not zero, then @data must be backed
256 * by a page fragment, not kmalloc() or vmalloc()
258 struct sk_buff *build_skb(void *data, unsigned int frag_size)
260 struct sk_buff *skb = __build_skb(data, frag_size);
262 if (skb && frag_size) {
264 if (page_is_pfmemalloc(virt_to_head_page(data)))
269 EXPORT_SYMBOL(build_skb);
272 * build_skb_around - build a network buffer around provided skb
273 * @skb: sk_buff provide by caller, must be memset cleared
274 * @data: data buffer provided by caller
275 * @frag_size: size of data, or 0 if head was kmalloced
277 struct sk_buff *build_skb_around(struct sk_buff *skb,
278 void *data, unsigned int frag_size)
283 __build_skb_around(skb, data, frag_size);
287 if (page_is_pfmemalloc(virt_to_head_page(data)))
292 EXPORT_SYMBOL(build_skb_around);
295 * __napi_build_skb - build a network buffer
296 * @data: data buffer provided by caller
297 * @frag_size: size of data, or 0 if head was kmalloced
299 * Version of __build_skb() that uses NAPI percpu caches to obtain
300 * skbuff_head instead of inplace allocation.
302 * Returns a new &sk_buff on success, %NULL on allocation failure.
304 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
308 skb = napi_skb_cache_get();
312 memset(skb, 0, offsetof(struct sk_buff, tail));
313 __build_skb_around(skb, data, frag_size);
319 * napi_build_skb - build a network buffer
320 * @data: data buffer provided by caller
321 * @frag_size: size of data, or 0 if head was kmalloced
323 * Version of __napi_build_skb() that takes care of skb->head_frag
324 * and skb->pfmemalloc when the data is a page or page fragment.
326 * Returns a new &sk_buff on success, %NULL on allocation failure.
328 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
330 struct sk_buff *skb = __napi_build_skb(data, frag_size);
332 if (likely(skb) && frag_size) {
334 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
339 EXPORT_SYMBOL(napi_build_skb);
342 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
343 * the caller if emergency pfmemalloc reserves are being used. If it is and
344 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
345 * may be used. Otherwise, the packet data may be discarded until enough
348 static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
352 bool ret_pfmemalloc = false;
355 * Try a regular allocation, when that fails and we're not entitled
356 * to the reserves, fail.
358 obj = kmalloc_node_track_caller(size,
359 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
361 if (obj || !(gfp_pfmemalloc_allowed(flags)))
364 /* Try again but now we are using pfmemalloc reserves */
365 ret_pfmemalloc = true;
366 obj = kmalloc_node_track_caller(size, flags, node);
370 *pfmemalloc = ret_pfmemalloc;
375 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
376 * 'private' fields and also do memory statistics to find all the
382 * __alloc_skb - allocate a network buffer
383 * @size: size to allocate
384 * @gfp_mask: allocation mask
385 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
386 * instead of head cache and allocate a cloned (child) skb.
387 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
388 * allocations in case the data is required for writeback
389 * @node: numa node to allocate memory on
391 * Allocate a new &sk_buff. The returned buffer has no headroom and a
392 * tail room of at least size bytes. The object has a reference count
393 * of one. The return is the buffer. On a failure the return is %NULL.
395 * Buffers may only be allocated from interrupts using a @gfp_mask of
398 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
401 struct kmem_cache *cache;
407 cache = (flags & SKB_ALLOC_FCLONE)
408 ? skbuff_fclone_cache : skbuff_head_cache;
410 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
411 gfp_mask |= __GFP_MEMALLOC;
414 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
415 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
416 skb = napi_skb_cache_get();
418 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
423 /* We do our best to align skb_shared_info on a separate cache
424 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
425 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
426 * Both skb->head and skb_shared_info are cache line aligned.
428 size = SKB_DATA_ALIGN(size);
429 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
430 data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
433 /* kmalloc(size) might give us more room than requested.
434 * Put skb_shared_info exactly at the end of allocated zone,
435 * to allow max possible filling before reallocation.
438 size = SKB_WITH_OVERHEAD(osize);
439 prefetchw(data + size);
442 * Only clear those fields we need to clear, not those that we will
443 * actually initialise below. Hence, don't put any more fields after
444 * the tail pointer in struct sk_buff!
446 memset(skb, 0, offsetof(struct sk_buff, tail));
447 __build_skb_around(skb, data, osize);
448 skb->pfmemalloc = pfmemalloc;
450 if (flags & SKB_ALLOC_FCLONE) {
451 struct sk_buff_fclones *fclones;
453 fclones = container_of(skb, struct sk_buff_fclones, skb1);
455 skb->fclone = SKB_FCLONE_ORIG;
456 refcount_set(&fclones->fclone_ref, 1);
462 kmem_cache_free(cache, skb);
465 EXPORT_SYMBOL(__alloc_skb);
468 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
469 * @dev: network device to receive on
470 * @len: length to allocate
471 * @gfp_mask: get_free_pages mask, passed to alloc_skb
473 * Allocate a new &sk_buff and assign it a usage count of one. The
474 * buffer has NET_SKB_PAD headroom built in. Users should allocate
475 * the headroom they think they need without accounting for the
476 * built in space. The built in space is used for optimisations.
478 * %NULL is returned if there is no free memory.
480 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
483 struct page_frag_cache *nc;
490 /* If requested length is either too small or too big,
491 * we use kmalloc() for skb->head allocation.
493 if (len <= SKB_WITH_OVERHEAD(1024) ||
494 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
495 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
496 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
502 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
503 len = SKB_DATA_ALIGN(len);
505 if (sk_memalloc_socks())
506 gfp_mask |= __GFP_MEMALLOC;
508 if (in_hardirq() || irqs_disabled()) {
509 nc = this_cpu_ptr(&netdev_alloc_cache);
510 data = page_frag_alloc(nc, len, gfp_mask);
511 pfmemalloc = nc->pfmemalloc;
514 nc = this_cpu_ptr(&napi_alloc_cache.page);
515 data = page_frag_alloc(nc, len, gfp_mask);
516 pfmemalloc = nc->pfmemalloc;
523 skb = __build_skb(data, len);
524 if (unlikely(!skb)) {
534 skb_reserve(skb, NET_SKB_PAD);
540 EXPORT_SYMBOL(__netdev_alloc_skb);
543 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
544 * @napi: napi instance this buffer was allocated for
545 * @len: length to allocate
546 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
548 * Allocate a new sk_buff for use in NAPI receive. This buffer will
549 * attempt to allocate the head from a special reserved region used
550 * only for NAPI Rx allocation. By doing this we can save several
551 * CPU cycles by avoiding having to disable and re-enable IRQs.
553 * %NULL is returned if there is no free memory.
555 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
558 struct napi_alloc_cache *nc;
562 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
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 if (skb_zcopy(skb)) {
673 bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
675 skb_zcopy_clear(skb, true);
680 for (i = 0; i < shinfo->nr_frags; i++)
681 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
684 if (shinfo->frag_list)
685 kfree_skb_list(shinfo->frag_list);
689 /* When we clone an SKB we copy the reycling bit. The pp_recycle
690 * bit is only set on the head though, so in order to avoid races
691 * while trying to recycle fragments on __skb_frag_unref() we need
692 * to make one SKB responsible for triggering the recycle path.
693 * So disable the recycling bit if an SKB is cloned and we have
694 * additional references to the fragmented part of the SKB.
695 * Eventually the last SKB will have the recycling bit set and it's
696 * dataref set to 0, which will trigger the recycling
702 * Free an skbuff by memory without cleaning the state.
704 static void kfree_skbmem(struct sk_buff *skb)
706 struct sk_buff_fclones *fclones;
708 switch (skb->fclone) {
709 case SKB_FCLONE_UNAVAILABLE:
710 kmem_cache_free(skbuff_head_cache, skb);
713 case SKB_FCLONE_ORIG:
714 fclones = container_of(skb, struct sk_buff_fclones, skb1);
716 /* We usually free the clone (TX completion) before original skb
717 * This test would have no chance to be true for the clone,
718 * while here, branch prediction will be good.
720 if (refcount_read(&fclones->fclone_ref) == 1)
724 default: /* SKB_FCLONE_CLONE */
725 fclones = container_of(skb, struct sk_buff_fclones, skb2);
728 if (!refcount_dec_and_test(&fclones->fclone_ref))
731 kmem_cache_free(skbuff_fclone_cache, fclones);
734 void skb_release_head_state(struct sk_buff *skb)
737 if (skb->destructor) {
738 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
739 skb->destructor(skb);
741 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
742 nf_conntrack_put(skb_nfct(skb));
747 /* Free everything but the sk_buff shell. */
748 static void skb_release_all(struct sk_buff *skb)
750 skb_release_head_state(skb);
751 if (likely(skb->head))
752 skb_release_data(skb);
756 * __kfree_skb - private function
759 * Free an sk_buff. Release anything attached to the buffer.
760 * Clean the state. This is an internal helper function. Users should
761 * always call kfree_skb
764 void __kfree_skb(struct sk_buff *skb)
766 skb_release_all(skb);
769 EXPORT_SYMBOL(__kfree_skb);
772 * kfree_skb_reason - free an sk_buff with special reason
773 * @skb: buffer to free
774 * @reason: reason why this skb is dropped
776 * Drop a reference to the buffer and free it if the usage count has
777 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
780 void kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
785 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
787 trace_kfree_skb(skb, __builtin_return_address(0), reason);
790 EXPORT_SYMBOL(kfree_skb_reason);
792 void kfree_skb_list_reason(struct sk_buff *segs,
793 enum skb_drop_reason reason)
796 struct sk_buff *next = segs->next;
798 kfree_skb_reason(segs, reason);
802 EXPORT_SYMBOL(kfree_skb_list_reason);
804 /* Dump skb information and contents.
806 * Must only be called from net_ratelimit()-ed paths.
808 * Dumps whole packets if full_pkt, only headers otherwise.
810 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
812 struct skb_shared_info *sh = skb_shinfo(skb);
813 struct net_device *dev = skb->dev;
814 struct sock *sk = skb->sk;
815 struct sk_buff *list_skb;
816 bool has_mac, has_trans;
817 int headroom, tailroom;
823 len = min_t(int, skb->len, MAX_HEADER + 128);
825 headroom = skb_headroom(skb);
826 tailroom = skb_tailroom(skb);
828 has_mac = skb_mac_header_was_set(skb);
829 has_trans = skb_transport_header_was_set(skb);
831 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
832 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
833 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
834 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
835 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
836 level, skb->len, headroom, skb_headlen(skb), tailroom,
837 has_mac ? skb->mac_header : -1,
838 has_mac ? skb_mac_header_len(skb) : -1,
840 has_trans ? skb_network_header_len(skb) : -1,
841 has_trans ? skb->transport_header : -1,
842 sh->tx_flags, sh->nr_frags,
843 sh->gso_size, sh->gso_type, sh->gso_segs,
844 skb->csum, skb->ip_summed, skb->csum_complete_sw,
845 skb->csum_valid, skb->csum_level,
846 skb->hash, skb->sw_hash, skb->l4_hash,
847 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
850 printk("%sdev name=%s feat=%pNF\n",
851 level, dev->name, &dev->features);
853 printk("%ssk family=%hu type=%u proto=%u\n",
854 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
856 if (full_pkt && headroom)
857 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
858 16, 1, skb->head, headroom, false);
860 seg_len = min_t(int, skb_headlen(skb), len);
862 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
863 16, 1, skb->data, seg_len, false);
866 if (full_pkt && tailroom)
867 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
868 16, 1, skb_tail_pointer(skb), tailroom, false);
870 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
871 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
872 u32 p_off, p_len, copied;
876 skb_frag_foreach_page(frag, skb_frag_off(frag),
877 skb_frag_size(frag), p, p_off, p_len,
879 seg_len = min_t(int, p_len, len);
880 vaddr = kmap_atomic(p);
881 print_hex_dump(level, "skb frag: ",
883 16, 1, vaddr + p_off, seg_len, false);
884 kunmap_atomic(vaddr);
891 if (full_pkt && skb_has_frag_list(skb)) {
892 printk("skb fraglist:\n");
893 skb_walk_frags(skb, list_skb)
894 skb_dump(level, list_skb, true);
897 EXPORT_SYMBOL(skb_dump);
900 * skb_tx_error - report an sk_buff xmit error
901 * @skb: buffer that triggered an error
903 * Report xmit error if a device callback is tracking this skb.
904 * skb must be freed afterwards.
906 void skb_tx_error(struct sk_buff *skb)
909 skb_zcopy_downgrade_managed(skb);
910 skb_zcopy_clear(skb, true);
913 EXPORT_SYMBOL(skb_tx_error);
915 #ifdef CONFIG_TRACEPOINTS
917 * consume_skb - free an skbuff
918 * @skb: buffer to free
920 * Drop a ref to the buffer and free it if the usage count has hit zero
921 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
922 * is being dropped after a failure and notes that
924 void consume_skb(struct sk_buff *skb)
929 trace_consume_skb(skb);
932 EXPORT_SYMBOL(consume_skb);
936 * __consume_stateless_skb - free an skbuff, assuming it is stateless
937 * @skb: buffer to free
939 * Alike consume_skb(), but this variant assumes that this is the last
940 * skb reference and all the head states have been already dropped
942 void __consume_stateless_skb(struct sk_buff *skb)
944 trace_consume_skb(skb);
945 skb_release_data(skb);
949 static void napi_skb_cache_put(struct sk_buff *skb)
951 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
954 kasan_poison_object_data(skbuff_head_cache, skb);
955 nc->skb_cache[nc->skb_count++] = skb;
957 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
958 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
959 kasan_unpoison_object_data(skbuff_head_cache,
962 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
963 nc->skb_cache + NAPI_SKB_CACHE_HALF);
964 nc->skb_count = NAPI_SKB_CACHE_HALF;
968 void __kfree_skb_defer(struct sk_buff *skb)
970 skb_release_all(skb);
971 napi_skb_cache_put(skb);
974 void napi_skb_free_stolen_head(struct sk_buff *skb)
976 if (unlikely(skb->slow_gro)) {
983 napi_skb_cache_put(skb);
986 void napi_consume_skb(struct sk_buff *skb, int budget)
988 /* Zero budget indicate non-NAPI context called us, like netpoll */
989 if (unlikely(!budget)) {
990 dev_consume_skb_any(skb);
994 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
999 /* if reaching here SKB is ready to free */
1000 trace_consume_skb(skb);
1002 /* if SKB is a clone, don't handle this case */
1003 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1008 skb_release_all(skb);
1009 napi_skb_cache_put(skb);
1011 EXPORT_SYMBOL(napi_consume_skb);
1013 /* Make sure a field is contained by headers group */
1014 #define CHECK_SKB_FIELD(field) \
1015 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1016 offsetof(struct sk_buff, headers.field)); \
1018 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1020 new->tstamp = old->tstamp;
1021 /* We do not copy old->sk */
1022 new->dev = old->dev;
1023 memcpy(new->cb, old->cb, sizeof(old->cb));
1024 skb_dst_copy(new, old);
1025 __skb_ext_copy(new, old);
1026 __nf_copy(new, old, false);
1028 /* Note : this field could be in the headers group.
1029 * It is not yet because we do not want to have a 16 bit hole
1031 new->queue_mapping = old->queue_mapping;
1033 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1034 CHECK_SKB_FIELD(protocol);
1035 CHECK_SKB_FIELD(csum);
1036 CHECK_SKB_FIELD(hash);
1037 CHECK_SKB_FIELD(priority);
1038 CHECK_SKB_FIELD(skb_iif);
1039 CHECK_SKB_FIELD(vlan_proto);
1040 CHECK_SKB_FIELD(vlan_tci);
1041 CHECK_SKB_FIELD(transport_header);
1042 CHECK_SKB_FIELD(network_header);
1043 CHECK_SKB_FIELD(mac_header);
1044 CHECK_SKB_FIELD(inner_protocol);
1045 CHECK_SKB_FIELD(inner_transport_header);
1046 CHECK_SKB_FIELD(inner_network_header);
1047 CHECK_SKB_FIELD(inner_mac_header);
1048 CHECK_SKB_FIELD(mark);
1049 #ifdef CONFIG_NETWORK_SECMARK
1050 CHECK_SKB_FIELD(secmark);
1052 #ifdef CONFIG_NET_RX_BUSY_POLL
1053 CHECK_SKB_FIELD(napi_id);
1055 CHECK_SKB_FIELD(alloc_cpu);
1057 CHECK_SKB_FIELD(sender_cpu);
1059 #ifdef CONFIG_NET_SCHED
1060 CHECK_SKB_FIELD(tc_index);
1066 * You should not add any new code to this function. Add it to
1067 * __copy_skb_header above instead.
1069 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1071 #define C(x) n->x = skb->x
1073 n->next = n->prev = NULL;
1075 __copy_skb_header(n, skb);
1080 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1086 n->destructor = NULL;
1093 refcount_set(&n->users, 1);
1095 atomic_inc(&(skb_shinfo(skb)->dataref));
1103 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1104 * @first: first sk_buff of the msg
1106 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1110 n = alloc_skb(0, GFP_ATOMIC);
1114 n->len = first->len;
1115 n->data_len = first->len;
1116 n->truesize = first->truesize;
1118 skb_shinfo(n)->frag_list = first;
1120 __copy_skb_header(n, first);
1121 n->destructor = NULL;
1125 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1128 * skb_morph - morph one skb into another
1129 * @dst: the skb to receive the contents
1130 * @src: the skb to supply the contents
1132 * This is identical to skb_clone except that the target skb is
1133 * supplied by the user.
1135 * The target skb is returned upon exit.
1137 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1139 skb_release_all(dst);
1140 return __skb_clone(dst, src);
1142 EXPORT_SYMBOL_GPL(skb_morph);
1144 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1146 unsigned long max_pg, num_pg, new_pg, old_pg;
1147 struct user_struct *user;
1149 if (capable(CAP_IPC_LOCK) || !size)
1152 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1153 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1154 user = mmp->user ? : current_user();
1157 old_pg = atomic_long_read(&user->locked_vm);
1158 new_pg = old_pg + num_pg;
1159 if (new_pg > max_pg)
1161 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1165 mmp->user = get_uid(user);
1166 mmp->num_pg = num_pg;
1168 mmp->num_pg += num_pg;
1173 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1175 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1178 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1179 free_uid(mmp->user);
1182 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1184 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1186 struct ubuf_info *uarg;
1187 struct sk_buff *skb;
1189 WARN_ON_ONCE(!in_task());
1191 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1195 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1196 uarg = (void *)skb->cb;
1197 uarg->mmp.user = NULL;
1199 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1204 uarg->callback = msg_zerocopy_callback;
1205 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1207 uarg->bytelen = size;
1209 uarg->flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1210 refcount_set(&uarg->refcnt, 1);
1216 static inline struct sk_buff *skb_from_uarg(struct ubuf_info *uarg)
1218 return container_of((void *)uarg, struct sk_buff, cb);
1221 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1222 struct ubuf_info *uarg)
1225 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1228 /* there might be non MSG_ZEROCOPY users */
1229 if (uarg->callback != msg_zerocopy_callback)
1232 /* realloc only when socket is locked (TCP, UDP cork),
1233 * so uarg->len and sk_zckey access is serialized
1235 if (!sock_owned_by_user(sk)) {
1240 bytelen = uarg->bytelen + size;
1241 if (uarg->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1242 /* TCP can create new skb to attach new uarg */
1243 if (sk->sk_type == SOCK_STREAM)
1248 next = (u32)atomic_read(&sk->sk_zckey);
1249 if ((u32)(uarg->id + uarg->len) == next) {
1250 if (mm_account_pinned_pages(&uarg->mmp, size))
1253 uarg->bytelen = bytelen;
1254 atomic_set(&sk->sk_zckey, ++next);
1256 /* no extra ref when appending to datagram (MSG_MORE) */
1257 if (sk->sk_type == SOCK_STREAM)
1258 net_zcopy_get(uarg);
1265 return msg_zerocopy_alloc(sk, size);
1267 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1269 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1271 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1275 old_lo = serr->ee.ee_info;
1276 old_hi = serr->ee.ee_data;
1277 sum_len = old_hi - old_lo + 1ULL + len;
1279 if (sum_len >= (1ULL << 32))
1282 if (lo != old_hi + 1)
1285 serr->ee.ee_data += len;
1289 static void __msg_zerocopy_callback(struct ubuf_info *uarg)
1291 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1292 struct sock_exterr_skb *serr;
1293 struct sock *sk = skb->sk;
1294 struct sk_buff_head *q;
1295 unsigned long flags;
1300 mm_unaccount_pinned_pages(&uarg->mmp);
1302 /* if !len, there was only 1 call, and it was aborted
1303 * so do not queue a completion notification
1305 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1310 hi = uarg->id + len - 1;
1311 is_zerocopy = uarg->zerocopy;
1313 serr = SKB_EXT_ERR(skb);
1314 memset(serr, 0, sizeof(*serr));
1315 serr->ee.ee_errno = 0;
1316 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1317 serr->ee.ee_data = hi;
1318 serr->ee.ee_info = lo;
1320 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1322 q = &sk->sk_error_queue;
1323 spin_lock_irqsave(&q->lock, flags);
1324 tail = skb_peek_tail(q);
1325 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1326 !skb_zerocopy_notify_extend(tail, lo, len)) {
1327 __skb_queue_tail(q, skb);
1330 spin_unlock_irqrestore(&q->lock, flags);
1332 sk_error_report(sk);
1339 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1342 uarg->zerocopy = uarg->zerocopy & success;
1344 if (refcount_dec_and_test(&uarg->refcnt))
1345 __msg_zerocopy_callback(uarg);
1347 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1349 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1351 struct sock *sk = skb_from_uarg(uarg)->sk;
1353 atomic_dec(&sk->sk_zckey);
1357 msg_zerocopy_callback(NULL, uarg, true);
1359 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1361 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1362 struct msghdr *msg, int len,
1363 struct ubuf_info *uarg)
1365 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1366 int err, orig_len = skb->len;
1368 /* An skb can only point to one uarg. This edge case happens when
1369 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1371 if (orig_uarg && uarg != orig_uarg)
1374 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1375 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1376 struct sock *save_sk = skb->sk;
1378 /* Streams do not free skb on error. Reset to prev state. */
1379 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1381 ___pskb_trim(skb, orig_len);
1386 skb_zcopy_set(skb, uarg, NULL);
1387 return skb->len - orig_len;
1389 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1391 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1395 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1396 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1397 skb_frag_ref(skb, i);
1399 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1401 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1404 if (skb_zcopy(orig)) {
1405 if (skb_zcopy(nskb)) {
1406 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1411 if (skb_uarg(nskb) == skb_uarg(orig))
1413 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1416 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1422 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1423 * @skb: the skb to modify
1424 * @gfp_mask: allocation priority
1426 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1427 * It will copy all frags into kernel and drop the reference
1428 * to userspace pages.
1430 * If this function is called from an interrupt gfp_mask() must be
1433 * Returns 0 on success or a negative error code on failure
1434 * to allocate kernel memory to copy to.
1436 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1438 int num_frags = skb_shinfo(skb)->nr_frags;
1439 struct page *page, *head = NULL;
1443 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1449 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1450 for (i = 0; i < new_frags; i++) {
1451 page = alloc_page(gfp_mask);
1454 struct page *next = (struct page *)page_private(head);
1460 set_page_private(page, (unsigned long)head);
1466 for (i = 0; i < num_frags; i++) {
1467 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1468 u32 p_off, p_len, copied;
1472 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1473 p, p_off, p_len, copied) {
1475 vaddr = kmap_atomic(p);
1477 while (done < p_len) {
1478 if (d_off == PAGE_SIZE) {
1480 page = (struct page *)page_private(page);
1482 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1483 memcpy(page_address(page) + d_off,
1484 vaddr + p_off + done, copy);
1488 kunmap_atomic(vaddr);
1492 /* skb frags release userspace buffers */
1493 for (i = 0; i < num_frags; i++)
1494 skb_frag_unref(skb, i);
1496 /* skb frags point to kernel buffers */
1497 for (i = 0; i < new_frags - 1; i++) {
1498 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1499 head = (struct page *)page_private(head);
1501 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1502 skb_shinfo(skb)->nr_frags = new_frags;
1505 skb_zcopy_clear(skb, false);
1508 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1511 * skb_clone - duplicate an sk_buff
1512 * @skb: buffer to clone
1513 * @gfp_mask: allocation priority
1515 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1516 * copies share the same packet data but not structure. The new
1517 * buffer has a reference count of 1. If the allocation fails the
1518 * function returns %NULL otherwise the new buffer is returned.
1520 * If this function is called from an interrupt gfp_mask() must be
1524 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1526 struct sk_buff_fclones *fclones = container_of(skb,
1527 struct sk_buff_fclones,
1531 if (skb_orphan_frags(skb, gfp_mask))
1534 if (skb->fclone == SKB_FCLONE_ORIG &&
1535 refcount_read(&fclones->fclone_ref) == 1) {
1537 refcount_set(&fclones->fclone_ref, 2);
1538 n->fclone = SKB_FCLONE_CLONE;
1540 if (skb_pfmemalloc(skb))
1541 gfp_mask |= __GFP_MEMALLOC;
1543 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1547 n->fclone = SKB_FCLONE_UNAVAILABLE;
1550 return __skb_clone(n, skb);
1552 EXPORT_SYMBOL(skb_clone);
1554 void skb_headers_offset_update(struct sk_buff *skb, int off)
1556 /* Only adjust this if it actually is csum_start rather than csum */
1557 if (skb->ip_summed == CHECKSUM_PARTIAL)
1558 skb->csum_start += off;
1559 /* {transport,network,mac}_header and tail are relative to skb->head */
1560 skb->transport_header += off;
1561 skb->network_header += off;
1562 if (skb_mac_header_was_set(skb))
1563 skb->mac_header += off;
1564 skb->inner_transport_header += off;
1565 skb->inner_network_header += off;
1566 skb->inner_mac_header += off;
1568 EXPORT_SYMBOL(skb_headers_offset_update);
1570 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1572 __copy_skb_header(new, old);
1574 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1575 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1576 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1578 EXPORT_SYMBOL(skb_copy_header);
1580 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1582 if (skb_pfmemalloc(skb))
1583 return SKB_ALLOC_RX;
1588 * skb_copy - create private copy of an sk_buff
1589 * @skb: buffer to copy
1590 * @gfp_mask: allocation priority
1592 * Make a copy of both an &sk_buff and its data. This is used when the
1593 * caller wishes to modify the data and needs a private copy of the
1594 * data to alter. Returns %NULL on failure or the pointer to the buffer
1595 * on success. The returned buffer has a reference count of 1.
1597 * As by-product this function converts non-linear &sk_buff to linear
1598 * one, so that &sk_buff becomes completely private and caller is allowed
1599 * to modify all the data of returned buffer. This means that this
1600 * function is not recommended for use in circumstances when only
1601 * header is going to be modified. Use pskb_copy() instead.
1604 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1606 int headerlen = skb_headroom(skb);
1607 unsigned int size = skb_end_offset(skb) + skb->data_len;
1608 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1609 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1614 /* Set the data pointer */
1615 skb_reserve(n, headerlen);
1616 /* Set the tail pointer and length */
1617 skb_put(n, skb->len);
1619 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1621 skb_copy_header(n, skb);
1624 EXPORT_SYMBOL(skb_copy);
1627 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1628 * @skb: buffer to copy
1629 * @headroom: headroom of new skb
1630 * @gfp_mask: allocation priority
1631 * @fclone: if true allocate the copy of the skb from the fclone
1632 * cache instead of the head cache; it is recommended to set this
1633 * to true for the cases where the copy will likely be cloned
1635 * Make a copy of both an &sk_buff and part of its data, located
1636 * in header. Fragmented data remain shared. This is used when
1637 * the caller wishes to modify only header of &sk_buff and needs
1638 * private copy of the header to alter. Returns %NULL on failure
1639 * or the pointer to the buffer on success.
1640 * The returned buffer has a reference count of 1.
1643 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1644 gfp_t gfp_mask, bool fclone)
1646 unsigned int size = skb_headlen(skb) + headroom;
1647 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1648 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1653 /* Set the data pointer */
1654 skb_reserve(n, headroom);
1655 /* Set the tail pointer and length */
1656 skb_put(n, skb_headlen(skb));
1657 /* Copy the bytes */
1658 skb_copy_from_linear_data(skb, n->data, n->len);
1660 n->truesize += skb->data_len;
1661 n->data_len = skb->data_len;
1664 if (skb_shinfo(skb)->nr_frags) {
1667 if (skb_orphan_frags(skb, gfp_mask) ||
1668 skb_zerocopy_clone(n, skb, gfp_mask)) {
1673 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1674 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1675 skb_frag_ref(skb, i);
1677 skb_shinfo(n)->nr_frags = i;
1680 if (skb_has_frag_list(skb)) {
1681 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1682 skb_clone_fraglist(n);
1685 skb_copy_header(n, skb);
1689 EXPORT_SYMBOL(__pskb_copy_fclone);
1692 * pskb_expand_head - reallocate header of &sk_buff
1693 * @skb: buffer to reallocate
1694 * @nhead: room to add at head
1695 * @ntail: room to add at tail
1696 * @gfp_mask: allocation priority
1698 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1699 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1700 * reference count of 1. Returns zero in the case of success or error,
1701 * if expansion failed. In the last case, &sk_buff is not changed.
1703 * All the pointers pointing into skb header may change and must be
1704 * reloaded after call to this function.
1707 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1710 int i, osize = skb_end_offset(skb);
1711 int size = osize + nhead + ntail;
1717 BUG_ON(skb_shared(skb));
1719 skb_zcopy_downgrade_managed(skb);
1721 size = SKB_DATA_ALIGN(size);
1723 if (skb_pfmemalloc(skb))
1724 gfp_mask |= __GFP_MEMALLOC;
1725 data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1726 gfp_mask, NUMA_NO_NODE, NULL);
1729 size = SKB_WITH_OVERHEAD(ksize(data));
1731 /* Copy only real data... and, alas, header. This should be
1732 * optimized for the cases when header is void.
1734 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1736 memcpy((struct skb_shared_info *)(data + size),
1738 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1741 * if shinfo is shared we must drop the old head gracefully, but if it
1742 * is not we can just drop the old head and let the existing refcount
1743 * be since all we did is relocate the values
1745 if (skb_cloned(skb)) {
1746 if (skb_orphan_frags(skb, gfp_mask))
1749 refcount_inc(&skb_uarg(skb)->refcnt);
1750 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1751 skb_frag_ref(skb, i);
1753 if (skb_has_frag_list(skb))
1754 skb_clone_fraglist(skb);
1756 skb_release_data(skb);
1760 off = (data + nhead) - skb->head;
1766 skb_set_end_offset(skb, size);
1767 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1771 skb_headers_offset_update(skb, nhead);
1775 atomic_set(&skb_shinfo(skb)->dataref, 1);
1777 skb_metadata_clear(skb);
1779 /* It is not generally safe to change skb->truesize.
1780 * For the moment, we really care of rx path, or
1781 * when skb is orphaned (not attached to a socket).
1783 if (!skb->sk || skb->destructor == sock_edemux)
1784 skb->truesize += size - osize;
1793 EXPORT_SYMBOL(pskb_expand_head);
1795 /* Make private copy of skb with writable head and some headroom */
1797 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1799 struct sk_buff *skb2;
1800 int delta = headroom - skb_headroom(skb);
1803 skb2 = pskb_copy(skb, GFP_ATOMIC);
1805 skb2 = skb_clone(skb, GFP_ATOMIC);
1806 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1814 EXPORT_SYMBOL(skb_realloc_headroom);
1816 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1818 unsigned int saved_end_offset, saved_truesize;
1819 struct skb_shared_info *shinfo;
1822 saved_end_offset = skb_end_offset(skb);
1823 saved_truesize = skb->truesize;
1825 res = pskb_expand_head(skb, 0, 0, pri);
1829 skb->truesize = saved_truesize;
1831 if (likely(skb_end_offset(skb) == saved_end_offset))
1834 shinfo = skb_shinfo(skb);
1836 /* We are about to change back skb->end,
1837 * we need to move skb_shinfo() to its new location.
1839 memmove(skb->head + saved_end_offset,
1841 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1843 skb_set_end_offset(skb, saved_end_offset);
1849 * skb_expand_head - reallocate header of &sk_buff
1850 * @skb: buffer to reallocate
1851 * @headroom: needed headroom
1853 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1854 * if possible; copies skb->sk to new skb as needed
1855 * and frees original skb in case of failures.
1857 * It expect increased headroom and generates warning otherwise.
1860 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1862 int delta = headroom - skb_headroom(skb);
1863 int osize = skb_end_offset(skb);
1864 struct sock *sk = skb->sk;
1866 if (WARN_ONCE(delta <= 0,
1867 "%s is expecting an increase in the headroom", __func__))
1870 delta = SKB_DATA_ALIGN(delta);
1871 /* pskb_expand_head() might crash, if skb is shared. */
1872 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1873 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1875 if (unlikely(!nskb))
1879 skb_set_owner_w(nskb, sk);
1883 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
1886 if (sk && is_skb_wmem(skb)) {
1887 delta = skb_end_offset(skb) - osize;
1888 refcount_add(delta, &sk->sk_wmem_alloc);
1889 skb->truesize += delta;
1897 EXPORT_SYMBOL(skb_expand_head);
1900 * skb_copy_expand - copy and expand sk_buff
1901 * @skb: buffer to copy
1902 * @newheadroom: new free bytes at head
1903 * @newtailroom: new free bytes at tail
1904 * @gfp_mask: allocation priority
1906 * Make a copy of both an &sk_buff and its data and while doing so
1907 * allocate additional space.
1909 * This is used when the caller wishes to modify the data and needs a
1910 * private copy of the data to alter as well as more space for new fields.
1911 * Returns %NULL on failure or the pointer to the buffer
1912 * on success. The returned buffer has a reference count of 1.
1914 * You must pass %GFP_ATOMIC as the allocation priority if this function
1915 * is called from an interrupt.
1917 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1918 int newheadroom, int newtailroom,
1922 * Allocate the copy buffer
1924 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1925 gfp_mask, skb_alloc_rx_flag(skb),
1927 int oldheadroom = skb_headroom(skb);
1928 int head_copy_len, head_copy_off;
1933 skb_reserve(n, newheadroom);
1935 /* Set the tail pointer and length */
1936 skb_put(n, skb->len);
1938 head_copy_len = oldheadroom;
1940 if (newheadroom <= head_copy_len)
1941 head_copy_len = newheadroom;
1943 head_copy_off = newheadroom - head_copy_len;
1945 /* Copy the linear header and data. */
1946 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1947 skb->len + head_copy_len));
1949 skb_copy_header(n, skb);
1951 skb_headers_offset_update(n, newheadroom - oldheadroom);
1955 EXPORT_SYMBOL(skb_copy_expand);
1958 * __skb_pad - zero pad the tail of an skb
1959 * @skb: buffer to pad
1960 * @pad: space to pad
1961 * @free_on_error: free buffer on error
1963 * Ensure that a buffer is followed by a padding area that is zero
1964 * filled. Used by network drivers which may DMA or transfer data
1965 * beyond the buffer end onto the wire.
1967 * May return error in out of memory cases. The skb is freed on error
1968 * if @free_on_error is true.
1971 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
1976 /* If the skbuff is non linear tailroom is always zero.. */
1977 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1978 memset(skb->data+skb->len, 0, pad);
1982 ntail = skb->data_len + pad - (skb->end - skb->tail);
1983 if (likely(skb_cloned(skb) || ntail > 0)) {
1984 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1989 /* FIXME: The use of this function with non-linear skb's really needs
1992 err = skb_linearize(skb);
1996 memset(skb->data + skb->len, 0, pad);
2004 EXPORT_SYMBOL(__skb_pad);
2007 * pskb_put - add data to the tail of a potentially fragmented buffer
2008 * @skb: start of the buffer to use
2009 * @tail: tail fragment of the buffer to use
2010 * @len: amount of data to add
2012 * This function extends the used data area of the potentially
2013 * fragmented buffer. @tail must be the last fragment of @skb -- or
2014 * @skb itself. If this would exceed the total buffer size the kernel
2015 * will panic. A pointer to the first byte of the extra data is
2019 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2022 skb->data_len += len;
2025 return skb_put(tail, len);
2027 EXPORT_SYMBOL_GPL(pskb_put);
2030 * skb_put - add data to a buffer
2031 * @skb: buffer to use
2032 * @len: amount of data to add
2034 * This function extends the used data area of the buffer. If this would
2035 * exceed the total buffer size the kernel will panic. A pointer to the
2036 * first byte of the extra data is returned.
2038 void *skb_put(struct sk_buff *skb, unsigned int len)
2040 void *tmp = skb_tail_pointer(skb);
2041 SKB_LINEAR_ASSERT(skb);
2044 if (unlikely(skb->tail > skb->end))
2045 skb_over_panic(skb, len, __builtin_return_address(0));
2048 EXPORT_SYMBOL(skb_put);
2051 * skb_push - add data to the start of a buffer
2052 * @skb: buffer to use
2053 * @len: amount of data to add
2055 * This function extends the used data area of the buffer at the buffer
2056 * start. If this would exceed the total buffer headroom the kernel will
2057 * panic. A pointer to the first byte of the extra data is returned.
2059 void *skb_push(struct sk_buff *skb, unsigned int len)
2063 if (unlikely(skb->data < skb->head))
2064 skb_under_panic(skb, len, __builtin_return_address(0));
2067 EXPORT_SYMBOL(skb_push);
2070 * skb_pull - remove data from the start of a buffer
2071 * @skb: buffer to use
2072 * @len: amount of data to remove
2074 * This function removes data from the start of a buffer, returning
2075 * the memory to the headroom. A pointer to the next data in the buffer
2076 * is returned. Once the data has been pulled future pushes will overwrite
2079 void *skb_pull(struct sk_buff *skb, unsigned int len)
2081 return skb_pull_inline(skb, len);
2083 EXPORT_SYMBOL(skb_pull);
2086 * skb_pull_data - remove data from the start of a buffer returning its
2087 * original position.
2088 * @skb: buffer to use
2089 * @len: amount of data to remove
2091 * This function removes data from the start of a buffer, returning
2092 * the memory to the headroom. A pointer to the original data in the buffer
2093 * is returned after checking if there is enough data to pull. Once the
2094 * data has been pulled future pushes will overwrite the old data.
2096 void *skb_pull_data(struct sk_buff *skb, size_t len)
2098 void *data = skb->data;
2107 EXPORT_SYMBOL(skb_pull_data);
2110 * skb_trim - remove end from a buffer
2111 * @skb: buffer to alter
2114 * Cut the length of a buffer down by removing data from the tail. If
2115 * the buffer is already under the length specified it is not modified.
2116 * The skb must be linear.
2118 void skb_trim(struct sk_buff *skb, unsigned int len)
2121 __skb_trim(skb, len);
2123 EXPORT_SYMBOL(skb_trim);
2125 /* Trims skb to length len. It can change skb pointers.
2128 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2130 struct sk_buff **fragp;
2131 struct sk_buff *frag;
2132 int offset = skb_headlen(skb);
2133 int nfrags = skb_shinfo(skb)->nr_frags;
2137 if (skb_cloned(skb) &&
2138 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2145 for (; i < nfrags; i++) {
2146 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2153 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2156 skb_shinfo(skb)->nr_frags = i;
2158 for (; i < nfrags; i++)
2159 skb_frag_unref(skb, i);
2161 if (skb_has_frag_list(skb))
2162 skb_drop_fraglist(skb);
2166 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2167 fragp = &frag->next) {
2168 int end = offset + frag->len;
2170 if (skb_shared(frag)) {
2171 struct sk_buff *nfrag;
2173 nfrag = skb_clone(frag, GFP_ATOMIC);
2174 if (unlikely(!nfrag))
2177 nfrag->next = frag->next;
2189 unlikely((err = pskb_trim(frag, len - offset))))
2193 skb_drop_list(&frag->next);
2198 if (len > skb_headlen(skb)) {
2199 skb->data_len -= skb->len - len;
2204 skb_set_tail_pointer(skb, len);
2207 if (!skb->sk || skb->destructor == sock_edemux)
2211 EXPORT_SYMBOL(___pskb_trim);
2213 /* Note : use pskb_trim_rcsum() instead of calling this directly
2215 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2217 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2218 int delta = skb->len - len;
2220 skb->csum = csum_block_sub(skb->csum,
2221 skb_checksum(skb, len, delta, 0),
2223 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2224 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2225 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2227 if (offset + sizeof(__sum16) > hdlen)
2230 return __pskb_trim(skb, len);
2232 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2235 * __pskb_pull_tail - advance tail of skb header
2236 * @skb: buffer to reallocate
2237 * @delta: number of bytes to advance tail
2239 * The function makes a sense only on a fragmented &sk_buff,
2240 * it expands header moving its tail forward and copying necessary
2241 * data from fragmented part.
2243 * &sk_buff MUST have reference count of 1.
2245 * Returns %NULL (and &sk_buff does not change) if pull failed
2246 * or value of new tail of skb in the case of success.
2248 * All the pointers pointing into skb header may change and must be
2249 * reloaded after call to this function.
2252 /* Moves tail of skb head forward, copying data from fragmented part,
2253 * when it is necessary.
2254 * 1. It may fail due to malloc failure.
2255 * 2. It may change skb pointers.
2257 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2259 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2261 /* If skb has not enough free space at tail, get new one
2262 * plus 128 bytes for future expansions. If we have enough
2263 * room at tail, reallocate without expansion only if skb is cloned.
2265 int i, k, eat = (skb->tail + delta) - skb->end;
2267 if (eat > 0 || skb_cloned(skb)) {
2268 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2273 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2274 skb_tail_pointer(skb), delta));
2276 /* Optimization: no fragments, no reasons to preestimate
2277 * size of pulled pages. Superb.
2279 if (!skb_has_frag_list(skb))
2282 /* Estimate size of pulled pages. */
2284 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2285 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2292 /* If we need update frag list, we are in troubles.
2293 * Certainly, it is possible to add an offset to skb data,
2294 * but taking into account that pulling is expected to
2295 * be very rare operation, it is worth to fight against
2296 * further bloating skb head and crucify ourselves here instead.
2297 * Pure masohism, indeed. 8)8)
2300 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2301 struct sk_buff *clone = NULL;
2302 struct sk_buff *insp = NULL;
2305 if (list->len <= eat) {
2306 /* Eaten as whole. */
2311 /* Eaten partially. */
2313 if (skb_shared(list)) {
2314 /* Sucks! We need to fork list. :-( */
2315 clone = skb_clone(list, GFP_ATOMIC);
2321 /* This may be pulled without
2325 if (!pskb_pull(list, eat)) {
2333 /* Free pulled out fragments. */
2334 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2335 skb_shinfo(skb)->frag_list = list->next;
2338 /* And insert new clone at head. */
2341 skb_shinfo(skb)->frag_list = clone;
2344 /* Success! Now we may commit changes to skb data. */
2349 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2350 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2353 skb_frag_unref(skb, i);
2356 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2358 *frag = skb_shinfo(skb)->frags[i];
2360 skb_frag_off_add(frag, eat);
2361 skb_frag_size_sub(frag, eat);
2369 skb_shinfo(skb)->nr_frags = k;
2373 skb->data_len -= delta;
2376 skb_zcopy_clear(skb, false);
2378 return skb_tail_pointer(skb);
2380 EXPORT_SYMBOL(__pskb_pull_tail);
2383 * skb_copy_bits - copy bits from skb to kernel buffer
2385 * @offset: offset in source
2386 * @to: destination buffer
2387 * @len: number of bytes to copy
2389 * Copy the specified number of bytes from the source skb to the
2390 * destination buffer.
2393 * If its prototype is ever changed,
2394 * check arch/{*}/net/{*}.S files,
2395 * since it is called from BPF assembly code.
2397 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2399 int start = skb_headlen(skb);
2400 struct sk_buff *frag_iter;
2403 if (offset > (int)skb->len - len)
2407 if ((copy = start - offset) > 0) {
2410 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2411 if ((len -= copy) == 0)
2417 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2419 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2421 WARN_ON(start > offset + len);
2423 end = start + skb_frag_size(f);
2424 if ((copy = end - offset) > 0) {
2425 u32 p_off, p_len, copied;
2432 skb_frag_foreach_page(f,
2433 skb_frag_off(f) + offset - start,
2434 copy, p, p_off, p_len, copied) {
2435 vaddr = kmap_atomic(p);
2436 memcpy(to + copied, vaddr + p_off, p_len);
2437 kunmap_atomic(vaddr);
2440 if ((len -= copy) == 0)
2448 skb_walk_frags(skb, frag_iter) {
2451 WARN_ON(start > offset + len);
2453 end = start + frag_iter->len;
2454 if ((copy = end - offset) > 0) {
2457 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2459 if ((len -= copy) == 0)
2473 EXPORT_SYMBOL(skb_copy_bits);
2476 * Callback from splice_to_pipe(), if we need to release some pages
2477 * at the end of the spd in case we error'ed out in filling the pipe.
2479 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2481 put_page(spd->pages[i]);
2484 static struct page *linear_to_page(struct page *page, unsigned int *len,
2485 unsigned int *offset,
2488 struct page_frag *pfrag = sk_page_frag(sk);
2490 if (!sk_page_frag_refill(sk, pfrag))
2493 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2495 memcpy(page_address(pfrag->page) + pfrag->offset,
2496 page_address(page) + *offset, *len);
2497 *offset = pfrag->offset;
2498 pfrag->offset += *len;
2503 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2505 unsigned int offset)
2507 return spd->nr_pages &&
2508 spd->pages[spd->nr_pages - 1] == page &&
2509 (spd->partial[spd->nr_pages - 1].offset +
2510 spd->partial[spd->nr_pages - 1].len == offset);
2514 * Fill page/offset/length into spd, if it can hold more pages.
2516 static bool spd_fill_page(struct splice_pipe_desc *spd,
2517 struct pipe_inode_info *pipe, struct page *page,
2518 unsigned int *len, unsigned int offset,
2522 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2526 page = linear_to_page(page, len, &offset, sk);
2530 if (spd_can_coalesce(spd, page, offset)) {
2531 spd->partial[spd->nr_pages - 1].len += *len;
2535 spd->pages[spd->nr_pages] = page;
2536 spd->partial[spd->nr_pages].len = *len;
2537 spd->partial[spd->nr_pages].offset = offset;
2543 static bool __splice_segment(struct page *page, unsigned int poff,
2544 unsigned int plen, unsigned int *off,
2546 struct splice_pipe_desc *spd, bool linear,
2548 struct pipe_inode_info *pipe)
2553 /* skip this segment if already processed */
2559 /* ignore any bits we already processed */
2565 unsigned int flen = min(*len, plen);
2567 if (spd_fill_page(spd, pipe, page, &flen, poff,
2573 } while (*len && plen);
2579 * Map linear and fragment data from the skb to spd. It reports true if the
2580 * pipe is full or if we already spliced the requested length.
2582 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2583 unsigned int *offset, unsigned int *len,
2584 struct splice_pipe_desc *spd, struct sock *sk)
2587 struct sk_buff *iter;
2589 /* map the linear part :
2590 * If skb->head_frag is set, this 'linear' part is backed by a
2591 * fragment, and if the head is not shared with any clones then
2592 * we can avoid a copy since we own the head portion of this page.
2594 if (__splice_segment(virt_to_page(skb->data),
2595 (unsigned long) skb->data & (PAGE_SIZE - 1),
2598 skb_head_is_locked(skb),
2603 * then map the fragments
2605 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2606 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2608 if (__splice_segment(skb_frag_page(f),
2609 skb_frag_off(f), skb_frag_size(f),
2610 offset, len, spd, false, sk, pipe))
2614 skb_walk_frags(skb, iter) {
2615 if (*offset >= iter->len) {
2616 *offset -= iter->len;
2619 /* __skb_splice_bits() only fails if the output has no room
2620 * left, so no point in going over the frag_list for the error
2623 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2631 * Map data from the skb to a pipe. Should handle both the linear part,
2632 * the fragments, and the frag list.
2634 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2635 struct pipe_inode_info *pipe, unsigned int tlen,
2638 struct partial_page partial[MAX_SKB_FRAGS];
2639 struct page *pages[MAX_SKB_FRAGS];
2640 struct splice_pipe_desc spd = {
2643 .nr_pages_max = MAX_SKB_FRAGS,
2644 .ops = &nosteal_pipe_buf_ops,
2645 .spd_release = sock_spd_release,
2649 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2652 ret = splice_to_pipe(pipe, &spd);
2656 EXPORT_SYMBOL_GPL(skb_splice_bits);
2658 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2659 struct kvec *vec, size_t num, size_t size)
2661 struct socket *sock = sk->sk_socket;
2665 return kernel_sendmsg(sock, msg, vec, num, size);
2668 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2669 size_t size, int flags)
2671 struct socket *sock = sk->sk_socket;
2675 return kernel_sendpage(sock, page, offset, size, flags);
2678 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2679 struct kvec *vec, size_t num, size_t size);
2680 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2681 size_t size, int flags);
2682 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2683 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2685 unsigned int orig_len = len;
2686 struct sk_buff *head = skb;
2687 unsigned short fragidx;
2692 /* Deal with head data */
2693 while (offset < skb_headlen(skb) && len) {
2697 slen = min_t(int, len, skb_headlen(skb) - offset);
2698 kv.iov_base = skb->data + offset;
2700 memset(&msg, 0, sizeof(msg));
2701 msg.msg_flags = MSG_DONTWAIT;
2703 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2704 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2712 /* All the data was skb head? */
2716 /* Make offset relative to start of frags */
2717 offset -= skb_headlen(skb);
2719 /* Find where we are in frag list */
2720 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2721 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2723 if (offset < skb_frag_size(frag))
2726 offset -= skb_frag_size(frag);
2729 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2730 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2732 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2735 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2736 sendpage_unlocked, sk,
2737 skb_frag_page(frag),
2738 skb_frag_off(frag) + offset,
2739 slen, MSG_DONTWAIT);
2752 /* Process any frag lists */
2755 if (skb_has_frag_list(skb)) {
2756 skb = skb_shinfo(skb)->frag_list;
2759 } else if (skb->next) {
2766 return orig_len - len;
2769 return orig_len == len ? ret : orig_len - len;
2772 /* Send skb data on a socket. Socket must be locked. */
2773 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2776 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2777 kernel_sendpage_locked);
2779 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2781 /* Send skb data on a socket. Socket must be unlocked. */
2782 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2784 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2789 * skb_store_bits - store bits from kernel buffer to skb
2790 * @skb: destination buffer
2791 * @offset: offset in destination
2792 * @from: source buffer
2793 * @len: number of bytes to copy
2795 * Copy the specified number of bytes from the source buffer to the
2796 * destination skb. This function handles all the messy bits of
2797 * traversing fragment lists and such.
2800 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2802 int start = skb_headlen(skb);
2803 struct sk_buff *frag_iter;
2806 if (offset > (int)skb->len - len)
2809 if ((copy = start - offset) > 0) {
2812 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2813 if ((len -= copy) == 0)
2819 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2820 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2823 WARN_ON(start > offset + len);
2825 end = start + skb_frag_size(frag);
2826 if ((copy = end - offset) > 0) {
2827 u32 p_off, p_len, copied;
2834 skb_frag_foreach_page(frag,
2835 skb_frag_off(frag) + offset - start,
2836 copy, p, p_off, p_len, copied) {
2837 vaddr = kmap_atomic(p);
2838 memcpy(vaddr + p_off, from + copied, p_len);
2839 kunmap_atomic(vaddr);
2842 if ((len -= copy) == 0)
2850 skb_walk_frags(skb, frag_iter) {
2853 WARN_ON(start > offset + len);
2855 end = start + frag_iter->len;
2856 if ((copy = end - offset) > 0) {
2859 if (skb_store_bits(frag_iter, offset - start,
2862 if ((len -= copy) == 0)
2875 EXPORT_SYMBOL(skb_store_bits);
2877 /* Checksum skb data. */
2878 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2879 __wsum csum, const struct skb_checksum_ops *ops)
2881 int start = skb_headlen(skb);
2882 int i, copy = start - offset;
2883 struct sk_buff *frag_iter;
2886 /* Checksum header. */
2890 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
2891 skb->data + offset, copy, csum);
2892 if ((len -= copy) == 0)
2898 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2900 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2902 WARN_ON(start > offset + len);
2904 end = start + skb_frag_size(frag);
2905 if ((copy = end - offset) > 0) {
2906 u32 p_off, p_len, copied;
2914 skb_frag_foreach_page(frag,
2915 skb_frag_off(frag) + offset - start,
2916 copy, p, p_off, p_len, copied) {
2917 vaddr = kmap_atomic(p);
2918 csum2 = INDIRECT_CALL_1(ops->update,
2920 vaddr + p_off, p_len, 0);
2921 kunmap_atomic(vaddr);
2922 csum = INDIRECT_CALL_1(ops->combine,
2923 csum_block_add_ext, csum,
2935 skb_walk_frags(skb, frag_iter) {
2938 WARN_ON(start > offset + len);
2940 end = start + frag_iter->len;
2941 if ((copy = end - offset) > 0) {
2945 csum2 = __skb_checksum(frag_iter, offset - start,
2947 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
2948 csum, csum2, pos, copy);
2949 if ((len -= copy) == 0)
2960 EXPORT_SYMBOL(__skb_checksum);
2962 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2963 int len, __wsum csum)
2965 const struct skb_checksum_ops ops = {
2966 .update = csum_partial_ext,
2967 .combine = csum_block_add_ext,
2970 return __skb_checksum(skb, offset, len, csum, &ops);
2972 EXPORT_SYMBOL(skb_checksum);
2974 /* Both of above in one bottle. */
2976 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2979 int start = skb_headlen(skb);
2980 int i, copy = start - offset;
2981 struct sk_buff *frag_iter;
2989 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2991 if ((len -= copy) == 0)
2998 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3001 WARN_ON(start > offset + len);
3003 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3004 if ((copy = end - offset) > 0) {
3005 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3006 u32 p_off, p_len, copied;
3014 skb_frag_foreach_page(frag,
3015 skb_frag_off(frag) + offset - start,
3016 copy, p, p_off, p_len, copied) {
3017 vaddr = kmap_atomic(p);
3018 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3021 kunmap_atomic(vaddr);
3022 csum = csum_block_add(csum, csum2, pos);
3034 skb_walk_frags(skb, frag_iter) {
3038 WARN_ON(start > offset + len);
3040 end = start + frag_iter->len;
3041 if ((copy = end - offset) > 0) {
3044 csum2 = skb_copy_and_csum_bits(frag_iter,
3047 csum = csum_block_add(csum, csum2, pos);
3048 if ((len -= copy) == 0)
3059 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3061 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3065 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3066 /* See comments in __skb_checksum_complete(). */
3068 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3069 !skb->csum_complete_sw)
3070 netdev_rx_csum_fault(skb->dev, skb);
3072 if (!skb_shared(skb))
3073 skb->csum_valid = !sum;
3076 EXPORT_SYMBOL(__skb_checksum_complete_head);
3078 /* This function assumes skb->csum already holds pseudo header's checksum,
3079 * which has been changed from the hardware checksum, for example, by
3080 * __skb_checksum_validate_complete(). And, the original skb->csum must
3081 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3083 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3084 * zero. The new checksum is stored back into skb->csum unless the skb is
3087 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3092 csum = skb_checksum(skb, 0, skb->len, 0);
3094 sum = csum_fold(csum_add(skb->csum, csum));
3095 /* This check is inverted, because we already knew the hardware
3096 * checksum is invalid before calling this function. So, if the
3097 * re-computed checksum is valid instead, then we have a mismatch
3098 * between the original skb->csum and skb_checksum(). This means either
3099 * the original hardware checksum is incorrect or we screw up skb->csum
3100 * when moving skb->data around.
3103 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3104 !skb->csum_complete_sw)
3105 netdev_rx_csum_fault(skb->dev, skb);
3108 if (!skb_shared(skb)) {
3109 /* Save full packet checksum */
3111 skb->ip_summed = CHECKSUM_COMPLETE;
3112 skb->csum_complete_sw = 1;
3113 skb->csum_valid = !sum;
3118 EXPORT_SYMBOL(__skb_checksum_complete);
3120 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3122 net_warn_ratelimited(
3123 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3128 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3129 int offset, int len)
3131 net_warn_ratelimited(
3132 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3137 static const struct skb_checksum_ops default_crc32c_ops = {
3138 .update = warn_crc32c_csum_update,
3139 .combine = warn_crc32c_csum_combine,
3142 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3143 &default_crc32c_ops;
3144 EXPORT_SYMBOL(crc32c_csum_stub);
3147 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3148 * @from: source buffer
3150 * Calculates the amount of linear headroom needed in the 'to' skb passed
3151 * into skb_zerocopy().
3154 skb_zerocopy_headlen(const struct sk_buff *from)
3156 unsigned int hlen = 0;
3158 if (!from->head_frag ||
3159 skb_headlen(from) < L1_CACHE_BYTES ||
3160 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3161 hlen = skb_headlen(from);
3166 if (skb_has_frag_list(from))
3171 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3174 * skb_zerocopy - Zero copy skb to skb
3175 * @to: destination buffer
3176 * @from: source buffer
3177 * @len: number of bytes to copy from source buffer
3178 * @hlen: size of linear headroom in destination buffer
3180 * Copies up to `len` bytes from `from` to `to` by creating references
3181 * to the frags in the source buffer.
3183 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3184 * headroom in the `to` buffer.
3187 * 0: everything is OK
3188 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3189 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3192 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3195 int plen = 0; /* length of skb->head fragment */
3198 unsigned int offset;
3200 BUG_ON(!from->head_frag && !hlen);
3202 /* dont bother with small payloads */
3203 if (len <= skb_tailroom(to))
3204 return skb_copy_bits(from, 0, skb_put(to, len), len);
3207 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3212 plen = min_t(int, skb_headlen(from), len);
3214 page = virt_to_head_page(from->head);
3215 offset = from->data - (unsigned char *)page_address(page);
3216 __skb_fill_page_desc(to, 0, page, offset, plen);
3223 skb_len_add(to, len + plen);
3225 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3229 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3231 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3236 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3237 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3239 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3241 skb_frag_ref(to, j);
3244 skb_shinfo(to)->nr_frags = j;
3248 EXPORT_SYMBOL_GPL(skb_zerocopy);
3250 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3255 if (skb->ip_summed == CHECKSUM_PARTIAL)
3256 csstart = skb_checksum_start_offset(skb);
3258 csstart = skb_headlen(skb);
3260 BUG_ON(csstart > skb_headlen(skb));
3262 skb_copy_from_linear_data(skb, to, csstart);
3265 if (csstart != skb->len)
3266 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3267 skb->len - csstart);
3269 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3270 long csstuff = csstart + skb->csum_offset;
3272 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3275 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3278 * skb_dequeue - remove from the head of the queue
3279 * @list: list to dequeue from
3281 * Remove the head of the list. The list lock is taken so the function
3282 * may be used safely with other locking list functions. The head item is
3283 * returned or %NULL if the list is empty.
3286 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3288 unsigned long flags;
3289 struct sk_buff *result;
3291 spin_lock_irqsave(&list->lock, flags);
3292 result = __skb_dequeue(list);
3293 spin_unlock_irqrestore(&list->lock, flags);
3296 EXPORT_SYMBOL(skb_dequeue);
3299 * skb_dequeue_tail - remove from the tail of the queue
3300 * @list: list to dequeue from
3302 * Remove the tail of the list. The list lock is taken so the function
3303 * may be used safely with other locking list functions. The tail item is
3304 * returned or %NULL if the list is empty.
3306 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3308 unsigned long flags;
3309 struct sk_buff *result;
3311 spin_lock_irqsave(&list->lock, flags);
3312 result = __skb_dequeue_tail(list);
3313 spin_unlock_irqrestore(&list->lock, flags);
3316 EXPORT_SYMBOL(skb_dequeue_tail);
3319 * skb_queue_purge - empty a list
3320 * @list: list to empty
3322 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3323 * the list and one reference dropped. This function takes the list
3324 * lock and is atomic with respect to other list locking functions.
3326 void skb_queue_purge(struct sk_buff_head *list)
3328 struct sk_buff *skb;
3329 while ((skb = skb_dequeue(list)) != NULL)
3332 EXPORT_SYMBOL(skb_queue_purge);
3335 * skb_rbtree_purge - empty a skb rbtree
3336 * @root: root of the rbtree to empty
3337 * Return value: the sum of truesizes of all purged skbs.
3339 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3340 * the list and one reference dropped. This function does not take
3341 * any lock. Synchronization should be handled by the caller (e.g., TCP
3342 * out-of-order queue is protected by the socket lock).
3344 unsigned int skb_rbtree_purge(struct rb_root *root)
3346 struct rb_node *p = rb_first(root);
3347 unsigned int sum = 0;
3350 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3353 rb_erase(&skb->rbnode, root);
3354 sum += skb->truesize;
3361 * skb_queue_head - queue a buffer at the list head
3362 * @list: list to use
3363 * @newsk: buffer to queue
3365 * Queue a buffer at the start of the list. This function takes the
3366 * list lock and can be used safely with other locking &sk_buff functions
3369 * A buffer cannot be placed on two lists at the same time.
3371 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3373 unsigned long flags;
3375 spin_lock_irqsave(&list->lock, flags);
3376 __skb_queue_head(list, newsk);
3377 spin_unlock_irqrestore(&list->lock, flags);
3379 EXPORT_SYMBOL(skb_queue_head);
3382 * skb_queue_tail - queue a buffer at the list tail
3383 * @list: list to use
3384 * @newsk: buffer to queue
3386 * Queue a buffer at the tail of the list. This function takes the
3387 * list lock and can be used safely with other locking &sk_buff functions
3390 * A buffer cannot be placed on two lists at the same time.
3392 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3394 unsigned long flags;
3396 spin_lock_irqsave(&list->lock, flags);
3397 __skb_queue_tail(list, newsk);
3398 spin_unlock_irqrestore(&list->lock, flags);
3400 EXPORT_SYMBOL(skb_queue_tail);
3403 * skb_unlink - remove a buffer from a list
3404 * @skb: buffer to remove
3405 * @list: list to use
3407 * Remove a packet from a list. The list locks are taken and this
3408 * function is atomic with respect to other list locked calls
3410 * You must know what list the SKB is on.
3412 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3414 unsigned long flags;
3416 spin_lock_irqsave(&list->lock, flags);
3417 __skb_unlink(skb, list);
3418 spin_unlock_irqrestore(&list->lock, flags);
3420 EXPORT_SYMBOL(skb_unlink);
3423 * skb_append - append a buffer
3424 * @old: buffer to insert after
3425 * @newsk: buffer to insert
3426 * @list: list to use
3428 * Place a packet after a given packet in a list. The list locks are taken
3429 * and this function is atomic with respect to other list locked calls.
3430 * A buffer cannot be placed on two lists at the same time.
3432 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3434 unsigned long flags;
3436 spin_lock_irqsave(&list->lock, flags);
3437 __skb_queue_after(list, old, newsk);
3438 spin_unlock_irqrestore(&list->lock, flags);
3440 EXPORT_SYMBOL(skb_append);
3442 static inline void skb_split_inside_header(struct sk_buff *skb,
3443 struct sk_buff* skb1,
3444 const u32 len, const int pos)
3448 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3450 /* And move data appendix as is. */
3451 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3452 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3454 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3455 skb_shinfo(skb)->nr_frags = 0;
3456 skb1->data_len = skb->data_len;
3457 skb1->len += skb1->data_len;
3460 skb_set_tail_pointer(skb, len);
3463 static inline void skb_split_no_header(struct sk_buff *skb,
3464 struct sk_buff* skb1,
3465 const u32 len, int pos)
3468 const int nfrags = skb_shinfo(skb)->nr_frags;
3470 skb_shinfo(skb)->nr_frags = 0;
3471 skb1->len = skb1->data_len = skb->len - len;
3473 skb->data_len = len - pos;
3475 for (i = 0; i < nfrags; i++) {
3476 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3478 if (pos + size > len) {
3479 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3483 * We have two variants in this case:
3484 * 1. Move all the frag to the second
3485 * part, if it is possible. F.e.
3486 * this approach is mandatory for TUX,
3487 * where splitting is expensive.
3488 * 2. Split is accurately. We make this.
3490 skb_frag_ref(skb, i);
3491 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3492 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3493 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3494 skb_shinfo(skb)->nr_frags++;
3498 skb_shinfo(skb)->nr_frags++;
3501 skb_shinfo(skb1)->nr_frags = k;
3505 * skb_split - Split fragmented skb to two parts at length len.
3506 * @skb: the buffer to split
3507 * @skb1: the buffer to receive the second part
3508 * @len: new length for skb
3510 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3512 int pos = skb_headlen(skb);
3513 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3515 skb_zcopy_downgrade_managed(skb);
3517 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3518 skb_zerocopy_clone(skb1, skb, 0);
3519 if (len < pos) /* Split line is inside header. */
3520 skb_split_inside_header(skb, skb1, len, pos);
3521 else /* Second chunk has no header, nothing to copy. */
3522 skb_split_no_header(skb, skb1, len, pos);
3524 EXPORT_SYMBOL(skb_split);
3526 /* Shifting from/to a cloned skb is a no-go.
3528 * Caller cannot keep skb_shinfo related pointers past calling here!
3530 static int skb_prepare_for_shift(struct sk_buff *skb)
3532 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3536 * skb_shift - Shifts paged data partially from skb to another
3537 * @tgt: buffer into which tail data gets added
3538 * @skb: buffer from which the paged data comes from
3539 * @shiftlen: shift up to this many bytes
3541 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3542 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3543 * It's up to caller to free skb if everything was shifted.
3545 * If @tgt runs out of frags, the whole operation is aborted.
3547 * Skb cannot include anything else but paged data while tgt is allowed
3548 * to have non-paged data as well.
3550 * TODO: full sized shift could be optimized but that would need
3551 * specialized skb free'er to handle frags without up-to-date nr_frags.
3553 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3555 int from, to, merge, todo;
3556 skb_frag_t *fragfrom, *fragto;
3558 BUG_ON(shiftlen > skb->len);
3560 if (skb_headlen(skb))
3562 if (skb_zcopy(tgt) || skb_zcopy(skb))
3567 to = skb_shinfo(tgt)->nr_frags;
3568 fragfrom = &skb_shinfo(skb)->frags[from];
3570 /* Actual merge is delayed until the point when we know we can
3571 * commit all, so that we don't have to undo partial changes
3574 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3575 skb_frag_off(fragfrom))) {
3580 todo -= skb_frag_size(fragfrom);
3582 if (skb_prepare_for_shift(skb) ||
3583 skb_prepare_for_shift(tgt))
3586 /* All previous frag pointers might be stale! */
3587 fragfrom = &skb_shinfo(skb)->frags[from];
3588 fragto = &skb_shinfo(tgt)->frags[merge];
3590 skb_frag_size_add(fragto, shiftlen);
3591 skb_frag_size_sub(fragfrom, shiftlen);
3592 skb_frag_off_add(fragfrom, shiftlen);
3600 /* Skip full, not-fitting skb to avoid expensive operations */
3601 if ((shiftlen == skb->len) &&
3602 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3605 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3608 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3609 if (to == MAX_SKB_FRAGS)
3612 fragfrom = &skb_shinfo(skb)->frags[from];
3613 fragto = &skb_shinfo(tgt)->frags[to];
3615 if (todo >= skb_frag_size(fragfrom)) {
3616 *fragto = *fragfrom;
3617 todo -= skb_frag_size(fragfrom);
3622 __skb_frag_ref(fragfrom);
3623 skb_frag_page_copy(fragto, fragfrom);
3624 skb_frag_off_copy(fragto, fragfrom);
3625 skb_frag_size_set(fragto, todo);
3627 skb_frag_off_add(fragfrom, todo);
3628 skb_frag_size_sub(fragfrom, todo);
3636 /* Ready to "commit" this state change to tgt */
3637 skb_shinfo(tgt)->nr_frags = to;
3640 fragfrom = &skb_shinfo(skb)->frags[0];
3641 fragto = &skb_shinfo(tgt)->frags[merge];
3643 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3644 __skb_frag_unref(fragfrom, skb->pp_recycle);
3647 /* Reposition in the original skb */
3649 while (from < skb_shinfo(skb)->nr_frags)
3650 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3651 skb_shinfo(skb)->nr_frags = to;
3653 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3656 /* Most likely the tgt won't ever need its checksum anymore, skb on
3657 * the other hand might need it if it needs to be resent
3659 tgt->ip_summed = CHECKSUM_PARTIAL;
3660 skb->ip_summed = CHECKSUM_PARTIAL;
3662 skb_len_add(skb, -shiftlen);
3663 skb_len_add(tgt, shiftlen);
3669 * skb_prepare_seq_read - Prepare a sequential read of skb data
3670 * @skb: the buffer to read
3671 * @from: lower offset of data to be read
3672 * @to: upper offset of data to be read
3673 * @st: state variable
3675 * Initializes the specified state variable. Must be called before
3676 * invoking skb_seq_read() for the first time.
3678 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3679 unsigned int to, struct skb_seq_state *st)
3681 st->lower_offset = from;
3682 st->upper_offset = to;
3683 st->root_skb = st->cur_skb = skb;
3684 st->frag_idx = st->stepped_offset = 0;
3685 st->frag_data = NULL;
3688 EXPORT_SYMBOL(skb_prepare_seq_read);
3691 * skb_seq_read - Sequentially read skb data
3692 * @consumed: number of bytes consumed by the caller so far
3693 * @data: destination pointer for data to be returned
3694 * @st: state variable
3696 * Reads a block of skb data at @consumed relative to the
3697 * lower offset specified to skb_prepare_seq_read(). Assigns
3698 * the head of the data block to @data and returns the length
3699 * of the block or 0 if the end of the skb data or the upper
3700 * offset has been reached.
3702 * The caller is not required to consume all of the data
3703 * returned, i.e. @consumed is typically set to the number
3704 * of bytes already consumed and the next call to
3705 * skb_seq_read() will return the remaining part of the block.
3707 * Note 1: The size of each block of data returned can be arbitrary,
3708 * this limitation is the cost for zerocopy sequential
3709 * reads of potentially non linear data.
3711 * Note 2: Fragment lists within fragments are not implemented
3712 * at the moment, state->root_skb could be replaced with
3713 * a stack for this purpose.
3715 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3716 struct skb_seq_state *st)
3718 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3721 if (unlikely(abs_offset >= st->upper_offset)) {
3722 if (st->frag_data) {
3723 kunmap_atomic(st->frag_data);
3724 st->frag_data = NULL;
3730 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3732 if (abs_offset < block_limit && !st->frag_data) {
3733 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3734 return block_limit - abs_offset;
3737 if (st->frag_idx == 0 && !st->frag_data)
3738 st->stepped_offset += skb_headlen(st->cur_skb);
3740 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3741 unsigned int pg_idx, pg_off, pg_sz;
3743 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3746 pg_off = skb_frag_off(frag);
3747 pg_sz = skb_frag_size(frag);
3749 if (skb_frag_must_loop(skb_frag_page(frag))) {
3750 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3751 pg_off = offset_in_page(pg_off + st->frag_off);
3752 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3753 PAGE_SIZE - pg_off);
3756 block_limit = pg_sz + st->stepped_offset;
3757 if (abs_offset < block_limit) {
3759 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3761 *data = (u8 *)st->frag_data + pg_off +
3762 (abs_offset - st->stepped_offset);
3764 return block_limit - abs_offset;
3767 if (st->frag_data) {
3768 kunmap_atomic(st->frag_data);
3769 st->frag_data = NULL;
3772 st->stepped_offset += pg_sz;
3773 st->frag_off += pg_sz;
3774 if (st->frag_off == skb_frag_size(frag)) {
3780 if (st->frag_data) {
3781 kunmap_atomic(st->frag_data);
3782 st->frag_data = NULL;
3785 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3786 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3789 } else if (st->cur_skb->next) {
3790 st->cur_skb = st->cur_skb->next;
3797 EXPORT_SYMBOL(skb_seq_read);
3800 * skb_abort_seq_read - Abort a sequential read of skb data
3801 * @st: state variable
3803 * Must be called if skb_seq_read() was not called until it
3806 void skb_abort_seq_read(struct skb_seq_state *st)
3809 kunmap_atomic(st->frag_data);
3811 EXPORT_SYMBOL(skb_abort_seq_read);
3813 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3815 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3816 struct ts_config *conf,
3817 struct ts_state *state)
3819 return skb_seq_read(offset, text, TS_SKB_CB(state));
3822 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3824 skb_abort_seq_read(TS_SKB_CB(state));
3828 * skb_find_text - Find a text pattern in skb data
3829 * @skb: the buffer to look in
3830 * @from: search offset
3832 * @config: textsearch configuration
3834 * Finds a pattern in the skb data according to the specified
3835 * textsearch configuration. Use textsearch_next() to retrieve
3836 * subsequent occurrences of the pattern. Returns the offset
3837 * to the first occurrence or UINT_MAX if no match was found.
3839 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3840 unsigned int to, struct ts_config *config)
3842 struct ts_state state;
3845 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3847 config->get_next_block = skb_ts_get_next_block;
3848 config->finish = skb_ts_finish;
3850 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3852 ret = textsearch_find(config, &state);
3853 return (ret <= to - from ? ret : UINT_MAX);
3855 EXPORT_SYMBOL(skb_find_text);
3857 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3858 int offset, size_t size)
3860 int i = skb_shinfo(skb)->nr_frags;
3862 if (skb_can_coalesce(skb, i, page, offset)) {
3863 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3864 } else if (i < MAX_SKB_FRAGS) {
3865 skb_zcopy_downgrade_managed(skb);
3867 skb_fill_page_desc(skb, i, page, offset, size);
3874 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3877 * skb_pull_rcsum - pull skb and update receive checksum
3878 * @skb: buffer to update
3879 * @len: length of data pulled
3881 * This function performs an skb_pull on the packet and updates
3882 * the CHECKSUM_COMPLETE checksum. It should be used on
3883 * receive path processing instead of skb_pull unless you know
3884 * that the checksum difference is zero (e.g., a valid IP header)
3885 * or you are setting ip_summed to CHECKSUM_NONE.
3887 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3889 unsigned char *data = skb->data;
3891 BUG_ON(len > skb->len);
3892 __skb_pull(skb, len);
3893 skb_postpull_rcsum(skb, data, len);
3896 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3898 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
3900 skb_frag_t head_frag;
3903 page = virt_to_head_page(frag_skb->head);
3904 __skb_frag_set_page(&head_frag, page);
3905 skb_frag_off_set(&head_frag, frag_skb->data -
3906 (unsigned char *)page_address(page));
3907 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
3911 struct sk_buff *skb_segment_list(struct sk_buff *skb,
3912 netdev_features_t features,
3913 unsigned int offset)
3915 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
3916 unsigned int tnl_hlen = skb_tnl_header_len(skb);
3917 unsigned int delta_truesize = 0;
3918 unsigned int delta_len = 0;
3919 struct sk_buff *tail = NULL;
3920 struct sk_buff *nskb, *tmp;
3923 skb_push(skb, -skb_network_offset(skb) + offset);
3925 skb_shinfo(skb)->frag_list = NULL;
3929 list_skb = list_skb->next;
3932 delta_truesize += nskb->truesize;
3933 if (skb_shared(nskb)) {
3934 tmp = skb_clone(nskb, GFP_ATOMIC);
3938 err = skb_unclone(nskb, GFP_ATOMIC);
3949 if (unlikely(err)) {
3950 nskb->next = list_skb;
3956 delta_len += nskb->len;
3958 skb_push(nskb, -skb_network_offset(nskb) + offset);
3960 skb_release_head_state(nskb);
3961 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
3962 __copy_skb_header(nskb, skb);
3964 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
3965 nskb->transport_header += len_diff;
3966 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
3967 nskb->data - tnl_hlen,
3970 if (skb_needs_linearize(nskb, features) &&
3971 __skb_linearize(nskb))
3976 skb->truesize = skb->truesize - delta_truesize;
3977 skb->data_len = skb->data_len - delta_len;
3978 skb->len = skb->len - delta_len;
3984 if (skb_needs_linearize(skb, features) &&
3985 __skb_linearize(skb))
3993 kfree_skb_list(skb->next);
3995 return ERR_PTR(-ENOMEM);
3997 EXPORT_SYMBOL_GPL(skb_segment_list);
4000 * skb_segment - Perform protocol segmentation on skb.
4001 * @head_skb: buffer to segment
4002 * @features: features for the output path (see dev->features)
4004 * This function performs segmentation on the given skb. It returns
4005 * a pointer to the first in a list of new skbs for the segments.
4006 * In case of error it returns ERR_PTR(err).
4008 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4009 netdev_features_t features)
4011 struct sk_buff *segs = NULL;
4012 struct sk_buff *tail = NULL;
4013 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4014 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4015 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4016 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4017 struct sk_buff *frag_skb = head_skb;
4018 unsigned int offset = doffset;
4019 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4020 unsigned int partial_segs = 0;
4021 unsigned int headroom;
4022 unsigned int len = head_skb->len;
4025 int nfrags = skb_shinfo(head_skb)->nr_frags;
4030 if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
4031 (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
4032 /* gso_size is untrusted, and we have a frag_list with a linear
4033 * non head_frag head.
4035 * (we assume checking the first list_skb member suffices;
4036 * i.e if either of the list_skb members have non head_frag
4037 * head, then the first one has too).
4039 * If head_skb's headlen does not fit requested gso_size, it
4040 * means that the frag_list members do NOT terminate on exact
4041 * gso_size boundaries. Hence we cannot perform skb_frag_t page
4042 * sharing. Therefore we must fallback to copying the frag_list
4043 * skbs; we do so by disabling SG.
4045 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
4046 features &= ~NETIF_F_SG;
4049 __skb_push(head_skb, doffset);
4050 proto = skb_network_protocol(head_skb, NULL);
4051 if (unlikely(!proto))
4052 return ERR_PTR(-EINVAL);
4054 sg = !!(features & NETIF_F_SG);
4055 csum = !!can_checksum_protocol(features, proto);
4057 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4058 if (!(features & NETIF_F_GSO_PARTIAL)) {
4059 struct sk_buff *iter;
4060 unsigned int frag_len;
4063 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4066 /* If we get here then all the required
4067 * GSO features except frag_list are supported.
4068 * Try to split the SKB to multiple GSO SKBs
4069 * with no frag_list.
4070 * Currently we can do that only when the buffers don't
4071 * have a linear part and all the buffers except
4072 * the last are of the same length.
4074 frag_len = list_skb->len;
4075 skb_walk_frags(head_skb, iter) {
4076 if (frag_len != iter->len && iter->next)
4078 if (skb_headlen(iter) && !iter->head_frag)
4084 if (len != frag_len)
4088 /* GSO partial only requires that we trim off any excess that
4089 * doesn't fit into an MSS sized block, so take care of that
4092 partial_segs = len / mss;
4093 if (partial_segs > 1)
4094 mss *= partial_segs;
4100 headroom = skb_headroom(head_skb);
4101 pos = skb_headlen(head_skb);
4104 struct sk_buff *nskb;
4105 skb_frag_t *nskb_frag;
4109 if (unlikely(mss == GSO_BY_FRAGS)) {
4110 len = list_skb->len;
4112 len = head_skb->len - offset;
4117 hsize = skb_headlen(head_skb) - offset;
4119 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4120 (skb_headlen(list_skb) == len || sg)) {
4121 BUG_ON(skb_headlen(list_skb) > len);
4124 nfrags = skb_shinfo(list_skb)->nr_frags;
4125 frag = skb_shinfo(list_skb)->frags;
4126 frag_skb = list_skb;
4127 pos += skb_headlen(list_skb);
4129 while (pos < offset + len) {
4130 BUG_ON(i >= nfrags);
4132 size = skb_frag_size(frag);
4133 if (pos + size > offset + len)
4141 nskb = skb_clone(list_skb, GFP_ATOMIC);
4142 list_skb = list_skb->next;
4144 if (unlikely(!nskb))
4147 if (unlikely(pskb_trim(nskb, len))) {
4152 hsize = skb_end_offset(nskb);
4153 if (skb_cow_head(nskb, doffset + headroom)) {
4158 nskb->truesize += skb_end_offset(nskb) - hsize;
4159 skb_release_head_state(nskb);
4160 __skb_push(nskb, doffset);
4164 if (hsize > len || !sg)
4167 nskb = __alloc_skb(hsize + doffset + headroom,
4168 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4171 if (unlikely(!nskb))
4174 skb_reserve(nskb, headroom);
4175 __skb_put(nskb, doffset);
4184 __copy_skb_header(nskb, head_skb);
4186 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4187 skb_reset_mac_len(nskb);
4189 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4190 nskb->data - tnl_hlen,
4191 doffset + tnl_hlen);
4193 if (nskb->len == len + doffset)
4194 goto perform_csum_check;
4198 if (!nskb->remcsum_offload)
4199 nskb->ip_summed = CHECKSUM_NONE;
4200 SKB_GSO_CB(nskb)->csum =
4201 skb_copy_and_csum_bits(head_skb, offset,
4205 SKB_GSO_CB(nskb)->csum_start =
4206 skb_headroom(nskb) + doffset;
4208 skb_copy_bits(head_skb, offset,
4215 nskb_frag = skb_shinfo(nskb)->frags;
4217 skb_copy_from_linear_data_offset(head_skb, offset,
4218 skb_put(nskb, hsize), hsize);
4220 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4223 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4224 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4227 while (pos < offset + len) {
4230 nfrags = skb_shinfo(list_skb)->nr_frags;
4231 frag = skb_shinfo(list_skb)->frags;
4232 frag_skb = list_skb;
4233 if (!skb_headlen(list_skb)) {
4236 BUG_ON(!list_skb->head_frag);
4238 /* to make room for head_frag. */
4242 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4243 skb_zerocopy_clone(nskb, frag_skb,
4247 list_skb = list_skb->next;
4250 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4252 net_warn_ratelimited(
4253 "skb_segment: too many frags: %u %u\n",
4259 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4260 __skb_frag_ref(nskb_frag);
4261 size = skb_frag_size(nskb_frag);
4264 skb_frag_off_add(nskb_frag, offset - pos);
4265 skb_frag_size_sub(nskb_frag, offset - pos);
4268 skb_shinfo(nskb)->nr_frags++;
4270 if (pos + size <= offset + len) {
4275 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4283 nskb->data_len = len - hsize;
4284 nskb->len += nskb->data_len;
4285 nskb->truesize += nskb->data_len;
4289 if (skb_has_shared_frag(nskb) &&
4290 __skb_linearize(nskb))
4293 if (!nskb->remcsum_offload)
4294 nskb->ip_summed = CHECKSUM_NONE;
4295 SKB_GSO_CB(nskb)->csum =
4296 skb_checksum(nskb, doffset,
4297 nskb->len - doffset, 0);
4298 SKB_GSO_CB(nskb)->csum_start =
4299 skb_headroom(nskb) + doffset;
4301 } while ((offset += len) < head_skb->len);
4303 /* Some callers want to get the end of the list.
4304 * Put it in segs->prev to avoid walking the list.
4305 * (see validate_xmit_skb_list() for example)
4310 struct sk_buff *iter;
4311 int type = skb_shinfo(head_skb)->gso_type;
4312 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4314 /* Update type to add partial and then remove dodgy if set */
4315 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4316 type &= ~SKB_GSO_DODGY;
4318 /* Update GSO info and prepare to start updating headers on
4319 * our way back down the stack of protocols.
4321 for (iter = segs; iter; iter = iter->next) {
4322 skb_shinfo(iter)->gso_size = gso_size;
4323 skb_shinfo(iter)->gso_segs = partial_segs;
4324 skb_shinfo(iter)->gso_type = type;
4325 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4328 if (tail->len - doffset <= gso_size)
4329 skb_shinfo(tail)->gso_size = 0;
4330 else if (tail != segs)
4331 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4334 /* Following permits correct backpressure, for protocols
4335 * using skb_set_owner_w().
4336 * Idea is to tranfert ownership from head_skb to last segment.
4338 if (head_skb->destructor == sock_wfree) {
4339 swap(tail->truesize, head_skb->truesize);
4340 swap(tail->destructor, head_skb->destructor);
4341 swap(tail->sk, head_skb->sk);
4346 kfree_skb_list(segs);
4347 return ERR_PTR(err);
4349 EXPORT_SYMBOL_GPL(skb_segment);
4351 #ifdef CONFIG_SKB_EXTENSIONS
4352 #define SKB_EXT_ALIGN_VALUE 8
4353 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4355 static const u8 skb_ext_type_len[] = {
4356 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4357 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4360 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4362 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4363 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4365 #if IS_ENABLED(CONFIG_MPTCP)
4366 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4368 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4369 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4373 static __always_inline unsigned int skb_ext_total_length(void)
4375 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4376 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4377 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4380 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4382 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4383 skb_ext_type_len[TC_SKB_EXT] +
4385 #if IS_ENABLED(CONFIG_MPTCP)
4386 skb_ext_type_len[SKB_EXT_MPTCP] +
4388 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4389 skb_ext_type_len[SKB_EXT_MCTP] +
4394 static void skb_extensions_init(void)
4396 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4397 BUILD_BUG_ON(skb_ext_total_length() > 255);
4399 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4400 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4402 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4406 static void skb_extensions_init(void) {}
4409 void __init skb_init(void)
4411 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4412 sizeof(struct sk_buff),
4414 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4415 offsetof(struct sk_buff, cb),
4416 sizeof_field(struct sk_buff, cb),
4418 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4419 sizeof(struct sk_buff_fclones),
4421 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4423 skb_extensions_init();
4427 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4428 unsigned int recursion_level)
4430 int start = skb_headlen(skb);
4431 int i, copy = start - offset;
4432 struct sk_buff *frag_iter;
4435 if (unlikely(recursion_level >= 24))
4441 sg_set_buf(sg, skb->data + offset, copy);
4443 if ((len -= copy) == 0)
4448 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4451 WARN_ON(start > offset + len);
4453 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4454 if ((copy = end - offset) > 0) {
4455 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4456 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4461 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4462 skb_frag_off(frag) + offset - start);
4471 skb_walk_frags(skb, frag_iter) {
4474 WARN_ON(start > offset + len);
4476 end = start + frag_iter->len;
4477 if ((copy = end - offset) > 0) {
4478 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4483 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4484 copy, recursion_level + 1);
4485 if (unlikely(ret < 0))
4488 if ((len -= copy) == 0)
4499 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4500 * @skb: Socket buffer containing the buffers to be mapped
4501 * @sg: The scatter-gather list to map into
4502 * @offset: The offset into the buffer's contents to start mapping
4503 * @len: Length of buffer space to be mapped
4505 * Fill the specified scatter-gather list with mappings/pointers into a
4506 * region of the buffer space attached to a socket buffer. Returns either
4507 * the number of scatterlist items used, or -EMSGSIZE if the contents
4510 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4512 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4517 sg_mark_end(&sg[nsg - 1]);
4521 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4523 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4524 * sglist without mark the sg which contain last skb data as the end.
4525 * So the caller can mannipulate sg list as will when padding new data after
4526 * the first call without calling sg_unmark_end to expend sg list.
4528 * Scenario to use skb_to_sgvec_nomark:
4530 * 2. skb_to_sgvec_nomark(payload1)
4531 * 3. skb_to_sgvec_nomark(payload2)
4533 * This is equivalent to:
4535 * 2. skb_to_sgvec(payload1)
4537 * 4. skb_to_sgvec(payload2)
4539 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4540 * is more preferable.
4542 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4543 int offset, int len)
4545 return __skb_to_sgvec(skb, sg, offset, len, 0);
4547 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4552 * skb_cow_data - Check that a socket buffer's data buffers are writable
4553 * @skb: The socket buffer to check.
4554 * @tailbits: Amount of trailing space to be added
4555 * @trailer: Returned pointer to the skb where the @tailbits space begins
4557 * Make sure that the data buffers attached to a socket buffer are
4558 * writable. If they are not, private copies are made of the data buffers
4559 * and the socket buffer is set to use these instead.
4561 * If @tailbits is given, make sure that there is space to write @tailbits
4562 * bytes of data beyond current end of socket buffer. @trailer will be
4563 * set to point to the skb in which this space begins.
4565 * The number of scatterlist elements required to completely map the
4566 * COW'd and extended socket buffer will be returned.
4568 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4572 struct sk_buff *skb1, **skb_p;
4574 /* If skb is cloned or its head is paged, reallocate
4575 * head pulling out all the pages (pages are considered not writable
4576 * at the moment even if they are anonymous).
4578 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4579 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4582 /* Easy case. Most of packets will go this way. */
4583 if (!skb_has_frag_list(skb)) {
4584 /* A little of trouble, not enough of space for trailer.
4585 * This should not happen, when stack is tuned to generate
4586 * good frames. OK, on miss we reallocate and reserve even more
4587 * space, 128 bytes is fair. */
4589 if (skb_tailroom(skb) < tailbits &&
4590 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4598 /* Misery. We are in troubles, going to mincer fragments... */
4601 skb_p = &skb_shinfo(skb)->frag_list;
4604 while ((skb1 = *skb_p) != NULL) {
4607 /* The fragment is partially pulled by someone,
4608 * this can happen on input. Copy it and everything
4611 if (skb_shared(skb1))
4614 /* If the skb is the last, worry about trailer. */
4616 if (skb1->next == NULL && tailbits) {
4617 if (skb_shinfo(skb1)->nr_frags ||
4618 skb_has_frag_list(skb1) ||
4619 skb_tailroom(skb1) < tailbits)
4620 ntail = tailbits + 128;
4626 skb_shinfo(skb1)->nr_frags ||
4627 skb_has_frag_list(skb1)) {
4628 struct sk_buff *skb2;
4630 /* Fuck, we are miserable poor guys... */
4632 skb2 = skb_copy(skb1, GFP_ATOMIC);
4634 skb2 = skb_copy_expand(skb1,
4638 if (unlikely(skb2 == NULL))
4642 skb_set_owner_w(skb2, skb1->sk);
4644 /* Looking around. Are we still alive?
4645 * OK, link new skb, drop old one */
4647 skb2->next = skb1->next;
4654 skb_p = &skb1->next;
4659 EXPORT_SYMBOL_GPL(skb_cow_data);
4661 static void sock_rmem_free(struct sk_buff *skb)
4663 struct sock *sk = skb->sk;
4665 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4668 static void skb_set_err_queue(struct sk_buff *skb)
4670 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4671 * So, it is safe to (mis)use it to mark skbs on the error queue.
4673 skb->pkt_type = PACKET_OUTGOING;
4674 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4678 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4680 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4682 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4683 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4688 skb->destructor = sock_rmem_free;
4689 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4690 skb_set_err_queue(skb);
4692 /* before exiting rcu section, make sure dst is refcounted */
4695 skb_queue_tail(&sk->sk_error_queue, skb);
4696 if (!sock_flag(sk, SOCK_DEAD))
4697 sk_error_report(sk);
4700 EXPORT_SYMBOL(sock_queue_err_skb);
4702 static bool is_icmp_err_skb(const struct sk_buff *skb)
4704 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4705 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4708 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4710 struct sk_buff_head *q = &sk->sk_error_queue;
4711 struct sk_buff *skb, *skb_next = NULL;
4712 bool icmp_next = false;
4713 unsigned long flags;
4715 spin_lock_irqsave(&q->lock, flags);
4716 skb = __skb_dequeue(q);
4717 if (skb && (skb_next = skb_peek(q))) {
4718 icmp_next = is_icmp_err_skb(skb_next);
4720 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4722 spin_unlock_irqrestore(&q->lock, flags);
4724 if (is_icmp_err_skb(skb) && !icmp_next)
4728 sk_error_report(sk);
4732 EXPORT_SYMBOL(sock_dequeue_err_skb);
4735 * skb_clone_sk - create clone of skb, and take reference to socket
4736 * @skb: the skb to clone
4738 * This function creates a clone of a buffer that holds a reference on
4739 * sk_refcnt. Buffers created via this function are meant to be
4740 * returned using sock_queue_err_skb, or free via kfree_skb.
4742 * When passing buffers allocated with this function to sock_queue_err_skb
4743 * it is necessary to wrap the call with sock_hold/sock_put in order to
4744 * prevent the socket from being released prior to being enqueued on
4745 * the sk_error_queue.
4747 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4749 struct sock *sk = skb->sk;
4750 struct sk_buff *clone;
4752 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4755 clone = skb_clone(skb, GFP_ATOMIC);
4762 clone->destructor = sock_efree;
4766 EXPORT_SYMBOL(skb_clone_sk);
4768 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4773 struct sock_exterr_skb *serr;
4776 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4778 serr = SKB_EXT_ERR(skb);
4779 memset(serr, 0, sizeof(*serr));
4780 serr->ee.ee_errno = ENOMSG;
4781 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4782 serr->ee.ee_info = tstype;
4783 serr->opt_stats = opt_stats;
4784 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4785 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4786 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4788 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4791 err = sock_queue_err_skb(sk, skb);
4797 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4801 if (likely(sysctl_tstamp_allow_data || tsonly))
4804 read_lock_bh(&sk->sk_callback_lock);
4805 ret = sk->sk_socket && sk->sk_socket->file &&
4806 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4807 read_unlock_bh(&sk->sk_callback_lock);
4811 void skb_complete_tx_timestamp(struct sk_buff *skb,
4812 struct skb_shared_hwtstamps *hwtstamps)
4814 struct sock *sk = skb->sk;
4816 if (!skb_may_tx_timestamp(sk, false))
4819 /* Take a reference to prevent skb_orphan() from freeing the socket,
4820 * but only if the socket refcount is not zero.
4822 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4823 *skb_hwtstamps(skb) = *hwtstamps;
4824 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4832 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4834 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4835 const struct sk_buff *ack_skb,
4836 struct skb_shared_hwtstamps *hwtstamps,
4837 struct sock *sk, int tstype)
4839 struct sk_buff *skb;
4840 bool tsonly, opt_stats = false;
4845 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4846 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4849 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4850 if (!skb_may_tx_timestamp(sk, tsonly))
4855 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4857 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4862 skb = alloc_skb(0, GFP_ATOMIC);
4864 skb = skb_clone(orig_skb, GFP_ATOMIC);
4870 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4872 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4876 *skb_hwtstamps(skb) = *hwtstamps;
4878 __net_timestamp(skb);
4880 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
4882 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4884 void skb_tstamp_tx(struct sk_buff *orig_skb,
4885 struct skb_shared_hwtstamps *hwtstamps)
4887 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4890 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4892 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
4894 struct sock *sk = skb->sk;
4895 struct sock_exterr_skb *serr;
4898 skb->wifi_acked_valid = 1;
4899 skb->wifi_acked = acked;
4901 serr = SKB_EXT_ERR(skb);
4902 memset(serr, 0, sizeof(*serr));
4903 serr->ee.ee_errno = ENOMSG;
4904 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
4906 /* Take a reference to prevent skb_orphan() from freeing the socket,
4907 * but only if the socket refcount is not zero.
4909 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4910 err = sock_queue_err_skb(sk, skb);
4916 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4919 * skb_partial_csum_set - set up and verify partial csum values for packet
4920 * @skb: the skb to set
4921 * @start: the number of bytes after skb->data to start checksumming.
4922 * @off: the offset from start to place the checksum.
4924 * For untrusted partially-checksummed packets, we need to make sure the values
4925 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4927 * This function checks and sets those values and skb->ip_summed: if this
4928 * returns false you should drop the packet.
4930 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4932 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
4933 u32 csum_start = skb_headroom(skb) + (u32)start;
4935 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
4936 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
4937 start, off, skb_headroom(skb), skb_headlen(skb));
4940 skb->ip_summed = CHECKSUM_PARTIAL;
4941 skb->csum_start = csum_start;
4942 skb->csum_offset = off;
4943 skb_set_transport_header(skb, start);
4946 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4948 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4951 if (skb_headlen(skb) >= len)
4954 /* If we need to pullup then pullup to the max, so we
4955 * won't need to do it again.
4960 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4963 if (skb_headlen(skb) < len)
4969 #define MAX_TCP_HDR_LEN (15 * 4)
4971 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4972 typeof(IPPROTO_IP) proto,
4979 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4980 off + MAX_TCP_HDR_LEN);
4981 if (!err && !skb_partial_csum_set(skb, off,
4982 offsetof(struct tcphdr,
4985 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4988 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4989 off + sizeof(struct udphdr));
4990 if (!err && !skb_partial_csum_set(skb, off,
4991 offsetof(struct udphdr,
4994 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4997 return ERR_PTR(-EPROTO);
5000 /* This value should be large enough to cover a tagged ethernet header plus
5001 * maximally sized IP and TCP or UDP headers.
5003 #define MAX_IP_HDR_LEN 128
5005 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5014 err = skb_maybe_pull_tail(skb,
5015 sizeof(struct iphdr),
5020 if (ip_is_fragment(ip_hdr(skb)))
5023 off = ip_hdrlen(skb);
5030 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5032 return PTR_ERR(csum);
5035 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5038 ip_hdr(skb)->protocol, 0);
5045 /* This value should be large enough to cover a tagged ethernet header plus
5046 * an IPv6 header, all options, and a maximal TCP or UDP header.
5048 #define MAX_IPV6_HDR_LEN 256
5050 #define OPT_HDR(type, skb, off) \
5051 (type *)(skb_network_header(skb) + (off))
5053 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5066 off = sizeof(struct ipv6hdr);
5068 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5072 nexthdr = ipv6_hdr(skb)->nexthdr;
5074 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5075 while (off <= len && !done) {
5077 case IPPROTO_DSTOPTS:
5078 case IPPROTO_HOPOPTS:
5079 case IPPROTO_ROUTING: {
5080 struct ipv6_opt_hdr *hp;
5082 err = skb_maybe_pull_tail(skb,
5084 sizeof(struct ipv6_opt_hdr),
5089 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5090 nexthdr = hp->nexthdr;
5091 off += ipv6_optlen(hp);
5095 struct ip_auth_hdr *hp;
5097 err = skb_maybe_pull_tail(skb,
5099 sizeof(struct ip_auth_hdr),
5104 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5105 nexthdr = hp->nexthdr;
5106 off += ipv6_authlen(hp);
5109 case IPPROTO_FRAGMENT: {
5110 struct frag_hdr *hp;
5112 err = skb_maybe_pull_tail(skb,
5114 sizeof(struct frag_hdr),
5119 hp = OPT_HDR(struct frag_hdr, skb, off);
5121 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5124 nexthdr = hp->nexthdr;
5125 off += sizeof(struct frag_hdr);
5136 if (!done || fragment)
5139 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5141 return PTR_ERR(csum);
5144 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5145 &ipv6_hdr(skb)->daddr,
5146 skb->len - off, nexthdr, 0);
5154 * skb_checksum_setup - set up partial checksum offset
5155 * @skb: the skb to set up
5156 * @recalculate: if true the pseudo-header checksum will be recalculated
5158 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5162 switch (skb->protocol) {
5163 case htons(ETH_P_IP):
5164 err = skb_checksum_setup_ipv4(skb, recalculate);
5167 case htons(ETH_P_IPV6):
5168 err = skb_checksum_setup_ipv6(skb, recalculate);
5178 EXPORT_SYMBOL(skb_checksum_setup);
5181 * skb_checksum_maybe_trim - maybe trims the given skb
5182 * @skb: the skb to check
5183 * @transport_len: the data length beyond the network header
5185 * Checks whether the given skb has data beyond the given transport length.
5186 * If so, returns a cloned skb trimmed to this transport length.
5187 * Otherwise returns the provided skb. Returns NULL in error cases
5188 * (e.g. transport_len exceeds skb length or out-of-memory).
5190 * Caller needs to set the skb transport header and free any returned skb if it
5191 * differs from the provided skb.
5193 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5194 unsigned int transport_len)
5196 struct sk_buff *skb_chk;
5197 unsigned int len = skb_transport_offset(skb) + transport_len;
5202 else if (skb->len == len)
5205 skb_chk = skb_clone(skb, GFP_ATOMIC);
5209 ret = pskb_trim_rcsum(skb_chk, len);
5219 * skb_checksum_trimmed - validate checksum of an skb
5220 * @skb: the skb to check
5221 * @transport_len: the data length beyond the network header
5222 * @skb_chkf: checksum function to use
5224 * Applies the given checksum function skb_chkf to the provided skb.
5225 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5227 * If the skb has data beyond the given transport length, then a
5228 * trimmed & cloned skb is checked and returned.
5230 * Caller needs to set the skb transport header and free any returned skb if it
5231 * differs from the provided skb.
5233 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5234 unsigned int transport_len,
5235 __sum16(*skb_chkf)(struct sk_buff *skb))
5237 struct sk_buff *skb_chk;
5238 unsigned int offset = skb_transport_offset(skb);
5241 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5245 if (!pskb_may_pull(skb_chk, offset))
5248 skb_pull_rcsum(skb_chk, offset);
5249 ret = skb_chkf(skb_chk);
5250 skb_push_rcsum(skb_chk, offset);
5258 if (skb_chk && skb_chk != skb)
5264 EXPORT_SYMBOL(skb_checksum_trimmed);
5266 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5268 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5271 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5273 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5276 skb_release_head_state(skb);
5277 kmem_cache_free(skbuff_head_cache, skb);
5282 EXPORT_SYMBOL(kfree_skb_partial);
5285 * skb_try_coalesce - try to merge skb to prior one
5287 * @from: buffer to add
5288 * @fragstolen: pointer to boolean
5289 * @delta_truesize: how much more was allocated than was requested
5291 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5292 bool *fragstolen, int *delta_truesize)
5294 struct skb_shared_info *to_shinfo, *from_shinfo;
5295 int i, delta, len = from->len;
5297 *fragstolen = false;
5302 /* In general, avoid mixing slab allocated and page_pool allocated
5303 * pages within the same SKB. However when @to is not pp_recycle and
5304 * @from is cloned, we can transition frag pages from page_pool to
5305 * reference counted.
5307 * On the other hand, don't allow coalescing two pp_recycle SKBs if
5308 * @from is cloned, in case the SKB is using page_pool fragment
5309 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5310 * references for cloned SKBs at the moment that would result in
5311 * inconsistent reference counts.
5313 if (to->pp_recycle != (from->pp_recycle && !skb_cloned(from)))
5316 if (len <= skb_tailroom(to)) {
5318 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5319 *delta_truesize = 0;
5323 to_shinfo = skb_shinfo(to);
5324 from_shinfo = skb_shinfo(from);
5325 if (to_shinfo->frag_list || from_shinfo->frag_list)
5327 if (skb_zcopy(to) || skb_zcopy(from))
5330 if (skb_headlen(from) != 0) {
5332 unsigned int offset;
5334 if (to_shinfo->nr_frags +
5335 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5338 if (skb_head_is_locked(from))
5341 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5343 page = virt_to_head_page(from->head);
5344 offset = from->data - (unsigned char *)page_address(page);
5346 skb_fill_page_desc(to, to_shinfo->nr_frags,
5347 page, offset, skb_headlen(from));
5350 if (to_shinfo->nr_frags +
5351 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5354 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5357 WARN_ON_ONCE(delta < len);
5359 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5361 from_shinfo->nr_frags * sizeof(skb_frag_t));
5362 to_shinfo->nr_frags += from_shinfo->nr_frags;
5364 if (!skb_cloned(from))
5365 from_shinfo->nr_frags = 0;
5367 /* if the skb is not cloned this does nothing
5368 * since we set nr_frags to 0.
5370 for (i = 0; i < from_shinfo->nr_frags; i++)
5371 __skb_frag_ref(&from_shinfo->frags[i]);
5373 to->truesize += delta;
5375 to->data_len += len;
5377 *delta_truesize = delta;
5380 EXPORT_SYMBOL(skb_try_coalesce);
5383 * skb_scrub_packet - scrub an skb
5385 * @skb: buffer to clean
5386 * @xnet: packet is crossing netns
5388 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5389 * into/from a tunnel. Some information have to be cleared during these
5391 * skb_scrub_packet can also be used to clean a skb before injecting it in
5392 * another namespace (@xnet == true). We have to clear all information in the
5393 * skb that could impact namespace isolation.
5395 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5397 skb->pkt_type = PACKET_HOST;
5403 nf_reset_trace(skb);
5405 #ifdef CONFIG_NET_SWITCHDEV
5406 skb->offload_fwd_mark = 0;
5407 skb->offload_l3_fwd_mark = 0;
5415 skb_clear_tstamp(skb);
5417 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5420 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5424 * skb_gso_transport_seglen is used to determine the real size of the
5425 * individual segments, including Layer4 headers (TCP/UDP).
5427 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5429 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5431 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5432 unsigned int thlen = 0;
5434 if (skb->encapsulation) {
5435 thlen = skb_inner_transport_header(skb) -
5436 skb_transport_header(skb);
5438 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5439 thlen += inner_tcp_hdrlen(skb);
5440 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5441 thlen = tcp_hdrlen(skb);
5442 } else if (unlikely(skb_is_gso_sctp(skb))) {
5443 thlen = sizeof(struct sctphdr);
5444 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5445 thlen = sizeof(struct udphdr);
5447 /* UFO sets gso_size to the size of the fragmentation
5448 * payload, i.e. the size of the L4 (UDP) header is already
5451 return thlen + shinfo->gso_size;
5455 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5459 * skb_gso_network_seglen is used to determine the real size of the
5460 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5462 * The MAC/L2 header is not accounted for.
5464 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5466 unsigned int hdr_len = skb_transport_header(skb) -
5467 skb_network_header(skb);
5469 return hdr_len + skb_gso_transport_seglen(skb);
5473 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5477 * skb_gso_mac_seglen is used to determine the real size of the
5478 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5479 * headers (TCP/UDP).
5481 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5483 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5485 return hdr_len + skb_gso_transport_seglen(skb);
5489 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5491 * There are a couple of instances where we have a GSO skb, and we
5492 * want to determine what size it would be after it is segmented.
5494 * We might want to check:
5495 * - L3+L4+payload size (e.g. IP forwarding)
5496 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5498 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5502 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5503 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5505 * @max_len: The maximum permissible length.
5507 * Returns true if the segmented length <= max length.
5509 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5510 unsigned int seg_len,
5511 unsigned int max_len) {
5512 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5513 const struct sk_buff *iter;
5515 if (shinfo->gso_size != GSO_BY_FRAGS)
5516 return seg_len <= max_len;
5518 /* Undo this so we can re-use header sizes */
5519 seg_len -= GSO_BY_FRAGS;
5521 skb_walk_frags(skb, iter) {
5522 if (seg_len + skb_headlen(iter) > max_len)
5530 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5533 * @mtu: MTU to validate against
5535 * skb_gso_validate_network_len validates if a given skb will fit a
5536 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5539 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5541 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5543 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5546 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5549 * @len: length to validate against
5551 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5552 * length once split, including L2, L3 and L4 headers and the payload.
5554 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5556 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5558 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5560 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5562 int mac_len, meta_len;
5565 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5570 mac_len = skb->data - skb_mac_header(skb);
5571 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5572 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5573 mac_len - VLAN_HLEN - ETH_TLEN);
5576 meta_len = skb_metadata_len(skb);
5578 meta = skb_metadata_end(skb) - meta_len;
5579 memmove(meta + VLAN_HLEN, meta, meta_len);
5582 skb->mac_header += VLAN_HLEN;
5586 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5588 struct vlan_hdr *vhdr;
5591 if (unlikely(skb_vlan_tag_present(skb))) {
5592 /* vlan_tci is already set-up so leave this for another time */
5596 skb = skb_share_check(skb, GFP_ATOMIC);
5599 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5600 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5603 vhdr = (struct vlan_hdr *)skb->data;
5604 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5605 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5607 skb_pull_rcsum(skb, VLAN_HLEN);
5608 vlan_set_encap_proto(skb, vhdr);
5610 skb = skb_reorder_vlan_header(skb);
5614 skb_reset_network_header(skb);
5615 if (!skb_transport_header_was_set(skb))
5616 skb_reset_transport_header(skb);
5617 skb_reset_mac_len(skb);
5625 EXPORT_SYMBOL(skb_vlan_untag);
5627 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5629 if (!pskb_may_pull(skb, write_len))
5632 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5635 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5637 EXPORT_SYMBOL(skb_ensure_writable);
5639 /* remove VLAN header from packet and update csum accordingly.
5640 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5642 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5644 struct vlan_hdr *vhdr;
5645 int offset = skb->data - skb_mac_header(skb);
5648 if (WARN_ONCE(offset,
5649 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5654 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5658 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5660 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5661 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5663 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5664 __skb_pull(skb, VLAN_HLEN);
5666 vlan_set_encap_proto(skb, vhdr);
5667 skb->mac_header += VLAN_HLEN;
5669 if (skb_network_offset(skb) < ETH_HLEN)
5670 skb_set_network_header(skb, ETH_HLEN);
5672 skb_reset_mac_len(skb);
5676 EXPORT_SYMBOL(__skb_vlan_pop);
5678 /* Pop a vlan tag either from hwaccel or from payload.
5679 * Expects skb->data at mac header.
5681 int skb_vlan_pop(struct sk_buff *skb)
5687 if (likely(skb_vlan_tag_present(skb))) {
5688 __vlan_hwaccel_clear_tag(skb);
5690 if (unlikely(!eth_type_vlan(skb->protocol)))
5693 err = __skb_vlan_pop(skb, &vlan_tci);
5697 /* move next vlan tag to hw accel tag */
5698 if (likely(!eth_type_vlan(skb->protocol)))
5701 vlan_proto = skb->protocol;
5702 err = __skb_vlan_pop(skb, &vlan_tci);
5706 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5709 EXPORT_SYMBOL(skb_vlan_pop);
5711 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5712 * Expects skb->data at mac header.
5714 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5716 if (skb_vlan_tag_present(skb)) {
5717 int offset = skb->data - skb_mac_header(skb);
5720 if (WARN_ONCE(offset,
5721 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5726 err = __vlan_insert_tag(skb, skb->vlan_proto,
5727 skb_vlan_tag_get(skb));
5731 skb->protocol = skb->vlan_proto;
5732 skb->mac_len += VLAN_HLEN;
5734 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5736 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5739 EXPORT_SYMBOL(skb_vlan_push);
5742 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5744 * @skb: Socket buffer to modify
5746 * Drop the Ethernet header of @skb.
5748 * Expects that skb->data points to the mac header and that no VLAN tags are
5751 * Returns 0 on success, -errno otherwise.
5753 int skb_eth_pop(struct sk_buff *skb)
5755 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5756 skb_network_offset(skb) < ETH_HLEN)
5759 skb_pull_rcsum(skb, ETH_HLEN);
5760 skb_reset_mac_header(skb);
5761 skb_reset_mac_len(skb);
5765 EXPORT_SYMBOL(skb_eth_pop);
5768 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5770 * @skb: Socket buffer to modify
5771 * @dst: Destination MAC address of the new header
5772 * @src: Source MAC address of the new header
5774 * Prepend @skb with a new Ethernet header.
5776 * Expects that skb->data points to the mac header, which must be empty.
5778 * Returns 0 on success, -errno otherwise.
5780 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5781 const unsigned char *src)
5786 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5789 err = skb_cow_head(skb, sizeof(*eth));
5793 skb_push(skb, sizeof(*eth));
5794 skb_reset_mac_header(skb);
5795 skb_reset_mac_len(skb);
5798 ether_addr_copy(eth->h_dest, dst);
5799 ether_addr_copy(eth->h_source, src);
5800 eth->h_proto = skb->protocol;
5802 skb_postpush_rcsum(skb, eth, sizeof(*eth));
5806 EXPORT_SYMBOL(skb_eth_push);
5808 /* Update the ethertype of hdr and the skb csum value if required. */
5809 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5812 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5813 __be16 diff[] = { ~hdr->h_proto, ethertype };
5815 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5818 hdr->h_proto = ethertype;
5822 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5826 * @mpls_lse: MPLS label stack entry to push
5827 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5828 * @mac_len: length of the MAC header
5829 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5832 * Expects skb->data at mac header.
5834 * Returns 0 on success, -errno otherwise.
5836 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5837 int mac_len, bool ethernet)
5839 struct mpls_shim_hdr *lse;
5842 if (unlikely(!eth_p_mpls(mpls_proto)))
5845 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5846 if (skb->encapsulation)
5849 err = skb_cow_head(skb, MPLS_HLEN);
5853 if (!skb->inner_protocol) {
5854 skb_set_inner_network_header(skb, skb_network_offset(skb));
5855 skb_set_inner_protocol(skb, skb->protocol);
5858 skb_push(skb, MPLS_HLEN);
5859 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5861 skb_reset_mac_header(skb);
5862 skb_set_network_header(skb, mac_len);
5863 skb_reset_mac_len(skb);
5865 lse = mpls_hdr(skb);
5866 lse->label_stack_entry = mpls_lse;
5867 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5869 if (ethernet && mac_len >= ETH_HLEN)
5870 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5871 skb->protocol = mpls_proto;
5875 EXPORT_SYMBOL_GPL(skb_mpls_push);
5878 * skb_mpls_pop() - pop the outermost MPLS header
5881 * @next_proto: ethertype of header after popped MPLS header
5882 * @mac_len: length of the MAC header
5883 * @ethernet: flag to indicate if the packet is ethernet
5885 * Expects skb->data at mac header.
5887 * Returns 0 on success, -errno otherwise.
5889 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5894 if (unlikely(!eth_p_mpls(skb->protocol)))
5897 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5901 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5902 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5905 __skb_pull(skb, MPLS_HLEN);
5906 skb_reset_mac_header(skb);
5907 skb_set_network_header(skb, mac_len);
5909 if (ethernet && mac_len >= ETH_HLEN) {
5912 /* use mpls_hdr() to get ethertype to account for VLANs. */
5913 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5914 skb_mod_eth_type(skb, hdr, next_proto);
5916 skb->protocol = next_proto;
5920 EXPORT_SYMBOL_GPL(skb_mpls_pop);
5923 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
5926 * @mpls_lse: new MPLS label stack entry to update to
5928 * Expects skb->data at mac header.
5930 * Returns 0 on success, -errno otherwise.
5932 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
5936 if (unlikely(!eth_p_mpls(skb->protocol)))
5939 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
5943 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5944 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
5946 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5949 mpls_hdr(skb)->label_stack_entry = mpls_lse;
5953 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
5956 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
5960 * Expects skb->data at mac header.
5962 * Returns 0 on success, -errno otherwise.
5964 int skb_mpls_dec_ttl(struct sk_buff *skb)
5969 if (unlikely(!eth_p_mpls(skb->protocol)))
5972 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
5975 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
5976 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
5980 lse &= ~MPLS_LS_TTL_MASK;
5981 lse |= ttl << MPLS_LS_TTL_SHIFT;
5983 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
5985 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
5988 * alloc_skb_with_frags - allocate skb with page frags
5990 * @header_len: size of linear part
5991 * @data_len: needed length in frags
5992 * @max_page_order: max page order desired.
5993 * @errcode: pointer to error code if any
5994 * @gfp_mask: allocation mask
5996 * This can be used to allocate a paged skb, given a maximal order for frags.
5998 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
5999 unsigned long data_len,
6004 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6005 unsigned long chunk;
6006 struct sk_buff *skb;
6010 *errcode = -EMSGSIZE;
6011 /* Note this test could be relaxed, if we succeed to allocate
6012 * high order pages...
6014 if (npages > MAX_SKB_FRAGS)
6017 *errcode = -ENOBUFS;
6018 skb = alloc_skb(header_len, gfp_mask);
6022 skb->truesize += npages << PAGE_SHIFT;
6024 for (i = 0; npages > 0; i++) {
6025 int order = max_page_order;
6028 if (npages >= 1 << order) {
6029 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6035 /* Do not retry other high order allocations */
6041 page = alloc_page(gfp_mask);
6045 chunk = min_t(unsigned long, data_len,
6046 PAGE_SIZE << order);
6047 skb_fill_page_desc(skb, i, page, 0, chunk);
6049 npages -= 1 << order;
6057 EXPORT_SYMBOL(alloc_skb_with_frags);
6059 /* carve out the first off bytes from skb when off < headlen */
6060 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6061 const int headlen, gfp_t gfp_mask)
6064 int size = skb_end_offset(skb);
6065 int new_hlen = headlen - off;
6068 size = SKB_DATA_ALIGN(size);
6070 if (skb_pfmemalloc(skb))
6071 gfp_mask |= __GFP_MEMALLOC;
6072 data = kmalloc_reserve(size +
6073 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6074 gfp_mask, NUMA_NO_NODE, NULL);
6078 size = SKB_WITH_OVERHEAD(ksize(data));
6080 /* Copy real data, and all frags */
6081 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6084 memcpy((struct skb_shared_info *)(data + size),
6086 offsetof(struct skb_shared_info,
6087 frags[skb_shinfo(skb)->nr_frags]));
6088 if (skb_cloned(skb)) {
6089 /* drop the old head gracefully */
6090 if (skb_orphan_frags(skb, gfp_mask)) {
6094 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6095 skb_frag_ref(skb, i);
6096 if (skb_has_frag_list(skb))
6097 skb_clone_fraglist(skb);
6098 skb_release_data(skb);
6100 /* we can reuse existing recount- all we did was
6109 skb_set_end_offset(skb, size);
6110 skb_set_tail_pointer(skb, skb_headlen(skb));
6111 skb_headers_offset_update(skb, 0);
6115 atomic_set(&skb_shinfo(skb)->dataref, 1);
6120 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6122 /* carve out the first eat bytes from skb's frag_list. May recurse into
6125 static int pskb_carve_frag_list(struct sk_buff *skb,
6126 struct skb_shared_info *shinfo, int eat,
6129 struct sk_buff *list = shinfo->frag_list;
6130 struct sk_buff *clone = NULL;
6131 struct sk_buff *insp = NULL;
6135 pr_err("Not enough bytes to eat. Want %d\n", eat);
6138 if (list->len <= eat) {
6139 /* Eaten as whole. */
6144 /* Eaten partially. */
6145 if (skb_shared(list)) {
6146 clone = skb_clone(list, gfp_mask);
6152 /* This may be pulled without problems. */
6155 if (pskb_carve(list, eat, gfp_mask) < 0) {
6163 /* Free pulled out fragments. */
6164 while ((list = shinfo->frag_list) != insp) {
6165 shinfo->frag_list = list->next;
6168 /* And insert new clone at head. */
6171 shinfo->frag_list = clone;
6176 /* carve off first len bytes from skb. Split line (off) is in the
6177 * non-linear part of skb
6179 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6180 int pos, gfp_t gfp_mask)
6183 int size = skb_end_offset(skb);
6185 const int nfrags = skb_shinfo(skb)->nr_frags;
6186 struct skb_shared_info *shinfo;
6188 size = SKB_DATA_ALIGN(size);
6190 if (skb_pfmemalloc(skb))
6191 gfp_mask |= __GFP_MEMALLOC;
6192 data = kmalloc_reserve(size +
6193 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6194 gfp_mask, NUMA_NO_NODE, NULL);
6198 size = SKB_WITH_OVERHEAD(ksize(data));
6200 memcpy((struct skb_shared_info *)(data + size),
6201 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6202 if (skb_orphan_frags(skb, gfp_mask)) {
6206 shinfo = (struct skb_shared_info *)(data + size);
6207 for (i = 0; i < nfrags; i++) {
6208 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6210 if (pos + fsize > off) {
6211 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6215 * We have two variants in this case:
6216 * 1. Move all the frag to the second
6217 * part, if it is possible. F.e.
6218 * this approach is mandatory for TUX,
6219 * where splitting is expensive.
6220 * 2. Split is accurately. We make this.
6222 skb_frag_off_add(&shinfo->frags[0], off - pos);
6223 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6225 skb_frag_ref(skb, i);
6230 shinfo->nr_frags = k;
6231 if (skb_has_frag_list(skb))
6232 skb_clone_fraglist(skb);
6234 /* split line is in frag list */
6235 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6236 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6237 if (skb_has_frag_list(skb))
6238 kfree_skb_list(skb_shinfo(skb)->frag_list);
6242 skb_release_data(skb);
6247 skb_set_end_offset(skb, size);
6248 skb_reset_tail_pointer(skb);
6249 skb_headers_offset_update(skb, 0);
6254 skb->data_len = skb->len;
6255 atomic_set(&skb_shinfo(skb)->dataref, 1);
6259 /* remove len bytes from the beginning of the skb */
6260 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6262 int headlen = skb_headlen(skb);
6265 return pskb_carve_inside_header(skb, len, headlen, gfp);
6267 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6270 /* Extract to_copy bytes starting at off from skb, and return this in
6273 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6274 int to_copy, gfp_t gfp)
6276 struct sk_buff *clone = skb_clone(skb, gfp);
6281 if (pskb_carve(clone, off, gfp) < 0 ||
6282 pskb_trim(clone, to_copy)) {
6288 EXPORT_SYMBOL(pskb_extract);
6291 * skb_condense - try to get rid of fragments/frag_list if possible
6294 * Can be used to save memory before skb is added to a busy queue.
6295 * If packet has bytes in frags and enough tail room in skb->head,
6296 * pull all of them, so that we can free the frags right now and adjust
6299 * We do not reallocate skb->head thus can not fail.
6300 * Caller must re-evaluate skb->truesize if needed.
6302 void skb_condense(struct sk_buff *skb)
6304 if (skb->data_len) {
6305 if (skb->data_len > skb->end - skb->tail ||
6309 /* Nice, we can free page frag(s) right now */
6310 __pskb_pull_tail(skb, skb->data_len);
6312 /* At this point, skb->truesize might be over estimated,
6313 * because skb had a fragment, and fragments do not tell
6315 * When we pulled its content into skb->head, fragment
6316 * was freed, but __pskb_pull_tail() could not possibly
6317 * adjust skb->truesize, not knowing the frag truesize.
6319 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6322 #ifdef CONFIG_SKB_EXTENSIONS
6323 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6325 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6329 * __skb_ext_alloc - allocate a new skb extensions storage
6331 * @flags: See kmalloc().
6333 * Returns the newly allocated pointer. The pointer can later attached to a
6334 * skb via __skb_ext_set().
6335 * Note: caller must handle the skb_ext as an opaque data.
6337 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6339 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6342 memset(new->offset, 0, sizeof(new->offset));
6343 refcount_set(&new->refcnt, 1);
6349 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6350 unsigned int old_active)
6352 struct skb_ext *new;
6354 if (refcount_read(&old->refcnt) == 1)
6357 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6361 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6362 refcount_set(&new->refcnt, 1);
6365 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6366 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6369 for (i = 0; i < sp->len; i++)
6370 xfrm_state_hold(sp->xvec[i]);
6378 * __skb_ext_set - attach the specified extension storage to this skb
6381 * @ext: extension storage previously allocated via __skb_ext_alloc()
6383 * Existing extensions, if any, are cleared.
6385 * Returns the pointer to the extension.
6387 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6388 struct skb_ext *ext)
6390 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6393 newlen = newoff + skb_ext_type_len[id];
6394 ext->chunks = newlen;
6395 ext->offset[id] = newoff;
6396 skb->extensions = ext;
6397 skb->active_extensions = 1 << id;
6398 return skb_ext_get_ptr(ext, id);
6402 * skb_ext_add - allocate space for given extension, COW if needed
6404 * @id: extension to allocate space for
6406 * Allocates enough space for the given extension.
6407 * If the extension is already present, a pointer to that extension
6410 * If the skb was cloned, COW applies and the returned memory can be
6411 * modified without changing the extension space of clones buffers.
6413 * Returns pointer to the extension or NULL on allocation failure.
6415 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6417 struct skb_ext *new, *old = NULL;
6418 unsigned int newlen, newoff;
6420 if (skb->active_extensions) {
6421 old = skb->extensions;
6423 new = skb_ext_maybe_cow(old, skb->active_extensions);
6427 if (__skb_ext_exist(new, id))
6430 newoff = new->chunks;
6432 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6434 new = __skb_ext_alloc(GFP_ATOMIC);
6439 newlen = newoff + skb_ext_type_len[id];
6440 new->chunks = newlen;
6441 new->offset[id] = newoff;
6444 skb->extensions = new;
6445 skb->active_extensions |= 1 << id;
6446 return skb_ext_get_ptr(new, id);
6448 EXPORT_SYMBOL(skb_ext_add);
6451 static void skb_ext_put_sp(struct sec_path *sp)
6455 for (i = 0; i < sp->len; i++)
6456 xfrm_state_put(sp->xvec[i]);
6460 #ifdef CONFIG_MCTP_FLOWS
6461 static void skb_ext_put_mctp(struct mctp_flow *flow)
6464 mctp_key_unref(flow->key);
6468 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6470 struct skb_ext *ext = skb->extensions;
6472 skb->active_extensions &= ~(1 << id);
6473 if (skb->active_extensions == 0) {
6474 skb->extensions = NULL;
6477 } else if (id == SKB_EXT_SEC_PATH &&
6478 refcount_read(&ext->refcnt) == 1) {
6479 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6486 EXPORT_SYMBOL(__skb_ext_del);
6488 void __skb_ext_put(struct skb_ext *ext)
6490 /* If this is last clone, nothing can increment
6491 * it after check passes. Avoids one atomic op.
6493 if (refcount_read(&ext->refcnt) == 1)
6496 if (!refcount_dec_and_test(&ext->refcnt))
6500 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6501 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6503 #ifdef CONFIG_MCTP_FLOWS
6504 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6505 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6508 kmem_cache_free(skbuff_ext_cache, ext);
6510 EXPORT_SYMBOL(__skb_ext_put);
6511 #endif /* CONFIG_SKB_EXTENSIONS */
6514 * skb_attempt_defer_free - queue skb for remote freeing
6517 * Put @skb in a per-cpu list, using the cpu which
6518 * allocated the skb/pages to reduce false sharing
6519 * and memory zone spinlock contention.
6521 void skb_attempt_defer_free(struct sk_buff *skb)
6523 int cpu = skb->alloc_cpu;
6524 struct softnet_data *sd;
6525 unsigned long flags;
6526 unsigned int defer_max;
6529 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6531 cpu == raw_smp_processor_id()) {
6532 nodefer: __kfree_skb(skb);
6536 sd = &per_cpu(softnet_data, cpu);
6537 defer_max = READ_ONCE(sysctl_skb_defer_max);
6538 if (READ_ONCE(sd->defer_count) >= defer_max)
6541 spin_lock_irqsave(&sd->defer_lock, flags);
6542 /* Send an IPI every time queue reaches half capacity. */
6543 kick = sd->defer_count == (defer_max >> 1);
6544 /* Paired with the READ_ONCE() few lines above */
6545 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6547 skb->next = sd->defer_list;
6548 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6549 WRITE_ONCE(sd->defer_list, skb);
6550 spin_unlock_irqrestore(&sd->defer_lock, flags);
6552 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6553 * if we are unlucky enough (this seems very unlikely).
6555 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6556 smp_call_function_single_async(cpu, &sd->defer_csd);