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>
73 #include <net/page_pool.h>
75 #include <linux/uaccess.h>
76 #include <trace/events/skb.h>
77 #include <linux/highmem.h>
78 #include <linux/capability.h>
79 #include <linux/user_namespace.h>
80 #include <linux/indirect_call_wrapper.h>
83 #include "sock_destructor.h"
85 struct kmem_cache *skbuff_head_cache __ro_after_init;
86 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
87 #ifdef CONFIG_SKB_EXTENSIONS
88 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
90 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
91 EXPORT_SYMBOL(sysctl_max_skb_frags);
94 * skb_panic - private function for out-of-line support
98 * @msg: skb_over_panic or skb_under_panic
100 * Out-of-line support for skb_put() and skb_push().
101 * Called via the wrapper skb_over_panic() or skb_under_panic().
102 * Keep out of line to prevent kernel bloat.
103 * __builtin_return_address is not used because it is not always reliable.
105 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
108 pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
109 msg, addr, skb->len, sz, skb->head, skb->data,
110 (unsigned long)skb->tail, (unsigned long)skb->end,
111 skb->dev ? skb->dev->name : "<NULL>");
115 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
117 skb_panic(skb, sz, addr, __func__);
120 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
122 skb_panic(skb, sz, addr, __func__);
125 #define NAPI_SKB_CACHE_SIZE 64
126 #define NAPI_SKB_CACHE_BULK 16
127 #define NAPI_SKB_CACHE_HALF (NAPI_SKB_CACHE_SIZE / 2)
129 struct napi_alloc_cache {
130 struct page_frag_cache page;
131 unsigned int skb_count;
132 void *skb_cache[NAPI_SKB_CACHE_SIZE];
135 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
136 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
138 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
140 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
142 fragsz = SKB_DATA_ALIGN(fragsz);
144 return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
146 EXPORT_SYMBOL(__napi_alloc_frag_align);
148 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
152 fragsz = SKB_DATA_ALIGN(fragsz);
153 if (in_hardirq() || irqs_disabled()) {
154 struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
156 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
158 struct napi_alloc_cache *nc;
161 nc = this_cpu_ptr(&napi_alloc_cache);
162 data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
167 EXPORT_SYMBOL(__netdev_alloc_frag_align);
169 static struct sk_buff *napi_skb_cache_get(void)
171 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
174 if (unlikely(!nc->skb_count))
175 nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
179 if (unlikely(!nc->skb_count))
182 skb = nc->skb_cache[--nc->skb_count];
183 kasan_unpoison_object_data(skbuff_head_cache, skb);
188 /* Caller must provide SKB that is memset cleared */
189 static void __build_skb_around(struct sk_buff *skb, void *data,
190 unsigned int frag_size)
192 struct skb_shared_info *shinfo;
193 unsigned int size = frag_size ? : ksize(data);
195 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
197 /* Assumes caller memset cleared SKB */
198 skb->truesize = SKB_TRUESIZE(size);
199 refcount_set(&skb->users, 1);
202 skb_reset_tail_pointer(skb);
203 skb->end = skb->tail + size;
204 skb->mac_header = (typeof(skb->mac_header))~0U;
205 skb->transport_header = (typeof(skb->transport_header))~0U;
207 /* make sure we initialize shinfo sequentially */
208 shinfo = skb_shinfo(skb);
209 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
210 atomic_set(&shinfo->dataref, 1);
212 skb_set_kcov_handle(skb, kcov_common_handle());
216 * __build_skb - build a network buffer
217 * @data: data buffer provided by caller
218 * @frag_size: size of data, or 0 if head was kmalloced
220 * Allocate a new &sk_buff. Caller provides space holding head and
221 * skb_shared_info. @data must have been allocated by kmalloc() only if
222 * @frag_size is 0, otherwise data should come from the page allocator
224 * The return is the new skb buffer.
225 * On a failure the return is %NULL, and @data is not freed.
227 * Before IO, driver allocates only data buffer where NIC put incoming frame
228 * Driver should add room at head (NET_SKB_PAD) and
229 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
230 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
231 * before giving packet to stack.
232 * RX rings only contains data buffers, not full skbs.
234 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
238 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
242 memset(skb, 0, offsetof(struct sk_buff, tail));
243 __build_skb_around(skb, data, frag_size);
248 /* build_skb() is wrapper over __build_skb(), that specifically
249 * takes care of skb->head and skb->pfmemalloc
250 * This means that if @frag_size is not zero, then @data must be backed
251 * by a page fragment, not kmalloc() or vmalloc()
253 struct sk_buff *build_skb(void *data, unsigned int frag_size)
255 struct sk_buff *skb = __build_skb(data, frag_size);
257 if (skb && frag_size) {
259 if (page_is_pfmemalloc(virt_to_head_page(data)))
264 EXPORT_SYMBOL(build_skb);
267 * build_skb_around - build a network buffer around provided skb
268 * @skb: sk_buff provide by caller, must be memset cleared
269 * @data: data buffer provided by caller
270 * @frag_size: size of data, or 0 if head was kmalloced
272 struct sk_buff *build_skb_around(struct sk_buff *skb,
273 void *data, unsigned int frag_size)
278 __build_skb_around(skb, data, frag_size);
282 if (page_is_pfmemalloc(virt_to_head_page(data)))
287 EXPORT_SYMBOL(build_skb_around);
290 * __napi_build_skb - build a network buffer
291 * @data: data buffer provided by caller
292 * @frag_size: size of data, or 0 if head was kmalloced
294 * Version of __build_skb() that uses NAPI percpu caches to obtain
295 * skbuff_head instead of inplace allocation.
297 * Returns a new &sk_buff on success, %NULL on allocation failure.
299 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
303 skb = napi_skb_cache_get();
307 memset(skb, 0, offsetof(struct sk_buff, tail));
308 __build_skb_around(skb, data, frag_size);
314 * napi_build_skb - build a network buffer
315 * @data: data buffer provided by caller
316 * @frag_size: size of data, or 0 if head was kmalloced
318 * Version of __napi_build_skb() that takes care of skb->head_frag
319 * and skb->pfmemalloc when the data is a page or page fragment.
321 * Returns a new &sk_buff on success, %NULL on allocation failure.
323 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
325 struct sk_buff *skb = __napi_build_skb(data, frag_size);
327 if (likely(skb) && frag_size) {
329 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
334 EXPORT_SYMBOL(napi_build_skb);
337 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
338 * the caller if emergency pfmemalloc reserves are being used. If it is and
339 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
340 * may be used. Otherwise, the packet data may be discarded until enough
343 static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
347 bool ret_pfmemalloc = false;
350 * Try a regular allocation, when that fails and we're not entitled
351 * to the reserves, fail.
353 obj = kmalloc_node_track_caller(size,
354 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
356 if (obj || !(gfp_pfmemalloc_allowed(flags)))
359 /* Try again but now we are using pfmemalloc reserves */
360 ret_pfmemalloc = true;
361 obj = kmalloc_node_track_caller(size, flags, node);
365 *pfmemalloc = ret_pfmemalloc;
370 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
371 * 'private' fields and also do memory statistics to find all the
377 * __alloc_skb - allocate a network buffer
378 * @size: size to allocate
379 * @gfp_mask: allocation mask
380 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
381 * instead of head cache and allocate a cloned (child) skb.
382 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
383 * allocations in case the data is required for writeback
384 * @node: numa node to allocate memory on
386 * Allocate a new &sk_buff. The returned buffer has no headroom and a
387 * tail room of at least size bytes. The object has a reference count
388 * of one. The return is the buffer. On a failure the return is %NULL.
390 * Buffers may only be allocated from interrupts using a @gfp_mask of
393 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
396 struct kmem_cache *cache;
402 cache = (flags & SKB_ALLOC_FCLONE)
403 ? skbuff_fclone_cache : skbuff_head_cache;
405 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
406 gfp_mask |= __GFP_MEMALLOC;
409 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
410 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
411 skb = napi_skb_cache_get();
413 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
418 /* We do our best to align skb_shared_info on a separate cache
419 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
420 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
421 * Both skb->head and skb_shared_info are cache line aligned.
423 size = SKB_DATA_ALIGN(size);
424 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
425 data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
428 /* kmalloc(size) might give us more room than requested.
429 * Put skb_shared_info exactly at the end of allocated zone,
430 * to allow max possible filling before reallocation.
433 size = SKB_WITH_OVERHEAD(osize);
434 prefetchw(data + size);
437 * Only clear those fields we need to clear, not those that we will
438 * actually initialise below. Hence, don't put any more fields after
439 * the tail pointer in struct sk_buff!
441 memset(skb, 0, offsetof(struct sk_buff, tail));
442 __build_skb_around(skb, data, osize);
443 skb->pfmemalloc = pfmemalloc;
445 if (flags & SKB_ALLOC_FCLONE) {
446 struct sk_buff_fclones *fclones;
448 fclones = container_of(skb, struct sk_buff_fclones, skb1);
450 skb->fclone = SKB_FCLONE_ORIG;
451 refcount_set(&fclones->fclone_ref, 1);
453 fclones->skb2.fclone = SKB_FCLONE_CLONE;
459 kmem_cache_free(cache, skb);
462 EXPORT_SYMBOL(__alloc_skb);
465 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
466 * @dev: network device to receive on
467 * @len: length to allocate
468 * @gfp_mask: get_free_pages mask, passed to alloc_skb
470 * Allocate a new &sk_buff and assign it a usage count of one. The
471 * buffer has NET_SKB_PAD headroom built in. Users should allocate
472 * the headroom they think they need without accounting for the
473 * built in space. The built in space is used for optimisations.
475 * %NULL is returned if there is no free memory.
477 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
480 struct page_frag_cache *nc;
487 /* If requested length is either too small or too big,
488 * we use kmalloc() for skb->head allocation.
490 if (len <= SKB_WITH_OVERHEAD(1024) ||
491 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
492 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
493 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
499 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
500 len = SKB_DATA_ALIGN(len);
502 if (sk_memalloc_socks())
503 gfp_mask |= __GFP_MEMALLOC;
505 if (in_hardirq() || irqs_disabled()) {
506 nc = this_cpu_ptr(&netdev_alloc_cache);
507 data = page_frag_alloc(nc, len, gfp_mask);
508 pfmemalloc = nc->pfmemalloc;
511 nc = this_cpu_ptr(&napi_alloc_cache.page);
512 data = page_frag_alloc(nc, len, gfp_mask);
513 pfmemalloc = nc->pfmemalloc;
520 skb = __build_skb(data, len);
521 if (unlikely(!skb)) {
531 skb_reserve(skb, NET_SKB_PAD);
537 EXPORT_SYMBOL(__netdev_alloc_skb);
540 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
541 * @napi: napi instance this buffer was allocated for
542 * @len: length to allocate
543 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
545 * Allocate a new sk_buff for use in NAPI receive. This buffer will
546 * attempt to allocate the head from a special reserved region used
547 * only for NAPI Rx allocation. By doing this we can save several
548 * CPU cycles by avoiding having to disable and re-enable IRQs.
550 * %NULL is returned if there is no free memory.
552 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
555 struct napi_alloc_cache *nc;
559 len += NET_SKB_PAD + NET_IP_ALIGN;
561 /* If requested length is either too small or too big,
562 * we use kmalloc() for skb->head allocation.
564 if (len <= SKB_WITH_OVERHEAD(1024) ||
565 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
566 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
567 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
574 nc = this_cpu_ptr(&napi_alloc_cache);
575 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
576 len = SKB_DATA_ALIGN(len);
578 if (sk_memalloc_socks())
579 gfp_mask |= __GFP_MEMALLOC;
581 data = page_frag_alloc(&nc->page, len, gfp_mask);
585 skb = __napi_build_skb(data, len);
586 if (unlikely(!skb)) {
591 if (nc->page.pfmemalloc)
596 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
597 skb->dev = napi->dev;
602 EXPORT_SYMBOL(__napi_alloc_skb);
604 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
605 int size, unsigned int truesize)
607 skb_fill_page_desc(skb, i, page, off, size);
609 skb->data_len += size;
610 skb->truesize += truesize;
612 EXPORT_SYMBOL(skb_add_rx_frag);
614 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
615 unsigned int truesize)
617 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
619 skb_frag_size_add(frag, size);
621 skb->data_len += size;
622 skb->truesize += truesize;
624 EXPORT_SYMBOL(skb_coalesce_rx_frag);
626 static void skb_drop_list(struct sk_buff **listp)
628 kfree_skb_list(*listp);
632 static inline void skb_drop_fraglist(struct sk_buff *skb)
634 skb_drop_list(&skb_shinfo(skb)->frag_list);
637 static void skb_clone_fraglist(struct sk_buff *skb)
639 struct sk_buff *list;
641 skb_walk_frags(skb, list)
645 static void skb_free_head(struct sk_buff *skb)
647 unsigned char *head = skb->head;
649 if (skb->head_frag) {
650 if (skb_pp_recycle(skb, head))
658 static void skb_release_data(struct sk_buff *skb)
660 struct skb_shared_info *shinfo = skb_shinfo(skb);
664 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
668 skb_zcopy_clear(skb, true);
670 for (i = 0; i < shinfo->nr_frags; i++)
671 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
673 if (shinfo->frag_list)
674 kfree_skb_list(shinfo->frag_list);
678 /* When we clone an SKB we copy the reycling bit. The pp_recycle
679 * bit is only set on the head though, so in order to avoid races
680 * while trying to recycle fragments on __skb_frag_unref() we need
681 * to make one SKB responsible for triggering the recycle path.
682 * So disable the recycling bit if an SKB is cloned and we have
683 * additional references to to the fragmented part of the SKB.
684 * Eventually the last SKB will have the recycling bit set and it's
685 * dataref set to 0, which will trigger the recycling
691 * Free an skbuff by memory without cleaning the state.
693 static void kfree_skbmem(struct sk_buff *skb)
695 struct sk_buff_fclones *fclones;
697 switch (skb->fclone) {
698 case SKB_FCLONE_UNAVAILABLE:
699 kmem_cache_free(skbuff_head_cache, skb);
702 case SKB_FCLONE_ORIG:
703 fclones = container_of(skb, struct sk_buff_fclones, skb1);
705 /* We usually free the clone (TX completion) before original skb
706 * This test would have no chance to be true for the clone,
707 * while here, branch prediction will be good.
709 if (refcount_read(&fclones->fclone_ref) == 1)
713 default: /* SKB_FCLONE_CLONE */
714 fclones = container_of(skb, struct sk_buff_fclones, skb2);
717 if (!refcount_dec_and_test(&fclones->fclone_ref))
720 kmem_cache_free(skbuff_fclone_cache, fclones);
723 void skb_release_head_state(struct sk_buff *skb)
726 if (skb->destructor) {
727 WARN_ON(in_hardirq());
728 skb->destructor(skb);
730 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
731 nf_conntrack_put(skb_nfct(skb));
736 /* Free everything but the sk_buff shell. */
737 static void skb_release_all(struct sk_buff *skb)
739 skb_release_head_state(skb);
740 if (likely(skb->head))
741 skb_release_data(skb);
745 * __kfree_skb - private function
748 * Free an sk_buff. Release anything attached to the buffer.
749 * Clean the state. This is an internal helper function. Users should
750 * always call kfree_skb
753 void __kfree_skb(struct sk_buff *skb)
755 skb_release_all(skb);
758 EXPORT_SYMBOL(__kfree_skb);
761 * kfree_skb - free an sk_buff
762 * @skb: buffer to free
764 * Drop a reference to the buffer and free it if the usage count has
767 void kfree_skb(struct sk_buff *skb)
772 trace_kfree_skb(skb, __builtin_return_address(0));
775 EXPORT_SYMBOL(kfree_skb);
777 void kfree_skb_list(struct sk_buff *segs)
780 struct sk_buff *next = segs->next;
786 EXPORT_SYMBOL(kfree_skb_list);
788 /* Dump skb information and contents.
790 * Must only be called from net_ratelimit()-ed paths.
792 * Dumps whole packets if full_pkt, only headers otherwise.
794 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
796 struct skb_shared_info *sh = skb_shinfo(skb);
797 struct net_device *dev = skb->dev;
798 struct sock *sk = skb->sk;
799 struct sk_buff *list_skb;
800 bool has_mac, has_trans;
801 int headroom, tailroom;
807 len = min_t(int, skb->len, MAX_HEADER + 128);
809 headroom = skb_headroom(skb);
810 tailroom = skb_tailroom(skb);
812 has_mac = skb_mac_header_was_set(skb);
813 has_trans = skb_transport_header_was_set(skb);
815 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
816 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
817 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
818 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
819 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
820 level, skb->len, headroom, skb_headlen(skb), tailroom,
821 has_mac ? skb->mac_header : -1,
822 has_mac ? skb_mac_header_len(skb) : -1,
824 has_trans ? skb_network_header_len(skb) : -1,
825 has_trans ? skb->transport_header : -1,
826 sh->tx_flags, sh->nr_frags,
827 sh->gso_size, sh->gso_type, sh->gso_segs,
828 skb->csum, skb->ip_summed, skb->csum_complete_sw,
829 skb->csum_valid, skb->csum_level,
830 skb->hash, skb->sw_hash, skb->l4_hash,
831 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
834 printk("%sdev name=%s feat=0x%pNF\n",
835 level, dev->name, &dev->features);
837 printk("%ssk family=%hu type=%u proto=%u\n",
838 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
840 if (full_pkt && headroom)
841 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
842 16, 1, skb->head, headroom, false);
844 seg_len = min_t(int, skb_headlen(skb), len);
846 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
847 16, 1, skb->data, seg_len, false);
850 if (full_pkt && tailroom)
851 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
852 16, 1, skb_tail_pointer(skb), tailroom, false);
854 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
855 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
856 u32 p_off, p_len, copied;
860 skb_frag_foreach_page(frag, skb_frag_off(frag),
861 skb_frag_size(frag), p, p_off, p_len,
863 seg_len = min_t(int, p_len, len);
864 vaddr = kmap_atomic(p);
865 print_hex_dump(level, "skb frag: ",
867 16, 1, vaddr + p_off, seg_len, false);
868 kunmap_atomic(vaddr);
875 if (full_pkt && skb_has_frag_list(skb)) {
876 printk("skb fraglist:\n");
877 skb_walk_frags(skb, list_skb)
878 skb_dump(level, list_skb, true);
881 EXPORT_SYMBOL(skb_dump);
884 * skb_tx_error - report an sk_buff xmit error
885 * @skb: buffer that triggered an error
887 * Report xmit error if a device callback is tracking this skb.
888 * skb must be freed afterwards.
890 void skb_tx_error(struct sk_buff *skb)
892 skb_zcopy_clear(skb, true);
894 EXPORT_SYMBOL(skb_tx_error);
896 #ifdef CONFIG_TRACEPOINTS
898 * consume_skb - free an skbuff
899 * @skb: buffer to free
901 * Drop a ref to the buffer and free it if the usage count has hit zero
902 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
903 * is being dropped after a failure and notes that
905 void consume_skb(struct sk_buff *skb)
910 trace_consume_skb(skb);
913 EXPORT_SYMBOL(consume_skb);
917 * __consume_stateless_skb - free an skbuff, assuming it is stateless
918 * @skb: buffer to free
920 * Alike consume_skb(), but this variant assumes that this is the last
921 * skb reference and all the head states have been already dropped
923 void __consume_stateless_skb(struct sk_buff *skb)
925 trace_consume_skb(skb);
926 skb_release_data(skb);
930 static void napi_skb_cache_put(struct sk_buff *skb)
932 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
935 kasan_poison_object_data(skbuff_head_cache, skb);
936 nc->skb_cache[nc->skb_count++] = skb;
938 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
939 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
940 kasan_unpoison_object_data(skbuff_head_cache,
943 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
944 nc->skb_cache + NAPI_SKB_CACHE_HALF);
945 nc->skb_count = NAPI_SKB_CACHE_HALF;
949 void __kfree_skb_defer(struct sk_buff *skb)
951 skb_release_all(skb);
952 napi_skb_cache_put(skb);
955 void napi_skb_free_stolen_head(struct sk_buff *skb)
957 if (unlikely(skb->slow_gro)) {
964 napi_skb_cache_put(skb);
967 void napi_consume_skb(struct sk_buff *skb, int budget)
969 /* Zero budget indicate non-NAPI context called us, like netpoll */
970 if (unlikely(!budget)) {
971 dev_consume_skb_any(skb);
975 lockdep_assert_in_softirq();
980 /* if reaching here SKB is ready to free */
981 trace_consume_skb(skb);
983 /* if SKB is a clone, don't handle this case */
984 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
989 skb_release_all(skb);
990 napi_skb_cache_put(skb);
992 EXPORT_SYMBOL(napi_consume_skb);
994 /* Make sure a field is enclosed inside headers_start/headers_end section */
995 #define CHECK_SKB_FIELD(field) \
996 BUILD_BUG_ON(offsetof(struct sk_buff, field) < \
997 offsetof(struct sk_buff, headers_start)); \
998 BUILD_BUG_ON(offsetof(struct sk_buff, field) > \
999 offsetof(struct sk_buff, headers_end)); \
1001 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1003 new->tstamp = old->tstamp;
1004 /* We do not copy old->sk */
1005 new->dev = old->dev;
1006 memcpy(new->cb, old->cb, sizeof(old->cb));
1007 skb_dst_copy(new, old);
1008 __skb_ext_copy(new, old);
1009 __nf_copy(new, old, false);
1011 /* Note : this field could be in headers_start/headers_end section
1012 * It is not yet because we do not want to have a 16 bit hole
1014 new->queue_mapping = old->queue_mapping;
1016 memcpy(&new->headers_start, &old->headers_start,
1017 offsetof(struct sk_buff, headers_end) -
1018 offsetof(struct sk_buff, headers_start));
1019 CHECK_SKB_FIELD(protocol);
1020 CHECK_SKB_FIELD(csum);
1021 CHECK_SKB_FIELD(hash);
1022 CHECK_SKB_FIELD(priority);
1023 CHECK_SKB_FIELD(skb_iif);
1024 CHECK_SKB_FIELD(vlan_proto);
1025 CHECK_SKB_FIELD(vlan_tci);
1026 CHECK_SKB_FIELD(transport_header);
1027 CHECK_SKB_FIELD(network_header);
1028 CHECK_SKB_FIELD(mac_header);
1029 CHECK_SKB_FIELD(inner_protocol);
1030 CHECK_SKB_FIELD(inner_transport_header);
1031 CHECK_SKB_FIELD(inner_network_header);
1032 CHECK_SKB_FIELD(inner_mac_header);
1033 CHECK_SKB_FIELD(mark);
1034 #ifdef CONFIG_NETWORK_SECMARK
1035 CHECK_SKB_FIELD(secmark);
1037 #ifdef CONFIG_NET_RX_BUSY_POLL
1038 CHECK_SKB_FIELD(napi_id);
1041 CHECK_SKB_FIELD(sender_cpu);
1043 #ifdef CONFIG_NET_SCHED
1044 CHECK_SKB_FIELD(tc_index);
1050 * You should not add any new code to this function. Add it to
1051 * __copy_skb_header above instead.
1053 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1055 #define C(x) n->x = skb->x
1057 n->next = n->prev = NULL;
1059 __copy_skb_header(n, skb);
1064 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1070 n->destructor = NULL;
1077 refcount_set(&n->users, 1);
1079 atomic_inc(&(skb_shinfo(skb)->dataref));
1087 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1088 * @first: first sk_buff of the msg
1090 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1094 n = alloc_skb(0, GFP_ATOMIC);
1098 n->len = first->len;
1099 n->data_len = first->len;
1100 n->truesize = first->truesize;
1102 skb_shinfo(n)->frag_list = first;
1104 __copy_skb_header(n, first);
1105 n->destructor = NULL;
1109 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1112 * skb_morph - morph one skb into another
1113 * @dst: the skb to receive the contents
1114 * @src: the skb to supply the contents
1116 * This is identical to skb_clone except that the target skb is
1117 * supplied by the user.
1119 * The target skb is returned upon exit.
1121 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1123 skb_release_all(dst);
1124 return __skb_clone(dst, src);
1126 EXPORT_SYMBOL_GPL(skb_morph);
1128 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1130 unsigned long max_pg, num_pg, new_pg, old_pg;
1131 struct user_struct *user;
1133 if (capable(CAP_IPC_LOCK) || !size)
1136 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1137 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1138 user = mmp->user ? : current_user();
1141 old_pg = atomic_long_read(&user->locked_vm);
1142 new_pg = old_pg + num_pg;
1143 if (new_pg > max_pg)
1145 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1149 mmp->user = get_uid(user);
1150 mmp->num_pg = num_pg;
1152 mmp->num_pg += num_pg;
1157 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1159 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1162 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1163 free_uid(mmp->user);
1166 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1168 struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1170 struct ubuf_info *uarg;
1171 struct sk_buff *skb;
1173 WARN_ON_ONCE(!in_task());
1175 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1179 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1180 uarg = (void *)skb->cb;
1181 uarg->mmp.user = NULL;
1183 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1188 uarg->callback = msg_zerocopy_callback;
1189 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1191 uarg->bytelen = size;
1193 uarg->flags = SKBFL_ZEROCOPY_FRAG;
1194 refcount_set(&uarg->refcnt, 1);
1199 EXPORT_SYMBOL_GPL(msg_zerocopy_alloc);
1201 static inline struct sk_buff *skb_from_uarg(struct ubuf_info *uarg)
1203 return container_of((void *)uarg, struct sk_buff, cb);
1206 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1207 struct ubuf_info *uarg)
1210 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1213 /* realloc only when socket is locked (TCP, UDP cork),
1214 * so uarg->len and sk_zckey access is serialized
1216 if (!sock_owned_by_user(sk)) {
1221 bytelen = uarg->bytelen + size;
1222 if (uarg->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1223 /* TCP can create new skb to attach new uarg */
1224 if (sk->sk_type == SOCK_STREAM)
1229 next = (u32)atomic_read(&sk->sk_zckey);
1230 if ((u32)(uarg->id + uarg->len) == next) {
1231 if (mm_account_pinned_pages(&uarg->mmp, size))
1234 uarg->bytelen = bytelen;
1235 atomic_set(&sk->sk_zckey, ++next);
1237 /* no extra ref when appending to datagram (MSG_MORE) */
1238 if (sk->sk_type == SOCK_STREAM)
1239 net_zcopy_get(uarg);
1246 return msg_zerocopy_alloc(sk, size);
1248 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1250 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1252 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1256 old_lo = serr->ee.ee_info;
1257 old_hi = serr->ee.ee_data;
1258 sum_len = old_hi - old_lo + 1ULL + len;
1260 if (sum_len >= (1ULL << 32))
1263 if (lo != old_hi + 1)
1266 serr->ee.ee_data += len;
1270 static void __msg_zerocopy_callback(struct ubuf_info *uarg)
1272 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1273 struct sock_exterr_skb *serr;
1274 struct sock *sk = skb->sk;
1275 struct sk_buff_head *q;
1276 unsigned long flags;
1281 mm_unaccount_pinned_pages(&uarg->mmp);
1283 /* if !len, there was only 1 call, and it was aborted
1284 * so do not queue a completion notification
1286 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1291 hi = uarg->id + len - 1;
1292 is_zerocopy = uarg->zerocopy;
1294 serr = SKB_EXT_ERR(skb);
1295 memset(serr, 0, sizeof(*serr));
1296 serr->ee.ee_errno = 0;
1297 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1298 serr->ee.ee_data = hi;
1299 serr->ee.ee_info = lo;
1301 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1303 q = &sk->sk_error_queue;
1304 spin_lock_irqsave(&q->lock, flags);
1305 tail = skb_peek_tail(q);
1306 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1307 !skb_zerocopy_notify_extend(tail, lo, len)) {
1308 __skb_queue_tail(q, skb);
1311 spin_unlock_irqrestore(&q->lock, flags);
1313 sk_error_report(sk);
1320 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1323 uarg->zerocopy = uarg->zerocopy & success;
1325 if (refcount_dec_and_test(&uarg->refcnt))
1326 __msg_zerocopy_callback(uarg);
1328 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1330 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1332 struct sock *sk = skb_from_uarg(uarg)->sk;
1334 atomic_dec(&sk->sk_zckey);
1338 msg_zerocopy_callback(NULL, uarg, true);
1340 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1342 int skb_zerocopy_iter_dgram(struct sk_buff *skb, struct msghdr *msg, int len)
1344 return __zerocopy_sg_from_iter(skb->sk, skb, &msg->msg_iter, len);
1346 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_dgram);
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 struct iov_iter orig_iter = msg->msg_iter;
1354 int err, orig_len = skb->len;
1356 /* An skb can only point to one uarg. This edge case happens when
1357 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1359 if (orig_uarg && uarg != orig_uarg)
1362 err = __zerocopy_sg_from_iter(sk, skb, &msg->msg_iter, len);
1363 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1364 struct sock *save_sk = skb->sk;
1366 /* Streams do not free skb on error. Reset to prev state. */
1367 msg->msg_iter = orig_iter;
1369 ___pskb_trim(skb, orig_len);
1374 skb_zcopy_set(skb, uarg, NULL);
1375 return skb->len - orig_len;
1377 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1379 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1382 if (skb_zcopy(orig)) {
1383 if (skb_zcopy(nskb)) {
1384 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1389 if (skb_uarg(nskb) == skb_uarg(orig))
1391 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1394 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1400 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1401 * @skb: the skb to modify
1402 * @gfp_mask: allocation priority
1404 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1405 * It will copy all frags into kernel and drop the reference
1406 * to userspace pages.
1408 * If this function is called from an interrupt gfp_mask() must be
1411 * Returns 0 on success or a negative error code on failure
1412 * to allocate kernel memory to copy to.
1414 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1416 int num_frags = skb_shinfo(skb)->nr_frags;
1417 struct page *page, *head = NULL;
1421 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1427 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1428 for (i = 0; i < new_frags; i++) {
1429 page = alloc_page(gfp_mask);
1432 struct page *next = (struct page *)page_private(head);
1438 set_page_private(page, (unsigned long)head);
1444 for (i = 0; i < num_frags; i++) {
1445 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1446 u32 p_off, p_len, copied;
1450 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1451 p, p_off, p_len, copied) {
1453 vaddr = kmap_atomic(p);
1455 while (done < p_len) {
1456 if (d_off == PAGE_SIZE) {
1458 page = (struct page *)page_private(page);
1460 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1461 memcpy(page_address(page) + d_off,
1462 vaddr + p_off + done, copy);
1466 kunmap_atomic(vaddr);
1470 /* skb frags release userspace buffers */
1471 for (i = 0; i < num_frags; i++)
1472 skb_frag_unref(skb, i);
1474 /* skb frags point to kernel buffers */
1475 for (i = 0; i < new_frags - 1; i++) {
1476 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1477 head = (struct page *)page_private(head);
1479 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1480 skb_shinfo(skb)->nr_frags = new_frags;
1483 skb_zcopy_clear(skb, false);
1486 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1489 * skb_clone - duplicate an sk_buff
1490 * @skb: buffer to clone
1491 * @gfp_mask: allocation priority
1493 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1494 * copies share the same packet data but not structure. The new
1495 * buffer has a reference count of 1. If the allocation fails the
1496 * function returns %NULL otherwise the new buffer is returned.
1498 * If this function is called from an interrupt gfp_mask() must be
1502 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1504 struct sk_buff_fclones *fclones = container_of(skb,
1505 struct sk_buff_fclones,
1509 if (skb_orphan_frags(skb, gfp_mask))
1512 if (skb->fclone == SKB_FCLONE_ORIG &&
1513 refcount_read(&fclones->fclone_ref) == 1) {
1515 refcount_set(&fclones->fclone_ref, 2);
1517 if (skb_pfmemalloc(skb))
1518 gfp_mask |= __GFP_MEMALLOC;
1520 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1524 n->fclone = SKB_FCLONE_UNAVAILABLE;
1527 return __skb_clone(n, skb);
1529 EXPORT_SYMBOL(skb_clone);
1531 void skb_headers_offset_update(struct sk_buff *skb, int off)
1533 /* Only adjust this if it actually is csum_start rather than csum */
1534 if (skb->ip_summed == CHECKSUM_PARTIAL)
1535 skb->csum_start += off;
1536 /* {transport,network,mac}_header and tail are relative to skb->head */
1537 skb->transport_header += off;
1538 skb->network_header += off;
1539 if (skb_mac_header_was_set(skb))
1540 skb->mac_header += off;
1541 skb->inner_transport_header += off;
1542 skb->inner_network_header += off;
1543 skb->inner_mac_header += off;
1545 EXPORT_SYMBOL(skb_headers_offset_update);
1547 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1549 __copy_skb_header(new, old);
1551 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1552 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1553 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1555 EXPORT_SYMBOL(skb_copy_header);
1557 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1559 if (skb_pfmemalloc(skb))
1560 return SKB_ALLOC_RX;
1565 * skb_copy - create private copy of an sk_buff
1566 * @skb: buffer to copy
1567 * @gfp_mask: allocation priority
1569 * Make a copy of both an &sk_buff and its data. This is used when the
1570 * caller wishes to modify the data and needs a private copy of the
1571 * data to alter. Returns %NULL on failure or the pointer to the buffer
1572 * on success. The returned buffer has a reference count of 1.
1574 * As by-product this function converts non-linear &sk_buff to linear
1575 * one, so that &sk_buff becomes completely private and caller is allowed
1576 * to modify all the data of returned buffer. This means that this
1577 * function is not recommended for use in circumstances when only
1578 * header is going to be modified. Use pskb_copy() instead.
1581 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1583 int headerlen = skb_headroom(skb);
1584 unsigned int size = skb_end_offset(skb) + skb->data_len;
1585 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1586 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1591 /* Set the data pointer */
1592 skb_reserve(n, headerlen);
1593 /* Set the tail pointer and length */
1594 skb_put(n, skb->len);
1596 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1598 skb_copy_header(n, skb);
1601 EXPORT_SYMBOL(skb_copy);
1604 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1605 * @skb: buffer to copy
1606 * @headroom: headroom of new skb
1607 * @gfp_mask: allocation priority
1608 * @fclone: if true allocate the copy of the skb from the fclone
1609 * cache instead of the head cache; it is recommended to set this
1610 * to true for the cases where the copy will likely be cloned
1612 * Make a copy of both an &sk_buff and part of its data, located
1613 * in header. Fragmented data remain shared. This is used when
1614 * the caller wishes to modify only header of &sk_buff and needs
1615 * private copy of the header to alter. Returns %NULL on failure
1616 * or the pointer to the buffer on success.
1617 * The returned buffer has a reference count of 1.
1620 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1621 gfp_t gfp_mask, bool fclone)
1623 unsigned int size = skb_headlen(skb) + headroom;
1624 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1625 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1630 /* Set the data pointer */
1631 skb_reserve(n, headroom);
1632 /* Set the tail pointer and length */
1633 skb_put(n, skb_headlen(skb));
1634 /* Copy the bytes */
1635 skb_copy_from_linear_data(skb, n->data, n->len);
1637 n->truesize += skb->data_len;
1638 n->data_len = skb->data_len;
1641 if (skb_shinfo(skb)->nr_frags) {
1644 if (skb_orphan_frags(skb, gfp_mask) ||
1645 skb_zerocopy_clone(n, skb, gfp_mask)) {
1650 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1651 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1652 skb_frag_ref(skb, i);
1654 skb_shinfo(n)->nr_frags = i;
1657 if (skb_has_frag_list(skb)) {
1658 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1659 skb_clone_fraglist(n);
1662 skb_copy_header(n, skb);
1666 EXPORT_SYMBOL(__pskb_copy_fclone);
1669 * pskb_expand_head - reallocate header of &sk_buff
1670 * @skb: buffer to reallocate
1671 * @nhead: room to add at head
1672 * @ntail: room to add at tail
1673 * @gfp_mask: allocation priority
1675 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1676 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1677 * reference count of 1. Returns zero in the case of success or error,
1678 * if expansion failed. In the last case, &sk_buff is not changed.
1680 * All the pointers pointing into skb header may change and must be
1681 * reloaded after call to this function.
1684 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1687 int i, osize = skb_end_offset(skb);
1688 int size = osize + nhead + ntail;
1694 BUG_ON(skb_shared(skb));
1696 size = SKB_DATA_ALIGN(size);
1698 if (skb_pfmemalloc(skb))
1699 gfp_mask |= __GFP_MEMALLOC;
1700 data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1701 gfp_mask, NUMA_NO_NODE, NULL);
1704 size = SKB_WITH_OVERHEAD(ksize(data));
1706 /* Copy only real data... and, alas, header. This should be
1707 * optimized for the cases when header is void.
1709 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1711 memcpy((struct skb_shared_info *)(data + size),
1713 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1716 * if shinfo is shared we must drop the old head gracefully, but if it
1717 * is not we can just drop the old head and let the existing refcount
1718 * be since all we did is relocate the values
1720 if (skb_cloned(skb)) {
1721 if (skb_orphan_frags(skb, gfp_mask))
1724 refcount_inc(&skb_uarg(skb)->refcnt);
1725 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1726 skb_frag_ref(skb, i);
1728 if (skb_has_frag_list(skb))
1729 skb_clone_fraglist(skb);
1731 skb_release_data(skb);
1735 off = (data + nhead) - skb->head;
1740 #ifdef NET_SKBUFF_DATA_USES_OFFSET
1744 skb->end = skb->head + size;
1747 skb_headers_offset_update(skb, nhead);
1751 atomic_set(&skb_shinfo(skb)->dataref, 1);
1753 skb_metadata_clear(skb);
1755 /* It is not generally safe to change skb->truesize.
1756 * For the moment, we really care of rx path, or
1757 * when skb is orphaned (not attached to a socket).
1759 if (!skb->sk || skb->destructor == sock_edemux)
1760 skb->truesize += size - osize;
1769 EXPORT_SYMBOL(pskb_expand_head);
1771 /* Make private copy of skb with writable head and some headroom */
1773 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
1775 struct sk_buff *skb2;
1776 int delta = headroom - skb_headroom(skb);
1779 skb2 = pskb_copy(skb, GFP_ATOMIC);
1781 skb2 = skb_clone(skb, GFP_ATOMIC);
1782 if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
1790 EXPORT_SYMBOL(skb_realloc_headroom);
1793 * skb_expand_head - reallocate header of &sk_buff
1794 * @skb: buffer to reallocate
1795 * @headroom: needed headroom
1797 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1798 * if possible; copies skb->sk to new skb as needed
1799 * and frees original skb in case of failures.
1801 * It expect increased headroom and generates warning otherwise.
1804 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1806 int delta = headroom - skb_headroom(skb);
1807 int osize = skb_end_offset(skb);
1808 struct sock *sk = skb->sk;
1810 if (WARN_ONCE(delta <= 0,
1811 "%s is expecting an increase in the headroom", __func__))
1814 delta = SKB_DATA_ALIGN(delta);
1815 /* pskb_expand_head() might crash, if skb is shared. */
1816 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1817 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1819 if (unlikely(!nskb))
1823 skb_set_owner_w(nskb, sk);
1827 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
1830 if (sk && is_skb_wmem(skb)) {
1831 delta = skb_end_offset(skb) - osize;
1832 refcount_add(delta, &sk->sk_wmem_alloc);
1833 skb->truesize += delta;
1841 EXPORT_SYMBOL(skb_expand_head);
1844 * skb_copy_expand - copy and expand sk_buff
1845 * @skb: buffer to copy
1846 * @newheadroom: new free bytes at head
1847 * @newtailroom: new free bytes at tail
1848 * @gfp_mask: allocation priority
1850 * Make a copy of both an &sk_buff and its data and while doing so
1851 * allocate additional space.
1853 * This is used when the caller wishes to modify the data and needs a
1854 * private copy of the data to alter as well as more space for new fields.
1855 * Returns %NULL on failure or the pointer to the buffer
1856 * on success. The returned buffer has a reference count of 1.
1858 * You must pass %GFP_ATOMIC as the allocation priority if this function
1859 * is called from an interrupt.
1861 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1862 int newheadroom, int newtailroom,
1866 * Allocate the copy buffer
1868 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1869 gfp_mask, skb_alloc_rx_flag(skb),
1871 int oldheadroom = skb_headroom(skb);
1872 int head_copy_len, head_copy_off;
1877 skb_reserve(n, newheadroom);
1879 /* Set the tail pointer and length */
1880 skb_put(n, skb->len);
1882 head_copy_len = oldheadroom;
1884 if (newheadroom <= head_copy_len)
1885 head_copy_len = newheadroom;
1887 head_copy_off = newheadroom - head_copy_len;
1889 /* Copy the linear header and data. */
1890 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1891 skb->len + head_copy_len));
1893 skb_copy_header(n, skb);
1895 skb_headers_offset_update(n, newheadroom - oldheadroom);
1899 EXPORT_SYMBOL(skb_copy_expand);
1902 * __skb_pad - zero pad the tail of an skb
1903 * @skb: buffer to pad
1904 * @pad: space to pad
1905 * @free_on_error: free buffer on error
1907 * Ensure that a buffer is followed by a padding area that is zero
1908 * filled. Used by network drivers which may DMA or transfer data
1909 * beyond the buffer end onto the wire.
1911 * May return error in out of memory cases. The skb is freed on error
1912 * if @free_on_error is true.
1915 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
1920 /* If the skbuff is non linear tailroom is always zero.. */
1921 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1922 memset(skb->data+skb->len, 0, pad);
1926 ntail = skb->data_len + pad - (skb->end - skb->tail);
1927 if (likely(skb_cloned(skb) || ntail > 0)) {
1928 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1933 /* FIXME: The use of this function with non-linear skb's really needs
1936 err = skb_linearize(skb);
1940 memset(skb->data + skb->len, 0, pad);
1948 EXPORT_SYMBOL(__skb_pad);
1951 * pskb_put - add data to the tail of a potentially fragmented buffer
1952 * @skb: start of the buffer to use
1953 * @tail: tail fragment of the buffer to use
1954 * @len: amount of data to add
1956 * This function extends the used data area of the potentially
1957 * fragmented buffer. @tail must be the last fragment of @skb -- or
1958 * @skb itself. If this would exceed the total buffer size the kernel
1959 * will panic. A pointer to the first byte of the extra data is
1963 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
1966 skb->data_len += len;
1969 return skb_put(tail, len);
1971 EXPORT_SYMBOL_GPL(pskb_put);
1974 * skb_put - add data to a buffer
1975 * @skb: buffer to use
1976 * @len: amount of data to add
1978 * This function extends the used data area of the buffer. If this would
1979 * exceed the total buffer size the kernel will panic. A pointer to the
1980 * first byte of the extra data is returned.
1982 void *skb_put(struct sk_buff *skb, unsigned int len)
1984 void *tmp = skb_tail_pointer(skb);
1985 SKB_LINEAR_ASSERT(skb);
1988 if (unlikely(skb->tail > skb->end))
1989 skb_over_panic(skb, len, __builtin_return_address(0));
1992 EXPORT_SYMBOL(skb_put);
1995 * skb_push - add data to the start of a buffer
1996 * @skb: buffer to use
1997 * @len: amount of data to add
1999 * This function extends the used data area of the buffer at the buffer
2000 * start. If this would exceed the total buffer headroom the kernel will
2001 * panic. A pointer to the first byte of the extra data is returned.
2003 void *skb_push(struct sk_buff *skb, unsigned int len)
2007 if (unlikely(skb->data < skb->head))
2008 skb_under_panic(skb, len, __builtin_return_address(0));
2011 EXPORT_SYMBOL(skb_push);
2014 * skb_pull - remove data from the start of a buffer
2015 * @skb: buffer to use
2016 * @len: amount of data to remove
2018 * This function removes data from the start of a buffer, returning
2019 * the memory to the headroom. A pointer to the next data in the buffer
2020 * is returned. Once the data has been pulled future pushes will overwrite
2023 void *skb_pull(struct sk_buff *skb, unsigned int len)
2025 return skb_pull_inline(skb, len);
2027 EXPORT_SYMBOL(skb_pull);
2030 * skb_trim - remove end from a buffer
2031 * @skb: buffer to alter
2034 * Cut the length of a buffer down by removing data from the tail. If
2035 * the buffer is already under the length specified it is not modified.
2036 * The skb must be linear.
2038 void skb_trim(struct sk_buff *skb, unsigned int len)
2041 __skb_trim(skb, len);
2043 EXPORT_SYMBOL(skb_trim);
2045 /* Trims skb to length len. It can change skb pointers.
2048 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2050 struct sk_buff **fragp;
2051 struct sk_buff *frag;
2052 int offset = skb_headlen(skb);
2053 int nfrags = skb_shinfo(skb)->nr_frags;
2057 if (skb_cloned(skb) &&
2058 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2065 for (; i < nfrags; i++) {
2066 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2073 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2076 skb_shinfo(skb)->nr_frags = i;
2078 for (; i < nfrags; i++)
2079 skb_frag_unref(skb, i);
2081 if (skb_has_frag_list(skb))
2082 skb_drop_fraglist(skb);
2086 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2087 fragp = &frag->next) {
2088 int end = offset + frag->len;
2090 if (skb_shared(frag)) {
2091 struct sk_buff *nfrag;
2093 nfrag = skb_clone(frag, GFP_ATOMIC);
2094 if (unlikely(!nfrag))
2097 nfrag->next = frag->next;
2109 unlikely((err = pskb_trim(frag, len - offset))))
2113 skb_drop_list(&frag->next);
2118 if (len > skb_headlen(skb)) {
2119 skb->data_len -= skb->len - len;
2124 skb_set_tail_pointer(skb, len);
2127 if (!skb->sk || skb->destructor == sock_edemux)
2131 EXPORT_SYMBOL(___pskb_trim);
2133 /* Note : use pskb_trim_rcsum() instead of calling this directly
2135 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2137 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2138 int delta = skb->len - len;
2140 skb->csum = csum_block_sub(skb->csum,
2141 skb_checksum(skb, len, delta, 0),
2143 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2144 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2145 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2147 if (offset + sizeof(__sum16) > hdlen)
2150 return __pskb_trim(skb, len);
2152 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2155 * __pskb_pull_tail - advance tail of skb header
2156 * @skb: buffer to reallocate
2157 * @delta: number of bytes to advance tail
2159 * The function makes a sense only on a fragmented &sk_buff,
2160 * it expands header moving its tail forward and copying necessary
2161 * data from fragmented part.
2163 * &sk_buff MUST have reference count of 1.
2165 * Returns %NULL (and &sk_buff does not change) if pull failed
2166 * or value of new tail of skb in the case of success.
2168 * All the pointers pointing into skb header may change and must be
2169 * reloaded after call to this function.
2172 /* Moves tail of skb head forward, copying data from fragmented part,
2173 * when it is necessary.
2174 * 1. It may fail due to malloc failure.
2175 * 2. It may change skb pointers.
2177 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2179 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2181 /* If skb has not enough free space at tail, get new one
2182 * plus 128 bytes for future expansions. If we have enough
2183 * room at tail, reallocate without expansion only if skb is cloned.
2185 int i, k, eat = (skb->tail + delta) - skb->end;
2187 if (eat > 0 || skb_cloned(skb)) {
2188 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2193 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2194 skb_tail_pointer(skb), delta));
2196 /* Optimization: no fragments, no reasons to preestimate
2197 * size of pulled pages. Superb.
2199 if (!skb_has_frag_list(skb))
2202 /* Estimate size of pulled pages. */
2204 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2205 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2212 /* If we need update frag list, we are in troubles.
2213 * Certainly, it is possible to add an offset to skb data,
2214 * but taking into account that pulling is expected to
2215 * be very rare operation, it is worth to fight against
2216 * further bloating skb head and crucify ourselves here instead.
2217 * Pure masohism, indeed. 8)8)
2220 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2221 struct sk_buff *clone = NULL;
2222 struct sk_buff *insp = NULL;
2225 if (list->len <= eat) {
2226 /* Eaten as whole. */
2231 /* Eaten partially. */
2233 if (skb_shared(list)) {
2234 /* Sucks! We need to fork list. :-( */
2235 clone = skb_clone(list, GFP_ATOMIC);
2241 /* This may be pulled without
2245 if (!pskb_pull(list, eat)) {
2253 /* Free pulled out fragments. */
2254 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2255 skb_shinfo(skb)->frag_list = list->next;
2258 /* And insert new clone at head. */
2261 skb_shinfo(skb)->frag_list = clone;
2264 /* Success! Now we may commit changes to skb data. */
2269 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2270 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2273 skb_frag_unref(skb, i);
2276 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2278 *frag = skb_shinfo(skb)->frags[i];
2280 skb_frag_off_add(frag, eat);
2281 skb_frag_size_sub(frag, eat);
2289 skb_shinfo(skb)->nr_frags = k;
2293 skb->data_len -= delta;
2296 skb_zcopy_clear(skb, false);
2298 return skb_tail_pointer(skb);
2300 EXPORT_SYMBOL(__pskb_pull_tail);
2303 * skb_copy_bits - copy bits from skb to kernel buffer
2305 * @offset: offset in source
2306 * @to: destination buffer
2307 * @len: number of bytes to copy
2309 * Copy the specified number of bytes from the source skb to the
2310 * destination buffer.
2313 * If its prototype is ever changed,
2314 * check arch/{*}/net/{*}.S files,
2315 * since it is called from BPF assembly code.
2317 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2319 int start = skb_headlen(skb);
2320 struct sk_buff *frag_iter;
2323 if (offset > (int)skb->len - len)
2327 if ((copy = start - offset) > 0) {
2330 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2331 if ((len -= copy) == 0)
2337 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2339 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2341 WARN_ON(start > offset + len);
2343 end = start + skb_frag_size(f);
2344 if ((copy = end - offset) > 0) {
2345 u32 p_off, p_len, copied;
2352 skb_frag_foreach_page(f,
2353 skb_frag_off(f) + offset - start,
2354 copy, p, p_off, p_len, copied) {
2355 vaddr = kmap_atomic(p);
2356 memcpy(to + copied, vaddr + p_off, p_len);
2357 kunmap_atomic(vaddr);
2360 if ((len -= copy) == 0)
2368 skb_walk_frags(skb, frag_iter) {
2371 WARN_ON(start > offset + len);
2373 end = start + frag_iter->len;
2374 if ((copy = end - offset) > 0) {
2377 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2379 if ((len -= copy) == 0)
2393 EXPORT_SYMBOL(skb_copy_bits);
2396 * Callback from splice_to_pipe(), if we need to release some pages
2397 * at the end of the spd in case we error'ed out in filling the pipe.
2399 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2401 put_page(spd->pages[i]);
2404 static struct page *linear_to_page(struct page *page, unsigned int *len,
2405 unsigned int *offset,
2408 struct page_frag *pfrag = sk_page_frag(sk);
2410 if (!sk_page_frag_refill(sk, pfrag))
2413 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2415 memcpy(page_address(pfrag->page) + pfrag->offset,
2416 page_address(page) + *offset, *len);
2417 *offset = pfrag->offset;
2418 pfrag->offset += *len;
2423 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2425 unsigned int offset)
2427 return spd->nr_pages &&
2428 spd->pages[spd->nr_pages - 1] == page &&
2429 (spd->partial[spd->nr_pages - 1].offset +
2430 spd->partial[spd->nr_pages - 1].len == offset);
2434 * Fill page/offset/length into spd, if it can hold more pages.
2436 static bool spd_fill_page(struct splice_pipe_desc *spd,
2437 struct pipe_inode_info *pipe, struct page *page,
2438 unsigned int *len, unsigned int offset,
2442 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2446 page = linear_to_page(page, len, &offset, sk);
2450 if (spd_can_coalesce(spd, page, offset)) {
2451 spd->partial[spd->nr_pages - 1].len += *len;
2455 spd->pages[spd->nr_pages] = page;
2456 spd->partial[spd->nr_pages].len = *len;
2457 spd->partial[spd->nr_pages].offset = offset;
2463 static bool __splice_segment(struct page *page, unsigned int poff,
2464 unsigned int plen, unsigned int *off,
2466 struct splice_pipe_desc *spd, bool linear,
2468 struct pipe_inode_info *pipe)
2473 /* skip this segment if already processed */
2479 /* ignore any bits we already processed */
2485 unsigned int flen = min(*len, plen);
2487 if (spd_fill_page(spd, pipe, page, &flen, poff,
2493 } while (*len && plen);
2499 * Map linear and fragment data from the skb to spd. It reports true if the
2500 * pipe is full or if we already spliced the requested length.
2502 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2503 unsigned int *offset, unsigned int *len,
2504 struct splice_pipe_desc *spd, struct sock *sk)
2507 struct sk_buff *iter;
2509 /* map the linear part :
2510 * If skb->head_frag is set, this 'linear' part is backed by a
2511 * fragment, and if the head is not shared with any clones then
2512 * we can avoid a copy since we own the head portion of this page.
2514 if (__splice_segment(virt_to_page(skb->data),
2515 (unsigned long) skb->data & (PAGE_SIZE - 1),
2518 skb_head_is_locked(skb),
2523 * then map the fragments
2525 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2526 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2528 if (__splice_segment(skb_frag_page(f),
2529 skb_frag_off(f), skb_frag_size(f),
2530 offset, len, spd, false, sk, pipe))
2534 skb_walk_frags(skb, iter) {
2535 if (*offset >= iter->len) {
2536 *offset -= iter->len;
2539 /* __skb_splice_bits() only fails if the output has no room
2540 * left, so no point in going over the frag_list for the error
2543 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2551 * Map data from the skb to a pipe. Should handle both the linear part,
2552 * the fragments, and the frag list.
2554 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2555 struct pipe_inode_info *pipe, unsigned int tlen,
2558 struct partial_page partial[MAX_SKB_FRAGS];
2559 struct page *pages[MAX_SKB_FRAGS];
2560 struct splice_pipe_desc spd = {
2563 .nr_pages_max = MAX_SKB_FRAGS,
2564 .ops = &nosteal_pipe_buf_ops,
2565 .spd_release = sock_spd_release,
2569 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2572 ret = splice_to_pipe(pipe, &spd);
2576 EXPORT_SYMBOL_GPL(skb_splice_bits);
2578 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2579 struct kvec *vec, size_t num, size_t size)
2581 struct socket *sock = sk->sk_socket;
2585 return kernel_sendmsg(sock, msg, vec, num, size);
2588 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2589 size_t size, int flags)
2591 struct socket *sock = sk->sk_socket;
2595 return kernel_sendpage(sock, page, offset, size, flags);
2598 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2599 struct kvec *vec, size_t num, size_t size);
2600 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2601 size_t size, int flags);
2602 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2603 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2605 unsigned int orig_len = len;
2606 struct sk_buff *head = skb;
2607 unsigned short fragidx;
2612 /* Deal with head data */
2613 while (offset < skb_headlen(skb) && len) {
2617 slen = min_t(int, len, skb_headlen(skb) - offset);
2618 kv.iov_base = skb->data + offset;
2620 memset(&msg, 0, sizeof(msg));
2621 msg.msg_flags = MSG_DONTWAIT;
2623 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2624 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2632 /* All the data was skb head? */
2636 /* Make offset relative to start of frags */
2637 offset -= skb_headlen(skb);
2639 /* Find where we are in frag list */
2640 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2641 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2643 if (offset < skb_frag_size(frag))
2646 offset -= skb_frag_size(frag);
2649 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2650 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2652 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2655 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2656 sendpage_unlocked, sk,
2657 skb_frag_page(frag),
2658 skb_frag_off(frag) + offset,
2659 slen, MSG_DONTWAIT);
2672 /* Process any frag lists */
2675 if (skb_has_frag_list(skb)) {
2676 skb = skb_shinfo(skb)->frag_list;
2679 } else if (skb->next) {
2686 return orig_len - len;
2689 return orig_len == len ? ret : orig_len - len;
2692 /* Send skb data on a socket. Socket must be locked. */
2693 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2696 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2697 kernel_sendpage_locked);
2699 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2701 /* Send skb data on a socket. Socket must be unlocked. */
2702 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2704 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2709 * skb_store_bits - store bits from kernel buffer to skb
2710 * @skb: destination buffer
2711 * @offset: offset in destination
2712 * @from: source buffer
2713 * @len: number of bytes to copy
2715 * Copy the specified number of bytes from the source buffer to the
2716 * destination skb. This function handles all the messy bits of
2717 * traversing fragment lists and such.
2720 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2722 int start = skb_headlen(skb);
2723 struct sk_buff *frag_iter;
2726 if (offset > (int)skb->len - len)
2729 if ((copy = start - offset) > 0) {
2732 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2733 if ((len -= copy) == 0)
2739 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2740 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2743 WARN_ON(start > offset + len);
2745 end = start + skb_frag_size(frag);
2746 if ((copy = end - offset) > 0) {
2747 u32 p_off, p_len, copied;
2754 skb_frag_foreach_page(frag,
2755 skb_frag_off(frag) + offset - start,
2756 copy, p, p_off, p_len, copied) {
2757 vaddr = kmap_atomic(p);
2758 memcpy(vaddr + p_off, from + copied, p_len);
2759 kunmap_atomic(vaddr);
2762 if ((len -= copy) == 0)
2770 skb_walk_frags(skb, frag_iter) {
2773 WARN_ON(start > offset + len);
2775 end = start + frag_iter->len;
2776 if ((copy = end - offset) > 0) {
2779 if (skb_store_bits(frag_iter, offset - start,
2782 if ((len -= copy) == 0)
2795 EXPORT_SYMBOL(skb_store_bits);
2797 /* Checksum skb data. */
2798 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2799 __wsum csum, const struct skb_checksum_ops *ops)
2801 int start = skb_headlen(skb);
2802 int i, copy = start - offset;
2803 struct sk_buff *frag_iter;
2806 /* Checksum header. */
2810 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
2811 skb->data + offset, copy, csum);
2812 if ((len -= copy) == 0)
2818 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2820 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2822 WARN_ON(start > offset + len);
2824 end = start + skb_frag_size(frag);
2825 if ((copy = end - offset) > 0) {
2826 u32 p_off, p_len, copied;
2834 skb_frag_foreach_page(frag,
2835 skb_frag_off(frag) + offset - start,
2836 copy, p, p_off, p_len, copied) {
2837 vaddr = kmap_atomic(p);
2838 csum2 = INDIRECT_CALL_1(ops->update,
2840 vaddr + p_off, p_len, 0);
2841 kunmap_atomic(vaddr);
2842 csum = INDIRECT_CALL_1(ops->combine,
2843 csum_block_add_ext, csum,
2855 skb_walk_frags(skb, frag_iter) {
2858 WARN_ON(start > offset + len);
2860 end = start + frag_iter->len;
2861 if ((copy = end - offset) > 0) {
2865 csum2 = __skb_checksum(frag_iter, offset - start,
2867 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
2868 csum, csum2, pos, copy);
2869 if ((len -= copy) == 0)
2880 EXPORT_SYMBOL(__skb_checksum);
2882 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2883 int len, __wsum csum)
2885 const struct skb_checksum_ops ops = {
2886 .update = csum_partial_ext,
2887 .combine = csum_block_add_ext,
2890 return __skb_checksum(skb, offset, len, csum, &ops);
2892 EXPORT_SYMBOL(skb_checksum);
2894 /* Both of above in one bottle. */
2896 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2899 int start = skb_headlen(skb);
2900 int i, copy = start - offset;
2901 struct sk_buff *frag_iter;
2909 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2911 if ((len -= copy) == 0)
2918 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2921 WARN_ON(start > offset + len);
2923 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2924 if ((copy = end - offset) > 0) {
2925 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2926 u32 p_off, p_len, copied;
2934 skb_frag_foreach_page(frag,
2935 skb_frag_off(frag) + offset - start,
2936 copy, p, p_off, p_len, copied) {
2937 vaddr = kmap_atomic(p);
2938 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
2941 kunmap_atomic(vaddr);
2942 csum = csum_block_add(csum, csum2, pos);
2954 skb_walk_frags(skb, frag_iter) {
2958 WARN_ON(start > offset + len);
2960 end = start + frag_iter->len;
2961 if ((copy = end - offset) > 0) {
2964 csum2 = skb_copy_and_csum_bits(frag_iter,
2967 csum = csum_block_add(csum, csum2, pos);
2968 if ((len -= copy) == 0)
2979 EXPORT_SYMBOL(skb_copy_and_csum_bits);
2981 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
2985 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
2986 /* See comments in __skb_checksum_complete(). */
2988 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
2989 !skb->csum_complete_sw)
2990 netdev_rx_csum_fault(skb->dev, skb);
2992 if (!skb_shared(skb))
2993 skb->csum_valid = !sum;
2996 EXPORT_SYMBOL(__skb_checksum_complete_head);
2998 /* This function assumes skb->csum already holds pseudo header's checksum,
2999 * which has been changed from the hardware checksum, for example, by
3000 * __skb_checksum_validate_complete(). And, the original skb->csum must
3001 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3003 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3004 * zero. The new checksum is stored back into skb->csum unless the skb is
3007 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3012 csum = skb_checksum(skb, 0, skb->len, 0);
3014 sum = csum_fold(csum_add(skb->csum, csum));
3015 /* This check is inverted, because we already knew the hardware
3016 * checksum is invalid before calling this function. So, if the
3017 * re-computed checksum is valid instead, then we have a mismatch
3018 * between the original skb->csum and skb_checksum(). This means either
3019 * the original hardware checksum is incorrect or we screw up skb->csum
3020 * when moving skb->data around.
3023 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3024 !skb->csum_complete_sw)
3025 netdev_rx_csum_fault(skb->dev, skb);
3028 if (!skb_shared(skb)) {
3029 /* Save full packet checksum */
3031 skb->ip_summed = CHECKSUM_COMPLETE;
3032 skb->csum_complete_sw = 1;
3033 skb->csum_valid = !sum;
3038 EXPORT_SYMBOL(__skb_checksum_complete);
3040 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3042 net_warn_ratelimited(
3043 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3048 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3049 int offset, int len)
3051 net_warn_ratelimited(
3052 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3057 static const struct skb_checksum_ops default_crc32c_ops = {
3058 .update = warn_crc32c_csum_update,
3059 .combine = warn_crc32c_csum_combine,
3062 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3063 &default_crc32c_ops;
3064 EXPORT_SYMBOL(crc32c_csum_stub);
3067 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3068 * @from: source buffer
3070 * Calculates the amount of linear headroom needed in the 'to' skb passed
3071 * into skb_zerocopy().
3074 skb_zerocopy_headlen(const struct sk_buff *from)
3076 unsigned int hlen = 0;
3078 if (!from->head_frag ||
3079 skb_headlen(from) < L1_CACHE_BYTES ||
3080 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3081 hlen = skb_headlen(from);
3086 if (skb_has_frag_list(from))
3091 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3094 * skb_zerocopy - Zero copy skb to skb
3095 * @to: destination buffer
3096 * @from: source buffer
3097 * @len: number of bytes to copy from source buffer
3098 * @hlen: size of linear headroom in destination buffer
3100 * Copies up to `len` bytes from `from` to `to` by creating references
3101 * to the frags in the source buffer.
3103 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3104 * headroom in the `to` buffer.
3107 * 0: everything is OK
3108 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3109 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3112 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3115 int plen = 0; /* length of skb->head fragment */
3118 unsigned int offset;
3120 BUG_ON(!from->head_frag && !hlen);
3122 /* dont bother with small payloads */
3123 if (len <= skb_tailroom(to))
3124 return skb_copy_bits(from, 0, skb_put(to, len), len);
3127 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3132 plen = min_t(int, skb_headlen(from), len);
3134 page = virt_to_head_page(from->head);
3135 offset = from->data - (unsigned char *)page_address(page);
3136 __skb_fill_page_desc(to, 0, page, offset, plen);
3143 to->truesize += len + plen;
3144 to->len += len + plen;
3145 to->data_len += len + plen;
3147 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3151 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3153 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3158 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3159 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3161 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3163 skb_frag_ref(to, j);
3166 skb_shinfo(to)->nr_frags = j;
3170 EXPORT_SYMBOL_GPL(skb_zerocopy);
3172 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3177 if (skb->ip_summed == CHECKSUM_PARTIAL)
3178 csstart = skb_checksum_start_offset(skb);
3180 csstart = skb_headlen(skb);
3182 BUG_ON(csstart > skb_headlen(skb));
3184 skb_copy_from_linear_data(skb, to, csstart);
3187 if (csstart != skb->len)
3188 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3189 skb->len - csstart);
3191 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3192 long csstuff = csstart + skb->csum_offset;
3194 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3197 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3200 * skb_dequeue - remove from the head of the queue
3201 * @list: list to dequeue from
3203 * Remove the head of the list. The list lock is taken so the function
3204 * may be used safely with other locking list functions. The head item is
3205 * returned or %NULL if the list is empty.
3208 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3210 unsigned long flags;
3211 struct sk_buff *result;
3213 spin_lock_irqsave(&list->lock, flags);
3214 result = __skb_dequeue(list);
3215 spin_unlock_irqrestore(&list->lock, flags);
3218 EXPORT_SYMBOL(skb_dequeue);
3221 * skb_dequeue_tail - remove from the tail of the queue
3222 * @list: list to dequeue from
3224 * Remove the tail of the list. The list lock is taken so the function
3225 * may be used safely with other locking list functions. The tail item is
3226 * returned or %NULL if the list is empty.
3228 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3230 unsigned long flags;
3231 struct sk_buff *result;
3233 spin_lock_irqsave(&list->lock, flags);
3234 result = __skb_dequeue_tail(list);
3235 spin_unlock_irqrestore(&list->lock, flags);
3238 EXPORT_SYMBOL(skb_dequeue_tail);
3241 * skb_queue_purge - empty a list
3242 * @list: list to empty
3244 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3245 * the list and one reference dropped. This function takes the list
3246 * lock and is atomic with respect to other list locking functions.
3248 void skb_queue_purge(struct sk_buff_head *list)
3250 struct sk_buff *skb;
3251 while ((skb = skb_dequeue(list)) != NULL)
3254 EXPORT_SYMBOL(skb_queue_purge);
3257 * skb_rbtree_purge - empty a skb rbtree
3258 * @root: root of the rbtree to empty
3259 * Return value: the sum of truesizes of all purged skbs.
3261 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3262 * the list and one reference dropped. This function does not take
3263 * any lock. Synchronization should be handled by the caller (e.g., TCP
3264 * out-of-order queue is protected by the socket lock).
3266 unsigned int skb_rbtree_purge(struct rb_root *root)
3268 struct rb_node *p = rb_first(root);
3269 unsigned int sum = 0;
3272 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3275 rb_erase(&skb->rbnode, root);
3276 sum += skb->truesize;
3283 * skb_queue_head - queue a buffer at the list head
3284 * @list: list to use
3285 * @newsk: buffer to queue
3287 * Queue a buffer at the start of the list. This function takes the
3288 * list lock and can be used safely with other locking &sk_buff functions
3291 * A buffer cannot be placed on two lists at the same time.
3293 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3295 unsigned long flags;
3297 spin_lock_irqsave(&list->lock, flags);
3298 __skb_queue_head(list, newsk);
3299 spin_unlock_irqrestore(&list->lock, flags);
3301 EXPORT_SYMBOL(skb_queue_head);
3304 * skb_queue_tail - queue a buffer at the list tail
3305 * @list: list to use
3306 * @newsk: buffer to queue
3308 * Queue a buffer at the tail of the list. This function takes the
3309 * list lock and can be used safely with other locking &sk_buff functions
3312 * A buffer cannot be placed on two lists at the same time.
3314 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3316 unsigned long flags;
3318 spin_lock_irqsave(&list->lock, flags);
3319 __skb_queue_tail(list, newsk);
3320 spin_unlock_irqrestore(&list->lock, flags);
3322 EXPORT_SYMBOL(skb_queue_tail);
3325 * skb_unlink - remove a buffer from a list
3326 * @skb: buffer to remove
3327 * @list: list to use
3329 * Remove a packet from a list. The list locks are taken and this
3330 * function is atomic with respect to other list locked calls
3332 * You must know what list the SKB is on.
3334 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3336 unsigned long flags;
3338 spin_lock_irqsave(&list->lock, flags);
3339 __skb_unlink(skb, list);
3340 spin_unlock_irqrestore(&list->lock, flags);
3342 EXPORT_SYMBOL(skb_unlink);
3345 * skb_append - append a buffer
3346 * @old: buffer to insert after
3347 * @newsk: buffer to insert
3348 * @list: list to use
3350 * Place a packet after a given packet in a list. The list locks are taken
3351 * and this function is atomic with respect to other list locked calls.
3352 * A buffer cannot be placed on two lists at the same time.
3354 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3356 unsigned long flags;
3358 spin_lock_irqsave(&list->lock, flags);
3359 __skb_queue_after(list, old, newsk);
3360 spin_unlock_irqrestore(&list->lock, flags);
3362 EXPORT_SYMBOL(skb_append);
3364 static inline void skb_split_inside_header(struct sk_buff *skb,
3365 struct sk_buff* skb1,
3366 const u32 len, const int pos)
3370 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3372 /* And move data appendix as is. */
3373 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3374 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3376 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3377 skb_shinfo(skb)->nr_frags = 0;
3378 skb1->data_len = skb->data_len;
3379 skb1->len += skb1->data_len;
3382 skb_set_tail_pointer(skb, len);
3385 static inline void skb_split_no_header(struct sk_buff *skb,
3386 struct sk_buff* skb1,
3387 const u32 len, int pos)
3390 const int nfrags = skb_shinfo(skb)->nr_frags;
3392 skb_shinfo(skb)->nr_frags = 0;
3393 skb1->len = skb1->data_len = skb->len - len;
3395 skb->data_len = len - pos;
3397 for (i = 0; i < nfrags; i++) {
3398 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3400 if (pos + size > len) {
3401 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3405 * We have two variants in this case:
3406 * 1. Move all the frag to the second
3407 * part, if it is possible. F.e.
3408 * this approach is mandatory for TUX,
3409 * where splitting is expensive.
3410 * 2. Split is accurately. We make this.
3412 skb_frag_ref(skb, i);
3413 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3414 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3415 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3416 skb_shinfo(skb)->nr_frags++;
3420 skb_shinfo(skb)->nr_frags++;
3423 skb_shinfo(skb1)->nr_frags = k;
3427 * skb_split - Split fragmented skb to two parts at length len.
3428 * @skb: the buffer to split
3429 * @skb1: the buffer to receive the second part
3430 * @len: new length for skb
3432 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3434 int pos = skb_headlen(skb);
3436 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & SKBFL_SHARED_FRAG;
3437 skb_zerocopy_clone(skb1, skb, 0);
3438 if (len < pos) /* Split line is inside header. */
3439 skb_split_inside_header(skb, skb1, len, pos);
3440 else /* Second chunk has no header, nothing to copy. */
3441 skb_split_no_header(skb, skb1, len, pos);
3443 EXPORT_SYMBOL(skb_split);
3445 /* Shifting from/to a cloned skb is a no-go.
3447 * Caller cannot keep skb_shinfo related pointers past calling here!
3449 static int skb_prepare_for_shift(struct sk_buff *skb)
3453 if (skb_cloned(skb)) {
3454 /* Save and restore truesize: pskb_expand_head() may reallocate
3455 * memory where ksize(kmalloc(S)) != ksize(kmalloc(S)), but we
3456 * cannot change truesize at this point.
3458 unsigned int save_truesize = skb->truesize;
3460 ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
3461 skb->truesize = save_truesize;
3467 * skb_shift - Shifts paged data partially from skb to another
3468 * @tgt: buffer into which tail data gets added
3469 * @skb: buffer from which the paged data comes from
3470 * @shiftlen: shift up to this many bytes
3472 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3473 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3474 * It's up to caller to free skb if everything was shifted.
3476 * If @tgt runs out of frags, the whole operation is aborted.
3478 * Skb cannot include anything else but paged data while tgt is allowed
3479 * to have non-paged data as well.
3481 * TODO: full sized shift could be optimized but that would need
3482 * specialized skb free'er to handle frags without up-to-date nr_frags.
3484 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3486 int from, to, merge, todo;
3487 skb_frag_t *fragfrom, *fragto;
3489 BUG_ON(shiftlen > skb->len);
3491 if (skb_headlen(skb))
3493 if (skb_zcopy(tgt) || skb_zcopy(skb))
3498 to = skb_shinfo(tgt)->nr_frags;
3499 fragfrom = &skb_shinfo(skb)->frags[from];
3501 /* Actual merge is delayed until the point when we know we can
3502 * commit all, so that we don't have to undo partial changes
3505 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3506 skb_frag_off(fragfrom))) {
3511 todo -= skb_frag_size(fragfrom);
3513 if (skb_prepare_for_shift(skb) ||
3514 skb_prepare_for_shift(tgt))
3517 /* All previous frag pointers might be stale! */
3518 fragfrom = &skb_shinfo(skb)->frags[from];
3519 fragto = &skb_shinfo(tgt)->frags[merge];
3521 skb_frag_size_add(fragto, shiftlen);
3522 skb_frag_size_sub(fragfrom, shiftlen);
3523 skb_frag_off_add(fragfrom, shiftlen);
3531 /* Skip full, not-fitting skb to avoid expensive operations */
3532 if ((shiftlen == skb->len) &&
3533 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3536 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3539 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3540 if (to == MAX_SKB_FRAGS)
3543 fragfrom = &skb_shinfo(skb)->frags[from];
3544 fragto = &skb_shinfo(tgt)->frags[to];
3546 if (todo >= skb_frag_size(fragfrom)) {
3547 *fragto = *fragfrom;
3548 todo -= skb_frag_size(fragfrom);
3553 __skb_frag_ref(fragfrom);
3554 skb_frag_page_copy(fragto, fragfrom);
3555 skb_frag_off_copy(fragto, fragfrom);
3556 skb_frag_size_set(fragto, todo);
3558 skb_frag_off_add(fragfrom, todo);
3559 skb_frag_size_sub(fragfrom, todo);
3567 /* Ready to "commit" this state change to tgt */
3568 skb_shinfo(tgt)->nr_frags = to;
3571 fragfrom = &skb_shinfo(skb)->frags[0];
3572 fragto = &skb_shinfo(tgt)->frags[merge];
3574 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3575 __skb_frag_unref(fragfrom, skb->pp_recycle);
3578 /* Reposition in the original skb */
3580 while (from < skb_shinfo(skb)->nr_frags)
3581 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3582 skb_shinfo(skb)->nr_frags = to;
3584 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3587 /* Most likely the tgt won't ever need its checksum anymore, skb on
3588 * the other hand might need it if it needs to be resent
3590 tgt->ip_summed = CHECKSUM_PARTIAL;
3591 skb->ip_summed = CHECKSUM_PARTIAL;
3593 /* Yak, is it really working this way? Some helper please? */
3594 skb->len -= shiftlen;
3595 skb->data_len -= shiftlen;
3596 skb->truesize -= shiftlen;
3597 tgt->len += shiftlen;
3598 tgt->data_len += shiftlen;
3599 tgt->truesize += shiftlen;
3605 * skb_prepare_seq_read - Prepare a sequential read of skb data
3606 * @skb: the buffer to read
3607 * @from: lower offset of data to be read
3608 * @to: upper offset of data to be read
3609 * @st: state variable
3611 * Initializes the specified state variable. Must be called before
3612 * invoking skb_seq_read() for the first time.
3614 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3615 unsigned int to, struct skb_seq_state *st)
3617 st->lower_offset = from;
3618 st->upper_offset = to;
3619 st->root_skb = st->cur_skb = skb;
3620 st->frag_idx = st->stepped_offset = 0;
3621 st->frag_data = NULL;
3624 EXPORT_SYMBOL(skb_prepare_seq_read);
3627 * skb_seq_read - Sequentially read skb data
3628 * @consumed: number of bytes consumed by the caller so far
3629 * @data: destination pointer for data to be returned
3630 * @st: state variable
3632 * Reads a block of skb data at @consumed relative to the
3633 * lower offset specified to skb_prepare_seq_read(). Assigns
3634 * the head of the data block to @data and returns the length
3635 * of the block or 0 if the end of the skb data or the upper
3636 * offset has been reached.
3638 * The caller is not required to consume all of the data
3639 * returned, i.e. @consumed is typically set to the number
3640 * of bytes already consumed and the next call to
3641 * skb_seq_read() will return the remaining part of the block.
3643 * Note 1: The size of each block of data returned can be arbitrary,
3644 * this limitation is the cost for zerocopy sequential
3645 * reads of potentially non linear data.
3647 * Note 2: Fragment lists within fragments are not implemented
3648 * at the moment, state->root_skb could be replaced with
3649 * a stack for this purpose.
3651 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3652 struct skb_seq_state *st)
3654 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3657 if (unlikely(abs_offset >= st->upper_offset)) {
3658 if (st->frag_data) {
3659 kunmap_atomic(st->frag_data);
3660 st->frag_data = NULL;
3666 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3668 if (abs_offset < block_limit && !st->frag_data) {
3669 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3670 return block_limit - abs_offset;
3673 if (st->frag_idx == 0 && !st->frag_data)
3674 st->stepped_offset += skb_headlen(st->cur_skb);
3676 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3677 unsigned int pg_idx, pg_off, pg_sz;
3679 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3682 pg_off = skb_frag_off(frag);
3683 pg_sz = skb_frag_size(frag);
3685 if (skb_frag_must_loop(skb_frag_page(frag))) {
3686 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3687 pg_off = offset_in_page(pg_off + st->frag_off);
3688 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3689 PAGE_SIZE - pg_off);
3692 block_limit = pg_sz + st->stepped_offset;
3693 if (abs_offset < block_limit) {
3695 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3697 *data = (u8 *)st->frag_data + pg_off +
3698 (abs_offset - st->stepped_offset);
3700 return block_limit - abs_offset;
3703 if (st->frag_data) {
3704 kunmap_atomic(st->frag_data);
3705 st->frag_data = NULL;
3708 st->stepped_offset += pg_sz;
3709 st->frag_off += pg_sz;
3710 if (st->frag_off == skb_frag_size(frag)) {
3716 if (st->frag_data) {
3717 kunmap_atomic(st->frag_data);
3718 st->frag_data = NULL;
3721 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3722 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3725 } else if (st->cur_skb->next) {
3726 st->cur_skb = st->cur_skb->next;
3733 EXPORT_SYMBOL(skb_seq_read);
3736 * skb_abort_seq_read - Abort a sequential read of skb data
3737 * @st: state variable
3739 * Must be called if skb_seq_read() was not called until it
3742 void skb_abort_seq_read(struct skb_seq_state *st)
3745 kunmap_atomic(st->frag_data);
3747 EXPORT_SYMBOL(skb_abort_seq_read);
3749 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3751 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3752 struct ts_config *conf,
3753 struct ts_state *state)
3755 return skb_seq_read(offset, text, TS_SKB_CB(state));
3758 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3760 skb_abort_seq_read(TS_SKB_CB(state));
3764 * skb_find_text - Find a text pattern in skb data
3765 * @skb: the buffer to look in
3766 * @from: search offset
3768 * @config: textsearch configuration
3770 * Finds a pattern in the skb data according to the specified
3771 * textsearch configuration. Use textsearch_next() to retrieve
3772 * subsequent occurrences of the pattern. Returns the offset
3773 * to the first occurrence or UINT_MAX if no match was found.
3775 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3776 unsigned int to, struct ts_config *config)
3778 struct ts_state state;
3781 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3783 config->get_next_block = skb_ts_get_next_block;
3784 config->finish = skb_ts_finish;
3786 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3788 ret = textsearch_find(config, &state);
3789 return (ret <= to - from ? ret : UINT_MAX);
3791 EXPORT_SYMBOL(skb_find_text);
3793 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3794 int offset, size_t size)
3796 int i = skb_shinfo(skb)->nr_frags;
3798 if (skb_can_coalesce(skb, i, page, offset)) {
3799 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3800 } else if (i < MAX_SKB_FRAGS) {
3802 skb_fill_page_desc(skb, i, page, offset, size);
3809 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3812 * skb_pull_rcsum - pull skb and update receive checksum
3813 * @skb: buffer to update
3814 * @len: length of data pulled
3816 * This function performs an skb_pull on the packet and updates
3817 * the CHECKSUM_COMPLETE checksum. It should be used on
3818 * receive path processing instead of skb_pull unless you know
3819 * that the checksum difference is zero (e.g., a valid IP header)
3820 * or you are setting ip_summed to CHECKSUM_NONE.
3822 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3824 unsigned char *data = skb->data;
3826 BUG_ON(len > skb->len);
3827 __skb_pull(skb, len);
3828 skb_postpull_rcsum(skb, data, len);
3831 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3833 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
3835 skb_frag_t head_frag;
3838 page = virt_to_head_page(frag_skb->head);
3839 __skb_frag_set_page(&head_frag, page);
3840 skb_frag_off_set(&head_frag, frag_skb->data -
3841 (unsigned char *)page_address(page));
3842 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
3846 struct sk_buff *skb_segment_list(struct sk_buff *skb,
3847 netdev_features_t features,
3848 unsigned int offset)
3850 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
3851 unsigned int tnl_hlen = skb_tnl_header_len(skb);
3852 unsigned int delta_truesize = 0;
3853 unsigned int delta_len = 0;
3854 struct sk_buff *tail = NULL;
3855 struct sk_buff *nskb, *tmp;
3858 skb_push(skb, -skb_network_offset(skb) + offset);
3860 skb_shinfo(skb)->frag_list = NULL;
3864 list_skb = list_skb->next;
3867 if (skb_shared(nskb)) {
3868 tmp = skb_clone(nskb, GFP_ATOMIC);
3872 err = skb_unclone(nskb, GFP_ATOMIC);
3883 if (unlikely(err)) {
3884 nskb->next = list_skb;
3890 delta_len += nskb->len;
3891 delta_truesize += nskb->truesize;
3893 skb_push(nskb, -skb_network_offset(nskb) + offset);
3895 skb_release_head_state(nskb);
3896 __copy_skb_header(nskb, skb);
3898 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
3899 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
3900 nskb->data - tnl_hlen,
3903 if (skb_needs_linearize(nskb, features) &&
3904 __skb_linearize(nskb))
3909 skb->truesize = skb->truesize - delta_truesize;
3910 skb->data_len = skb->data_len - delta_len;
3911 skb->len = skb->len - delta_len;
3917 if (skb_needs_linearize(skb, features) &&
3918 __skb_linearize(skb))
3926 kfree_skb_list(skb->next);
3928 return ERR_PTR(-ENOMEM);
3930 EXPORT_SYMBOL_GPL(skb_segment_list);
3932 int skb_gro_receive_list(struct sk_buff *p, struct sk_buff *skb)
3934 if (unlikely(p->len + skb->len >= 65536))
3937 if (NAPI_GRO_CB(p)->last == p)
3938 skb_shinfo(p)->frag_list = skb;
3940 NAPI_GRO_CB(p)->last->next = skb;
3942 skb_pull(skb, skb_gro_offset(skb));
3944 NAPI_GRO_CB(p)->last = skb;
3945 NAPI_GRO_CB(p)->count++;
3946 p->data_len += skb->len;
3948 /* sk owenrship - if any - completely transferred to the aggregated packet */
3949 skb->destructor = NULL;
3950 p->truesize += skb->truesize;
3953 NAPI_GRO_CB(skb)->same_flow = 1;
3959 * skb_segment - Perform protocol segmentation on skb.
3960 * @head_skb: buffer to segment
3961 * @features: features for the output path (see dev->features)
3963 * This function performs segmentation on the given skb. It returns
3964 * a pointer to the first in a list of new skbs for the segments.
3965 * In case of error it returns ERR_PTR(err).
3967 struct sk_buff *skb_segment(struct sk_buff *head_skb,
3968 netdev_features_t features)
3970 struct sk_buff *segs = NULL;
3971 struct sk_buff *tail = NULL;
3972 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3973 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3974 unsigned int mss = skb_shinfo(head_skb)->gso_size;
3975 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
3976 struct sk_buff *frag_skb = head_skb;
3977 unsigned int offset = doffset;
3978 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3979 unsigned int partial_segs = 0;
3980 unsigned int headroom;
3981 unsigned int len = head_skb->len;
3984 int nfrags = skb_shinfo(head_skb)->nr_frags;
3989 if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
3990 (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
3991 /* gso_size is untrusted, and we have a frag_list with a linear
3992 * non head_frag head.
3994 * (we assume checking the first list_skb member suffices;
3995 * i.e if either of the list_skb members have non head_frag
3996 * head, then the first one has too).
3998 * If head_skb's headlen does not fit requested gso_size, it
3999 * means that the frag_list members do NOT terminate on exact
4000 * gso_size boundaries. Hence we cannot perform skb_frag_t page
4001 * sharing. Therefore we must fallback to copying the frag_list
4002 * skbs; we do so by disabling SG.
4004 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
4005 features &= ~NETIF_F_SG;
4008 __skb_push(head_skb, doffset);
4009 proto = skb_network_protocol(head_skb, NULL);
4010 if (unlikely(!proto))
4011 return ERR_PTR(-EINVAL);
4013 sg = !!(features & NETIF_F_SG);
4014 csum = !!can_checksum_protocol(features, proto);
4016 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4017 if (!(features & NETIF_F_GSO_PARTIAL)) {
4018 struct sk_buff *iter;
4019 unsigned int frag_len;
4022 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4025 /* If we get here then all the required
4026 * GSO features except frag_list are supported.
4027 * Try to split the SKB to multiple GSO SKBs
4028 * with no frag_list.
4029 * Currently we can do that only when the buffers don't
4030 * have a linear part and all the buffers except
4031 * the last are of the same length.
4033 frag_len = list_skb->len;
4034 skb_walk_frags(head_skb, iter) {
4035 if (frag_len != iter->len && iter->next)
4037 if (skb_headlen(iter) && !iter->head_frag)
4043 if (len != frag_len)
4047 /* GSO partial only requires that we trim off any excess that
4048 * doesn't fit into an MSS sized block, so take care of that
4051 partial_segs = len / mss;
4052 if (partial_segs > 1)
4053 mss *= partial_segs;
4059 headroom = skb_headroom(head_skb);
4060 pos = skb_headlen(head_skb);
4063 struct sk_buff *nskb;
4064 skb_frag_t *nskb_frag;
4068 if (unlikely(mss == GSO_BY_FRAGS)) {
4069 len = list_skb->len;
4071 len = head_skb->len - offset;
4076 hsize = skb_headlen(head_skb) - offset;
4078 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4079 (skb_headlen(list_skb) == len || sg)) {
4080 BUG_ON(skb_headlen(list_skb) > len);
4083 nfrags = skb_shinfo(list_skb)->nr_frags;
4084 frag = skb_shinfo(list_skb)->frags;
4085 frag_skb = list_skb;
4086 pos += skb_headlen(list_skb);
4088 while (pos < offset + len) {
4089 BUG_ON(i >= nfrags);
4091 size = skb_frag_size(frag);
4092 if (pos + size > offset + len)
4100 nskb = skb_clone(list_skb, GFP_ATOMIC);
4101 list_skb = list_skb->next;
4103 if (unlikely(!nskb))
4106 if (unlikely(pskb_trim(nskb, len))) {
4111 hsize = skb_end_offset(nskb);
4112 if (skb_cow_head(nskb, doffset + headroom)) {
4117 nskb->truesize += skb_end_offset(nskb) - hsize;
4118 skb_release_head_state(nskb);
4119 __skb_push(nskb, doffset);
4123 if (hsize > len || !sg)
4126 nskb = __alloc_skb(hsize + doffset + headroom,
4127 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4130 if (unlikely(!nskb))
4133 skb_reserve(nskb, headroom);
4134 __skb_put(nskb, doffset);
4143 __copy_skb_header(nskb, head_skb);
4145 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4146 skb_reset_mac_len(nskb);
4148 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4149 nskb->data - tnl_hlen,
4150 doffset + tnl_hlen);
4152 if (nskb->len == len + doffset)
4153 goto perform_csum_check;
4157 if (!nskb->remcsum_offload)
4158 nskb->ip_summed = CHECKSUM_NONE;
4159 SKB_GSO_CB(nskb)->csum =
4160 skb_copy_and_csum_bits(head_skb, offset,
4164 SKB_GSO_CB(nskb)->csum_start =
4165 skb_headroom(nskb) + doffset;
4167 skb_copy_bits(head_skb, offset,
4174 nskb_frag = skb_shinfo(nskb)->frags;
4176 skb_copy_from_linear_data_offset(head_skb, offset,
4177 skb_put(nskb, hsize), hsize);
4179 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4182 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4183 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4186 while (pos < offset + len) {
4189 nfrags = skb_shinfo(list_skb)->nr_frags;
4190 frag = skb_shinfo(list_skb)->frags;
4191 frag_skb = list_skb;
4192 if (!skb_headlen(list_skb)) {
4195 BUG_ON(!list_skb->head_frag);
4197 /* to make room for head_frag. */
4201 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4202 skb_zerocopy_clone(nskb, frag_skb,
4206 list_skb = list_skb->next;
4209 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4211 net_warn_ratelimited(
4212 "skb_segment: too many frags: %u %u\n",
4218 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4219 __skb_frag_ref(nskb_frag);
4220 size = skb_frag_size(nskb_frag);
4223 skb_frag_off_add(nskb_frag, offset - pos);
4224 skb_frag_size_sub(nskb_frag, offset - pos);
4227 skb_shinfo(nskb)->nr_frags++;
4229 if (pos + size <= offset + len) {
4234 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4242 nskb->data_len = len - hsize;
4243 nskb->len += nskb->data_len;
4244 nskb->truesize += nskb->data_len;
4248 if (skb_has_shared_frag(nskb) &&
4249 __skb_linearize(nskb))
4252 if (!nskb->remcsum_offload)
4253 nskb->ip_summed = CHECKSUM_NONE;
4254 SKB_GSO_CB(nskb)->csum =
4255 skb_checksum(nskb, doffset,
4256 nskb->len - doffset, 0);
4257 SKB_GSO_CB(nskb)->csum_start =
4258 skb_headroom(nskb) + doffset;
4260 } while ((offset += len) < head_skb->len);
4262 /* Some callers want to get the end of the list.
4263 * Put it in segs->prev to avoid walking the list.
4264 * (see validate_xmit_skb_list() for example)
4269 struct sk_buff *iter;
4270 int type = skb_shinfo(head_skb)->gso_type;
4271 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4273 /* Update type to add partial and then remove dodgy if set */
4274 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4275 type &= ~SKB_GSO_DODGY;
4277 /* Update GSO info and prepare to start updating headers on
4278 * our way back down the stack of protocols.
4280 for (iter = segs; iter; iter = iter->next) {
4281 skb_shinfo(iter)->gso_size = gso_size;
4282 skb_shinfo(iter)->gso_segs = partial_segs;
4283 skb_shinfo(iter)->gso_type = type;
4284 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4287 if (tail->len - doffset <= gso_size)
4288 skb_shinfo(tail)->gso_size = 0;
4289 else if (tail != segs)
4290 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4293 /* Following permits correct backpressure, for protocols
4294 * using skb_set_owner_w().
4295 * Idea is to tranfert ownership from head_skb to last segment.
4297 if (head_skb->destructor == sock_wfree) {
4298 swap(tail->truesize, head_skb->truesize);
4299 swap(tail->destructor, head_skb->destructor);
4300 swap(tail->sk, head_skb->sk);
4305 kfree_skb_list(segs);
4306 return ERR_PTR(err);
4308 EXPORT_SYMBOL_GPL(skb_segment);
4310 int skb_gro_receive(struct sk_buff *p, struct sk_buff *skb)
4312 struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
4313 unsigned int offset = skb_gro_offset(skb);
4314 unsigned int headlen = skb_headlen(skb);
4315 unsigned int len = skb_gro_len(skb);
4316 unsigned int delta_truesize;
4317 unsigned int new_truesize;
4320 if (unlikely(p->len + len >= 65536 || NAPI_GRO_CB(skb)->flush))
4323 lp = NAPI_GRO_CB(p)->last;
4324 pinfo = skb_shinfo(lp);
4326 if (headlen <= offset) {
4329 int i = skbinfo->nr_frags;
4330 int nr_frags = pinfo->nr_frags + i;
4332 if (nr_frags > MAX_SKB_FRAGS)
4336 pinfo->nr_frags = nr_frags;
4337 skbinfo->nr_frags = 0;
4339 frag = pinfo->frags + nr_frags;
4340 frag2 = skbinfo->frags + i;
4345 skb_frag_off_add(frag, offset);
4346 skb_frag_size_sub(frag, offset);
4348 /* all fragments truesize : remove (head size + sk_buff) */
4349 new_truesize = SKB_TRUESIZE(skb_end_offset(skb));
4350 delta_truesize = skb->truesize - new_truesize;
4352 skb->truesize = new_truesize;
4353 skb->len -= skb->data_len;
4356 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
4358 } else if (skb->head_frag) {
4359 int nr_frags = pinfo->nr_frags;
4360 skb_frag_t *frag = pinfo->frags + nr_frags;
4361 struct page *page = virt_to_head_page(skb->head);
4362 unsigned int first_size = headlen - offset;
4363 unsigned int first_offset;
4365 if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
4368 first_offset = skb->data -
4369 (unsigned char *)page_address(page) +
4372 pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
4374 __skb_frag_set_page(frag, page);
4375 skb_frag_off_set(frag, first_offset);
4376 skb_frag_size_set(frag, first_size);
4378 memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
4379 /* We dont need to clear skbinfo->nr_frags here */
4381 new_truesize = SKB_DATA_ALIGN(sizeof(struct sk_buff));
4382 delta_truesize = skb->truesize - new_truesize;
4383 skb->truesize = new_truesize;
4384 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
4389 /* sk owenrship - if any - completely transferred to the aggregated packet */
4390 skb->destructor = NULL;
4391 delta_truesize = skb->truesize;
4392 if (offset > headlen) {
4393 unsigned int eat = offset - headlen;
4395 skb_frag_off_add(&skbinfo->frags[0], eat);
4396 skb_frag_size_sub(&skbinfo->frags[0], eat);
4397 skb->data_len -= eat;
4402 __skb_pull(skb, offset);
4404 if (NAPI_GRO_CB(p)->last == p)
4405 skb_shinfo(p)->frag_list = skb;
4407 NAPI_GRO_CB(p)->last->next = skb;
4408 NAPI_GRO_CB(p)->last = skb;
4409 __skb_header_release(skb);
4413 NAPI_GRO_CB(p)->count++;
4415 p->truesize += delta_truesize;
4418 lp->data_len += len;
4419 lp->truesize += delta_truesize;
4422 NAPI_GRO_CB(skb)->same_flow = 1;
4426 #ifdef CONFIG_SKB_EXTENSIONS
4427 #define SKB_EXT_ALIGN_VALUE 8
4428 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4430 static const u8 skb_ext_type_len[] = {
4431 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4432 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4435 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4437 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4438 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4440 #if IS_ENABLED(CONFIG_MPTCP)
4441 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4445 static __always_inline unsigned int skb_ext_total_length(void)
4447 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4448 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4449 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4452 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4454 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4455 skb_ext_type_len[TC_SKB_EXT] +
4457 #if IS_ENABLED(CONFIG_MPTCP)
4458 skb_ext_type_len[SKB_EXT_MPTCP] +
4463 static void skb_extensions_init(void)
4465 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4466 BUILD_BUG_ON(skb_ext_total_length() > 255);
4468 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4469 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4471 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4475 static void skb_extensions_init(void) {}
4478 void __init skb_init(void)
4480 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4481 sizeof(struct sk_buff),
4483 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4484 offsetof(struct sk_buff, cb),
4485 sizeof_field(struct sk_buff, cb),
4487 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4488 sizeof(struct sk_buff_fclones),
4490 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4492 skb_extensions_init();
4496 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4497 unsigned int recursion_level)
4499 int start = skb_headlen(skb);
4500 int i, copy = start - offset;
4501 struct sk_buff *frag_iter;
4504 if (unlikely(recursion_level >= 24))
4510 sg_set_buf(sg, skb->data + offset, copy);
4512 if ((len -= copy) == 0)
4517 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4520 WARN_ON(start > offset + len);
4522 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4523 if ((copy = end - offset) > 0) {
4524 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4525 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4530 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4531 skb_frag_off(frag) + offset - start);
4540 skb_walk_frags(skb, frag_iter) {
4543 WARN_ON(start > offset + len);
4545 end = start + frag_iter->len;
4546 if ((copy = end - offset) > 0) {
4547 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4552 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4553 copy, recursion_level + 1);
4554 if (unlikely(ret < 0))
4557 if ((len -= copy) == 0)
4568 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4569 * @skb: Socket buffer containing the buffers to be mapped
4570 * @sg: The scatter-gather list to map into
4571 * @offset: The offset into the buffer's contents to start mapping
4572 * @len: Length of buffer space to be mapped
4574 * Fill the specified scatter-gather list with mappings/pointers into a
4575 * region of the buffer space attached to a socket buffer. Returns either
4576 * the number of scatterlist items used, or -EMSGSIZE if the contents
4579 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4581 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4586 sg_mark_end(&sg[nsg - 1]);
4590 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4592 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4593 * sglist without mark the sg which contain last skb data as the end.
4594 * So the caller can mannipulate sg list as will when padding new data after
4595 * the first call without calling sg_unmark_end to expend sg list.
4597 * Scenario to use skb_to_sgvec_nomark:
4599 * 2. skb_to_sgvec_nomark(payload1)
4600 * 3. skb_to_sgvec_nomark(payload2)
4602 * This is equivalent to:
4604 * 2. skb_to_sgvec(payload1)
4606 * 4. skb_to_sgvec(payload2)
4608 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4609 * is more preferable.
4611 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4612 int offset, int len)
4614 return __skb_to_sgvec(skb, sg, offset, len, 0);
4616 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4621 * skb_cow_data - Check that a socket buffer's data buffers are writable
4622 * @skb: The socket buffer to check.
4623 * @tailbits: Amount of trailing space to be added
4624 * @trailer: Returned pointer to the skb where the @tailbits space begins
4626 * Make sure that the data buffers attached to a socket buffer are
4627 * writable. If they are not, private copies are made of the data buffers
4628 * and the socket buffer is set to use these instead.
4630 * If @tailbits is given, make sure that there is space to write @tailbits
4631 * bytes of data beyond current end of socket buffer. @trailer will be
4632 * set to point to the skb in which this space begins.
4634 * The number of scatterlist elements required to completely map the
4635 * COW'd and extended socket buffer will be returned.
4637 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4641 struct sk_buff *skb1, **skb_p;
4643 /* If skb is cloned or its head is paged, reallocate
4644 * head pulling out all the pages (pages are considered not writable
4645 * at the moment even if they are anonymous).
4647 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4648 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4651 /* Easy case. Most of packets will go this way. */
4652 if (!skb_has_frag_list(skb)) {
4653 /* A little of trouble, not enough of space for trailer.
4654 * This should not happen, when stack is tuned to generate
4655 * good frames. OK, on miss we reallocate and reserve even more
4656 * space, 128 bytes is fair. */
4658 if (skb_tailroom(skb) < tailbits &&
4659 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4667 /* Misery. We are in troubles, going to mincer fragments... */
4670 skb_p = &skb_shinfo(skb)->frag_list;
4673 while ((skb1 = *skb_p) != NULL) {
4676 /* The fragment is partially pulled by someone,
4677 * this can happen on input. Copy it and everything
4680 if (skb_shared(skb1))
4683 /* If the skb is the last, worry about trailer. */
4685 if (skb1->next == NULL && tailbits) {
4686 if (skb_shinfo(skb1)->nr_frags ||
4687 skb_has_frag_list(skb1) ||
4688 skb_tailroom(skb1) < tailbits)
4689 ntail = tailbits + 128;
4695 skb_shinfo(skb1)->nr_frags ||
4696 skb_has_frag_list(skb1)) {
4697 struct sk_buff *skb2;
4699 /* Fuck, we are miserable poor guys... */
4701 skb2 = skb_copy(skb1, GFP_ATOMIC);
4703 skb2 = skb_copy_expand(skb1,
4707 if (unlikely(skb2 == NULL))
4711 skb_set_owner_w(skb2, skb1->sk);
4713 /* Looking around. Are we still alive?
4714 * OK, link new skb, drop old one */
4716 skb2->next = skb1->next;
4723 skb_p = &skb1->next;
4728 EXPORT_SYMBOL_GPL(skb_cow_data);
4730 static void sock_rmem_free(struct sk_buff *skb)
4732 struct sock *sk = skb->sk;
4734 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4737 static void skb_set_err_queue(struct sk_buff *skb)
4739 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4740 * So, it is safe to (mis)use it to mark skbs on the error queue.
4742 skb->pkt_type = PACKET_OUTGOING;
4743 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4747 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4749 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4751 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4752 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4757 skb->destructor = sock_rmem_free;
4758 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4759 skb_set_err_queue(skb);
4761 /* before exiting rcu section, make sure dst is refcounted */
4764 skb_queue_tail(&sk->sk_error_queue, skb);
4765 if (!sock_flag(sk, SOCK_DEAD))
4766 sk_error_report(sk);
4769 EXPORT_SYMBOL(sock_queue_err_skb);
4771 static bool is_icmp_err_skb(const struct sk_buff *skb)
4773 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4774 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4777 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4779 struct sk_buff_head *q = &sk->sk_error_queue;
4780 struct sk_buff *skb, *skb_next = NULL;
4781 bool icmp_next = false;
4782 unsigned long flags;
4784 spin_lock_irqsave(&q->lock, flags);
4785 skb = __skb_dequeue(q);
4786 if (skb && (skb_next = skb_peek(q))) {
4787 icmp_next = is_icmp_err_skb(skb_next);
4789 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4791 spin_unlock_irqrestore(&q->lock, flags);
4793 if (is_icmp_err_skb(skb) && !icmp_next)
4797 sk_error_report(sk);
4801 EXPORT_SYMBOL(sock_dequeue_err_skb);
4804 * skb_clone_sk - create clone of skb, and take reference to socket
4805 * @skb: the skb to clone
4807 * This function creates a clone of a buffer that holds a reference on
4808 * sk_refcnt. Buffers created via this function are meant to be
4809 * returned using sock_queue_err_skb, or free via kfree_skb.
4811 * When passing buffers allocated with this function to sock_queue_err_skb
4812 * it is necessary to wrap the call with sock_hold/sock_put in order to
4813 * prevent the socket from being released prior to being enqueued on
4814 * the sk_error_queue.
4816 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4818 struct sock *sk = skb->sk;
4819 struct sk_buff *clone;
4821 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4824 clone = skb_clone(skb, GFP_ATOMIC);
4831 clone->destructor = sock_efree;
4835 EXPORT_SYMBOL(skb_clone_sk);
4837 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4842 struct sock_exterr_skb *serr;
4845 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4847 serr = SKB_EXT_ERR(skb);
4848 memset(serr, 0, sizeof(*serr));
4849 serr->ee.ee_errno = ENOMSG;
4850 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4851 serr->ee.ee_info = tstype;
4852 serr->opt_stats = opt_stats;
4853 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4854 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4855 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4856 if (sk->sk_protocol == IPPROTO_TCP &&
4857 sk->sk_type == SOCK_STREAM)
4858 serr->ee.ee_data -= sk->sk_tskey;
4861 err = sock_queue_err_skb(sk, skb);
4867 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4871 if (likely(sysctl_tstamp_allow_data || tsonly))
4874 read_lock_bh(&sk->sk_callback_lock);
4875 ret = sk->sk_socket && sk->sk_socket->file &&
4876 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4877 read_unlock_bh(&sk->sk_callback_lock);
4881 void skb_complete_tx_timestamp(struct sk_buff *skb,
4882 struct skb_shared_hwtstamps *hwtstamps)
4884 struct sock *sk = skb->sk;
4886 if (!skb_may_tx_timestamp(sk, false))
4889 /* Take a reference to prevent skb_orphan() from freeing the socket,
4890 * but only if the socket refcount is not zero.
4892 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4893 *skb_hwtstamps(skb) = *hwtstamps;
4894 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4902 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4904 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4905 const struct sk_buff *ack_skb,
4906 struct skb_shared_hwtstamps *hwtstamps,
4907 struct sock *sk, int tstype)
4909 struct sk_buff *skb;
4910 bool tsonly, opt_stats = false;
4915 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4916 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4919 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4920 if (!skb_may_tx_timestamp(sk, tsonly))
4925 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4926 sk->sk_protocol == IPPROTO_TCP &&
4927 sk->sk_type == SOCK_STREAM) {
4928 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4933 skb = alloc_skb(0, GFP_ATOMIC);
4935 skb = skb_clone(orig_skb, GFP_ATOMIC);
4941 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4943 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4947 *skb_hwtstamps(skb) = *hwtstamps;
4949 skb->tstamp = ktime_get_real();
4951 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
4953 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4955 void skb_tstamp_tx(struct sk_buff *orig_skb,
4956 struct skb_shared_hwtstamps *hwtstamps)
4958 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4961 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4963 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
4965 struct sock *sk = skb->sk;
4966 struct sock_exterr_skb *serr;
4969 skb->wifi_acked_valid = 1;
4970 skb->wifi_acked = acked;
4972 serr = SKB_EXT_ERR(skb);
4973 memset(serr, 0, sizeof(*serr));
4974 serr->ee.ee_errno = ENOMSG;
4975 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
4977 /* Take a reference to prevent skb_orphan() from freeing the socket,
4978 * but only if the socket refcount is not zero.
4980 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4981 err = sock_queue_err_skb(sk, skb);
4987 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4990 * skb_partial_csum_set - set up and verify partial csum values for packet
4991 * @skb: the skb to set
4992 * @start: the number of bytes after skb->data to start checksumming.
4993 * @off: the offset from start to place the checksum.
4995 * For untrusted partially-checksummed packets, we need to make sure the values
4996 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4998 * This function checks and sets those values and skb->ip_summed: if this
4999 * returns false you should drop the packet.
5001 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5003 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5004 u32 csum_start = skb_headroom(skb) + (u32)start;
5006 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
5007 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5008 start, off, skb_headroom(skb), skb_headlen(skb));
5011 skb->ip_summed = CHECKSUM_PARTIAL;
5012 skb->csum_start = csum_start;
5013 skb->csum_offset = off;
5014 skb_set_transport_header(skb, start);
5017 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5019 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5022 if (skb_headlen(skb) >= len)
5025 /* If we need to pullup then pullup to the max, so we
5026 * won't need to do it again.
5031 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5034 if (skb_headlen(skb) < len)
5040 #define MAX_TCP_HDR_LEN (15 * 4)
5042 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5043 typeof(IPPROTO_IP) proto,
5050 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5051 off + MAX_TCP_HDR_LEN);
5052 if (!err && !skb_partial_csum_set(skb, off,
5053 offsetof(struct tcphdr,
5056 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5059 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5060 off + sizeof(struct udphdr));
5061 if (!err && !skb_partial_csum_set(skb, off,
5062 offsetof(struct udphdr,
5065 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5068 return ERR_PTR(-EPROTO);
5071 /* This value should be large enough to cover a tagged ethernet header plus
5072 * maximally sized IP and TCP or UDP headers.
5074 #define MAX_IP_HDR_LEN 128
5076 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5085 err = skb_maybe_pull_tail(skb,
5086 sizeof(struct iphdr),
5091 if (ip_is_fragment(ip_hdr(skb)))
5094 off = ip_hdrlen(skb);
5101 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5103 return PTR_ERR(csum);
5106 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5109 ip_hdr(skb)->protocol, 0);
5116 /* This value should be large enough to cover a tagged ethernet header plus
5117 * an IPv6 header, all options, and a maximal TCP or UDP header.
5119 #define MAX_IPV6_HDR_LEN 256
5121 #define OPT_HDR(type, skb, off) \
5122 (type *)(skb_network_header(skb) + (off))
5124 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5137 off = sizeof(struct ipv6hdr);
5139 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5143 nexthdr = ipv6_hdr(skb)->nexthdr;
5145 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5146 while (off <= len && !done) {
5148 case IPPROTO_DSTOPTS:
5149 case IPPROTO_HOPOPTS:
5150 case IPPROTO_ROUTING: {
5151 struct ipv6_opt_hdr *hp;
5153 err = skb_maybe_pull_tail(skb,
5155 sizeof(struct ipv6_opt_hdr),
5160 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5161 nexthdr = hp->nexthdr;
5162 off += ipv6_optlen(hp);
5166 struct ip_auth_hdr *hp;
5168 err = skb_maybe_pull_tail(skb,
5170 sizeof(struct ip_auth_hdr),
5175 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5176 nexthdr = hp->nexthdr;
5177 off += ipv6_authlen(hp);
5180 case IPPROTO_FRAGMENT: {
5181 struct frag_hdr *hp;
5183 err = skb_maybe_pull_tail(skb,
5185 sizeof(struct frag_hdr),
5190 hp = OPT_HDR(struct frag_hdr, skb, off);
5192 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5195 nexthdr = hp->nexthdr;
5196 off += sizeof(struct frag_hdr);
5207 if (!done || fragment)
5210 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5212 return PTR_ERR(csum);
5215 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5216 &ipv6_hdr(skb)->daddr,
5217 skb->len - off, nexthdr, 0);
5225 * skb_checksum_setup - set up partial checksum offset
5226 * @skb: the skb to set up
5227 * @recalculate: if true the pseudo-header checksum will be recalculated
5229 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5233 switch (skb->protocol) {
5234 case htons(ETH_P_IP):
5235 err = skb_checksum_setup_ipv4(skb, recalculate);
5238 case htons(ETH_P_IPV6):
5239 err = skb_checksum_setup_ipv6(skb, recalculate);
5249 EXPORT_SYMBOL(skb_checksum_setup);
5252 * skb_checksum_maybe_trim - maybe trims the given skb
5253 * @skb: the skb to check
5254 * @transport_len: the data length beyond the network header
5256 * Checks whether the given skb has data beyond the given transport length.
5257 * If so, returns a cloned skb trimmed to this transport length.
5258 * Otherwise returns the provided skb. Returns NULL in error cases
5259 * (e.g. transport_len exceeds skb length or out-of-memory).
5261 * Caller needs to set the skb transport header and free any returned skb if it
5262 * differs from the provided skb.
5264 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5265 unsigned int transport_len)
5267 struct sk_buff *skb_chk;
5268 unsigned int len = skb_transport_offset(skb) + transport_len;
5273 else if (skb->len == len)
5276 skb_chk = skb_clone(skb, GFP_ATOMIC);
5280 ret = pskb_trim_rcsum(skb_chk, len);
5290 * skb_checksum_trimmed - validate checksum of an skb
5291 * @skb: the skb to check
5292 * @transport_len: the data length beyond the network header
5293 * @skb_chkf: checksum function to use
5295 * Applies the given checksum function skb_chkf to the provided skb.
5296 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5298 * If the skb has data beyond the given transport length, then a
5299 * trimmed & cloned skb is checked and returned.
5301 * Caller needs to set the skb transport header and free any returned skb if it
5302 * differs from the provided skb.
5304 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5305 unsigned int transport_len,
5306 __sum16(*skb_chkf)(struct sk_buff *skb))
5308 struct sk_buff *skb_chk;
5309 unsigned int offset = skb_transport_offset(skb);
5312 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5316 if (!pskb_may_pull(skb_chk, offset))
5319 skb_pull_rcsum(skb_chk, offset);
5320 ret = skb_chkf(skb_chk);
5321 skb_push_rcsum(skb_chk, offset);
5329 if (skb_chk && skb_chk != skb)
5335 EXPORT_SYMBOL(skb_checksum_trimmed);
5337 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5339 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5342 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5344 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5347 skb_release_head_state(skb);
5348 kmem_cache_free(skbuff_head_cache, skb);
5353 EXPORT_SYMBOL(kfree_skb_partial);
5356 * skb_try_coalesce - try to merge skb to prior one
5358 * @from: buffer to add
5359 * @fragstolen: pointer to boolean
5360 * @delta_truesize: how much more was allocated than was requested
5362 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5363 bool *fragstolen, int *delta_truesize)
5365 struct skb_shared_info *to_shinfo, *from_shinfo;
5366 int i, delta, len = from->len;
5368 *fragstolen = false;
5373 /* The page pool signature of struct page will eventually figure out
5374 * which pages can be recycled or not but for now let's prohibit slab
5375 * allocated and page_pool allocated SKBs from being coalesced.
5377 if (to->pp_recycle != from->pp_recycle)
5380 if (len <= skb_tailroom(to)) {
5382 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5383 *delta_truesize = 0;
5387 to_shinfo = skb_shinfo(to);
5388 from_shinfo = skb_shinfo(from);
5389 if (to_shinfo->frag_list || from_shinfo->frag_list)
5391 if (skb_zcopy(to) || skb_zcopy(from))
5394 if (skb_headlen(from) != 0) {
5396 unsigned int offset;
5398 if (to_shinfo->nr_frags +
5399 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5402 if (skb_head_is_locked(from))
5405 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5407 page = virt_to_head_page(from->head);
5408 offset = from->data - (unsigned char *)page_address(page);
5410 skb_fill_page_desc(to, to_shinfo->nr_frags,
5411 page, offset, skb_headlen(from));
5414 if (to_shinfo->nr_frags +
5415 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5418 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5421 WARN_ON_ONCE(delta < len);
5423 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5425 from_shinfo->nr_frags * sizeof(skb_frag_t));
5426 to_shinfo->nr_frags += from_shinfo->nr_frags;
5428 if (!skb_cloned(from))
5429 from_shinfo->nr_frags = 0;
5431 /* if the skb is not cloned this does nothing
5432 * since we set nr_frags to 0.
5434 for (i = 0; i < from_shinfo->nr_frags; i++)
5435 __skb_frag_ref(&from_shinfo->frags[i]);
5437 to->truesize += delta;
5439 to->data_len += len;
5441 *delta_truesize = delta;
5444 EXPORT_SYMBOL(skb_try_coalesce);
5447 * skb_scrub_packet - scrub an skb
5449 * @skb: buffer to clean
5450 * @xnet: packet is crossing netns
5452 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5453 * into/from a tunnel. Some information have to be cleared during these
5455 * skb_scrub_packet can also be used to clean a skb before injecting it in
5456 * another namespace (@xnet == true). We have to clear all information in the
5457 * skb that could impact namespace isolation.
5459 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5461 skb->pkt_type = PACKET_HOST;
5467 nf_reset_trace(skb);
5469 #ifdef CONFIG_NET_SWITCHDEV
5470 skb->offload_fwd_mark = 0;
5471 skb->offload_l3_fwd_mark = 0;
5481 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5484 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5488 * skb_gso_transport_seglen is used to determine the real size of the
5489 * individual segments, including Layer4 headers (TCP/UDP).
5491 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5493 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5495 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5496 unsigned int thlen = 0;
5498 if (skb->encapsulation) {
5499 thlen = skb_inner_transport_header(skb) -
5500 skb_transport_header(skb);
5502 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5503 thlen += inner_tcp_hdrlen(skb);
5504 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5505 thlen = tcp_hdrlen(skb);
5506 } else if (unlikely(skb_is_gso_sctp(skb))) {
5507 thlen = sizeof(struct sctphdr);
5508 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5509 thlen = sizeof(struct udphdr);
5511 /* UFO sets gso_size to the size of the fragmentation
5512 * payload, i.e. the size of the L4 (UDP) header is already
5515 return thlen + shinfo->gso_size;
5519 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5523 * skb_gso_network_seglen is used to determine the real size of the
5524 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5526 * The MAC/L2 header is not accounted for.
5528 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5530 unsigned int hdr_len = skb_transport_header(skb) -
5531 skb_network_header(skb);
5533 return hdr_len + skb_gso_transport_seglen(skb);
5537 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5541 * skb_gso_mac_seglen is used to determine the real size of the
5542 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5543 * headers (TCP/UDP).
5545 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5547 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5549 return hdr_len + skb_gso_transport_seglen(skb);
5553 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5555 * There are a couple of instances where we have a GSO skb, and we
5556 * want to determine what size it would be after it is segmented.
5558 * We might want to check:
5559 * - L3+L4+payload size (e.g. IP forwarding)
5560 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5562 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5566 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5567 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5569 * @max_len: The maximum permissible length.
5571 * Returns true if the segmented length <= max length.
5573 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5574 unsigned int seg_len,
5575 unsigned int max_len) {
5576 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5577 const struct sk_buff *iter;
5579 if (shinfo->gso_size != GSO_BY_FRAGS)
5580 return seg_len <= max_len;
5582 /* Undo this so we can re-use header sizes */
5583 seg_len -= GSO_BY_FRAGS;
5585 skb_walk_frags(skb, iter) {
5586 if (seg_len + skb_headlen(iter) > max_len)
5594 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5597 * @mtu: MTU to validate against
5599 * skb_gso_validate_network_len validates if a given skb will fit a
5600 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5603 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5605 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5607 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5610 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5613 * @len: length to validate against
5615 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5616 * length once split, including L2, L3 and L4 headers and the payload.
5618 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5620 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5622 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5624 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5626 int mac_len, meta_len;
5629 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5634 mac_len = skb->data - skb_mac_header(skb);
5635 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5636 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5637 mac_len - VLAN_HLEN - ETH_TLEN);
5640 meta_len = skb_metadata_len(skb);
5642 meta = skb_metadata_end(skb) - meta_len;
5643 memmove(meta + VLAN_HLEN, meta, meta_len);
5646 skb->mac_header += VLAN_HLEN;
5650 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5652 struct vlan_hdr *vhdr;
5655 if (unlikely(skb_vlan_tag_present(skb))) {
5656 /* vlan_tci is already set-up so leave this for another time */
5660 skb = skb_share_check(skb, GFP_ATOMIC);
5663 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5664 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5667 vhdr = (struct vlan_hdr *)skb->data;
5668 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5669 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5671 skb_pull_rcsum(skb, VLAN_HLEN);
5672 vlan_set_encap_proto(skb, vhdr);
5674 skb = skb_reorder_vlan_header(skb);
5678 skb_reset_network_header(skb);
5679 if (!skb_transport_header_was_set(skb))
5680 skb_reset_transport_header(skb);
5681 skb_reset_mac_len(skb);
5689 EXPORT_SYMBOL(skb_vlan_untag);
5691 int skb_ensure_writable(struct sk_buff *skb, int write_len)
5693 if (!pskb_may_pull(skb, write_len))
5696 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5699 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5701 EXPORT_SYMBOL(skb_ensure_writable);
5703 /* remove VLAN header from packet and update csum accordingly.
5704 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5706 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5708 struct vlan_hdr *vhdr;
5709 int offset = skb->data - skb_mac_header(skb);
5712 if (WARN_ONCE(offset,
5713 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5718 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5722 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5724 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5725 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5727 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5728 __skb_pull(skb, VLAN_HLEN);
5730 vlan_set_encap_proto(skb, vhdr);
5731 skb->mac_header += VLAN_HLEN;
5733 if (skb_network_offset(skb) < ETH_HLEN)
5734 skb_set_network_header(skb, ETH_HLEN);
5736 skb_reset_mac_len(skb);
5740 EXPORT_SYMBOL(__skb_vlan_pop);
5742 /* Pop a vlan tag either from hwaccel or from payload.
5743 * Expects skb->data at mac header.
5745 int skb_vlan_pop(struct sk_buff *skb)
5751 if (likely(skb_vlan_tag_present(skb))) {
5752 __vlan_hwaccel_clear_tag(skb);
5754 if (unlikely(!eth_type_vlan(skb->protocol)))
5757 err = __skb_vlan_pop(skb, &vlan_tci);
5761 /* move next vlan tag to hw accel tag */
5762 if (likely(!eth_type_vlan(skb->protocol)))
5765 vlan_proto = skb->protocol;
5766 err = __skb_vlan_pop(skb, &vlan_tci);
5770 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5773 EXPORT_SYMBOL(skb_vlan_pop);
5775 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5776 * Expects skb->data at mac header.
5778 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5780 if (skb_vlan_tag_present(skb)) {
5781 int offset = skb->data - skb_mac_header(skb);
5784 if (WARN_ONCE(offset,
5785 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5790 err = __vlan_insert_tag(skb, skb->vlan_proto,
5791 skb_vlan_tag_get(skb));
5795 skb->protocol = skb->vlan_proto;
5796 skb->mac_len += VLAN_HLEN;
5798 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5800 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5803 EXPORT_SYMBOL(skb_vlan_push);
5806 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5808 * @skb: Socket buffer to modify
5810 * Drop the Ethernet header of @skb.
5812 * Expects that skb->data points to the mac header and that no VLAN tags are
5815 * Returns 0 on success, -errno otherwise.
5817 int skb_eth_pop(struct sk_buff *skb)
5819 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5820 skb_network_offset(skb) < ETH_HLEN)
5823 skb_pull_rcsum(skb, ETH_HLEN);
5824 skb_reset_mac_header(skb);
5825 skb_reset_mac_len(skb);
5829 EXPORT_SYMBOL(skb_eth_pop);
5832 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5834 * @skb: Socket buffer to modify
5835 * @dst: Destination MAC address of the new header
5836 * @src: Source MAC address of the new header
5838 * Prepend @skb with a new Ethernet header.
5840 * Expects that skb->data points to the mac header, which must be empty.
5842 * Returns 0 on success, -errno otherwise.
5844 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5845 const unsigned char *src)
5850 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5853 err = skb_cow_head(skb, sizeof(*eth));
5857 skb_push(skb, sizeof(*eth));
5858 skb_reset_mac_header(skb);
5859 skb_reset_mac_len(skb);
5862 ether_addr_copy(eth->h_dest, dst);
5863 ether_addr_copy(eth->h_source, src);
5864 eth->h_proto = skb->protocol;
5866 skb_postpush_rcsum(skb, eth, sizeof(*eth));
5870 EXPORT_SYMBOL(skb_eth_push);
5872 /* Update the ethertype of hdr and the skb csum value if required. */
5873 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5876 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5877 __be16 diff[] = { ~hdr->h_proto, ethertype };
5879 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5882 hdr->h_proto = ethertype;
5886 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5890 * @mpls_lse: MPLS label stack entry to push
5891 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5892 * @mac_len: length of the MAC header
5893 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5896 * Expects skb->data at mac header.
5898 * Returns 0 on success, -errno otherwise.
5900 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5901 int mac_len, bool ethernet)
5903 struct mpls_shim_hdr *lse;
5906 if (unlikely(!eth_p_mpls(mpls_proto)))
5909 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5910 if (skb->encapsulation)
5913 err = skb_cow_head(skb, MPLS_HLEN);
5917 if (!skb->inner_protocol) {
5918 skb_set_inner_network_header(skb, skb_network_offset(skb));
5919 skb_set_inner_protocol(skb, skb->protocol);
5922 skb_push(skb, MPLS_HLEN);
5923 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5925 skb_reset_mac_header(skb);
5926 skb_set_network_header(skb, mac_len);
5927 skb_reset_mac_len(skb);
5929 lse = mpls_hdr(skb);
5930 lse->label_stack_entry = mpls_lse;
5931 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5933 if (ethernet && mac_len >= ETH_HLEN)
5934 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5935 skb->protocol = mpls_proto;
5939 EXPORT_SYMBOL_GPL(skb_mpls_push);
5942 * skb_mpls_pop() - pop the outermost MPLS header
5945 * @next_proto: ethertype of header after popped MPLS header
5946 * @mac_len: length of the MAC header
5947 * @ethernet: flag to indicate if the packet is ethernet
5949 * Expects skb->data at mac header.
5951 * Returns 0 on success, -errno otherwise.
5953 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5958 if (unlikely(!eth_p_mpls(skb->protocol)))
5961 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5965 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5966 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5969 __skb_pull(skb, MPLS_HLEN);
5970 skb_reset_mac_header(skb);
5971 skb_set_network_header(skb, mac_len);
5973 if (ethernet && mac_len >= ETH_HLEN) {
5976 /* use mpls_hdr() to get ethertype to account for VLANs. */
5977 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5978 skb_mod_eth_type(skb, hdr, next_proto);
5980 skb->protocol = next_proto;
5984 EXPORT_SYMBOL_GPL(skb_mpls_pop);
5987 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
5990 * @mpls_lse: new MPLS label stack entry to update to
5992 * Expects skb->data at mac header.
5994 * Returns 0 on success, -errno otherwise.
5996 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6000 if (unlikely(!eth_p_mpls(skb->protocol)))
6003 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6007 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6008 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6010 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6013 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6017 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6020 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6024 * Expects skb->data at mac header.
6026 * Returns 0 on success, -errno otherwise.
6028 int skb_mpls_dec_ttl(struct sk_buff *skb)
6033 if (unlikely(!eth_p_mpls(skb->protocol)))
6036 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6039 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6040 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6044 lse &= ~MPLS_LS_TTL_MASK;
6045 lse |= ttl << MPLS_LS_TTL_SHIFT;
6047 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6049 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6052 * alloc_skb_with_frags - allocate skb with page frags
6054 * @header_len: size of linear part
6055 * @data_len: needed length in frags
6056 * @max_page_order: max page order desired.
6057 * @errcode: pointer to error code if any
6058 * @gfp_mask: allocation mask
6060 * This can be used to allocate a paged skb, given a maximal order for frags.
6062 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6063 unsigned long data_len,
6068 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6069 unsigned long chunk;
6070 struct sk_buff *skb;
6074 *errcode = -EMSGSIZE;
6075 /* Note this test could be relaxed, if we succeed to allocate
6076 * high order pages...
6078 if (npages > MAX_SKB_FRAGS)
6081 *errcode = -ENOBUFS;
6082 skb = alloc_skb(header_len, gfp_mask);
6086 skb->truesize += npages << PAGE_SHIFT;
6088 for (i = 0; npages > 0; i++) {
6089 int order = max_page_order;
6092 if (npages >= 1 << order) {
6093 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6099 /* Do not retry other high order allocations */
6105 page = alloc_page(gfp_mask);
6109 chunk = min_t(unsigned long, data_len,
6110 PAGE_SIZE << order);
6111 skb_fill_page_desc(skb, i, page, 0, chunk);
6113 npages -= 1 << order;
6121 EXPORT_SYMBOL(alloc_skb_with_frags);
6123 /* carve out the first off bytes from skb when off < headlen */
6124 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6125 const int headlen, gfp_t gfp_mask)
6128 int size = skb_end_offset(skb);
6129 int new_hlen = headlen - off;
6132 size = SKB_DATA_ALIGN(size);
6134 if (skb_pfmemalloc(skb))
6135 gfp_mask |= __GFP_MEMALLOC;
6136 data = kmalloc_reserve(size +
6137 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6138 gfp_mask, NUMA_NO_NODE, NULL);
6142 size = SKB_WITH_OVERHEAD(ksize(data));
6144 /* Copy real data, and all frags */
6145 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6148 memcpy((struct skb_shared_info *)(data + size),
6150 offsetof(struct skb_shared_info,
6151 frags[skb_shinfo(skb)->nr_frags]));
6152 if (skb_cloned(skb)) {
6153 /* drop the old head gracefully */
6154 if (skb_orphan_frags(skb, gfp_mask)) {
6158 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6159 skb_frag_ref(skb, i);
6160 if (skb_has_frag_list(skb))
6161 skb_clone_fraglist(skb);
6162 skb_release_data(skb);
6164 /* we can reuse existing recount- all we did was
6173 #ifdef NET_SKBUFF_DATA_USES_OFFSET
6176 skb->end = skb->head + size;
6178 skb_set_tail_pointer(skb, skb_headlen(skb));
6179 skb_headers_offset_update(skb, 0);
6183 atomic_set(&skb_shinfo(skb)->dataref, 1);
6188 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6190 /* carve out the first eat bytes from skb's frag_list. May recurse into
6193 static int pskb_carve_frag_list(struct sk_buff *skb,
6194 struct skb_shared_info *shinfo, int eat,
6197 struct sk_buff *list = shinfo->frag_list;
6198 struct sk_buff *clone = NULL;
6199 struct sk_buff *insp = NULL;
6203 pr_err("Not enough bytes to eat. Want %d\n", eat);
6206 if (list->len <= eat) {
6207 /* Eaten as whole. */
6212 /* Eaten partially. */
6213 if (skb_shared(list)) {
6214 clone = skb_clone(list, gfp_mask);
6220 /* This may be pulled without problems. */
6223 if (pskb_carve(list, eat, gfp_mask) < 0) {
6231 /* Free pulled out fragments. */
6232 while ((list = shinfo->frag_list) != insp) {
6233 shinfo->frag_list = list->next;
6236 /* And insert new clone at head. */
6239 shinfo->frag_list = clone;
6244 /* carve off first len bytes from skb. Split line (off) is in the
6245 * non-linear part of skb
6247 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6248 int pos, gfp_t gfp_mask)
6251 int size = skb_end_offset(skb);
6253 const int nfrags = skb_shinfo(skb)->nr_frags;
6254 struct skb_shared_info *shinfo;
6256 size = SKB_DATA_ALIGN(size);
6258 if (skb_pfmemalloc(skb))
6259 gfp_mask |= __GFP_MEMALLOC;
6260 data = kmalloc_reserve(size +
6261 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6262 gfp_mask, NUMA_NO_NODE, NULL);
6266 size = SKB_WITH_OVERHEAD(ksize(data));
6268 memcpy((struct skb_shared_info *)(data + size),
6269 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6270 if (skb_orphan_frags(skb, gfp_mask)) {
6274 shinfo = (struct skb_shared_info *)(data + size);
6275 for (i = 0; i < nfrags; i++) {
6276 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6278 if (pos + fsize > off) {
6279 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6283 * We have two variants in this case:
6284 * 1. Move all the frag to the second
6285 * part, if it is possible. F.e.
6286 * this approach is mandatory for TUX,
6287 * where splitting is expensive.
6288 * 2. Split is accurately. We make this.
6290 skb_frag_off_add(&shinfo->frags[0], off - pos);
6291 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6293 skb_frag_ref(skb, i);
6298 shinfo->nr_frags = k;
6299 if (skb_has_frag_list(skb))
6300 skb_clone_fraglist(skb);
6302 /* split line is in frag list */
6303 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6304 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6305 if (skb_has_frag_list(skb))
6306 kfree_skb_list(skb_shinfo(skb)->frag_list);
6310 skb_release_data(skb);
6315 #ifdef NET_SKBUFF_DATA_USES_OFFSET
6318 skb->end = skb->head + size;
6320 skb_reset_tail_pointer(skb);
6321 skb_headers_offset_update(skb, 0);
6326 skb->data_len = skb->len;
6327 atomic_set(&skb_shinfo(skb)->dataref, 1);
6331 /* remove len bytes from the beginning of the skb */
6332 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6334 int headlen = skb_headlen(skb);
6337 return pskb_carve_inside_header(skb, len, headlen, gfp);
6339 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6342 /* Extract to_copy bytes starting at off from skb, and return this in
6345 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6346 int to_copy, gfp_t gfp)
6348 struct sk_buff *clone = skb_clone(skb, gfp);
6353 if (pskb_carve(clone, off, gfp) < 0 ||
6354 pskb_trim(clone, to_copy)) {
6360 EXPORT_SYMBOL(pskb_extract);
6363 * skb_condense - try to get rid of fragments/frag_list if possible
6366 * Can be used to save memory before skb is added to a busy queue.
6367 * If packet has bytes in frags and enough tail room in skb->head,
6368 * pull all of them, so that we can free the frags right now and adjust
6371 * We do not reallocate skb->head thus can not fail.
6372 * Caller must re-evaluate skb->truesize if needed.
6374 void skb_condense(struct sk_buff *skb)
6376 if (skb->data_len) {
6377 if (skb->data_len > skb->end - skb->tail ||
6381 /* Nice, we can free page frag(s) right now */
6382 __pskb_pull_tail(skb, skb->data_len);
6384 /* At this point, skb->truesize might be over estimated,
6385 * because skb had a fragment, and fragments do not tell
6387 * When we pulled its content into skb->head, fragment
6388 * was freed, but __pskb_pull_tail() could not possibly
6389 * adjust skb->truesize, not knowing the frag truesize.
6391 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6394 #ifdef CONFIG_SKB_EXTENSIONS
6395 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6397 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6401 * __skb_ext_alloc - allocate a new skb extensions storage
6403 * @flags: See kmalloc().
6405 * Returns the newly allocated pointer. The pointer can later attached to a
6406 * skb via __skb_ext_set().
6407 * Note: caller must handle the skb_ext as an opaque data.
6409 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6411 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6414 memset(new->offset, 0, sizeof(new->offset));
6415 refcount_set(&new->refcnt, 1);
6421 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6422 unsigned int old_active)
6424 struct skb_ext *new;
6426 if (refcount_read(&old->refcnt) == 1)
6429 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6433 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6434 refcount_set(&new->refcnt, 1);
6437 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6438 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6441 for (i = 0; i < sp->len; i++)
6442 xfrm_state_hold(sp->xvec[i]);
6450 * __skb_ext_set - attach the specified extension storage to this skb
6453 * @ext: extension storage previously allocated via __skb_ext_alloc()
6455 * Existing extensions, if any, are cleared.
6457 * Returns the pointer to the extension.
6459 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6460 struct skb_ext *ext)
6462 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6465 newlen = newoff + skb_ext_type_len[id];
6466 ext->chunks = newlen;
6467 ext->offset[id] = newoff;
6468 skb->extensions = ext;
6469 skb->active_extensions = 1 << id;
6470 return skb_ext_get_ptr(ext, id);
6474 * skb_ext_add - allocate space for given extension, COW if needed
6476 * @id: extension to allocate space for
6478 * Allocates enough space for the given extension.
6479 * If the extension is already present, a pointer to that extension
6482 * If the skb was cloned, COW applies and the returned memory can be
6483 * modified without changing the extension space of clones buffers.
6485 * Returns pointer to the extension or NULL on allocation failure.
6487 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6489 struct skb_ext *new, *old = NULL;
6490 unsigned int newlen, newoff;
6492 if (skb->active_extensions) {
6493 old = skb->extensions;
6495 new = skb_ext_maybe_cow(old, skb->active_extensions);
6499 if (__skb_ext_exist(new, id))
6502 newoff = new->chunks;
6504 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6506 new = __skb_ext_alloc(GFP_ATOMIC);
6511 newlen = newoff + skb_ext_type_len[id];
6512 new->chunks = newlen;
6513 new->offset[id] = newoff;
6516 skb->extensions = new;
6517 skb->active_extensions |= 1 << id;
6518 return skb_ext_get_ptr(new, id);
6520 EXPORT_SYMBOL(skb_ext_add);
6523 static void skb_ext_put_sp(struct sec_path *sp)
6527 for (i = 0; i < sp->len; i++)
6528 xfrm_state_put(sp->xvec[i]);
6532 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6534 struct skb_ext *ext = skb->extensions;
6536 skb->active_extensions &= ~(1 << id);
6537 if (skb->active_extensions == 0) {
6538 skb->extensions = NULL;
6541 } else if (id == SKB_EXT_SEC_PATH &&
6542 refcount_read(&ext->refcnt) == 1) {
6543 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6550 EXPORT_SYMBOL(__skb_ext_del);
6552 void __skb_ext_put(struct skb_ext *ext)
6554 /* If this is last clone, nothing can increment
6555 * it after check passes. Avoids one atomic op.
6557 if (refcount_read(&ext->refcnt) == 1)
6560 if (!refcount_dec_and_test(&ext->refcnt))
6564 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6565 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6568 kmem_cache_free(skbuff_ext_cache, ext);
6570 EXPORT_SYMBOL(__skb_ext_put);
6571 #endif /* CONFIG_SKB_EXTENSIONS */