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'
781 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
783 if (unlikely(!skb_unref(skb)))
786 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
788 trace_kfree_skb(skb, __builtin_return_address(0), reason);
791 EXPORT_SYMBOL(kfree_skb_reason);
793 void kfree_skb_list_reason(struct sk_buff *segs,
794 enum skb_drop_reason reason)
797 struct sk_buff *next = segs->next;
799 kfree_skb_reason(segs, reason);
803 EXPORT_SYMBOL(kfree_skb_list_reason);
805 /* Dump skb information and contents.
807 * Must only be called from net_ratelimit()-ed paths.
809 * Dumps whole packets if full_pkt, only headers otherwise.
811 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
813 struct skb_shared_info *sh = skb_shinfo(skb);
814 struct net_device *dev = skb->dev;
815 struct sock *sk = skb->sk;
816 struct sk_buff *list_skb;
817 bool has_mac, has_trans;
818 int headroom, tailroom;
824 len = min_t(int, skb->len, MAX_HEADER + 128);
826 headroom = skb_headroom(skb);
827 tailroom = skb_tailroom(skb);
829 has_mac = skb_mac_header_was_set(skb);
830 has_trans = skb_transport_header_was_set(skb);
832 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
833 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
834 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
835 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
836 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
837 level, skb->len, headroom, skb_headlen(skb), tailroom,
838 has_mac ? skb->mac_header : -1,
839 has_mac ? skb_mac_header_len(skb) : -1,
841 has_trans ? skb_network_header_len(skb) : -1,
842 has_trans ? skb->transport_header : -1,
843 sh->tx_flags, sh->nr_frags,
844 sh->gso_size, sh->gso_type, sh->gso_segs,
845 skb->csum, skb->ip_summed, skb->csum_complete_sw,
846 skb->csum_valid, skb->csum_level,
847 skb->hash, skb->sw_hash, skb->l4_hash,
848 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
851 printk("%sdev name=%s feat=%pNF\n",
852 level, dev->name, &dev->features);
854 printk("%ssk family=%hu type=%u proto=%u\n",
855 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
857 if (full_pkt && headroom)
858 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
859 16, 1, skb->head, headroom, false);
861 seg_len = min_t(int, skb_headlen(skb), len);
863 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
864 16, 1, skb->data, seg_len, false);
867 if (full_pkt && tailroom)
868 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
869 16, 1, skb_tail_pointer(skb), tailroom, false);
871 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
872 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
873 u32 p_off, p_len, copied;
877 skb_frag_foreach_page(frag, skb_frag_off(frag),
878 skb_frag_size(frag), p, p_off, p_len,
880 seg_len = min_t(int, p_len, len);
881 vaddr = kmap_atomic(p);
882 print_hex_dump(level, "skb frag: ",
884 16, 1, vaddr + p_off, seg_len, false);
885 kunmap_atomic(vaddr);
892 if (full_pkt && skb_has_frag_list(skb)) {
893 printk("skb fraglist:\n");
894 skb_walk_frags(skb, list_skb)
895 skb_dump(level, list_skb, true);
898 EXPORT_SYMBOL(skb_dump);
901 * skb_tx_error - report an sk_buff xmit error
902 * @skb: buffer that triggered an error
904 * Report xmit error if a device callback is tracking this skb.
905 * skb must be freed afterwards.
907 void skb_tx_error(struct sk_buff *skb)
910 skb_zcopy_downgrade_managed(skb);
911 skb_zcopy_clear(skb, true);
914 EXPORT_SYMBOL(skb_tx_error);
916 #ifdef CONFIG_TRACEPOINTS
918 * consume_skb - free an skbuff
919 * @skb: buffer to free
921 * Drop a ref to the buffer and free it if the usage count has hit zero
922 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
923 * is being dropped after a failure and notes that
925 void consume_skb(struct sk_buff *skb)
930 trace_consume_skb(skb);
933 EXPORT_SYMBOL(consume_skb);
937 * __consume_stateless_skb - free an skbuff, assuming it is stateless
938 * @skb: buffer to free
940 * Alike consume_skb(), but this variant assumes that this is the last
941 * skb reference and all the head states have been already dropped
943 void __consume_stateless_skb(struct sk_buff *skb)
945 trace_consume_skb(skb);
946 skb_release_data(skb);
950 static void napi_skb_cache_put(struct sk_buff *skb)
952 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
955 kasan_poison_object_data(skbuff_head_cache, skb);
956 nc->skb_cache[nc->skb_count++] = skb;
958 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
959 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
960 kasan_unpoison_object_data(skbuff_head_cache,
963 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
964 nc->skb_cache + NAPI_SKB_CACHE_HALF);
965 nc->skb_count = NAPI_SKB_CACHE_HALF;
969 void __kfree_skb_defer(struct sk_buff *skb)
971 skb_release_all(skb);
972 napi_skb_cache_put(skb);
975 void napi_skb_free_stolen_head(struct sk_buff *skb)
977 if (unlikely(skb->slow_gro)) {
984 napi_skb_cache_put(skb);
987 void napi_consume_skb(struct sk_buff *skb, int budget)
989 /* Zero budget indicate non-NAPI context called us, like netpoll */
990 if (unlikely(!budget)) {
991 dev_consume_skb_any(skb);
995 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1000 /* if reaching here SKB is ready to free */
1001 trace_consume_skb(skb);
1003 /* if SKB is a clone, don't handle this case */
1004 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1009 skb_release_all(skb);
1010 napi_skb_cache_put(skb);
1012 EXPORT_SYMBOL(napi_consume_skb);
1014 /* Make sure a field is contained by headers group */
1015 #define CHECK_SKB_FIELD(field) \
1016 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1017 offsetof(struct sk_buff, headers.field)); \
1019 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1021 new->tstamp = old->tstamp;
1022 /* We do not copy old->sk */
1023 new->dev = old->dev;
1024 memcpy(new->cb, old->cb, sizeof(old->cb));
1025 skb_dst_copy(new, old);
1026 __skb_ext_copy(new, old);
1027 __nf_copy(new, old, false);
1029 /* Note : this field could be in the headers group.
1030 * It is not yet because we do not want to have a 16 bit hole
1032 new->queue_mapping = old->queue_mapping;
1034 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1035 CHECK_SKB_FIELD(protocol);
1036 CHECK_SKB_FIELD(csum);
1037 CHECK_SKB_FIELD(hash);
1038 CHECK_SKB_FIELD(priority);
1039 CHECK_SKB_FIELD(skb_iif);
1040 CHECK_SKB_FIELD(vlan_proto);
1041 CHECK_SKB_FIELD(vlan_tci);
1042 CHECK_SKB_FIELD(transport_header);
1043 CHECK_SKB_FIELD(network_header);
1044 CHECK_SKB_FIELD(mac_header);
1045 CHECK_SKB_FIELD(inner_protocol);
1046 CHECK_SKB_FIELD(inner_transport_header);
1047 CHECK_SKB_FIELD(inner_network_header);
1048 CHECK_SKB_FIELD(inner_mac_header);
1049 CHECK_SKB_FIELD(mark);
1050 #ifdef CONFIG_NETWORK_SECMARK
1051 CHECK_SKB_FIELD(secmark);
1053 #ifdef CONFIG_NET_RX_BUSY_POLL
1054 CHECK_SKB_FIELD(napi_id);
1056 CHECK_SKB_FIELD(alloc_cpu);
1058 CHECK_SKB_FIELD(sender_cpu);
1060 #ifdef CONFIG_NET_SCHED
1061 CHECK_SKB_FIELD(tc_index);
1067 * You should not add any new code to this function. Add it to
1068 * __copy_skb_header above instead.
1070 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1072 #define C(x) n->x = skb->x
1074 n->next = n->prev = NULL;
1076 __copy_skb_header(n, skb);
1081 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1087 n->destructor = NULL;
1094 refcount_set(&n->users, 1);
1096 atomic_inc(&(skb_shinfo(skb)->dataref));
1104 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1105 * @first: first sk_buff of the msg
1107 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1111 n = alloc_skb(0, GFP_ATOMIC);
1115 n->len = first->len;
1116 n->data_len = first->len;
1117 n->truesize = first->truesize;
1119 skb_shinfo(n)->frag_list = first;
1121 __copy_skb_header(n, first);
1122 n->destructor = NULL;
1126 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1129 * skb_morph - morph one skb into another
1130 * @dst: the skb to receive the contents
1131 * @src: the skb to supply the contents
1133 * This is identical to skb_clone except that the target skb is
1134 * supplied by the user.
1136 * The target skb is returned upon exit.
1138 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1140 skb_release_all(dst);
1141 return __skb_clone(dst, src);
1143 EXPORT_SYMBOL_GPL(skb_morph);
1145 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1147 unsigned long max_pg, num_pg, new_pg, old_pg;
1148 struct user_struct *user;
1150 if (capable(CAP_IPC_LOCK) || !size)
1153 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1154 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1155 user = mmp->user ? : current_user();
1158 old_pg = atomic_long_read(&user->locked_vm);
1159 new_pg = old_pg + num_pg;
1160 if (new_pg > max_pg)
1162 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1166 mmp->user = get_uid(user);
1167 mmp->num_pg = num_pg;
1169 mmp->num_pg += num_pg;
1174 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1176 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1179 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1180 free_uid(mmp->user);
1183 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1185 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1187 struct ubuf_info *uarg;
1188 struct sk_buff *skb;
1190 WARN_ON_ONCE(!in_task());
1192 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1196 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1197 uarg = (void *)skb->cb;
1198 uarg->mmp.user = NULL;
1200 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1205 uarg->callback = msg_zerocopy_callback;
1206 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1208 uarg->bytelen = size;
1210 uarg->flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1211 refcount_set(&uarg->refcnt, 1);
1217 static inline struct sk_buff *skb_from_uarg(struct ubuf_info *uarg)
1219 return container_of((void *)uarg, struct sk_buff, cb);
1222 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1223 struct ubuf_info *uarg)
1226 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1229 /* there might be non MSG_ZEROCOPY users */
1230 if (uarg->callback != msg_zerocopy_callback)
1233 /* realloc only when socket is locked (TCP, UDP cork),
1234 * so uarg->len and sk_zckey access is serialized
1236 if (!sock_owned_by_user(sk)) {
1241 bytelen = uarg->bytelen + size;
1242 if (uarg->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1243 /* TCP can create new skb to attach new uarg */
1244 if (sk->sk_type == SOCK_STREAM)
1249 next = (u32)atomic_read(&sk->sk_zckey);
1250 if ((u32)(uarg->id + uarg->len) == next) {
1251 if (mm_account_pinned_pages(&uarg->mmp, size))
1254 uarg->bytelen = bytelen;
1255 atomic_set(&sk->sk_zckey, ++next);
1257 /* no extra ref when appending to datagram (MSG_MORE) */
1258 if (sk->sk_type == SOCK_STREAM)
1259 net_zcopy_get(uarg);
1266 return msg_zerocopy_alloc(sk, size);
1268 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1270 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1272 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1276 old_lo = serr->ee.ee_info;
1277 old_hi = serr->ee.ee_data;
1278 sum_len = old_hi - old_lo + 1ULL + len;
1280 if (sum_len >= (1ULL << 32))
1283 if (lo != old_hi + 1)
1286 serr->ee.ee_data += len;
1290 static void __msg_zerocopy_callback(struct ubuf_info *uarg)
1292 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1293 struct sock_exterr_skb *serr;
1294 struct sock *sk = skb->sk;
1295 struct sk_buff_head *q;
1296 unsigned long flags;
1301 mm_unaccount_pinned_pages(&uarg->mmp);
1303 /* if !len, there was only 1 call, and it was aborted
1304 * so do not queue a completion notification
1306 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1311 hi = uarg->id + len - 1;
1312 is_zerocopy = uarg->zerocopy;
1314 serr = SKB_EXT_ERR(skb);
1315 memset(serr, 0, sizeof(*serr));
1316 serr->ee.ee_errno = 0;
1317 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1318 serr->ee.ee_data = hi;
1319 serr->ee.ee_info = lo;
1321 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1323 q = &sk->sk_error_queue;
1324 spin_lock_irqsave(&q->lock, flags);
1325 tail = skb_peek_tail(q);
1326 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1327 !skb_zerocopy_notify_extend(tail, lo, len)) {
1328 __skb_queue_tail(q, skb);
1331 spin_unlock_irqrestore(&q->lock, flags);
1333 sk_error_report(sk);
1340 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1343 uarg->zerocopy = uarg->zerocopy & success;
1345 if (refcount_dec_and_test(&uarg->refcnt))
1346 __msg_zerocopy_callback(uarg);
1348 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1350 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1352 struct sock *sk = skb_from_uarg(uarg)->sk;
1354 atomic_dec(&sk->sk_zckey);
1358 msg_zerocopy_callback(NULL, uarg, true);
1360 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1362 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1363 struct msghdr *msg, int len,
1364 struct ubuf_info *uarg)
1366 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1367 int err, orig_len = skb->len;
1369 /* An skb can only point to one uarg. This edge case happens when
1370 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1372 if (orig_uarg && uarg != orig_uarg)
1375 err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1376 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1377 struct sock *save_sk = skb->sk;
1379 /* Streams do not free skb on error. Reset to prev state. */
1380 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1382 ___pskb_trim(skb, orig_len);
1387 skb_zcopy_set(skb, uarg, NULL);
1388 return skb->len - orig_len;
1390 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1392 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1396 skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1397 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1398 skb_frag_ref(skb, i);
1400 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1402 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1405 if (skb_zcopy(orig)) {
1406 if (skb_zcopy(nskb)) {
1407 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1412 if (skb_uarg(nskb) == skb_uarg(orig))
1414 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1417 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1423 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1424 * @skb: the skb to modify
1425 * @gfp_mask: allocation priority
1427 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1428 * It will copy all frags into kernel and drop the reference
1429 * to userspace pages.
1431 * If this function is called from an interrupt gfp_mask() must be
1434 * Returns 0 on success or a negative error code on failure
1435 * to allocate kernel memory to copy to.
1437 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1439 int num_frags = skb_shinfo(skb)->nr_frags;
1440 struct page *page, *head = NULL;
1444 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1450 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1451 for (i = 0; i < new_frags; i++) {
1452 page = alloc_page(gfp_mask);
1455 struct page *next = (struct page *)page_private(head);
1461 set_page_private(page, (unsigned long)head);
1467 for (i = 0; i < num_frags; i++) {
1468 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1469 u32 p_off, p_len, copied;
1473 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1474 p, p_off, p_len, copied) {
1476 vaddr = kmap_atomic(p);
1478 while (done < p_len) {
1479 if (d_off == PAGE_SIZE) {
1481 page = (struct page *)page_private(page);
1483 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1484 memcpy(page_address(page) + d_off,
1485 vaddr + p_off + done, copy);
1489 kunmap_atomic(vaddr);
1493 /* skb frags release userspace buffers */
1494 for (i = 0; i < num_frags; i++)
1495 skb_frag_unref(skb, i);
1497 /* skb frags point to kernel buffers */
1498 for (i = 0; i < new_frags - 1; i++) {
1499 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1500 head = (struct page *)page_private(head);
1502 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1503 skb_shinfo(skb)->nr_frags = new_frags;
1506 skb_zcopy_clear(skb, false);
1509 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1512 * skb_clone - duplicate an sk_buff
1513 * @skb: buffer to clone
1514 * @gfp_mask: allocation priority
1516 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1517 * copies share the same packet data but not structure. The new
1518 * buffer has a reference count of 1. If the allocation fails the
1519 * function returns %NULL otherwise the new buffer is returned.
1521 * If this function is called from an interrupt gfp_mask() must be
1525 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1527 struct sk_buff_fclones *fclones = container_of(skb,
1528 struct sk_buff_fclones,
1532 if (skb_orphan_frags(skb, gfp_mask))
1535 if (skb->fclone == SKB_FCLONE_ORIG &&
1536 refcount_read(&fclones->fclone_ref) == 1) {
1538 refcount_set(&fclones->fclone_ref, 2);
1539 n->fclone = SKB_FCLONE_CLONE;
1541 if (skb_pfmemalloc(skb))
1542 gfp_mask |= __GFP_MEMALLOC;
1544 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1548 n->fclone = SKB_FCLONE_UNAVAILABLE;
1551 return __skb_clone(n, skb);
1553 EXPORT_SYMBOL(skb_clone);
1555 void skb_headers_offset_update(struct sk_buff *skb, int off)
1557 /* Only adjust this if it actually is csum_start rather than csum */
1558 if (skb->ip_summed == CHECKSUM_PARTIAL)
1559 skb->csum_start += off;
1560 /* {transport,network,mac}_header and tail are relative to skb->head */
1561 skb->transport_header += off;
1562 skb->network_header += off;
1563 if (skb_mac_header_was_set(skb))
1564 skb->mac_header += off;
1565 skb->inner_transport_header += off;
1566 skb->inner_network_header += off;
1567 skb->inner_mac_header += off;
1569 EXPORT_SYMBOL(skb_headers_offset_update);
1571 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1573 __copy_skb_header(new, old);
1575 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1576 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1577 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1579 EXPORT_SYMBOL(skb_copy_header);
1581 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1583 if (skb_pfmemalloc(skb))
1584 return SKB_ALLOC_RX;
1589 * skb_copy - create private copy of an sk_buff
1590 * @skb: buffer to copy
1591 * @gfp_mask: allocation priority
1593 * Make a copy of both an &sk_buff and its data. This is used when the
1594 * caller wishes to modify the data and needs a private copy of the
1595 * data to alter. Returns %NULL on failure or the pointer to the buffer
1596 * on success. The returned buffer has a reference count of 1.
1598 * As by-product this function converts non-linear &sk_buff to linear
1599 * one, so that &sk_buff becomes completely private and caller is allowed
1600 * to modify all the data of returned buffer. This means that this
1601 * function is not recommended for use in circumstances when only
1602 * header is going to be modified. Use pskb_copy() instead.
1605 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1607 int headerlen = skb_headroom(skb);
1608 unsigned int size = skb_end_offset(skb) + skb->data_len;
1609 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1610 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1615 /* Set the data pointer */
1616 skb_reserve(n, headerlen);
1617 /* Set the tail pointer and length */
1618 skb_put(n, skb->len);
1620 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1622 skb_copy_header(n, skb);
1625 EXPORT_SYMBOL(skb_copy);
1628 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1629 * @skb: buffer to copy
1630 * @headroom: headroom of new skb
1631 * @gfp_mask: allocation priority
1632 * @fclone: if true allocate the copy of the skb from the fclone
1633 * cache instead of the head cache; it is recommended to set this
1634 * to true for the cases where the copy will likely be cloned
1636 * Make a copy of both an &sk_buff and part of its data, located
1637 * in header. Fragmented data remain shared. This is used when
1638 * the caller wishes to modify only header of &sk_buff and needs
1639 * private copy of the header to alter. Returns %NULL on failure
1640 * or the pointer to the buffer on success.
1641 * The returned buffer has a reference count of 1.
1644 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1645 gfp_t gfp_mask, bool fclone)
1647 unsigned int size = skb_headlen(skb) + headroom;
1648 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1649 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1654 /* Set the data pointer */
1655 skb_reserve(n, headroom);
1656 /* Set the tail pointer and length */
1657 skb_put(n, skb_headlen(skb));
1658 /* Copy the bytes */
1659 skb_copy_from_linear_data(skb, n->data, n->len);
1661 n->truesize += skb->data_len;
1662 n->data_len = skb->data_len;
1665 if (skb_shinfo(skb)->nr_frags) {
1668 if (skb_orphan_frags(skb, gfp_mask) ||
1669 skb_zerocopy_clone(n, skb, gfp_mask)) {
1674 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1675 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1676 skb_frag_ref(skb, i);
1678 skb_shinfo(n)->nr_frags = i;
1681 if (skb_has_frag_list(skb)) {
1682 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1683 skb_clone_fraglist(n);
1686 skb_copy_header(n, skb);
1690 EXPORT_SYMBOL(__pskb_copy_fclone);
1693 * pskb_expand_head - reallocate header of &sk_buff
1694 * @skb: buffer to reallocate
1695 * @nhead: room to add at head
1696 * @ntail: room to add at tail
1697 * @gfp_mask: allocation priority
1699 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1700 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1701 * reference count of 1. Returns zero in the case of success or error,
1702 * if expansion failed. In the last case, &sk_buff is not changed.
1704 * All the pointers pointing into skb header may change and must be
1705 * reloaded after call to this function.
1708 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1711 int i, osize = skb_end_offset(skb);
1712 int size = osize + nhead + ntail;
1718 BUG_ON(skb_shared(skb));
1720 skb_zcopy_downgrade_managed(skb);
1722 size = SKB_DATA_ALIGN(size);
1724 if (skb_pfmemalloc(skb))
1725 gfp_mask |= __GFP_MEMALLOC;
1726 data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1727 gfp_mask, NUMA_NO_NODE, NULL);
1730 size = SKB_WITH_OVERHEAD(ksize(data));
1732 /* Copy only real data... and, alas, header. This should be
1733 * optimized for the cases when header is void.
1735 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1737 memcpy((struct skb_shared_info *)(data + size),
1739 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1742 * if shinfo is shared we must drop the old head gracefully, but if it
1743 * is not we can just drop the old head and let the existing refcount
1744 * be since all we did is relocate the values
1746 if (skb_cloned(skb)) {
1747 if (skb_orphan_frags(skb, gfp_mask))
1750 refcount_inc(&skb_uarg(skb)->refcnt);
1751 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1752 skb_frag_ref(skb, i);
1754 if (skb_has_frag_list(skb))
1755 skb_clone_fraglist(skb);
1757 skb_release_data(skb);
1761 off = (data + nhead) - skb->head;
1767 skb_set_end_offset(skb, size);
1768 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1772 skb_headers_offset_update(skb, nhead);
1776 atomic_set(&skb_shinfo(skb)->dataref, 1);
1778 skb_metadata_clear(skb);
1780 /* It is not generally safe to change skb->truesize.
1781 * For the moment, we really care of rx path, or
1782 * when skb is orphaned (not attached to a socket).
1784 if (!skb->sk || skb->destructor == sock_edemux)
1785 skb->truesize += size - osize;
1794 EXPORT_SYMBOL(pskb_expand_head);
1796 /* Make private copy of skb with writable head and some headroom */
1798 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1800 struct sk_buff *skb2;
1801 int delta = headroom - skb_headroom(skb);
1804 skb2 = pskb_copy(skb, GFP_ATOMIC);
1806 skb2 = skb_clone(skb, GFP_ATOMIC);
1807 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1815 EXPORT_SYMBOL(skb_realloc_headroom);
1817 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1819 unsigned int saved_end_offset, saved_truesize;
1820 struct skb_shared_info *shinfo;
1823 saved_end_offset = skb_end_offset(skb);
1824 saved_truesize = skb->truesize;
1826 res = pskb_expand_head(skb, 0, 0, pri);
1830 skb->truesize = saved_truesize;
1832 if (likely(skb_end_offset(skb) == saved_end_offset))
1835 shinfo = skb_shinfo(skb);
1837 /* We are about to change back skb->end,
1838 * we need to move skb_shinfo() to its new location.
1840 memmove(skb->head + saved_end_offset,
1842 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1844 skb_set_end_offset(skb, saved_end_offset);
1850 * skb_expand_head - reallocate header of &sk_buff
1851 * @skb: buffer to reallocate
1852 * @headroom: needed headroom
1854 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1855 * if possible; copies skb->sk to new skb as needed
1856 * and frees original skb in case of failures.
1858 * It expect increased headroom and generates warning otherwise.
1861 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1863 int delta = headroom - skb_headroom(skb);
1864 int osize = skb_end_offset(skb);
1865 struct sock *sk = skb->sk;
1867 if (WARN_ONCE(delta <= 0,
1868 "%s is expecting an increase in the headroom", __func__))
1871 delta = SKB_DATA_ALIGN(delta);
1872 /* pskb_expand_head() might crash, if skb is shared. */
1873 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1874 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1876 if (unlikely(!nskb))
1880 skb_set_owner_w(nskb, sk);
1884 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
1887 if (sk && is_skb_wmem(skb)) {
1888 delta = skb_end_offset(skb) - osize;
1889 refcount_add(delta, &sk->sk_wmem_alloc);
1890 skb->truesize += delta;
1898 EXPORT_SYMBOL(skb_expand_head);
1901 * skb_copy_expand - copy and expand sk_buff
1902 * @skb: buffer to copy
1903 * @newheadroom: new free bytes at head
1904 * @newtailroom: new free bytes at tail
1905 * @gfp_mask: allocation priority
1907 * Make a copy of both an &sk_buff and its data and while doing so
1908 * allocate additional space.
1910 * This is used when the caller wishes to modify the data and needs a
1911 * private copy of the data to alter as well as more space for new fields.
1912 * Returns %NULL on failure or the pointer to the buffer
1913 * on success. The returned buffer has a reference count of 1.
1915 * You must pass %GFP_ATOMIC as the allocation priority if this function
1916 * is called from an interrupt.
1918 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1919 int newheadroom, int newtailroom,
1923 * Allocate the copy buffer
1925 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1926 gfp_mask, skb_alloc_rx_flag(skb),
1928 int oldheadroom = skb_headroom(skb);
1929 int head_copy_len, head_copy_off;
1934 skb_reserve(n, newheadroom);
1936 /* Set the tail pointer and length */
1937 skb_put(n, skb->len);
1939 head_copy_len = oldheadroom;
1941 if (newheadroom <= head_copy_len)
1942 head_copy_len = newheadroom;
1944 head_copy_off = newheadroom - head_copy_len;
1946 /* Copy the linear header and data. */
1947 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1948 skb->len + head_copy_len));
1950 skb_copy_header(n, skb);
1952 skb_headers_offset_update(n, newheadroom - oldheadroom);
1956 EXPORT_SYMBOL(skb_copy_expand);
1959 * __skb_pad - zero pad the tail of an skb
1960 * @skb: buffer to pad
1961 * @pad: space to pad
1962 * @free_on_error: free buffer on error
1964 * Ensure that a buffer is followed by a padding area that is zero
1965 * filled. Used by network drivers which may DMA or transfer data
1966 * beyond the buffer end onto the wire.
1968 * May return error in out of memory cases. The skb is freed on error
1969 * if @free_on_error is true.
1972 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
1977 /* If the skbuff is non linear tailroom is always zero.. */
1978 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1979 memset(skb->data+skb->len, 0, pad);
1983 ntail = skb->data_len + pad - (skb->end - skb->tail);
1984 if (likely(skb_cloned(skb) || ntail > 0)) {
1985 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1990 /* FIXME: The use of this function with non-linear skb's really needs
1993 err = skb_linearize(skb);
1997 memset(skb->data + skb->len, 0, pad);
2005 EXPORT_SYMBOL(__skb_pad);
2008 * pskb_put - add data to the tail of a potentially fragmented buffer
2009 * @skb: start of the buffer to use
2010 * @tail: tail fragment of the buffer to use
2011 * @len: amount of data to add
2013 * This function extends the used data area of the potentially
2014 * fragmented buffer. @tail must be the last fragment of @skb -- or
2015 * @skb itself. If this would exceed the total buffer size the kernel
2016 * will panic. A pointer to the first byte of the extra data is
2020 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2023 skb->data_len += len;
2026 return skb_put(tail, len);
2028 EXPORT_SYMBOL_GPL(pskb_put);
2031 * skb_put - add data to a buffer
2032 * @skb: buffer to use
2033 * @len: amount of data to add
2035 * This function extends the used data area of the buffer. If this would
2036 * exceed the total buffer size the kernel will panic. A pointer to the
2037 * first byte of the extra data is returned.
2039 void *skb_put(struct sk_buff *skb, unsigned int len)
2041 void *tmp = skb_tail_pointer(skb);
2042 SKB_LINEAR_ASSERT(skb);
2045 if (unlikely(skb->tail > skb->end))
2046 skb_over_panic(skb, len, __builtin_return_address(0));
2049 EXPORT_SYMBOL(skb_put);
2052 * skb_push - add data to the start of a buffer
2053 * @skb: buffer to use
2054 * @len: amount of data to add
2056 * This function extends the used data area of the buffer at the buffer
2057 * start. If this would exceed the total buffer headroom the kernel will
2058 * panic. A pointer to the first byte of the extra data is returned.
2060 void *skb_push(struct sk_buff *skb, unsigned int len)
2064 if (unlikely(skb->data < skb->head))
2065 skb_under_panic(skb, len, __builtin_return_address(0));
2068 EXPORT_SYMBOL(skb_push);
2071 * skb_pull - remove data from the start of a buffer
2072 * @skb: buffer to use
2073 * @len: amount of data to remove
2075 * This function removes data from the start of a buffer, returning
2076 * the memory to the headroom. A pointer to the next data in the buffer
2077 * is returned. Once the data has been pulled future pushes will overwrite
2080 void *skb_pull(struct sk_buff *skb, unsigned int len)
2082 return skb_pull_inline(skb, len);
2084 EXPORT_SYMBOL(skb_pull);
2087 * skb_pull_data - remove data from the start of a buffer returning its
2088 * original position.
2089 * @skb: buffer to use
2090 * @len: amount of data to remove
2092 * This function removes data from the start of a buffer, returning
2093 * the memory to the headroom. A pointer to the original data in the buffer
2094 * is returned after checking if there is enough data to pull. Once the
2095 * data has been pulled future pushes will overwrite the old data.
2097 void *skb_pull_data(struct sk_buff *skb, size_t len)
2099 void *data = skb->data;
2108 EXPORT_SYMBOL(skb_pull_data);
2111 * skb_trim - remove end from a buffer
2112 * @skb: buffer to alter
2115 * Cut the length of a buffer down by removing data from the tail. If
2116 * the buffer is already under the length specified it is not modified.
2117 * The skb must be linear.
2119 void skb_trim(struct sk_buff *skb, unsigned int len)
2122 __skb_trim(skb, len);
2124 EXPORT_SYMBOL(skb_trim);
2126 /* Trims skb to length len. It can change skb pointers.
2129 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2131 struct sk_buff **fragp;
2132 struct sk_buff *frag;
2133 int offset = skb_headlen(skb);
2134 int nfrags = skb_shinfo(skb)->nr_frags;
2138 if (skb_cloned(skb) &&
2139 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2146 for (; i < nfrags; i++) {
2147 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2154 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2157 skb_shinfo(skb)->nr_frags = i;
2159 for (; i < nfrags; i++)
2160 skb_frag_unref(skb, i);
2162 if (skb_has_frag_list(skb))
2163 skb_drop_fraglist(skb);
2167 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2168 fragp = &frag->next) {
2169 int end = offset + frag->len;
2171 if (skb_shared(frag)) {
2172 struct sk_buff *nfrag;
2174 nfrag = skb_clone(frag, GFP_ATOMIC);
2175 if (unlikely(!nfrag))
2178 nfrag->next = frag->next;
2190 unlikely((err = pskb_trim(frag, len - offset))))
2194 skb_drop_list(&frag->next);
2199 if (len > skb_headlen(skb)) {
2200 skb->data_len -= skb->len - len;
2205 skb_set_tail_pointer(skb, len);
2208 if (!skb->sk || skb->destructor == sock_edemux)
2212 EXPORT_SYMBOL(___pskb_trim);
2214 /* Note : use pskb_trim_rcsum() instead of calling this directly
2216 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2218 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2219 int delta = skb->len - len;
2221 skb->csum = csum_block_sub(skb->csum,
2222 skb_checksum(skb, len, delta, 0),
2224 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2225 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2226 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2228 if (offset + sizeof(__sum16) > hdlen)
2231 return __pskb_trim(skb, len);
2233 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2236 * __pskb_pull_tail - advance tail of skb header
2237 * @skb: buffer to reallocate
2238 * @delta: number of bytes to advance tail
2240 * The function makes a sense only on a fragmented &sk_buff,
2241 * it expands header moving its tail forward and copying necessary
2242 * data from fragmented part.
2244 * &sk_buff MUST have reference count of 1.
2246 * Returns %NULL (and &sk_buff does not change) if pull failed
2247 * or value of new tail of skb in the case of success.
2249 * All the pointers pointing into skb header may change and must be
2250 * reloaded after call to this function.
2253 /* Moves tail of skb head forward, copying data from fragmented part,
2254 * when it is necessary.
2255 * 1. It may fail due to malloc failure.
2256 * 2. It may change skb pointers.
2258 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2260 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2262 /* If skb has not enough free space at tail, get new one
2263 * plus 128 bytes for future expansions. If we have enough
2264 * room at tail, reallocate without expansion only if skb is cloned.
2266 int i, k, eat = (skb->tail + delta) - skb->end;
2268 if (eat > 0 || skb_cloned(skb)) {
2269 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2274 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2275 skb_tail_pointer(skb), delta));
2277 /* Optimization: no fragments, no reasons to preestimate
2278 * size of pulled pages. Superb.
2280 if (!skb_has_frag_list(skb))
2283 /* Estimate size of pulled pages. */
2285 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2286 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2293 /* If we need update frag list, we are in troubles.
2294 * Certainly, it is possible to add an offset to skb data,
2295 * but taking into account that pulling is expected to
2296 * be very rare operation, it is worth to fight against
2297 * further bloating skb head and crucify ourselves here instead.
2298 * Pure masohism, indeed. 8)8)
2301 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2302 struct sk_buff *clone = NULL;
2303 struct sk_buff *insp = NULL;
2306 if (list->len <= eat) {
2307 /* Eaten as whole. */
2312 /* Eaten partially. */
2314 if (skb_shared(list)) {
2315 /* Sucks! We need to fork list. :-( */
2316 clone = skb_clone(list, GFP_ATOMIC);
2322 /* This may be pulled without
2326 if (!pskb_pull(list, eat)) {
2334 /* Free pulled out fragments. */
2335 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2336 skb_shinfo(skb)->frag_list = list->next;
2339 /* And insert new clone at head. */
2342 skb_shinfo(skb)->frag_list = clone;
2345 /* Success! Now we may commit changes to skb data. */
2350 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2351 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2354 skb_frag_unref(skb, i);
2357 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2359 *frag = skb_shinfo(skb)->frags[i];
2361 skb_frag_off_add(frag, eat);
2362 skb_frag_size_sub(frag, eat);
2370 skb_shinfo(skb)->nr_frags = k;
2374 skb->data_len -= delta;
2377 skb_zcopy_clear(skb, false);
2379 return skb_tail_pointer(skb);
2381 EXPORT_SYMBOL(__pskb_pull_tail);
2384 * skb_copy_bits - copy bits from skb to kernel buffer
2386 * @offset: offset in source
2387 * @to: destination buffer
2388 * @len: number of bytes to copy
2390 * Copy the specified number of bytes from the source skb to the
2391 * destination buffer.
2394 * If its prototype is ever changed,
2395 * check arch/{*}/net/{*}.S files,
2396 * since it is called from BPF assembly code.
2398 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2400 int start = skb_headlen(skb);
2401 struct sk_buff *frag_iter;
2404 if (offset > (int)skb->len - len)
2408 if ((copy = start - offset) > 0) {
2411 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2412 if ((len -= copy) == 0)
2418 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2420 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2422 WARN_ON(start > offset + len);
2424 end = start + skb_frag_size(f);
2425 if ((copy = end - offset) > 0) {
2426 u32 p_off, p_len, copied;
2433 skb_frag_foreach_page(f,
2434 skb_frag_off(f) + offset - start,
2435 copy, p, p_off, p_len, copied) {
2436 vaddr = kmap_atomic(p);
2437 memcpy(to + copied, vaddr + p_off, p_len);
2438 kunmap_atomic(vaddr);
2441 if ((len -= copy) == 0)
2449 skb_walk_frags(skb, frag_iter) {
2452 WARN_ON(start > offset + len);
2454 end = start + frag_iter->len;
2455 if ((copy = end - offset) > 0) {
2458 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2460 if ((len -= copy) == 0)
2474 EXPORT_SYMBOL(skb_copy_bits);
2477 * Callback from splice_to_pipe(), if we need to release some pages
2478 * at the end of the spd in case we error'ed out in filling the pipe.
2480 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2482 put_page(spd->pages[i]);
2485 static struct page *linear_to_page(struct page *page, unsigned int *len,
2486 unsigned int *offset,
2489 struct page_frag *pfrag = sk_page_frag(sk);
2491 if (!sk_page_frag_refill(sk, pfrag))
2494 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2496 memcpy(page_address(pfrag->page) + pfrag->offset,
2497 page_address(page) + *offset, *len);
2498 *offset = pfrag->offset;
2499 pfrag->offset += *len;
2504 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2506 unsigned int offset)
2508 return spd->nr_pages &&
2509 spd->pages[spd->nr_pages - 1] == page &&
2510 (spd->partial[spd->nr_pages - 1].offset +
2511 spd->partial[spd->nr_pages - 1].len == offset);
2515 * Fill page/offset/length into spd, if it can hold more pages.
2517 static bool spd_fill_page(struct splice_pipe_desc *spd,
2518 struct pipe_inode_info *pipe, struct page *page,
2519 unsigned int *len, unsigned int offset,
2523 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2527 page = linear_to_page(page, len, &offset, sk);
2531 if (spd_can_coalesce(spd, page, offset)) {
2532 spd->partial[spd->nr_pages - 1].len += *len;
2536 spd->pages[spd->nr_pages] = page;
2537 spd->partial[spd->nr_pages].len = *len;
2538 spd->partial[spd->nr_pages].offset = offset;
2544 static bool __splice_segment(struct page *page, unsigned int poff,
2545 unsigned int plen, unsigned int *off,
2547 struct splice_pipe_desc *spd, bool linear,
2549 struct pipe_inode_info *pipe)
2554 /* skip this segment if already processed */
2560 /* ignore any bits we already processed */
2566 unsigned int flen = min(*len, plen);
2568 if (spd_fill_page(spd, pipe, page, &flen, poff,
2574 } while (*len && plen);
2580 * Map linear and fragment data from the skb to spd. It reports true if the
2581 * pipe is full or if we already spliced the requested length.
2583 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2584 unsigned int *offset, unsigned int *len,
2585 struct splice_pipe_desc *spd, struct sock *sk)
2588 struct sk_buff *iter;
2590 /* map the linear part :
2591 * If skb->head_frag is set, this 'linear' part is backed by a
2592 * fragment, and if the head is not shared with any clones then
2593 * we can avoid a copy since we own the head portion of this page.
2595 if (__splice_segment(virt_to_page(skb->data),
2596 (unsigned long) skb->data & (PAGE_SIZE - 1),
2599 skb_head_is_locked(skb),
2604 * then map the fragments
2606 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2607 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2609 if (__splice_segment(skb_frag_page(f),
2610 skb_frag_off(f), skb_frag_size(f),
2611 offset, len, spd, false, sk, pipe))
2615 skb_walk_frags(skb, iter) {
2616 if (*offset >= iter->len) {
2617 *offset -= iter->len;
2620 /* __skb_splice_bits() only fails if the output has no room
2621 * left, so no point in going over the frag_list for the error
2624 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2632 * Map data from the skb to a pipe. Should handle both the linear part,
2633 * the fragments, and the frag list.
2635 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2636 struct pipe_inode_info *pipe, unsigned int tlen,
2639 struct partial_page partial[MAX_SKB_FRAGS];
2640 struct page *pages[MAX_SKB_FRAGS];
2641 struct splice_pipe_desc spd = {
2644 .nr_pages_max = MAX_SKB_FRAGS,
2645 .ops = &nosteal_pipe_buf_ops,
2646 .spd_release = sock_spd_release,
2650 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2653 ret = splice_to_pipe(pipe, &spd);
2657 EXPORT_SYMBOL_GPL(skb_splice_bits);
2659 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2660 struct kvec *vec, size_t num, size_t size)
2662 struct socket *sock = sk->sk_socket;
2666 return kernel_sendmsg(sock, msg, vec, num, size);
2669 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2670 size_t size, int flags)
2672 struct socket *sock = sk->sk_socket;
2676 return kernel_sendpage(sock, page, offset, size, flags);
2679 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2680 struct kvec *vec, size_t num, size_t size);
2681 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2682 size_t size, int flags);
2683 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2684 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2686 unsigned int orig_len = len;
2687 struct sk_buff *head = skb;
2688 unsigned short fragidx;
2693 /* Deal with head data */
2694 while (offset < skb_headlen(skb) && len) {
2698 slen = min_t(int, len, skb_headlen(skb) - offset);
2699 kv.iov_base = skb->data + offset;
2701 memset(&msg, 0, sizeof(msg));
2702 msg.msg_flags = MSG_DONTWAIT;
2704 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2705 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2713 /* All the data was skb head? */
2717 /* Make offset relative to start of frags */
2718 offset -= skb_headlen(skb);
2720 /* Find where we are in frag list */
2721 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2722 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2724 if (offset < skb_frag_size(frag))
2727 offset -= skb_frag_size(frag);
2730 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2731 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2733 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2736 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2737 sendpage_unlocked, sk,
2738 skb_frag_page(frag),
2739 skb_frag_off(frag) + offset,
2740 slen, MSG_DONTWAIT);
2753 /* Process any frag lists */
2756 if (skb_has_frag_list(skb)) {
2757 skb = skb_shinfo(skb)->frag_list;
2760 } else if (skb->next) {
2767 return orig_len - len;
2770 return orig_len == len ? ret : orig_len - len;
2773 /* Send skb data on a socket. Socket must be locked. */
2774 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2777 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2778 kernel_sendpage_locked);
2780 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2782 /* Send skb data on a socket. Socket must be unlocked. */
2783 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2785 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2790 * skb_store_bits - store bits from kernel buffer to skb
2791 * @skb: destination buffer
2792 * @offset: offset in destination
2793 * @from: source buffer
2794 * @len: number of bytes to copy
2796 * Copy the specified number of bytes from the source buffer to the
2797 * destination skb. This function handles all the messy bits of
2798 * traversing fragment lists and such.
2801 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2803 int start = skb_headlen(skb);
2804 struct sk_buff *frag_iter;
2807 if (offset > (int)skb->len - len)
2810 if ((copy = start - offset) > 0) {
2813 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2814 if ((len -= copy) == 0)
2820 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2821 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2824 WARN_ON(start > offset + len);
2826 end = start + skb_frag_size(frag);
2827 if ((copy = end - offset) > 0) {
2828 u32 p_off, p_len, copied;
2835 skb_frag_foreach_page(frag,
2836 skb_frag_off(frag) + offset - start,
2837 copy, p, p_off, p_len, copied) {
2838 vaddr = kmap_atomic(p);
2839 memcpy(vaddr + p_off, from + copied, p_len);
2840 kunmap_atomic(vaddr);
2843 if ((len -= copy) == 0)
2851 skb_walk_frags(skb, frag_iter) {
2854 WARN_ON(start > offset + len);
2856 end = start + frag_iter->len;
2857 if ((copy = end - offset) > 0) {
2860 if (skb_store_bits(frag_iter, offset - start,
2863 if ((len -= copy) == 0)
2876 EXPORT_SYMBOL(skb_store_bits);
2878 /* Checksum skb data. */
2879 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2880 __wsum csum, const struct skb_checksum_ops *ops)
2882 int start = skb_headlen(skb);
2883 int i, copy = start - offset;
2884 struct sk_buff *frag_iter;
2887 /* Checksum header. */
2891 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
2892 skb->data + offset, copy, csum);
2893 if ((len -= copy) == 0)
2899 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2901 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2903 WARN_ON(start > offset + len);
2905 end = start + skb_frag_size(frag);
2906 if ((copy = end - offset) > 0) {
2907 u32 p_off, p_len, copied;
2915 skb_frag_foreach_page(frag,
2916 skb_frag_off(frag) + offset - start,
2917 copy, p, p_off, p_len, copied) {
2918 vaddr = kmap_atomic(p);
2919 csum2 = INDIRECT_CALL_1(ops->update,
2921 vaddr + p_off, p_len, 0);
2922 kunmap_atomic(vaddr);
2923 csum = INDIRECT_CALL_1(ops->combine,
2924 csum_block_add_ext, csum,
2936 skb_walk_frags(skb, frag_iter) {
2939 WARN_ON(start > offset + len);
2941 end = start + frag_iter->len;
2942 if ((copy = end - offset) > 0) {
2946 csum2 = __skb_checksum(frag_iter, offset - start,
2948 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
2949 csum, csum2, pos, copy);
2950 if ((len -= copy) == 0)
2961 EXPORT_SYMBOL(__skb_checksum);
2963 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2964 int len, __wsum csum)
2966 const struct skb_checksum_ops ops = {
2967 .update = csum_partial_ext,
2968 .combine = csum_block_add_ext,
2971 return __skb_checksum(skb, offset, len, csum, &ops);
2973 EXPORT_SYMBOL(skb_checksum);
2975 /* Both of above in one bottle. */
2977 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2980 int start = skb_headlen(skb);
2981 int i, copy = start - offset;
2982 struct sk_buff *frag_iter;
2990 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2992 if ((len -= copy) == 0)
2999 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3002 WARN_ON(start > offset + len);
3004 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3005 if ((copy = end - offset) > 0) {
3006 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3007 u32 p_off, p_len, copied;
3015 skb_frag_foreach_page(frag,
3016 skb_frag_off(frag) + offset - start,
3017 copy, p, p_off, p_len, copied) {
3018 vaddr = kmap_atomic(p);
3019 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3022 kunmap_atomic(vaddr);
3023 csum = csum_block_add(csum, csum2, pos);
3035 skb_walk_frags(skb, frag_iter) {
3039 WARN_ON(start > offset + len);
3041 end = start + frag_iter->len;
3042 if ((copy = end - offset) > 0) {
3045 csum2 = skb_copy_and_csum_bits(frag_iter,
3048 csum = csum_block_add(csum, csum2, pos);
3049 if ((len -= copy) == 0)
3060 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3062 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3066 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3067 /* See comments in __skb_checksum_complete(). */
3069 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3070 !skb->csum_complete_sw)
3071 netdev_rx_csum_fault(skb->dev, skb);
3073 if (!skb_shared(skb))
3074 skb->csum_valid = !sum;
3077 EXPORT_SYMBOL(__skb_checksum_complete_head);
3079 /* This function assumes skb->csum already holds pseudo header's checksum,
3080 * which has been changed from the hardware checksum, for example, by
3081 * __skb_checksum_validate_complete(). And, the original skb->csum must
3082 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3084 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3085 * zero. The new checksum is stored back into skb->csum unless the skb is
3088 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3093 csum = skb_checksum(skb, 0, skb->len, 0);
3095 sum = csum_fold(csum_add(skb->csum, csum));
3096 /* This check is inverted, because we already knew the hardware
3097 * checksum is invalid before calling this function. So, if the
3098 * re-computed checksum is valid instead, then we have a mismatch
3099 * between the original skb->csum and skb_checksum(). This means either
3100 * the original hardware checksum is incorrect or we screw up skb->csum
3101 * when moving skb->data around.
3104 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3105 !skb->csum_complete_sw)
3106 netdev_rx_csum_fault(skb->dev, skb);
3109 if (!skb_shared(skb)) {
3110 /* Save full packet checksum */
3112 skb->ip_summed = CHECKSUM_COMPLETE;
3113 skb->csum_complete_sw = 1;
3114 skb->csum_valid = !sum;
3119 EXPORT_SYMBOL(__skb_checksum_complete);
3121 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3123 net_warn_ratelimited(
3124 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3129 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3130 int offset, int len)
3132 net_warn_ratelimited(
3133 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3138 static const struct skb_checksum_ops default_crc32c_ops = {
3139 .update = warn_crc32c_csum_update,
3140 .combine = warn_crc32c_csum_combine,
3143 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3144 &default_crc32c_ops;
3145 EXPORT_SYMBOL(crc32c_csum_stub);
3148 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3149 * @from: source buffer
3151 * Calculates the amount of linear headroom needed in the 'to' skb passed
3152 * into skb_zerocopy().
3155 skb_zerocopy_headlen(const struct sk_buff *from)
3157 unsigned int hlen = 0;
3159 if (!from->head_frag ||
3160 skb_headlen(from) < L1_CACHE_BYTES ||
3161 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3162 hlen = skb_headlen(from);
3167 if (skb_has_frag_list(from))
3172 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3175 * skb_zerocopy - Zero copy skb to skb
3176 * @to: destination buffer
3177 * @from: source buffer
3178 * @len: number of bytes to copy from source buffer
3179 * @hlen: size of linear headroom in destination buffer
3181 * Copies up to `len` bytes from `from` to `to` by creating references
3182 * to the frags in the source buffer.
3184 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3185 * headroom in the `to` buffer.
3188 * 0: everything is OK
3189 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3190 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3193 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3196 int plen = 0; /* length of skb->head fragment */
3199 unsigned int offset;
3201 BUG_ON(!from->head_frag && !hlen);
3203 /* dont bother with small payloads */
3204 if (len <= skb_tailroom(to))
3205 return skb_copy_bits(from, 0, skb_put(to, len), len);
3208 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3213 plen = min_t(int, skb_headlen(from), len);
3215 page = virt_to_head_page(from->head);
3216 offset = from->data - (unsigned char *)page_address(page);
3217 __skb_fill_page_desc(to, 0, page, offset, plen);
3224 skb_len_add(to, len + plen);
3226 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3230 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3232 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3237 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3238 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3240 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3242 skb_frag_ref(to, j);
3245 skb_shinfo(to)->nr_frags = j;
3249 EXPORT_SYMBOL_GPL(skb_zerocopy);
3251 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3256 if (skb->ip_summed == CHECKSUM_PARTIAL)
3257 csstart = skb_checksum_start_offset(skb);
3259 csstart = skb_headlen(skb);
3261 BUG_ON(csstart > skb_headlen(skb));
3263 skb_copy_from_linear_data(skb, to, csstart);
3266 if (csstart != skb->len)
3267 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3268 skb->len - csstart);
3270 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3271 long csstuff = csstart + skb->csum_offset;
3273 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3276 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3279 * skb_dequeue - remove from the head of the queue
3280 * @list: list to dequeue from
3282 * Remove the head of the list. The list lock is taken so the function
3283 * may be used safely with other locking list functions. The head item is
3284 * returned or %NULL if the list is empty.
3287 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3289 unsigned long flags;
3290 struct sk_buff *result;
3292 spin_lock_irqsave(&list->lock, flags);
3293 result = __skb_dequeue(list);
3294 spin_unlock_irqrestore(&list->lock, flags);
3297 EXPORT_SYMBOL(skb_dequeue);
3300 * skb_dequeue_tail - remove from the tail of the queue
3301 * @list: list to dequeue from
3303 * Remove the tail of the list. The list lock is taken so the function
3304 * may be used safely with other locking list functions. The tail item is
3305 * returned or %NULL if the list is empty.
3307 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3309 unsigned long flags;
3310 struct sk_buff *result;
3312 spin_lock_irqsave(&list->lock, flags);
3313 result = __skb_dequeue_tail(list);
3314 spin_unlock_irqrestore(&list->lock, flags);
3317 EXPORT_SYMBOL(skb_dequeue_tail);
3320 * skb_queue_purge - empty a list
3321 * @list: list to empty
3323 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3324 * the list and one reference dropped. This function takes the list
3325 * lock and is atomic with respect to other list locking functions.
3327 void skb_queue_purge(struct sk_buff_head *list)
3329 struct sk_buff *skb;
3330 while ((skb = skb_dequeue(list)) != NULL)
3333 EXPORT_SYMBOL(skb_queue_purge);
3336 * skb_rbtree_purge - empty a skb rbtree
3337 * @root: root of the rbtree to empty
3338 * Return value: the sum of truesizes of all purged skbs.
3340 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3341 * the list and one reference dropped. This function does not take
3342 * any lock. Synchronization should be handled by the caller (e.g., TCP
3343 * out-of-order queue is protected by the socket lock).
3345 unsigned int skb_rbtree_purge(struct rb_root *root)
3347 struct rb_node *p = rb_first(root);
3348 unsigned int sum = 0;
3351 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3354 rb_erase(&skb->rbnode, root);
3355 sum += skb->truesize;
3362 * skb_queue_head - queue a buffer at the list head
3363 * @list: list to use
3364 * @newsk: buffer to queue
3366 * Queue a buffer at the start of the list. This function takes the
3367 * list lock and can be used safely with other locking &sk_buff functions
3370 * A buffer cannot be placed on two lists at the same time.
3372 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3374 unsigned long flags;
3376 spin_lock_irqsave(&list->lock, flags);
3377 __skb_queue_head(list, newsk);
3378 spin_unlock_irqrestore(&list->lock, flags);
3380 EXPORT_SYMBOL(skb_queue_head);
3383 * skb_queue_tail - queue a buffer at the list tail
3384 * @list: list to use
3385 * @newsk: buffer to queue
3387 * Queue a buffer at the tail of the list. This function takes the
3388 * list lock and can be used safely with other locking &sk_buff functions
3391 * A buffer cannot be placed on two lists at the same time.
3393 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3395 unsigned long flags;
3397 spin_lock_irqsave(&list->lock, flags);
3398 __skb_queue_tail(list, newsk);
3399 spin_unlock_irqrestore(&list->lock, flags);
3401 EXPORT_SYMBOL(skb_queue_tail);
3404 * skb_unlink - remove a buffer from a list
3405 * @skb: buffer to remove
3406 * @list: list to use
3408 * Remove a packet from a list. The list locks are taken and this
3409 * function is atomic with respect to other list locked calls
3411 * You must know what list the SKB is on.
3413 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3415 unsigned long flags;
3417 spin_lock_irqsave(&list->lock, flags);
3418 __skb_unlink(skb, list);
3419 spin_unlock_irqrestore(&list->lock, flags);
3421 EXPORT_SYMBOL(skb_unlink);
3424 * skb_append - append a buffer
3425 * @old: buffer to insert after
3426 * @newsk: buffer to insert
3427 * @list: list to use
3429 * Place a packet after a given packet in a list. The list locks are taken
3430 * and this function is atomic with respect to other list locked calls.
3431 * A buffer cannot be placed on two lists at the same time.
3433 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3435 unsigned long flags;
3437 spin_lock_irqsave(&list->lock, flags);
3438 __skb_queue_after(list, old, newsk);
3439 spin_unlock_irqrestore(&list->lock, flags);
3441 EXPORT_SYMBOL(skb_append);
3443 static inline void skb_split_inside_header(struct sk_buff *skb,
3444 struct sk_buff* skb1,
3445 const u32 len, const int pos)
3449 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3451 /* And move data appendix as is. */
3452 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3453 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3455 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3456 skb_shinfo(skb)->nr_frags = 0;
3457 skb1->data_len = skb->data_len;
3458 skb1->len += skb1->data_len;
3461 skb_set_tail_pointer(skb, len);
3464 static inline void skb_split_no_header(struct sk_buff *skb,
3465 struct sk_buff* skb1,
3466 const u32 len, int pos)
3469 const int nfrags = skb_shinfo(skb)->nr_frags;
3471 skb_shinfo(skb)->nr_frags = 0;
3472 skb1->len = skb1->data_len = skb->len - len;
3474 skb->data_len = len - pos;
3476 for (i = 0; i < nfrags; i++) {
3477 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3479 if (pos + size > len) {
3480 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3484 * We have two variants in this case:
3485 * 1. Move all the frag to the second
3486 * part, if it is possible. F.e.
3487 * this approach is mandatory for TUX,
3488 * where splitting is expensive.
3489 * 2. Split is accurately. We make this.
3491 skb_frag_ref(skb, i);
3492 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3493 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3494 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3495 skb_shinfo(skb)->nr_frags++;
3499 skb_shinfo(skb)->nr_frags++;
3502 skb_shinfo(skb1)->nr_frags = k;
3506 * skb_split - Split fragmented skb to two parts at length len.
3507 * @skb: the buffer to split
3508 * @skb1: the buffer to receive the second part
3509 * @len: new length for skb
3511 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3513 int pos = skb_headlen(skb);
3514 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3516 skb_zcopy_downgrade_managed(skb);
3518 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3519 skb_zerocopy_clone(skb1, skb, 0);
3520 if (len < pos) /* Split line is inside header. */
3521 skb_split_inside_header(skb, skb1, len, pos);
3522 else /* Second chunk has no header, nothing to copy. */
3523 skb_split_no_header(skb, skb1, len, pos);
3525 EXPORT_SYMBOL(skb_split);
3527 /* Shifting from/to a cloned skb is a no-go.
3529 * Caller cannot keep skb_shinfo related pointers past calling here!
3531 static int skb_prepare_for_shift(struct sk_buff *skb)
3533 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3537 * skb_shift - Shifts paged data partially from skb to another
3538 * @tgt: buffer into which tail data gets added
3539 * @skb: buffer from which the paged data comes from
3540 * @shiftlen: shift up to this many bytes
3542 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3543 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3544 * It's up to caller to free skb if everything was shifted.
3546 * If @tgt runs out of frags, the whole operation is aborted.
3548 * Skb cannot include anything else but paged data while tgt is allowed
3549 * to have non-paged data as well.
3551 * TODO: full sized shift could be optimized but that would need
3552 * specialized skb free'er to handle frags without up-to-date nr_frags.
3554 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3556 int from, to, merge, todo;
3557 skb_frag_t *fragfrom, *fragto;
3559 BUG_ON(shiftlen > skb->len);
3561 if (skb_headlen(skb))
3563 if (skb_zcopy(tgt) || skb_zcopy(skb))
3568 to = skb_shinfo(tgt)->nr_frags;
3569 fragfrom = &skb_shinfo(skb)->frags[from];
3571 /* Actual merge is delayed until the point when we know we can
3572 * commit all, so that we don't have to undo partial changes
3575 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3576 skb_frag_off(fragfrom))) {
3581 todo -= skb_frag_size(fragfrom);
3583 if (skb_prepare_for_shift(skb) ||
3584 skb_prepare_for_shift(tgt))
3587 /* All previous frag pointers might be stale! */
3588 fragfrom = &skb_shinfo(skb)->frags[from];
3589 fragto = &skb_shinfo(tgt)->frags[merge];
3591 skb_frag_size_add(fragto, shiftlen);
3592 skb_frag_size_sub(fragfrom, shiftlen);
3593 skb_frag_off_add(fragfrom, shiftlen);
3601 /* Skip full, not-fitting skb to avoid expensive operations */
3602 if ((shiftlen == skb->len) &&
3603 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3606 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3609 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3610 if (to == MAX_SKB_FRAGS)
3613 fragfrom = &skb_shinfo(skb)->frags[from];
3614 fragto = &skb_shinfo(tgt)->frags[to];
3616 if (todo >= skb_frag_size(fragfrom)) {
3617 *fragto = *fragfrom;
3618 todo -= skb_frag_size(fragfrom);
3623 __skb_frag_ref(fragfrom);
3624 skb_frag_page_copy(fragto, fragfrom);
3625 skb_frag_off_copy(fragto, fragfrom);
3626 skb_frag_size_set(fragto, todo);
3628 skb_frag_off_add(fragfrom, todo);
3629 skb_frag_size_sub(fragfrom, todo);
3637 /* Ready to "commit" this state change to tgt */
3638 skb_shinfo(tgt)->nr_frags = to;
3641 fragfrom = &skb_shinfo(skb)->frags[0];
3642 fragto = &skb_shinfo(tgt)->frags[merge];
3644 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3645 __skb_frag_unref(fragfrom, skb->pp_recycle);
3648 /* Reposition in the original skb */
3650 while (from < skb_shinfo(skb)->nr_frags)
3651 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3652 skb_shinfo(skb)->nr_frags = to;
3654 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3657 /* Most likely the tgt won't ever need its checksum anymore, skb on
3658 * the other hand might need it if it needs to be resent
3660 tgt->ip_summed = CHECKSUM_PARTIAL;
3661 skb->ip_summed = CHECKSUM_PARTIAL;
3663 skb_len_add(skb, -shiftlen);
3664 skb_len_add(tgt, shiftlen);
3670 * skb_prepare_seq_read - Prepare a sequential read of skb data
3671 * @skb: the buffer to read
3672 * @from: lower offset of data to be read
3673 * @to: upper offset of data to be read
3674 * @st: state variable
3676 * Initializes the specified state variable. Must be called before
3677 * invoking skb_seq_read() for the first time.
3679 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3680 unsigned int to, struct skb_seq_state *st)
3682 st->lower_offset = from;
3683 st->upper_offset = to;
3684 st->root_skb = st->cur_skb = skb;
3685 st->frag_idx = st->stepped_offset = 0;
3686 st->frag_data = NULL;
3689 EXPORT_SYMBOL(skb_prepare_seq_read);
3692 * skb_seq_read - Sequentially read skb data
3693 * @consumed: number of bytes consumed by the caller so far
3694 * @data: destination pointer for data to be returned
3695 * @st: state variable
3697 * Reads a block of skb data at @consumed relative to the
3698 * lower offset specified to skb_prepare_seq_read(). Assigns
3699 * the head of the data block to @data and returns the length
3700 * of the block or 0 if the end of the skb data or the upper
3701 * offset has been reached.
3703 * The caller is not required to consume all of the data
3704 * returned, i.e. @consumed is typically set to the number
3705 * of bytes already consumed and the next call to
3706 * skb_seq_read() will return the remaining part of the block.
3708 * Note 1: The size of each block of data returned can be arbitrary,
3709 * this limitation is the cost for zerocopy sequential
3710 * reads of potentially non linear data.
3712 * Note 2: Fragment lists within fragments are not implemented
3713 * at the moment, state->root_skb could be replaced with
3714 * a stack for this purpose.
3716 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3717 struct skb_seq_state *st)
3719 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3722 if (unlikely(abs_offset >= st->upper_offset)) {
3723 if (st->frag_data) {
3724 kunmap_atomic(st->frag_data);
3725 st->frag_data = NULL;
3731 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3733 if (abs_offset < block_limit && !st->frag_data) {
3734 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3735 return block_limit - abs_offset;
3738 if (st->frag_idx == 0 && !st->frag_data)
3739 st->stepped_offset += skb_headlen(st->cur_skb);
3741 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3742 unsigned int pg_idx, pg_off, pg_sz;
3744 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3747 pg_off = skb_frag_off(frag);
3748 pg_sz = skb_frag_size(frag);
3750 if (skb_frag_must_loop(skb_frag_page(frag))) {
3751 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3752 pg_off = offset_in_page(pg_off + st->frag_off);
3753 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3754 PAGE_SIZE - pg_off);
3757 block_limit = pg_sz + st->stepped_offset;
3758 if (abs_offset < block_limit) {
3760 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3762 *data = (u8 *)st->frag_data + pg_off +
3763 (abs_offset - st->stepped_offset);
3765 return block_limit - abs_offset;
3768 if (st->frag_data) {
3769 kunmap_atomic(st->frag_data);
3770 st->frag_data = NULL;
3773 st->stepped_offset += pg_sz;
3774 st->frag_off += pg_sz;
3775 if (st->frag_off == skb_frag_size(frag)) {
3781 if (st->frag_data) {
3782 kunmap_atomic(st->frag_data);
3783 st->frag_data = NULL;
3786 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3787 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3790 } else if (st->cur_skb->next) {
3791 st->cur_skb = st->cur_skb->next;
3798 EXPORT_SYMBOL(skb_seq_read);
3801 * skb_abort_seq_read - Abort a sequential read of skb data
3802 * @st: state variable
3804 * Must be called if skb_seq_read() was not called until it
3807 void skb_abort_seq_read(struct skb_seq_state *st)
3810 kunmap_atomic(st->frag_data);
3812 EXPORT_SYMBOL(skb_abort_seq_read);
3814 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3816 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3817 struct ts_config *conf,
3818 struct ts_state *state)
3820 return skb_seq_read(offset, text, TS_SKB_CB(state));
3823 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3825 skb_abort_seq_read(TS_SKB_CB(state));
3829 * skb_find_text - Find a text pattern in skb data
3830 * @skb: the buffer to look in
3831 * @from: search offset
3833 * @config: textsearch configuration
3835 * Finds a pattern in the skb data according to the specified
3836 * textsearch configuration. Use textsearch_next() to retrieve
3837 * subsequent occurrences of the pattern. Returns the offset
3838 * to the first occurrence or UINT_MAX if no match was found.
3840 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3841 unsigned int to, struct ts_config *config)
3843 struct ts_state state;
3846 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3848 config->get_next_block = skb_ts_get_next_block;
3849 config->finish = skb_ts_finish;
3851 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3853 ret = textsearch_find(config, &state);
3854 return (ret <= to - from ? ret : UINT_MAX);
3856 EXPORT_SYMBOL(skb_find_text);
3858 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3859 int offset, size_t size)
3861 int i = skb_shinfo(skb)->nr_frags;
3863 if (skb_can_coalesce(skb, i, page, offset)) {
3864 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3865 } else if (i < MAX_SKB_FRAGS) {
3866 skb_zcopy_downgrade_managed(skb);
3868 skb_fill_page_desc(skb, i, page, offset, size);
3875 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3878 * skb_pull_rcsum - pull skb and update receive checksum
3879 * @skb: buffer to update
3880 * @len: length of data pulled
3882 * This function performs an skb_pull on the packet and updates
3883 * the CHECKSUM_COMPLETE checksum. It should be used on
3884 * receive path processing instead of skb_pull unless you know
3885 * that the checksum difference is zero (e.g., a valid IP header)
3886 * or you are setting ip_summed to CHECKSUM_NONE.
3888 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3890 unsigned char *data = skb->data;
3892 BUG_ON(len > skb->len);
3893 __skb_pull(skb, len);
3894 skb_postpull_rcsum(skb, data, len);
3897 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3899 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
3901 skb_frag_t head_frag;
3904 page = virt_to_head_page(frag_skb->head);
3905 __skb_frag_set_page(&head_frag, page);
3906 skb_frag_off_set(&head_frag, frag_skb->data -
3907 (unsigned char *)page_address(page));
3908 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
3912 struct sk_buff *skb_segment_list(struct sk_buff *skb,
3913 netdev_features_t features,
3914 unsigned int offset)
3916 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
3917 unsigned int tnl_hlen = skb_tnl_header_len(skb);
3918 unsigned int delta_truesize = 0;
3919 unsigned int delta_len = 0;
3920 struct sk_buff *tail = NULL;
3921 struct sk_buff *nskb, *tmp;
3924 skb_push(skb, -skb_network_offset(skb) + offset);
3926 skb_shinfo(skb)->frag_list = NULL;
3930 list_skb = list_skb->next;
3933 delta_truesize += nskb->truesize;
3934 if (skb_shared(nskb)) {
3935 tmp = skb_clone(nskb, GFP_ATOMIC);
3939 err = skb_unclone(nskb, GFP_ATOMIC);
3950 if (unlikely(err)) {
3951 nskb->next = list_skb;
3957 delta_len += nskb->len;
3959 skb_push(nskb, -skb_network_offset(nskb) + offset);
3961 skb_release_head_state(nskb);
3962 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
3963 __copy_skb_header(nskb, skb);
3965 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
3966 nskb->transport_header += len_diff;
3967 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
3968 nskb->data - tnl_hlen,
3971 if (skb_needs_linearize(nskb, features) &&
3972 __skb_linearize(nskb))
3977 skb->truesize = skb->truesize - delta_truesize;
3978 skb->data_len = skb->data_len - delta_len;
3979 skb->len = skb->len - delta_len;
3985 if (skb_needs_linearize(skb, features) &&
3986 __skb_linearize(skb))
3994 kfree_skb_list(skb->next);
3996 return ERR_PTR(-ENOMEM);
3998 EXPORT_SYMBOL_GPL(skb_segment_list);
4001 * skb_segment - Perform protocol segmentation on skb.
4002 * @head_skb: buffer to segment
4003 * @features: features for the output path (see dev->features)
4005 * This function performs segmentation on the given skb. It returns
4006 * a pointer to the first in a list of new skbs for the segments.
4007 * In case of error it returns ERR_PTR(err).
4009 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4010 netdev_features_t features)
4012 struct sk_buff *segs = NULL;
4013 struct sk_buff *tail = NULL;
4014 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4015 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4016 unsigned int mss = skb_shinfo(head_skb)->gso_size;
4017 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4018 struct sk_buff *frag_skb = head_skb;
4019 unsigned int offset = doffset;
4020 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4021 unsigned int partial_segs = 0;
4022 unsigned int headroom;
4023 unsigned int len = head_skb->len;
4026 int nfrags = skb_shinfo(head_skb)->nr_frags;
4031 if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
4032 (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
4033 /* gso_size is untrusted, and we have a frag_list with a linear
4034 * non head_frag head.
4036 * (we assume checking the first list_skb member suffices;
4037 * i.e if either of the list_skb members have non head_frag
4038 * head, then the first one has too).
4040 * If head_skb's headlen does not fit requested gso_size, it
4041 * means that the frag_list members do NOT terminate on exact
4042 * gso_size boundaries. Hence we cannot perform skb_frag_t page
4043 * sharing. Therefore we must fallback to copying the frag_list
4044 * skbs; we do so by disabling SG.
4046 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
4047 features &= ~NETIF_F_SG;
4050 __skb_push(head_skb, doffset);
4051 proto = skb_network_protocol(head_skb, NULL);
4052 if (unlikely(!proto))
4053 return ERR_PTR(-EINVAL);
4055 sg = !!(features & NETIF_F_SG);
4056 csum = !!can_checksum_protocol(features, proto);
4058 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4059 if (!(features & NETIF_F_GSO_PARTIAL)) {
4060 struct sk_buff *iter;
4061 unsigned int frag_len;
4064 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4067 /* If we get here then all the required
4068 * GSO features except frag_list are supported.
4069 * Try to split the SKB to multiple GSO SKBs
4070 * with no frag_list.
4071 * Currently we can do that only when the buffers don't
4072 * have a linear part and all the buffers except
4073 * the last are of the same length.
4075 frag_len = list_skb->len;
4076 skb_walk_frags(head_skb, iter) {
4077 if (frag_len != iter->len && iter->next)
4079 if (skb_headlen(iter) && !iter->head_frag)
4085 if (len != frag_len)
4089 /* GSO partial only requires that we trim off any excess that
4090 * doesn't fit into an MSS sized block, so take care of that
4093 partial_segs = len / mss;
4094 if (partial_segs > 1)
4095 mss *= partial_segs;
4101 headroom = skb_headroom(head_skb);
4102 pos = skb_headlen(head_skb);
4105 struct sk_buff *nskb;
4106 skb_frag_t *nskb_frag;
4110 if (unlikely(mss == GSO_BY_FRAGS)) {
4111 len = list_skb->len;
4113 len = head_skb->len - offset;
4118 hsize = skb_headlen(head_skb) - offset;
4120 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4121 (skb_headlen(list_skb) == len || sg)) {
4122 BUG_ON(skb_headlen(list_skb) > len);
4125 nfrags = skb_shinfo(list_skb)->nr_frags;
4126 frag = skb_shinfo(list_skb)->frags;
4127 frag_skb = list_skb;
4128 pos += skb_headlen(list_skb);
4130 while (pos < offset + len) {
4131 BUG_ON(i >= nfrags);
4133 size = skb_frag_size(frag);
4134 if (pos + size > offset + len)
4142 nskb = skb_clone(list_skb, GFP_ATOMIC);
4143 list_skb = list_skb->next;
4145 if (unlikely(!nskb))
4148 if (unlikely(pskb_trim(nskb, len))) {
4153 hsize = skb_end_offset(nskb);
4154 if (skb_cow_head(nskb, doffset + headroom)) {
4159 nskb->truesize += skb_end_offset(nskb) - hsize;
4160 skb_release_head_state(nskb);
4161 __skb_push(nskb, doffset);
4165 if (hsize > len || !sg)
4168 nskb = __alloc_skb(hsize + doffset + headroom,
4169 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4172 if (unlikely(!nskb))
4175 skb_reserve(nskb, headroom);
4176 __skb_put(nskb, doffset);
4185 __copy_skb_header(nskb, head_skb);
4187 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4188 skb_reset_mac_len(nskb);
4190 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4191 nskb->data - tnl_hlen,
4192 doffset + tnl_hlen);
4194 if (nskb->len == len + doffset)
4195 goto perform_csum_check;
4199 if (!nskb->remcsum_offload)
4200 nskb->ip_summed = CHECKSUM_NONE;
4201 SKB_GSO_CB(nskb)->csum =
4202 skb_copy_and_csum_bits(head_skb, offset,
4206 SKB_GSO_CB(nskb)->csum_start =
4207 skb_headroom(nskb) + doffset;
4209 if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
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(READ_ONCE(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);