1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * Routines having to do with the 'struct sk_buff' memory handlers.
5 * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
6 * Florian La Roche <rzsfl@rz.uni-sb.de>
9 * Alan Cox : Fixed the worst of the load
11 * Dave Platt : Interrupt stacking fix.
12 * Richard Kooijman : Timestamp fixes.
13 * Alan Cox : Changed buffer format.
14 * Alan Cox : destructor hook for AF_UNIX etc.
15 * Linus Torvalds : Better skb_clone.
16 * Alan Cox : Added skb_copy.
17 * Alan Cox : Added all the changed routines Linus
18 * only put in the headers
19 * Ray VanTassle : Fixed --skb->lock in free
20 * Alan Cox : skb_copy copy arp field
21 * Andi Kleen : slabified it.
22 * Robert Olsson : Removed skb_head_pool
25 * The __skb_ routines should be called with interrupts
26 * disabled, or you better be *real* sure that the operation is atomic
27 * with respect to whatever list is being frobbed (e.g. via lock_sock()
28 * or via disabling bottom half handlers, etc).
32 * The functions in this file will not compile correctly with gcc 2.4.x
35 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/kernel.h>
41 #include <linux/interrupt.h>
43 #include <linux/inet.h>
44 #include <linux/slab.h>
45 #include <linux/tcp.h>
46 #include <linux/udp.h>
47 #include <linux/sctp.h>
48 #include <linux/netdevice.h>
49 #ifdef CONFIG_NET_CLS_ACT
50 #include <net/pkt_sched.h>
52 #include <linux/string.h>
53 #include <linux/skbuff.h>
54 #include <linux/splice.h>
55 #include <linux/cache.h>
56 #include <linux/rtnetlink.h>
57 #include <linux/init.h>
58 #include <linux/scatterlist.h>
59 #include <linux/errqueue.h>
60 #include <linux/prefetch.h>
61 #include <linux/if_vlan.h>
62 #include <linux/mpls.h>
63 #include <linux/kcov.h>
65 #include <net/protocol.h>
68 #include <net/checksum.h>
69 #include <net/ip6_checksum.h>
72 #include <net/mptcp.h>
74 #include <net/page_pool.h>
76 #include <linux/uaccess.h>
77 #include <trace/events/skb.h>
78 #include <linux/highmem.h>
79 #include <linux/capability.h>
80 #include <linux/user_namespace.h>
81 #include <linux/indirect_call_wrapper.h>
84 #include "sock_destructor.h"
86 struct kmem_cache *skbuff_head_cache __ro_after_init;
87 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
88 #ifdef CONFIG_SKB_EXTENSIONS
89 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
91 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
92 EXPORT_SYMBOL(sysctl_max_skb_frags);
94 /* The array 'drop_reasons' is auto-generated in dropreason_str.c */
95 EXPORT_SYMBOL(drop_reasons);
98 * skb_panic - private function for out-of-line support
102 * @msg: skb_over_panic or skb_under_panic
104 * Out-of-line support for skb_put() and skb_push().
105 * Called via the wrapper skb_over_panic() or skb_under_panic().
106 * Keep out of line to prevent kernel bloat.
107 * __builtin_return_address is not used because it is not always reliable.
109 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
112 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
113 msg, addr, skb->len, sz, skb->head, skb->data,
114 (unsigned long)skb->tail, (unsigned long)skb->end,
115 skb->dev ? skb->dev->name : "<NULL>");
119 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
121 skb_panic(skb, sz, addr, __func__);
124 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
126 skb_panic(skb, sz, addr, __func__);
129 #define NAPI_SKB_CACHE_SIZE 64
130 #define NAPI_SKB_CACHE_BULK 16
131 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
133 struct napi_alloc_cache {
134 struct page_frag_cache page;
135 unsigned int skb_count;
136 void *skb_cache[NAPI_SKB_CACHE_SIZE];
139 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
140 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
142 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
144 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
146 fragsz = SKB_DATA_ALIGN(fragsz);
148 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
150 EXPORT_SYMBOL(__napi_alloc_frag_align);
152 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
156 fragsz = SKB_DATA_ALIGN(fragsz);
157 if (in_hardirq() || irqs_disabled()) {
158 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
160 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
162 struct napi_alloc_cache *nc;
165 nc = this_cpu_ptr(&napi_alloc_cache);
166 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
171 EXPORT_SYMBOL(__netdev_alloc_frag_align);
173 static struct sk_buff *napi_skb_cache_get(void)
175 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
178 if (unlikely(!nc->skb_count))
179 nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
183 if (unlikely(!nc->skb_count))
186 skb = nc->skb_cache[--nc->skb_count];
187 kasan_unpoison_object_data(skbuff_head_cache, skb);
192 /* Caller must provide SKB that is memset cleared */
193 static void __build_skb_around(struct sk_buff *skb, void *data,
194 unsigned int frag_size)
196 struct skb_shared_info *shinfo;
197 unsigned int size = frag_size ? : ksize(data);
199 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
201 /* Assumes caller memset cleared SKB */
202 skb->truesize = SKB_TRUESIZE(size);
203 refcount_set(&skb->users, 1);
206 skb_reset_tail_pointer(skb);
207 skb_set_end_offset(skb, size);
208 skb->mac_header = (typeof(skb->mac_header))~0U;
209 skb->transport_header = (typeof(skb->transport_header))~0U;
210 skb->alloc_cpu = raw_smp_processor_id();
211 /* make sure we initialize shinfo sequentially */
212 shinfo = skb_shinfo(skb);
213 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
214 atomic_set(&shinfo->dataref, 1);
216 skb_set_kcov_handle(skb, kcov_common_handle());
220 * __build_skb - build a network buffer
221 * @data: data buffer provided by caller
222 * @frag_size: size of data, or 0 if head was kmalloced
224 * Allocate a new &sk_buff. Caller provides space holding head and
225 * skb_shared_info. @data must have been allocated by kmalloc() only if
226 * @frag_size is 0, otherwise data should come from the page allocator
228 * The return is the new skb buffer.
229 * On a failure the return is %NULL, and @data is not freed.
231 * Before IO, driver allocates only data buffer where NIC put incoming frame
232 * Driver should add room at head (NET_SKB_PAD) and
233 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
234 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
235 * before giving packet to stack.
236 * RX rings only contains data buffers, not full skbs.
238 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
242 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
246 memset(skb, 0, offsetof(struct sk_buff, tail));
247 __build_skb_around(skb, data, frag_size);
252 /* build_skb() is wrapper over __build_skb(), that specifically
253 * takes care of skb->head and skb->pfmemalloc
254 * This means that if @frag_size is not zero, then @data must be backed
255 * by a page fragment, not kmalloc() or vmalloc()
257 struct sk_buff *build_skb(void *data, unsigned int frag_size)
259 struct sk_buff *skb = __build_skb(data, frag_size);
261 if (skb && frag_size) {
263 if (page_is_pfmemalloc(virt_to_head_page(data)))
268 EXPORT_SYMBOL(build_skb);
271 * build_skb_around - build a network buffer around provided skb
272 * @skb: sk_buff provide by caller, must be memset cleared
273 * @data: data buffer provided by caller
274 * @frag_size: size of data, or 0 if head was kmalloced
276 struct sk_buff *build_skb_around(struct sk_buff *skb,
277 void *data, unsigned int frag_size)
282 __build_skb_around(skb, data, frag_size);
286 if (page_is_pfmemalloc(virt_to_head_page(data)))
291 EXPORT_SYMBOL(build_skb_around);
294 * __napi_build_skb - build a network buffer
295 * @data: data buffer provided by caller
296 * @frag_size: size of data, or 0 if head was kmalloced
298 * Version of __build_skb() that uses NAPI percpu caches to obtain
299 * skbuff_head instead of inplace allocation.
301 * Returns a new &sk_buff on success, %NULL on allocation failure.
303 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
307 skb = napi_skb_cache_get();
311 memset(skb, 0, offsetof(struct sk_buff, tail));
312 __build_skb_around(skb, data, frag_size);
318 * napi_build_skb - build a network buffer
319 * @data: data buffer provided by caller
320 * @frag_size: size of data, or 0 if head was kmalloced
322 * Version of __napi_build_skb() that takes care of skb->head_frag
323 * and skb->pfmemalloc when the data is a page or page fragment.
325 * Returns a new &sk_buff on success, %NULL on allocation failure.
327 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
329 struct sk_buff *skb = __napi_build_skb(data, frag_size);
331 if (likely(skb) && frag_size) {
333 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
338 EXPORT_SYMBOL(napi_build_skb);
341 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
342 * the caller if emergency pfmemalloc reserves are being used. If it is and
343 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
344 * may be used. Otherwise, the packet data may be discarded until enough
347 static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
351 bool ret_pfmemalloc = false;
354 * Try a regular allocation, when that fails and we're not entitled
355 * to the reserves, fail.
357 obj = kmalloc_node_track_caller(size,
358 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
360 if (obj || !(gfp_pfmemalloc_allowed(flags)))
363 /* Try again but now we are using pfmemalloc reserves */
364 ret_pfmemalloc = true;
365 obj = kmalloc_node_track_caller(size, flags, node);
369 *pfmemalloc = ret_pfmemalloc;
374 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
375 * 'private' fields and also do memory statistics to find all the
381 * __alloc_skb - allocate a network buffer
382 * @size: size to allocate
383 * @gfp_mask: allocation mask
384 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
385 * instead of head cache and allocate a cloned (child) skb.
386 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
387 * allocations in case the data is required for writeback
388 * @node: numa node to allocate memory on
390 * Allocate a new &sk_buff. The returned buffer has no headroom and a
391 * tail room of at least size bytes. The object has a reference count
392 * of one. The return is the buffer. On a failure the return is %NULL.
394 * Buffers may only be allocated from interrupts using a @gfp_mask of
397 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
400 struct kmem_cache *cache;
406 cache = (flags & SKB_ALLOC_FCLONE)
407 ? skbuff_fclone_cache : skbuff_head_cache;
409 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
410 gfp_mask |= __GFP_MEMALLOC;
413 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
414 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
415 skb = napi_skb_cache_get();
417 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
422 /* We do our best to align skb_shared_info on a separate cache
423 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
424 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
425 * Both skb->head and skb_shared_info are cache line aligned.
427 size = SKB_DATA_ALIGN(size);
428 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
429 data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
432 /* kmalloc(size) might give us more room than requested.
433 * Put skb_shared_info exactly at the end of allocated zone,
434 * to allow max possible filling before reallocation.
437 size = SKB_WITH_OVERHEAD(osize);
438 prefetchw(data + size);
441 * Only clear those fields we need to clear, not those that we will
442 * actually initialise below. Hence, don't put any more fields after
443 * the tail pointer in struct sk_buff!
445 memset(skb, 0, offsetof(struct sk_buff, tail));
446 __build_skb_around(skb, data, osize);
447 skb->pfmemalloc = pfmemalloc;
449 if (flags & SKB_ALLOC_FCLONE) {
450 struct sk_buff_fclones *fclones;
452 fclones = container_of(skb, struct sk_buff_fclones, skb1);
454 skb->fclone = SKB_FCLONE_ORIG;
455 refcount_set(&fclones->fclone_ref, 1);
457 fclones->skb2.fclone = SKB_FCLONE_CLONE;
463 kmem_cache_free(cache, skb);
466 EXPORT_SYMBOL(__alloc_skb);
469 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
470 * @dev: network device to receive on
471 * @len: length to allocate
472 * @gfp_mask: get_free_pages mask, passed to alloc_skb
474 * Allocate a new &sk_buff and assign it a usage count of one. The
475 * buffer has NET_SKB_PAD headroom built in. Users should allocate
476 * the headroom they think they need without accounting for the
477 * built in space. The built in space is used for optimisations.
479 * %NULL is returned if there is no free memory.
481 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
484 struct page_frag_cache *nc;
491 /* If requested length is either too small or too big,
492 * we use kmalloc() for skb->head allocation.
494 if (len <= SKB_WITH_OVERHEAD(1024) ||
495 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
496 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
497 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
503 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
504 len = SKB_DATA_ALIGN(len);
506 if (sk_memalloc_socks())
507 gfp_mask |= __GFP_MEMALLOC;
509 if (in_hardirq() || irqs_disabled()) {
510 nc = this_cpu_ptr(&netdev_alloc_cache);
511 data = page_frag_alloc(nc, len, gfp_mask);
512 pfmemalloc = nc->pfmemalloc;
515 nc = this_cpu_ptr(&napi_alloc_cache.page);
516 data = page_frag_alloc(nc, len, gfp_mask);
517 pfmemalloc = nc->pfmemalloc;
524 skb = __build_skb(data, len);
525 if (unlikely(!skb)) {
535 skb_reserve(skb, NET_SKB_PAD);
541 EXPORT_SYMBOL(__netdev_alloc_skb);
544 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
545 * @napi: napi instance this buffer was allocated for
546 * @len: length to allocate
547 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
549 * Allocate a new sk_buff for use in NAPI receive. This buffer will
550 * attempt to allocate the head from a special reserved region used
551 * only for NAPI Rx allocation. By doing this we can save several
552 * CPU cycles by avoiding having to disable and re-enable IRQs.
554 * %NULL is returned if there is no free memory.
556 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
559 struct napi_alloc_cache *nc;
563 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
564 len += NET_SKB_PAD + NET_IP_ALIGN;
566 /* If requested length is either too small or too big,
567 * we use kmalloc() for skb->head allocation.
569 if (len <= SKB_WITH_OVERHEAD(1024) ||
570 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
571 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
572 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
579 nc = this_cpu_ptr(&napi_alloc_cache);
580 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
581 len = SKB_DATA_ALIGN(len);
583 if (sk_memalloc_socks())
584 gfp_mask |= __GFP_MEMALLOC;
586 data = page_frag_alloc(&nc->page, len, gfp_mask);
590 skb = __napi_build_skb(data, len);
591 if (unlikely(!skb)) {
596 if (nc->page.pfmemalloc)
601 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
602 skb->dev = napi->dev;
607 EXPORT_SYMBOL(__napi_alloc_skb);
609 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
610 int size, unsigned int truesize)
612 skb_fill_page_desc(skb, i, page, off, size);
614 skb->data_len += size;
615 skb->truesize += truesize;
617 EXPORT_SYMBOL(skb_add_rx_frag);
619 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
620 unsigned int truesize)
622 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
624 skb_frag_size_add(frag, size);
626 skb->data_len += size;
627 skb->truesize += truesize;
629 EXPORT_SYMBOL(skb_coalesce_rx_frag);
631 static void skb_drop_list(struct sk_buff **listp)
633 kfree_skb_list(*listp);
637 static inline void skb_drop_fraglist(struct sk_buff *skb)
639 skb_drop_list(&skb_shinfo(skb)->frag_list);
642 static void skb_clone_fraglist(struct sk_buff *skb)
644 struct sk_buff *list;
646 skb_walk_frags(skb, list)
650 static void skb_free_head(struct sk_buff *skb)
652 unsigned char *head = skb->head;
654 if (skb->head_frag) {
655 if (skb_pp_recycle(skb, head))
663 static void skb_release_data(struct sk_buff *skb)
665 struct skb_shared_info *shinfo = skb_shinfo(skb);
669 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
673 skb_zcopy_clear(skb, true);
675 for (i = 0; i < shinfo->nr_frags; i++)
676 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
678 if (shinfo->frag_list)
679 kfree_skb_list(shinfo->frag_list);
683 /* When we clone an SKB we copy the reycling bit. The pp_recycle
684 * bit is only set on the head though, so in order to avoid races
685 * while trying to recycle fragments on __skb_frag_unref() we need
686 * to make one SKB responsible for triggering the recycle path.
687 * So disable the recycling bit if an SKB is cloned and we have
688 * additional references to the fragmented part of the SKB.
689 * Eventually the last SKB will have the recycling bit set and it's
690 * dataref set to 0, which will trigger the recycling
696 * Free an skbuff by memory without cleaning the state.
698 static void kfree_skbmem(struct sk_buff *skb)
700 struct sk_buff_fclones *fclones;
702 switch (skb->fclone) {
703 case SKB_FCLONE_UNAVAILABLE:
704 kmem_cache_free(skbuff_head_cache, skb);
707 case SKB_FCLONE_ORIG:
708 fclones = container_of(skb, struct sk_buff_fclones, skb1);
710 /* We usually free the clone (TX completion) before original skb
711 * This test would have no chance to be true for the clone,
712 * while here, branch prediction will be good.
714 if (refcount_read(&fclones->fclone_ref) == 1)
718 default: /* SKB_FCLONE_CLONE */
719 fclones = container_of(skb, struct sk_buff_fclones, skb2);
722 if (!refcount_dec_and_test(&fclones->fclone_ref))
725 kmem_cache_free(skbuff_fclone_cache, fclones);
728 void skb_release_head_state(struct sk_buff *skb)
731 if (skb->destructor) {
732 DEBUG_NET_WARN_ON_ONCE(in_hardirq());
733 skb->destructor(skb);
735 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
736 nf_conntrack_put(skb_nfct(skb));
741 /* Free everything but the sk_buff shell. */
742 static void skb_release_all(struct sk_buff *skb)
744 skb_release_head_state(skb);
745 if (likely(skb->head))
746 skb_release_data(skb);
750 * __kfree_skb - private function
753 * Free an sk_buff. Release anything attached to the buffer.
754 * Clean the state. This is an internal helper function. Users should
755 * always call kfree_skb
758 void __kfree_skb(struct sk_buff *skb)
760 skb_release_all(skb);
763 EXPORT_SYMBOL(__kfree_skb);
766 * kfree_skb_reason - free an sk_buff with special reason
767 * @skb: buffer to free
768 * @reason: reason why this skb is dropped
770 * Drop a reference to the buffer and free it if the usage count has
771 * hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
774 void kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
779 DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
781 trace_kfree_skb(skb, __builtin_return_address(0), reason);
784 EXPORT_SYMBOL(kfree_skb_reason);
786 void kfree_skb_list_reason(struct sk_buff *segs,
787 enum skb_drop_reason reason)
790 struct sk_buff *next = segs->next;
792 kfree_skb_reason(segs, reason);
796 EXPORT_SYMBOL(kfree_skb_list_reason);
798 /* Dump skb information and contents.
800 * Must only be called from net_ratelimit()-ed paths.
802 * Dumps whole packets if full_pkt, only headers otherwise.
804 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
806 struct skb_shared_info *sh = skb_shinfo(skb);
807 struct net_device *dev = skb->dev;
808 struct sock *sk = skb->sk;
809 struct sk_buff *list_skb;
810 bool has_mac, has_trans;
811 int headroom, tailroom;
817 len = min_t(int, skb->len, MAX_HEADER + 128);
819 headroom = skb_headroom(skb);
820 tailroom = skb_tailroom(skb);
822 has_mac = skb_mac_header_was_set(skb);
823 has_trans = skb_transport_header_was_set(skb);
825 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
826 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
827 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
828 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
829 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
830 level, skb->len, headroom, skb_headlen(skb), tailroom,
831 has_mac ? skb->mac_header : -1,
832 has_mac ? skb_mac_header_len(skb) : -1,
834 has_trans ? skb_network_header_len(skb) : -1,
835 has_trans ? skb->transport_header : -1,
836 sh->tx_flags, sh->nr_frags,
837 sh->gso_size, sh->gso_type, sh->gso_segs,
838 skb->csum, skb->ip_summed, skb->csum_complete_sw,
839 skb->csum_valid, skb->csum_level,
840 skb->hash, skb->sw_hash, skb->l4_hash,
841 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
844 printk("%sdev name=%s feat=%pNF\n",
845 level, dev->name, &dev->features);
847 printk("%ssk family=%hu type=%u proto=%u\n",
848 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
850 if (full_pkt && headroom)
851 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
852 16, 1, skb->head, headroom, false);
854 seg_len = min_t(int, skb_headlen(skb), len);
856 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
857 16, 1, skb->data, seg_len, false);
860 if (full_pkt && tailroom)
861 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
862 16, 1, skb_tail_pointer(skb), tailroom, false);
864 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
865 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
866 u32 p_off, p_len, copied;
870 skb_frag_foreach_page(frag, skb_frag_off(frag),
871 skb_frag_size(frag), p, p_off, p_len,
873 seg_len = min_t(int, p_len, len);
874 vaddr = kmap_atomic(p);
875 print_hex_dump(level, "skb frag: ",
877 16, 1, vaddr + p_off, seg_len, false);
878 kunmap_atomic(vaddr);
885 if (full_pkt && skb_has_frag_list(skb)) {
886 printk("skb fraglist:\n");
887 skb_walk_frags(skb, list_skb)
888 skb_dump(level, list_skb, true);
891 EXPORT_SYMBOL(skb_dump);
894 * skb_tx_error - report an sk_buff xmit error
895 * @skb: buffer that triggered an error
897 * Report xmit error if a device callback is tracking this skb.
898 * skb must be freed afterwards.
900 void skb_tx_error(struct sk_buff *skb)
902 skb_zcopy_clear(skb, true);
904 EXPORT_SYMBOL(skb_tx_error);
906 #ifdef CONFIG_TRACEPOINTS
908 * consume_skb - free an skbuff
909 * @skb: buffer to free
911 * Drop a ref to the buffer and free it if the usage count has hit zero
912 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
913 * is being dropped after a failure and notes that
915 void consume_skb(struct sk_buff *skb)
920 trace_consume_skb(skb);
923 EXPORT_SYMBOL(consume_skb);
927 * __consume_stateless_skb - free an skbuff, assuming it is stateless
928 * @skb: buffer to free
930 * Alike consume_skb(), but this variant assumes that this is the last
931 * skb reference and all the head states have been already dropped
933 void __consume_stateless_skb(struct sk_buff *skb)
935 trace_consume_skb(skb);
936 skb_release_data(skb);
940 static void napi_skb_cache_put(struct sk_buff *skb)
942 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
945 kasan_poison_object_data(skbuff_head_cache, skb);
946 nc->skb_cache[nc->skb_count++] = skb;
948 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
949 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
950 kasan_unpoison_object_data(skbuff_head_cache,
953 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
954 nc->skb_cache + NAPI_SKB_CACHE_HALF);
955 nc->skb_count = NAPI_SKB_CACHE_HALF;
959 void __kfree_skb_defer(struct sk_buff *skb)
961 skb_release_all(skb);
962 napi_skb_cache_put(skb);
965 void napi_skb_free_stolen_head(struct sk_buff *skb)
967 if (unlikely(skb->slow_gro)) {
974 napi_skb_cache_put(skb);
977 void napi_consume_skb(struct sk_buff *skb, int budget)
979 /* Zero budget indicate non-NAPI context called us, like netpoll */
980 if (unlikely(!budget)) {
981 dev_consume_skb_any(skb);
985 DEBUG_NET_WARN_ON_ONCE(!in_softirq());
990 /* if reaching here SKB is ready to free */
991 trace_consume_skb(skb);
993 /* if SKB is a clone, don't handle this case */
994 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
999 skb_release_all(skb);
1000 napi_skb_cache_put(skb);
1002 EXPORT_SYMBOL(napi_consume_skb);
1004 /* Make sure a field is contained by headers group */
1005 #define CHECK_SKB_FIELD(field) \
1006 BUILD_BUG_ON(offsetof(struct sk_buff, field) != \
1007 offsetof(struct sk_buff, headers.field)); \
1009 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1011 new->tstamp = old->tstamp;
1012 /* We do not copy old->sk */
1013 new->dev = old->dev;
1014 memcpy(new->cb, old->cb, sizeof(old->cb));
1015 skb_dst_copy(new, old);
1016 __skb_ext_copy(new, old);
1017 __nf_copy(new, old, false);
1019 /* Note : this field could be in the headers group.
1020 * It is not yet because we do not want to have a 16 bit hole
1022 new->queue_mapping = old->queue_mapping;
1024 memcpy(&new->headers, &old->headers, sizeof(new->headers));
1025 CHECK_SKB_FIELD(protocol);
1026 CHECK_SKB_FIELD(csum);
1027 CHECK_SKB_FIELD(hash);
1028 CHECK_SKB_FIELD(priority);
1029 CHECK_SKB_FIELD(skb_iif);
1030 CHECK_SKB_FIELD(vlan_proto);
1031 CHECK_SKB_FIELD(vlan_tci);
1032 CHECK_SKB_FIELD(transport_header);
1033 CHECK_SKB_FIELD(network_header);
1034 CHECK_SKB_FIELD(mac_header);
1035 CHECK_SKB_FIELD(inner_protocol);
1036 CHECK_SKB_FIELD(inner_transport_header);
1037 CHECK_SKB_FIELD(inner_network_header);
1038 CHECK_SKB_FIELD(inner_mac_header);
1039 CHECK_SKB_FIELD(mark);
1040 #ifdef CONFIG_NETWORK_SECMARK
1041 CHECK_SKB_FIELD(secmark);
1043 #ifdef CONFIG_NET_RX_BUSY_POLL
1044 CHECK_SKB_FIELD(napi_id);
1046 CHECK_SKB_FIELD(alloc_cpu);
1048 CHECK_SKB_FIELD(sender_cpu);
1050 #ifdef CONFIG_NET_SCHED
1051 CHECK_SKB_FIELD(tc_index);
1057 * You should not add any new code to this function. Add it to
1058 * __copy_skb_header above instead.
1060 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1062 #define C(x) n->x = skb->x
1064 n->next = n->prev = NULL;
1066 __copy_skb_header(n, skb);
1071 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1077 n->destructor = NULL;
1084 refcount_set(&n->users, 1);
1086 atomic_inc(&(skb_shinfo(skb)->dataref));
1094 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1095 * @first: first sk_buff of the msg
1097 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1101 n = alloc_skb(0, GFP_ATOMIC);
1105 n->len = first->len;
1106 n->data_len = first->len;
1107 n->truesize = first->truesize;
1109 skb_shinfo(n)->frag_list = first;
1111 __copy_skb_header(n, first);
1112 n->destructor = NULL;
1116 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1119 * skb_morph - morph one skb into another
1120 * @dst: the skb to receive the contents
1121 * @src: the skb to supply the contents
1123 * This is identical to skb_clone except that the target skb is
1124 * supplied by the user.
1126 * The target skb is returned upon exit.
1128 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1130 skb_release_all(dst);
1131 return __skb_clone(dst, src);
1133 EXPORT_SYMBOL_GPL(skb_morph);
1135 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1137 unsigned long max_pg, num_pg, new_pg, old_pg;
1138 struct user_struct *user;
1140 if (capable(CAP_IPC_LOCK) || !size)
1143 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1144 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1145 user = mmp->user ? : current_user();
1148 old_pg = atomic_long_read(&user->locked_vm);
1149 new_pg = old_pg + num_pg;
1150 if (new_pg > max_pg)
1152 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1156 mmp->user = get_uid(user);
1157 mmp->num_pg = num_pg;
1159 mmp->num_pg += num_pg;
1164 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1166 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1169 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1170 free_uid(mmp->user);
1173 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1175 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1177 struct ubuf_info *uarg;
1178 struct sk_buff *skb;
1180 WARN_ON_ONCE(!in_task());
1182 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1186 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1187 uarg = (void *)skb->cb;
1188 uarg->mmp.user = NULL;
1190 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1195 uarg->callback = msg_zerocopy_callback;
1196 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1198 uarg->bytelen = size;
1200 uarg->flags = SKBFL_ZEROCOPY_FRAG;
1201 refcount_set(&uarg->refcnt, 1);
1207 static inline struct sk_buff *skb_from_uarg(struct ubuf_info *uarg)
1209 return container_of((void *)uarg, struct sk_buff, cb);
1212 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1213 struct ubuf_info *uarg)
1216 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1219 /* realloc only when socket is locked (TCP, UDP cork),
1220 * so uarg->len and sk_zckey access is serialized
1222 if (!sock_owned_by_user(sk)) {
1227 bytelen = uarg->bytelen + size;
1228 if (uarg->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1229 /* TCP can create new skb to attach new uarg */
1230 if (sk->sk_type == SOCK_STREAM)
1235 next = (u32)atomic_read(&sk->sk_zckey);
1236 if ((u32)(uarg->id + uarg->len) == next) {
1237 if (mm_account_pinned_pages(&uarg->mmp, size))
1240 uarg->bytelen = bytelen;
1241 atomic_set(&sk->sk_zckey, ++next);
1243 /* no extra ref when appending to datagram (MSG_MORE) */
1244 if (sk->sk_type == SOCK_STREAM)
1245 net_zcopy_get(uarg);
1252 return msg_zerocopy_alloc(sk, size);
1254 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1256 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1258 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1262 old_lo = serr->ee.ee_info;
1263 old_hi = serr->ee.ee_data;
1264 sum_len = old_hi - old_lo + 1ULL + len;
1266 if (sum_len >= (1ULL << 32))
1269 if (lo != old_hi + 1)
1272 serr->ee.ee_data += len;
1276 static void __msg_zerocopy_callback(struct ubuf_info *uarg)
1278 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1279 struct sock_exterr_skb *serr;
1280 struct sock *sk = skb->sk;
1281 struct sk_buff_head *q;
1282 unsigned long flags;
1287 mm_unaccount_pinned_pages(&uarg->mmp);
1289 /* if !len, there was only 1 call, and it was aborted
1290 * so do not queue a completion notification
1292 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1297 hi = uarg->id + len - 1;
1298 is_zerocopy = uarg->zerocopy;
1300 serr = SKB_EXT_ERR(skb);
1301 memset(serr, 0, sizeof(*serr));
1302 serr->ee.ee_errno = 0;
1303 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1304 serr->ee.ee_data = hi;
1305 serr->ee.ee_info = lo;
1307 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1309 q = &sk->sk_error_queue;
1310 spin_lock_irqsave(&q->lock, flags);
1311 tail = skb_peek_tail(q);
1312 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1313 !skb_zerocopy_notify_extend(tail, lo, len)) {
1314 __skb_queue_tail(q, skb);
1317 spin_unlock_irqrestore(&q->lock, flags);
1319 sk_error_report(sk);
1326 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1329 uarg->zerocopy = uarg->zerocopy & success;
1331 if (refcount_dec_and_test(&uarg->refcnt))
1332 __msg_zerocopy_callback(uarg);
1334 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1336 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1338 struct sock *sk = skb_from_uarg(uarg)->sk;
1340 atomic_dec(&sk->sk_zckey);
1344 msg_zerocopy_callback(NULL, uarg, true);
1346 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1348 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1349 struct msghdr *msg, int len,
1350 struct ubuf_info *uarg)
1352 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1353 int err, orig_len = skb->len;
1355 /* An skb can only point to one uarg. This edge case happens when
1356 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1358 if (orig_uarg && uarg != orig_uarg)
1361 err = __zerocopy_sg_from_iter(sk, skb, &msg->msg_iter, len);
1362 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1363 struct sock *save_sk = skb->sk;
1365 /* Streams do not free skb on error. Reset to prev state. */
1366 iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1368 ___pskb_trim(skb, orig_len);
1373 skb_zcopy_set(skb, uarg, NULL);
1374 return skb->len - orig_len;
1376 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1378 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1381 if (skb_zcopy(orig)) {
1382 if (skb_zcopy(nskb)) {
1383 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1388 if (skb_uarg(nskb) == skb_uarg(orig))
1390 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1393 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1399 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1400 * @skb: the skb to modify
1401 * @gfp_mask: allocation priority
1403 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1404 * It will copy all frags into kernel and drop the reference
1405 * to userspace pages.
1407 * If this function is called from an interrupt gfp_mask() must be
1410 * Returns 0 on success or a negative error code on failure
1411 * to allocate kernel memory to copy to.
1413 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1415 int num_frags = skb_shinfo(skb)->nr_frags;
1416 struct page *page, *head = NULL;
1420 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1426 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1427 for (i = 0; i < new_frags; i++) {
1428 page = alloc_page(gfp_mask);
1431 struct page *next = (struct page *)page_private(head);
1437 set_page_private(page, (unsigned long)head);
1443 for (i = 0; i < num_frags; i++) {
1444 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1445 u32 p_off, p_len, copied;
1449 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1450 p, p_off, p_len, copied) {
1452 vaddr = kmap_atomic(p);
1454 while (done < p_len) {
1455 if (d_off == PAGE_SIZE) {
1457 page = (struct page *)page_private(page);
1459 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1460 memcpy(page_address(page) + d_off,
1461 vaddr + p_off + done, copy);
1465 kunmap_atomic(vaddr);
1469 /* skb frags release userspace buffers */
1470 for (i = 0; i < num_frags; i++)
1471 skb_frag_unref(skb, i);
1473 /* skb frags point to kernel buffers */
1474 for (i = 0; i < new_frags - 1; i++) {
1475 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1476 head = (struct page *)page_private(head);
1478 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1479 skb_shinfo(skb)->nr_frags = new_frags;
1482 skb_zcopy_clear(skb, false);
1485 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1488 * skb_clone - duplicate an sk_buff
1489 * @skb: buffer to clone
1490 * @gfp_mask: allocation priority
1492 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1493 * copies share the same packet data but not structure. The new
1494 * buffer has a reference count of 1. If the allocation fails the
1495 * function returns %NULL otherwise the new buffer is returned.
1497 * If this function is called from an interrupt gfp_mask() must be
1501 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1503 struct sk_buff_fclones *fclones = container_of(skb,
1504 struct sk_buff_fclones,
1508 if (skb_orphan_frags(skb, gfp_mask))
1511 if (skb->fclone == SKB_FCLONE_ORIG &&
1512 refcount_read(&fclones->fclone_ref) == 1) {
1514 refcount_set(&fclones->fclone_ref, 2);
1516 if (skb_pfmemalloc(skb))
1517 gfp_mask |= __GFP_MEMALLOC;
1519 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1523 n->fclone = SKB_FCLONE_UNAVAILABLE;
1526 return __skb_clone(n, skb);
1528 EXPORT_SYMBOL(skb_clone);
1530 void skb_headers_offset_update(struct sk_buff *skb, int off)
1532 /* Only adjust this if it actually is csum_start rather than csum */
1533 if (skb->ip_summed == CHECKSUM_PARTIAL)
1534 skb->csum_start += off;
1535 /* {transport,network,mac}_header and tail are relative to skb->head */
1536 skb->transport_header += off;
1537 skb->network_header += off;
1538 if (skb_mac_header_was_set(skb))
1539 skb->mac_header += off;
1540 skb->inner_transport_header += off;
1541 skb->inner_network_header += off;
1542 skb->inner_mac_header += off;
1544 EXPORT_SYMBOL(skb_headers_offset_update);
1546 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1548 __copy_skb_header(new, old);
1550 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1551 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1552 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1554 EXPORT_SYMBOL(skb_copy_header);
1556 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1558 if (skb_pfmemalloc(skb))
1559 return SKB_ALLOC_RX;
1564 * skb_copy - create private copy of an sk_buff
1565 * @skb: buffer to copy
1566 * @gfp_mask: allocation priority
1568 * Make a copy of both an &sk_buff and its data. This is used when the
1569 * caller wishes to modify the data and needs a private copy of the
1570 * data to alter. Returns %NULL on failure or the pointer to the buffer
1571 * on success. The returned buffer has a reference count of 1.
1573 * As by-product this function converts non-linear &sk_buff to linear
1574 * one, so that &sk_buff becomes completely private and caller is allowed
1575 * to modify all the data of returned buffer. This means that this
1576 * function is not recommended for use in circumstances when only
1577 * header is going to be modified. Use pskb_copy() instead.
1580 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1582 int headerlen = skb_headroom(skb);
1583 unsigned int size = skb_end_offset(skb) + skb->data_len;
1584 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1585 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1590 /* Set the data pointer */
1591 skb_reserve(n, headerlen);
1592 /* Set the tail pointer and length */
1593 skb_put(n, skb->len);
1595 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1597 skb_copy_header(n, skb);
1600 EXPORT_SYMBOL(skb_copy);
1603 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1604 * @skb: buffer to copy
1605 * @headroom: headroom of new skb
1606 * @gfp_mask: allocation priority
1607 * @fclone: if true allocate the copy of the skb from the fclone
1608 * cache instead of the head cache; it is recommended to set this
1609 * to true for the cases where the copy will likely be cloned
1611 * Make a copy of both an &sk_buff and part of its data, located
1612 * in header. Fragmented data remain shared. This is used when
1613 * the caller wishes to modify only header of &sk_buff and needs
1614 * private copy of the header to alter. Returns %NULL on failure
1615 * or the pointer to the buffer on success.
1616 * The returned buffer has a reference count of 1.
1619 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1620 gfp_t gfp_mask, bool fclone)
1622 unsigned int size = skb_headlen(skb) + headroom;
1623 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1624 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1629 /* Set the data pointer */
1630 skb_reserve(n, headroom);
1631 /* Set the tail pointer and length */
1632 skb_put(n, skb_headlen(skb));
1633 /* Copy the bytes */
1634 skb_copy_from_linear_data(skb, n->data, n->len);
1636 n->truesize += skb->data_len;
1637 n->data_len = skb->data_len;
1640 if (skb_shinfo(skb)->nr_frags) {
1643 if (skb_orphan_frags(skb, gfp_mask) ||
1644 skb_zerocopy_clone(n, skb, gfp_mask)) {
1649 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1650 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1651 skb_frag_ref(skb, i);
1653 skb_shinfo(n)->nr_frags = i;
1656 if (skb_has_frag_list(skb)) {
1657 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1658 skb_clone_fraglist(n);
1661 skb_copy_header(n, skb);
1665 EXPORT_SYMBOL(__pskb_copy_fclone);
1668 * pskb_expand_head - reallocate header of &sk_buff
1669 * @skb: buffer to reallocate
1670 * @nhead: room to add at head
1671 * @ntail: room to add at tail
1672 * @gfp_mask: allocation priority
1674 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1675 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1676 * reference count of 1. Returns zero in the case of success or error,
1677 * if expansion failed. In the last case, &sk_buff is not changed.
1679 * All the pointers pointing into skb header may change and must be
1680 * reloaded after call to this function.
1683 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1686 int i, osize = skb_end_offset(skb);
1687 int size = osize + nhead + ntail;
1693 BUG_ON(skb_shared(skb));
1695 size = SKB_DATA_ALIGN(size);
1697 if (skb_pfmemalloc(skb))
1698 gfp_mask |= __GFP_MEMALLOC;
1699 data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1700 gfp_mask, NUMA_NO_NODE, NULL);
1703 size = SKB_WITH_OVERHEAD(ksize(data));
1705 /* Copy only real data... and, alas, header. This should be
1706 * optimized for the cases when header is void.
1708 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1710 memcpy((struct skb_shared_info *)(data + size),
1712 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1715 * if shinfo is shared we must drop the old head gracefully, but if it
1716 * is not we can just drop the old head and let the existing refcount
1717 * be since all we did is relocate the values
1719 if (skb_cloned(skb)) {
1720 if (skb_orphan_frags(skb, gfp_mask))
1723 refcount_inc(&skb_uarg(skb)->refcnt);
1724 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1725 skb_frag_ref(skb, i);
1727 if (skb_has_frag_list(skb))
1728 skb_clone_fraglist(skb);
1730 skb_release_data(skb);
1734 off = (data + nhead) - skb->head;
1740 skb_set_end_offset(skb, size);
1741 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1745 skb_headers_offset_update(skb, nhead);
1749 atomic_set(&skb_shinfo(skb)->dataref, 1);
1751 skb_metadata_clear(skb);
1753 /* It is not generally safe to change skb->truesize.
1754 * For the moment, we really care of rx path, or
1755 * when skb is orphaned (not attached to a socket).
1757 if (!skb->sk || skb->destructor == sock_edemux)
1758 skb->truesize += size - osize;
1767 EXPORT_SYMBOL(pskb_expand_head);
1769 /* Make private copy of skb with writable head and some headroom */
1771 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1773 struct sk_buff *skb2;
1774 int delta = headroom - skb_headroom(skb);
1777 skb2 = pskb_copy(skb, GFP_ATOMIC);
1779 skb2 = skb_clone(skb, GFP_ATOMIC);
1780 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1788 EXPORT_SYMBOL(skb_realloc_headroom);
1790 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1792 unsigned int saved_end_offset, saved_truesize;
1793 struct skb_shared_info *shinfo;
1796 saved_end_offset = skb_end_offset(skb);
1797 saved_truesize = skb->truesize;
1799 res = pskb_expand_head(skb, 0, 0, pri);
1803 skb->truesize = saved_truesize;
1805 if (likely(skb_end_offset(skb) == saved_end_offset))
1808 shinfo = skb_shinfo(skb);
1810 /* We are about to change back skb->end,
1811 * we need to move skb_shinfo() to its new location.
1813 memmove(skb->head + saved_end_offset,
1815 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1817 skb_set_end_offset(skb, saved_end_offset);
1823 * skb_expand_head - reallocate header of &sk_buff
1824 * @skb: buffer to reallocate
1825 * @headroom: needed headroom
1827 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1828 * if possible; copies skb->sk to new skb as needed
1829 * and frees original skb in case of failures.
1831 * It expect increased headroom and generates warning otherwise.
1834 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1836 int delta = headroom - skb_headroom(skb);
1837 int osize = skb_end_offset(skb);
1838 struct sock *sk = skb->sk;
1840 if (WARN_ONCE(delta <= 0,
1841 "%s is expecting an increase in the headroom", __func__))
1844 delta = SKB_DATA_ALIGN(delta);
1845 /* pskb_expand_head() might crash, if skb is shared. */
1846 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1847 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1849 if (unlikely(!nskb))
1853 skb_set_owner_w(nskb, sk);
1857 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
1860 if (sk && is_skb_wmem(skb)) {
1861 delta = skb_end_offset(skb) - osize;
1862 refcount_add(delta, &sk->sk_wmem_alloc);
1863 skb->truesize += delta;
1871 EXPORT_SYMBOL(skb_expand_head);
1874 * skb_copy_expand - copy and expand sk_buff
1875 * @skb: buffer to copy
1876 * @newheadroom: new free bytes at head
1877 * @newtailroom: new free bytes at tail
1878 * @gfp_mask: allocation priority
1880 * Make a copy of both an &sk_buff and its data and while doing so
1881 * allocate additional space.
1883 * This is used when the caller wishes to modify the data and needs a
1884 * private copy of the data to alter as well as more space for new fields.
1885 * Returns %NULL on failure or the pointer to the buffer
1886 * on success. The returned buffer has a reference count of 1.
1888 * You must pass %GFP_ATOMIC as the allocation priority if this function
1889 * is called from an interrupt.
1891 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1892 int newheadroom, int newtailroom,
1896 * Allocate the copy buffer
1898 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1899 gfp_mask, skb_alloc_rx_flag(skb),
1901 int oldheadroom = skb_headroom(skb);
1902 int head_copy_len, head_copy_off;
1907 skb_reserve(n, newheadroom);
1909 /* Set the tail pointer and length */
1910 skb_put(n, skb->len);
1912 head_copy_len = oldheadroom;
1914 if (newheadroom <= head_copy_len)
1915 head_copy_len = newheadroom;
1917 head_copy_off = newheadroom - head_copy_len;
1919 /* Copy the linear header and data. */
1920 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1921 skb->len + head_copy_len));
1923 skb_copy_header(n, skb);
1925 skb_headers_offset_update(n, newheadroom - oldheadroom);
1929 EXPORT_SYMBOL(skb_copy_expand);
1932 * __skb_pad - zero pad the tail of an skb
1933 * @skb: buffer to pad
1934 * @pad: space to pad
1935 * @free_on_error: free buffer on error
1937 * Ensure that a buffer is followed by a padding area that is zero
1938 * filled. Used by network drivers which may DMA or transfer data
1939 * beyond the buffer end onto the wire.
1941 * May return error in out of memory cases. The skb is freed on error
1942 * if @free_on_error is true.
1945 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
1950 /* If the skbuff is non linear tailroom is always zero.. */
1951 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1952 memset(skb->data+skb->len, 0, pad);
1956 ntail = skb->data_len + pad - (skb->end - skb->tail);
1957 if (likely(skb_cloned(skb) || ntail > 0)) {
1958 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1963 /* FIXME: The use of this function with non-linear skb's really needs
1966 err = skb_linearize(skb);
1970 memset(skb->data + skb->len, 0, pad);
1978 EXPORT_SYMBOL(__skb_pad);
1981 * pskb_put - add data to the tail of a potentially fragmented buffer
1982 * @skb: start of the buffer to use
1983 * @tail: tail fragment of the buffer to use
1984 * @len: amount of data to add
1986 * This function extends the used data area of the potentially
1987 * fragmented buffer. @tail must be the last fragment of @skb -- or
1988 * @skb itself. If this would exceed the total buffer size the kernel
1989 * will panic. A pointer to the first byte of the extra data is
1993 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
1996 skb->data_len += len;
1999 return skb_put(tail, len);
2001 EXPORT_SYMBOL_GPL(pskb_put);
2004 * skb_put - add data to a buffer
2005 * @skb: buffer to use
2006 * @len: amount of data to add
2008 * This function extends the used data area of the buffer. If this would
2009 * exceed the total buffer size the kernel will panic. A pointer to the
2010 * first byte of the extra data is returned.
2012 void *skb_put(struct sk_buff *skb, unsigned int len)
2014 void *tmp = skb_tail_pointer(skb);
2015 SKB_LINEAR_ASSERT(skb);
2018 if (unlikely(skb->tail > skb->end))
2019 skb_over_panic(skb, len, __builtin_return_address(0));
2022 EXPORT_SYMBOL(skb_put);
2025 * skb_push - add data to the start of a buffer
2026 * @skb: buffer to use
2027 * @len: amount of data to add
2029 * This function extends the used data area of the buffer at the buffer
2030 * start. If this would exceed the total buffer headroom the kernel will
2031 * panic. A pointer to the first byte of the extra data is returned.
2033 void *skb_push(struct sk_buff *skb, unsigned int len)
2037 if (unlikely(skb->data < skb->head))
2038 skb_under_panic(skb, len, __builtin_return_address(0));
2041 EXPORT_SYMBOL(skb_push);
2044 * skb_pull - remove data from the start of a buffer
2045 * @skb: buffer to use
2046 * @len: amount of data to remove
2048 * This function removes data from the start of a buffer, returning
2049 * the memory to the headroom. A pointer to the next data in the buffer
2050 * is returned. Once the data has been pulled future pushes will overwrite
2053 void *skb_pull(struct sk_buff *skb, unsigned int len)
2055 return skb_pull_inline(skb, len);
2057 EXPORT_SYMBOL(skb_pull);
2060 * skb_pull_data - remove data from the start of a buffer returning its
2061 * original position.
2062 * @skb: buffer to use
2063 * @len: amount of data to remove
2065 * This function removes data from the start of a buffer, returning
2066 * the memory to the headroom. A pointer to the original data in the buffer
2067 * is returned after checking if there is enough data to pull. Once the
2068 * data has been pulled future pushes will overwrite the old data.
2070 void *skb_pull_data(struct sk_buff *skb, size_t len)
2072 void *data = skb->data;
2081 EXPORT_SYMBOL(skb_pull_data);
2084 * skb_trim - remove end from a buffer
2085 * @skb: buffer to alter
2088 * Cut the length of a buffer down by removing data from the tail. If
2089 * the buffer is already under the length specified it is not modified.
2090 * The skb must be linear.
2092 void skb_trim(struct sk_buff *skb, unsigned int len)
2095 __skb_trim(skb, len);
2097 EXPORT_SYMBOL(skb_trim);
2099 /* Trims skb to length len. It can change skb pointers.
2102 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2104 struct sk_buff **fragp;
2105 struct sk_buff *frag;
2106 int offset = skb_headlen(skb);
2107 int nfrags = skb_shinfo(skb)->nr_frags;
2111 if (skb_cloned(skb) &&
2112 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2119 for (; i < nfrags; i++) {
2120 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2127 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2130 skb_shinfo(skb)->nr_frags = i;
2132 for (; i < nfrags; i++)
2133 skb_frag_unref(skb, i);
2135 if (skb_has_frag_list(skb))
2136 skb_drop_fraglist(skb);
2140 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2141 fragp = &frag->next) {
2142 int end = offset + frag->len;
2144 if (skb_shared(frag)) {
2145 struct sk_buff *nfrag;
2147 nfrag = skb_clone(frag, GFP_ATOMIC);
2148 if (unlikely(!nfrag))
2151 nfrag->next = frag->next;
2163 unlikely((err = pskb_trim(frag, len - offset))))
2167 skb_drop_list(&frag->next);
2172 if (len > skb_headlen(skb)) {
2173 skb->data_len -= skb->len - len;
2178 skb_set_tail_pointer(skb, len);
2181 if (!skb->sk || skb->destructor == sock_edemux)
2185 EXPORT_SYMBOL(___pskb_trim);
2187 /* Note : use pskb_trim_rcsum() instead of calling this directly
2189 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2191 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2192 int delta = skb->len - len;
2194 skb->csum = csum_block_sub(skb->csum,
2195 skb_checksum(skb, len, delta, 0),
2197 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2198 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2199 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2201 if (offset + sizeof(__sum16) > hdlen)
2204 return __pskb_trim(skb, len);
2206 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2209 * __pskb_pull_tail - advance tail of skb header
2210 * @skb: buffer to reallocate
2211 * @delta: number of bytes to advance tail
2213 * The function makes a sense only on a fragmented &sk_buff,
2214 * it expands header moving its tail forward and copying necessary
2215 * data from fragmented part.
2217 * &sk_buff MUST have reference count of 1.
2219 * Returns %NULL (and &sk_buff does not change) if pull failed
2220 * or value of new tail of skb in the case of success.
2222 * All the pointers pointing into skb header may change and must be
2223 * reloaded after call to this function.
2226 /* Moves tail of skb head forward, copying data from fragmented part,
2227 * when it is necessary.
2228 * 1. It may fail due to malloc failure.
2229 * 2. It may change skb pointers.
2231 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2233 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2235 /* If skb has not enough free space at tail, get new one
2236 * plus 128 bytes for future expansions. If we have enough
2237 * room at tail, reallocate without expansion only if skb is cloned.
2239 int i, k, eat = (skb->tail + delta) - skb->end;
2241 if (eat > 0 || skb_cloned(skb)) {
2242 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2247 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2248 skb_tail_pointer(skb), delta));
2250 /* Optimization: no fragments, no reasons to preestimate
2251 * size of pulled pages. Superb.
2253 if (!skb_has_frag_list(skb))
2256 /* Estimate size of pulled pages. */
2258 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2259 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2266 /* If we need update frag list, we are in troubles.
2267 * Certainly, it is possible to add an offset to skb data,
2268 * but taking into account that pulling is expected to
2269 * be very rare operation, it is worth to fight against
2270 * further bloating skb head and crucify ourselves here instead.
2271 * Pure masohism, indeed. 8)8)
2274 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2275 struct sk_buff *clone = NULL;
2276 struct sk_buff *insp = NULL;
2279 if (list->len <= eat) {
2280 /* Eaten as whole. */
2285 /* Eaten partially. */
2287 if (skb_shared(list)) {
2288 /* Sucks! We need to fork list. :-( */
2289 clone = skb_clone(list, GFP_ATOMIC);
2295 /* This may be pulled without
2299 if (!pskb_pull(list, eat)) {
2307 /* Free pulled out fragments. */
2308 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2309 skb_shinfo(skb)->frag_list = list->next;
2312 /* And insert new clone at head. */
2315 skb_shinfo(skb)->frag_list = clone;
2318 /* Success! Now we may commit changes to skb data. */
2323 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2324 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2327 skb_frag_unref(skb, i);
2330 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2332 *frag = skb_shinfo(skb)->frags[i];
2334 skb_frag_off_add(frag, eat);
2335 skb_frag_size_sub(frag, eat);
2343 skb_shinfo(skb)->nr_frags = k;
2347 skb->data_len -= delta;
2350 skb_zcopy_clear(skb, false);
2352 return skb_tail_pointer(skb);
2354 EXPORT_SYMBOL(__pskb_pull_tail);
2357 * skb_copy_bits - copy bits from skb to kernel buffer
2359 * @offset: offset in source
2360 * @to: destination buffer
2361 * @len: number of bytes to copy
2363 * Copy the specified number of bytes from the source skb to the
2364 * destination buffer.
2367 * If its prototype is ever changed,
2368 * check arch/{*}/net/{*}.S files,
2369 * since it is called from BPF assembly code.
2371 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2373 int start = skb_headlen(skb);
2374 struct sk_buff *frag_iter;
2377 if (offset > (int)skb->len - len)
2381 if ((copy = start - offset) > 0) {
2384 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2385 if ((len -= copy) == 0)
2391 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2393 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2395 WARN_ON(start > offset + len);
2397 end = start + skb_frag_size(f);
2398 if ((copy = end - offset) > 0) {
2399 u32 p_off, p_len, copied;
2406 skb_frag_foreach_page(f,
2407 skb_frag_off(f) + offset - start,
2408 copy, p, p_off, p_len, copied) {
2409 vaddr = kmap_atomic(p);
2410 memcpy(to + copied, vaddr + p_off, p_len);
2411 kunmap_atomic(vaddr);
2414 if ((len -= copy) == 0)
2422 skb_walk_frags(skb, frag_iter) {
2425 WARN_ON(start > offset + len);
2427 end = start + frag_iter->len;
2428 if ((copy = end - offset) > 0) {
2431 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2433 if ((len -= copy) == 0)
2447 EXPORT_SYMBOL(skb_copy_bits);
2450 * Callback from splice_to_pipe(), if we need to release some pages
2451 * at the end of the spd in case we error'ed out in filling the pipe.
2453 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2455 put_page(spd->pages[i]);
2458 static struct page *linear_to_page(struct page *page, unsigned int *len,
2459 unsigned int *offset,
2462 struct page_frag *pfrag = sk_page_frag(sk);
2464 if (!sk_page_frag_refill(sk, pfrag))
2467 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2469 memcpy(page_address(pfrag->page) + pfrag->offset,
2470 page_address(page) + *offset, *len);
2471 *offset = pfrag->offset;
2472 pfrag->offset += *len;
2477 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2479 unsigned int offset)
2481 return spd->nr_pages &&
2482 spd->pages[spd->nr_pages - 1] == page &&
2483 (spd->partial[spd->nr_pages - 1].offset +
2484 spd->partial[spd->nr_pages - 1].len == offset);
2488 * Fill page/offset/length into spd, if it can hold more pages.
2490 static bool spd_fill_page(struct splice_pipe_desc *spd,
2491 struct pipe_inode_info *pipe, struct page *page,
2492 unsigned int *len, unsigned int offset,
2496 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2500 page = linear_to_page(page, len, &offset, sk);
2504 if (spd_can_coalesce(spd, page, offset)) {
2505 spd->partial[spd->nr_pages - 1].len += *len;
2509 spd->pages[spd->nr_pages] = page;
2510 spd->partial[spd->nr_pages].len = *len;
2511 spd->partial[spd->nr_pages].offset = offset;
2517 static bool __splice_segment(struct page *page, unsigned int poff,
2518 unsigned int plen, unsigned int *off,
2520 struct splice_pipe_desc *spd, bool linear,
2522 struct pipe_inode_info *pipe)
2527 /* skip this segment if already processed */
2533 /* ignore any bits we already processed */
2539 unsigned int flen = min(*len, plen);
2541 if (spd_fill_page(spd, pipe, page, &flen, poff,
2547 } while (*len && plen);
2553 * Map linear and fragment data from the skb to spd. It reports true if the
2554 * pipe is full or if we already spliced the requested length.
2556 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2557 unsigned int *offset, unsigned int *len,
2558 struct splice_pipe_desc *spd, struct sock *sk)
2561 struct sk_buff *iter;
2563 /* map the linear part :
2564 * If skb->head_frag is set, this 'linear' part is backed by a
2565 * fragment, and if the head is not shared with any clones then
2566 * we can avoid a copy since we own the head portion of this page.
2568 if (__splice_segment(virt_to_page(skb->data),
2569 (unsigned long) skb->data & (PAGE_SIZE - 1),
2572 skb_head_is_locked(skb),
2577 * then map the fragments
2579 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2580 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2582 if (__splice_segment(skb_frag_page(f),
2583 skb_frag_off(f), skb_frag_size(f),
2584 offset, len, spd, false, sk, pipe))
2588 skb_walk_frags(skb, iter) {
2589 if (*offset >= iter->len) {
2590 *offset -= iter->len;
2593 /* __skb_splice_bits() only fails if the output has no room
2594 * left, so no point in going over the frag_list for the error
2597 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2605 * Map data from the skb to a pipe. Should handle both the linear part,
2606 * the fragments, and the frag list.
2608 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2609 struct pipe_inode_info *pipe, unsigned int tlen,
2612 struct partial_page partial[MAX_SKB_FRAGS];
2613 struct page *pages[MAX_SKB_FRAGS];
2614 struct splice_pipe_desc spd = {
2617 .nr_pages_max = MAX_SKB_FRAGS,
2618 .ops = &nosteal_pipe_buf_ops,
2619 .spd_release = sock_spd_release,
2623 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2626 ret = splice_to_pipe(pipe, &spd);
2630 EXPORT_SYMBOL_GPL(skb_splice_bits);
2632 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2633 struct kvec *vec, size_t num, size_t size)
2635 struct socket *sock = sk->sk_socket;
2639 return kernel_sendmsg(sock, msg, vec, num, size);
2642 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2643 size_t size, int flags)
2645 struct socket *sock = sk->sk_socket;
2649 return kernel_sendpage(sock, page, offset, size, flags);
2652 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2653 struct kvec *vec, size_t num, size_t size);
2654 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2655 size_t size, int flags);
2656 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2657 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2659 unsigned int orig_len = len;
2660 struct sk_buff *head = skb;
2661 unsigned short fragidx;
2666 /* Deal with head data */
2667 while (offset < skb_headlen(skb) && len) {
2671 slen = min_t(int, len, skb_headlen(skb) - offset);
2672 kv.iov_base = skb->data + offset;
2674 memset(&msg, 0, sizeof(msg));
2675 msg.msg_flags = MSG_DONTWAIT;
2677 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2678 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2686 /* All the data was skb head? */
2690 /* Make offset relative to start of frags */
2691 offset -= skb_headlen(skb);
2693 /* Find where we are in frag list */
2694 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2695 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2697 if (offset < skb_frag_size(frag))
2700 offset -= skb_frag_size(frag);
2703 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2704 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2706 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2709 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2710 sendpage_unlocked, sk,
2711 skb_frag_page(frag),
2712 skb_frag_off(frag) + offset,
2713 slen, MSG_DONTWAIT);
2726 /* Process any frag lists */
2729 if (skb_has_frag_list(skb)) {
2730 skb = skb_shinfo(skb)->frag_list;
2733 } else if (skb->next) {
2740 return orig_len - len;
2743 return orig_len == len ? ret : orig_len - len;
2746 /* Send skb data on a socket. Socket must be locked. */
2747 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2750 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2751 kernel_sendpage_locked);
2753 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2755 /* Send skb data on a socket. Socket must be unlocked. */
2756 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2758 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2763 * skb_store_bits - store bits from kernel buffer to skb
2764 * @skb: destination buffer
2765 * @offset: offset in destination
2766 * @from: source buffer
2767 * @len: number of bytes to copy
2769 * Copy the specified number of bytes from the source buffer to the
2770 * destination skb. This function handles all the messy bits of
2771 * traversing fragment lists and such.
2774 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2776 int start = skb_headlen(skb);
2777 struct sk_buff *frag_iter;
2780 if (offset > (int)skb->len - len)
2783 if ((copy = start - offset) > 0) {
2786 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2787 if ((len -= copy) == 0)
2793 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2794 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2797 WARN_ON(start > offset + len);
2799 end = start + skb_frag_size(frag);
2800 if ((copy = end - offset) > 0) {
2801 u32 p_off, p_len, copied;
2808 skb_frag_foreach_page(frag,
2809 skb_frag_off(frag) + offset - start,
2810 copy, p, p_off, p_len, copied) {
2811 vaddr = kmap_atomic(p);
2812 memcpy(vaddr + p_off, from + copied, p_len);
2813 kunmap_atomic(vaddr);
2816 if ((len -= copy) == 0)
2824 skb_walk_frags(skb, frag_iter) {
2827 WARN_ON(start > offset + len);
2829 end = start + frag_iter->len;
2830 if ((copy = end - offset) > 0) {
2833 if (skb_store_bits(frag_iter, offset - start,
2836 if ((len -= copy) == 0)
2849 EXPORT_SYMBOL(skb_store_bits);
2851 /* Checksum skb data. */
2852 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2853 __wsum csum, const struct skb_checksum_ops *ops)
2855 int start = skb_headlen(skb);
2856 int i, copy = start - offset;
2857 struct sk_buff *frag_iter;
2860 /* Checksum header. */
2864 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
2865 skb->data + offset, copy, csum);
2866 if ((len -= copy) == 0)
2872 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2874 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2876 WARN_ON(start > offset + len);
2878 end = start + skb_frag_size(frag);
2879 if ((copy = end - offset) > 0) {
2880 u32 p_off, p_len, copied;
2888 skb_frag_foreach_page(frag,
2889 skb_frag_off(frag) + offset - start,
2890 copy, p, p_off, p_len, copied) {
2891 vaddr = kmap_atomic(p);
2892 csum2 = INDIRECT_CALL_1(ops->update,
2894 vaddr + p_off, p_len, 0);
2895 kunmap_atomic(vaddr);
2896 csum = INDIRECT_CALL_1(ops->combine,
2897 csum_block_add_ext, csum,
2909 skb_walk_frags(skb, frag_iter) {
2912 WARN_ON(start > offset + len);
2914 end = start + frag_iter->len;
2915 if ((copy = end - offset) > 0) {
2919 csum2 = __skb_checksum(frag_iter, offset - start,
2921 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
2922 csum, csum2, pos, copy);
2923 if ((len -= copy) == 0)
2934 EXPORT_SYMBOL(__skb_checksum);
2936 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2937 int len, __wsum csum)
2939 const struct skb_checksum_ops ops = {
2940 .update = csum_partial_ext,
2941 .combine = csum_block_add_ext,
2944 return __skb_checksum(skb, offset, len, csum, &ops);
2946 EXPORT_SYMBOL(skb_checksum);
2948 /* Both of above in one bottle. */
2950 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2953 int start = skb_headlen(skb);
2954 int i, copy = start - offset;
2955 struct sk_buff *frag_iter;
2963 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2965 if ((len -= copy) == 0)
2972 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2975 WARN_ON(start > offset + len);
2977 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2978 if ((copy = end - offset) > 0) {
2979 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2980 u32 p_off, p_len, copied;
2988 skb_frag_foreach_page(frag,
2989 skb_frag_off(frag) + offset - start,
2990 copy, p, p_off, p_len, copied) {
2991 vaddr = kmap_atomic(p);
2992 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
2995 kunmap_atomic(vaddr);
2996 csum = csum_block_add(csum, csum2, pos);
3008 skb_walk_frags(skb, frag_iter) {
3012 WARN_ON(start > offset + len);
3014 end = start + frag_iter->len;
3015 if ((copy = end - offset) > 0) {
3018 csum2 = skb_copy_and_csum_bits(frag_iter,
3021 csum = csum_block_add(csum, csum2, pos);
3022 if ((len -= copy) == 0)
3033 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3035 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3039 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3040 /* See comments in __skb_checksum_complete(). */
3042 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3043 !skb->csum_complete_sw)
3044 netdev_rx_csum_fault(skb->dev, skb);
3046 if (!skb_shared(skb))
3047 skb->csum_valid = !sum;
3050 EXPORT_SYMBOL(__skb_checksum_complete_head);
3052 /* This function assumes skb->csum already holds pseudo header's checksum,
3053 * which has been changed from the hardware checksum, for example, by
3054 * __skb_checksum_validate_complete(). And, the original skb->csum must
3055 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3057 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3058 * zero. The new checksum is stored back into skb->csum unless the skb is
3061 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3066 csum = skb_checksum(skb, 0, skb->len, 0);
3068 sum = csum_fold(csum_add(skb->csum, csum));
3069 /* This check is inverted, because we already knew the hardware
3070 * checksum is invalid before calling this function. So, if the
3071 * re-computed checksum is valid instead, then we have a mismatch
3072 * between the original skb->csum and skb_checksum(). This means either
3073 * the original hardware checksum is incorrect or we screw up skb->csum
3074 * when moving skb->data around.
3077 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3078 !skb->csum_complete_sw)
3079 netdev_rx_csum_fault(skb->dev, skb);
3082 if (!skb_shared(skb)) {
3083 /* Save full packet checksum */
3085 skb->ip_summed = CHECKSUM_COMPLETE;
3086 skb->csum_complete_sw = 1;
3087 skb->csum_valid = !sum;
3092 EXPORT_SYMBOL(__skb_checksum_complete);
3094 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3096 net_warn_ratelimited(
3097 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3102 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3103 int offset, int len)
3105 net_warn_ratelimited(
3106 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3111 static const struct skb_checksum_ops default_crc32c_ops = {
3112 .update = warn_crc32c_csum_update,
3113 .combine = warn_crc32c_csum_combine,
3116 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3117 &default_crc32c_ops;
3118 EXPORT_SYMBOL(crc32c_csum_stub);
3121 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3122 * @from: source buffer
3124 * Calculates the amount of linear headroom needed in the 'to' skb passed
3125 * into skb_zerocopy().
3128 skb_zerocopy_headlen(const struct sk_buff *from)
3130 unsigned int hlen = 0;
3132 if (!from->head_frag ||
3133 skb_headlen(from) < L1_CACHE_BYTES ||
3134 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3135 hlen = skb_headlen(from);
3140 if (skb_has_frag_list(from))
3145 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3148 * skb_zerocopy - Zero copy skb to skb
3149 * @to: destination buffer
3150 * @from: source buffer
3151 * @len: number of bytes to copy from source buffer
3152 * @hlen: size of linear headroom in destination buffer
3154 * Copies up to `len` bytes from `from` to `to` by creating references
3155 * to the frags in the source buffer.
3157 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3158 * headroom in the `to` buffer.
3161 * 0: everything is OK
3162 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3163 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3166 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3169 int plen = 0; /* length of skb->head fragment */
3172 unsigned int offset;
3174 BUG_ON(!from->head_frag && !hlen);
3176 /* dont bother with small payloads */
3177 if (len <= skb_tailroom(to))
3178 return skb_copy_bits(from, 0, skb_put(to, len), len);
3181 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3186 plen = min_t(int, skb_headlen(from), len);
3188 page = virt_to_head_page(from->head);
3189 offset = from->data - (unsigned char *)page_address(page);
3190 __skb_fill_page_desc(to, 0, page, offset, plen);
3197 to->truesize += len + plen;
3198 to->len += len + plen;
3199 to->data_len += len + plen;
3201 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3205 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3207 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3212 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3213 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3215 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3217 skb_frag_ref(to, j);
3220 skb_shinfo(to)->nr_frags = j;
3224 EXPORT_SYMBOL_GPL(skb_zerocopy);
3226 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3231 if (skb->ip_summed == CHECKSUM_PARTIAL)
3232 csstart = skb_checksum_start_offset(skb);
3234 csstart = skb_headlen(skb);
3236 BUG_ON(csstart > skb_headlen(skb));
3238 skb_copy_from_linear_data(skb, to, csstart);
3241 if (csstart != skb->len)
3242 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3243 skb->len - csstart);
3245 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3246 long csstuff = csstart + skb->csum_offset;
3248 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3251 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3254 * skb_dequeue - remove from the head of the queue
3255 * @list: list to dequeue from
3257 * Remove the head of the list. The list lock is taken so the function
3258 * may be used safely with other locking list functions. The head item is
3259 * returned or %NULL if the list is empty.
3262 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3264 unsigned long flags;
3265 struct sk_buff *result;
3267 spin_lock_irqsave(&list->lock, flags);
3268 result = __skb_dequeue(list);
3269 spin_unlock_irqrestore(&list->lock, flags);
3272 EXPORT_SYMBOL(skb_dequeue);
3275 * skb_dequeue_tail - remove from the tail of the queue
3276 * @list: list to dequeue from
3278 * Remove the tail of the list. The list lock is taken so the function
3279 * may be used safely with other locking list functions. The tail item is
3280 * returned or %NULL if the list is empty.
3282 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3284 unsigned long flags;
3285 struct sk_buff *result;
3287 spin_lock_irqsave(&list->lock, flags);
3288 result = __skb_dequeue_tail(list);
3289 spin_unlock_irqrestore(&list->lock, flags);
3292 EXPORT_SYMBOL(skb_dequeue_tail);
3295 * skb_queue_purge - empty a list
3296 * @list: list to empty
3298 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3299 * the list and one reference dropped. This function takes the list
3300 * lock and is atomic with respect to other list locking functions.
3302 void skb_queue_purge(struct sk_buff_head *list)
3304 struct sk_buff *skb;
3305 while ((skb = skb_dequeue(list)) != NULL)
3308 EXPORT_SYMBOL(skb_queue_purge);
3311 * skb_rbtree_purge - empty a skb rbtree
3312 * @root: root of the rbtree to empty
3313 * Return value: the sum of truesizes of all purged skbs.
3315 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3316 * the list and one reference dropped. This function does not take
3317 * any lock. Synchronization should be handled by the caller (e.g., TCP
3318 * out-of-order queue is protected by the socket lock).
3320 unsigned int skb_rbtree_purge(struct rb_root *root)
3322 struct rb_node *p = rb_first(root);
3323 unsigned int sum = 0;
3326 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3329 rb_erase(&skb->rbnode, root);
3330 sum += skb->truesize;
3337 * skb_queue_head - queue a buffer at the list head
3338 * @list: list to use
3339 * @newsk: buffer to queue
3341 * Queue a buffer at the start of the list. This function takes the
3342 * list lock and can be used safely with other locking &sk_buff functions
3345 * A buffer cannot be placed on two lists at the same time.
3347 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3349 unsigned long flags;
3351 spin_lock_irqsave(&list->lock, flags);
3352 __skb_queue_head(list, newsk);
3353 spin_unlock_irqrestore(&list->lock, flags);
3355 EXPORT_SYMBOL(skb_queue_head);
3358 * skb_queue_tail - queue a buffer at the list tail
3359 * @list: list to use
3360 * @newsk: buffer to queue
3362 * Queue a buffer at the tail of the list. This function takes the
3363 * list lock and can be used safely with other locking &sk_buff functions
3366 * A buffer cannot be placed on two lists at the same time.
3368 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3370 unsigned long flags;
3372 spin_lock_irqsave(&list->lock, flags);
3373 __skb_queue_tail(list, newsk);
3374 spin_unlock_irqrestore(&list->lock, flags);
3376 EXPORT_SYMBOL(skb_queue_tail);
3379 * skb_unlink - remove a buffer from a list
3380 * @skb: buffer to remove
3381 * @list: list to use
3383 * Remove a packet from a list. The list locks are taken and this
3384 * function is atomic with respect to other list locked calls
3386 * You must know what list the SKB is on.
3388 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3390 unsigned long flags;
3392 spin_lock_irqsave(&list->lock, flags);
3393 __skb_unlink(skb, list);
3394 spin_unlock_irqrestore(&list->lock, flags);
3396 EXPORT_SYMBOL(skb_unlink);
3399 * skb_append - append a buffer
3400 * @old: buffer to insert after
3401 * @newsk: buffer to insert
3402 * @list: list to use
3404 * Place a packet after a given packet in a list. The list locks are taken
3405 * and this function is atomic with respect to other list locked calls.
3406 * A buffer cannot be placed on two lists at the same time.
3408 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3410 unsigned long flags;
3412 spin_lock_irqsave(&list->lock, flags);
3413 __skb_queue_after(list, old, newsk);
3414 spin_unlock_irqrestore(&list->lock, flags);
3416 EXPORT_SYMBOL(skb_append);
3418 static inline void skb_split_inside_header(struct sk_buff *skb,
3419 struct sk_buff* skb1,
3420 const u32 len, const int pos)
3424 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3426 /* And move data appendix as is. */
3427 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3428 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3430 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3431 skb_shinfo(skb)->nr_frags = 0;
3432 skb1->data_len = skb->data_len;
3433 skb1->len += skb1->data_len;
3436 skb_set_tail_pointer(skb, len);
3439 static inline void skb_split_no_header(struct sk_buff *skb,
3440 struct sk_buff* skb1,
3441 const u32 len, int pos)
3444 const int nfrags = skb_shinfo(skb)->nr_frags;
3446 skb_shinfo(skb)->nr_frags = 0;
3447 skb1->len = skb1->data_len = skb->len - len;
3449 skb->data_len = len - pos;
3451 for (i = 0; i < nfrags; i++) {
3452 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3454 if (pos + size > len) {
3455 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3459 * We have two variants in this case:
3460 * 1. Move all the frag to the second
3461 * part, if it is possible. F.e.
3462 * this approach is mandatory for TUX,
3463 * where splitting is expensive.
3464 * 2. Split is accurately. We make this.
3466 skb_frag_ref(skb, i);
3467 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3468 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3469 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3470 skb_shinfo(skb)->nr_frags++;
3474 skb_shinfo(skb)->nr_frags++;
3477 skb_shinfo(skb1)->nr_frags = k;
3481 * skb_split - Split fragmented skb to two parts at length len.
3482 * @skb: the buffer to split
3483 * @skb1: the buffer to receive the second part
3484 * @len: new length for skb
3486 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3488 int pos = skb_headlen(skb);
3489 const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3491 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3492 skb_zerocopy_clone(skb1, skb, 0);
3493 if (len < pos) /* Split line is inside header. */
3494 skb_split_inside_header(skb, skb1, len, pos);
3495 else /* Second chunk has no header, nothing to copy. */
3496 skb_split_no_header(skb, skb1, len, pos);
3498 EXPORT_SYMBOL(skb_split);
3500 /* Shifting from/to a cloned skb is a no-go.
3502 * Caller cannot keep skb_shinfo related pointers past calling here!
3504 static int skb_prepare_for_shift(struct sk_buff *skb)
3506 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3510 * skb_shift - Shifts paged data partially from skb to another
3511 * @tgt: buffer into which tail data gets added
3512 * @skb: buffer from which the paged data comes from
3513 * @shiftlen: shift up to this many bytes
3515 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3516 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3517 * It's up to caller to free skb if everything was shifted.
3519 * If @tgt runs out of frags, the whole operation is aborted.
3521 * Skb cannot include anything else but paged data while tgt is allowed
3522 * to have non-paged data as well.
3524 * TODO: full sized shift could be optimized but that would need
3525 * specialized skb free'er to handle frags without up-to-date nr_frags.
3527 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3529 int from, to, merge, todo;
3530 skb_frag_t *fragfrom, *fragto;
3532 BUG_ON(shiftlen > skb->len);
3534 if (skb_headlen(skb))
3536 if (skb_zcopy(tgt) || skb_zcopy(skb))
3541 to = skb_shinfo(tgt)->nr_frags;
3542 fragfrom = &skb_shinfo(skb)->frags[from];
3544 /* Actual merge is delayed until the point when we know we can
3545 * commit all, so that we don't have to undo partial changes
3548 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3549 skb_frag_off(fragfrom))) {
3554 todo -= skb_frag_size(fragfrom);
3556 if (skb_prepare_for_shift(skb) ||
3557 skb_prepare_for_shift(tgt))
3560 /* All previous frag pointers might be stale! */
3561 fragfrom = &skb_shinfo(skb)->frags[from];
3562 fragto = &skb_shinfo(tgt)->frags[merge];
3564 skb_frag_size_add(fragto, shiftlen);
3565 skb_frag_size_sub(fragfrom, shiftlen);
3566 skb_frag_off_add(fragfrom, shiftlen);
3574 /* Skip full, not-fitting skb to avoid expensive operations */
3575 if ((shiftlen == skb->len) &&
3576 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3579 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3582 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3583 if (to == MAX_SKB_FRAGS)
3586 fragfrom = &skb_shinfo(skb)->frags[from];
3587 fragto = &skb_shinfo(tgt)->frags[to];
3589 if (todo >= skb_frag_size(fragfrom)) {
3590 *fragto = *fragfrom;
3591 todo -= skb_frag_size(fragfrom);
3596 __skb_frag_ref(fragfrom);
3597 skb_frag_page_copy(fragto, fragfrom);
3598 skb_frag_off_copy(fragto, fragfrom);
3599 skb_frag_size_set(fragto, todo);
3601 skb_frag_off_add(fragfrom, todo);
3602 skb_frag_size_sub(fragfrom, todo);
3610 /* Ready to "commit" this state change to tgt */
3611 skb_shinfo(tgt)->nr_frags = to;
3614 fragfrom = &skb_shinfo(skb)->frags[0];
3615 fragto = &skb_shinfo(tgt)->frags[merge];
3617 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3618 __skb_frag_unref(fragfrom, skb->pp_recycle);
3621 /* Reposition in the original skb */
3623 while (from < skb_shinfo(skb)->nr_frags)
3624 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3625 skb_shinfo(skb)->nr_frags = to;
3627 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3630 /* Most likely the tgt won't ever need its checksum anymore, skb on
3631 * the other hand might need it if it needs to be resent
3633 tgt->ip_summed = CHECKSUM_PARTIAL;
3634 skb->ip_summed = CHECKSUM_PARTIAL;
3636 /* Yak, is it really working this way? Some helper please? */
3637 skb->len -= shiftlen;
3638 skb->data_len -= shiftlen;
3639 skb->truesize -= shiftlen;
3640 tgt->len += shiftlen;
3641 tgt->data_len += shiftlen;
3642 tgt->truesize += shiftlen;
3648 * skb_prepare_seq_read - Prepare a sequential read of skb data
3649 * @skb: the buffer to read
3650 * @from: lower offset of data to be read
3651 * @to: upper offset of data to be read
3652 * @st: state variable
3654 * Initializes the specified state variable. Must be called before
3655 * invoking skb_seq_read() for the first time.
3657 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3658 unsigned int to, struct skb_seq_state *st)
3660 st->lower_offset = from;
3661 st->upper_offset = to;
3662 st->root_skb = st->cur_skb = skb;
3663 st->frag_idx = st->stepped_offset = 0;
3664 st->frag_data = NULL;
3667 EXPORT_SYMBOL(skb_prepare_seq_read);
3670 * skb_seq_read - Sequentially read skb data
3671 * @consumed: number of bytes consumed by the caller so far
3672 * @data: destination pointer for data to be returned
3673 * @st: state variable
3675 * Reads a block of skb data at @consumed relative to the
3676 * lower offset specified to skb_prepare_seq_read(). Assigns
3677 * the head of the data block to @data and returns the length
3678 * of the block or 0 if the end of the skb data or the upper
3679 * offset has been reached.
3681 * The caller is not required to consume all of the data
3682 * returned, i.e. @consumed is typically set to the number
3683 * of bytes already consumed and the next call to
3684 * skb_seq_read() will return the remaining part of the block.
3686 * Note 1: The size of each block of data returned can be arbitrary,
3687 * this limitation is the cost for zerocopy sequential
3688 * reads of potentially non linear data.
3690 * Note 2: Fragment lists within fragments are not implemented
3691 * at the moment, state->root_skb could be replaced with
3692 * a stack for this purpose.
3694 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3695 struct skb_seq_state *st)
3697 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3700 if (unlikely(abs_offset >= st->upper_offset)) {
3701 if (st->frag_data) {
3702 kunmap_atomic(st->frag_data);
3703 st->frag_data = NULL;
3709 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3711 if (abs_offset < block_limit && !st->frag_data) {
3712 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3713 return block_limit - abs_offset;
3716 if (st->frag_idx == 0 && !st->frag_data)
3717 st->stepped_offset += skb_headlen(st->cur_skb);
3719 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3720 unsigned int pg_idx, pg_off, pg_sz;
3722 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3725 pg_off = skb_frag_off(frag);
3726 pg_sz = skb_frag_size(frag);
3728 if (skb_frag_must_loop(skb_frag_page(frag))) {
3729 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3730 pg_off = offset_in_page(pg_off + st->frag_off);
3731 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3732 PAGE_SIZE - pg_off);
3735 block_limit = pg_sz + st->stepped_offset;
3736 if (abs_offset < block_limit) {
3738 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3740 *data = (u8 *)st->frag_data + pg_off +
3741 (abs_offset - st->stepped_offset);
3743 return block_limit - abs_offset;
3746 if (st->frag_data) {
3747 kunmap_atomic(st->frag_data);
3748 st->frag_data = NULL;
3751 st->stepped_offset += pg_sz;
3752 st->frag_off += pg_sz;
3753 if (st->frag_off == skb_frag_size(frag)) {
3759 if (st->frag_data) {
3760 kunmap_atomic(st->frag_data);
3761 st->frag_data = NULL;
3764 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3765 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3768 } else if (st->cur_skb->next) {
3769 st->cur_skb = st->cur_skb->next;
3776 EXPORT_SYMBOL(skb_seq_read);
3779 * skb_abort_seq_read - Abort a sequential read of skb data
3780 * @st: state variable
3782 * Must be called if skb_seq_read() was not called until it
3785 void skb_abort_seq_read(struct skb_seq_state *st)
3788 kunmap_atomic(st->frag_data);
3790 EXPORT_SYMBOL(skb_abort_seq_read);
3792 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3794 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3795 struct ts_config *conf,
3796 struct ts_state *state)
3798 return skb_seq_read(offset, text, TS_SKB_CB(state));
3801 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3803 skb_abort_seq_read(TS_SKB_CB(state));
3807 * skb_find_text - Find a text pattern in skb data
3808 * @skb: the buffer to look in
3809 * @from: search offset
3811 * @config: textsearch configuration
3813 * Finds a pattern in the skb data according to the specified
3814 * textsearch configuration. Use textsearch_next() to retrieve
3815 * subsequent occurrences of the pattern. Returns the offset
3816 * to the first occurrence or UINT_MAX if no match was found.
3818 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3819 unsigned int to, struct ts_config *config)
3821 struct ts_state state;
3824 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3826 config->get_next_block = skb_ts_get_next_block;
3827 config->finish = skb_ts_finish;
3829 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3831 ret = textsearch_find(config, &state);
3832 return (ret <= to - from ? ret : UINT_MAX);
3834 EXPORT_SYMBOL(skb_find_text);
3836 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3837 int offset, size_t size)
3839 int i = skb_shinfo(skb)->nr_frags;
3841 if (skb_can_coalesce(skb, i, page, offset)) {
3842 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3843 } else if (i < MAX_SKB_FRAGS) {
3845 skb_fill_page_desc(skb, i, page, offset, size);
3852 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3855 * skb_pull_rcsum - pull skb and update receive checksum
3856 * @skb: buffer to update
3857 * @len: length of data pulled
3859 * This function performs an skb_pull on the packet and updates
3860 * the CHECKSUM_COMPLETE checksum. It should be used on
3861 * receive path processing instead of skb_pull unless you know
3862 * that the checksum difference is zero (e.g., a valid IP header)
3863 * or you are setting ip_summed to CHECKSUM_NONE.
3865 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3867 unsigned char *data = skb->data;
3869 BUG_ON(len > skb->len);
3870 __skb_pull(skb, len);
3871 skb_postpull_rcsum(skb, data, len);
3874 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3876 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
3878 skb_frag_t head_frag;
3881 page = virt_to_head_page(frag_skb->head);
3882 __skb_frag_set_page(&head_frag, page);
3883 skb_frag_off_set(&head_frag, frag_skb->data -
3884 (unsigned char *)page_address(page));
3885 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
3889 struct sk_buff *skb_segment_list(struct sk_buff *skb,
3890 netdev_features_t features,
3891 unsigned int offset)
3893 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
3894 unsigned int tnl_hlen = skb_tnl_header_len(skb);
3895 unsigned int delta_truesize = 0;
3896 unsigned int delta_len = 0;
3897 struct sk_buff *tail = NULL;
3898 struct sk_buff *nskb, *tmp;
3901 skb_push(skb, -skb_network_offset(skb) + offset);
3903 skb_shinfo(skb)->frag_list = NULL;
3907 list_skb = list_skb->next;
3910 delta_truesize += nskb->truesize;
3911 if (skb_shared(nskb)) {
3912 tmp = skb_clone(nskb, GFP_ATOMIC);
3916 err = skb_unclone(nskb, GFP_ATOMIC);
3927 if (unlikely(err)) {
3928 nskb->next = list_skb;
3934 delta_len += nskb->len;
3936 skb_push(nskb, -skb_network_offset(nskb) + offset);
3938 skb_release_head_state(nskb);
3939 len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
3940 __copy_skb_header(nskb, skb);
3942 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
3943 nskb->transport_header += len_diff;
3944 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
3945 nskb->data - tnl_hlen,
3948 if (skb_needs_linearize(nskb, features) &&
3949 __skb_linearize(nskb))
3954 skb->truesize = skb->truesize - delta_truesize;
3955 skb->data_len = skb->data_len - delta_len;
3956 skb->len = skb->len - delta_len;
3962 if (skb_needs_linearize(skb, features) &&
3963 __skb_linearize(skb))
3971 kfree_skb_list(skb->next);
3973 return ERR_PTR(-ENOMEM);
3975 EXPORT_SYMBOL_GPL(skb_segment_list);
3978 * skb_segment - Perform protocol segmentation on skb.
3979 * @head_skb: buffer to segment
3980 * @features: features for the output path (see dev->features)
3982 * This function performs segmentation on the given skb. It returns
3983 * a pointer to the first in a list of new skbs for the segments.
3984 * In case of error it returns ERR_PTR(err).
3986 struct sk_buff *skb_segment(struct sk_buff *head_skb,
3987 netdev_features_t features)
3989 struct sk_buff *segs = NULL;
3990 struct sk_buff *tail = NULL;
3991 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3992 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3993 unsigned int mss = skb_shinfo(head_skb)->gso_size;
3994 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
3995 struct sk_buff *frag_skb = head_skb;
3996 unsigned int offset = doffset;
3997 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3998 unsigned int partial_segs = 0;
3999 unsigned int headroom;
4000 unsigned int len = head_skb->len;
4003 int nfrags = skb_shinfo(head_skb)->nr_frags;
4008 if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
4009 (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
4010 /* gso_size is untrusted, and we have a frag_list with a linear
4011 * non head_frag head.
4013 * (we assume checking the first list_skb member suffices;
4014 * i.e if either of the list_skb members have non head_frag
4015 * head, then the first one has too).
4017 * If head_skb's headlen does not fit requested gso_size, it
4018 * means that the frag_list members do NOT terminate on exact
4019 * gso_size boundaries. Hence we cannot perform skb_frag_t page
4020 * sharing. Therefore we must fallback to copying the frag_list
4021 * skbs; we do so by disabling SG.
4023 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
4024 features &= ~NETIF_F_SG;
4027 __skb_push(head_skb, doffset);
4028 proto = skb_network_protocol(head_skb, NULL);
4029 if (unlikely(!proto))
4030 return ERR_PTR(-EINVAL);
4032 sg = !!(features & NETIF_F_SG);
4033 csum = !!can_checksum_protocol(features, proto);
4035 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4036 if (!(features & NETIF_F_GSO_PARTIAL)) {
4037 struct sk_buff *iter;
4038 unsigned int frag_len;
4041 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4044 /* If we get here then all the required
4045 * GSO features except frag_list are supported.
4046 * Try to split the SKB to multiple GSO SKBs
4047 * with no frag_list.
4048 * Currently we can do that only when the buffers don't
4049 * have a linear part and all the buffers except
4050 * the last are of the same length.
4052 frag_len = list_skb->len;
4053 skb_walk_frags(head_skb, iter) {
4054 if (frag_len != iter->len && iter->next)
4056 if (skb_headlen(iter) && !iter->head_frag)
4062 if (len != frag_len)
4066 /* GSO partial only requires that we trim off any excess that
4067 * doesn't fit into an MSS sized block, so take care of that
4070 partial_segs = len / mss;
4071 if (partial_segs > 1)
4072 mss *= partial_segs;
4078 headroom = skb_headroom(head_skb);
4079 pos = skb_headlen(head_skb);
4082 struct sk_buff *nskb;
4083 skb_frag_t *nskb_frag;
4087 if (unlikely(mss == GSO_BY_FRAGS)) {
4088 len = list_skb->len;
4090 len = head_skb->len - offset;
4095 hsize = skb_headlen(head_skb) - offset;
4097 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4098 (skb_headlen(list_skb) == len || sg)) {
4099 BUG_ON(skb_headlen(list_skb) > len);
4102 nfrags = skb_shinfo(list_skb)->nr_frags;
4103 frag = skb_shinfo(list_skb)->frags;
4104 frag_skb = list_skb;
4105 pos += skb_headlen(list_skb);
4107 while (pos < offset + len) {
4108 BUG_ON(i >= nfrags);
4110 size = skb_frag_size(frag);
4111 if (pos + size > offset + len)
4119 nskb = skb_clone(list_skb, GFP_ATOMIC);
4120 list_skb = list_skb->next;
4122 if (unlikely(!nskb))
4125 if (unlikely(pskb_trim(nskb, len))) {
4130 hsize = skb_end_offset(nskb);
4131 if (skb_cow_head(nskb, doffset + headroom)) {
4136 nskb->truesize += skb_end_offset(nskb) - hsize;
4137 skb_release_head_state(nskb);
4138 __skb_push(nskb, doffset);
4142 if (hsize > len || !sg)
4145 nskb = __alloc_skb(hsize + doffset + headroom,
4146 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4149 if (unlikely(!nskb))
4152 skb_reserve(nskb, headroom);
4153 __skb_put(nskb, doffset);
4162 __copy_skb_header(nskb, head_skb);
4164 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4165 skb_reset_mac_len(nskb);
4167 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4168 nskb->data - tnl_hlen,
4169 doffset + tnl_hlen);
4171 if (nskb->len == len + doffset)
4172 goto perform_csum_check;
4176 if (!nskb->remcsum_offload)
4177 nskb->ip_summed = CHECKSUM_NONE;
4178 SKB_GSO_CB(nskb)->csum =
4179 skb_copy_and_csum_bits(head_skb, offset,
4183 SKB_GSO_CB(nskb)->csum_start =
4184 skb_headroom(nskb) + doffset;
4186 skb_copy_bits(head_skb, offset,
4193 nskb_frag = skb_shinfo(nskb)->frags;
4195 skb_copy_from_linear_data_offset(head_skb, offset,
4196 skb_put(nskb, hsize), hsize);
4198 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4201 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4202 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4205 while (pos < offset + len) {
4208 nfrags = skb_shinfo(list_skb)->nr_frags;
4209 frag = skb_shinfo(list_skb)->frags;
4210 frag_skb = list_skb;
4211 if (!skb_headlen(list_skb)) {
4214 BUG_ON(!list_skb->head_frag);
4216 /* to make room for head_frag. */
4220 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4221 skb_zerocopy_clone(nskb, frag_skb,
4225 list_skb = list_skb->next;
4228 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4230 net_warn_ratelimited(
4231 "skb_segment: too many frags: %u %u\n",
4237 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4238 __skb_frag_ref(nskb_frag);
4239 size = skb_frag_size(nskb_frag);
4242 skb_frag_off_add(nskb_frag, offset - pos);
4243 skb_frag_size_sub(nskb_frag, offset - pos);
4246 skb_shinfo(nskb)->nr_frags++;
4248 if (pos + size <= offset + len) {
4253 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4261 nskb->data_len = len - hsize;
4262 nskb->len += nskb->data_len;
4263 nskb->truesize += nskb->data_len;
4267 if (skb_has_shared_frag(nskb) &&
4268 __skb_linearize(nskb))
4271 if (!nskb->remcsum_offload)
4272 nskb->ip_summed = CHECKSUM_NONE;
4273 SKB_GSO_CB(nskb)->csum =
4274 skb_checksum(nskb, doffset,
4275 nskb->len - doffset, 0);
4276 SKB_GSO_CB(nskb)->csum_start =
4277 skb_headroom(nskb) + doffset;
4279 } while ((offset += len) < head_skb->len);
4281 /* Some callers want to get the end of the list.
4282 * Put it in segs->prev to avoid walking the list.
4283 * (see validate_xmit_skb_list() for example)
4288 struct sk_buff *iter;
4289 int type = skb_shinfo(head_skb)->gso_type;
4290 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4292 /* Update type to add partial and then remove dodgy if set */
4293 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4294 type &= ~SKB_GSO_DODGY;
4296 /* Update GSO info and prepare to start updating headers on
4297 * our way back down the stack of protocols.
4299 for (iter = segs; iter; iter = iter->next) {
4300 skb_shinfo(iter)->gso_size = gso_size;
4301 skb_shinfo(iter)->gso_segs = partial_segs;
4302 skb_shinfo(iter)->gso_type = type;
4303 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4306 if (tail->len - doffset <= gso_size)
4307 skb_shinfo(tail)->gso_size = 0;
4308 else if (tail != segs)
4309 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4312 /* Following permits correct backpressure, for protocols
4313 * using skb_set_owner_w().
4314 * Idea is to tranfert ownership from head_skb to last segment.
4316 if (head_skb->destructor == sock_wfree) {
4317 swap(tail->truesize, head_skb->truesize);
4318 swap(tail->destructor, head_skb->destructor);
4319 swap(tail->sk, head_skb->sk);
4324 kfree_skb_list(segs);
4325 return ERR_PTR(err);
4327 EXPORT_SYMBOL_GPL(skb_segment);
4329 #ifdef CONFIG_SKB_EXTENSIONS
4330 #define SKB_EXT_ALIGN_VALUE 8
4331 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4333 static const u8 skb_ext_type_len[] = {
4334 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4335 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4338 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4340 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4341 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4343 #if IS_ENABLED(CONFIG_MPTCP)
4344 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4346 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4347 [SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4351 static __always_inline unsigned int skb_ext_total_length(void)
4353 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4354 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4355 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4358 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4360 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4361 skb_ext_type_len[TC_SKB_EXT] +
4363 #if IS_ENABLED(CONFIG_MPTCP)
4364 skb_ext_type_len[SKB_EXT_MPTCP] +
4366 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4367 skb_ext_type_len[SKB_EXT_MCTP] +
4372 static void skb_extensions_init(void)
4374 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4375 BUILD_BUG_ON(skb_ext_total_length() > 255);
4377 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4378 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4380 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4384 static void skb_extensions_init(void) {}
4387 void __init skb_init(void)
4389 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4390 sizeof(struct sk_buff),
4392 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4393 offsetof(struct sk_buff, cb),
4394 sizeof_field(struct sk_buff, cb),
4396 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4397 sizeof(struct sk_buff_fclones),
4399 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4401 skb_extensions_init();
4405 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4406 unsigned int recursion_level)
4408 int start = skb_headlen(skb);
4409 int i, copy = start - offset;
4410 struct sk_buff *frag_iter;
4413 if (unlikely(recursion_level >= 24))
4419 sg_set_buf(sg, skb->data + offset, copy);
4421 if ((len -= copy) == 0)
4426 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4429 WARN_ON(start > offset + len);
4431 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4432 if ((copy = end - offset) > 0) {
4433 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4434 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4439 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4440 skb_frag_off(frag) + offset - start);
4449 skb_walk_frags(skb, frag_iter) {
4452 WARN_ON(start > offset + len);
4454 end = start + frag_iter->len;
4455 if ((copy = end - offset) > 0) {
4456 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4461 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4462 copy, recursion_level + 1);
4463 if (unlikely(ret < 0))
4466 if ((len -= copy) == 0)
4477 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4478 * @skb: Socket buffer containing the buffers to be mapped
4479 * @sg: The scatter-gather list to map into
4480 * @offset: The offset into the buffer's contents to start mapping
4481 * @len: Length of buffer space to be mapped
4483 * Fill the specified scatter-gather list with mappings/pointers into a
4484 * region of the buffer space attached to a socket buffer. Returns either
4485 * the number of scatterlist items used, or -EMSGSIZE if the contents
4488 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4490 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4495 sg_mark_end(&sg[nsg - 1]);
4499 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4501 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4502 * sglist without mark the sg which contain last skb data as the end.
4503 * So the caller can mannipulate sg list as will when padding new data after
4504 * the first call without calling sg_unmark_end to expend sg list.
4506 * Scenario to use skb_to_sgvec_nomark:
4508 * 2. skb_to_sgvec_nomark(payload1)
4509 * 3. skb_to_sgvec_nomark(payload2)
4511 * This is equivalent to:
4513 * 2. skb_to_sgvec(payload1)
4515 * 4. skb_to_sgvec(payload2)
4517 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4518 * is more preferable.
4520 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4521 int offset, int len)
4523 return __skb_to_sgvec(skb, sg, offset, len, 0);
4525 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4530 * skb_cow_data - Check that a socket buffer's data buffers are writable
4531 * @skb: The socket buffer to check.
4532 * @tailbits: Amount of trailing space to be added
4533 * @trailer: Returned pointer to the skb where the @tailbits space begins
4535 * Make sure that the data buffers attached to a socket buffer are
4536 * writable. If they are not, private copies are made of the data buffers
4537 * and the socket buffer is set to use these instead.
4539 * If @tailbits is given, make sure that there is space to write @tailbits
4540 * bytes of data beyond current end of socket buffer. @trailer will be
4541 * set to point to the skb in which this space begins.
4543 * The number of scatterlist elements required to completely map the
4544 * COW'd and extended socket buffer will be returned.
4546 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4550 struct sk_buff *skb1, **skb_p;
4552 /* If skb is cloned or its head is paged, reallocate
4553 * head pulling out all the pages (pages are considered not writable
4554 * at the moment even if they are anonymous).
4556 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4557 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4560 /* Easy case. Most of packets will go this way. */
4561 if (!skb_has_frag_list(skb)) {
4562 /* A little of trouble, not enough of space for trailer.
4563 * This should not happen, when stack is tuned to generate
4564 * good frames. OK, on miss we reallocate and reserve even more
4565 * space, 128 bytes is fair. */
4567 if (skb_tailroom(skb) < tailbits &&
4568 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4576 /* Misery. We are in troubles, going to mincer fragments... */
4579 skb_p = &skb_shinfo(skb)->frag_list;
4582 while ((skb1 = *skb_p) != NULL) {
4585 /* The fragment is partially pulled by someone,
4586 * this can happen on input. Copy it and everything
4589 if (skb_shared(skb1))
4592 /* If the skb is the last, worry about trailer. */
4594 if (skb1->next == NULL && tailbits) {
4595 if (skb_shinfo(skb1)->nr_frags ||
4596 skb_has_frag_list(skb1) ||
4597 skb_tailroom(skb1) < tailbits)
4598 ntail = tailbits + 128;
4604 skb_shinfo(skb1)->nr_frags ||
4605 skb_has_frag_list(skb1)) {
4606 struct sk_buff *skb2;
4608 /* Fuck, we are miserable poor guys... */
4610 skb2 = skb_copy(skb1, GFP_ATOMIC);
4612 skb2 = skb_copy_expand(skb1,
4616 if (unlikely(skb2 == NULL))
4620 skb_set_owner_w(skb2, skb1->sk);
4622 /* Looking around. Are we still alive?
4623 * OK, link new skb, drop old one */
4625 skb2->next = skb1->next;
4632 skb_p = &skb1->next;
4637 EXPORT_SYMBOL_GPL(skb_cow_data);
4639 static void sock_rmem_free(struct sk_buff *skb)
4641 struct sock *sk = skb->sk;
4643 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4646 static void skb_set_err_queue(struct sk_buff *skb)
4648 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4649 * So, it is safe to (mis)use it to mark skbs on the error queue.
4651 skb->pkt_type = PACKET_OUTGOING;
4652 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4656 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4658 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4660 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4661 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4666 skb->destructor = sock_rmem_free;
4667 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4668 skb_set_err_queue(skb);
4670 /* before exiting rcu section, make sure dst is refcounted */
4673 skb_queue_tail(&sk->sk_error_queue, skb);
4674 if (!sock_flag(sk, SOCK_DEAD))
4675 sk_error_report(sk);
4678 EXPORT_SYMBOL(sock_queue_err_skb);
4680 static bool is_icmp_err_skb(const struct sk_buff *skb)
4682 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4683 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4686 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4688 struct sk_buff_head *q = &sk->sk_error_queue;
4689 struct sk_buff *skb, *skb_next = NULL;
4690 bool icmp_next = false;
4691 unsigned long flags;
4693 spin_lock_irqsave(&q->lock, flags);
4694 skb = __skb_dequeue(q);
4695 if (skb && (skb_next = skb_peek(q))) {
4696 icmp_next = is_icmp_err_skb(skb_next);
4698 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4700 spin_unlock_irqrestore(&q->lock, flags);
4702 if (is_icmp_err_skb(skb) && !icmp_next)
4706 sk_error_report(sk);
4710 EXPORT_SYMBOL(sock_dequeue_err_skb);
4713 * skb_clone_sk - create clone of skb, and take reference to socket
4714 * @skb: the skb to clone
4716 * This function creates a clone of a buffer that holds a reference on
4717 * sk_refcnt. Buffers created via this function are meant to be
4718 * returned using sock_queue_err_skb, or free via kfree_skb.
4720 * When passing buffers allocated with this function to sock_queue_err_skb
4721 * it is necessary to wrap the call with sock_hold/sock_put in order to
4722 * prevent the socket from being released prior to being enqueued on
4723 * the sk_error_queue.
4725 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4727 struct sock *sk = skb->sk;
4728 struct sk_buff *clone;
4730 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4733 clone = skb_clone(skb, GFP_ATOMIC);
4740 clone->destructor = sock_efree;
4744 EXPORT_SYMBOL(skb_clone_sk);
4746 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4751 struct sock_exterr_skb *serr;
4754 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4756 serr = SKB_EXT_ERR(skb);
4757 memset(serr, 0, sizeof(*serr));
4758 serr->ee.ee_errno = ENOMSG;
4759 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4760 serr->ee.ee_info = tstype;
4761 serr->opt_stats = opt_stats;
4762 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4763 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4764 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4766 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4769 err = sock_queue_err_skb(sk, skb);
4775 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4779 if (likely(sysctl_tstamp_allow_data || tsonly))
4782 read_lock_bh(&sk->sk_callback_lock);
4783 ret = sk->sk_socket && sk->sk_socket->file &&
4784 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4785 read_unlock_bh(&sk->sk_callback_lock);
4789 void skb_complete_tx_timestamp(struct sk_buff *skb,
4790 struct skb_shared_hwtstamps *hwtstamps)
4792 struct sock *sk = skb->sk;
4794 if (!skb_may_tx_timestamp(sk, false))
4797 /* Take a reference to prevent skb_orphan() from freeing the socket,
4798 * but only if the socket refcount is not zero.
4800 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4801 *skb_hwtstamps(skb) = *hwtstamps;
4802 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4810 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4812 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4813 const struct sk_buff *ack_skb,
4814 struct skb_shared_hwtstamps *hwtstamps,
4815 struct sock *sk, int tstype)
4817 struct sk_buff *skb;
4818 bool tsonly, opt_stats = false;
4823 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4824 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4827 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4828 if (!skb_may_tx_timestamp(sk, tsonly))
4833 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4835 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4840 skb = alloc_skb(0, GFP_ATOMIC);
4842 skb = skb_clone(orig_skb, GFP_ATOMIC);
4848 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4850 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4854 *skb_hwtstamps(skb) = *hwtstamps;
4856 __net_timestamp(skb);
4858 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
4860 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4862 void skb_tstamp_tx(struct sk_buff *orig_skb,
4863 struct skb_shared_hwtstamps *hwtstamps)
4865 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4868 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4870 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
4872 struct sock *sk = skb->sk;
4873 struct sock_exterr_skb *serr;
4876 skb->wifi_acked_valid = 1;
4877 skb->wifi_acked = acked;
4879 serr = SKB_EXT_ERR(skb);
4880 memset(serr, 0, sizeof(*serr));
4881 serr->ee.ee_errno = ENOMSG;
4882 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
4884 /* Take a reference to prevent skb_orphan() from freeing the socket,
4885 * but only if the socket refcount is not zero.
4887 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4888 err = sock_queue_err_skb(sk, skb);
4894 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4897 * skb_partial_csum_set - set up and verify partial csum values for packet
4898 * @skb: the skb to set
4899 * @start: the number of bytes after skb->data to start checksumming.
4900 * @off: the offset from start to place the checksum.
4902 * For untrusted partially-checksummed packets, we need to make sure the values
4903 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4905 * This function checks and sets those values and skb->ip_summed: if this
4906 * returns false you should drop the packet.
4908 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4910 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
4911 u32 csum_start = skb_headroom(skb) + (u32)start;
4913 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
4914 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
4915 start, off, skb_headroom(skb), skb_headlen(skb));
4918 skb->ip_summed = CHECKSUM_PARTIAL;
4919 skb->csum_start = csum_start;
4920 skb->csum_offset = off;
4921 skb_set_transport_header(skb, start);
4924 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4926 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4929 if (skb_headlen(skb) >= len)
4932 /* If we need to pullup then pullup to the max, so we
4933 * won't need to do it again.
4938 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4941 if (skb_headlen(skb) < len)
4947 #define MAX_TCP_HDR_LEN (15 * 4)
4949 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4950 typeof(IPPROTO_IP) proto,
4957 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4958 off + MAX_TCP_HDR_LEN);
4959 if (!err && !skb_partial_csum_set(skb, off,
4960 offsetof(struct tcphdr,
4963 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4966 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4967 off + sizeof(struct udphdr));
4968 if (!err && !skb_partial_csum_set(skb, off,
4969 offsetof(struct udphdr,
4972 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4975 return ERR_PTR(-EPROTO);
4978 /* This value should be large enough to cover a tagged ethernet header plus
4979 * maximally sized IP and TCP or UDP headers.
4981 #define MAX_IP_HDR_LEN 128
4983 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
4992 err = skb_maybe_pull_tail(skb,
4993 sizeof(struct iphdr),
4998 if (ip_is_fragment(ip_hdr(skb)))
5001 off = ip_hdrlen(skb);
5008 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5010 return PTR_ERR(csum);
5013 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5016 ip_hdr(skb)->protocol, 0);
5023 /* This value should be large enough to cover a tagged ethernet header plus
5024 * an IPv6 header, all options, and a maximal TCP or UDP header.
5026 #define MAX_IPV6_HDR_LEN 256
5028 #define OPT_HDR(type, skb, off) \
5029 (type *)(skb_network_header(skb) + (off))
5031 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5044 off = sizeof(struct ipv6hdr);
5046 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5050 nexthdr = ipv6_hdr(skb)->nexthdr;
5052 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5053 while (off <= len && !done) {
5055 case IPPROTO_DSTOPTS:
5056 case IPPROTO_HOPOPTS:
5057 case IPPROTO_ROUTING: {
5058 struct ipv6_opt_hdr *hp;
5060 err = skb_maybe_pull_tail(skb,
5062 sizeof(struct ipv6_opt_hdr),
5067 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5068 nexthdr = hp->nexthdr;
5069 off += ipv6_optlen(hp);
5073 struct ip_auth_hdr *hp;
5075 err = skb_maybe_pull_tail(skb,
5077 sizeof(struct ip_auth_hdr),
5082 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5083 nexthdr = hp->nexthdr;
5084 off += ipv6_authlen(hp);
5087 case IPPROTO_FRAGMENT: {
5088 struct frag_hdr *hp;
5090 err = skb_maybe_pull_tail(skb,
5092 sizeof(struct frag_hdr),
5097 hp = OPT_HDR(struct frag_hdr, skb, off);
5099 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5102 nexthdr = hp->nexthdr;
5103 off += sizeof(struct frag_hdr);
5114 if (!done || fragment)
5117 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5119 return PTR_ERR(csum);
5122 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5123 &ipv6_hdr(skb)->daddr,
5124 skb->len - off, nexthdr, 0);
5132 * skb_checksum_setup - set up partial checksum offset
5133 * @skb: the skb to set up
5134 * @recalculate: if true the pseudo-header checksum will be recalculated
5136 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5140 switch (skb->protocol) {
5141 case htons(ETH_P_IP):
5142 err = skb_checksum_setup_ipv4(skb, recalculate);
5145 case htons(ETH_P_IPV6):
5146 err = skb_checksum_setup_ipv6(skb, recalculate);
5156 EXPORT_SYMBOL(skb_checksum_setup);
5159 * skb_checksum_maybe_trim - maybe trims the given skb
5160 * @skb: the skb to check
5161 * @transport_len: the data length beyond the network header
5163 * Checks whether the given skb has data beyond the given transport length.
5164 * If so, returns a cloned skb trimmed to this transport length.
5165 * Otherwise returns the provided skb. Returns NULL in error cases
5166 * (e.g. transport_len exceeds skb length or out-of-memory).
5168 * Caller needs to set the skb transport header and free any returned skb if it
5169 * differs from the provided skb.
5171 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5172 unsigned int transport_len)
5174 struct sk_buff *skb_chk;
5175 unsigned int len = skb_transport_offset(skb) + transport_len;
5180 else if (skb->len == len)
5183 skb_chk = skb_clone(skb, GFP_ATOMIC);
5187 ret = pskb_trim_rcsum(skb_chk, len);
5197 * skb_checksum_trimmed - validate checksum of an skb
5198 * @skb: the skb to check
5199 * @transport_len: the data length beyond the network header
5200 * @skb_chkf: checksum function to use
5202 * Applies the given checksum function skb_chkf to the provided skb.
5203 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5205 * If the skb has data beyond the given transport length, then a
5206 * trimmed & cloned skb is checked and returned.
5208 * Caller needs to set the skb transport header and free any returned skb if it
5209 * differs from the provided skb.
5211 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5212 unsigned int transport_len,
5213 __sum16(*skb_chkf)(struct sk_buff *skb))
5215 struct sk_buff *skb_chk;
5216 unsigned int offset = skb_transport_offset(skb);
5219 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5223 if (!pskb_may_pull(skb_chk, offset))
5226 skb_pull_rcsum(skb_chk, offset);
5227 ret = skb_chkf(skb_chk);
5228 skb_push_rcsum(skb_chk, offset);
5236 if (skb_chk && skb_chk != skb)
5242 EXPORT_SYMBOL(skb_checksum_trimmed);
5244 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5246 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5249 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5251 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5254 skb_release_head_state(skb);
5255 kmem_cache_free(skbuff_head_cache, skb);
5260 EXPORT_SYMBOL(kfree_skb_partial);
5263 * skb_try_coalesce - try to merge skb to prior one
5265 * @from: buffer to add
5266 * @fragstolen: pointer to boolean
5267 * @delta_truesize: how much more was allocated than was requested
5269 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5270 bool *fragstolen, int *delta_truesize)
5272 struct skb_shared_info *to_shinfo, *from_shinfo;
5273 int i, delta, len = from->len;
5275 *fragstolen = false;
5280 /* In general, avoid mixing slab allocated and page_pool allocated
5281 * pages within the same SKB. However when @to is not pp_recycle and
5282 * @from is cloned, we can transition frag pages from page_pool to
5283 * reference counted.
5285 * On the other hand, don't allow coalescing two pp_recycle SKBs if
5286 * @from is cloned, in case the SKB is using page_pool fragment
5287 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5288 * references for cloned SKBs at the moment that would result in
5289 * inconsistent reference counts.
5291 if (to->pp_recycle != (from->pp_recycle && !skb_cloned(from)))
5294 if (len <= skb_tailroom(to)) {
5296 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5297 *delta_truesize = 0;
5301 to_shinfo = skb_shinfo(to);
5302 from_shinfo = skb_shinfo(from);
5303 if (to_shinfo->frag_list || from_shinfo->frag_list)
5305 if (skb_zcopy(to) || skb_zcopy(from))
5308 if (skb_headlen(from) != 0) {
5310 unsigned int offset;
5312 if (to_shinfo->nr_frags +
5313 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5316 if (skb_head_is_locked(from))
5319 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5321 page = virt_to_head_page(from->head);
5322 offset = from->data - (unsigned char *)page_address(page);
5324 skb_fill_page_desc(to, to_shinfo->nr_frags,
5325 page, offset, skb_headlen(from));
5328 if (to_shinfo->nr_frags +
5329 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5332 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5335 WARN_ON_ONCE(delta < len);
5337 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5339 from_shinfo->nr_frags * sizeof(skb_frag_t));
5340 to_shinfo->nr_frags += from_shinfo->nr_frags;
5342 if (!skb_cloned(from))
5343 from_shinfo->nr_frags = 0;
5345 /* if the skb is not cloned this does nothing
5346 * since we set nr_frags to 0.
5348 for (i = 0; i < from_shinfo->nr_frags; i++)
5349 __skb_frag_ref(&from_shinfo->frags[i]);
5351 to->truesize += delta;
5353 to->data_len += len;
5355 *delta_truesize = delta;
5358 EXPORT_SYMBOL(skb_try_coalesce);
5361 * skb_scrub_packet - scrub an skb
5363 * @skb: buffer to clean
5364 * @xnet: packet is crossing netns
5366 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5367 * into/from a tunnel. Some information have to be cleared during these
5369 * skb_scrub_packet can also be used to clean a skb before injecting it in
5370 * another namespace (@xnet == true). We have to clear all information in the
5371 * skb that could impact namespace isolation.
5373 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5375 skb->pkt_type = PACKET_HOST;
5381 nf_reset_trace(skb);
5383 #ifdef CONFIG_NET_SWITCHDEV
5384 skb->offload_fwd_mark = 0;
5385 skb->offload_l3_fwd_mark = 0;
5393 skb_clear_tstamp(skb);
5395 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5398 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5402 * skb_gso_transport_seglen is used to determine the real size of the
5403 * individual segments, including Layer4 headers (TCP/UDP).
5405 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5407 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5409 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5410 unsigned int thlen = 0;
5412 if (skb->encapsulation) {
5413 thlen = skb_inner_transport_header(skb) -
5414 skb_transport_header(skb);
5416 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5417 thlen += inner_tcp_hdrlen(skb);
5418 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5419 thlen = tcp_hdrlen(skb);
5420 } else if (unlikely(skb_is_gso_sctp(skb))) {
5421 thlen = sizeof(struct sctphdr);
5422 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5423 thlen = sizeof(struct udphdr);
5425 /* UFO sets gso_size to the size of the fragmentation
5426 * payload, i.e. the size of the L4 (UDP) header is already
5429 return thlen + shinfo->gso_size;
5433 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5437 * skb_gso_network_seglen is used to determine the real size of the
5438 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5440 * The MAC/L2 header is not accounted for.
5442 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5444 unsigned int hdr_len = skb_transport_header(skb) -
5445 skb_network_header(skb);
5447 return hdr_len + skb_gso_transport_seglen(skb);
5451 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5455 * skb_gso_mac_seglen is used to determine the real size of the
5456 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5457 * headers (TCP/UDP).
5459 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5461 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5463 return hdr_len + skb_gso_transport_seglen(skb);
5467 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5469 * There are a couple of instances where we have a GSO skb, and we
5470 * want to determine what size it would be after it is segmented.
5472 * We might want to check:
5473 * - L3+L4+payload size (e.g. IP forwarding)
5474 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5476 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5480 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5481 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5483 * @max_len: The maximum permissible length.
5485 * Returns true if the segmented length <= max length.
5487 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5488 unsigned int seg_len,
5489 unsigned int max_len) {
5490 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5491 const struct sk_buff *iter;
5493 if (shinfo->gso_size != GSO_BY_FRAGS)
5494 return seg_len <= max_len;
5496 /* Undo this so we can re-use header sizes */
5497 seg_len -= GSO_BY_FRAGS;
5499 skb_walk_frags(skb, iter) {
5500 if (seg_len + skb_headlen(iter) > max_len)
5508 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5511 * @mtu: MTU to validate against
5513 * skb_gso_validate_network_len validates if a given skb will fit a
5514 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5517 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5519 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5521 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5524 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5527 * @len: length to validate against
5529 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5530 * length once split, including L2, L3 and L4 headers and the payload.
5532 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5534 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5536 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5538 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5540 int mac_len, meta_len;
5543 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5548 mac_len = skb->data - skb_mac_header(skb);
5549 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5550 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5551 mac_len - VLAN_HLEN - ETH_TLEN);
5554 meta_len = skb_metadata_len(skb);
5556 meta = skb_metadata_end(skb) - meta_len;
5557 memmove(meta + VLAN_HLEN, meta, meta_len);
5560 skb->mac_header += VLAN_HLEN;
5564 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5566 struct vlan_hdr *vhdr;
5569 if (unlikely(skb_vlan_tag_present(skb))) {
5570 /* vlan_tci is already set-up so leave this for another time */
5574 skb = skb_share_check(skb, GFP_ATOMIC);
5577 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5578 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5581 vhdr = (struct vlan_hdr *)skb->data;
5582 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5583 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5585 skb_pull_rcsum(skb, VLAN_HLEN);
5586 vlan_set_encap_proto(skb, vhdr);
5588 skb = skb_reorder_vlan_header(skb);
5592 skb_reset_network_header(skb);
5593 if (!skb_transport_header_was_set(skb))
5594 skb_reset_transport_header(skb);
5595 skb_reset_mac_len(skb);
5603 EXPORT_SYMBOL(skb_vlan_untag);
5605 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5607 if (!pskb_may_pull(skb, write_len))
5610 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5613 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5615 EXPORT_SYMBOL(skb_ensure_writable);
5617 /* remove VLAN header from packet and update csum accordingly.
5618 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5620 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5622 struct vlan_hdr *vhdr;
5623 int offset = skb->data - skb_mac_header(skb);
5626 if (WARN_ONCE(offset,
5627 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5632 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5636 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5638 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5639 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5641 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5642 __skb_pull(skb, VLAN_HLEN);
5644 vlan_set_encap_proto(skb, vhdr);
5645 skb->mac_header += VLAN_HLEN;
5647 if (skb_network_offset(skb) < ETH_HLEN)
5648 skb_set_network_header(skb, ETH_HLEN);
5650 skb_reset_mac_len(skb);
5654 EXPORT_SYMBOL(__skb_vlan_pop);
5656 /* Pop a vlan tag either from hwaccel or from payload.
5657 * Expects skb->data at mac header.
5659 int skb_vlan_pop(struct sk_buff *skb)
5665 if (likely(skb_vlan_tag_present(skb))) {
5666 __vlan_hwaccel_clear_tag(skb);
5668 if (unlikely(!eth_type_vlan(skb->protocol)))
5671 err = __skb_vlan_pop(skb, &vlan_tci);
5675 /* move next vlan tag to hw accel tag */
5676 if (likely(!eth_type_vlan(skb->protocol)))
5679 vlan_proto = skb->protocol;
5680 err = __skb_vlan_pop(skb, &vlan_tci);
5684 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5687 EXPORT_SYMBOL(skb_vlan_pop);
5689 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5690 * Expects skb->data at mac header.
5692 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5694 if (skb_vlan_tag_present(skb)) {
5695 int offset = skb->data - skb_mac_header(skb);
5698 if (WARN_ONCE(offset,
5699 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5704 err = __vlan_insert_tag(skb, skb->vlan_proto,
5705 skb_vlan_tag_get(skb));
5709 skb->protocol = skb->vlan_proto;
5710 skb->mac_len += VLAN_HLEN;
5712 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5714 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5717 EXPORT_SYMBOL(skb_vlan_push);
5720 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5722 * @skb: Socket buffer to modify
5724 * Drop the Ethernet header of @skb.
5726 * Expects that skb->data points to the mac header and that no VLAN tags are
5729 * Returns 0 on success, -errno otherwise.
5731 int skb_eth_pop(struct sk_buff *skb)
5733 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5734 skb_network_offset(skb) < ETH_HLEN)
5737 skb_pull_rcsum(skb, ETH_HLEN);
5738 skb_reset_mac_header(skb);
5739 skb_reset_mac_len(skb);
5743 EXPORT_SYMBOL(skb_eth_pop);
5746 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5748 * @skb: Socket buffer to modify
5749 * @dst: Destination MAC address of the new header
5750 * @src: Source MAC address of the new header
5752 * Prepend @skb with a new Ethernet header.
5754 * Expects that skb->data points to the mac header, which must be empty.
5756 * Returns 0 on success, -errno otherwise.
5758 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5759 const unsigned char *src)
5764 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5767 err = skb_cow_head(skb, sizeof(*eth));
5771 skb_push(skb, sizeof(*eth));
5772 skb_reset_mac_header(skb);
5773 skb_reset_mac_len(skb);
5776 ether_addr_copy(eth->h_dest, dst);
5777 ether_addr_copy(eth->h_source, src);
5778 eth->h_proto = skb->protocol;
5780 skb_postpush_rcsum(skb, eth, sizeof(*eth));
5784 EXPORT_SYMBOL(skb_eth_push);
5786 /* Update the ethertype of hdr and the skb csum value if required. */
5787 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5790 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5791 __be16 diff[] = { ~hdr->h_proto, ethertype };
5793 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5796 hdr->h_proto = ethertype;
5800 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5804 * @mpls_lse: MPLS label stack entry to push
5805 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5806 * @mac_len: length of the MAC header
5807 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5810 * Expects skb->data at mac header.
5812 * Returns 0 on success, -errno otherwise.
5814 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5815 int mac_len, bool ethernet)
5817 struct mpls_shim_hdr *lse;
5820 if (unlikely(!eth_p_mpls(mpls_proto)))
5823 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5824 if (skb->encapsulation)
5827 err = skb_cow_head(skb, MPLS_HLEN);
5831 if (!skb->inner_protocol) {
5832 skb_set_inner_network_header(skb, skb_network_offset(skb));
5833 skb_set_inner_protocol(skb, skb->protocol);
5836 skb_push(skb, MPLS_HLEN);
5837 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5839 skb_reset_mac_header(skb);
5840 skb_set_network_header(skb, mac_len);
5841 skb_reset_mac_len(skb);
5843 lse = mpls_hdr(skb);
5844 lse->label_stack_entry = mpls_lse;
5845 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5847 if (ethernet && mac_len >= ETH_HLEN)
5848 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5849 skb->protocol = mpls_proto;
5853 EXPORT_SYMBOL_GPL(skb_mpls_push);
5856 * skb_mpls_pop() - pop the outermost MPLS header
5859 * @next_proto: ethertype of header after popped MPLS header
5860 * @mac_len: length of the MAC header
5861 * @ethernet: flag to indicate if the packet is ethernet
5863 * Expects skb->data at mac header.
5865 * Returns 0 on success, -errno otherwise.
5867 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5872 if (unlikely(!eth_p_mpls(skb->protocol)))
5875 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5879 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5880 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5883 __skb_pull(skb, MPLS_HLEN);
5884 skb_reset_mac_header(skb);
5885 skb_set_network_header(skb, mac_len);
5887 if (ethernet && mac_len >= ETH_HLEN) {
5890 /* use mpls_hdr() to get ethertype to account for VLANs. */
5891 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5892 skb_mod_eth_type(skb, hdr, next_proto);
5894 skb->protocol = next_proto;
5898 EXPORT_SYMBOL_GPL(skb_mpls_pop);
5901 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
5904 * @mpls_lse: new MPLS label stack entry to update to
5906 * Expects skb->data at mac header.
5908 * Returns 0 on success, -errno otherwise.
5910 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
5914 if (unlikely(!eth_p_mpls(skb->protocol)))
5917 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
5921 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5922 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
5924 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5927 mpls_hdr(skb)->label_stack_entry = mpls_lse;
5931 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
5934 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
5938 * Expects skb->data at mac header.
5940 * Returns 0 on success, -errno otherwise.
5942 int skb_mpls_dec_ttl(struct sk_buff *skb)
5947 if (unlikely(!eth_p_mpls(skb->protocol)))
5950 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
5953 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
5954 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
5958 lse &= ~MPLS_LS_TTL_MASK;
5959 lse |= ttl << MPLS_LS_TTL_SHIFT;
5961 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
5963 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
5966 * alloc_skb_with_frags - allocate skb with page frags
5968 * @header_len: size of linear part
5969 * @data_len: needed length in frags
5970 * @max_page_order: max page order desired.
5971 * @errcode: pointer to error code if any
5972 * @gfp_mask: allocation mask
5974 * This can be used to allocate a paged skb, given a maximal order for frags.
5976 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
5977 unsigned long data_len,
5982 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
5983 unsigned long chunk;
5984 struct sk_buff *skb;
5988 *errcode = -EMSGSIZE;
5989 /* Note this test could be relaxed, if we succeed to allocate
5990 * high order pages...
5992 if (npages > MAX_SKB_FRAGS)
5995 *errcode = -ENOBUFS;
5996 skb = alloc_skb(header_len, gfp_mask);
6000 skb->truesize += npages << PAGE_SHIFT;
6002 for (i = 0; npages > 0; i++) {
6003 int order = max_page_order;
6006 if (npages >= 1 << order) {
6007 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6013 /* Do not retry other high order allocations */
6019 page = alloc_page(gfp_mask);
6023 chunk = min_t(unsigned long, data_len,
6024 PAGE_SIZE << order);
6025 skb_fill_page_desc(skb, i, page, 0, chunk);
6027 npages -= 1 << order;
6035 EXPORT_SYMBOL(alloc_skb_with_frags);
6037 /* carve out the first off bytes from skb when off < headlen */
6038 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6039 const int headlen, gfp_t gfp_mask)
6042 int size = skb_end_offset(skb);
6043 int new_hlen = headlen - off;
6046 size = SKB_DATA_ALIGN(size);
6048 if (skb_pfmemalloc(skb))
6049 gfp_mask |= __GFP_MEMALLOC;
6050 data = kmalloc_reserve(size +
6051 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6052 gfp_mask, NUMA_NO_NODE, NULL);
6056 size = SKB_WITH_OVERHEAD(ksize(data));
6058 /* Copy real data, and all frags */
6059 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6062 memcpy((struct skb_shared_info *)(data + size),
6064 offsetof(struct skb_shared_info,
6065 frags[skb_shinfo(skb)->nr_frags]));
6066 if (skb_cloned(skb)) {
6067 /* drop the old head gracefully */
6068 if (skb_orphan_frags(skb, gfp_mask)) {
6072 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6073 skb_frag_ref(skb, i);
6074 if (skb_has_frag_list(skb))
6075 skb_clone_fraglist(skb);
6076 skb_release_data(skb);
6078 /* we can reuse existing recount- all we did was
6087 skb_set_end_offset(skb, size);
6088 skb_set_tail_pointer(skb, skb_headlen(skb));
6089 skb_headers_offset_update(skb, 0);
6093 atomic_set(&skb_shinfo(skb)->dataref, 1);
6098 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6100 /* carve out the first eat bytes from skb's frag_list. May recurse into
6103 static int pskb_carve_frag_list(struct sk_buff *skb,
6104 struct skb_shared_info *shinfo, int eat,
6107 struct sk_buff *list = shinfo->frag_list;
6108 struct sk_buff *clone = NULL;
6109 struct sk_buff *insp = NULL;
6113 pr_err("Not enough bytes to eat. Want %d\n", eat);
6116 if (list->len <= eat) {
6117 /* Eaten as whole. */
6122 /* Eaten partially. */
6123 if (skb_shared(list)) {
6124 clone = skb_clone(list, gfp_mask);
6130 /* This may be pulled without problems. */
6133 if (pskb_carve(list, eat, gfp_mask) < 0) {
6141 /* Free pulled out fragments. */
6142 while ((list = shinfo->frag_list) != insp) {
6143 shinfo->frag_list = list->next;
6146 /* And insert new clone at head. */
6149 shinfo->frag_list = clone;
6154 /* carve off first len bytes from skb. Split line (off) is in the
6155 * non-linear part of skb
6157 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6158 int pos, gfp_t gfp_mask)
6161 int size = skb_end_offset(skb);
6163 const int nfrags = skb_shinfo(skb)->nr_frags;
6164 struct skb_shared_info *shinfo;
6166 size = SKB_DATA_ALIGN(size);
6168 if (skb_pfmemalloc(skb))
6169 gfp_mask |= __GFP_MEMALLOC;
6170 data = kmalloc_reserve(size +
6171 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6172 gfp_mask, NUMA_NO_NODE, NULL);
6176 size = SKB_WITH_OVERHEAD(ksize(data));
6178 memcpy((struct skb_shared_info *)(data + size),
6179 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6180 if (skb_orphan_frags(skb, gfp_mask)) {
6184 shinfo = (struct skb_shared_info *)(data + size);
6185 for (i = 0; i < nfrags; i++) {
6186 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6188 if (pos + fsize > off) {
6189 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6193 * We have two variants in this case:
6194 * 1. Move all the frag to the second
6195 * part, if it is possible. F.e.
6196 * this approach is mandatory for TUX,
6197 * where splitting is expensive.
6198 * 2. Split is accurately. We make this.
6200 skb_frag_off_add(&shinfo->frags[0], off - pos);
6201 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6203 skb_frag_ref(skb, i);
6208 shinfo->nr_frags = k;
6209 if (skb_has_frag_list(skb))
6210 skb_clone_fraglist(skb);
6212 /* split line is in frag list */
6213 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6214 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6215 if (skb_has_frag_list(skb))
6216 kfree_skb_list(skb_shinfo(skb)->frag_list);
6220 skb_release_data(skb);
6225 skb_set_end_offset(skb, size);
6226 skb_reset_tail_pointer(skb);
6227 skb_headers_offset_update(skb, 0);
6232 skb->data_len = skb->len;
6233 atomic_set(&skb_shinfo(skb)->dataref, 1);
6237 /* remove len bytes from the beginning of the skb */
6238 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6240 int headlen = skb_headlen(skb);
6243 return pskb_carve_inside_header(skb, len, headlen, gfp);
6245 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6248 /* Extract to_copy bytes starting at off from skb, and return this in
6251 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6252 int to_copy, gfp_t gfp)
6254 struct sk_buff *clone = skb_clone(skb, gfp);
6259 if (pskb_carve(clone, off, gfp) < 0 ||
6260 pskb_trim(clone, to_copy)) {
6266 EXPORT_SYMBOL(pskb_extract);
6269 * skb_condense - try to get rid of fragments/frag_list if possible
6272 * Can be used to save memory before skb is added to a busy queue.
6273 * If packet has bytes in frags and enough tail room in skb->head,
6274 * pull all of them, so that we can free the frags right now and adjust
6277 * We do not reallocate skb->head thus can not fail.
6278 * Caller must re-evaluate skb->truesize if needed.
6280 void skb_condense(struct sk_buff *skb)
6282 if (skb->data_len) {
6283 if (skb->data_len > skb->end - skb->tail ||
6287 /* Nice, we can free page frag(s) right now */
6288 __pskb_pull_tail(skb, skb->data_len);
6290 /* At this point, skb->truesize might be over estimated,
6291 * because skb had a fragment, and fragments do not tell
6293 * When we pulled its content into skb->head, fragment
6294 * was freed, but __pskb_pull_tail() could not possibly
6295 * adjust skb->truesize, not knowing the frag truesize.
6297 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6300 #ifdef CONFIG_SKB_EXTENSIONS
6301 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6303 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6307 * __skb_ext_alloc - allocate a new skb extensions storage
6309 * @flags: See kmalloc().
6311 * Returns the newly allocated pointer. The pointer can later attached to a
6312 * skb via __skb_ext_set().
6313 * Note: caller must handle the skb_ext as an opaque data.
6315 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6317 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6320 memset(new->offset, 0, sizeof(new->offset));
6321 refcount_set(&new->refcnt, 1);
6327 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6328 unsigned int old_active)
6330 struct skb_ext *new;
6332 if (refcount_read(&old->refcnt) == 1)
6335 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6339 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6340 refcount_set(&new->refcnt, 1);
6343 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6344 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6347 for (i = 0; i < sp->len; i++)
6348 xfrm_state_hold(sp->xvec[i]);
6356 * __skb_ext_set - attach the specified extension storage to this skb
6359 * @ext: extension storage previously allocated via __skb_ext_alloc()
6361 * Existing extensions, if any, are cleared.
6363 * Returns the pointer to the extension.
6365 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6366 struct skb_ext *ext)
6368 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6371 newlen = newoff + skb_ext_type_len[id];
6372 ext->chunks = newlen;
6373 ext->offset[id] = newoff;
6374 skb->extensions = ext;
6375 skb->active_extensions = 1 << id;
6376 return skb_ext_get_ptr(ext, id);
6380 * skb_ext_add - allocate space for given extension, COW if needed
6382 * @id: extension to allocate space for
6384 * Allocates enough space for the given extension.
6385 * If the extension is already present, a pointer to that extension
6388 * If the skb was cloned, COW applies and the returned memory can be
6389 * modified without changing the extension space of clones buffers.
6391 * Returns pointer to the extension or NULL on allocation failure.
6393 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6395 struct skb_ext *new, *old = NULL;
6396 unsigned int newlen, newoff;
6398 if (skb->active_extensions) {
6399 old = skb->extensions;
6401 new = skb_ext_maybe_cow(old, skb->active_extensions);
6405 if (__skb_ext_exist(new, id))
6408 newoff = new->chunks;
6410 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6412 new = __skb_ext_alloc(GFP_ATOMIC);
6417 newlen = newoff + skb_ext_type_len[id];
6418 new->chunks = newlen;
6419 new->offset[id] = newoff;
6422 skb->extensions = new;
6423 skb->active_extensions |= 1 << id;
6424 return skb_ext_get_ptr(new, id);
6426 EXPORT_SYMBOL(skb_ext_add);
6429 static void skb_ext_put_sp(struct sec_path *sp)
6433 for (i = 0; i < sp->len; i++)
6434 xfrm_state_put(sp->xvec[i]);
6438 #ifdef CONFIG_MCTP_FLOWS
6439 static void skb_ext_put_mctp(struct mctp_flow *flow)
6442 mctp_key_unref(flow->key);
6446 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6448 struct skb_ext *ext = skb->extensions;
6450 skb->active_extensions &= ~(1 << id);
6451 if (skb->active_extensions == 0) {
6452 skb->extensions = NULL;
6455 } else if (id == SKB_EXT_SEC_PATH &&
6456 refcount_read(&ext->refcnt) == 1) {
6457 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6464 EXPORT_SYMBOL(__skb_ext_del);
6466 void __skb_ext_put(struct skb_ext *ext)
6468 /* If this is last clone, nothing can increment
6469 * it after check passes. Avoids one atomic op.
6471 if (refcount_read(&ext->refcnt) == 1)
6474 if (!refcount_dec_and_test(&ext->refcnt))
6478 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6479 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6481 #ifdef CONFIG_MCTP_FLOWS
6482 if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6483 skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6486 kmem_cache_free(skbuff_ext_cache, ext);
6488 EXPORT_SYMBOL(__skb_ext_put);
6489 #endif /* CONFIG_SKB_EXTENSIONS */
6492 * skb_attempt_defer_free - queue skb for remote freeing
6495 * Put @skb in a per-cpu list, using the cpu which
6496 * allocated the skb/pages to reduce false sharing
6497 * and memory zone spinlock contention.
6499 void skb_attempt_defer_free(struct sk_buff *skb)
6501 int cpu = skb->alloc_cpu;
6502 struct softnet_data *sd;
6503 unsigned long flags;
6504 unsigned int defer_max;
6507 if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6509 cpu == raw_smp_processor_id()) {
6510 nodefer: __kfree_skb(skb);
6514 sd = &per_cpu(softnet_data, cpu);
6515 defer_max = READ_ONCE(sysctl_skb_defer_max);
6516 if (READ_ONCE(sd->defer_count) >= defer_max)
6519 spin_lock_irqsave(&sd->defer_lock, flags);
6520 /* Send an IPI every time queue reaches half capacity. */
6521 kick = sd->defer_count == (defer_max >> 1);
6522 /* Paired with the READ_ONCE() few lines above */
6523 WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6525 skb->next = sd->defer_list;
6526 /* Paired with READ_ONCE() in skb_defer_free_flush() */
6527 WRITE_ONCE(sd->defer_list, skb);
6528 spin_unlock_irqrestore(&sd->defer_lock, flags);
6530 /* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6531 * if we are unlucky enough (this seems very unlikely).
6533 if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6534 smp_call_function_single_async(cpu, &sd->defer_csd);