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 static void *__alloc_frag_align(unsigned int fragsz, gfp_t gfp_mask,
139 unsigned int align_mask)
141 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
143 return page_frag_alloc_align(&nc->page, fragsz, gfp_mask, align_mask);
146 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
148 fragsz = SKB_DATA_ALIGN(fragsz);
150 return __alloc_frag_align(fragsz, GFP_ATOMIC, align_mask);
152 EXPORT_SYMBOL(__napi_alloc_frag_align);
154 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
156 struct page_frag_cache *nc;
159 fragsz = SKB_DATA_ALIGN(fragsz);
160 if (in_hardirq() || irqs_disabled()) {
161 nc = this_cpu_ptr(&netdev_alloc_cache);
162 data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
165 data = __alloc_frag_align(fragsz, GFP_ATOMIC, align_mask);
170 EXPORT_SYMBOL(__netdev_alloc_frag_align);
172 static struct sk_buff *napi_skb_cache_get(void)
174 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
177 if (unlikely(!nc->skb_count))
178 nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
182 if (unlikely(!nc->skb_count))
185 skb = nc->skb_cache[--nc->skb_count];
186 kasan_unpoison_object_data(skbuff_head_cache, skb);
191 /* Caller must provide SKB that is memset cleared */
192 static void __build_skb_around(struct sk_buff *skb, void *data,
193 unsigned int frag_size)
195 struct skb_shared_info *shinfo;
196 unsigned int size = frag_size ? : ksize(data);
198 size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
200 /* Assumes caller memset cleared SKB */
201 skb->truesize = SKB_TRUESIZE(size);
202 refcount_set(&skb->users, 1);
205 skb_reset_tail_pointer(skb);
206 skb_set_end_offset(skb, size);
207 skb->mac_header = (typeof(skb->mac_header))~0U;
208 skb->transport_header = (typeof(skb->transport_header))~0U;
210 /* make sure we initialize shinfo sequentially */
211 shinfo = skb_shinfo(skb);
212 memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
213 atomic_set(&shinfo->dataref, 1);
215 skb_set_kcov_handle(skb, kcov_common_handle());
219 * __build_skb - build a network buffer
220 * @data: data buffer provided by caller
221 * @frag_size: size of data, or 0 if head was kmalloced
223 * Allocate a new &sk_buff. Caller provides space holding head and
224 * skb_shared_info. @data must have been allocated by kmalloc() only if
225 * @frag_size is 0, otherwise data should come from the page allocator
227 * The return is the new skb buffer.
228 * On a failure the return is %NULL, and @data is not freed.
230 * Before IO, driver allocates only data buffer where NIC put incoming frame
231 * Driver should add room at head (NET_SKB_PAD) and
232 * MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
233 * After IO, driver calls build_skb(), to allocate sk_buff and populate it
234 * before giving packet to stack.
235 * RX rings only contains data buffers, not full skbs.
237 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
241 skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
245 memset(skb, 0, offsetof(struct sk_buff, tail));
246 __build_skb_around(skb, data, frag_size);
251 /* build_skb() is wrapper over __build_skb(), that specifically
252 * takes care of skb->head and skb->pfmemalloc
253 * This means that if @frag_size is not zero, then @data must be backed
254 * by a page fragment, not kmalloc() or vmalloc()
256 struct sk_buff *build_skb(void *data, unsigned int frag_size)
258 struct sk_buff *skb = __build_skb(data, frag_size);
260 if (skb && frag_size) {
262 if (page_is_pfmemalloc(virt_to_head_page(data)))
267 EXPORT_SYMBOL(build_skb);
270 * build_skb_around - build a network buffer around provided skb
271 * @skb: sk_buff provide by caller, must be memset cleared
272 * @data: data buffer provided by caller
273 * @frag_size: size of data, or 0 if head was kmalloced
275 struct sk_buff *build_skb_around(struct sk_buff *skb,
276 void *data, unsigned int frag_size)
281 __build_skb_around(skb, data, frag_size);
285 if (page_is_pfmemalloc(virt_to_head_page(data)))
290 EXPORT_SYMBOL(build_skb_around);
293 * __napi_build_skb - build a network buffer
294 * @data: data buffer provided by caller
295 * @frag_size: size of data, or 0 if head was kmalloced
297 * Version of __build_skb() that uses NAPI percpu caches to obtain
298 * skbuff_head instead of inplace allocation.
300 * Returns a new &sk_buff on success, %NULL on allocation failure.
302 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
306 skb = napi_skb_cache_get();
310 memset(skb, 0, offsetof(struct sk_buff, tail));
311 __build_skb_around(skb, data, frag_size);
317 * napi_build_skb - build a network buffer
318 * @data: data buffer provided by caller
319 * @frag_size: size of data, or 0 if head was kmalloced
321 * Version of __napi_build_skb() that takes care of skb->head_frag
322 * and skb->pfmemalloc when the data is a page or page fragment.
324 * Returns a new &sk_buff on success, %NULL on allocation failure.
326 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
328 struct sk_buff *skb = __napi_build_skb(data, frag_size);
330 if (likely(skb) && frag_size) {
332 skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
337 EXPORT_SYMBOL(napi_build_skb);
340 * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
341 * the caller if emergency pfmemalloc reserves are being used. If it is and
342 * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
343 * may be used. Otherwise, the packet data may be discarded until enough
346 static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
350 bool ret_pfmemalloc = false;
353 * Try a regular allocation, when that fails and we're not entitled
354 * to the reserves, fail.
356 obj = kmalloc_node_track_caller(size,
357 flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
359 if (obj || !(gfp_pfmemalloc_allowed(flags)))
362 /* Try again but now we are using pfmemalloc reserves */
363 ret_pfmemalloc = true;
364 obj = kmalloc_node_track_caller(size, flags, node);
368 *pfmemalloc = ret_pfmemalloc;
373 /* Allocate a new skbuff. We do this ourselves so we can fill in a few
374 * 'private' fields and also do memory statistics to find all the
380 * __alloc_skb - allocate a network buffer
381 * @size: size to allocate
382 * @gfp_mask: allocation mask
383 * @flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
384 * instead of head cache and allocate a cloned (child) skb.
385 * If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
386 * allocations in case the data is required for writeback
387 * @node: numa node to allocate memory on
389 * Allocate a new &sk_buff. The returned buffer has no headroom and a
390 * tail room of at least size bytes. The object has a reference count
391 * of one. The return is the buffer. On a failure the return is %NULL.
393 * Buffers may only be allocated from interrupts using a @gfp_mask of
396 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
399 struct kmem_cache *cache;
404 cache = (flags & SKB_ALLOC_FCLONE)
405 ? skbuff_fclone_cache : skbuff_head_cache;
407 if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
408 gfp_mask |= __GFP_MEMALLOC;
411 if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
412 likely(node == NUMA_NO_NODE || node == numa_mem_id()))
413 skb = napi_skb_cache_get();
415 skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
420 /* We do our best to align skb_shared_info on a separate cache
421 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
422 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
423 * Both skb->head and skb_shared_info are cache line aligned.
425 size = SKB_DATA_ALIGN(size);
426 size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
427 data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
430 /* kmalloc(size) might give us more room than requested.
431 * Put skb_shared_info exactly at the end of allocated zone,
432 * to allow max possible filling before reallocation.
434 size = SKB_WITH_OVERHEAD(ksize(data));
435 prefetchw(data + size);
438 * Only clear those fields we need to clear, not those that we will
439 * actually initialise below. Hence, don't put any more fields after
440 * the tail pointer in struct sk_buff!
442 memset(skb, 0, offsetof(struct sk_buff, tail));
443 __build_skb_around(skb, data, 0);
444 skb->pfmemalloc = pfmemalloc;
446 if (flags & SKB_ALLOC_FCLONE) {
447 struct sk_buff_fclones *fclones;
449 fclones = container_of(skb, struct sk_buff_fclones, skb1);
451 skb->fclone = SKB_FCLONE_ORIG;
452 refcount_set(&fclones->fclone_ref, 1);
454 fclones->skb2.fclone = SKB_FCLONE_CLONE;
460 kmem_cache_free(cache, skb);
463 EXPORT_SYMBOL(__alloc_skb);
466 * __netdev_alloc_skb - allocate an skbuff for rx on a specific device
467 * @dev: network device to receive on
468 * @len: length to allocate
469 * @gfp_mask: get_free_pages mask, passed to alloc_skb
471 * Allocate a new &sk_buff and assign it a usage count of one. The
472 * buffer has NET_SKB_PAD headroom built in. Users should allocate
473 * the headroom they think they need without accounting for the
474 * built in space. The built in space is used for optimisations.
476 * %NULL is returned if there is no free memory.
478 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
481 struct page_frag_cache *nc;
488 /* If requested length is either too small or too big,
489 * we use kmalloc() for skb->head allocation.
491 if (len <= SKB_WITH_OVERHEAD(1024) ||
492 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
493 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
494 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
500 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
501 len = SKB_DATA_ALIGN(len);
503 if (sk_memalloc_socks())
504 gfp_mask |= __GFP_MEMALLOC;
506 if (in_hardirq() || irqs_disabled()) {
507 nc = this_cpu_ptr(&netdev_alloc_cache);
508 data = page_frag_alloc(nc, len, gfp_mask);
509 pfmemalloc = nc->pfmemalloc;
512 nc = this_cpu_ptr(&napi_alloc_cache.page);
513 data = page_frag_alloc(nc, len, gfp_mask);
514 pfmemalloc = nc->pfmemalloc;
521 skb = __build_skb(data, len);
522 if (unlikely(!skb)) {
532 skb_reserve(skb, NET_SKB_PAD);
538 EXPORT_SYMBOL(__netdev_alloc_skb);
541 * __napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
542 * @napi: napi instance this buffer was allocated for
543 * @len: length to allocate
544 * @gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
546 * Allocate a new sk_buff for use in NAPI receive. This buffer will
547 * attempt to allocate the head from a special reserved region used
548 * only for NAPI Rx allocation. By doing this we can save several
549 * CPU cycles by avoiding having to disable and re-enable IRQs.
551 * %NULL is returned if there is no free memory.
553 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
556 struct napi_alloc_cache *nc;
560 len += NET_SKB_PAD + NET_IP_ALIGN;
562 /* If requested length is either too small or too big,
563 * we use kmalloc() for skb->head allocation.
565 if (len <= SKB_WITH_OVERHEAD(1024) ||
566 len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
567 (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
568 skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
575 nc = this_cpu_ptr(&napi_alloc_cache);
576 len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
577 len = SKB_DATA_ALIGN(len);
579 if (sk_memalloc_socks())
580 gfp_mask |= __GFP_MEMALLOC;
582 data = page_frag_alloc(&nc->page, len, gfp_mask);
586 skb = __napi_build_skb(data, len);
587 if (unlikely(!skb)) {
592 if (nc->page.pfmemalloc)
597 skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
598 skb->dev = napi->dev;
603 EXPORT_SYMBOL(__napi_alloc_skb);
605 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
606 int size, unsigned int truesize)
608 skb_fill_page_desc(skb, i, page, off, size);
610 skb->data_len += size;
611 skb->truesize += truesize;
613 EXPORT_SYMBOL(skb_add_rx_frag);
615 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
616 unsigned int truesize)
618 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
620 skb_frag_size_add(frag, size);
622 skb->data_len += size;
623 skb->truesize += truesize;
625 EXPORT_SYMBOL(skb_coalesce_rx_frag);
627 static void skb_drop_list(struct sk_buff **listp)
629 kfree_skb_list(*listp);
633 static inline void skb_drop_fraglist(struct sk_buff *skb)
635 skb_drop_list(&skb_shinfo(skb)->frag_list);
638 static void skb_clone_fraglist(struct sk_buff *skb)
640 struct sk_buff *list;
642 skb_walk_frags(skb, list)
646 static void skb_free_head(struct sk_buff *skb)
648 unsigned char *head = skb->head;
650 if (skb->head_frag) {
651 if (skb_pp_recycle(skb, head))
659 static void skb_release_data(struct sk_buff *skb)
661 struct skb_shared_info *shinfo = skb_shinfo(skb);
665 atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
669 skb_zcopy_clear(skb, true);
671 for (i = 0; i < shinfo->nr_frags; i++)
672 __skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
674 if (shinfo->frag_list)
675 kfree_skb_list(shinfo->frag_list);
679 /* When we clone an SKB we copy the reycling bit. The pp_recycle
680 * bit is only set on the head though, so in order to avoid races
681 * while trying to recycle fragments on __skb_frag_unref() we need
682 * to make one SKB responsible for triggering the recycle path.
683 * So disable the recycling bit if an SKB is cloned and we have
684 * additional references to to the fragmented part of the SKB.
685 * Eventually the last SKB will have the recycling bit set and it's
686 * dataref set to 0, which will trigger the recycling
692 * Free an skbuff by memory without cleaning the state.
694 static void kfree_skbmem(struct sk_buff *skb)
696 struct sk_buff_fclones *fclones;
698 switch (skb->fclone) {
699 case SKB_FCLONE_UNAVAILABLE:
700 kmem_cache_free(skbuff_head_cache, skb);
703 case SKB_FCLONE_ORIG:
704 fclones = container_of(skb, struct sk_buff_fclones, skb1);
706 /* We usually free the clone (TX completion) before original skb
707 * This test would have no chance to be true for the clone,
708 * while here, branch prediction will be good.
710 if (refcount_read(&fclones->fclone_ref) == 1)
714 default: /* SKB_FCLONE_CLONE */
715 fclones = container_of(skb, struct sk_buff_fclones, skb2);
718 if (!refcount_dec_and_test(&fclones->fclone_ref))
721 kmem_cache_free(skbuff_fclone_cache, fclones);
724 void skb_release_head_state(struct sk_buff *skb)
727 if (skb->destructor) {
728 WARN_ON(in_hardirq());
729 skb->destructor(skb);
731 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
732 nf_conntrack_put(skb_nfct(skb));
737 /* Free everything but the sk_buff shell. */
738 static void skb_release_all(struct sk_buff *skb)
740 skb_release_head_state(skb);
741 if (likely(skb->head))
742 skb_release_data(skb);
746 * __kfree_skb - private function
749 * Free an sk_buff. Release anything attached to the buffer.
750 * Clean the state. This is an internal helper function. Users should
751 * always call kfree_skb
754 void __kfree_skb(struct sk_buff *skb)
756 skb_release_all(skb);
759 EXPORT_SYMBOL(__kfree_skb);
762 * kfree_skb - free an sk_buff
763 * @skb: buffer to free
765 * Drop a reference to the buffer and free it if the usage count has
768 void kfree_skb(struct sk_buff *skb)
773 trace_kfree_skb(skb, __builtin_return_address(0));
776 EXPORT_SYMBOL(kfree_skb);
778 void kfree_skb_list(struct sk_buff *segs)
781 struct sk_buff *next = segs->next;
787 EXPORT_SYMBOL(kfree_skb_list);
789 /* Dump skb information and contents.
791 * Must only be called from net_ratelimit()-ed paths.
793 * Dumps whole packets if full_pkt, only headers otherwise.
795 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
797 struct skb_shared_info *sh = skb_shinfo(skb);
798 struct net_device *dev = skb->dev;
799 struct sock *sk = skb->sk;
800 struct sk_buff *list_skb;
801 bool has_mac, has_trans;
802 int headroom, tailroom;
808 len = min_t(int, skb->len, MAX_HEADER + 128);
810 headroom = skb_headroom(skb);
811 tailroom = skb_tailroom(skb);
813 has_mac = skb_mac_header_was_set(skb);
814 has_trans = skb_transport_header_was_set(skb);
816 printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
817 "mac=(%d,%d) net=(%d,%d) trans=%d\n"
818 "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
819 "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
820 "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
821 level, skb->len, headroom, skb_headlen(skb), tailroom,
822 has_mac ? skb->mac_header : -1,
823 has_mac ? skb_mac_header_len(skb) : -1,
825 has_trans ? skb_network_header_len(skb) : -1,
826 has_trans ? skb->transport_header : -1,
827 sh->tx_flags, sh->nr_frags,
828 sh->gso_size, sh->gso_type, sh->gso_segs,
829 skb->csum, skb->ip_summed, skb->csum_complete_sw,
830 skb->csum_valid, skb->csum_level,
831 skb->hash, skb->sw_hash, skb->l4_hash,
832 ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
835 printk("%sdev name=%s feat=%pNF\n",
836 level, dev->name, &dev->features);
838 printk("%ssk family=%hu type=%u proto=%u\n",
839 level, sk->sk_family, sk->sk_type, sk->sk_protocol);
841 if (full_pkt && headroom)
842 print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
843 16, 1, skb->head, headroom, false);
845 seg_len = min_t(int, skb_headlen(skb), len);
847 print_hex_dump(level, "skb linear: ", DUMP_PREFIX_OFFSET,
848 16, 1, skb->data, seg_len, false);
851 if (full_pkt && tailroom)
852 print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
853 16, 1, skb_tail_pointer(skb), tailroom, false);
855 for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
856 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
857 u32 p_off, p_len, copied;
861 skb_frag_foreach_page(frag, skb_frag_off(frag),
862 skb_frag_size(frag), p, p_off, p_len,
864 seg_len = min_t(int, p_len, len);
865 vaddr = kmap_atomic(p);
866 print_hex_dump(level, "skb frag: ",
868 16, 1, vaddr + p_off, seg_len, false);
869 kunmap_atomic(vaddr);
876 if (full_pkt && skb_has_frag_list(skb)) {
877 printk("skb fraglist:\n");
878 skb_walk_frags(skb, list_skb)
879 skb_dump(level, list_skb, true);
882 EXPORT_SYMBOL(skb_dump);
885 * skb_tx_error - report an sk_buff xmit error
886 * @skb: buffer that triggered an error
888 * Report xmit error if a device callback is tracking this skb.
889 * skb must be freed afterwards.
891 void skb_tx_error(struct sk_buff *skb)
893 skb_zcopy_clear(skb, true);
895 EXPORT_SYMBOL(skb_tx_error);
897 #ifdef CONFIG_TRACEPOINTS
899 * consume_skb - free an skbuff
900 * @skb: buffer to free
902 * Drop a ref to the buffer and free it if the usage count has hit zero
903 * Functions identically to kfree_skb, but kfree_skb assumes that the frame
904 * is being dropped after a failure and notes that
906 void consume_skb(struct sk_buff *skb)
911 trace_consume_skb(skb);
914 EXPORT_SYMBOL(consume_skb);
918 * __consume_stateless_skb - free an skbuff, assuming it is stateless
919 * @skb: buffer to free
921 * Alike consume_skb(), but this variant assumes that this is the last
922 * skb reference and all the head states have been already dropped
924 void __consume_stateless_skb(struct sk_buff *skb)
926 trace_consume_skb(skb);
927 skb_release_data(skb);
931 static void napi_skb_cache_put(struct sk_buff *skb)
933 struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
936 kasan_poison_object_data(skbuff_head_cache, skb);
937 nc->skb_cache[nc->skb_count++] = skb;
939 if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
940 for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
941 kasan_unpoison_object_data(skbuff_head_cache,
944 kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
945 nc->skb_cache + NAPI_SKB_CACHE_HALF);
946 nc->skb_count = NAPI_SKB_CACHE_HALF;
950 void __kfree_skb_defer(struct sk_buff *skb)
952 skb_release_all(skb);
953 napi_skb_cache_put(skb);
956 void napi_skb_free_stolen_head(struct sk_buff *skb)
958 if (unlikely(skb->slow_gro)) {
965 napi_skb_cache_put(skb);
968 void napi_consume_skb(struct sk_buff *skb, int budget)
970 /* Zero budget indicate non-NAPI context called us, like netpoll */
971 if (unlikely(!budget)) {
972 dev_consume_skb_any(skb);
976 lockdep_assert_in_softirq();
981 /* if reaching here SKB is ready to free */
982 trace_consume_skb(skb);
984 /* if SKB is a clone, don't handle this case */
985 if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
990 skb_release_all(skb);
991 napi_skb_cache_put(skb);
993 EXPORT_SYMBOL(napi_consume_skb);
995 /* Make sure a field is enclosed inside headers_start/headers_end section */
996 #define CHECK_SKB_FIELD(field) \
997 BUILD_BUG_ON(offsetof(struct sk_buff, field) < \
998 offsetof(struct sk_buff, headers_start)); \
999 BUILD_BUG_ON(offsetof(struct sk_buff, field) > \
1000 offsetof(struct sk_buff, headers_end)); \
1002 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1004 new->tstamp = old->tstamp;
1005 /* We do not copy old->sk */
1006 new->dev = old->dev;
1007 memcpy(new->cb, old->cb, sizeof(old->cb));
1008 skb_dst_copy(new, old);
1009 __skb_ext_copy(new, old);
1010 __nf_copy(new, old, false);
1012 /* Note : this field could be in headers_start/headers_end section
1013 * It is not yet because we do not want to have a 16 bit hole
1015 new->queue_mapping = old->queue_mapping;
1017 memcpy(&new->headers_start, &old->headers_start,
1018 offsetof(struct sk_buff, headers_end) -
1019 offsetof(struct sk_buff, headers_start));
1020 CHECK_SKB_FIELD(protocol);
1021 CHECK_SKB_FIELD(csum);
1022 CHECK_SKB_FIELD(hash);
1023 CHECK_SKB_FIELD(priority);
1024 CHECK_SKB_FIELD(skb_iif);
1025 CHECK_SKB_FIELD(vlan_proto);
1026 CHECK_SKB_FIELD(vlan_tci);
1027 CHECK_SKB_FIELD(transport_header);
1028 CHECK_SKB_FIELD(network_header);
1029 CHECK_SKB_FIELD(mac_header);
1030 CHECK_SKB_FIELD(inner_protocol);
1031 CHECK_SKB_FIELD(inner_transport_header);
1032 CHECK_SKB_FIELD(inner_network_header);
1033 CHECK_SKB_FIELD(inner_mac_header);
1034 CHECK_SKB_FIELD(mark);
1035 #ifdef CONFIG_NETWORK_SECMARK
1036 CHECK_SKB_FIELD(secmark);
1038 #ifdef CONFIG_NET_RX_BUSY_POLL
1039 CHECK_SKB_FIELD(napi_id);
1042 CHECK_SKB_FIELD(sender_cpu);
1044 #ifdef CONFIG_NET_SCHED
1045 CHECK_SKB_FIELD(tc_index);
1051 * You should not add any new code to this function. Add it to
1052 * __copy_skb_header above instead.
1054 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1056 #define C(x) n->x = skb->x
1058 n->next = n->prev = NULL;
1060 __copy_skb_header(n, skb);
1065 n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1071 n->destructor = NULL;
1078 refcount_set(&n->users, 1);
1080 atomic_inc(&(skb_shinfo(skb)->dataref));
1088 * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1089 * @first: first sk_buff of the msg
1091 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1095 n = alloc_skb(0, GFP_ATOMIC);
1099 n->len = first->len;
1100 n->data_len = first->len;
1101 n->truesize = first->truesize;
1103 skb_shinfo(n)->frag_list = first;
1105 __copy_skb_header(n, first);
1106 n->destructor = NULL;
1110 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1113 * skb_morph - morph one skb into another
1114 * @dst: the skb to receive the contents
1115 * @src: the skb to supply the contents
1117 * This is identical to skb_clone except that the target skb is
1118 * supplied by the user.
1120 * The target skb is returned upon exit.
1122 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1124 skb_release_all(dst);
1125 return __skb_clone(dst, src);
1127 EXPORT_SYMBOL_GPL(skb_morph);
1129 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1131 unsigned long max_pg, num_pg, new_pg, old_pg;
1132 struct user_struct *user;
1134 if (capable(CAP_IPC_LOCK) || !size)
1137 num_pg = (size >> PAGE_SHIFT) + 2; /* worst case */
1138 max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1139 user = mmp->user ? : current_user();
1142 old_pg = atomic_long_read(&user->locked_vm);
1143 new_pg = old_pg + num_pg;
1144 if (new_pg > max_pg)
1146 } while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1150 mmp->user = get_uid(user);
1151 mmp->num_pg = num_pg;
1153 mmp->num_pg += num_pg;
1158 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1160 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1163 atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1164 free_uid(mmp->user);
1167 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1169 struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1171 struct ubuf_info *uarg;
1172 struct sk_buff *skb;
1174 WARN_ON_ONCE(!in_task());
1176 skb = sock_omalloc(sk, 0, GFP_KERNEL);
1180 BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1181 uarg = (void *)skb->cb;
1182 uarg->mmp.user = NULL;
1184 if (mm_account_pinned_pages(&uarg->mmp, size)) {
1189 uarg->callback = msg_zerocopy_callback;
1190 uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1192 uarg->bytelen = size;
1194 uarg->flags = SKBFL_ZEROCOPY_FRAG;
1195 refcount_set(&uarg->refcnt, 1);
1200 EXPORT_SYMBOL_GPL(msg_zerocopy_alloc);
1202 static inline struct sk_buff *skb_from_uarg(struct ubuf_info *uarg)
1204 return container_of((void *)uarg, struct sk_buff, cb);
1207 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1208 struct ubuf_info *uarg)
1211 const u32 byte_limit = 1 << 19; /* limit to a few TSO */
1214 /* realloc only when socket is locked (TCP, UDP cork),
1215 * so uarg->len and sk_zckey access is serialized
1217 if (!sock_owned_by_user(sk)) {
1222 bytelen = uarg->bytelen + size;
1223 if (uarg->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1224 /* TCP can create new skb to attach new uarg */
1225 if (sk->sk_type == SOCK_STREAM)
1230 next = (u32)atomic_read(&sk->sk_zckey);
1231 if ((u32)(uarg->id + uarg->len) == next) {
1232 if (mm_account_pinned_pages(&uarg->mmp, size))
1235 uarg->bytelen = bytelen;
1236 atomic_set(&sk->sk_zckey, ++next);
1238 /* no extra ref when appending to datagram (MSG_MORE) */
1239 if (sk->sk_type == SOCK_STREAM)
1240 net_zcopy_get(uarg);
1247 return msg_zerocopy_alloc(sk, size);
1249 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1251 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1253 struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1257 old_lo = serr->ee.ee_info;
1258 old_hi = serr->ee.ee_data;
1259 sum_len = old_hi - old_lo + 1ULL + len;
1261 if (sum_len >= (1ULL << 32))
1264 if (lo != old_hi + 1)
1267 serr->ee.ee_data += len;
1271 static void __msg_zerocopy_callback(struct ubuf_info *uarg)
1273 struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1274 struct sock_exterr_skb *serr;
1275 struct sock *sk = skb->sk;
1276 struct sk_buff_head *q;
1277 unsigned long flags;
1282 mm_unaccount_pinned_pages(&uarg->mmp);
1284 /* if !len, there was only 1 call, and it was aborted
1285 * so do not queue a completion notification
1287 if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1292 hi = uarg->id + len - 1;
1293 is_zerocopy = uarg->zerocopy;
1295 serr = SKB_EXT_ERR(skb);
1296 memset(serr, 0, sizeof(*serr));
1297 serr->ee.ee_errno = 0;
1298 serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1299 serr->ee.ee_data = hi;
1300 serr->ee.ee_info = lo;
1302 serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1304 q = &sk->sk_error_queue;
1305 spin_lock_irqsave(&q->lock, flags);
1306 tail = skb_peek_tail(q);
1307 if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1308 !skb_zerocopy_notify_extend(tail, lo, len)) {
1309 __skb_queue_tail(q, skb);
1312 spin_unlock_irqrestore(&q->lock, flags);
1314 sk_error_report(sk);
1321 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1324 uarg->zerocopy = uarg->zerocopy & success;
1326 if (refcount_dec_and_test(&uarg->refcnt))
1327 __msg_zerocopy_callback(uarg);
1329 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1331 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1333 struct sock *sk = skb_from_uarg(uarg)->sk;
1335 atomic_dec(&sk->sk_zckey);
1339 msg_zerocopy_callback(NULL, uarg, true);
1341 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1343 int skb_zerocopy_iter_dgram(struct sk_buff *skb, struct msghdr *msg, int len)
1345 return __zerocopy_sg_from_iter(skb->sk, skb, &msg->msg_iter, len);
1347 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_dgram);
1349 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1350 struct msghdr *msg, int len,
1351 struct ubuf_info *uarg)
1353 struct ubuf_info *orig_uarg = skb_zcopy(skb);
1354 struct iov_iter orig_iter = msg->msg_iter;
1355 int err, orig_len = skb->len;
1357 /* An skb can only point to one uarg. This edge case happens when
1358 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1360 if (orig_uarg && uarg != orig_uarg)
1363 err = __zerocopy_sg_from_iter(sk, skb, &msg->msg_iter, len);
1364 if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1365 struct sock *save_sk = skb->sk;
1367 /* Streams do not free skb on error. Reset to prev state. */
1368 msg->msg_iter = orig_iter;
1370 ___pskb_trim(skb, orig_len);
1375 skb_zcopy_set(skb, uarg, NULL);
1376 return skb->len - orig_len;
1378 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1380 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1383 if (skb_zcopy(orig)) {
1384 if (skb_zcopy(nskb)) {
1385 /* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1390 if (skb_uarg(nskb) == skb_uarg(orig))
1392 if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1395 skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1401 * skb_copy_ubufs - copy userspace skb frags buffers to kernel
1402 * @skb: the skb to modify
1403 * @gfp_mask: allocation priority
1405 * This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1406 * It will copy all frags into kernel and drop the reference
1407 * to userspace pages.
1409 * If this function is called from an interrupt gfp_mask() must be
1412 * Returns 0 on success or a negative error code on failure
1413 * to allocate kernel memory to copy to.
1415 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1417 int num_frags = skb_shinfo(skb)->nr_frags;
1418 struct page *page, *head = NULL;
1422 if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1428 new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1429 for (i = 0; i < new_frags; i++) {
1430 page = alloc_page(gfp_mask);
1433 struct page *next = (struct page *)page_private(head);
1439 set_page_private(page, (unsigned long)head);
1445 for (i = 0; i < num_frags; i++) {
1446 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1447 u32 p_off, p_len, copied;
1451 skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1452 p, p_off, p_len, copied) {
1454 vaddr = kmap_atomic(p);
1456 while (done < p_len) {
1457 if (d_off == PAGE_SIZE) {
1459 page = (struct page *)page_private(page);
1461 copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1462 memcpy(page_address(page) + d_off,
1463 vaddr + p_off + done, copy);
1467 kunmap_atomic(vaddr);
1471 /* skb frags release userspace buffers */
1472 for (i = 0; i < num_frags; i++)
1473 skb_frag_unref(skb, i);
1475 /* skb frags point to kernel buffers */
1476 for (i = 0; i < new_frags - 1; i++) {
1477 __skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1478 head = (struct page *)page_private(head);
1480 __skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1481 skb_shinfo(skb)->nr_frags = new_frags;
1484 skb_zcopy_clear(skb, false);
1487 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1490 * skb_clone - duplicate an sk_buff
1491 * @skb: buffer to clone
1492 * @gfp_mask: allocation priority
1494 * Duplicate an &sk_buff. The new one is not owned by a socket. Both
1495 * copies share the same packet data but not structure. The new
1496 * buffer has a reference count of 1. If the allocation fails the
1497 * function returns %NULL otherwise the new buffer is returned.
1499 * If this function is called from an interrupt gfp_mask() must be
1503 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1505 struct sk_buff_fclones *fclones = container_of(skb,
1506 struct sk_buff_fclones,
1510 if (skb_orphan_frags(skb, gfp_mask))
1513 if (skb->fclone == SKB_FCLONE_ORIG &&
1514 refcount_read(&fclones->fclone_ref) == 1) {
1516 refcount_set(&fclones->fclone_ref, 2);
1518 if (skb_pfmemalloc(skb))
1519 gfp_mask |= __GFP_MEMALLOC;
1521 n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1525 n->fclone = SKB_FCLONE_UNAVAILABLE;
1528 return __skb_clone(n, skb);
1530 EXPORT_SYMBOL(skb_clone);
1532 void skb_headers_offset_update(struct sk_buff *skb, int off)
1534 /* Only adjust this if it actually is csum_start rather than csum */
1535 if (skb->ip_summed == CHECKSUM_PARTIAL)
1536 skb->csum_start += off;
1537 /* {transport,network,mac}_header and tail are relative to skb->head */
1538 skb->transport_header += off;
1539 skb->network_header += off;
1540 if (skb_mac_header_was_set(skb))
1541 skb->mac_header += off;
1542 skb->inner_transport_header += off;
1543 skb->inner_network_header += off;
1544 skb->inner_mac_header += off;
1546 EXPORT_SYMBOL(skb_headers_offset_update);
1548 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1550 __copy_skb_header(new, old);
1552 skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1553 skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1554 skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1556 EXPORT_SYMBOL(skb_copy_header);
1558 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1560 if (skb_pfmemalloc(skb))
1561 return SKB_ALLOC_RX;
1566 * skb_copy - create private copy of an sk_buff
1567 * @skb: buffer to copy
1568 * @gfp_mask: allocation priority
1570 * Make a copy of both an &sk_buff and its data. This is used when the
1571 * caller wishes to modify the data and needs a private copy of the
1572 * data to alter. Returns %NULL on failure or the pointer to the buffer
1573 * on success. The returned buffer has a reference count of 1.
1575 * As by-product this function converts non-linear &sk_buff to linear
1576 * one, so that &sk_buff becomes completely private and caller is allowed
1577 * to modify all the data of returned buffer. This means that this
1578 * function is not recommended for use in circumstances when only
1579 * header is going to be modified. Use pskb_copy() instead.
1582 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1584 int headerlen = skb_headroom(skb);
1585 unsigned int size = skb_end_offset(skb) + skb->data_len;
1586 struct sk_buff *n = __alloc_skb(size, gfp_mask,
1587 skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1592 /* Set the data pointer */
1593 skb_reserve(n, headerlen);
1594 /* Set the tail pointer and length */
1595 skb_put(n, skb->len);
1597 BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1599 skb_copy_header(n, skb);
1602 EXPORT_SYMBOL(skb_copy);
1605 * __pskb_copy_fclone - create copy of an sk_buff with private head.
1606 * @skb: buffer to copy
1607 * @headroom: headroom of new skb
1608 * @gfp_mask: allocation priority
1609 * @fclone: if true allocate the copy of the skb from the fclone
1610 * cache instead of the head cache; it is recommended to set this
1611 * to true for the cases where the copy will likely be cloned
1613 * Make a copy of both an &sk_buff and part of its data, located
1614 * in header. Fragmented data remain shared. This is used when
1615 * the caller wishes to modify only header of &sk_buff and needs
1616 * private copy of the header to alter. Returns %NULL on failure
1617 * or the pointer to the buffer on success.
1618 * The returned buffer has a reference count of 1.
1621 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1622 gfp_t gfp_mask, bool fclone)
1624 unsigned int size = skb_headlen(skb) + headroom;
1625 int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1626 struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1631 /* Set the data pointer */
1632 skb_reserve(n, headroom);
1633 /* Set the tail pointer and length */
1634 skb_put(n, skb_headlen(skb));
1635 /* Copy the bytes */
1636 skb_copy_from_linear_data(skb, n->data, n->len);
1638 n->truesize += skb->data_len;
1639 n->data_len = skb->data_len;
1642 if (skb_shinfo(skb)->nr_frags) {
1645 if (skb_orphan_frags(skb, gfp_mask) ||
1646 skb_zerocopy_clone(n, skb, gfp_mask)) {
1651 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1652 skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1653 skb_frag_ref(skb, i);
1655 skb_shinfo(n)->nr_frags = i;
1658 if (skb_has_frag_list(skb)) {
1659 skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1660 skb_clone_fraglist(n);
1663 skb_copy_header(n, skb);
1667 EXPORT_SYMBOL(__pskb_copy_fclone);
1670 * pskb_expand_head - reallocate header of &sk_buff
1671 * @skb: buffer to reallocate
1672 * @nhead: room to add at head
1673 * @ntail: room to add at tail
1674 * @gfp_mask: allocation priority
1676 * Expands (or creates identical copy, if @nhead and @ntail are zero)
1677 * header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1678 * reference count of 1. Returns zero in the case of success or error,
1679 * if expansion failed. In the last case, &sk_buff is not changed.
1681 * All the pointers pointing into skb header may change and must be
1682 * reloaded after call to this function.
1685 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1688 int i, osize = skb_end_offset(skb);
1689 int size = osize + nhead + ntail;
1695 BUG_ON(skb_shared(skb));
1697 size = SKB_DATA_ALIGN(size);
1699 if (skb_pfmemalloc(skb))
1700 gfp_mask |= __GFP_MEMALLOC;
1701 data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1702 gfp_mask, NUMA_NO_NODE, NULL);
1705 size = SKB_WITH_OVERHEAD(ksize(data));
1707 /* Copy only real data... and, alas, header. This should be
1708 * optimized for the cases when header is void.
1710 memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
1712 memcpy((struct skb_shared_info *)(data + size),
1714 offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
1717 * if shinfo is shared we must drop the old head gracefully, but if it
1718 * is not we can just drop the old head and let the existing refcount
1719 * be since all we did is relocate the values
1721 if (skb_cloned(skb)) {
1722 if (skb_orphan_frags(skb, gfp_mask))
1725 refcount_inc(&skb_uarg(skb)->refcnt);
1726 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1727 skb_frag_ref(skb, i);
1729 if (skb_has_frag_list(skb))
1730 skb_clone_fraglist(skb);
1732 skb_release_data(skb);
1736 off = (data + nhead) - skb->head;
1742 skb_set_end_offset(skb, size);
1743 #ifdef NET_SKBUFF_DATA_USES_OFFSET
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);
1792 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
1794 unsigned int saved_end_offset, saved_truesize;
1795 struct skb_shared_info *shinfo;
1798 saved_end_offset = skb_end_offset(skb);
1799 saved_truesize = skb->truesize;
1801 res = pskb_expand_head(skb, 0, 0, pri);
1805 skb->truesize = saved_truesize;
1807 if (likely(skb_end_offset(skb) == saved_end_offset))
1810 shinfo = skb_shinfo(skb);
1812 /* We are about to change back skb->end,
1813 * we need to move skb_shinfo() to its new location.
1815 memmove(skb->head + saved_end_offset,
1817 offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
1819 skb_set_end_offset(skb, saved_end_offset);
1825 * skb_expand_head - reallocate header of &sk_buff
1826 * @skb: buffer to reallocate
1827 * @headroom: needed headroom
1829 * Unlike skb_realloc_headroom, this one does not allocate a new skb
1830 * if possible; copies skb->sk to new skb as needed
1831 * and frees original skb in case of failures.
1833 * It expect increased headroom and generates warning otherwise.
1836 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1838 int delta = headroom - skb_headroom(skb);
1839 int osize = skb_end_offset(skb);
1840 struct sock *sk = skb->sk;
1842 if (WARN_ONCE(delta <= 0,
1843 "%s is expecting an increase in the headroom", __func__))
1846 delta = SKB_DATA_ALIGN(delta);
1847 /* pskb_expand_head() might crash, if skb is shared. */
1848 if (skb_shared(skb) || !is_skb_wmem(skb)) {
1849 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1851 if (unlikely(!nskb))
1855 skb_set_owner_w(nskb, sk);
1859 if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
1862 if (sk && is_skb_wmem(skb)) {
1863 delta = skb_end_offset(skb) - osize;
1864 refcount_add(delta, &sk->sk_wmem_alloc);
1865 skb->truesize += delta;
1873 EXPORT_SYMBOL(skb_expand_head);
1876 * skb_copy_expand - copy and expand sk_buff
1877 * @skb: buffer to copy
1878 * @newheadroom: new free bytes at head
1879 * @newtailroom: new free bytes at tail
1880 * @gfp_mask: allocation priority
1882 * Make a copy of both an &sk_buff and its data and while doing so
1883 * allocate additional space.
1885 * This is used when the caller wishes to modify the data and needs a
1886 * private copy of the data to alter as well as more space for new fields.
1887 * Returns %NULL on failure or the pointer to the buffer
1888 * on success. The returned buffer has a reference count of 1.
1890 * You must pass %GFP_ATOMIC as the allocation priority if this function
1891 * is called from an interrupt.
1893 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
1894 int newheadroom, int newtailroom,
1898 * Allocate the copy buffer
1900 struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1901 gfp_mask, skb_alloc_rx_flag(skb),
1903 int oldheadroom = skb_headroom(skb);
1904 int head_copy_len, head_copy_off;
1909 skb_reserve(n, newheadroom);
1911 /* Set the tail pointer and length */
1912 skb_put(n, skb->len);
1914 head_copy_len = oldheadroom;
1916 if (newheadroom <= head_copy_len)
1917 head_copy_len = newheadroom;
1919 head_copy_off = newheadroom - head_copy_len;
1921 /* Copy the linear header and data. */
1922 BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
1923 skb->len + head_copy_len));
1925 skb_copy_header(n, skb);
1927 skb_headers_offset_update(n, newheadroom - oldheadroom);
1931 EXPORT_SYMBOL(skb_copy_expand);
1934 * __skb_pad - zero pad the tail of an skb
1935 * @skb: buffer to pad
1936 * @pad: space to pad
1937 * @free_on_error: free buffer on error
1939 * Ensure that a buffer is followed by a padding area that is zero
1940 * filled. Used by network drivers which may DMA or transfer data
1941 * beyond the buffer end onto the wire.
1943 * May return error in out of memory cases. The skb is freed on error
1944 * if @free_on_error is true.
1947 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
1952 /* If the skbuff is non linear tailroom is always zero.. */
1953 if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
1954 memset(skb->data+skb->len, 0, pad);
1958 ntail = skb->data_len + pad - (skb->end - skb->tail);
1959 if (likely(skb_cloned(skb) || ntail > 0)) {
1960 err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
1965 /* FIXME: The use of this function with non-linear skb's really needs
1968 err = skb_linearize(skb);
1972 memset(skb->data + skb->len, 0, pad);
1980 EXPORT_SYMBOL(__skb_pad);
1983 * pskb_put - add data to the tail of a potentially fragmented buffer
1984 * @skb: start of the buffer to use
1985 * @tail: tail fragment of the buffer to use
1986 * @len: amount of data to add
1988 * This function extends the used data area of the potentially
1989 * fragmented buffer. @tail must be the last fragment of @skb -- or
1990 * @skb itself. If this would exceed the total buffer size the kernel
1991 * will panic. A pointer to the first byte of the extra data is
1995 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
1998 skb->data_len += len;
2001 return skb_put(tail, len);
2003 EXPORT_SYMBOL_GPL(pskb_put);
2006 * skb_put - add data to a buffer
2007 * @skb: buffer to use
2008 * @len: amount of data to add
2010 * This function extends the used data area of the buffer. If this would
2011 * exceed the total buffer size the kernel will panic. A pointer to the
2012 * first byte of the extra data is returned.
2014 void *skb_put(struct sk_buff *skb, unsigned int len)
2016 void *tmp = skb_tail_pointer(skb);
2017 SKB_LINEAR_ASSERT(skb);
2020 if (unlikely(skb->tail > skb->end))
2021 skb_over_panic(skb, len, __builtin_return_address(0));
2024 EXPORT_SYMBOL(skb_put);
2027 * skb_push - add data to the start of a buffer
2028 * @skb: buffer to use
2029 * @len: amount of data to add
2031 * This function extends the used data area of the buffer at the buffer
2032 * start. If this would exceed the total buffer headroom the kernel will
2033 * panic. A pointer to the first byte of the extra data is returned.
2035 void *skb_push(struct sk_buff *skb, unsigned int len)
2039 if (unlikely(skb->data < skb->head))
2040 skb_under_panic(skb, len, __builtin_return_address(0));
2043 EXPORT_SYMBOL(skb_push);
2046 * skb_pull - remove data from the start of a buffer
2047 * @skb: buffer to use
2048 * @len: amount of data to remove
2050 * This function removes data from the start of a buffer, returning
2051 * the memory to the headroom. A pointer to the next data in the buffer
2052 * is returned. Once the data has been pulled future pushes will overwrite
2055 void *skb_pull(struct sk_buff *skb, unsigned int len)
2057 return skb_pull_inline(skb, len);
2059 EXPORT_SYMBOL(skb_pull);
2062 * skb_trim - remove end from a buffer
2063 * @skb: buffer to alter
2066 * Cut the length of a buffer down by removing data from the tail. If
2067 * the buffer is already under the length specified it is not modified.
2068 * The skb must be linear.
2070 void skb_trim(struct sk_buff *skb, unsigned int len)
2073 __skb_trim(skb, len);
2075 EXPORT_SYMBOL(skb_trim);
2077 /* Trims skb to length len. It can change skb pointers.
2080 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2082 struct sk_buff **fragp;
2083 struct sk_buff *frag;
2084 int offset = skb_headlen(skb);
2085 int nfrags = skb_shinfo(skb)->nr_frags;
2089 if (skb_cloned(skb) &&
2090 unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2097 for (; i < nfrags; i++) {
2098 int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2105 skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2108 skb_shinfo(skb)->nr_frags = i;
2110 for (; i < nfrags; i++)
2111 skb_frag_unref(skb, i);
2113 if (skb_has_frag_list(skb))
2114 skb_drop_fraglist(skb);
2118 for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2119 fragp = &frag->next) {
2120 int end = offset + frag->len;
2122 if (skb_shared(frag)) {
2123 struct sk_buff *nfrag;
2125 nfrag = skb_clone(frag, GFP_ATOMIC);
2126 if (unlikely(!nfrag))
2129 nfrag->next = frag->next;
2141 unlikely((err = pskb_trim(frag, len - offset))))
2145 skb_drop_list(&frag->next);
2150 if (len > skb_headlen(skb)) {
2151 skb->data_len -= skb->len - len;
2156 skb_set_tail_pointer(skb, len);
2159 if (!skb->sk || skb->destructor == sock_edemux)
2163 EXPORT_SYMBOL(___pskb_trim);
2165 /* Note : use pskb_trim_rcsum() instead of calling this directly
2167 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2169 if (skb->ip_summed == CHECKSUM_COMPLETE) {
2170 int delta = skb->len - len;
2172 skb->csum = csum_block_sub(skb->csum,
2173 skb_checksum(skb, len, delta, 0),
2175 } else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2176 int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2177 int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2179 if (offset + sizeof(__sum16) > hdlen)
2182 return __pskb_trim(skb, len);
2184 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2187 * __pskb_pull_tail - advance tail of skb header
2188 * @skb: buffer to reallocate
2189 * @delta: number of bytes to advance tail
2191 * The function makes a sense only on a fragmented &sk_buff,
2192 * it expands header moving its tail forward and copying necessary
2193 * data from fragmented part.
2195 * &sk_buff MUST have reference count of 1.
2197 * Returns %NULL (and &sk_buff does not change) if pull failed
2198 * or value of new tail of skb in the case of success.
2200 * All the pointers pointing into skb header may change and must be
2201 * reloaded after call to this function.
2204 /* Moves tail of skb head forward, copying data from fragmented part,
2205 * when it is necessary.
2206 * 1. It may fail due to malloc failure.
2207 * 2. It may change skb pointers.
2209 * It is pretty complicated. Luckily, it is called only in exceptional cases.
2211 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2213 /* If skb has not enough free space at tail, get new one
2214 * plus 128 bytes for future expansions. If we have enough
2215 * room at tail, reallocate without expansion only if skb is cloned.
2217 int i, k, eat = (skb->tail + delta) - skb->end;
2219 if (eat > 0 || skb_cloned(skb)) {
2220 if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2225 BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2226 skb_tail_pointer(skb), delta));
2228 /* Optimization: no fragments, no reasons to preestimate
2229 * size of pulled pages. Superb.
2231 if (!skb_has_frag_list(skb))
2234 /* Estimate size of pulled pages. */
2236 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2237 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2244 /* If we need update frag list, we are in troubles.
2245 * Certainly, it is possible to add an offset to skb data,
2246 * but taking into account that pulling is expected to
2247 * be very rare operation, it is worth to fight against
2248 * further bloating skb head and crucify ourselves here instead.
2249 * Pure masohism, indeed. 8)8)
2252 struct sk_buff *list = skb_shinfo(skb)->frag_list;
2253 struct sk_buff *clone = NULL;
2254 struct sk_buff *insp = NULL;
2257 if (list->len <= eat) {
2258 /* Eaten as whole. */
2263 /* Eaten partially. */
2265 if (skb_shared(list)) {
2266 /* Sucks! We need to fork list. :-( */
2267 clone = skb_clone(list, GFP_ATOMIC);
2273 /* This may be pulled without
2277 if (!pskb_pull(list, eat)) {
2285 /* Free pulled out fragments. */
2286 while ((list = skb_shinfo(skb)->frag_list) != insp) {
2287 skb_shinfo(skb)->frag_list = list->next;
2290 /* And insert new clone at head. */
2293 skb_shinfo(skb)->frag_list = clone;
2296 /* Success! Now we may commit changes to skb data. */
2301 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2302 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2305 skb_frag_unref(skb, i);
2308 skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2310 *frag = skb_shinfo(skb)->frags[i];
2312 skb_frag_off_add(frag, eat);
2313 skb_frag_size_sub(frag, eat);
2321 skb_shinfo(skb)->nr_frags = k;
2325 skb->data_len -= delta;
2328 skb_zcopy_clear(skb, false);
2330 return skb_tail_pointer(skb);
2332 EXPORT_SYMBOL(__pskb_pull_tail);
2335 * skb_copy_bits - copy bits from skb to kernel buffer
2337 * @offset: offset in source
2338 * @to: destination buffer
2339 * @len: number of bytes to copy
2341 * Copy the specified number of bytes from the source skb to the
2342 * destination buffer.
2345 * If its prototype is ever changed,
2346 * check arch/{*}/net/{*}.S files,
2347 * since it is called from BPF assembly code.
2349 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2351 int start = skb_headlen(skb);
2352 struct sk_buff *frag_iter;
2355 if (offset > (int)skb->len - len)
2359 if ((copy = start - offset) > 0) {
2362 skb_copy_from_linear_data_offset(skb, offset, to, copy);
2363 if ((len -= copy) == 0)
2369 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2371 skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2373 WARN_ON(start > offset + len);
2375 end = start + skb_frag_size(f);
2376 if ((copy = end - offset) > 0) {
2377 u32 p_off, p_len, copied;
2384 skb_frag_foreach_page(f,
2385 skb_frag_off(f) + offset - start,
2386 copy, p, p_off, p_len, copied) {
2387 vaddr = kmap_atomic(p);
2388 memcpy(to + copied, vaddr + p_off, p_len);
2389 kunmap_atomic(vaddr);
2392 if ((len -= copy) == 0)
2400 skb_walk_frags(skb, frag_iter) {
2403 WARN_ON(start > offset + len);
2405 end = start + frag_iter->len;
2406 if ((copy = end - offset) > 0) {
2409 if (skb_copy_bits(frag_iter, offset - start, to, copy))
2411 if ((len -= copy) == 0)
2425 EXPORT_SYMBOL(skb_copy_bits);
2428 * Callback from splice_to_pipe(), if we need to release some pages
2429 * at the end of the spd in case we error'ed out in filling the pipe.
2431 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2433 put_page(spd->pages[i]);
2436 static struct page *linear_to_page(struct page *page, unsigned int *len,
2437 unsigned int *offset,
2440 struct page_frag *pfrag = sk_page_frag(sk);
2442 if (!sk_page_frag_refill(sk, pfrag))
2445 *len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2447 memcpy(page_address(pfrag->page) + pfrag->offset,
2448 page_address(page) + *offset, *len);
2449 *offset = pfrag->offset;
2450 pfrag->offset += *len;
2455 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2457 unsigned int offset)
2459 return spd->nr_pages &&
2460 spd->pages[spd->nr_pages - 1] == page &&
2461 (spd->partial[spd->nr_pages - 1].offset +
2462 spd->partial[spd->nr_pages - 1].len == offset);
2466 * Fill page/offset/length into spd, if it can hold more pages.
2468 static bool spd_fill_page(struct splice_pipe_desc *spd,
2469 struct pipe_inode_info *pipe, struct page *page,
2470 unsigned int *len, unsigned int offset,
2474 if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2478 page = linear_to_page(page, len, &offset, sk);
2482 if (spd_can_coalesce(spd, page, offset)) {
2483 spd->partial[spd->nr_pages - 1].len += *len;
2487 spd->pages[spd->nr_pages] = page;
2488 spd->partial[spd->nr_pages].len = *len;
2489 spd->partial[spd->nr_pages].offset = offset;
2495 static bool __splice_segment(struct page *page, unsigned int poff,
2496 unsigned int plen, unsigned int *off,
2498 struct splice_pipe_desc *spd, bool linear,
2500 struct pipe_inode_info *pipe)
2505 /* skip this segment if already processed */
2511 /* ignore any bits we already processed */
2517 unsigned int flen = min(*len, plen);
2519 if (spd_fill_page(spd, pipe, page, &flen, poff,
2525 } while (*len && plen);
2531 * Map linear and fragment data from the skb to spd. It reports true if the
2532 * pipe is full or if we already spliced the requested length.
2534 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2535 unsigned int *offset, unsigned int *len,
2536 struct splice_pipe_desc *spd, struct sock *sk)
2539 struct sk_buff *iter;
2541 /* map the linear part :
2542 * If skb->head_frag is set, this 'linear' part is backed by a
2543 * fragment, and if the head is not shared with any clones then
2544 * we can avoid a copy since we own the head portion of this page.
2546 if (__splice_segment(virt_to_page(skb->data),
2547 (unsigned long) skb->data & (PAGE_SIZE - 1),
2550 skb_head_is_locked(skb),
2555 * then map the fragments
2557 for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2558 const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2560 if (__splice_segment(skb_frag_page(f),
2561 skb_frag_off(f), skb_frag_size(f),
2562 offset, len, spd, false, sk, pipe))
2566 skb_walk_frags(skb, iter) {
2567 if (*offset >= iter->len) {
2568 *offset -= iter->len;
2571 /* __skb_splice_bits() only fails if the output has no room
2572 * left, so no point in going over the frag_list for the error
2575 if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2583 * Map data from the skb to a pipe. Should handle both the linear part,
2584 * the fragments, and the frag list.
2586 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2587 struct pipe_inode_info *pipe, unsigned int tlen,
2590 struct partial_page partial[MAX_SKB_FRAGS];
2591 struct page *pages[MAX_SKB_FRAGS];
2592 struct splice_pipe_desc spd = {
2595 .nr_pages_max = MAX_SKB_FRAGS,
2596 .ops = &nosteal_pipe_buf_ops,
2597 .spd_release = sock_spd_release,
2601 __skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2604 ret = splice_to_pipe(pipe, &spd);
2608 EXPORT_SYMBOL_GPL(skb_splice_bits);
2610 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2611 struct kvec *vec, size_t num, size_t size)
2613 struct socket *sock = sk->sk_socket;
2617 return kernel_sendmsg(sock, msg, vec, num, size);
2620 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2621 size_t size, int flags)
2623 struct socket *sock = sk->sk_socket;
2627 return kernel_sendpage(sock, page, offset, size, flags);
2630 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2631 struct kvec *vec, size_t num, size_t size);
2632 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2633 size_t size, int flags);
2634 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2635 int len, sendmsg_func sendmsg, sendpage_func sendpage)
2637 unsigned int orig_len = len;
2638 struct sk_buff *head = skb;
2639 unsigned short fragidx;
2644 /* Deal with head data */
2645 while (offset < skb_headlen(skb) && len) {
2649 slen = min_t(int, len, skb_headlen(skb) - offset);
2650 kv.iov_base = skb->data + offset;
2652 memset(&msg, 0, sizeof(msg));
2653 msg.msg_flags = MSG_DONTWAIT;
2655 ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2656 sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2664 /* All the data was skb head? */
2668 /* Make offset relative to start of frags */
2669 offset -= skb_headlen(skb);
2671 /* Find where we are in frag list */
2672 for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2673 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2675 if (offset < skb_frag_size(frag))
2678 offset -= skb_frag_size(frag);
2681 for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
2682 skb_frag_t *frag = &skb_shinfo(skb)->frags[fragidx];
2684 slen = min_t(size_t, len, skb_frag_size(frag) - offset);
2687 ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
2688 sendpage_unlocked, sk,
2689 skb_frag_page(frag),
2690 skb_frag_off(frag) + offset,
2691 slen, MSG_DONTWAIT);
2704 /* Process any frag lists */
2707 if (skb_has_frag_list(skb)) {
2708 skb = skb_shinfo(skb)->frag_list;
2711 } else if (skb->next) {
2718 return orig_len - len;
2721 return orig_len == len ? ret : orig_len - len;
2724 /* Send skb data on a socket. Socket must be locked. */
2725 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
2728 return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
2729 kernel_sendpage_locked);
2731 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
2733 /* Send skb data on a socket. Socket must be unlocked. */
2734 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
2736 return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
2741 * skb_store_bits - store bits from kernel buffer to skb
2742 * @skb: destination buffer
2743 * @offset: offset in destination
2744 * @from: source buffer
2745 * @len: number of bytes to copy
2747 * Copy the specified number of bytes from the source buffer to the
2748 * destination skb. This function handles all the messy bits of
2749 * traversing fragment lists and such.
2752 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2754 int start = skb_headlen(skb);
2755 struct sk_buff *frag_iter;
2758 if (offset > (int)skb->len - len)
2761 if ((copy = start - offset) > 0) {
2764 skb_copy_to_linear_data_offset(skb, offset, from, copy);
2765 if ((len -= copy) == 0)
2771 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2772 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2775 WARN_ON(start > offset + len);
2777 end = start + skb_frag_size(frag);
2778 if ((copy = end - offset) > 0) {
2779 u32 p_off, p_len, copied;
2786 skb_frag_foreach_page(frag,
2787 skb_frag_off(frag) + offset - start,
2788 copy, p, p_off, p_len, copied) {
2789 vaddr = kmap_atomic(p);
2790 memcpy(vaddr + p_off, from + copied, p_len);
2791 kunmap_atomic(vaddr);
2794 if ((len -= copy) == 0)
2802 skb_walk_frags(skb, frag_iter) {
2805 WARN_ON(start > offset + len);
2807 end = start + frag_iter->len;
2808 if ((copy = end - offset) > 0) {
2811 if (skb_store_bits(frag_iter, offset - start,
2814 if ((len -= copy) == 0)
2827 EXPORT_SYMBOL(skb_store_bits);
2829 /* Checksum skb data. */
2830 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
2831 __wsum csum, const struct skb_checksum_ops *ops)
2833 int start = skb_headlen(skb);
2834 int i, copy = start - offset;
2835 struct sk_buff *frag_iter;
2838 /* Checksum header. */
2842 csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
2843 skb->data + offset, copy, csum);
2844 if ((len -= copy) == 0)
2850 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2852 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2854 WARN_ON(start > offset + len);
2856 end = start + skb_frag_size(frag);
2857 if ((copy = end - offset) > 0) {
2858 u32 p_off, p_len, copied;
2866 skb_frag_foreach_page(frag,
2867 skb_frag_off(frag) + offset - start,
2868 copy, p, p_off, p_len, copied) {
2869 vaddr = kmap_atomic(p);
2870 csum2 = INDIRECT_CALL_1(ops->update,
2872 vaddr + p_off, p_len, 0);
2873 kunmap_atomic(vaddr);
2874 csum = INDIRECT_CALL_1(ops->combine,
2875 csum_block_add_ext, csum,
2887 skb_walk_frags(skb, frag_iter) {
2890 WARN_ON(start > offset + len);
2892 end = start + frag_iter->len;
2893 if ((copy = end - offset) > 0) {
2897 csum2 = __skb_checksum(frag_iter, offset - start,
2899 csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
2900 csum, csum2, pos, copy);
2901 if ((len -= copy) == 0)
2912 EXPORT_SYMBOL(__skb_checksum);
2914 __wsum skb_checksum(const struct sk_buff *skb, int offset,
2915 int len, __wsum csum)
2917 const struct skb_checksum_ops ops = {
2918 .update = csum_partial_ext,
2919 .combine = csum_block_add_ext,
2922 return __skb_checksum(skb, offset, len, csum, &ops);
2924 EXPORT_SYMBOL(skb_checksum);
2926 /* Both of above in one bottle. */
2928 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
2931 int start = skb_headlen(skb);
2932 int i, copy = start - offset;
2933 struct sk_buff *frag_iter;
2941 csum = csum_partial_copy_nocheck(skb->data + offset, to,
2943 if ((len -= copy) == 0)
2950 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2953 WARN_ON(start > offset + len);
2955 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2956 if ((copy = end - offset) > 0) {
2957 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2958 u32 p_off, p_len, copied;
2966 skb_frag_foreach_page(frag,
2967 skb_frag_off(frag) + offset - start,
2968 copy, p, p_off, p_len, copied) {
2969 vaddr = kmap_atomic(p);
2970 csum2 = csum_partial_copy_nocheck(vaddr + p_off,
2973 kunmap_atomic(vaddr);
2974 csum = csum_block_add(csum, csum2, pos);
2986 skb_walk_frags(skb, frag_iter) {
2990 WARN_ON(start > offset + len);
2992 end = start + frag_iter->len;
2993 if ((copy = end - offset) > 0) {
2996 csum2 = skb_copy_and_csum_bits(frag_iter,
2999 csum = csum_block_add(csum, csum2, pos);
3000 if ((len -= copy) == 0)
3011 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3013 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3017 sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3018 /* See comments in __skb_checksum_complete(). */
3020 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3021 !skb->csum_complete_sw)
3022 netdev_rx_csum_fault(skb->dev, skb);
3024 if (!skb_shared(skb))
3025 skb->csum_valid = !sum;
3028 EXPORT_SYMBOL(__skb_checksum_complete_head);
3030 /* This function assumes skb->csum already holds pseudo header's checksum,
3031 * which has been changed from the hardware checksum, for example, by
3032 * __skb_checksum_validate_complete(). And, the original skb->csum must
3033 * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3035 * It returns non-zero if the recomputed checksum is still invalid, otherwise
3036 * zero. The new checksum is stored back into skb->csum unless the skb is
3039 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3044 csum = skb_checksum(skb, 0, skb->len, 0);
3046 sum = csum_fold(csum_add(skb->csum, csum));
3047 /* This check is inverted, because we already knew the hardware
3048 * checksum is invalid before calling this function. So, if the
3049 * re-computed checksum is valid instead, then we have a mismatch
3050 * between the original skb->csum and skb_checksum(). This means either
3051 * the original hardware checksum is incorrect or we screw up skb->csum
3052 * when moving skb->data around.
3055 if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3056 !skb->csum_complete_sw)
3057 netdev_rx_csum_fault(skb->dev, skb);
3060 if (!skb_shared(skb)) {
3061 /* Save full packet checksum */
3063 skb->ip_summed = CHECKSUM_COMPLETE;
3064 skb->csum_complete_sw = 1;
3065 skb->csum_valid = !sum;
3070 EXPORT_SYMBOL(__skb_checksum_complete);
3072 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3074 net_warn_ratelimited(
3075 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3080 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3081 int offset, int len)
3083 net_warn_ratelimited(
3084 "%s: attempt to compute crc32c without libcrc32c.ko\n",
3089 static const struct skb_checksum_ops default_crc32c_ops = {
3090 .update = warn_crc32c_csum_update,
3091 .combine = warn_crc32c_csum_combine,
3094 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3095 &default_crc32c_ops;
3096 EXPORT_SYMBOL(crc32c_csum_stub);
3099 * skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3100 * @from: source buffer
3102 * Calculates the amount of linear headroom needed in the 'to' skb passed
3103 * into skb_zerocopy().
3106 skb_zerocopy_headlen(const struct sk_buff *from)
3108 unsigned int hlen = 0;
3110 if (!from->head_frag ||
3111 skb_headlen(from) < L1_CACHE_BYTES ||
3112 skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3113 hlen = skb_headlen(from);
3118 if (skb_has_frag_list(from))
3123 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3126 * skb_zerocopy - Zero copy skb to skb
3127 * @to: destination buffer
3128 * @from: source buffer
3129 * @len: number of bytes to copy from source buffer
3130 * @hlen: size of linear headroom in destination buffer
3132 * Copies up to `len` bytes from `from` to `to` by creating references
3133 * to the frags in the source buffer.
3135 * The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3136 * headroom in the `to` buffer.
3139 * 0: everything is OK
3140 * -ENOMEM: couldn't orphan frags of @from due to lack of memory
3141 * -EFAULT: skb_copy_bits() found some problem with skb geometry
3144 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3147 int plen = 0; /* length of skb->head fragment */
3150 unsigned int offset;
3152 BUG_ON(!from->head_frag && !hlen);
3154 /* dont bother with small payloads */
3155 if (len <= skb_tailroom(to))
3156 return skb_copy_bits(from, 0, skb_put(to, len), len);
3159 ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3164 plen = min_t(int, skb_headlen(from), len);
3166 page = virt_to_head_page(from->head);
3167 offset = from->data - (unsigned char *)page_address(page);
3168 __skb_fill_page_desc(to, 0, page, offset, plen);
3175 to->truesize += len + plen;
3176 to->len += len + plen;
3177 to->data_len += len + plen;
3179 if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3183 skb_zerocopy_clone(to, from, GFP_ATOMIC);
3185 for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3190 skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3191 size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3193 skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3195 skb_frag_ref(to, j);
3198 skb_shinfo(to)->nr_frags = j;
3202 EXPORT_SYMBOL_GPL(skb_zerocopy);
3204 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3209 if (skb->ip_summed == CHECKSUM_PARTIAL)
3210 csstart = skb_checksum_start_offset(skb);
3212 csstart = skb_headlen(skb);
3214 BUG_ON(csstart > skb_headlen(skb));
3216 skb_copy_from_linear_data(skb, to, csstart);
3219 if (csstart != skb->len)
3220 csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3221 skb->len - csstart);
3223 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3224 long csstuff = csstart + skb->csum_offset;
3226 *((__sum16 *)(to + csstuff)) = csum_fold(csum);
3229 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3232 * skb_dequeue - remove from the head of the queue
3233 * @list: list to dequeue from
3235 * Remove the head of the list. The list lock is taken so the function
3236 * may be used safely with other locking list functions. The head item is
3237 * returned or %NULL if the list is empty.
3240 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3242 unsigned long flags;
3243 struct sk_buff *result;
3245 spin_lock_irqsave(&list->lock, flags);
3246 result = __skb_dequeue(list);
3247 spin_unlock_irqrestore(&list->lock, flags);
3250 EXPORT_SYMBOL(skb_dequeue);
3253 * skb_dequeue_tail - remove from the tail of the queue
3254 * @list: list to dequeue from
3256 * Remove the tail of the list. The list lock is taken so the function
3257 * may be used safely with other locking list functions. The tail item is
3258 * returned or %NULL if the list is empty.
3260 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3262 unsigned long flags;
3263 struct sk_buff *result;
3265 spin_lock_irqsave(&list->lock, flags);
3266 result = __skb_dequeue_tail(list);
3267 spin_unlock_irqrestore(&list->lock, flags);
3270 EXPORT_SYMBOL(skb_dequeue_tail);
3273 * skb_queue_purge - empty a list
3274 * @list: list to empty
3276 * Delete all buffers on an &sk_buff list. Each buffer is removed from
3277 * the list and one reference dropped. This function takes the list
3278 * lock and is atomic with respect to other list locking functions.
3280 void skb_queue_purge(struct sk_buff_head *list)
3282 struct sk_buff *skb;
3283 while ((skb = skb_dequeue(list)) != NULL)
3286 EXPORT_SYMBOL(skb_queue_purge);
3289 * skb_rbtree_purge - empty a skb rbtree
3290 * @root: root of the rbtree to empty
3291 * Return value: the sum of truesizes of all purged skbs.
3293 * Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3294 * the list and one reference dropped. This function does not take
3295 * any lock. Synchronization should be handled by the caller (e.g., TCP
3296 * out-of-order queue is protected by the socket lock).
3298 unsigned int skb_rbtree_purge(struct rb_root *root)
3300 struct rb_node *p = rb_first(root);
3301 unsigned int sum = 0;
3304 struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3307 rb_erase(&skb->rbnode, root);
3308 sum += skb->truesize;
3315 * skb_queue_head - queue a buffer at the list head
3316 * @list: list to use
3317 * @newsk: buffer to queue
3319 * Queue a buffer at the start of the list. This function takes the
3320 * list lock and can be used safely with other locking &sk_buff functions
3323 * A buffer cannot be placed on two lists at the same time.
3325 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3327 unsigned long flags;
3329 spin_lock_irqsave(&list->lock, flags);
3330 __skb_queue_head(list, newsk);
3331 spin_unlock_irqrestore(&list->lock, flags);
3333 EXPORT_SYMBOL(skb_queue_head);
3336 * skb_queue_tail - queue a buffer at the list tail
3337 * @list: list to use
3338 * @newsk: buffer to queue
3340 * Queue a buffer at the tail of the list. This function takes the
3341 * list lock and can be used safely with other locking &sk_buff functions
3344 * A buffer cannot be placed on two lists at the same time.
3346 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3348 unsigned long flags;
3350 spin_lock_irqsave(&list->lock, flags);
3351 __skb_queue_tail(list, newsk);
3352 spin_unlock_irqrestore(&list->lock, flags);
3354 EXPORT_SYMBOL(skb_queue_tail);
3357 * skb_unlink - remove a buffer from a list
3358 * @skb: buffer to remove
3359 * @list: list to use
3361 * Remove a packet from a list. The list locks are taken and this
3362 * function is atomic with respect to other list locked calls
3364 * You must know what list the SKB is on.
3366 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3368 unsigned long flags;
3370 spin_lock_irqsave(&list->lock, flags);
3371 __skb_unlink(skb, list);
3372 spin_unlock_irqrestore(&list->lock, flags);
3374 EXPORT_SYMBOL(skb_unlink);
3377 * skb_append - append a buffer
3378 * @old: buffer to insert after
3379 * @newsk: buffer to insert
3380 * @list: list to use
3382 * Place a packet after a given packet in a list. The list locks are taken
3383 * and this function is atomic with respect to other list locked calls.
3384 * A buffer cannot be placed on two lists at the same time.
3386 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3388 unsigned long flags;
3390 spin_lock_irqsave(&list->lock, flags);
3391 __skb_queue_after(list, old, newsk);
3392 spin_unlock_irqrestore(&list->lock, flags);
3394 EXPORT_SYMBOL(skb_append);
3396 static inline void skb_split_inside_header(struct sk_buff *skb,
3397 struct sk_buff* skb1,
3398 const u32 len, const int pos)
3402 skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3404 /* And move data appendix as is. */
3405 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3406 skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3408 skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3409 skb_shinfo(skb)->nr_frags = 0;
3410 skb1->data_len = skb->data_len;
3411 skb1->len += skb1->data_len;
3414 skb_set_tail_pointer(skb, len);
3417 static inline void skb_split_no_header(struct sk_buff *skb,
3418 struct sk_buff* skb1,
3419 const u32 len, int pos)
3422 const int nfrags = skb_shinfo(skb)->nr_frags;
3424 skb_shinfo(skb)->nr_frags = 0;
3425 skb1->len = skb1->data_len = skb->len - len;
3427 skb->data_len = len - pos;
3429 for (i = 0; i < nfrags; i++) {
3430 int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3432 if (pos + size > len) {
3433 skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3437 * We have two variants in this case:
3438 * 1. Move all the frag to the second
3439 * part, if it is possible. F.e.
3440 * this approach is mandatory for TUX,
3441 * where splitting is expensive.
3442 * 2. Split is accurately. We make this.
3444 skb_frag_ref(skb, i);
3445 skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3446 skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3447 skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3448 skb_shinfo(skb)->nr_frags++;
3452 skb_shinfo(skb)->nr_frags++;
3455 skb_shinfo(skb1)->nr_frags = k;
3459 * skb_split - Split fragmented skb to two parts at length len.
3460 * @skb: the buffer to split
3461 * @skb1: the buffer to receive the second part
3462 * @len: new length for skb
3464 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3466 int pos = skb_headlen(skb);
3468 skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & SKBFL_SHARED_FRAG;
3469 skb_zerocopy_clone(skb1, skb, 0);
3470 if (len < pos) /* Split line is inside header. */
3471 skb_split_inside_header(skb, skb1, len, pos);
3472 else /* Second chunk has no header, nothing to copy. */
3473 skb_split_no_header(skb, skb1, len, pos);
3475 EXPORT_SYMBOL(skb_split);
3477 /* Shifting from/to a cloned skb is a no-go.
3479 * Caller cannot keep skb_shinfo related pointers past calling here!
3481 static int skb_prepare_for_shift(struct sk_buff *skb)
3483 return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3487 * skb_shift - Shifts paged data partially from skb to another
3488 * @tgt: buffer into which tail data gets added
3489 * @skb: buffer from which the paged data comes from
3490 * @shiftlen: shift up to this many bytes
3492 * Attempts to shift up to shiftlen worth of bytes, which may be less than
3493 * the length of the skb, from skb to tgt. Returns number bytes shifted.
3494 * It's up to caller to free skb if everything was shifted.
3496 * If @tgt runs out of frags, the whole operation is aborted.
3498 * Skb cannot include anything else but paged data while tgt is allowed
3499 * to have non-paged data as well.
3501 * TODO: full sized shift could be optimized but that would need
3502 * specialized skb free'er to handle frags without up-to-date nr_frags.
3504 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3506 int from, to, merge, todo;
3507 skb_frag_t *fragfrom, *fragto;
3509 BUG_ON(shiftlen > skb->len);
3511 if (skb_headlen(skb))
3513 if (skb_zcopy(tgt) || skb_zcopy(skb))
3518 to = skb_shinfo(tgt)->nr_frags;
3519 fragfrom = &skb_shinfo(skb)->frags[from];
3521 /* Actual merge is delayed until the point when we know we can
3522 * commit all, so that we don't have to undo partial changes
3525 !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3526 skb_frag_off(fragfrom))) {
3531 todo -= skb_frag_size(fragfrom);
3533 if (skb_prepare_for_shift(skb) ||
3534 skb_prepare_for_shift(tgt))
3537 /* All previous frag pointers might be stale! */
3538 fragfrom = &skb_shinfo(skb)->frags[from];
3539 fragto = &skb_shinfo(tgt)->frags[merge];
3541 skb_frag_size_add(fragto, shiftlen);
3542 skb_frag_size_sub(fragfrom, shiftlen);
3543 skb_frag_off_add(fragfrom, shiftlen);
3551 /* Skip full, not-fitting skb to avoid expensive operations */
3552 if ((shiftlen == skb->len) &&
3553 (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3556 if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3559 while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3560 if (to == MAX_SKB_FRAGS)
3563 fragfrom = &skb_shinfo(skb)->frags[from];
3564 fragto = &skb_shinfo(tgt)->frags[to];
3566 if (todo >= skb_frag_size(fragfrom)) {
3567 *fragto = *fragfrom;
3568 todo -= skb_frag_size(fragfrom);
3573 __skb_frag_ref(fragfrom);
3574 skb_frag_page_copy(fragto, fragfrom);
3575 skb_frag_off_copy(fragto, fragfrom);
3576 skb_frag_size_set(fragto, todo);
3578 skb_frag_off_add(fragfrom, todo);
3579 skb_frag_size_sub(fragfrom, todo);
3587 /* Ready to "commit" this state change to tgt */
3588 skb_shinfo(tgt)->nr_frags = to;
3591 fragfrom = &skb_shinfo(skb)->frags[0];
3592 fragto = &skb_shinfo(tgt)->frags[merge];
3594 skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3595 __skb_frag_unref(fragfrom, skb->pp_recycle);
3598 /* Reposition in the original skb */
3600 while (from < skb_shinfo(skb)->nr_frags)
3601 skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3602 skb_shinfo(skb)->nr_frags = to;
3604 BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3607 /* Most likely the tgt won't ever need its checksum anymore, skb on
3608 * the other hand might need it if it needs to be resent
3610 tgt->ip_summed = CHECKSUM_PARTIAL;
3611 skb->ip_summed = CHECKSUM_PARTIAL;
3613 /* Yak, is it really working this way? Some helper please? */
3614 skb->len -= shiftlen;
3615 skb->data_len -= shiftlen;
3616 skb->truesize -= shiftlen;
3617 tgt->len += shiftlen;
3618 tgt->data_len += shiftlen;
3619 tgt->truesize += shiftlen;
3625 * skb_prepare_seq_read - Prepare a sequential read of skb data
3626 * @skb: the buffer to read
3627 * @from: lower offset of data to be read
3628 * @to: upper offset of data to be read
3629 * @st: state variable
3631 * Initializes the specified state variable. Must be called before
3632 * invoking skb_seq_read() for the first time.
3634 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3635 unsigned int to, struct skb_seq_state *st)
3637 st->lower_offset = from;
3638 st->upper_offset = to;
3639 st->root_skb = st->cur_skb = skb;
3640 st->frag_idx = st->stepped_offset = 0;
3641 st->frag_data = NULL;
3644 EXPORT_SYMBOL(skb_prepare_seq_read);
3647 * skb_seq_read - Sequentially read skb data
3648 * @consumed: number of bytes consumed by the caller so far
3649 * @data: destination pointer for data to be returned
3650 * @st: state variable
3652 * Reads a block of skb data at @consumed relative to the
3653 * lower offset specified to skb_prepare_seq_read(). Assigns
3654 * the head of the data block to @data and returns the length
3655 * of the block or 0 if the end of the skb data or the upper
3656 * offset has been reached.
3658 * The caller is not required to consume all of the data
3659 * returned, i.e. @consumed is typically set to the number
3660 * of bytes already consumed and the next call to
3661 * skb_seq_read() will return the remaining part of the block.
3663 * Note 1: The size of each block of data returned can be arbitrary,
3664 * this limitation is the cost for zerocopy sequential
3665 * reads of potentially non linear data.
3667 * Note 2: Fragment lists within fragments are not implemented
3668 * at the moment, state->root_skb could be replaced with
3669 * a stack for this purpose.
3671 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3672 struct skb_seq_state *st)
3674 unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3677 if (unlikely(abs_offset >= st->upper_offset)) {
3678 if (st->frag_data) {
3679 kunmap_atomic(st->frag_data);
3680 st->frag_data = NULL;
3686 block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3688 if (abs_offset < block_limit && !st->frag_data) {
3689 *data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3690 return block_limit - abs_offset;
3693 if (st->frag_idx == 0 && !st->frag_data)
3694 st->stepped_offset += skb_headlen(st->cur_skb);
3696 while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
3697 unsigned int pg_idx, pg_off, pg_sz;
3699 frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
3702 pg_off = skb_frag_off(frag);
3703 pg_sz = skb_frag_size(frag);
3705 if (skb_frag_must_loop(skb_frag_page(frag))) {
3706 pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
3707 pg_off = offset_in_page(pg_off + st->frag_off);
3708 pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
3709 PAGE_SIZE - pg_off);
3712 block_limit = pg_sz + st->stepped_offset;
3713 if (abs_offset < block_limit) {
3715 st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3717 *data = (u8 *)st->frag_data + pg_off +
3718 (abs_offset - st->stepped_offset);
3720 return block_limit - abs_offset;
3723 if (st->frag_data) {
3724 kunmap_atomic(st->frag_data);
3725 st->frag_data = NULL;
3728 st->stepped_offset += pg_sz;
3729 st->frag_off += pg_sz;
3730 if (st->frag_off == skb_frag_size(frag)) {
3736 if (st->frag_data) {
3737 kunmap_atomic(st->frag_data);
3738 st->frag_data = NULL;
3741 if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3742 st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
3745 } else if (st->cur_skb->next) {
3746 st->cur_skb = st->cur_skb->next;
3753 EXPORT_SYMBOL(skb_seq_read);
3756 * skb_abort_seq_read - Abort a sequential read of skb data
3757 * @st: state variable
3759 * Must be called if skb_seq_read() was not called until it
3762 void skb_abort_seq_read(struct skb_seq_state *st)
3765 kunmap_atomic(st->frag_data);
3767 EXPORT_SYMBOL(skb_abort_seq_read);
3769 #define TS_SKB_CB(state) ((struct skb_seq_state *) &((state)->cb))
3771 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
3772 struct ts_config *conf,
3773 struct ts_state *state)
3775 return skb_seq_read(offset, text, TS_SKB_CB(state));
3778 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
3780 skb_abort_seq_read(TS_SKB_CB(state));
3784 * skb_find_text - Find a text pattern in skb data
3785 * @skb: the buffer to look in
3786 * @from: search offset
3788 * @config: textsearch configuration
3790 * Finds a pattern in the skb data according to the specified
3791 * textsearch configuration. Use textsearch_next() to retrieve
3792 * subsequent occurrences of the pattern. Returns the offset
3793 * to the first occurrence or UINT_MAX if no match was found.
3795 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3796 unsigned int to, struct ts_config *config)
3798 struct ts_state state;
3801 BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3803 config->get_next_block = skb_ts_get_next_block;
3804 config->finish = skb_ts_finish;
3806 skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
3808 ret = textsearch_find(config, &state);
3809 return (ret <= to - from ? ret : UINT_MAX);
3811 EXPORT_SYMBOL(skb_find_text);
3813 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3814 int offset, size_t size)
3816 int i = skb_shinfo(skb)->nr_frags;
3818 if (skb_can_coalesce(skb, i, page, offset)) {
3819 skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3820 } else if (i < MAX_SKB_FRAGS) {
3822 skb_fill_page_desc(skb, i, page, offset, size);
3829 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3832 * skb_pull_rcsum - pull skb and update receive checksum
3833 * @skb: buffer to update
3834 * @len: length of data pulled
3836 * This function performs an skb_pull on the packet and updates
3837 * the CHECKSUM_COMPLETE checksum. It should be used on
3838 * receive path processing instead of skb_pull unless you know
3839 * that the checksum difference is zero (e.g., a valid IP header)
3840 * or you are setting ip_summed to CHECKSUM_NONE.
3842 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3844 unsigned char *data = skb->data;
3846 BUG_ON(len > skb->len);
3847 __skb_pull(skb, len);
3848 skb_postpull_rcsum(skb, data, len);
3851 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3853 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
3855 skb_frag_t head_frag;
3858 page = virt_to_head_page(frag_skb->head);
3859 __skb_frag_set_page(&head_frag, page);
3860 skb_frag_off_set(&head_frag, frag_skb->data -
3861 (unsigned char *)page_address(page));
3862 skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
3866 struct sk_buff *skb_segment_list(struct sk_buff *skb,
3867 netdev_features_t features,
3868 unsigned int offset)
3870 struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
3871 unsigned int tnl_hlen = skb_tnl_header_len(skb);
3872 unsigned int delta_truesize = 0;
3873 unsigned int delta_len = 0;
3874 struct sk_buff *tail = NULL;
3875 struct sk_buff *nskb, *tmp;
3878 skb_push(skb, -skb_network_offset(skb) + offset);
3880 skb_shinfo(skb)->frag_list = NULL;
3884 list_skb = list_skb->next;
3887 delta_truesize += nskb->truesize;
3888 if (skb_shared(nskb)) {
3889 tmp = skb_clone(nskb, GFP_ATOMIC);
3893 err = skb_unclone(nskb, GFP_ATOMIC);
3904 if (unlikely(err)) {
3905 nskb->next = list_skb;
3911 delta_len += nskb->len;
3913 skb_push(nskb, -skb_network_offset(nskb) + offset);
3915 skb_release_head_state(nskb);
3916 __copy_skb_header(nskb, skb);
3918 skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
3919 skb_copy_from_linear_data_offset(skb, -tnl_hlen,
3920 nskb->data - tnl_hlen,
3923 if (skb_needs_linearize(nskb, features) &&
3924 __skb_linearize(nskb))
3929 skb->truesize = skb->truesize - delta_truesize;
3930 skb->data_len = skb->data_len - delta_len;
3931 skb->len = skb->len - delta_len;
3937 if (skb_needs_linearize(skb, features) &&
3938 __skb_linearize(skb))
3946 kfree_skb_list(skb->next);
3948 return ERR_PTR(-ENOMEM);
3950 EXPORT_SYMBOL_GPL(skb_segment_list);
3952 int skb_gro_receive_list(struct sk_buff *p, struct sk_buff *skb)
3954 if (unlikely(p->len + skb->len >= 65536))
3957 if (NAPI_GRO_CB(p)->last == p)
3958 skb_shinfo(p)->frag_list = skb;
3960 NAPI_GRO_CB(p)->last->next = skb;
3962 skb_pull(skb, skb_gro_offset(skb));
3964 NAPI_GRO_CB(p)->last = skb;
3965 NAPI_GRO_CB(p)->count++;
3966 p->data_len += skb->len;
3968 /* sk owenrship - if any - completely transferred to the aggregated packet */
3969 skb->destructor = NULL;
3970 p->truesize += skb->truesize;
3973 NAPI_GRO_CB(skb)->same_flow = 1;
3979 * skb_segment - Perform protocol segmentation on skb.
3980 * @head_skb: buffer to segment
3981 * @features: features for the output path (see dev->features)
3983 * This function performs segmentation on the given skb. It returns
3984 * a pointer to the first in a list of new skbs for the segments.
3985 * In case of error it returns ERR_PTR(err).
3987 struct sk_buff *skb_segment(struct sk_buff *head_skb,
3988 netdev_features_t features)
3990 struct sk_buff *segs = NULL;
3991 struct sk_buff *tail = NULL;
3992 struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3993 skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3994 unsigned int mss = skb_shinfo(head_skb)->gso_size;
3995 unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
3996 struct sk_buff *frag_skb = head_skb;
3997 unsigned int offset = doffset;
3998 unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3999 unsigned int partial_segs = 0;
4000 unsigned int headroom;
4001 unsigned int len = head_skb->len;
4004 int nfrags = skb_shinfo(head_skb)->nr_frags;
4009 if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
4010 (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
4011 /* gso_size is untrusted, and we have a frag_list with a linear
4012 * non head_frag head.
4014 * (we assume checking the first list_skb member suffices;
4015 * i.e if either of the list_skb members have non head_frag
4016 * head, then the first one has too).
4018 * If head_skb's headlen does not fit requested gso_size, it
4019 * means that the frag_list members do NOT terminate on exact
4020 * gso_size boundaries. Hence we cannot perform skb_frag_t page
4021 * sharing. Therefore we must fallback to copying the frag_list
4022 * skbs; we do so by disabling SG.
4024 if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
4025 features &= ~NETIF_F_SG;
4028 __skb_push(head_skb, doffset);
4029 proto = skb_network_protocol(head_skb, NULL);
4030 if (unlikely(!proto))
4031 return ERR_PTR(-EINVAL);
4033 sg = !!(features & NETIF_F_SG);
4034 csum = !!can_checksum_protocol(features, proto);
4036 if (sg && csum && (mss != GSO_BY_FRAGS)) {
4037 if (!(features & NETIF_F_GSO_PARTIAL)) {
4038 struct sk_buff *iter;
4039 unsigned int frag_len;
4042 !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4045 /* If we get here then all the required
4046 * GSO features except frag_list are supported.
4047 * Try to split the SKB to multiple GSO SKBs
4048 * with no frag_list.
4049 * Currently we can do that only when the buffers don't
4050 * have a linear part and all the buffers except
4051 * the last are of the same length.
4053 frag_len = list_skb->len;
4054 skb_walk_frags(head_skb, iter) {
4055 if (frag_len != iter->len && iter->next)
4057 if (skb_headlen(iter) && !iter->head_frag)
4063 if (len != frag_len)
4067 /* GSO partial only requires that we trim off any excess that
4068 * doesn't fit into an MSS sized block, so take care of that
4071 partial_segs = len / mss;
4072 if (partial_segs > 1)
4073 mss *= partial_segs;
4079 headroom = skb_headroom(head_skb);
4080 pos = skb_headlen(head_skb);
4083 struct sk_buff *nskb;
4084 skb_frag_t *nskb_frag;
4088 if (unlikely(mss == GSO_BY_FRAGS)) {
4089 len = list_skb->len;
4091 len = head_skb->len - offset;
4096 hsize = skb_headlen(head_skb) - offset;
4098 if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4099 (skb_headlen(list_skb) == len || sg)) {
4100 BUG_ON(skb_headlen(list_skb) > len);
4103 nfrags = skb_shinfo(list_skb)->nr_frags;
4104 frag = skb_shinfo(list_skb)->frags;
4105 frag_skb = list_skb;
4106 pos += skb_headlen(list_skb);
4108 while (pos < offset + len) {
4109 BUG_ON(i >= nfrags);
4111 size = skb_frag_size(frag);
4112 if (pos + size > offset + len)
4120 nskb = skb_clone(list_skb, GFP_ATOMIC);
4121 list_skb = list_skb->next;
4123 if (unlikely(!nskb))
4126 if (unlikely(pskb_trim(nskb, len))) {
4131 hsize = skb_end_offset(nskb);
4132 if (skb_cow_head(nskb, doffset + headroom)) {
4137 nskb->truesize += skb_end_offset(nskb) - hsize;
4138 skb_release_head_state(nskb);
4139 __skb_push(nskb, doffset);
4143 if (hsize > len || !sg)
4146 nskb = __alloc_skb(hsize + doffset + headroom,
4147 GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4150 if (unlikely(!nskb))
4153 skb_reserve(nskb, headroom);
4154 __skb_put(nskb, doffset);
4163 __copy_skb_header(nskb, head_skb);
4165 skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4166 skb_reset_mac_len(nskb);
4168 skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4169 nskb->data - tnl_hlen,
4170 doffset + tnl_hlen);
4172 if (nskb->len == len + doffset)
4173 goto perform_csum_check;
4177 if (!nskb->remcsum_offload)
4178 nskb->ip_summed = CHECKSUM_NONE;
4179 SKB_GSO_CB(nskb)->csum =
4180 skb_copy_and_csum_bits(head_skb, offset,
4184 SKB_GSO_CB(nskb)->csum_start =
4185 skb_headroom(nskb) + doffset;
4187 skb_copy_bits(head_skb, offset,
4194 nskb_frag = skb_shinfo(nskb)->frags;
4196 skb_copy_from_linear_data_offset(head_skb, offset,
4197 skb_put(nskb, hsize), hsize);
4199 skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4202 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4203 skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4206 while (pos < offset + len) {
4209 nfrags = skb_shinfo(list_skb)->nr_frags;
4210 frag = skb_shinfo(list_skb)->frags;
4211 frag_skb = list_skb;
4212 if (!skb_headlen(list_skb)) {
4215 BUG_ON(!list_skb->head_frag);
4217 /* to make room for head_frag. */
4221 if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4222 skb_zerocopy_clone(nskb, frag_skb,
4226 list_skb = list_skb->next;
4229 if (unlikely(skb_shinfo(nskb)->nr_frags >=
4231 net_warn_ratelimited(
4232 "skb_segment: too many frags: %u %u\n",
4238 *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4239 __skb_frag_ref(nskb_frag);
4240 size = skb_frag_size(nskb_frag);
4243 skb_frag_off_add(nskb_frag, offset - pos);
4244 skb_frag_size_sub(nskb_frag, offset - pos);
4247 skb_shinfo(nskb)->nr_frags++;
4249 if (pos + size <= offset + len) {
4254 skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4262 nskb->data_len = len - hsize;
4263 nskb->len += nskb->data_len;
4264 nskb->truesize += nskb->data_len;
4268 if (skb_has_shared_frag(nskb) &&
4269 __skb_linearize(nskb))
4272 if (!nskb->remcsum_offload)
4273 nskb->ip_summed = CHECKSUM_NONE;
4274 SKB_GSO_CB(nskb)->csum =
4275 skb_checksum(nskb, doffset,
4276 nskb->len - doffset, 0);
4277 SKB_GSO_CB(nskb)->csum_start =
4278 skb_headroom(nskb) + doffset;
4280 } while ((offset += len) < head_skb->len);
4282 /* Some callers want to get the end of the list.
4283 * Put it in segs->prev to avoid walking the list.
4284 * (see validate_xmit_skb_list() for example)
4289 struct sk_buff *iter;
4290 int type = skb_shinfo(head_skb)->gso_type;
4291 unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4293 /* Update type to add partial and then remove dodgy if set */
4294 type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4295 type &= ~SKB_GSO_DODGY;
4297 /* Update GSO info and prepare to start updating headers on
4298 * our way back down the stack of protocols.
4300 for (iter = segs; iter; iter = iter->next) {
4301 skb_shinfo(iter)->gso_size = gso_size;
4302 skb_shinfo(iter)->gso_segs = partial_segs;
4303 skb_shinfo(iter)->gso_type = type;
4304 SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4307 if (tail->len - doffset <= gso_size)
4308 skb_shinfo(tail)->gso_size = 0;
4309 else if (tail != segs)
4310 skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4313 /* Following permits correct backpressure, for protocols
4314 * using skb_set_owner_w().
4315 * Idea is to tranfert ownership from head_skb to last segment.
4317 if (head_skb->destructor == sock_wfree) {
4318 swap(tail->truesize, head_skb->truesize);
4319 swap(tail->destructor, head_skb->destructor);
4320 swap(tail->sk, head_skb->sk);
4325 kfree_skb_list(segs);
4326 return ERR_PTR(err);
4328 EXPORT_SYMBOL_GPL(skb_segment);
4330 int skb_gro_receive(struct sk_buff *p, struct sk_buff *skb)
4332 struct skb_shared_info *pinfo, *skbinfo = skb_shinfo(skb);
4333 unsigned int offset = skb_gro_offset(skb);
4334 unsigned int headlen = skb_headlen(skb);
4335 unsigned int len = skb_gro_len(skb);
4336 unsigned int delta_truesize;
4337 unsigned int new_truesize;
4340 if (unlikely(p->len + len >= 65536 || NAPI_GRO_CB(skb)->flush))
4343 lp = NAPI_GRO_CB(p)->last;
4344 pinfo = skb_shinfo(lp);
4346 if (headlen <= offset) {
4349 int i = skbinfo->nr_frags;
4350 int nr_frags = pinfo->nr_frags + i;
4352 if (nr_frags > MAX_SKB_FRAGS)
4356 pinfo->nr_frags = nr_frags;
4357 skbinfo->nr_frags = 0;
4359 frag = pinfo->frags + nr_frags;
4360 frag2 = skbinfo->frags + i;
4365 skb_frag_off_add(frag, offset);
4366 skb_frag_size_sub(frag, offset);
4368 /* all fragments truesize : remove (head size + sk_buff) */
4369 new_truesize = SKB_TRUESIZE(skb_end_offset(skb));
4370 delta_truesize = skb->truesize - new_truesize;
4372 skb->truesize = new_truesize;
4373 skb->len -= skb->data_len;
4376 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE;
4378 } else if (skb->head_frag) {
4379 int nr_frags = pinfo->nr_frags;
4380 skb_frag_t *frag = pinfo->frags + nr_frags;
4381 struct page *page = virt_to_head_page(skb->head);
4382 unsigned int first_size = headlen - offset;
4383 unsigned int first_offset;
4385 if (nr_frags + 1 + skbinfo->nr_frags > MAX_SKB_FRAGS)
4388 first_offset = skb->data -
4389 (unsigned char *)page_address(page) +
4392 pinfo->nr_frags = nr_frags + 1 + skbinfo->nr_frags;
4394 __skb_frag_set_page(frag, page);
4395 skb_frag_off_set(frag, first_offset);
4396 skb_frag_size_set(frag, first_size);
4398 memcpy(frag + 1, skbinfo->frags, sizeof(*frag) * skbinfo->nr_frags);
4399 /* We dont need to clear skbinfo->nr_frags here */
4401 new_truesize = SKB_DATA_ALIGN(sizeof(struct sk_buff));
4402 delta_truesize = skb->truesize - new_truesize;
4403 skb->truesize = new_truesize;
4404 NAPI_GRO_CB(skb)->free = NAPI_GRO_FREE_STOLEN_HEAD;
4409 /* sk owenrship - if any - completely transferred to the aggregated packet */
4410 skb->destructor = NULL;
4411 delta_truesize = skb->truesize;
4412 if (offset > headlen) {
4413 unsigned int eat = offset - headlen;
4415 skb_frag_off_add(&skbinfo->frags[0], eat);
4416 skb_frag_size_sub(&skbinfo->frags[0], eat);
4417 skb->data_len -= eat;
4422 __skb_pull(skb, offset);
4424 if (NAPI_GRO_CB(p)->last == p)
4425 skb_shinfo(p)->frag_list = skb;
4427 NAPI_GRO_CB(p)->last->next = skb;
4428 NAPI_GRO_CB(p)->last = skb;
4429 __skb_header_release(skb);
4433 NAPI_GRO_CB(p)->count++;
4435 p->truesize += delta_truesize;
4438 lp->data_len += len;
4439 lp->truesize += delta_truesize;
4442 NAPI_GRO_CB(skb)->same_flow = 1;
4446 #ifdef CONFIG_SKB_EXTENSIONS
4447 #define SKB_EXT_ALIGN_VALUE 8
4448 #define SKB_EXT_CHUNKSIZEOF(x) (ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4450 static const u8 skb_ext_type_len[] = {
4451 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4452 [SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4455 [SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4457 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4458 [TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4460 #if IS_ENABLED(CONFIG_MPTCP)
4461 [SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4465 static __always_inline unsigned int skb_ext_total_length(void)
4467 return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4468 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4469 skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4472 skb_ext_type_len[SKB_EXT_SEC_PATH] +
4474 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4475 skb_ext_type_len[TC_SKB_EXT] +
4477 #if IS_ENABLED(CONFIG_MPTCP)
4478 skb_ext_type_len[SKB_EXT_MPTCP] +
4483 static void skb_extensions_init(void)
4485 BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4486 BUILD_BUG_ON(skb_ext_total_length() > 255);
4488 skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4489 SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4491 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4495 static void skb_extensions_init(void) {}
4498 void __init skb_init(void)
4500 skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4501 sizeof(struct sk_buff),
4503 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4504 offsetof(struct sk_buff, cb),
4505 sizeof_field(struct sk_buff, cb),
4507 skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4508 sizeof(struct sk_buff_fclones),
4510 SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4512 skb_extensions_init();
4516 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4517 unsigned int recursion_level)
4519 int start = skb_headlen(skb);
4520 int i, copy = start - offset;
4521 struct sk_buff *frag_iter;
4524 if (unlikely(recursion_level >= 24))
4530 sg_set_buf(sg, skb->data + offset, copy);
4532 if ((len -= copy) == 0)
4537 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4540 WARN_ON(start > offset + len);
4542 end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4543 if ((copy = end - offset) > 0) {
4544 skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4545 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4550 sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4551 skb_frag_off(frag) + offset - start);
4560 skb_walk_frags(skb, frag_iter) {
4563 WARN_ON(start > offset + len);
4565 end = start + frag_iter->len;
4566 if ((copy = end - offset) > 0) {
4567 if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4572 ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4573 copy, recursion_level + 1);
4574 if (unlikely(ret < 0))
4577 if ((len -= copy) == 0)
4588 * skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4589 * @skb: Socket buffer containing the buffers to be mapped
4590 * @sg: The scatter-gather list to map into
4591 * @offset: The offset into the buffer's contents to start mapping
4592 * @len: Length of buffer space to be mapped
4594 * Fill the specified scatter-gather list with mappings/pointers into a
4595 * region of the buffer space attached to a socket buffer. Returns either
4596 * the number of scatterlist items used, or -EMSGSIZE if the contents
4599 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4601 int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4606 sg_mark_end(&sg[nsg - 1]);
4610 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4612 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4613 * sglist without mark the sg which contain last skb data as the end.
4614 * So the caller can mannipulate sg list as will when padding new data after
4615 * the first call without calling sg_unmark_end to expend sg list.
4617 * Scenario to use skb_to_sgvec_nomark:
4619 * 2. skb_to_sgvec_nomark(payload1)
4620 * 3. skb_to_sgvec_nomark(payload2)
4622 * This is equivalent to:
4624 * 2. skb_to_sgvec(payload1)
4626 * 4. skb_to_sgvec(payload2)
4628 * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4629 * is more preferable.
4631 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4632 int offset, int len)
4634 return __skb_to_sgvec(skb, sg, offset, len, 0);
4636 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4641 * skb_cow_data - Check that a socket buffer's data buffers are writable
4642 * @skb: The socket buffer to check.
4643 * @tailbits: Amount of trailing space to be added
4644 * @trailer: Returned pointer to the skb where the @tailbits space begins
4646 * Make sure that the data buffers attached to a socket buffer are
4647 * writable. If they are not, private copies are made of the data buffers
4648 * and the socket buffer is set to use these instead.
4650 * If @tailbits is given, make sure that there is space to write @tailbits
4651 * bytes of data beyond current end of socket buffer. @trailer will be
4652 * set to point to the skb in which this space begins.
4654 * The number of scatterlist elements required to completely map the
4655 * COW'd and extended socket buffer will be returned.
4657 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4661 struct sk_buff *skb1, **skb_p;
4663 /* If skb is cloned or its head is paged, reallocate
4664 * head pulling out all the pages (pages are considered not writable
4665 * at the moment even if they are anonymous).
4667 if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4668 !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4671 /* Easy case. Most of packets will go this way. */
4672 if (!skb_has_frag_list(skb)) {
4673 /* A little of trouble, not enough of space for trailer.
4674 * This should not happen, when stack is tuned to generate
4675 * good frames. OK, on miss we reallocate and reserve even more
4676 * space, 128 bytes is fair. */
4678 if (skb_tailroom(skb) < tailbits &&
4679 pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4687 /* Misery. We are in troubles, going to mincer fragments... */
4690 skb_p = &skb_shinfo(skb)->frag_list;
4693 while ((skb1 = *skb_p) != NULL) {
4696 /* The fragment is partially pulled by someone,
4697 * this can happen on input. Copy it and everything
4700 if (skb_shared(skb1))
4703 /* If the skb is the last, worry about trailer. */
4705 if (skb1->next == NULL && tailbits) {
4706 if (skb_shinfo(skb1)->nr_frags ||
4707 skb_has_frag_list(skb1) ||
4708 skb_tailroom(skb1) < tailbits)
4709 ntail = tailbits + 128;
4715 skb_shinfo(skb1)->nr_frags ||
4716 skb_has_frag_list(skb1)) {
4717 struct sk_buff *skb2;
4719 /* Fuck, we are miserable poor guys... */
4721 skb2 = skb_copy(skb1, GFP_ATOMIC);
4723 skb2 = skb_copy_expand(skb1,
4727 if (unlikely(skb2 == NULL))
4731 skb_set_owner_w(skb2, skb1->sk);
4733 /* Looking around. Are we still alive?
4734 * OK, link new skb, drop old one */
4736 skb2->next = skb1->next;
4743 skb_p = &skb1->next;
4748 EXPORT_SYMBOL_GPL(skb_cow_data);
4750 static void sock_rmem_free(struct sk_buff *skb)
4752 struct sock *sk = skb->sk;
4754 atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4757 static void skb_set_err_queue(struct sk_buff *skb)
4759 /* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4760 * So, it is safe to (mis)use it to mark skbs on the error queue.
4762 skb->pkt_type = PACKET_OUTGOING;
4763 BUILD_BUG_ON(PACKET_OUTGOING == 0);
4767 * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4769 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4771 if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4772 (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4777 skb->destructor = sock_rmem_free;
4778 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4779 skb_set_err_queue(skb);
4781 /* before exiting rcu section, make sure dst is refcounted */
4784 skb_queue_tail(&sk->sk_error_queue, skb);
4785 if (!sock_flag(sk, SOCK_DEAD))
4786 sk_error_report(sk);
4789 EXPORT_SYMBOL(sock_queue_err_skb);
4791 static bool is_icmp_err_skb(const struct sk_buff *skb)
4793 return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4794 SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4797 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4799 struct sk_buff_head *q = &sk->sk_error_queue;
4800 struct sk_buff *skb, *skb_next = NULL;
4801 bool icmp_next = false;
4802 unsigned long flags;
4804 spin_lock_irqsave(&q->lock, flags);
4805 skb = __skb_dequeue(q);
4806 if (skb && (skb_next = skb_peek(q))) {
4807 icmp_next = is_icmp_err_skb(skb_next);
4809 sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4811 spin_unlock_irqrestore(&q->lock, flags);
4813 if (is_icmp_err_skb(skb) && !icmp_next)
4817 sk_error_report(sk);
4821 EXPORT_SYMBOL(sock_dequeue_err_skb);
4824 * skb_clone_sk - create clone of skb, and take reference to socket
4825 * @skb: the skb to clone
4827 * This function creates a clone of a buffer that holds a reference on
4828 * sk_refcnt. Buffers created via this function are meant to be
4829 * returned using sock_queue_err_skb, or free via kfree_skb.
4831 * When passing buffers allocated with this function to sock_queue_err_skb
4832 * it is necessary to wrap the call with sock_hold/sock_put in order to
4833 * prevent the socket from being released prior to being enqueued on
4834 * the sk_error_queue.
4836 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4838 struct sock *sk = skb->sk;
4839 struct sk_buff *clone;
4841 if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4844 clone = skb_clone(skb, GFP_ATOMIC);
4851 clone->destructor = sock_efree;
4855 EXPORT_SYMBOL(skb_clone_sk);
4857 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4862 struct sock_exterr_skb *serr;
4865 BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4867 serr = SKB_EXT_ERR(skb);
4868 memset(serr, 0, sizeof(*serr));
4869 serr->ee.ee_errno = ENOMSG;
4870 serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4871 serr->ee.ee_info = tstype;
4872 serr->opt_stats = opt_stats;
4873 serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4874 if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4875 serr->ee.ee_data = skb_shinfo(skb)->tskey;
4876 if (sk->sk_protocol == IPPROTO_TCP &&
4877 sk->sk_type == SOCK_STREAM)
4878 serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4881 err = sock_queue_err_skb(sk, skb);
4887 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4891 if (likely(sysctl_tstamp_allow_data || tsonly))
4894 read_lock_bh(&sk->sk_callback_lock);
4895 ret = sk->sk_socket && sk->sk_socket->file &&
4896 file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4897 read_unlock_bh(&sk->sk_callback_lock);
4901 void skb_complete_tx_timestamp(struct sk_buff *skb,
4902 struct skb_shared_hwtstamps *hwtstamps)
4904 struct sock *sk = skb->sk;
4906 if (!skb_may_tx_timestamp(sk, false))
4909 /* Take a reference to prevent skb_orphan() from freeing the socket,
4910 * but only if the socket refcount is not zero.
4912 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4913 *skb_hwtstamps(skb) = *hwtstamps;
4914 __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4922 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4924 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4925 const struct sk_buff *ack_skb,
4926 struct skb_shared_hwtstamps *hwtstamps,
4927 struct sock *sk, int tstype)
4929 struct sk_buff *skb;
4930 bool tsonly, opt_stats = false;
4935 if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4936 skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4939 tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4940 if (!skb_may_tx_timestamp(sk, tsonly))
4945 if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4946 sk->sk_protocol == IPPROTO_TCP &&
4947 sk->sk_type == SOCK_STREAM) {
4948 skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4953 skb = alloc_skb(0, GFP_ATOMIC);
4955 skb = skb_clone(orig_skb, GFP_ATOMIC);
4961 skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4963 skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4967 *skb_hwtstamps(skb) = *hwtstamps;
4969 skb->tstamp = ktime_get_real();
4971 __skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
4973 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4975 void skb_tstamp_tx(struct sk_buff *orig_skb,
4976 struct skb_shared_hwtstamps *hwtstamps)
4978 return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4981 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4983 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
4985 struct sock *sk = skb->sk;
4986 struct sock_exterr_skb *serr;
4989 skb->wifi_acked_valid = 1;
4990 skb->wifi_acked = acked;
4992 serr = SKB_EXT_ERR(skb);
4993 memset(serr, 0, sizeof(*serr));
4994 serr->ee.ee_errno = ENOMSG;
4995 serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
4997 /* Take a reference to prevent skb_orphan() from freeing the socket,
4998 * but only if the socket refcount is not zero.
5000 if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5001 err = sock_queue_err_skb(sk, skb);
5007 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5010 * skb_partial_csum_set - set up and verify partial csum values for packet
5011 * @skb: the skb to set
5012 * @start: the number of bytes after skb->data to start checksumming.
5013 * @off: the offset from start to place the checksum.
5015 * For untrusted partially-checksummed packets, we need to make sure the values
5016 * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5018 * This function checks and sets those values and skb->ip_summed: if this
5019 * returns false you should drop the packet.
5021 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5023 u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5024 u32 csum_start = skb_headroom(skb) + (u32)start;
5026 if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
5027 net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5028 start, off, skb_headroom(skb), skb_headlen(skb));
5031 skb->ip_summed = CHECKSUM_PARTIAL;
5032 skb->csum_start = csum_start;
5033 skb->csum_offset = off;
5034 skb_set_transport_header(skb, start);
5037 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5039 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5042 if (skb_headlen(skb) >= len)
5045 /* If we need to pullup then pullup to the max, so we
5046 * won't need to do it again.
5051 if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5054 if (skb_headlen(skb) < len)
5060 #define MAX_TCP_HDR_LEN (15 * 4)
5062 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5063 typeof(IPPROTO_IP) proto,
5070 err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5071 off + MAX_TCP_HDR_LEN);
5072 if (!err && !skb_partial_csum_set(skb, off,
5073 offsetof(struct tcphdr,
5076 return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5079 err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5080 off + sizeof(struct udphdr));
5081 if (!err && !skb_partial_csum_set(skb, off,
5082 offsetof(struct udphdr,
5085 return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5088 return ERR_PTR(-EPROTO);
5091 /* This value should be large enough to cover a tagged ethernet header plus
5092 * maximally sized IP and TCP or UDP headers.
5094 #define MAX_IP_HDR_LEN 128
5096 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5105 err = skb_maybe_pull_tail(skb,
5106 sizeof(struct iphdr),
5111 if (ip_is_fragment(ip_hdr(skb)))
5114 off = ip_hdrlen(skb);
5121 csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5123 return PTR_ERR(csum);
5126 *csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5129 ip_hdr(skb)->protocol, 0);
5136 /* This value should be large enough to cover a tagged ethernet header plus
5137 * an IPv6 header, all options, and a maximal TCP or UDP header.
5139 #define MAX_IPV6_HDR_LEN 256
5141 #define OPT_HDR(type, skb, off) \
5142 (type *)(skb_network_header(skb) + (off))
5144 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5157 off = sizeof(struct ipv6hdr);
5159 err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5163 nexthdr = ipv6_hdr(skb)->nexthdr;
5165 len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5166 while (off <= len && !done) {
5168 case IPPROTO_DSTOPTS:
5169 case IPPROTO_HOPOPTS:
5170 case IPPROTO_ROUTING: {
5171 struct ipv6_opt_hdr *hp;
5173 err = skb_maybe_pull_tail(skb,
5175 sizeof(struct ipv6_opt_hdr),
5180 hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5181 nexthdr = hp->nexthdr;
5182 off += ipv6_optlen(hp);
5186 struct ip_auth_hdr *hp;
5188 err = skb_maybe_pull_tail(skb,
5190 sizeof(struct ip_auth_hdr),
5195 hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5196 nexthdr = hp->nexthdr;
5197 off += ipv6_authlen(hp);
5200 case IPPROTO_FRAGMENT: {
5201 struct frag_hdr *hp;
5203 err = skb_maybe_pull_tail(skb,
5205 sizeof(struct frag_hdr),
5210 hp = OPT_HDR(struct frag_hdr, skb, off);
5212 if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5215 nexthdr = hp->nexthdr;
5216 off += sizeof(struct frag_hdr);
5227 if (!done || fragment)
5230 csum = skb_checksum_setup_ip(skb, nexthdr, off);
5232 return PTR_ERR(csum);
5235 *csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5236 &ipv6_hdr(skb)->daddr,
5237 skb->len - off, nexthdr, 0);
5245 * skb_checksum_setup - set up partial checksum offset
5246 * @skb: the skb to set up
5247 * @recalculate: if true the pseudo-header checksum will be recalculated
5249 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5253 switch (skb->protocol) {
5254 case htons(ETH_P_IP):
5255 err = skb_checksum_setup_ipv4(skb, recalculate);
5258 case htons(ETH_P_IPV6):
5259 err = skb_checksum_setup_ipv6(skb, recalculate);
5269 EXPORT_SYMBOL(skb_checksum_setup);
5272 * skb_checksum_maybe_trim - maybe trims the given skb
5273 * @skb: the skb to check
5274 * @transport_len: the data length beyond the network header
5276 * Checks whether the given skb has data beyond the given transport length.
5277 * If so, returns a cloned skb trimmed to this transport length.
5278 * Otherwise returns the provided skb. Returns NULL in error cases
5279 * (e.g. transport_len exceeds skb length or out-of-memory).
5281 * Caller needs to set the skb transport header and free any returned skb if it
5282 * differs from the provided skb.
5284 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5285 unsigned int transport_len)
5287 struct sk_buff *skb_chk;
5288 unsigned int len = skb_transport_offset(skb) + transport_len;
5293 else if (skb->len == len)
5296 skb_chk = skb_clone(skb, GFP_ATOMIC);
5300 ret = pskb_trim_rcsum(skb_chk, len);
5310 * skb_checksum_trimmed - validate checksum of an skb
5311 * @skb: the skb to check
5312 * @transport_len: the data length beyond the network header
5313 * @skb_chkf: checksum function to use
5315 * Applies the given checksum function skb_chkf to the provided skb.
5316 * Returns a checked and maybe trimmed skb. Returns NULL on error.
5318 * If the skb has data beyond the given transport length, then a
5319 * trimmed & cloned skb is checked and returned.
5321 * Caller needs to set the skb transport header and free any returned skb if it
5322 * differs from the provided skb.
5324 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5325 unsigned int transport_len,
5326 __sum16(*skb_chkf)(struct sk_buff *skb))
5328 struct sk_buff *skb_chk;
5329 unsigned int offset = skb_transport_offset(skb);
5332 skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5336 if (!pskb_may_pull(skb_chk, offset))
5339 skb_pull_rcsum(skb_chk, offset);
5340 ret = skb_chkf(skb_chk);
5341 skb_push_rcsum(skb_chk, offset);
5349 if (skb_chk && skb_chk != skb)
5355 EXPORT_SYMBOL(skb_checksum_trimmed);
5357 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5359 net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5362 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5364 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5367 skb_release_head_state(skb);
5368 kmem_cache_free(skbuff_head_cache, skb);
5373 EXPORT_SYMBOL(kfree_skb_partial);
5376 * skb_try_coalesce - try to merge skb to prior one
5378 * @from: buffer to add
5379 * @fragstolen: pointer to boolean
5380 * @delta_truesize: how much more was allocated than was requested
5382 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5383 bool *fragstolen, int *delta_truesize)
5385 struct skb_shared_info *to_shinfo, *from_shinfo;
5386 int i, delta, len = from->len;
5388 *fragstolen = false;
5393 /* The page pool signature of struct page will eventually figure out
5394 * which pages can be recycled or not but for now let's prohibit slab
5395 * allocated and page_pool allocated SKBs from being coalesced.
5397 if (to->pp_recycle != from->pp_recycle)
5400 if (len <= skb_tailroom(to)) {
5402 BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5403 *delta_truesize = 0;
5407 to_shinfo = skb_shinfo(to);
5408 from_shinfo = skb_shinfo(from);
5409 if (to_shinfo->frag_list || from_shinfo->frag_list)
5411 if (skb_zcopy(to) || skb_zcopy(from))
5414 if (skb_headlen(from) != 0) {
5416 unsigned int offset;
5418 if (to_shinfo->nr_frags +
5419 from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5422 if (skb_head_is_locked(from))
5425 delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5427 page = virt_to_head_page(from->head);
5428 offset = from->data - (unsigned char *)page_address(page);
5430 skb_fill_page_desc(to, to_shinfo->nr_frags,
5431 page, offset, skb_headlen(from));
5434 if (to_shinfo->nr_frags +
5435 from_shinfo->nr_frags > MAX_SKB_FRAGS)
5438 delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5441 WARN_ON_ONCE(delta < len);
5443 memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5445 from_shinfo->nr_frags * sizeof(skb_frag_t));
5446 to_shinfo->nr_frags += from_shinfo->nr_frags;
5448 if (!skb_cloned(from))
5449 from_shinfo->nr_frags = 0;
5451 /* if the skb is not cloned this does nothing
5452 * since we set nr_frags to 0.
5454 for (i = 0; i < from_shinfo->nr_frags; i++)
5455 __skb_frag_ref(&from_shinfo->frags[i]);
5457 to->truesize += delta;
5459 to->data_len += len;
5461 *delta_truesize = delta;
5464 EXPORT_SYMBOL(skb_try_coalesce);
5467 * skb_scrub_packet - scrub an skb
5469 * @skb: buffer to clean
5470 * @xnet: packet is crossing netns
5472 * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5473 * into/from a tunnel. Some information have to be cleared during these
5475 * skb_scrub_packet can also be used to clean a skb before injecting it in
5476 * another namespace (@xnet == true). We have to clear all information in the
5477 * skb that could impact namespace isolation.
5479 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5481 skb->pkt_type = PACKET_HOST;
5487 nf_reset_trace(skb);
5489 #ifdef CONFIG_NET_SWITCHDEV
5490 skb->offload_fwd_mark = 0;
5491 skb->offload_l3_fwd_mark = 0;
5501 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5504 * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5508 * skb_gso_transport_seglen is used to determine the real size of the
5509 * individual segments, including Layer4 headers (TCP/UDP).
5511 * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5513 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5515 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5516 unsigned int thlen = 0;
5518 if (skb->encapsulation) {
5519 thlen = skb_inner_transport_header(skb) -
5520 skb_transport_header(skb);
5522 if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5523 thlen += inner_tcp_hdrlen(skb);
5524 } else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5525 thlen = tcp_hdrlen(skb);
5526 } else if (unlikely(skb_is_gso_sctp(skb))) {
5527 thlen = sizeof(struct sctphdr);
5528 } else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5529 thlen = sizeof(struct udphdr);
5531 /* UFO sets gso_size to the size of the fragmentation
5532 * payload, i.e. the size of the L4 (UDP) header is already
5535 return thlen + shinfo->gso_size;
5539 * skb_gso_network_seglen - Return length of individual segments of a gso packet
5543 * skb_gso_network_seglen is used to determine the real size of the
5544 * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5546 * The MAC/L2 header is not accounted for.
5548 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5550 unsigned int hdr_len = skb_transport_header(skb) -
5551 skb_network_header(skb);
5553 return hdr_len + skb_gso_transport_seglen(skb);
5557 * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5561 * skb_gso_mac_seglen is used to determine the real size of the
5562 * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5563 * headers (TCP/UDP).
5565 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5567 unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5569 return hdr_len + skb_gso_transport_seglen(skb);
5573 * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5575 * There are a couple of instances where we have a GSO skb, and we
5576 * want to determine what size it would be after it is segmented.
5578 * We might want to check:
5579 * - L3+L4+payload size (e.g. IP forwarding)
5580 * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5582 * This is a helper to do that correctly considering GSO_BY_FRAGS.
5586 * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5587 * GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5589 * @max_len: The maximum permissible length.
5591 * Returns true if the segmented length <= max length.
5593 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5594 unsigned int seg_len,
5595 unsigned int max_len) {
5596 const struct skb_shared_info *shinfo = skb_shinfo(skb);
5597 const struct sk_buff *iter;
5599 if (shinfo->gso_size != GSO_BY_FRAGS)
5600 return seg_len <= max_len;
5602 /* Undo this so we can re-use header sizes */
5603 seg_len -= GSO_BY_FRAGS;
5605 skb_walk_frags(skb, iter) {
5606 if (seg_len + skb_headlen(iter) > max_len)
5614 * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5617 * @mtu: MTU to validate against
5619 * skb_gso_validate_network_len validates if a given skb will fit a
5620 * wanted MTU once split. It considers L3 headers, L4 headers, and the
5623 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5625 return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5627 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5630 * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5633 * @len: length to validate against
5635 * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5636 * length once split, including L2, L3 and L4 headers and the payload.
5638 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5640 return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5642 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5644 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5646 int mac_len, meta_len;
5649 if (skb_cow(skb, skb_headroom(skb)) < 0) {
5654 mac_len = skb->data - skb_mac_header(skb);
5655 if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5656 memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5657 mac_len - VLAN_HLEN - ETH_TLEN);
5660 meta_len = skb_metadata_len(skb);
5662 meta = skb_metadata_end(skb) - meta_len;
5663 memmove(meta + VLAN_HLEN, meta, meta_len);
5666 skb->mac_header += VLAN_HLEN;
5670 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5672 struct vlan_hdr *vhdr;
5675 if (unlikely(skb_vlan_tag_present(skb))) {
5676 /* vlan_tci is already set-up so leave this for another time */
5680 skb = skb_share_check(skb, GFP_ATOMIC);
5683 /* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5684 if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5687 vhdr = (struct vlan_hdr *)skb->data;
5688 vlan_tci = ntohs(vhdr->h_vlan_TCI);
5689 __vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5691 skb_pull_rcsum(skb, VLAN_HLEN);
5692 vlan_set_encap_proto(skb, vhdr);
5694 skb = skb_reorder_vlan_header(skb);
5698 skb_reset_network_header(skb);
5699 if (!skb_transport_header_was_set(skb))
5700 skb_reset_transport_header(skb);
5701 skb_reset_mac_len(skb);
5709 EXPORT_SYMBOL(skb_vlan_untag);
5711 int skb_ensure_writable(struct sk_buff *skb, int write_len)
5713 if (!pskb_may_pull(skb, write_len))
5716 if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5719 return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5721 EXPORT_SYMBOL(skb_ensure_writable);
5723 /* remove VLAN header from packet and update csum accordingly.
5724 * expects a non skb_vlan_tag_present skb with a vlan tag payload
5726 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5728 struct vlan_hdr *vhdr;
5729 int offset = skb->data - skb_mac_header(skb);
5732 if (WARN_ONCE(offset,
5733 "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5738 err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5742 skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5744 vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5745 *vlan_tci = ntohs(vhdr->h_vlan_TCI);
5747 memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5748 __skb_pull(skb, VLAN_HLEN);
5750 vlan_set_encap_proto(skb, vhdr);
5751 skb->mac_header += VLAN_HLEN;
5753 if (skb_network_offset(skb) < ETH_HLEN)
5754 skb_set_network_header(skb, ETH_HLEN);
5756 skb_reset_mac_len(skb);
5760 EXPORT_SYMBOL(__skb_vlan_pop);
5762 /* Pop a vlan tag either from hwaccel or from payload.
5763 * Expects skb->data at mac header.
5765 int skb_vlan_pop(struct sk_buff *skb)
5771 if (likely(skb_vlan_tag_present(skb))) {
5772 __vlan_hwaccel_clear_tag(skb);
5774 if (unlikely(!eth_type_vlan(skb->protocol)))
5777 err = __skb_vlan_pop(skb, &vlan_tci);
5781 /* move next vlan tag to hw accel tag */
5782 if (likely(!eth_type_vlan(skb->protocol)))
5785 vlan_proto = skb->protocol;
5786 err = __skb_vlan_pop(skb, &vlan_tci);
5790 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5793 EXPORT_SYMBOL(skb_vlan_pop);
5795 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5796 * Expects skb->data at mac header.
5798 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5800 if (skb_vlan_tag_present(skb)) {
5801 int offset = skb->data - skb_mac_header(skb);
5804 if (WARN_ONCE(offset,
5805 "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5810 err = __vlan_insert_tag(skb, skb->vlan_proto,
5811 skb_vlan_tag_get(skb));
5815 skb->protocol = skb->vlan_proto;
5816 skb->mac_len += VLAN_HLEN;
5818 skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5820 __vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5823 EXPORT_SYMBOL(skb_vlan_push);
5826 * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5828 * @skb: Socket buffer to modify
5830 * Drop the Ethernet header of @skb.
5832 * Expects that skb->data points to the mac header and that no VLAN tags are
5835 * Returns 0 on success, -errno otherwise.
5837 int skb_eth_pop(struct sk_buff *skb)
5839 if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5840 skb_network_offset(skb) < ETH_HLEN)
5843 skb_pull_rcsum(skb, ETH_HLEN);
5844 skb_reset_mac_header(skb);
5845 skb_reset_mac_len(skb);
5849 EXPORT_SYMBOL(skb_eth_pop);
5852 * skb_eth_push() - Add a new Ethernet header at the head of a packet
5854 * @skb: Socket buffer to modify
5855 * @dst: Destination MAC address of the new header
5856 * @src: Source MAC address of the new header
5858 * Prepend @skb with a new Ethernet header.
5860 * Expects that skb->data points to the mac header, which must be empty.
5862 * Returns 0 on success, -errno otherwise.
5864 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5865 const unsigned char *src)
5870 if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5873 err = skb_cow_head(skb, sizeof(*eth));
5877 skb_push(skb, sizeof(*eth));
5878 skb_reset_mac_header(skb);
5879 skb_reset_mac_len(skb);
5882 ether_addr_copy(eth->h_dest, dst);
5883 ether_addr_copy(eth->h_source, src);
5884 eth->h_proto = skb->protocol;
5886 skb_postpush_rcsum(skb, eth, sizeof(*eth));
5890 EXPORT_SYMBOL(skb_eth_push);
5892 /* Update the ethertype of hdr and the skb csum value if required. */
5893 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5896 if (skb->ip_summed == CHECKSUM_COMPLETE) {
5897 __be16 diff[] = { ~hdr->h_proto, ethertype };
5899 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5902 hdr->h_proto = ethertype;
5906 * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5910 * @mpls_lse: MPLS label stack entry to push
5911 * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5912 * @mac_len: length of the MAC header
5913 * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5916 * Expects skb->data at mac header.
5918 * Returns 0 on success, -errno otherwise.
5920 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5921 int mac_len, bool ethernet)
5923 struct mpls_shim_hdr *lse;
5926 if (unlikely(!eth_p_mpls(mpls_proto)))
5929 /* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5930 if (skb->encapsulation)
5933 err = skb_cow_head(skb, MPLS_HLEN);
5937 if (!skb->inner_protocol) {
5938 skb_set_inner_network_header(skb, skb_network_offset(skb));
5939 skb_set_inner_protocol(skb, skb->protocol);
5942 skb_push(skb, MPLS_HLEN);
5943 memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5945 skb_reset_mac_header(skb);
5946 skb_set_network_header(skb, mac_len);
5947 skb_reset_mac_len(skb);
5949 lse = mpls_hdr(skb);
5950 lse->label_stack_entry = mpls_lse;
5951 skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5953 if (ethernet && mac_len >= ETH_HLEN)
5954 skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5955 skb->protocol = mpls_proto;
5959 EXPORT_SYMBOL_GPL(skb_mpls_push);
5962 * skb_mpls_pop() - pop the outermost MPLS header
5965 * @next_proto: ethertype of header after popped MPLS header
5966 * @mac_len: length of the MAC header
5967 * @ethernet: flag to indicate if the packet is ethernet
5969 * Expects skb->data at mac header.
5971 * Returns 0 on success, -errno otherwise.
5973 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5978 if (unlikely(!eth_p_mpls(skb->protocol)))
5981 err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5985 skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5986 memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5989 __skb_pull(skb, MPLS_HLEN);
5990 skb_reset_mac_header(skb);
5991 skb_set_network_header(skb, mac_len);
5993 if (ethernet && mac_len >= ETH_HLEN) {
5996 /* use mpls_hdr() to get ethertype to account for VLANs. */
5997 hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5998 skb_mod_eth_type(skb, hdr, next_proto);
6000 skb->protocol = next_proto;
6004 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6007 * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6010 * @mpls_lse: new MPLS label stack entry to update to
6012 * Expects skb->data at mac header.
6014 * Returns 0 on success, -errno otherwise.
6016 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6020 if (unlikely(!eth_p_mpls(skb->protocol)))
6023 err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6027 if (skb->ip_summed == CHECKSUM_COMPLETE) {
6028 __be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6030 skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6033 mpls_hdr(skb)->label_stack_entry = mpls_lse;
6037 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6040 * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6044 * Expects skb->data at mac header.
6046 * Returns 0 on success, -errno otherwise.
6048 int skb_mpls_dec_ttl(struct sk_buff *skb)
6053 if (unlikely(!eth_p_mpls(skb->protocol)))
6056 if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6059 lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6060 ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6064 lse &= ~MPLS_LS_TTL_MASK;
6065 lse |= ttl << MPLS_LS_TTL_SHIFT;
6067 return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6069 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6072 * alloc_skb_with_frags - allocate skb with page frags
6074 * @header_len: size of linear part
6075 * @data_len: needed length in frags
6076 * @max_page_order: max page order desired.
6077 * @errcode: pointer to error code if any
6078 * @gfp_mask: allocation mask
6080 * This can be used to allocate a paged skb, given a maximal order for frags.
6082 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6083 unsigned long data_len,
6088 int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6089 unsigned long chunk;
6090 struct sk_buff *skb;
6094 *errcode = -EMSGSIZE;
6095 /* Note this test could be relaxed, if we succeed to allocate
6096 * high order pages...
6098 if (npages > MAX_SKB_FRAGS)
6101 *errcode = -ENOBUFS;
6102 skb = alloc_skb(header_len, gfp_mask);
6106 skb->truesize += npages << PAGE_SHIFT;
6108 for (i = 0; npages > 0; i++) {
6109 int order = max_page_order;
6112 if (npages >= 1 << order) {
6113 page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6119 /* Do not retry other high order allocations */
6125 page = alloc_page(gfp_mask);
6129 chunk = min_t(unsigned long, data_len,
6130 PAGE_SIZE << order);
6131 skb_fill_page_desc(skb, i, page, 0, chunk);
6133 npages -= 1 << order;
6141 EXPORT_SYMBOL(alloc_skb_with_frags);
6143 /* carve out the first off bytes from skb when off < headlen */
6144 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6145 const int headlen, gfp_t gfp_mask)
6148 int size = skb_end_offset(skb);
6149 int new_hlen = headlen - off;
6152 size = SKB_DATA_ALIGN(size);
6154 if (skb_pfmemalloc(skb))
6155 gfp_mask |= __GFP_MEMALLOC;
6156 data = kmalloc_reserve(size +
6157 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6158 gfp_mask, NUMA_NO_NODE, NULL);
6162 size = SKB_WITH_OVERHEAD(ksize(data));
6164 /* Copy real data, and all frags */
6165 skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6168 memcpy((struct skb_shared_info *)(data + size),
6170 offsetof(struct skb_shared_info,
6171 frags[skb_shinfo(skb)->nr_frags]));
6172 if (skb_cloned(skb)) {
6173 /* drop the old head gracefully */
6174 if (skb_orphan_frags(skb, gfp_mask)) {
6178 for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6179 skb_frag_ref(skb, i);
6180 if (skb_has_frag_list(skb))
6181 skb_clone_fraglist(skb);
6182 skb_release_data(skb);
6184 /* we can reuse existing recount- all we did was
6193 skb_set_end_offset(skb, size);
6194 skb_set_tail_pointer(skb, skb_headlen(skb));
6195 skb_headers_offset_update(skb, 0);
6199 atomic_set(&skb_shinfo(skb)->dataref, 1);
6204 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6206 /* carve out the first eat bytes from skb's frag_list. May recurse into
6209 static int pskb_carve_frag_list(struct sk_buff *skb,
6210 struct skb_shared_info *shinfo, int eat,
6213 struct sk_buff *list = shinfo->frag_list;
6214 struct sk_buff *clone = NULL;
6215 struct sk_buff *insp = NULL;
6219 pr_err("Not enough bytes to eat. Want %d\n", eat);
6222 if (list->len <= eat) {
6223 /* Eaten as whole. */
6228 /* Eaten partially. */
6229 if (skb_shared(list)) {
6230 clone = skb_clone(list, gfp_mask);
6236 /* This may be pulled without problems. */
6239 if (pskb_carve(list, eat, gfp_mask) < 0) {
6247 /* Free pulled out fragments. */
6248 while ((list = shinfo->frag_list) != insp) {
6249 shinfo->frag_list = list->next;
6252 /* And insert new clone at head. */
6255 shinfo->frag_list = clone;
6260 /* carve off first len bytes from skb. Split line (off) is in the
6261 * non-linear part of skb
6263 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6264 int pos, gfp_t gfp_mask)
6267 int size = skb_end_offset(skb);
6269 const int nfrags = skb_shinfo(skb)->nr_frags;
6270 struct skb_shared_info *shinfo;
6272 size = SKB_DATA_ALIGN(size);
6274 if (skb_pfmemalloc(skb))
6275 gfp_mask |= __GFP_MEMALLOC;
6276 data = kmalloc_reserve(size +
6277 SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6278 gfp_mask, NUMA_NO_NODE, NULL);
6282 size = SKB_WITH_OVERHEAD(ksize(data));
6284 memcpy((struct skb_shared_info *)(data + size),
6285 skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6286 if (skb_orphan_frags(skb, gfp_mask)) {
6290 shinfo = (struct skb_shared_info *)(data + size);
6291 for (i = 0; i < nfrags; i++) {
6292 int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6294 if (pos + fsize > off) {
6295 shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6299 * We have two variants in this case:
6300 * 1. Move all the frag to the second
6301 * part, if it is possible. F.e.
6302 * this approach is mandatory for TUX,
6303 * where splitting is expensive.
6304 * 2. Split is accurately. We make this.
6306 skb_frag_off_add(&shinfo->frags[0], off - pos);
6307 skb_frag_size_sub(&shinfo->frags[0], off - pos);
6309 skb_frag_ref(skb, i);
6314 shinfo->nr_frags = k;
6315 if (skb_has_frag_list(skb))
6316 skb_clone_fraglist(skb);
6318 /* split line is in frag list */
6319 if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6320 /* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6321 if (skb_has_frag_list(skb))
6322 kfree_skb_list(skb_shinfo(skb)->frag_list);
6326 skb_release_data(skb);
6331 skb_set_end_offset(skb, size);
6332 skb_reset_tail_pointer(skb);
6333 skb_headers_offset_update(skb, 0);
6338 skb->data_len = skb->len;
6339 atomic_set(&skb_shinfo(skb)->dataref, 1);
6343 /* remove len bytes from the beginning of the skb */
6344 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6346 int headlen = skb_headlen(skb);
6349 return pskb_carve_inside_header(skb, len, headlen, gfp);
6351 return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6354 /* Extract to_copy bytes starting at off from skb, and return this in
6357 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6358 int to_copy, gfp_t gfp)
6360 struct sk_buff *clone = skb_clone(skb, gfp);
6365 if (pskb_carve(clone, off, gfp) < 0 ||
6366 pskb_trim(clone, to_copy)) {
6372 EXPORT_SYMBOL(pskb_extract);
6375 * skb_condense - try to get rid of fragments/frag_list if possible
6378 * Can be used to save memory before skb is added to a busy queue.
6379 * If packet has bytes in frags and enough tail room in skb->head,
6380 * pull all of them, so that we can free the frags right now and adjust
6383 * We do not reallocate skb->head thus can not fail.
6384 * Caller must re-evaluate skb->truesize if needed.
6386 void skb_condense(struct sk_buff *skb)
6388 if (skb->data_len) {
6389 if (skb->data_len > skb->end - skb->tail ||
6393 /* Nice, we can free page frag(s) right now */
6394 __pskb_pull_tail(skb, skb->data_len);
6396 /* At this point, skb->truesize might be over estimated,
6397 * because skb had a fragment, and fragments do not tell
6399 * When we pulled its content into skb->head, fragment
6400 * was freed, but __pskb_pull_tail() could not possibly
6401 * adjust skb->truesize, not knowing the frag truesize.
6403 skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6406 #ifdef CONFIG_SKB_EXTENSIONS
6407 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6409 return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6413 * __skb_ext_alloc - allocate a new skb extensions storage
6415 * @flags: See kmalloc().
6417 * Returns the newly allocated pointer. The pointer can later attached to a
6418 * skb via __skb_ext_set().
6419 * Note: caller must handle the skb_ext as an opaque data.
6421 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6423 struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6426 memset(new->offset, 0, sizeof(new->offset));
6427 refcount_set(&new->refcnt, 1);
6433 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6434 unsigned int old_active)
6436 struct skb_ext *new;
6438 if (refcount_read(&old->refcnt) == 1)
6441 new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6445 memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6446 refcount_set(&new->refcnt, 1);
6449 if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6450 struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6453 for (i = 0; i < sp->len; i++)
6454 xfrm_state_hold(sp->xvec[i]);
6462 * __skb_ext_set - attach the specified extension storage to this skb
6465 * @ext: extension storage previously allocated via __skb_ext_alloc()
6467 * Existing extensions, if any, are cleared.
6469 * Returns the pointer to the extension.
6471 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6472 struct skb_ext *ext)
6474 unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6477 newlen = newoff + skb_ext_type_len[id];
6478 ext->chunks = newlen;
6479 ext->offset[id] = newoff;
6480 skb->extensions = ext;
6481 skb->active_extensions = 1 << id;
6482 return skb_ext_get_ptr(ext, id);
6486 * skb_ext_add - allocate space for given extension, COW if needed
6488 * @id: extension to allocate space for
6490 * Allocates enough space for the given extension.
6491 * If the extension is already present, a pointer to that extension
6494 * If the skb was cloned, COW applies and the returned memory can be
6495 * modified without changing the extension space of clones buffers.
6497 * Returns pointer to the extension or NULL on allocation failure.
6499 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6501 struct skb_ext *new, *old = NULL;
6502 unsigned int newlen, newoff;
6504 if (skb->active_extensions) {
6505 old = skb->extensions;
6507 new = skb_ext_maybe_cow(old, skb->active_extensions);
6511 if (__skb_ext_exist(new, id))
6514 newoff = new->chunks;
6516 newoff = SKB_EXT_CHUNKSIZEOF(*new);
6518 new = __skb_ext_alloc(GFP_ATOMIC);
6523 newlen = newoff + skb_ext_type_len[id];
6524 new->chunks = newlen;
6525 new->offset[id] = newoff;
6528 skb->extensions = new;
6529 skb->active_extensions |= 1 << id;
6530 return skb_ext_get_ptr(new, id);
6532 EXPORT_SYMBOL(skb_ext_add);
6535 static void skb_ext_put_sp(struct sec_path *sp)
6539 for (i = 0; i < sp->len; i++)
6540 xfrm_state_put(sp->xvec[i]);
6544 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6546 struct skb_ext *ext = skb->extensions;
6548 skb->active_extensions &= ~(1 << id);
6549 if (skb->active_extensions == 0) {
6550 skb->extensions = NULL;
6553 } else if (id == SKB_EXT_SEC_PATH &&
6554 refcount_read(&ext->refcnt) == 1) {
6555 struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6562 EXPORT_SYMBOL(__skb_ext_del);
6564 void __skb_ext_put(struct skb_ext *ext)
6566 /* If this is last clone, nothing can increment
6567 * it after check passes. Avoids one atomic op.
6569 if (refcount_read(&ext->refcnt) == 1)
6572 if (!refcount_dec_and_test(&ext->refcnt))
6576 if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6577 skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6580 kmem_cache_free(skbuff_ext_cache, ext);
6582 EXPORT_SYMBOL(__skb_ext_put);
6583 #endif /* CONFIG_SKB_EXTENSIONS */