xref: /openbmc/linux/net/core/skbuff.c (revision 03f61041)
12874c5fdSThomas Gleixner // SPDX-License-Identifier: GPL-2.0-or-later
21da177e4SLinus Torvalds /*
31da177e4SLinus Torvalds  *	Routines having to do with the 'struct sk_buff' memory handlers.
41da177e4SLinus Torvalds  *
5113aa838SAlan Cox  *	Authors:	Alan Cox <alan@lxorguk.ukuu.org.uk>
61da177e4SLinus Torvalds  *			Florian La Roche <rzsfl@rz.uni-sb.de>
71da177e4SLinus Torvalds  *
81da177e4SLinus Torvalds  *	Fixes:
91da177e4SLinus Torvalds  *		Alan Cox	:	Fixed the worst of the load
101da177e4SLinus Torvalds  *					balancer bugs.
111da177e4SLinus Torvalds  *		Dave Platt	:	Interrupt stacking fix.
121da177e4SLinus Torvalds  *	Richard Kooijman	:	Timestamp fixes.
131da177e4SLinus Torvalds  *		Alan Cox	:	Changed buffer format.
141da177e4SLinus Torvalds  *		Alan Cox	:	destructor hook for AF_UNIX etc.
151da177e4SLinus Torvalds  *		Linus Torvalds	:	Better skb_clone.
161da177e4SLinus Torvalds  *		Alan Cox	:	Added skb_copy.
171da177e4SLinus Torvalds  *		Alan Cox	:	Added all the changed routines Linus
181da177e4SLinus Torvalds  *					only put in the headers
191da177e4SLinus Torvalds  *		Ray VanTassle	:	Fixed --skb->lock in free
201da177e4SLinus Torvalds  *		Alan Cox	:	skb_copy copy arp field
211da177e4SLinus Torvalds  *		Andi Kleen	:	slabified it.
221da177e4SLinus Torvalds  *		Robert Olsson	:	Removed skb_head_pool
231da177e4SLinus Torvalds  *
241da177e4SLinus Torvalds  *	NOTE:
251da177e4SLinus Torvalds  *		The __skb_ routines should be called with interrupts
261da177e4SLinus Torvalds  *	disabled, or you better be *real* sure that the operation is atomic
271da177e4SLinus Torvalds  *	with respect to whatever list is being frobbed (e.g. via lock_sock()
281da177e4SLinus Torvalds  *	or via disabling bottom half handlers, etc).
291da177e4SLinus Torvalds  */
301da177e4SLinus Torvalds 
311da177e4SLinus Torvalds /*
321da177e4SLinus Torvalds  *	The functions in this file will not compile correctly with gcc 2.4.x
331da177e4SLinus Torvalds  */
341da177e4SLinus Torvalds 
35e005d193SJoe Perches #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
36e005d193SJoe Perches 
371da177e4SLinus Torvalds #include <linux/module.h>
381da177e4SLinus Torvalds #include <linux/types.h>
391da177e4SLinus Torvalds #include <linux/kernel.h>
401da177e4SLinus Torvalds #include <linux/mm.h>
411da177e4SLinus Torvalds #include <linux/interrupt.h>
421da177e4SLinus Torvalds #include <linux/in.h>
431da177e4SLinus Torvalds #include <linux/inet.h>
441da177e4SLinus Torvalds #include <linux/slab.h>
45de960aa9SFlorian Westphal #include <linux/tcp.h>
46de960aa9SFlorian Westphal #include <linux/udp.h>
4790017accSMarcelo Ricardo Leitner #include <linux/sctp.h>
481da177e4SLinus Torvalds #include <linux/netdevice.h>
491da177e4SLinus Torvalds #ifdef CONFIG_NET_CLS_ACT
501da177e4SLinus Torvalds #include <net/pkt_sched.h>
511da177e4SLinus Torvalds #endif
521da177e4SLinus Torvalds #include <linux/string.h>
531da177e4SLinus Torvalds #include <linux/skbuff.h>
549c55e01cSJens Axboe #include <linux/splice.h>
551da177e4SLinus Torvalds #include <linux/cache.h>
561da177e4SLinus Torvalds #include <linux/rtnetlink.h>
571da177e4SLinus Torvalds #include <linux/init.h>
58716ea3a7SDavid Howells #include <linux/scatterlist.h>
59ac45f602SPatrick Ohly #include <linux/errqueue.h>
60268bb0ceSLinus Torvalds #include <linux/prefetch.h>
610d5501c1SVlad Yasevich #include <linux/if_vlan.h>
622a2ea508SJohn Hurley #include <linux/mpls.h>
63183f47fcSSebastian Andrzej Siewior #include <linux/kcov.h>
641da177e4SLinus Torvalds 
651da177e4SLinus Torvalds #include <net/protocol.h>
661da177e4SLinus Torvalds #include <net/dst.h>
671da177e4SLinus Torvalds #include <net/sock.h>
681da177e4SLinus Torvalds #include <net/checksum.h>
69ed1f50c3SPaul Durrant #include <net/ip6_checksum.h>
701da177e4SLinus Torvalds #include <net/xfrm.h>
718822e270SJohn Hurley #include <net/mpls.h>
723ee17bc7SMat Martineau #include <net/mptcp.h>
7378476d31SJeremy Kerr #include <net/mctp.h>
746a5bcd84SIlias Apalodimas #include <net/page_pool.h>
751da177e4SLinus Torvalds 
767c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
77ad8d75ffSSteven Rostedt #include <trace/events/skb.h>
7851c56b00SEric Dumazet #include <linux/highmem.h>
79b245be1fSWillem de Bruijn #include <linux/capability.h>
80b245be1fSWillem de Bruijn #include <linux/user_namespace.h>
812544af03SMatteo Croce #include <linux/indirect_call_wrapper.h>
82a1f8e7f7SAl Viro 
837b7ed885SBart Van Assche #include "datagram.h"
847f678defSVasily Averin #include "sock_destructor.h"
857b7ed885SBart Van Assche 
8608009a76SAlexey Dobriyan struct kmem_cache *skbuff_head_cache __ro_after_init;
8708009a76SAlexey Dobriyan static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
88df5042f4SFlorian Westphal #ifdef CONFIG_SKB_EXTENSIONS
89df5042f4SFlorian Westphal static struct kmem_cache *skbuff_ext_cache __ro_after_init;
90df5042f4SFlorian Westphal #endif
915f74f82eSHans Westgaard Ry int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
925f74f82eSHans Westgaard Ry EXPORT_SYMBOL(sysctl_max_skb_frags);
931da177e4SLinus Torvalds 
941da177e4SLinus Torvalds /**
95f05de73bSJean Sacren  *	skb_panic - private function for out-of-line support
961da177e4SLinus Torvalds  *	@skb:	buffer
971da177e4SLinus Torvalds  *	@sz:	size
98f05de73bSJean Sacren  *	@addr:	address
9999d5851eSJames Hogan  *	@msg:	skb_over_panic or skb_under_panic
1001da177e4SLinus Torvalds  *
101f05de73bSJean Sacren  *	Out-of-line support for skb_put() and skb_push().
102f05de73bSJean Sacren  *	Called via the wrapper skb_over_panic() or skb_under_panic().
103f05de73bSJean Sacren  *	Keep out of line to prevent kernel bloat.
104f05de73bSJean Sacren  *	__builtin_return_address is not used because it is not always reliable.
1051da177e4SLinus Torvalds  */
106f05de73bSJean Sacren static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
10799d5851eSJames Hogan 		      const char msg[])
1081da177e4SLinus Torvalds {
10941a46913SJesper Dangaard Brouer 	pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
11099d5851eSJames Hogan 		 msg, addr, skb->len, sz, skb->head, skb->data,
1114305b541SArnaldo Carvalho de Melo 		 (unsigned long)skb->tail, (unsigned long)skb->end,
11226095455SPatrick McHardy 		 skb->dev ? skb->dev->name : "<NULL>");
1131da177e4SLinus Torvalds 	BUG();
1141da177e4SLinus Torvalds }
1151da177e4SLinus Torvalds 
116f05de73bSJean Sacren static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
1171da177e4SLinus Torvalds {
118f05de73bSJean Sacren 	skb_panic(skb, sz, addr, __func__);
1191da177e4SLinus Torvalds }
1201da177e4SLinus Torvalds 
121f05de73bSJean Sacren static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
122f05de73bSJean Sacren {
123f05de73bSJean Sacren 	skb_panic(skb, sz, addr, __func__);
124f05de73bSJean Sacren }
125c93bdd0eSMel Gorman 
12650fad4b5SAlexander Lobakin #define NAPI_SKB_CACHE_SIZE	64
127f450d539SAlexander Lobakin #define NAPI_SKB_CACHE_BULK	16
128f450d539SAlexander Lobakin #define NAPI_SKB_CACHE_HALF	(NAPI_SKB_CACHE_SIZE / 2)
12950fad4b5SAlexander Lobakin 
13050fad4b5SAlexander Lobakin struct napi_alloc_cache {
13150fad4b5SAlexander Lobakin 	struct page_frag_cache page;
13250fad4b5SAlexander Lobakin 	unsigned int skb_count;
13350fad4b5SAlexander Lobakin 	void *skb_cache[NAPI_SKB_CACHE_SIZE];
13450fad4b5SAlexander Lobakin };
13550fad4b5SAlexander Lobakin 
13650fad4b5SAlexander Lobakin static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
13750fad4b5SAlexander Lobakin static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
13850fad4b5SAlexander Lobakin 
13932e3573fSYajun Deng void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
14050fad4b5SAlexander Lobakin {
14150fad4b5SAlexander Lobakin 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
14250fad4b5SAlexander Lobakin 
14350fad4b5SAlexander Lobakin 	fragsz = SKB_DATA_ALIGN(fragsz);
14450fad4b5SAlexander Lobakin 
14532e3573fSYajun Deng 	return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
14650fad4b5SAlexander Lobakin }
14750fad4b5SAlexander Lobakin EXPORT_SYMBOL(__napi_alloc_frag_align);
14850fad4b5SAlexander Lobakin 
14950fad4b5SAlexander Lobakin void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
15050fad4b5SAlexander Lobakin {
15150fad4b5SAlexander Lobakin 	void *data;
15250fad4b5SAlexander Lobakin 
15350fad4b5SAlexander Lobakin 	fragsz = SKB_DATA_ALIGN(fragsz);
154afa79d08SChangbin Du 	if (in_hardirq() || irqs_disabled()) {
15532e3573fSYajun Deng 		struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
15632e3573fSYajun Deng 
15750fad4b5SAlexander Lobakin 		data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
15850fad4b5SAlexander Lobakin 	} else {
15932e3573fSYajun Deng 		struct napi_alloc_cache *nc;
16032e3573fSYajun Deng 
16150fad4b5SAlexander Lobakin 		local_bh_disable();
16232e3573fSYajun Deng 		nc = this_cpu_ptr(&napi_alloc_cache);
16332e3573fSYajun Deng 		data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
16450fad4b5SAlexander Lobakin 		local_bh_enable();
16550fad4b5SAlexander Lobakin 	}
16650fad4b5SAlexander Lobakin 	return data;
16750fad4b5SAlexander Lobakin }
16850fad4b5SAlexander Lobakin EXPORT_SYMBOL(__netdev_alloc_frag_align);
16950fad4b5SAlexander Lobakin 
170f450d539SAlexander Lobakin static struct sk_buff *napi_skb_cache_get(void)
171f450d539SAlexander Lobakin {
172f450d539SAlexander Lobakin 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
173f450d539SAlexander Lobakin 	struct sk_buff *skb;
174f450d539SAlexander Lobakin 
175f450d539SAlexander Lobakin 	if (unlikely(!nc->skb_count))
176f450d539SAlexander Lobakin 		nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
177f450d539SAlexander Lobakin 						      GFP_ATOMIC,
178f450d539SAlexander Lobakin 						      NAPI_SKB_CACHE_BULK,
179f450d539SAlexander Lobakin 						      nc->skb_cache);
180f450d539SAlexander Lobakin 	if (unlikely(!nc->skb_count))
181f450d539SAlexander Lobakin 		return NULL;
182f450d539SAlexander Lobakin 
183f450d539SAlexander Lobakin 	skb = nc->skb_cache[--nc->skb_count];
184f450d539SAlexander Lobakin 	kasan_unpoison_object_data(skbuff_head_cache, skb);
185f450d539SAlexander Lobakin 
186f450d539SAlexander Lobakin 	return skb;
187f450d539SAlexander Lobakin }
188f450d539SAlexander Lobakin 
189ba0509b6SJesper Dangaard Brouer /* Caller must provide SKB that is memset cleared */
190483126b3SAlexander Lobakin static void __build_skb_around(struct sk_buff *skb, void *data,
191483126b3SAlexander Lobakin 			       unsigned int frag_size)
192ba0509b6SJesper Dangaard Brouer {
193ba0509b6SJesper Dangaard Brouer 	struct skb_shared_info *shinfo;
194ba0509b6SJesper Dangaard Brouer 	unsigned int size = frag_size ? : ksize(data);
195ba0509b6SJesper Dangaard Brouer 
196ba0509b6SJesper Dangaard Brouer 	size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
197ba0509b6SJesper Dangaard Brouer 
198ba0509b6SJesper Dangaard Brouer 	/* Assumes caller memset cleared SKB */
199ba0509b6SJesper Dangaard Brouer 	skb->truesize = SKB_TRUESIZE(size);
200ba0509b6SJesper Dangaard Brouer 	refcount_set(&skb->users, 1);
201ba0509b6SJesper Dangaard Brouer 	skb->head = data;
202ba0509b6SJesper Dangaard Brouer 	skb->data = data;
203ba0509b6SJesper Dangaard Brouer 	skb_reset_tail_pointer(skb);
204ba0509b6SJesper Dangaard Brouer 	skb->end = skb->tail + size;
205ba0509b6SJesper Dangaard Brouer 	skb->mac_header = (typeof(skb->mac_header))~0U;
206ba0509b6SJesper Dangaard Brouer 	skb->transport_header = (typeof(skb->transport_header))~0U;
207ba0509b6SJesper Dangaard Brouer 
208ba0509b6SJesper Dangaard Brouer 	/* make sure we initialize shinfo sequentially */
209ba0509b6SJesper Dangaard Brouer 	shinfo = skb_shinfo(skb);
210ba0509b6SJesper Dangaard Brouer 	memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
211ba0509b6SJesper Dangaard Brouer 	atomic_set(&shinfo->dataref, 1);
212ba0509b6SJesper Dangaard Brouer 
2136370cc3bSAleksandr Nogikh 	skb_set_kcov_handle(skb, kcov_common_handle());
214ba0509b6SJesper Dangaard Brouer }
215ba0509b6SJesper Dangaard Brouer 
2161da177e4SLinus Torvalds /**
2172ea2f62cSEric Dumazet  * __build_skb - build a network buffer
218b2b5ce9dSEric Dumazet  * @data: data buffer provided by caller
2192ea2f62cSEric Dumazet  * @frag_size: size of data, or 0 if head was kmalloced
220b2b5ce9dSEric Dumazet  *
221b2b5ce9dSEric Dumazet  * Allocate a new &sk_buff. Caller provides space holding head and
222deceb4c0SFlorian Fainelli  * skb_shared_info. @data must have been allocated by kmalloc() only if
2232ea2f62cSEric Dumazet  * @frag_size is 0, otherwise data should come from the page allocator
2242ea2f62cSEric Dumazet  *  or vmalloc()
225b2b5ce9dSEric Dumazet  * The return is the new skb buffer.
226b2b5ce9dSEric Dumazet  * On a failure the return is %NULL, and @data is not freed.
227b2b5ce9dSEric Dumazet  * Notes :
228b2b5ce9dSEric Dumazet  *  Before IO, driver allocates only data buffer where NIC put incoming frame
229b2b5ce9dSEric Dumazet  *  Driver should add room at head (NET_SKB_PAD) and
230b2b5ce9dSEric Dumazet  *  MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
231b2b5ce9dSEric Dumazet  *  After IO, driver calls build_skb(), to allocate sk_buff and populate it
232b2b5ce9dSEric Dumazet  *  before giving packet to stack.
233b2b5ce9dSEric Dumazet  *  RX rings only contains data buffers, not full skbs.
234b2b5ce9dSEric Dumazet  */
2352ea2f62cSEric Dumazet struct sk_buff *__build_skb(void *data, unsigned int frag_size)
236b2b5ce9dSEric Dumazet {
237b2b5ce9dSEric Dumazet 	struct sk_buff *skb;
238b2b5ce9dSEric Dumazet 
239b2b5ce9dSEric Dumazet 	skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
240ba0509b6SJesper Dangaard Brouer 	if (unlikely(!skb))
241b2b5ce9dSEric Dumazet 		return NULL;
242b2b5ce9dSEric Dumazet 
243b2b5ce9dSEric Dumazet 	memset(skb, 0, offsetof(struct sk_buff, tail));
244483126b3SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
245b2b5ce9dSEric Dumazet 
246483126b3SAlexander Lobakin 	return skb;
247b2b5ce9dSEric Dumazet }
2482ea2f62cSEric Dumazet 
2492ea2f62cSEric Dumazet /* build_skb() is wrapper over __build_skb(), that specifically
2502ea2f62cSEric Dumazet  * takes care of skb->head and skb->pfmemalloc
2512ea2f62cSEric Dumazet  * This means that if @frag_size is not zero, then @data must be backed
2522ea2f62cSEric Dumazet  * by a page fragment, not kmalloc() or vmalloc()
2532ea2f62cSEric Dumazet  */
2542ea2f62cSEric Dumazet struct sk_buff *build_skb(void *data, unsigned int frag_size)
2552ea2f62cSEric Dumazet {
2562ea2f62cSEric Dumazet 	struct sk_buff *skb = __build_skb(data, frag_size);
2572ea2f62cSEric Dumazet 
2582ea2f62cSEric Dumazet 	if (skb && frag_size) {
2592ea2f62cSEric Dumazet 		skb->head_frag = 1;
2602f064f34SMichal Hocko 		if (page_is_pfmemalloc(virt_to_head_page(data)))
2612ea2f62cSEric Dumazet 			skb->pfmemalloc = 1;
2622ea2f62cSEric Dumazet 	}
2632ea2f62cSEric Dumazet 	return skb;
2642ea2f62cSEric Dumazet }
265b2b5ce9dSEric Dumazet EXPORT_SYMBOL(build_skb);
266b2b5ce9dSEric Dumazet 
267ba0509b6SJesper Dangaard Brouer /**
268ba0509b6SJesper Dangaard Brouer  * build_skb_around - build a network buffer around provided skb
269ba0509b6SJesper Dangaard Brouer  * @skb: sk_buff provide by caller, must be memset cleared
270ba0509b6SJesper Dangaard Brouer  * @data: data buffer provided by caller
271ba0509b6SJesper Dangaard Brouer  * @frag_size: size of data, or 0 if head was kmalloced
272ba0509b6SJesper Dangaard Brouer  */
273ba0509b6SJesper Dangaard Brouer struct sk_buff *build_skb_around(struct sk_buff *skb,
274ba0509b6SJesper Dangaard Brouer 				 void *data, unsigned int frag_size)
275ba0509b6SJesper Dangaard Brouer {
276ba0509b6SJesper Dangaard Brouer 	if (unlikely(!skb))
277ba0509b6SJesper Dangaard Brouer 		return NULL;
278ba0509b6SJesper Dangaard Brouer 
279483126b3SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
280ba0509b6SJesper Dangaard Brouer 
281483126b3SAlexander Lobakin 	if (frag_size) {
282ba0509b6SJesper Dangaard Brouer 		skb->head_frag = 1;
283ba0509b6SJesper Dangaard Brouer 		if (page_is_pfmemalloc(virt_to_head_page(data)))
284ba0509b6SJesper Dangaard Brouer 			skb->pfmemalloc = 1;
285ba0509b6SJesper Dangaard Brouer 	}
286ba0509b6SJesper Dangaard Brouer 	return skb;
287ba0509b6SJesper Dangaard Brouer }
288ba0509b6SJesper Dangaard Brouer EXPORT_SYMBOL(build_skb_around);
289ba0509b6SJesper Dangaard Brouer 
290f450d539SAlexander Lobakin /**
291f450d539SAlexander Lobakin  * __napi_build_skb - build a network buffer
292f450d539SAlexander Lobakin  * @data: data buffer provided by caller
293f450d539SAlexander Lobakin  * @frag_size: size of data, or 0 if head was kmalloced
294f450d539SAlexander Lobakin  *
295f450d539SAlexander Lobakin  * Version of __build_skb() that uses NAPI percpu caches to obtain
296f450d539SAlexander Lobakin  * skbuff_head instead of inplace allocation.
297f450d539SAlexander Lobakin  *
298f450d539SAlexander Lobakin  * Returns a new &sk_buff on success, %NULL on allocation failure.
299f450d539SAlexander Lobakin  */
300f450d539SAlexander Lobakin static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
301f450d539SAlexander Lobakin {
302f450d539SAlexander Lobakin 	struct sk_buff *skb;
303f450d539SAlexander Lobakin 
304f450d539SAlexander Lobakin 	skb = napi_skb_cache_get();
305f450d539SAlexander Lobakin 	if (unlikely(!skb))
306f450d539SAlexander Lobakin 		return NULL;
307f450d539SAlexander Lobakin 
308f450d539SAlexander Lobakin 	memset(skb, 0, offsetof(struct sk_buff, tail));
309f450d539SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
310f450d539SAlexander Lobakin 
311f450d539SAlexander Lobakin 	return skb;
312f450d539SAlexander Lobakin }
313f450d539SAlexander Lobakin 
314f450d539SAlexander Lobakin /**
315f450d539SAlexander Lobakin  * napi_build_skb - build a network buffer
316f450d539SAlexander Lobakin  * @data: data buffer provided by caller
317f450d539SAlexander Lobakin  * @frag_size: size of data, or 0 if head was kmalloced
318f450d539SAlexander Lobakin  *
319f450d539SAlexander Lobakin  * Version of __napi_build_skb() that takes care of skb->head_frag
320f450d539SAlexander Lobakin  * and skb->pfmemalloc when the data is a page or page fragment.
321f450d539SAlexander Lobakin  *
322f450d539SAlexander Lobakin  * Returns a new &sk_buff on success, %NULL on allocation failure.
323f450d539SAlexander Lobakin  */
324f450d539SAlexander Lobakin struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
325f450d539SAlexander Lobakin {
326f450d539SAlexander Lobakin 	struct sk_buff *skb = __napi_build_skb(data, frag_size);
327f450d539SAlexander Lobakin 
328f450d539SAlexander Lobakin 	if (likely(skb) && frag_size) {
329f450d539SAlexander Lobakin 		skb->head_frag = 1;
330f450d539SAlexander Lobakin 		skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
331f450d539SAlexander Lobakin 	}
332f450d539SAlexander Lobakin 
333f450d539SAlexander Lobakin 	return skb;
334f450d539SAlexander Lobakin }
335f450d539SAlexander Lobakin EXPORT_SYMBOL(napi_build_skb);
336f450d539SAlexander Lobakin 
3375381b23dSAlexander Lobakin /*
3385381b23dSAlexander Lobakin  * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
3395381b23dSAlexander Lobakin  * the caller if emergency pfmemalloc reserves are being used. If it is and
3405381b23dSAlexander Lobakin  * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
3415381b23dSAlexander Lobakin  * may be used. Otherwise, the packet data may be discarded until enough
3425381b23dSAlexander Lobakin  * memory is free
3435381b23dSAlexander Lobakin  */
344ef28095fSAlexander Lobakin static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
345ef28095fSAlexander Lobakin 			     bool *pfmemalloc)
3465381b23dSAlexander Lobakin {
3475381b23dSAlexander Lobakin 	void *obj;
3485381b23dSAlexander Lobakin 	bool ret_pfmemalloc = false;
3495381b23dSAlexander Lobakin 
3505381b23dSAlexander Lobakin 	/*
3515381b23dSAlexander Lobakin 	 * Try a regular allocation, when that fails and we're not entitled
3525381b23dSAlexander Lobakin 	 * to the reserves, fail.
3535381b23dSAlexander Lobakin 	 */
3545381b23dSAlexander Lobakin 	obj = kmalloc_node_track_caller(size,
3555381b23dSAlexander Lobakin 					flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
3565381b23dSAlexander Lobakin 					node);
3575381b23dSAlexander Lobakin 	if (obj || !(gfp_pfmemalloc_allowed(flags)))
3585381b23dSAlexander Lobakin 		goto out;
3595381b23dSAlexander Lobakin 
3605381b23dSAlexander Lobakin 	/* Try again but now we are using pfmemalloc reserves */
3615381b23dSAlexander Lobakin 	ret_pfmemalloc = true;
3625381b23dSAlexander Lobakin 	obj = kmalloc_node_track_caller(size, flags, node);
3635381b23dSAlexander Lobakin 
3645381b23dSAlexander Lobakin out:
3655381b23dSAlexander Lobakin 	if (pfmemalloc)
3665381b23dSAlexander Lobakin 		*pfmemalloc = ret_pfmemalloc;
3675381b23dSAlexander Lobakin 
3685381b23dSAlexander Lobakin 	return obj;
3695381b23dSAlexander Lobakin }
3705381b23dSAlexander Lobakin 
3715381b23dSAlexander Lobakin /* 	Allocate a new skbuff. We do this ourselves so we can fill in a few
3725381b23dSAlexander Lobakin  *	'private' fields and also do memory statistics to find all the
3735381b23dSAlexander Lobakin  *	[BEEP] leaks.
3745381b23dSAlexander Lobakin  *
3755381b23dSAlexander Lobakin  */
3765381b23dSAlexander Lobakin 
3775381b23dSAlexander Lobakin /**
3785381b23dSAlexander Lobakin  *	__alloc_skb	-	allocate a network buffer
3795381b23dSAlexander Lobakin  *	@size: size to allocate
3805381b23dSAlexander Lobakin  *	@gfp_mask: allocation mask
3815381b23dSAlexander Lobakin  *	@flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
3825381b23dSAlexander Lobakin  *		instead of head cache and allocate a cloned (child) skb.
3835381b23dSAlexander Lobakin  *		If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
3845381b23dSAlexander Lobakin  *		allocations in case the data is required for writeback
3855381b23dSAlexander Lobakin  *	@node: numa node to allocate memory on
3865381b23dSAlexander Lobakin  *
3875381b23dSAlexander Lobakin  *	Allocate a new &sk_buff. The returned buffer has no headroom and a
3885381b23dSAlexander Lobakin  *	tail room of at least size bytes. The object has a reference count
3895381b23dSAlexander Lobakin  *	of one. The return is the buffer. On a failure the return is %NULL.
3905381b23dSAlexander Lobakin  *
3915381b23dSAlexander Lobakin  *	Buffers may only be allocated from interrupts using a @gfp_mask of
3925381b23dSAlexander Lobakin  *	%GFP_ATOMIC.
3935381b23dSAlexander Lobakin  */
3945381b23dSAlexander Lobakin struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
3955381b23dSAlexander Lobakin 			    int flags, int node)
3965381b23dSAlexander Lobakin {
3975381b23dSAlexander Lobakin 	struct kmem_cache *cache;
3985381b23dSAlexander Lobakin 	struct sk_buff *skb;
399a5df6333SLi RongQing 	unsigned int osize;
4005381b23dSAlexander Lobakin 	bool pfmemalloc;
401a5df6333SLi RongQing 	u8 *data;
4025381b23dSAlexander Lobakin 
4035381b23dSAlexander Lobakin 	cache = (flags & SKB_ALLOC_FCLONE)
4045381b23dSAlexander Lobakin 		? skbuff_fclone_cache : skbuff_head_cache;
4055381b23dSAlexander Lobakin 
4065381b23dSAlexander Lobakin 	if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
4075381b23dSAlexander Lobakin 		gfp_mask |= __GFP_MEMALLOC;
4085381b23dSAlexander Lobakin 
4095381b23dSAlexander Lobakin 	/* Get the HEAD */
410d13612b5SAlexander Lobakin 	if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
411d13612b5SAlexander Lobakin 	    likely(node == NUMA_NO_NODE || node == numa_mem_id()))
412d13612b5SAlexander Lobakin 		skb = napi_skb_cache_get();
413d13612b5SAlexander Lobakin 	else
414d13612b5SAlexander Lobakin 		skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
415df1ae022SAlexander Lobakin 	if (unlikely(!skb))
416df1ae022SAlexander Lobakin 		return NULL;
4175381b23dSAlexander Lobakin 	prefetchw(skb);
4185381b23dSAlexander Lobakin 
4195381b23dSAlexander Lobakin 	/* We do our best to align skb_shared_info on a separate cache
4205381b23dSAlexander Lobakin 	 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
4215381b23dSAlexander Lobakin 	 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
4225381b23dSAlexander Lobakin 	 * Both skb->head and skb_shared_info are cache line aligned.
4235381b23dSAlexander Lobakin 	 */
4245381b23dSAlexander Lobakin 	size = SKB_DATA_ALIGN(size);
4255381b23dSAlexander Lobakin 	size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4265381b23dSAlexander Lobakin 	data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
427df1ae022SAlexander Lobakin 	if (unlikely(!data))
4285381b23dSAlexander Lobakin 		goto nodata;
4295381b23dSAlexander Lobakin 	/* kmalloc(size) might give us more room than requested.
4305381b23dSAlexander Lobakin 	 * Put skb_shared_info exactly at the end of allocated zone,
4315381b23dSAlexander Lobakin 	 * to allow max possible filling before reallocation.
4325381b23dSAlexander Lobakin 	 */
433a5df6333SLi RongQing 	osize = ksize(data);
434a5df6333SLi RongQing 	size = SKB_WITH_OVERHEAD(osize);
4355381b23dSAlexander Lobakin 	prefetchw(data + size);
4365381b23dSAlexander Lobakin 
4375381b23dSAlexander Lobakin 	/*
4385381b23dSAlexander Lobakin 	 * Only clear those fields we need to clear, not those that we will
4395381b23dSAlexander Lobakin 	 * actually initialise below. Hence, don't put any more fields after
4405381b23dSAlexander Lobakin 	 * the tail pointer in struct sk_buff!
4415381b23dSAlexander Lobakin 	 */
4425381b23dSAlexander Lobakin 	memset(skb, 0, offsetof(struct sk_buff, tail));
443a5df6333SLi RongQing 	__build_skb_around(skb, data, osize);
4445381b23dSAlexander Lobakin 	skb->pfmemalloc = pfmemalloc;
4455381b23dSAlexander Lobakin 
4465381b23dSAlexander Lobakin 	if (flags & SKB_ALLOC_FCLONE) {
4475381b23dSAlexander Lobakin 		struct sk_buff_fclones *fclones;
4485381b23dSAlexander Lobakin 
4495381b23dSAlexander Lobakin 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
4505381b23dSAlexander Lobakin 
4515381b23dSAlexander Lobakin 		skb->fclone = SKB_FCLONE_ORIG;
4525381b23dSAlexander Lobakin 		refcount_set(&fclones->fclone_ref, 1);
4535381b23dSAlexander Lobakin 
4545381b23dSAlexander Lobakin 		fclones->skb2.fclone = SKB_FCLONE_CLONE;
4555381b23dSAlexander Lobakin 	}
4565381b23dSAlexander Lobakin 
4575381b23dSAlexander Lobakin 	return skb;
458df1ae022SAlexander Lobakin 
4595381b23dSAlexander Lobakin nodata:
4605381b23dSAlexander Lobakin 	kmem_cache_free(cache, skb);
461df1ae022SAlexander Lobakin 	return NULL;
4625381b23dSAlexander Lobakin }
4635381b23dSAlexander Lobakin EXPORT_SYMBOL(__alloc_skb);
4645381b23dSAlexander Lobakin 
4657ba7aeabSSebastian Andrzej Siewior /**
466fd11a83dSAlexander Duyck  *	__netdev_alloc_skb - allocate an skbuff for rx on a specific device
467fd11a83dSAlexander Duyck  *	@dev: network device to receive on
468d7499160SMasanari Iida  *	@len: length to allocate
469fd11a83dSAlexander Duyck  *	@gfp_mask: get_free_pages mask, passed to alloc_skb
470fd11a83dSAlexander Duyck  *
471fd11a83dSAlexander Duyck  *	Allocate a new &sk_buff and assign it a usage count of one. The
472fd11a83dSAlexander Duyck  *	buffer has NET_SKB_PAD headroom built in. Users should allocate
473fd11a83dSAlexander Duyck  *	the headroom they think they need without accounting for the
474fd11a83dSAlexander Duyck  *	built in space. The built in space is used for optimisations.
475fd11a83dSAlexander Duyck  *
476fd11a83dSAlexander Duyck  *	%NULL is returned if there is no free memory.
477fd11a83dSAlexander Duyck  */
4789451980aSAlexander Duyck struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
4799451980aSAlexander Duyck 				   gfp_t gfp_mask)
480fd11a83dSAlexander Duyck {
481b63ae8caSAlexander Duyck 	struct page_frag_cache *nc;
482fd11a83dSAlexander Duyck 	struct sk_buff *skb;
4839451980aSAlexander Duyck 	bool pfmemalloc;
4849451980aSAlexander Duyck 	void *data;
485fd11a83dSAlexander Duyck 
4869451980aSAlexander Duyck 	len += NET_SKB_PAD;
487fd11a83dSAlexander Duyck 
48866c55602SAlexander Lobakin 	/* If requested length is either too small or too big,
48966c55602SAlexander Lobakin 	 * we use kmalloc() for skb->head allocation.
49066c55602SAlexander Lobakin 	 */
49166c55602SAlexander Lobakin 	if (len <= SKB_WITH_OVERHEAD(1024) ||
49266c55602SAlexander Lobakin 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
493d0164adcSMel Gorman 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
494a080e7bdSAlexander Duyck 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
495a080e7bdSAlexander Duyck 		if (!skb)
496a080e7bdSAlexander Duyck 			goto skb_fail;
497a080e7bdSAlexander Duyck 		goto skb_success;
498a080e7bdSAlexander Duyck 	}
4999451980aSAlexander Duyck 
5009451980aSAlexander Duyck 	len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
5019451980aSAlexander Duyck 	len = SKB_DATA_ALIGN(len);
5029451980aSAlexander Duyck 
5039451980aSAlexander Duyck 	if (sk_memalloc_socks())
5049451980aSAlexander Duyck 		gfp_mask |= __GFP_MEMALLOC;
5059451980aSAlexander Duyck 
506afa79d08SChangbin Du 	if (in_hardirq() || irqs_disabled()) {
5079451980aSAlexander Duyck 		nc = this_cpu_ptr(&netdev_alloc_cache);
5088c2dd3e4SAlexander Duyck 		data = page_frag_alloc(nc, len, gfp_mask);
5099451980aSAlexander Duyck 		pfmemalloc = nc->pfmemalloc;
51092dcabd7SSebastian Andrzej Siewior 	} else {
51192dcabd7SSebastian Andrzej Siewior 		local_bh_disable();
51292dcabd7SSebastian Andrzej Siewior 		nc = this_cpu_ptr(&napi_alloc_cache.page);
51392dcabd7SSebastian Andrzej Siewior 		data = page_frag_alloc(nc, len, gfp_mask);
51492dcabd7SSebastian Andrzej Siewior 		pfmemalloc = nc->pfmemalloc;
51592dcabd7SSebastian Andrzej Siewior 		local_bh_enable();
51692dcabd7SSebastian Andrzej Siewior 	}
5179451980aSAlexander Duyck 
5189451980aSAlexander Duyck 	if (unlikely(!data))
5199451980aSAlexander Duyck 		return NULL;
5209451980aSAlexander Duyck 
5219451980aSAlexander Duyck 	skb = __build_skb(data, len);
5229451980aSAlexander Duyck 	if (unlikely(!skb)) {
523181edb2bSAlexander Duyck 		skb_free_frag(data);
5249451980aSAlexander Duyck 		return NULL;
5259451980aSAlexander Duyck 	}
5269451980aSAlexander Duyck 
5279451980aSAlexander Duyck 	if (pfmemalloc)
5289451980aSAlexander Duyck 		skb->pfmemalloc = 1;
5299451980aSAlexander Duyck 	skb->head_frag = 1;
5309451980aSAlexander Duyck 
531a080e7bdSAlexander Duyck skb_success:
5328af27456SChristoph Hellwig 	skb_reserve(skb, NET_SKB_PAD);
5337b2e497aSChristoph Hellwig 	skb->dev = dev;
534fd11a83dSAlexander Duyck 
535a080e7bdSAlexander Duyck skb_fail:
5368af27456SChristoph Hellwig 	return skb;
5378af27456SChristoph Hellwig }
538b4ac530fSDavid S. Miller EXPORT_SYMBOL(__netdev_alloc_skb);
5391da177e4SLinus Torvalds 
540fd11a83dSAlexander Duyck /**
541fd11a83dSAlexander Duyck  *	__napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
542fd11a83dSAlexander Duyck  *	@napi: napi instance this buffer was allocated for
543d7499160SMasanari Iida  *	@len: length to allocate
544fd11a83dSAlexander Duyck  *	@gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
545fd11a83dSAlexander Duyck  *
546fd11a83dSAlexander Duyck  *	Allocate a new sk_buff for use in NAPI receive.  This buffer will
547fd11a83dSAlexander Duyck  *	attempt to allocate the head from a special reserved region used
548fd11a83dSAlexander Duyck  *	only for NAPI Rx allocation.  By doing this we can save several
549fd11a83dSAlexander Duyck  *	CPU cycles by avoiding having to disable and re-enable IRQs.
550fd11a83dSAlexander Duyck  *
551fd11a83dSAlexander Duyck  *	%NULL is returned if there is no free memory.
552fd11a83dSAlexander Duyck  */
5539451980aSAlexander Duyck struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
5549451980aSAlexander Duyck 				 gfp_t gfp_mask)
555fd11a83dSAlexander Duyck {
5563226b158SEric Dumazet 	struct napi_alloc_cache *nc;
557fd11a83dSAlexander Duyck 	struct sk_buff *skb;
5589451980aSAlexander Duyck 	void *data;
559fd11a83dSAlexander Duyck 
5609451980aSAlexander Duyck 	len += NET_SKB_PAD + NET_IP_ALIGN;
561fd11a83dSAlexander Duyck 
5623226b158SEric Dumazet 	/* If requested length is either too small or too big,
5633226b158SEric Dumazet 	 * we use kmalloc() for skb->head allocation.
5643226b158SEric Dumazet 	 */
5653226b158SEric Dumazet 	if (len <= SKB_WITH_OVERHEAD(1024) ||
5663226b158SEric Dumazet 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
567d0164adcSMel Gorman 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
568cfb8ec65SAlexander Lobakin 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
569cfb8ec65SAlexander Lobakin 				  NUMA_NO_NODE);
570a080e7bdSAlexander Duyck 		if (!skb)
571a080e7bdSAlexander Duyck 			goto skb_fail;
572a080e7bdSAlexander Duyck 		goto skb_success;
573a080e7bdSAlexander Duyck 	}
5749451980aSAlexander Duyck 
5753226b158SEric Dumazet 	nc = this_cpu_ptr(&napi_alloc_cache);
5769451980aSAlexander Duyck 	len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
5779451980aSAlexander Duyck 	len = SKB_DATA_ALIGN(len);
5789451980aSAlexander Duyck 
5799451980aSAlexander Duyck 	if (sk_memalloc_socks())
5809451980aSAlexander Duyck 		gfp_mask |= __GFP_MEMALLOC;
5819451980aSAlexander Duyck 
5828c2dd3e4SAlexander Duyck 	data = page_frag_alloc(&nc->page, len, gfp_mask);
5839451980aSAlexander Duyck 	if (unlikely(!data))
5849451980aSAlexander Duyck 		return NULL;
5859451980aSAlexander Duyck 
586cfb8ec65SAlexander Lobakin 	skb = __napi_build_skb(data, len);
5879451980aSAlexander Duyck 	if (unlikely(!skb)) {
588181edb2bSAlexander Duyck 		skb_free_frag(data);
5899451980aSAlexander Duyck 		return NULL;
5909451980aSAlexander Duyck 	}
5919451980aSAlexander Duyck 
592795bb1c0SJesper Dangaard Brouer 	if (nc->page.pfmemalloc)
5939451980aSAlexander Duyck 		skb->pfmemalloc = 1;
5949451980aSAlexander Duyck 	skb->head_frag = 1;
5959451980aSAlexander Duyck 
596a080e7bdSAlexander Duyck skb_success:
597fd11a83dSAlexander Duyck 	skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
598fd11a83dSAlexander Duyck 	skb->dev = napi->dev;
599fd11a83dSAlexander Duyck 
600a080e7bdSAlexander Duyck skb_fail:
601fd11a83dSAlexander Duyck 	return skb;
602fd11a83dSAlexander Duyck }
603fd11a83dSAlexander Duyck EXPORT_SYMBOL(__napi_alloc_skb);
604fd11a83dSAlexander Duyck 
605654bed16SPeter Zijlstra void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
60650269e19SEric Dumazet 		     int size, unsigned int truesize)
607654bed16SPeter Zijlstra {
608654bed16SPeter Zijlstra 	skb_fill_page_desc(skb, i, page, off, size);
609654bed16SPeter Zijlstra 	skb->len += size;
610654bed16SPeter Zijlstra 	skb->data_len += size;
61150269e19SEric Dumazet 	skb->truesize += truesize;
612654bed16SPeter Zijlstra }
613654bed16SPeter Zijlstra EXPORT_SYMBOL(skb_add_rx_frag);
614654bed16SPeter Zijlstra 
615f8e617e1SJason Wang void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
616f8e617e1SJason Wang 			  unsigned int truesize)
617f8e617e1SJason Wang {
618f8e617e1SJason Wang 	skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
619f8e617e1SJason Wang 
620f8e617e1SJason Wang 	skb_frag_size_add(frag, size);
621f8e617e1SJason Wang 	skb->len += size;
622f8e617e1SJason Wang 	skb->data_len += size;
623f8e617e1SJason Wang 	skb->truesize += truesize;
624f8e617e1SJason Wang }
625f8e617e1SJason Wang EXPORT_SYMBOL(skb_coalesce_rx_frag);
626f8e617e1SJason Wang 
62727b437c8SHerbert Xu static void skb_drop_list(struct sk_buff **listp)
6281da177e4SLinus Torvalds {
629bd8a7036SEric Dumazet 	kfree_skb_list(*listp);
63027b437c8SHerbert Xu 	*listp = NULL;
6311da177e4SLinus Torvalds }
6321da177e4SLinus Torvalds 
63327b437c8SHerbert Xu static inline void skb_drop_fraglist(struct sk_buff *skb)
63427b437c8SHerbert Xu {
63527b437c8SHerbert Xu 	skb_drop_list(&skb_shinfo(skb)->frag_list);
63627b437c8SHerbert Xu }
63727b437c8SHerbert Xu 
6381da177e4SLinus Torvalds static void skb_clone_fraglist(struct sk_buff *skb)
6391da177e4SLinus Torvalds {
6401da177e4SLinus Torvalds 	struct sk_buff *list;
6411da177e4SLinus Torvalds 
642fbb398a8SDavid S. Miller 	skb_walk_frags(skb, list)
6431da177e4SLinus Torvalds 		skb_get(list);
6441da177e4SLinus Torvalds }
6451da177e4SLinus Torvalds 
646d3836f21SEric Dumazet static void skb_free_head(struct sk_buff *skb)
647d3836f21SEric Dumazet {
648181edb2bSAlexander Duyck 	unsigned char *head = skb->head;
649181edb2bSAlexander Duyck 
6506a5bcd84SIlias Apalodimas 	if (skb->head_frag) {
6516a5bcd84SIlias Apalodimas 		if (skb_pp_recycle(skb, head))
6526a5bcd84SIlias Apalodimas 			return;
653181edb2bSAlexander Duyck 		skb_free_frag(head);
6546a5bcd84SIlias Apalodimas 	} else {
655181edb2bSAlexander Duyck 		kfree(head);
656d3836f21SEric Dumazet 	}
6576a5bcd84SIlias Apalodimas }
658d3836f21SEric Dumazet 
6595bba1712SAdrian Bunk static void skb_release_data(struct sk_buff *skb)
6601da177e4SLinus Torvalds {
661ff04a771SEric Dumazet 	struct skb_shared_info *shinfo = skb_shinfo(skb);
6621da177e4SLinus Torvalds 	int i;
663ff04a771SEric Dumazet 
664ff04a771SEric Dumazet 	if (skb->cloned &&
665ff04a771SEric Dumazet 	    atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
666ff04a771SEric Dumazet 			      &shinfo->dataref))
6672cc3aeb5SIlias Apalodimas 		goto exit;
668ff04a771SEric Dumazet 
66970c43167SJonathan Lemon 	skb_zcopy_clear(skb, true);
67070c43167SJonathan Lemon 
671ff04a771SEric Dumazet 	for (i = 0; i < shinfo->nr_frags; i++)
6726a5bcd84SIlias Apalodimas 		__skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
6731da177e4SLinus Torvalds 
674ff04a771SEric Dumazet 	if (shinfo->frag_list)
675ff04a771SEric Dumazet 		kfree_skb_list(shinfo->frag_list);
6761da177e4SLinus Torvalds 
677d3836f21SEric Dumazet 	skb_free_head(skb);
6782cc3aeb5SIlias Apalodimas exit:
6792cc3aeb5SIlias Apalodimas 	/* When we clone an SKB we copy the reycling bit. The pp_recycle
6802cc3aeb5SIlias Apalodimas 	 * bit is only set on the head though, so in order to avoid races
6812cc3aeb5SIlias Apalodimas 	 * while trying to recycle fragments on __skb_frag_unref() we need
6822cc3aeb5SIlias Apalodimas 	 * to make one SKB responsible for triggering the recycle path.
6832cc3aeb5SIlias Apalodimas 	 * So disable the recycling bit if an SKB is cloned and we have
6842cc3aeb5SIlias Apalodimas 	 * additional references to to the fragmented part of the SKB.
6852cc3aeb5SIlias Apalodimas 	 * Eventually the last SKB will have the recycling bit set and it's
6862cc3aeb5SIlias Apalodimas 	 * dataref set to 0, which will trigger the recycling
6872cc3aeb5SIlias Apalodimas 	 */
6882cc3aeb5SIlias Apalodimas 	skb->pp_recycle = 0;
6891da177e4SLinus Torvalds }
6901da177e4SLinus Torvalds 
6911da177e4SLinus Torvalds /*
6921da177e4SLinus Torvalds  *	Free an skbuff by memory without cleaning the state.
6931da177e4SLinus Torvalds  */
6942d4baff8SHerbert Xu static void kfree_skbmem(struct sk_buff *skb)
6951da177e4SLinus Torvalds {
696d0bf4a9eSEric Dumazet 	struct sk_buff_fclones *fclones;
697d179cd12SDavid S. Miller 
698d179cd12SDavid S. Miller 	switch (skb->fclone) {
699d179cd12SDavid S. Miller 	case SKB_FCLONE_UNAVAILABLE:
7001da177e4SLinus Torvalds 		kmem_cache_free(skbuff_head_cache, skb);
7016ffe75ebSEric Dumazet 		return;
702d179cd12SDavid S. Miller 
703d179cd12SDavid S. Miller 	case SKB_FCLONE_ORIG:
704d0bf4a9eSEric Dumazet 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
7056ffe75ebSEric Dumazet 
7066ffe75ebSEric Dumazet 		/* We usually free the clone (TX completion) before original skb
7076ffe75ebSEric Dumazet 		 * This test would have no chance to be true for the clone,
7086ffe75ebSEric Dumazet 		 * while here, branch prediction will be good.
7096ffe75ebSEric Dumazet 		 */
7102638595aSReshetova, Elena 		if (refcount_read(&fclones->fclone_ref) == 1)
7116ffe75ebSEric Dumazet 			goto fastpath;
712d179cd12SDavid S. Miller 		break;
713d179cd12SDavid S. Miller 
7146ffe75ebSEric Dumazet 	default: /* SKB_FCLONE_CLONE */
715d0bf4a9eSEric Dumazet 		fclones = container_of(skb, struct sk_buff_fclones, skb2);
716d179cd12SDavid S. Miller 		break;
7173ff50b79SStephen Hemminger 	}
7182638595aSReshetova, Elena 	if (!refcount_dec_and_test(&fclones->fclone_ref))
7196ffe75ebSEric Dumazet 		return;
7206ffe75ebSEric Dumazet fastpath:
7216ffe75ebSEric Dumazet 	kmem_cache_free(skbuff_fclone_cache, fclones);
7221da177e4SLinus Torvalds }
7231da177e4SLinus Torvalds 
7240a463c78SPaolo Abeni void skb_release_head_state(struct sk_buff *skb)
7251da177e4SLinus Torvalds {
726adf30907SEric Dumazet 	skb_dst_drop(skb);
7271da177e4SLinus Torvalds 	if (skb->destructor) {
728afa79d08SChangbin Du 		WARN_ON(in_hardirq());
7291da177e4SLinus Torvalds 		skb->destructor(skb);
7301da177e4SLinus Torvalds 	}
731a3bf7ae9SIgor Maravić #if IS_ENABLED(CONFIG_NF_CONNTRACK)
732cb9c6836SFlorian Westphal 	nf_conntrack_put(skb_nfct(skb));
7332fc72c7bSKOVACS Krisztian #endif
734df5042f4SFlorian Westphal 	skb_ext_put(skb);
73504a4bb55SLennert Buytenhek }
73604a4bb55SLennert Buytenhek 
73704a4bb55SLennert Buytenhek /* Free everything but the sk_buff shell. */
73804a4bb55SLennert Buytenhek static void skb_release_all(struct sk_buff *skb)
73904a4bb55SLennert Buytenhek {
74004a4bb55SLennert Buytenhek 	skb_release_head_state(skb);
741a28b1b90SFlorian Westphal 	if (likely(skb->head))
7422d4baff8SHerbert Xu 		skb_release_data(skb);
7432d4baff8SHerbert Xu }
7441da177e4SLinus Torvalds 
7452d4baff8SHerbert Xu /**
7462d4baff8SHerbert Xu  *	__kfree_skb - private function
7472d4baff8SHerbert Xu  *	@skb: buffer
7482d4baff8SHerbert Xu  *
7492d4baff8SHerbert Xu  *	Free an sk_buff. Release anything attached to the buffer.
7502d4baff8SHerbert Xu  *	Clean the state. This is an internal helper function. Users should
7512d4baff8SHerbert Xu  *	always call kfree_skb
7522d4baff8SHerbert Xu  */
7532d4baff8SHerbert Xu 
7542d4baff8SHerbert Xu void __kfree_skb(struct sk_buff *skb)
7552d4baff8SHerbert Xu {
7562d4baff8SHerbert Xu 	skb_release_all(skb);
7571da177e4SLinus Torvalds 	kfree_skbmem(skb);
7581da177e4SLinus Torvalds }
759b4ac530fSDavid S. Miller EXPORT_SYMBOL(__kfree_skb);
7601da177e4SLinus Torvalds 
7611da177e4SLinus Torvalds /**
762231d06aeSJörn Engel  *	kfree_skb - free an sk_buff
763231d06aeSJörn Engel  *	@skb: buffer to free
764231d06aeSJörn Engel  *
765231d06aeSJörn Engel  *	Drop a reference to the buffer and free it if the usage count has
766231d06aeSJörn Engel  *	hit zero.
767231d06aeSJörn Engel  */
768231d06aeSJörn Engel void kfree_skb(struct sk_buff *skb)
769231d06aeSJörn Engel {
7703889a803SPaolo Abeni 	if (!skb_unref(skb))
771231d06aeSJörn Engel 		return;
7723889a803SPaolo Abeni 
773ead2ceb0SNeil Horman 	trace_kfree_skb(skb, __builtin_return_address(0));
774231d06aeSJörn Engel 	__kfree_skb(skb);
775231d06aeSJörn Engel }
776b4ac530fSDavid S. Miller EXPORT_SYMBOL(kfree_skb);
777231d06aeSJörn Engel 
778bd8a7036SEric Dumazet void kfree_skb_list(struct sk_buff *segs)
779bd8a7036SEric Dumazet {
780bd8a7036SEric Dumazet 	while (segs) {
781bd8a7036SEric Dumazet 		struct sk_buff *next = segs->next;
782bd8a7036SEric Dumazet 
783bd8a7036SEric Dumazet 		kfree_skb(segs);
784bd8a7036SEric Dumazet 		segs = next;
785bd8a7036SEric Dumazet 	}
786bd8a7036SEric Dumazet }
787bd8a7036SEric Dumazet EXPORT_SYMBOL(kfree_skb_list);
788bd8a7036SEric Dumazet 
7896413139dSWillem de Bruijn /* Dump skb information and contents.
7906413139dSWillem de Bruijn  *
7916413139dSWillem de Bruijn  * Must only be called from net_ratelimit()-ed paths.
7926413139dSWillem de Bruijn  *
793302af7c6SVladimir Oltean  * Dumps whole packets if full_pkt, only headers otherwise.
7946413139dSWillem de Bruijn  */
7956413139dSWillem de Bruijn void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
7966413139dSWillem de Bruijn {
7976413139dSWillem de Bruijn 	struct skb_shared_info *sh = skb_shinfo(skb);
7986413139dSWillem de Bruijn 	struct net_device *dev = skb->dev;
7996413139dSWillem de Bruijn 	struct sock *sk = skb->sk;
8006413139dSWillem de Bruijn 	struct sk_buff *list_skb;
8016413139dSWillem de Bruijn 	bool has_mac, has_trans;
8026413139dSWillem de Bruijn 	int headroom, tailroom;
8036413139dSWillem de Bruijn 	int i, len, seg_len;
8046413139dSWillem de Bruijn 
8056413139dSWillem de Bruijn 	if (full_pkt)
8066413139dSWillem de Bruijn 		len = skb->len;
8076413139dSWillem de Bruijn 	else
8086413139dSWillem de Bruijn 		len = min_t(int, skb->len, MAX_HEADER + 128);
8096413139dSWillem de Bruijn 
8106413139dSWillem de Bruijn 	headroom = skb_headroom(skb);
8116413139dSWillem de Bruijn 	tailroom = skb_tailroom(skb);
8126413139dSWillem de Bruijn 
8136413139dSWillem de Bruijn 	has_mac = skb_mac_header_was_set(skb);
8146413139dSWillem de Bruijn 	has_trans = skb_transport_header_was_set(skb);
8156413139dSWillem de Bruijn 
8166413139dSWillem de Bruijn 	printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
8176413139dSWillem de Bruijn 	       "mac=(%d,%d) net=(%d,%d) trans=%d\n"
8186413139dSWillem de Bruijn 	       "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
8196413139dSWillem de Bruijn 	       "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
8206413139dSWillem de Bruijn 	       "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
8216413139dSWillem de Bruijn 	       level, skb->len, headroom, skb_headlen(skb), tailroom,
8226413139dSWillem de Bruijn 	       has_mac ? skb->mac_header : -1,
8236413139dSWillem de Bruijn 	       has_mac ? skb_mac_header_len(skb) : -1,
8246413139dSWillem de Bruijn 	       skb->network_header,
8256413139dSWillem de Bruijn 	       has_trans ? skb_network_header_len(skb) : -1,
8266413139dSWillem de Bruijn 	       has_trans ? skb->transport_header : -1,
8276413139dSWillem de Bruijn 	       sh->tx_flags, sh->nr_frags,
8286413139dSWillem de Bruijn 	       sh->gso_size, sh->gso_type, sh->gso_segs,
8296413139dSWillem de Bruijn 	       skb->csum, skb->ip_summed, skb->csum_complete_sw,
8306413139dSWillem de Bruijn 	       skb->csum_valid, skb->csum_level,
8316413139dSWillem de Bruijn 	       skb->hash, skb->sw_hash, skb->l4_hash,
8326413139dSWillem de Bruijn 	       ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
8336413139dSWillem de Bruijn 
8346413139dSWillem de Bruijn 	if (dev)
8356413139dSWillem de Bruijn 		printk("%sdev name=%s feat=0x%pNF\n",
8366413139dSWillem de Bruijn 		       level, dev->name, &dev->features);
8376413139dSWillem de Bruijn 	if (sk)
838db8051f3SQian Cai 		printk("%ssk family=%hu type=%u proto=%u\n",
8396413139dSWillem de Bruijn 		       level, sk->sk_family, sk->sk_type, sk->sk_protocol);
8406413139dSWillem de Bruijn 
8416413139dSWillem de Bruijn 	if (full_pkt && headroom)
8426413139dSWillem de Bruijn 		print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
8436413139dSWillem de Bruijn 			       16, 1, skb->head, headroom, false);
8446413139dSWillem de Bruijn 
8456413139dSWillem de Bruijn 	seg_len = min_t(int, skb_headlen(skb), len);
8466413139dSWillem de Bruijn 	if (seg_len)
8476413139dSWillem de Bruijn 		print_hex_dump(level, "skb linear:   ", DUMP_PREFIX_OFFSET,
8486413139dSWillem de Bruijn 			       16, 1, skb->data, seg_len, false);
8496413139dSWillem de Bruijn 	len -= seg_len;
8506413139dSWillem de Bruijn 
8516413139dSWillem de Bruijn 	if (full_pkt && tailroom)
8526413139dSWillem de Bruijn 		print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
8536413139dSWillem de Bruijn 			       16, 1, skb_tail_pointer(skb), tailroom, false);
8546413139dSWillem de Bruijn 
8556413139dSWillem de Bruijn 	for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
8566413139dSWillem de Bruijn 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
8576413139dSWillem de Bruijn 		u32 p_off, p_len, copied;
8586413139dSWillem de Bruijn 		struct page *p;
8596413139dSWillem de Bruijn 		u8 *vaddr;
8606413139dSWillem de Bruijn 
861b54c9d5bSJonathan Lemon 		skb_frag_foreach_page(frag, skb_frag_off(frag),
8626413139dSWillem de Bruijn 				      skb_frag_size(frag), p, p_off, p_len,
8636413139dSWillem de Bruijn 				      copied) {
8646413139dSWillem de Bruijn 			seg_len = min_t(int, p_len, len);
8656413139dSWillem de Bruijn 			vaddr = kmap_atomic(p);
8666413139dSWillem de Bruijn 			print_hex_dump(level, "skb frag:     ",
8676413139dSWillem de Bruijn 				       DUMP_PREFIX_OFFSET,
8686413139dSWillem de Bruijn 				       16, 1, vaddr + p_off, seg_len, false);
8696413139dSWillem de Bruijn 			kunmap_atomic(vaddr);
8706413139dSWillem de Bruijn 			len -= seg_len;
8716413139dSWillem de Bruijn 			if (!len)
8726413139dSWillem de Bruijn 				break;
8736413139dSWillem de Bruijn 		}
8746413139dSWillem de Bruijn 	}
8756413139dSWillem de Bruijn 
8766413139dSWillem de Bruijn 	if (full_pkt && skb_has_frag_list(skb)) {
8776413139dSWillem de Bruijn 		printk("skb fraglist:\n");
8786413139dSWillem de Bruijn 		skb_walk_frags(skb, list_skb)
8796413139dSWillem de Bruijn 			skb_dump(level, list_skb, true);
8806413139dSWillem de Bruijn 	}
8816413139dSWillem de Bruijn }
8826413139dSWillem de Bruijn EXPORT_SYMBOL(skb_dump);
8836413139dSWillem de Bruijn 
884d1a203eaSStephen Hemminger /**
88525121173SMichael S. Tsirkin  *	skb_tx_error - report an sk_buff xmit error
88625121173SMichael S. Tsirkin  *	@skb: buffer that triggered an error
88725121173SMichael S. Tsirkin  *
88825121173SMichael S. Tsirkin  *	Report xmit error if a device callback is tracking this skb.
88925121173SMichael S. Tsirkin  *	skb must be freed afterwards.
89025121173SMichael S. Tsirkin  */
89125121173SMichael S. Tsirkin void skb_tx_error(struct sk_buff *skb)
89225121173SMichael S. Tsirkin {
8931f8b977aSWillem de Bruijn 	skb_zcopy_clear(skb, true);
89425121173SMichael S. Tsirkin }
89525121173SMichael S. Tsirkin EXPORT_SYMBOL(skb_tx_error);
89625121173SMichael S. Tsirkin 
897be769db2SHerbert Xu #ifdef CONFIG_TRACEPOINTS
89825121173SMichael S. Tsirkin /**
899ead2ceb0SNeil Horman  *	consume_skb - free an skbuff
900ead2ceb0SNeil Horman  *	@skb: buffer to free
901ead2ceb0SNeil Horman  *
902ead2ceb0SNeil Horman  *	Drop a ref to the buffer and free it if the usage count has hit zero
903ead2ceb0SNeil Horman  *	Functions identically to kfree_skb, but kfree_skb assumes that the frame
904ead2ceb0SNeil Horman  *	is being dropped after a failure and notes that
905ead2ceb0SNeil Horman  */
906ead2ceb0SNeil Horman void consume_skb(struct sk_buff *skb)
907ead2ceb0SNeil Horman {
9083889a803SPaolo Abeni 	if (!skb_unref(skb))
909ead2ceb0SNeil Horman 		return;
9103889a803SPaolo Abeni 
91107dc22e7SKoki Sanagi 	trace_consume_skb(skb);
912ead2ceb0SNeil Horman 	__kfree_skb(skb);
913ead2ceb0SNeil Horman }
914ead2ceb0SNeil Horman EXPORT_SYMBOL(consume_skb);
915be769db2SHerbert Xu #endif
916ead2ceb0SNeil Horman 
9170a463c78SPaolo Abeni /**
918c1639be9SMauro Carvalho Chehab  *	__consume_stateless_skb - free an skbuff, assuming it is stateless
9190a463c78SPaolo Abeni  *	@skb: buffer to free
9200a463c78SPaolo Abeni  *
921ca2c1418SPaolo Abeni  *	Alike consume_skb(), but this variant assumes that this is the last
922ca2c1418SPaolo Abeni  *	skb reference and all the head states have been already dropped
9230a463c78SPaolo Abeni  */
924ca2c1418SPaolo Abeni void __consume_stateless_skb(struct sk_buff *skb)
9250a463c78SPaolo Abeni {
9260a463c78SPaolo Abeni 	trace_consume_skb(skb);
9270a463c78SPaolo Abeni 	skb_release_data(skb);
9280a463c78SPaolo Abeni 	kfree_skbmem(skb);
9290a463c78SPaolo Abeni }
9300a463c78SPaolo Abeni 
931f450d539SAlexander Lobakin static void napi_skb_cache_put(struct sk_buff *skb)
932795bb1c0SJesper Dangaard Brouer {
933795bb1c0SJesper Dangaard Brouer 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
934f450d539SAlexander Lobakin 	u32 i;
935795bb1c0SJesper Dangaard Brouer 
936f450d539SAlexander Lobakin 	kasan_poison_object_data(skbuff_head_cache, skb);
937795bb1c0SJesper Dangaard Brouer 	nc->skb_cache[nc->skb_count++] = skb;
938795bb1c0SJesper Dangaard Brouer 
939795bb1c0SJesper Dangaard Brouer 	if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
940f450d539SAlexander Lobakin 		for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
941f450d539SAlexander Lobakin 			kasan_unpoison_object_data(skbuff_head_cache,
942f450d539SAlexander Lobakin 						   nc->skb_cache[i]);
943f450d539SAlexander Lobakin 
944f450d539SAlexander Lobakin 		kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
945f450d539SAlexander Lobakin 				     nc->skb_cache + NAPI_SKB_CACHE_HALF);
946f450d539SAlexander Lobakin 		nc->skb_count = NAPI_SKB_CACHE_HALF;
947795bb1c0SJesper Dangaard Brouer 	}
948795bb1c0SJesper Dangaard Brouer }
949f450d539SAlexander Lobakin 
95015fad714SJesper Dangaard Brouer void __kfree_skb_defer(struct sk_buff *skb)
95115fad714SJesper Dangaard Brouer {
9529243adfcSAlexander Lobakin 	skb_release_all(skb);
9539243adfcSAlexander Lobakin 	napi_skb_cache_put(skb);
9549243adfcSAlexander Lobakin }
9559243adfcSAlexander Lobakin 
9569243adfcSAlexander Lobakin void napi_skb_free_stolen_head(struct sk_buff *skb)
9579243adfcSAlexander Lobakin {
9589efb4b5bSPaolo Abeni 	if (unlikely(skb->slow_gro)) {
9598550ff8dSPaul Blakey 		nf_reset_ct(skb);
9609243adfcSAlexander Lobakin 		skb_dst_drop(skb);
9619243adfcSAlexander Lobakin 		skb_ext_put(skb);
9625e10da53SPaolo Abeni 		skb_orphan(skb);
9639efb4b5bSPaolo Abeni 		skb->slow_gro = 0;
9649efb4b5bSPaolo Abeni 	}
965f450d539SAlexander Lobakin 	napi_skb_cache_put(skb);
96615fad714SJesper Dangaard Brouer }
967795bb1c0SJesper Dangaard Brouer 
968795bb1c0SJesper Dangaard Brouer void napi_consume_skb(struct sk_buff *skb, int budget)
969795bb1c0SJesper Dangaard Brouer {
970885eb0a5SJesper Dangaard Brouer 	/* Zero budget indicate non-NAPI context called us, like netpoll */
971795bb1c0SJesper Dangaard Brouer 	if (unlikely(!budget)) {
972885eb0a5SJesper Dangaard Brouer 		dev_consume_skb_any(skb);
973795bb1c0SJesper Dangaard Brouer 		return;
974795bb1c0SJesper Dangaard Brouer 	}
975795bb1c0SJesper Dangaard Brouer 
9766454eca8SYunsheng Lin 	lockdep_assert_in_softirq();
9776454eca8SYunsheng Lin 
9787608894eSPaolo Abeni 	if (!skb_unref(skb))
979795bb1c0SJesper Dangaard Brouer 		return;
9807608894eSPaolo Abeni 
981795bb1c0SJesper Dangaard Brouer 	/* if reaching here SKB is ready to free */
982795bb1c0SJesper Dangaard Brouer 	trace_consume_skb(skb);
983795bb1c0SJesper Dangaard Brouer 
984795bb1c0SJesper Dangaard Brouer 	/* if SKB is a clone, don't handle this case */
985abbdb5a7SEric Dumazet 	if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
986795bb1c0SJesper Dangaard Brouer 		__kfree_skb(skb);
987795bb1c0SJesper Dangaard Brouer 		return;
988795bb1c0SJesper Dangaard Brouer 	}
989795bb1c0SJesper Dangaard Brouer 
9909243adfcSAlexander Lobakin 	skb_release_all(skb);
991f450d539SAlexander Lobakin 	napi_skb_cache_put(skb);
992795bb1c0SJesper Dangaard Brouer }
993795bb1c0SJesper Dangaard Brouer EXPORT_SYMBOL(napi_consume_skb);
994795bb1c0SJesper Dangaard Brouer 
995*03f61041SKees Cook /* Make sure a field is contained by headers group */
996b1937227SEric Dumazet #define CHECK_SKB_FIELD(field) \
997*03f61041SKees Cook 	BUILD_BUG_ON(offsetof(struct sk_buff, field) !=		\
998*03f61041SKees Cook 		     offsetof(struct sk_buff, headers.field));	\
999b1937227SEric Dumazet 
1000dec18810SHerbert Xu static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1001dec18810SHerbert Xu {
1002dec18810SHerbert Xu 	new->tstamp		= old->tstamp;
1003b1937227SEric Dumazet 	/* We do not copy old->sk */
1004dec18810SHerbert Xu 	new->dev		= old->dev;
1005b1937227SEric Dumazet 	memcpy(new->cb, old->cb, sizeof(old->cb));
10067fee226aSEric Dumazet 	skb_dst_copy(new, old);
1007df5042f4SFlorian Westphal 	__skb_ext_copy(new, old);
1008b1937227SEric Dumazet 	__nf_copy(new, old, false);
10096aa895b0SPatrick McHardy 
1010*03f61041SKees Cook 	/* Note : this field could be in the headers group.
1011b1937227SEric Dumazet 	 * It is not yet because we do not want to have a 16 bit hole
1012b1937227SEric Dumazet 	 */
1013b1937227SEric Dumazet 	new->queue_mapping = old->queue_mapping;
101406021292SEliezer Tamir 
1015*03f61041SKees Cook 	memcpy(&new->headers, &old->headers, sizeof(new->headers));
1016b1937227SEric Dumazet 	CHECK_SKB_FIELD(protocol);
1017b1937227SEric Dumazet 	CHECK_SKB_FIELD(csum);
1018b1937227SEric Dumazet 	CHECK_SKB_FIELD(hash);
1019b1937227SEric Dumazet 	CHECK_SKB_FIELD(priority);
1020b1937227SEric Dumazet 	CHECK_SKB_FIELD(skb_iif);
1021b1937227SEric Dumazet 	CHECK_SKB_FIELD(vlan_proto);
1022b1937227SEric Dumazet 	CHECK_SKB_FIELD(vlan_tci);
1023b1937227SEric Dumazet 	CHECK_SKB_FIELD(transport_header);
1024b1937227SEric Dumazet 	CHECK_SKB_FIELD(network_header);
1025b1937227SEric Dumazet 	CHECK_SKB_FIELD(mac_header);
1026b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_protocol);
1027b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_transport_header);
1028b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_network_header);
1029b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_mac_header);
1030b1937227SEric Dumazet 	CHECK_SKB_FIELD(mark);
1031b1937227SEric Dumazet #ifdef CONFIG_NETWORK_SECMARK
1032b1937227SEric Dumazet 	CHECK_SKB_FIELD(secmark);
1033b1937227SEric Dumazet #endif
1034e0d1095aSCong Wang #ifdef CONFIG_NET_RX_BUSY_POLL
1035b1937227SEric Dumazet 	CHECK_SKB_FIELD(napi_id);
103606021292SEliezer Tamir #endif
10372bd82484SEric Dumazet #ifdef CONFIG_XPS
10382bd82484SEric Dumazet 	CHECK_SKB_FIELD(sender_cpu);
10392bd82484SEric Dumazet #endif
1040b1937227SEric Dumazet #ifdef CONFIG_NET_SCHED
1041b1937227SEric Dumazet 	CHECK_SKB_FIELD(tc_index);
1042b1937227SEric Dumazet #endif
1043b1937227SEric Dumazet 
1044dec18810SHerbert Xu }
1045dec18810SHerbert Xu 
104682c49a35SHerbert Xu /*
104782c49a35SHerbert Xu  * You should not add any new code to this function.  Add it to
104882c49a35SHerbert Xu  * __copy_skb_header above instead.
104982c49a35SHerbert Xu  */
1050e0053ec0SHerbert Xu static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
10511da177e4SLinus Torvalds {
10521da177e4SLinus Torvalds #define C(x) n->x = skb->x
10531da177e4SLinus Torvalds 
10541da177e4SLinus Torvalds 	n->next = n->prev = NULL;
10551da177e4SLinus Torvalds 	n->sk = NULL;
1056dec18810SHerbert Xu 	__copy_skb_header(n, skb);
1057dec18810SHerbert Xu 
10581da177e4SLinus Torvalds 	C(len);
10591da177e4SLinus Torvalds 	C(data_len);
10603e6b3b2eSAlexey Dobriyan 	C(mac_len);
1061334a8132SPatrick McHardy 	n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
106202f1c89dSPaul Moore 	n->cloned = 1;
10631da177e4SLinus Torvalds 	n->nohdr = 0;
1064b13dda9fSEric Dumazet 	n->peeked = 0;
1065e78bfb07SStefano Brivio 	C(pfmemalloc);
10666a5bcd84SIlias Apalodimas 	C(pp_recycle);
10671da177e4SLinus Torvalds 	n->destructor = NULL;
10681da177e4SLinus Torvalds 	C(tail);
10691da177e4SLinus Torvalds 	C(end);
107002f1c89dSPaul Moore 	C(head);
1071d3836f21SEric Dumazet 	C(head_frag);
107202f1c89dSPaul Moore 	C(data);
107302f1c89dSPaul Moore 	C(truesize);
107463354797SReshetova, Elena 	refcount_set(&n->users, 1);
10751da177e4SLinus Torvalds 
10761da177e4SLinus Torvalds 	atomic_inc(&(skb_shinfo(skb)->dataref));
10771da177e4SLinus Torvalds 	skb->cloned = 1;
10781da177e4SLinus Torvalds 
10791da177e4SLinus Torvalds 	return n;
1080e0053ec0SHerbert Xu #undef C
1081e0053ec0SHerbert Xu }
1082e0053ec0SHerbert Xu 
1083e0053ec0SHerbert Xu /**
1084da29e4b4SJakub Kicinski  * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1085da29e4b4SJakub Kicinski  * @first: first sk_buff of the msg
1086da29e4b4SJakub Kicinski  */
1087da29e4b4SJakub Kicinski struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1088da29e4b4SJakub Kicinski {
1089da29e4b4SJakub Kicinski 	struct sk_buff *n;
1090da29e4b4SJakub Kicinski 
1091da29e4b4SJakub Kicinski 	n = alloc_skb(0, GFP_ATOMIC);
1092da29e4b4SJakub Kicinski 	if (!n)
1093da29e4b4SJakub Kicinski 		return NULL;
1094da29e4b4SJakub Kicinski 
1095da29e4b4SJakub Kicinski 	n->len = first->len;
1096da29e4b4SJakub Kicinski 	n->data_len = first->len;
1097da29e4b4SJakub Kicinski 	n->truesize = first->truesize;
1098da29e4b4SJakub Kicinski 
1099da29e4b4SJakub Kicinski 	skb_shinfo(n)->frag_list = first;
1100da29e4b4SJakub Kicinski 
1101da29e4b4SJakub Kicinski 	__copy_skb_header(n, first);
1102da29e4b4SJakub Kicinski 	n->destructor = NULL;
1103da29e4b4SJakub Kicinski 
1104da29e4b4SJakub Kicinski 	return n;
1105da29e4b4SJakub Kicinski }
1106da29e4b4SJakub Kicinski EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1107da29e4b4SJakub Kicinski 
1108da29e4b4SJakub Kicinski /**
1109e0053ec0SHerbert Xu  *	skb_morph	-	morph one skb into another
1110e0053ec0SHerbert Xu  *	@dst: the skb to receive the contents
1111e0053ec0SHerbert Xu  *	@src: the skb to supply the contents
1112e0053ec0SHerbert Xu  *
1113e0053ec0SHerbert Xu  *	This is identical to skb_clone except that the target skb is
1114e0053ec0SHerbert Xu  *	supplied by the user.
1115e0053ec0SHerbert Xu  *
1116e0053ec0SHerbert Xu  *	The target skb is returned upon exit.
1117e0053ec0SHerbert Xu  */
1118e0053ec0SHerbert Xu struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1119e0053ec0SHerbert Xu {
11202d4baff8SHerbert Xu 	skb_release_all(dst);
1121e0053ec0SHerbert Xu 	return __skb_clone(dst, src);
1122e0053ec0SHerbert Xu }
1123e0053ec0SHerbert Xu EXPORT_SYMBOL_GPL(skb_morph);
1124e0053ec0SHerbert Xu 
11256f89dbceSSowmini Varadhan int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1126a91dbff5SWillem de Bruijn {
1127a91dbff5SWillem de Bruijn 	unsigned long max_pg, num_pg, new_pg, old_pg;
1128a91dbff5SWillem de Bruijn 	struct user_struct *user;
1129a91dbff5SWillem de Bruijn 
1130a91dbff5SWillem de Bruijn 	if (capable(CAP_IPC_LOCK) || !size)
1131a91dbff5SWillem de Bruijn 		return 0;
1132a91dbff5SWillem de Bruijn 
1133a91dbff5SWillem de Bruijn 	num_pg = (size >> PAGE_SHIFT) + 2;	/* worst case */
1134a91dbff5SWillem de Bruijn 	max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1135a91dbff5SWillem de Bruijn 	user = mmp->user ? : current_user();
1136a91dbff5SWillem de Bruijn 
1137a91dbff5SWillem de Bruijn 	do {
1138a91dbff5SWillem de Bruijn 		old_pg = atomic_long_read(&user->locked_vm);
1139a91dbff5SWillem de Bruijn 		new_pg = old_pg + num_pg;
1140a91dbff5SWillem de Bruijn 		if (new_pg > max_pg)
1141a91dbff5SWillem de Bruijn 			return -ENOBUFS;
1142a91dbff5SWillem de Bruijn 	} while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1143a91dbff5SWillem de Bruijn 		 old_pg);
1144a91dbff5SWillem de Bruijn 
1145a91dbff5SWillem de Bruijn 	if (!mmp->user) {
1146a91dbff5SWillem de Bruijn 		mmp->user = get_uid(user);
1147a91dbff5SWillem de Bruijn 		mmp->num_pg = num_pg;
1148a91dbff5SWillem de Bruijn 	} else {
1149a91dbff5SWillem de Bruijn 		mmp->num_pg += num_pg;
1150a91dbff5SWillem de Bruijn 	}
1151a91dbff5SWillem de Bruijn 
1152a91dbff5SWillem de Bruijn 	return 0;
1153a91dbff5SWillem de Bruijn }
11546f89dbceSSowmini Varadhan EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1155a91dbff5SWillem de Bruijn 
11566f89dbceSSowmini Varadhan void mm_unaccount_pinned_pages(struct mmpin *mmp)
1157a91dbff5SWillem de Bruijn {
1158a91dbff5SWillem de Bruijn 	if (mmp->user) {
1159a91dbff5SWillem de Bruijn 		atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1160a91dbff5SWillem de Bruijn 		free_uid(mmp->user);
1161a91dbff5SWillem de Bruijn 	}
1162a91dbff5SWillem de Bruijn }
11636f89dbceSSowmini Varadhan EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1164a91dbff5SWillem de Bruijn 
11658c793822SJonathan Lemon struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
116652267790SWillem de Bruijn {
116752267790SWillem de Bruijn 	struct ubuf_info *uarg;
116852267790SWillem de Bruijn 	struct sk_buff *skb;
116952267790SWillem de Bruijn 
117052267790SWillem de Bruijn 	WARN_ON_ONCE(!in_task());
117152267790SWillem de Bruijn 
117252267790SWillem de Bruijn 	skb = sock_omalloc(sk, 0, GFP_KERNEL);
117352267790SWillem de Bruijn 	if (!skb)
117452267790SWillem de Bruijn 		return NULL;
117552267790SWillem de Bruijn 
117652267790SWillem de Bruijn 	BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
117752267790SWillem de Bruijn 	uarg = (void *)skb->cb;
1178a91dbff5SWillem de Bruijn 	uarg->mmp.user = NULL;
1179a91dbff5SWillem de Bruijn 
1180a91dbff5SWillem de Bruijn 	if (mm_account_pinned_pages(&uarg->mmp, size)) {
1181a91dbff5SWillem de Bruijn 		kfree_skb(skb);
1182a91dbff5SWillem de Bruijn 		return NULL;
1183a91dbff5SWillem de Bruijn 	}
118452267790SWillem de Bruijn 
11858c793822SJonathan Lemon 	uarg->callback = msg_zerocopy_callback;
11864ab6c99dSWillem de Bruijn 	uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
11874ab6c99dSWillem de Bruijn 	uarg->len = 1;
11884ab6c99dSWillem de Bruijn 	uarg->bytelen = size;
118952267790SWillem de Bruijn 	uarg->zerocopy = 1;
119004c2d33eSJonathan Lemon 	uarg->flags = SKBFL_ZEROCOPY_FRAG;
1191c1d1b437SEric Dumazet 	refcount_set(&uarg->refcnt, 1);
119252267790SWillem de Bruijn 	sock_hold(sk);
119352267790SWillem de Bruijn 
119452267790SWillem de Bruijn 	return uarg;
119552267790SWillem de Bruijn }
11968c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_alloc);
119752267790SWillem de Bruijn 
119852267790SWillem de Bruijn static inline struct sk_buff *skb_from_uarg(struct ubuf_info *uarg)
119952267790SWillem de Bruijn {
120052267790SWillem de Bruijn 	return container_of((void *)uarg, struct sk_buff, cb);
120152267790SWillem de Bruijn }
120252267790SWillem de Bruijn 
12038c793822SJonathan Lemon struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
12044ab6c99dSWillem de Bruijn 				       struct ubuf_info *uarg)
12054ab6c99dSWillem de Bruijn {
12064ab6c99dSWillem de Bruijn 	if (uarg) {
12074ab6c99dSWillem de Bruijn 		const u32 byte_limit = 1 << 19;		/* limit to a few TSO */
12084ab6c99dSWillem de Bruijn 		u32 bytelen, next;
12094ab6c99dSWillem de Bruijn 
12104ab6c99dSWillem de Bruijn 		/* realloc only when socket is locked (TCP, UDP cork),
12114ab6c99dSWillem de Bruijn 		 * so uarg->len and sk_zckey access is serialized
12124ab6c99dSWillem de Bruijn 		 */
12134ab6c99dSWillem de Bruijn 		if (!sock_owned_by_user(sk)) {
12144ab6c99dSWillem de Bruijn 			WARN_ON_ONCE(1);
12154ab6c99dSWillem de Bruijn 			return NULL;
12164ab6c99dSWillem de Bruijn 		}
12174ab6c99dSWillem de Bruijn 
12184ab6c99dSWillem de Bruijn 		bytelen = uarg->bytelen + size;
12194ab6c99dSWillem de Bruijn 		if (uarg->len == USHRT_MAX - 1 || bytelen > byte_limit) {
12204ab6c99dSWillem de Bruijn 			/* TCP can create new skb to attach new uarg */
12214ab6c99dSWillem de Bruijn 			if (sk->sk_type == SOCK_STREAM)
12224ab6c99dSWillem de Bruijn 				goto new_alloc;
12234ab6c99dSWillem de Bruijn 			return NULL;
12244ab6c99dSWillem de Bruijn 		}
12254ab6c99dSWillem de Bruijn 
12264ab6c99dSWillem de Bruijn 		next = (u32)atomic_read(&sk->sk_zckey);
12274ab6c99dSWillem de Bruijn 		if ((u32)(uarg->id + uarg->len) == next) {
1228a91dbff5SWillem de Bruijn 			if (mm_account_pinned_pages(&uarg->mmp, size))
1229a91dbff5SWillem de Bruijn 				return NULL;
12304ab6c99dSWillem de Bruijn 			uarg->len++;
12314ab6c99dSWillem de Bruijn 			uarg->bytelen = bytelen;
12324ab6c99dSWillem de Bruijn 			atomic_set(&sk->sk_zckey, ++next);
1233100f6d8eSWillem de Bruijn 
1234100f6d8eSWillem de Bruijn 			/* no extra ref when appending to datagram (MSG_MORE) */
1235100f6d8eSWillem de Bruijn 			if (sk->sk_type == SOCK_STREAM)
12368e044917SJonathan Lemon 				net_zcopy_get(uarg);
1237100f6d8eSWillem de Bruijn 
12384ab6c99dSWillem de Bruijn 			return uarg;
12394ab6c99dSWillem de Bruijn 		}
12404ab6c99dSWillem de Bruijn 	}
12414ab6c99dSWillem de Bruijn 
12424ab6c99dSWillem de Bruijn new_alloc:
12438c793822SJonathan Lemon 	return msg_zerocopy_alloc(sk, size);
12444ab6c99dSWillem de Bruijn }
12458c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
12464ab6c99dSWillem de Bruijn 
12474ab6c99dSWillem de Bruijn static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
12484ab6c99dSWillem de Bruijn {
12494ab6c99dSWillem de Bruijn 	struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
12504ab6c99dSWillem de Bruijn 	u32 old_lo, old_hi;
12514ab6c99dSWillem de Bruijn 	u64 sum_len;
12524ab6c99dSWillem de Bruijn 
12534ab6c99dSWillem de Bruijn 	old_lo = serr->ee.ee_info;
12544ab6c99dSWillem de Bruijn 	old_hi = serr->ee.ee_data;
12554ab6c99dSWillem de Bruijn 	sum_len = old_hi - old_lo + 1ULL + len;
12564ab6c99dSWillem de Bruijn 
12574ab6c99dSWillem de Bruijn 	if (sum_len >= (1ULL << 32))
12584ab6c99dSWillem de Bruijn 		return false;
12594ab6c99dSWillem de Bruijn 
12604ab6c99dSWillem de Bruijn 	if (lo != old_hi + 1)
12614ab6c99dSWillem de Bruijn 		return false;
12624ab6c99dSWillem de Bruijn 
12634ab6c99dSWillem de Bruijn 	serr->ee.ee_data += len;
12644ab6c99dSWillem de Bruijn 	return true;
12654ab6c99dSWillem de Bruijn }
12664ab6c99dSWillem de Bruijn 
12678c793822SJonathan Lemon static void __msg_zerocopy_callback(struct ubuf_info *uarg)
126852267790SWillem de Bruijn {
12694ab6c99dSWillem de Bruijn 	struct sk_buff *tail, *skb = skb_from_uarg(uarg);
127052267790SWillem de Bruijn 	struct sock_exterr_skb *serr;
127152267790SWillem de Bruijn 	struct sock *sk = skb->sk;
12724ab6c99dSWillem de Bruijn 	struct sk_buff_head *q;
12734ab6c99dSWillem de Bruijn 	unsigned long flags;
12743bdd5ee0SWillem de Bruijn 	bool is_zerocopy;
12754ab6c99dSWillem de Bruijn 	u32 lo, hi;
12764ab6c99dSWillem de Bruijn 	u16 len;
127752267790SWillem de Bruijn 
1278ccaffff1SWillem de Bruijn 	mm_unaccount_pinned_pages(&uarg->mmp);
1279ccaffff1SWillem de Bruijn 
12804ab6c99dSWillem de Bruijn 	/* if !len, there was only 1 call, and it was aborted
12814ab6c99dSWillem de Bruijn 	 * so do not queue a completion notification
12824ab6c99dSWillem de Bruijn 	 */
12834ab6c99dSWillem de Bruijn 	if (!uarg->len || sock_flag(sk, SOCK_DEAD))
128452267790SWillem de Bruijn 		goto release;
128552267790SWillem de Bruijn 
12864ab6c99dSWillem de Bruijn 	len = uarg->len;
12874ab6c99dSWillem de Bruijn 	lo = uarg->id;
12884ab6c99dSWillem de Bruijn 	hi = uarg->id + len - 1;
12893bdd5ee0SWillem de Bruijn 	is_zerocopy = uarg->zerocopy;
12904ab6c99dSWillem de Bruijn 
129152267790SWillem de Bruijn 	serr = SKB_EXT_ERR(skb);
129252267790SWillem de Bruijn 	memset(serr, 0, sizeof(*serr));
129352267790SWillem de Bruijn 	serr->ee.ee_errno = 0;
129452267790SWillem de Bruijn 	serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
12954ab6c99dSWillem de Bruijn 	serr->ee.ee_data = hi;
12964ab6c99dSWillem de Bruijn 	serr->ee.ee_info = lo;
12973bdd5ee0SWillem de Bruijn 	if (!is_zerocopy)
129852267790SWillem de Bruijn 		serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
129952267790SWillem de Bruijn 
13004ab6c99dSWillem de Bruijn 	q = &sk->sk_error_queue;
13014ab6c99dSWillem de Bruijn 	spin_lock_irqsave(&q->lock, flags);
13024ab6c99dSWillem de Bruijn 	tail = skb_peek_tail(q);
13034ab6c99dSWillem de Bruijn 	if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
13044ab6c99dSWillem de Bruijn 	    !skb_zerocopy_notify_extend(tail, lo, len)) {
13054ab6c99dSWillem de Bruijn 		__skb_queue_tail(q, skb);
130652267790SWillem de Bruijn 		skb = NULL;
13074ab6c99dSWillem de Bruijn 	}
13084ab6c99dSWillem de Bruijn 	spin_unlock_irqrestore(&q->lock, flags);
130952267790SWillem de Bruijn 
1310e3ae2365SAlexander Aring 	sk_error_report(sk);
131152267790SWillem de Bruijn 
131252267790SWillem de Bruijn release:
131352267790SWillem de Bruijn 	consume_skb(skb);
131452267790SWillem de Bruijn 	sock_put(sk);
131552267790SWillem de Bruijn }
131675518851SJonathan Lemon 
13178c793822SJonathan Lemon void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
131836177832SJonathan Lemon 			   bool success)
131975518851SJonathan Lemon {
132075518851SJonathan Lemon 	uarg->zerocopy = uarg->zerocopy & success;
132175518851SJonathan Lemon 
132275518851SJonathan Lemon 	if (refcount_dec_and_test(&uarg->refcnt))
13238c793822SJonathan Lemon 		__msg_zerocopy_callback(uarg);
132475518851SJonathan Lemon }
13258c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
132652267790SWillem de Bruijn 
13278c793822SJonathan Lemon void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
132852267790SWillem de Bruijn {
132952267790SWillem de Bruijn 	struct sock *sk = skb_from_uarg(uarg)->sk;
133052267790SWillem de Bruijn 
133152267790SWillem de Bruijn 	atomic_dec(&sk->sk_zckey);
13324ab6c99dSWillem de Bruijn 	uarg->len--;
133352267790SWillem de Bruijn 
133452900d22SWillem de Bruijn 	if (have_uref)
13358c793822SJonathan Lemon 		msg_zerocopy_callback(NULL, uarg, true);
133652267790SWillem de Bruijn }
13378c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
133852267790SWillem de Bruijn 
1339b5947e5dSWillem de Bruijn int skb_zerocopy_iter_dgram(struct sk_buff *skb, struct msghdr *msg, int len)
1340b5947e5dSWillem de Bruijn {
1341b5947e5dSWillem de Bruijn 	return __zerocopy_sg_from_iter(skb->sk, skb, &msg->msg_iter, len);
1342b5947e5dSWillem de Bruijn }
1343b5947e5dSWillem de Bruijn EXPORT_SYMBOL_GPL(skb_zerocopy_iter_dgram);
1344b5947e5dSWillem de Bruijn 
134552267790SWillem de Bruijn int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
134652267790SWillem de Bruijn 			     struct msghdr *msg, int len,
134752267790SWillem de Bruijn 			     struct ubuf_info *uarg)
134852267790SWillem de Bruijn {
13494ab6c99dSWillem de Bruijn 	struct ubuf_info *orig_uarg = skb_zcopy(skb);
135052267790SWillem de Bruijn 	struct iov_iter orig_iter = msg->msg_iter;
135152267790SWillem de Bruijn 	int err, orig_len = skb->len;
135252267790SWillem de Bruijn 
13534ab6c99dSWillem de Bruijn 	/* An skb can only point to one uarg. This edge case happens when
13544ab6c99dSWillem de Bruijn 	 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
13554ab6c99dSWillem de Bruijn 	 */
13564ab6c99dSWillem de Bruijn 	if (orig_uarg && uarg != orig_uarg)
13574ab6c99dSWillem de Bruijn 		return -EEXIST;
13584ab6c99dSWillem de Bruijn 
135952267790SWillem de Bruijn 	err = __zerocopy_sg_from_iter(sk, skb, &msg->msg_iter, len);
136052267790SWillem de Bruijn 	if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
136154d43117SWillem de Bruijn 		struct sock *save_sk = skb->sk;
136254d43117SWillem de Bruijn 
136352267790SWillem de Bruijn 		/* Streams do not free skb on error. Reset to prev state. */
136452267790SWillem de Bruijn 		msg->msg_iter = orig_iter;
136554d43117SWillem de Bruijn 		skb->sk = sk;
136652267790SWillem de Bruijn 		___pskb_trim(skb, orig_len);
136754d43117SWillem de Bruijn 		skb->sk = save_sk;
136852267790SWillem de Bruijn 		return err;
136952267790SWillem de Bruijn 	}
137052267790SWillem de Bruijn 
137152900d22SWillem de Bruijn 	skb_zcopy_set(skb, uarg, NULL);
137252267790SWillem de Bruijn 	return skb->len - orig_len;
137352267790SWillem de Bruijn }
137452267790SWillem de Bruijn EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
137552267790SWillem de Bruijn 
13761f8b977aSWillem de Bruijn static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
137752267790SWillem de Bruijn 			      gfp_t gfp_mask)
137852267790SWillem de Bruijn {
137952267790SWillem de Bruijn 	if (skb_zcopy(orig)) {
138052267790SWillem de Bruijn 		if (skb_zcopy(nskb)) {
138152267790SWillem de Bruijn 			/* !gfp_mask callers are verified to !skb_zcopy(nskb) */
138252267790SWillem de Bruijn 			if (!gfp_mask) {
138352267790SWillem de Bruijn 				WARN_ON_ONCE(1);
138452267790SWillem de Bruijn 				return -ENOMEM;
138552267790SWillem de Bruijn 			}
138652267790SWillem de Bruijn 			if (skb_uarg(nskb) == skb_uarg(orig))
138752267790SWillem de Bruijn 				return 0;
138852267790SWillem de Bruijn 			if (skb_copy_ubufs(nskb, GFP_ATOMIC))
138952267790SWillem de Bruijn 				return -EIO;
139052267790SWillem de Bruijn 		}
139152900d22SWillem de Bruijn 		skb_zcopy_set(nskb, skb_uarg(orig), NULL);
139252267790SWillem de Bruijn 	}
139352267790SWillem de Bruijn 	return 0;
139452267790SWillem de Bruijn }
139552267790SWillem de Bruijn 
13962c53040fSBen Hutchings /**
13972c53040fSBen Hutchings  *	skb_copy_ubufs	-	copy userspace skb frags buffers to kernel
139848c83012SMichael S. Tsirkin  *	@skb: the skb to modify
139948c83012SMichael S. Tsirkin  *	@gfp_mask: allocation priority
140048c83012SMichael S. Tsirkin  *
140106b4feb3SJonathan Lemon  *	This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
140248c83012SMichael S. Tsirkin  *	It will copy all frags into kernel and drop the reference
140348c83012SMichael S. Tsirkin  *	to userspace pages.
140448c83012SMichael S. Tsirkin  *
140548c83012SMichael S. Tsirkin  *	If this function is called from an interrupt gfp_mask() must be
140648c83012SMichael S. Tsirkin  *	%GFP_ATOMIC.
140748c83012SMichael S. Tsirkin  *
140848c83012SMichael S. Tsirkin  *	Returns 0 on success or a negative error code on failure
140948c83012SMichael S. Tsirkin  *	to allocate kernel memory to copy to.
141048c83012SMichael S. Tsirkin  */
141148c83012SMichael S. Tsirkin int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1412a6686f2fSShirley Ma {
1413a6686f2fSShirley Ma 	int num_frags = skb_shinfo(skb)->nr_frags;
1414a6686f2fSShirley Ma 	struct page *page, *head = NULL;
14153ece7826SWillem de Bruijn 	int i, new_frags;
14163ece7826SWillem de Bruijn 	u32 d_off;
1417a6686f2fSShirley Ma 
14183ece7826SWillem de Bruijn 	if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
14193ece7826SWillem de Bruijn 		return -EINVAL;
14203ece7826SWillem de Bruijn 
1421f72c4ac6SWillem de Bruijn 	if (!num_frags)
1422f72c4ac6SWillem de Bruijn 		goto release;
1423f72c4ac6SWillem de Bruijn 
14243ece7826SWillem de Bruijn 	new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
14253ece7826SWillem de Bruijn 	for (i = 0; i < new_frags; i++) {
142602756ed4SKrishna Kumar 		page = alloc_page(gfp_mask);
1427a6686f2fSShirley Ma 		if (!page) {
1428a6686f2fSShirley Ma 			while (head) {
142940dadff2SSunghan Suh 				struct page *next = (struct page *)page_private(head);
1430a6686f2fSShirley Ma 				put_page(head);
1431a6686f2fSShirley Ma 				head = next;
1432a6686f2fSShirley Ma 			}
1433a6686f2fSShirley Ma 			return -ENOMEM;
1434a6686f2fSShirley Ma 		}
14353ece7826SWillem de Bruijn 		set_page_private(page, (unsigned long)head);
14363ece7826SWillem de Bruijn 		head = page;
14373ece7826SWillem de Bruijn 	}
14383ece7826SWillem de Bruijn 
14393ece7826SWillem de Bruijn 	page = head;
14403ece7826SWillem de Bruijn 	d_off = 0;
14413ece7826SWillem de Bruijn 	for (i = 0; i < num_frags; i++) {
14423ece7826SWillem de Bruijn 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
14433ece7826SWillem de Bruijn 		u32 p_off, p_len, copied;
14443ece7826SWillem de Bruijn 		struct page *p;
14453ece7826SWillem de Bruijn 		u8 *vaddr;
1446c613c209SWillem de Bruijn 
1447b54c9d5bSJonathan Lemon 		skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1448c613c209SWillem de Bruijn 				      p, p_off, p_len, copied) {
14493ece7826SWillem de Bruijn 			u32 copy, done = 0;
1450c613c209SWillem de Bruijn 			vaddr = kmap_atomic(p);
14513ece7826SWillem de Bruijn 
14523ece7826SWillem de Bruijn 			while (done < p_len) {
14533ece7826SWillem de Bruijn 				if (d_off == PAGE_SIZE) {
14543ece7826SWillem de Bruijn 					d_off = 0;
14553ece7826SWillem de Bruijn 					page = (struct page *)page_private(page);
14563ece7826SWillem de Bruijn 				}
14573ece7826SWillem de Bruijn 				copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
14583ece7826SWillem de Bruijn 				memcpy(page_address(page) + d_off,
14593ece7826SWillem de Bruijn 				       vaddr + p_off + done, copy);
14603ece7826SWillem de Bruijn 				done += copy;
14613ece7826SWillem de Bruijn 				d_off += copy;
14623ece7826SWillem de Bruijn 			}
146351c56b00SEric Dumazet 			kunmap_atomic(vaddr);
1464c613c209SWillem de Bruijn 		}
1465a6686f2fSShirley Ma 	}
1466a6686f2fSShirley Ma 
1467a6686f2fSShirley Ma 	/* skb frags release userspace buffers */
146802756ed4SKrishna Kumar 	for (i = 0; i < num_frags; i++)
1469a8605c60SIan Campbell 		skb_frag_unref(skb, i);
1470a6686f2fSShirley Ma 
1471a6686f2fSShirley Ma 	/* skb frags point to kernel buffers */
14723ece7826SWillem de Bruijn 	for (i = 0; i < new_frags - 1; i++) {
14733ece7826SWillem de Bruijn 		__skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
147440dadff2SSunghan Suh 		head = (struct page *)page_private(head);
1475a6686f2fSShirley Ma 	}
14763ece7826SWillem de Bruijn 	__skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
14773ece7826SWillem de Bruijn 	skb_shinfo(skb)->nr_frags = new_frags;
147848c83012SMichael S. Tsirkin 
1479b90ddd56SWillem de Bruijn release:
14801f8b977aSWillem de Bruijn 	skb_zcopy_clear(skb, false);
1481a6686f2fSShirley Ma 	return 0;
1482a6686f2fSShirley Ma }
1483dcc0fb78SMichael S. Tsirkin EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1484a6686f2fSShirley Ma 
1485e0053ec0SHerbert Xu /**
1486e0053ec0SHerbert Xu  *	skb_clone	-	duplicate an sk_buff
1487e0053ec0SHerbert Xu  *	@skb: buffer to clone
1488e0053ec0SHerbert Xu  *	@gfp_mask: allocation priority
1489e0053ec0SHerbert Xu  *
1490e0053ec0SHerbert Xu  *	Duplicate an &sk_buff. The new one is not owned by a socket. Both
1491e0053ec0SHerbert Xu  *	copies share the same packet data but not structure. The new
1492e0053ec0SHerbert Xu  *	buffer has a reference count of 1. If the allocation fails the
1493e0053ec0SHerbert Xu  *	function returns %NULL otherwise the new buffer is returned.
1494e0053ec0SHerbert Xu  *
1495e0053ec0SHerbert Xu  *	If this function is called from an interrupt gfp_mask() must be
1496e0053ec0SHerbert Xu  *	%GFP_ATOMIC.
1497e0053ec0SHerbert Xu  */
1498e0053ec0SHerbert Xu 
1499e0053ec0SHerbert Xu struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1500e0053ec0SHerbert Xu {
1501d0bf4a9eSEric Dumazet 	struct sk_buff_fclones *fclones = container_of(skb,
1502d0bf4a9eSEric Dumazet 						       struct sk_buff_fclones,
1503d0bf4a9eSEric Dumazet 						       skb1);
15046ffe75ebSEric Dumazet 	struct sk_buff *n;
1505e0053ec0SHerbert Xu 
150670008aa5SMichael S. Tsirkin 	if (skb_orphan_frags(skb, gfp_mask))
1507a6686f2fSShirley Ma 		return NULL;
1508a6686f2fSShirley Ma 
1509e0053ec0SHerbert Xu 	if (skb->fclone == SKB_FCLONE_ORIG &&
15102638595aSReshetova, Elena 	    refcount_read(&fclones->fclone_ref) == 1) {
15116ffe75ebSEric Dumazet 		n = &fclones->skb2;
15122638595aSReshetova, Elena 		refcount_set(&fclones->fclone_ref, 2);
1513e0053ec0SHerbert Xu 	} else {
1514c93bdd0eSMel Gorman 		if (skb_pfmemalloc(skb))
1515c93bdd0eSMel Gorman 			gfp_mask |= __GFP_MEMALLOC;
1516c93bdd0eSMel Gorman 
1517e0053ec0SHerbert Xu 		n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1518e0053ec0SHerbert Xu 		if (!n)
1519e0053ec0SHerbert Xu 			return NULL;
1520fe55f6d5SVegard Nossum 
1521e0053ec0SHerbert Xu 		n->fclone = SKB_FCLONE_UNAVAILABLE;
1522e0053ec0SHerbert Xu 	}
1523e0053ec0SHerbert Xu 
1524e0053ec0SHerbert Xu 	return __skb_clone(n, skb);
15251da177e4SLinus Torvalds }
1526b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_clone);
15271da177e4SLinus Torvalds 
1528b0768a86SToshiaki Makita void skb_headers_offset_update(struct sk_buff *skb, int off)
1529f5b17294SPravin B Shelar {
1530030737bcSEric Dumazet 	/* Only adjust this if it actually is csum_start rather than csum */
1531030737bcSEric Dumazet 	if (skb->ip_summed == CHECKSUM_PARTIAL)
1532030737bcSEric Dumazet 		skb->csum_start += off;
1533f5b17294SPravin B Shelar 	/* {transport,network,mac}_header and tail are relative to skb->head */
1534f5b17294SPravin B Shelar 	skb->transport_header += off;
1535f5b17294SPravin B Shelar 	skb->network_header   += off;
1536f5b17294SPravin B Shelar 	if (skb_mac_header_was_set(skb))
1537f5b17294SPravin B Shelar 		skb->mac_header += off;
1538f5b17294SPravin B Shelar 	skb->inner_transport_header += off;
1539f5b17294SPravin B Shelar 	skb->inner_network_header += off;
1540aefbd2b3SPravin B Shelar 	skb->inner_mac_header += off;
1541f5b17294SPravin B Shelar }
1542b0768a86SToshiaki Makita EXPORT_SYMBOL(skb_headers_offset_update);
1543f5b17294SPravin B Shelar 
154408303c18SIlya Lesokhin void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
15451da177e4SLinus Torvalds {
1546dec18810SHerbert Xu 	__copy_skb_header(new, old);
1547dec18810SHerbert Xu 
15487967168cSHerbert Xu 	skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
15497967168cSHerbert Xu 	skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
15507967168cSHerbert Xu 	skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
15511da177e4SLinus Torvalds }
155208303c18SIlya Lesokhin EXPORT_SYMBOL(skb_copy_header);
15531da177e4SLinus Torvalds 
1554c93bdd0eSMel Gorman static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1555c93bdd0eSMel Gorman {
1556c93bdd0eSMel Gorman 	if (skb_pfmemalloc(skb))
1557c93bdd0eSMel Gorman 		return SKB_ALLOC_RX;
1558c93bdd0eSMel Gorman 	return 0;
1559c93bdd0eSMel Gorman }
1560c93bdd0eSMel Gorman 
15611da177e4SLinus Torvalds /**
15621da177e4SLinus Torvalds  *	skb_copy	-	create private copy of an sk_buff
15631da177e4SLinus Torvalds  *	@skb: buffer to copy
15641da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
15651da177e4SLinus Torvalds  *
15661da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and its data. This is used when the
15671da177e4SLinus Torvalds  *	caller wishes to modify the data and needs a private copy of the
15681da177e4SLinus Torvalds  *	data to alter. Returns %NULL on failure or the pointer to the buffer
15691da177e4SLinus Torvalds  *	on success. The returned buffer has a reference count of 1.
15701da177e4SLinus Torvalds  *
15711da177e4SLinus Torvalds  *	As by-product this function converts non-linear &sk_buff to linear
15721da177e4SLinus Torvalds  *	one, so that &sk_buff becomes completely private and caller is allowed
15731da177e4SLinus Torvalds  *	to modify all the data of returned buffer. This means that this
15741da177e4SLinus Torvalds  *	function is not recommended for use in circumstances when only
15751da177e4SLinus Torvalds  *	header is going to be modified. Use pskb_copy() instead.
15761da177e4SLinus Torvalds  */
15771da177e4SLinus Torvalds 
1578dd0fc66fSAl Viro struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
15791da177e4SLinus Torvalds {
15806602cebbSEric Dumazet 	int headerlen = skb_headroom(skb);
1581ec47ea82SAlexander Duyck 	unsigned int size = skb_end_offset(skb) + skb->data_len;
1582c93bdd0eSMel Gorman 	struct sk_buff *n = __alloc_skb(size, gfp_mask,
1583c93bdd0eSMel Gorman 					skb_alloc_rx_flag(skb), NUMA_NO_NODE);
15846602cebbSEric Dumazet 
15851da177e4SLinus Torvalds 	if (!n)
15861da177e4SLinus Torvalds 		return NULL;
15871da177e4SLinus Torvalds 
15881da177e4SLinus Torvalds 	/* Set the data pointer */
15891da177e4SLinus Torvalds 	skb_reserve(n, headerlen);
15901da177e4SLinus Torvalds 	/* Set the tail pointer and length */
15911da177e4SLinus Torvalds 	skb_put(n, skb->len);
15921da177e4SLinus Torvalds 
15939f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
15941da177e4SLinus Torvalds 
159508303c18SIlya Lesokhin 	skb_copy_header(n, skb);
15961da177e4SLinus Torvalds 	return n;
15971da177e4SLinus Torvalds }
1598b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy);
15991da177e4SLinus Torvalds 
16001da177e4SLinus Torvalds /**
1601bad93e9dSOctavian Purdila  *	__pskb_copy_fclone	-  create copy of an sk_buff with private head.
16021da177e4SLinus Torvalds  *	@skb: buffer to copy
1603117632e6SEric Dumazet  *	@headroom: headroom of new skb
16041da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
1605bad93e9dSOctavian Purdila  *	@fclone: if true allocate the copy of the skb from the fclone
1606bad93e9dSOctavian Purdila  *	cache instead of the head cache; it is recommended to set this
1607bad93e9dSOctavian Purdila  *	to true for the cases where the copy will likely be cloned
16081da177e4SLinus Torvalds  *
16091da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and part of its data, located
16101da177e4SLinus Torvalds  *	in header. Fragmented data remain shared. This is used when
16111da177e4SLinus Torvalds  *	the caller wishes to modify only header of &sk_buff and needs
16121da177e4SLinus Torvalds  *	private copy of the header to alter. Returns %NULL on failure
16131da177e4SLinus Torvalds  *	or the pointer to the buffer on success.
16141da177e4SLinus Torvalds  *	The returned buffer has a reference count of 1.
16151da177e4SLinus Torvalds  */
16161da177e4SLinus Torvalds 
1617bad93e9dSOctavian Purdila struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1618bad93e9dSOctavian Purdila 				   gfp_t gfp_mask, bool fclone)
16191da177e4SLinus Torvalds {
1620117632e6SEric Dumazet 	unsigned int size = skb_headlen(skb) + headroom;
1621bad93e9dSOctavian Purdila 	int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1622bad93e9dSOctavian Purdila 	struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
16236602cebbSEric Dumazet 
16241da177e4SLinus Torvalds 	if (!n)
16251da177e4SLinus Torvalds 		goto out;
16261da177e4SLinus Torvalds 
16271da177e4SLinus Torvalds 	/* Set the data pointer */
1628117632e6SEric Dumazet 	skb_reserve(n, headroom);
16291da177e4SLinus Torvalds 	/* Set the tail pointer and length */
16301da177e4SLinus Torvalds 	skb_put(n, skb_headlen(skb));
16311da177e4SLinus Torvalds 	/* Copy the bytes */
1632d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data(skb, n->data, n->len);
16331da177e4SLinus Torvalds 
163425f484a6SHerbert Xu 	n->truesize += skb->data_len;
16351da177e4SLinus Torvalds 	n->data_len  = skb->data_len;
16361da177e4SLinus Torvalds 	n->len	     = skb->len;
16371da177e4SLinus Torvalds 
16381da177e4SLinus Torvalds 	if (skb_shinfo(skb)->nr_frags) {
16391da177e4SLinus Torvalds 		int i;
16401da177e4SLinus Torvalds 
16411f8b977aSWillem de Bruijn 		if (skb_orphan_frags(skb, gfp_mask) ||
16421f8b977aSWillem de Bruijn 		    skb_zerocopy_clone(n, skb, gfp_mask)) {
16431511022cSDan Carpenter 			kfree_skb(n);
16441511022cSDan Carpenter 			n = NULL;
1645a6686f2fSShirley Ma 			goto out;
1646a6686f2fSShirley Ma 		}
16471da177e4SLinus Torvalds 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
16481da177e4SLinus Torvalds 			skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1649ea2ab693SIan Campbell 			skb_frag_ref(skb, i);
16501da177e4SLinus Torvalds 		}
16511da177e4SLinus Torvalds 		skb_shinfo(n)->nr_frags = i;
16521da177e4SLinus Torvalds 	}
16531da177e4SLinus Torvalds 
165421dc3301SDavid S. Miller 	if (skb_has_frag_list(skb)) {
16551da177e4SLinus Torvalds 		skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
16561da177e4SLinus Torvalds 		skb_clone_fraglist(n);
16571da177e4SLinus Torvalds 	}
16581da177e4SLinus Torvalds 
165908303c18SIlya Lesokhin 	skb_copy_header(n, skb);
16601da177e4SLinus Torvalds out:
16611da177e4SLinus Torvalds 	return n;
16621da177e4SLinus Torvalds }
1663bad93e9dSOctavian Purdila EXPORT_SYMBOL(__pskb_copy_fclone);
16641da177e4SLinus Torvalds 
16651da177e4SLinus Torvalds /**
16661da177e4SLinus Torvalds  *	pskb_expand_head - reallocate header of &sk_buff
16671da177e4SLinus Torvalds  *	@skb: buffer to reallocate
16681da177e4SLinus Torvalds  *	@nhead: room to add at head
16691da177e4SLinus Torvalds  *	@ntail: room to add at tail
16701da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
16711da177e4SLinus Torvalds  *
1672bc32383cSMathias Krause  *	Expands (or creates identical copy, if @nhead and @ntail are zero)
1673bc32383cSMathias Krause  *	header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
16741da177e4SLinus Torvalds  *	reference count of 1. Returns zero in the case of success or error,
16751da177e4SLinus Torvalds  *	if expansion failed. In the last case, &sk_buff is not changed.
16761da177e4SLinus Torvalds  *
16771da177e4SLinus Torvalds  *	All the pointers pointing into skb header may change and must be
16781da177e4SLinus Torvalds  *	reloaded after call to this function.
16791da177e4SLinus Torvalds  */
16801da177e4SLinus Torvalds 
168186a76cafSVictor Fusco int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1682dd0fc66fSAl Viro 		     gfp_t gfp_mask)
16831da177e4SLinus Torvalds {
1684158f323bSEric Dumazet 	int i, osize = skb_end_offset(skb);
1685158f323bSEric Dumazet 	int size = osize + nhead + ntail;
16861da177e4SLinus Torvalds 	long off;
1687158f323bSEric Dumazet 	u8 *data;
16881da177e4SLinus Torvalds 
16894edd87adSHerbert Xu 	BUG_ON(nhead < 0);
16904edd87adSHerbert Xu 
16919f77fad3STim Hansen 	BUG_ON(skb_shared(skb));
16921da177e4SLinus Torvalds 
16931da177e4SLinus Torvalds 	size = SKB_DATA_ALIGN(size);
16941da177e4SLinus Torvalds 
1695c93bdd0eSMel Gorman 	if (skb_pfmemalloc(skb))
1696c93bdd0eSMel Gorman 		gfp_mask |= __GFP_MEMALLOC;
1697c93bdd0eSMel Gorman 	data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1698c93bdd0eSMel Gorman 			       gfp_mask, NUMA_NO_NODE, NULL);
16991da177e4SLinus Torvalds 	if (!data)
17001da177e4SLinus Torvalds 		goto nodata;
170187151b86SEric Dumazet 	size = SKB_WITH_OVERHEAD(ksize(data));
17021da177e4SLinus Torvalds 
17031da177e4SLinus Torvalds 	/* Copy only real data... and, alas, header. This should be
17046602cebbSEric Dumazet 	 * optimized for the cases when header is void.
17056602cebbSEric Dumazet 	 */
17066602cebbSEric Dumazet 	memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
17076602cebbSEric Dumazet 
17086602cebbSEric Dumazet 	memcpy((struct skb_shared_info *)(data + size),
17096602cebbSEric Dumazet 	       skb_shinfo(skb),
1710fed66381SEric Dumazet 	       offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
17111da177e4SLinus Torvalds 
17123e24591aSAlexander Duyck 	/*
17133e24591aSAlexander Duyck 	 * if shinfo is shared we must drop the old head gracefully, but if it
17143e24591aSAlexander Duyck 	 * is not we can just drop the old head and let the existing refcount
17153e24591aSAlexander Duyck 	 * be since all we did is relocate the values
17163e24591aSAlexander Duyck 	 */
17173e24591aSAlexander Duyck 	if (skb_cloned(skb)) {
171870008aa5SMichael S. Tsirkin 		if (skb_orphan_frags(skb, gfp_mask))
1719a6686f2fSShirley Ma 			goto nofrags;
17201f8b977aSWillem de Bruijn 		if (skb_zcopy(skb))
1721c1d1b437SEric Dumazet 			refcount_inc(&skb_uarg(skb)->refcnt);
17221da177e4SLinus Torvalds 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1723ea2ab693SIan Campbell 			skb_frag_ref(skb, i);
17241da177e4SLinus Torvalds 
172521dc3301SDavid S. Miller 		if (skb_has_frag_list(skb))
17261da177e4SLinus Torvalds 			skb_clone_fraglist(skb);
17271da177e4SLinus Torvalds 
17281da177e4SLinus Torvalds 		skb_release_data(skb);
17293e24591aSAlexander Duyck 	} else {
17303e24591aSAlexander Duyck 		skb_free_head(skb);
17311fd63041SEric Dumazet 	}
17321da177e4SLinus Torvalds 	off = (data + nhead) - skb->head;
17331da177e4SLinus Torvalds 
17341da177e4SLinus Torvalds 	skb->head     = data;
1735d3836f21SEric Dumazet 	skb->head_frag = 0;
17361da177e4SLinus Torvalds 	skb->data    += off;
17374305b541SArnaldo Carvalho de Melo #ifdef NET_SKBUFF_DATA_USES_OFFSET
17384305b541SArnaldo Carvalho de Melo 	skb->end      = size;
173956eb8882SPatrick McHardy 	off           = nhead;
17404305b541SArnaldo Carvalho de Melo #else
17414305b541SArnaldo Carvalho de Melo 	skb->end      = skb->head + size;
174256eb8882SPatrick McHardy #endif
174327a884dcSArnaldo Carvalho de Melo 	skb->tail	      += off;
1744b41abb42SPeter Pan(潘卫平) 	skb_headers_offset_update(skb, nhead);
17451da177e4SLinus Torvalds 	skb->cloned   = 0;
1746334a8132SPatrick McHardy 	skb->hdr_len  = 0;
17471da177e4SLinus Torvalds 	skb->nohdr    = 0;
17481da177e4SLinus Torvalds 	atomic_set(&skb_shinfo(skb)->dataref, 1);
1749158f323bSEric Dumazet 
1750de8f3a83SDaniel Borkmann 	skb_metadata_clear(skb);
1751de8f3a83SDaniel Borkmann 
1752158f323bSEric Dumazet 	/* It is not generally safe to change skb->truesize.
1753158f323bSEric Dumazet 	 * For the moment, we really care of rx path, or
1754158f323bSEric Dumazet 	 * when skb is orphaned (not attached to a socket).
1755158f323bSEric Dumazet 	 */
1756158f323bSEric Dumazet 	if (!skb->sk || skb->destructor == sock_edemux)
1757158f323bSEric Dumazet 		skb->truesize += size - osize;
1758158f323bSEric Dumazet 
17591da177e4SLinus Torvalds 	return 0;
17601da177e4SLinus Torvalds 
1761a6686f2fSShirley Ma nofrags:
1762a6686f2fSShirley Ma 	kfree(data);
17631da177e4SLinus Torvalds nodata:
17641da177e4SLinus Torvalds 	return -ENOMEM;
17651da177e4SLinus Torvalds }
1766b4ac530fSDavid S. Miller EXPORT_SYMBOL(pskb_expand_head);
17671da177e4SLinus Torvalds 
17681da177e4SLinus Torvalds /* Make private copy of skb with writable head and some headroom */
17691da177e4SLinus Torvalds 
17701da177e4SLinus Torvalds struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
17711da177e4SLinus Torvalds {
17721da177e4SLinus Torvalds 	struct sk_buff *skb2;
17731da177e4SLinus Torvalds 	int delta = headroom - skb_headroom(skb);
17741da177e4SLinus Torvalds 
17751da177e4SLinus Torvalds 	if (delta <= 0)
17761da177e4SLinus Torvalds 		skb2 = pskb_copy(skb, GFP_ATOMIC);
17771da177e4SLinus Torvalds 	else {
17781da177e4SLinus Torvalds 		skb2 = skb_clone(skb, GFP_ATOMIC);
17791da177e4SLinus Torvalds 		if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
17801da177e4SLinus Torvalds 					     GFP_ATOMIC)) {
17811da177e4SLinus Torvalds 			kfree_skb(skb2);
17821da177e4SLinus Torvalds 			skb2 = NULL;
17831da177e4SLinus Torvalds 		}
17841da177e4SLinus Torvalds 	}
17851da177e4SLinus Torvalds 	return skb2;
17861da177e4SLinus Torvalds }
1787b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_realloc_headroom);
17881da177e4SLinus Torvalds 
17891da177e4SLinus Torvalds /**
1790f1260ff1SVasily Averin  *	skb_expand_head - reallocate header of &sk_buff
1791f1260ff1SVasily Averin  *	@skb: buffer to reallocate
1792f1260ff1SVasily Averin  *	@headroom: needed headroom
1793f1260ff1SVasily Averin  *
1794f1260ff1SVasily Averin  *	Unlike skb_realloc_headroom, this one does not allocate a new skb
1795f1260ff1SVasily Averin  *	if possible; copies skb->sk to new skb as needed
1796f1260ff1SVasily Averin  *	and frees original skb in case of failures.
1797f1260ff1SVasily Averin  *
1798f1260ff1SVasily Averin  *	It expect increased headroom and generates warning otherwise.
1799f1260ff1SVasily Averin  */
1800f1260ff1SVasily Averin 
1801f1260ff1SVasily Averin struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1802f1260ff1SVasily Averin {
1803f1260ff1SVasily Averin 	int delta = headroom - skb_headroom(skb);
18047f678defSVasily Averin 	int osize = skb_end_offset(skb);
18057f678defSVasily Averin 	struct sock *sk = skb->sk;
1806f1260ff1SVasily Averin 
1807f1260ff1SVasily Averin 	if (WARN_ONCE(delta <= 0,
1808f1260ff1SVasily Averin 		      "%s is expecting an increase in the headroom", __func__))
1809f1260ff1SVasily Averin 		return skb;
1810f1260ff1SVasily Averin 
18117f678defSVasily Averin 	delta = SKB_DATA_ALIGN(delta);
18127f678defSVasily Averin 	/* pskb_expand_head() might crash, if skb is shared. */
18137f678defSVasily Averin 	if (skb_shared(skb) || !is_skb_wmem(skb)) {
1814f1260ff1SVasily Averin 		struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1815f1260ff1SVasily Averin 
18167f678defSVasily Averin 		if (unlikely(!nskb))
18177f678defSVasily Averin 			goto fail;
18187f678defSVasily Averin 
18197f678defSVasily Averin 		if (sk)
18207f678defSVasily Averin 			skb_set_owner_w(nskb, sk);
1821f1260ff1SVasily Averin 		consume_skb(skb);
1822f1260ff1SVasily Averin 		skb = nskb;
1823f1260ff1SVasily Averin 	}
18247f678defSVasily Averin 	if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
18257f678defSVasily Averin 		goto fail;
18267f678defSVasily Averin 
18277f678defSVasily Averin 	if (sk && is_skb_wmem(skb)) {
18287f678defSVasily Averin 		delta = skb_end_offset(skb) - osize;
18297f678defSVasily Averin 		refcount_add(delta, &sk->sk_wmem_alloc);
18307f678defSVasily Averin 		skb->truesize += delta;
1831f1260ff1SVasily Averin 	}
1832f1260ff1SVasily Averin 	return skb;
18337f678defSVasily Averin 
18347f678defSVasily Averin fail:
18357f678defSVasily Averin 	kfree_skb(skb);
18367f678defSVasily Averin 	return NULL;
1837f1260ff1SVasily Averin }
1838f1260ff1SVasily Averin EXPORT_SYMBOL(skb_expand_head);
1839f1260ff1SVasily Averin 
1840f1260ff1SVasily Averin /**
18411da177e4SLinus Torvalds  *	skb_copy_expand	-	copy and expand sk_buff
18421da177e4SLinus Torvalds  *	@skb: buffer to copy
18431da177e4SLinus Torvalds  *	@newheadroom: new free bytes at head
18441da177e4SLinus Torvalds  *	@newtailroom: new free bytes at tail
18451da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
18461da177e4SLinus Torvalds  *
18471da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and its data and while doing so
18481da177e4SLinus Torvalds  *	allocate additional space.
18491da177e4SLinus Torvalds  *
18501da177e4SLinus Torvalds  *	This is used when the caller wishes to modify the data and needs a
18511da177e4SLinus Torvalds  *	private copy of the data to alter as well as more space for new fields.
18521da177e4SLinus Torvalds  *	Returns %NULL on failure or the pointer to the buffer
18531da177e4SLinus Torvalds  *	on success. The returned buffer has a reference count of 1.
18541da177e4SLinus Torvalds  *
18551da177e4SLinus Torvalds  *	You must pass %GFP_ATOMIC as the allocation priority if this function
18561da177e4SLinus Torvalds  *	is called from an interrupt.
18571da177e4SLinus Torvalds  */
18581da177e4SLinus Torvalds struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
185986a76cafSVictor Fusco 				int newheadroom, int newtailroom,
1860dd0fc66fSAl Viro 				gfp_t gfp_mask)
18611da177e4SLinus Torvalds {
18621da177e4SLinus Torvalds 	/*
18631da177e4SLinus Torvalds 	 *	Allocate the copy buffer
18641da177e4SLinus Torvalds 	 */
1865c93bdd0eSMel Gorman 	struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1866c93bdd0eSMel Gorman 					gfp_mask, skb_alloc_rx_flag(skb),
1867c93bdd0eSMel Gorman 					NUMA_NO_NODE);
1868efd1e8d5SPatrick McHardy 	int oldheadroom = skb_headroom(skb);
18691da177e4SLinus Torvalds 	int head_copy_len, head_copy_off;
18701da177e4SLinus Torvalds 
18711da177e4SLinus Torvalds 	if (!n)
18721da177e4SLinus Torvalds 		return NULL;
18731da177e4SLinus Torvalds 
18741da177e4SLinus Torvalds 	skb_reserve(n, newheadroom);
18751da177e4SLinus Torvalds 
18761da177e4SLinus Torvalds 	/* Set the tail pointer and length */
18771da177e4SLinus Torvalds 	skb_put(n, skb->len);
18781da177e4SLinus Torvalds 
1879efd1e8d5SPatrick McHardy 	head_copy_len = oldheadroom;
18801da177e4SLinus Torvalds 	head_copy_off = 0;
18811da177e4SLinus Torvalds 	if (newheadroom <= head_copy_len)
18821da177e4SLinus Torvalds 		head_copy_len = newheadroom;
18831da177e4SLinus Torvalds 	else
18841da177e4SLinus Torvalds 		head_copy_off = newheadroom - head_copy_len;
18851da177e4SLinus Torvalds 
18861da177e4SLinus Torvalds 	/* Copy the linear header and data. */
18879f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
18889f77fad3STim Hansen 			     skb->len + head_copy_len));
18891da177e4SLinus Torvalds 
189008303c18SIlya Lesokhin 	skb_copy_header(n, skb);
18911da177e4SLinus Torvalds 
1892030737bcSEric Dumazet 	skb_headers_offset_update(n, newheadroom - oldheadroom);
1893efd1e8d5SPatrick McHardy 
18941da177e4SLinus Torvalds 	return n;
18951da177e4SLinus Torvalds }
1896b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_expand);
18971da177e4SLinus Torvalds 
18981da177e4SLinus Torvalds /**
1899cd0a137aSFlorian Fainelli  *	__skb_pad		-	zero pad the tail of an skb
19001da177e4SLinus Torvalds  *	@skb: buffer to pad
19011da177e4SLinus Torvalds  *	@pad: space to pad
1902cd0a137aSFlorian Fainelli  *	@free_on_error: free buffer on error
19031da177e4SLinus Torvalds  *
19041da177e4SLinus Torvalds  *	Ensure that a buffer is followed by a padding area that is zero
19051da177e4SLinus Torvalds  *	filled. Used by network drivers which may DMA or transfer data
19061da177e4SLinus Torvalds  *	beyond the buffer end onto the wire.
19071da177e4SLinus Torvalds  *
1908cd0a137aSFlorian Fainelli  *	May return error in out of memory cases. The skb is freed on error
1909cd0a137aSFlorian Fainelli  *	if @free_on_error is true.
19101da177e4SLinus Torvalds  */
19111da177e4SLinus Torvalds 
1912cd0a137aSFlorian Fainelli int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
19131da177e4SLinus Torvalds {
19145b057c6bSHerbert Xu 	int err;
19155b057c6bSHerbert Xu 	int ntail;
19161da177e4SLinus Torvalds 
19171da177e4SLinus Torvalds 	/* If the skbuff is non linear tailroom is always zero.. */
19185b057c6bSHerbert Xu 	if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
19191da177e4SLinus Torvalds 		memset(skb->data+skb->len, 0, pad);
19205b057c6bSHerbert Xu 		return 0;
19211da177e4SLinus Torvalds 	}
19221da177e4SLinus Torvalds 
19234305b541SArnaldo Carvalho de Melo 	ntail = skb->data_len + pad - (skb->end - skb->tail);
19245b057c6bSHerbert Xu 	if (likely(skb_cloned(skb) || ntail > 0)) {
19255b057c6bSHerbert Xu 		err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
19265b057c6bSHerbert Xu 		if (unlikely(err))
19275b057c6bSHerbert Xu 			goto free_skb;
19285b057c6bSHerbert Xu 	}
19295b057c6bSHerbert Xu 
19305b057c6bSHerbert Xu 	/* FIXME: The use of this function with non-linear skb's really needs
19315b057c6bSHerbert Xu 	 * to be audited.
19325b057c6bSHerbert Xu 	 */
19335b057c6bSHerbert Xu 	err = skb_linearize(skb);
19345b057c6bSHerbert Xu 	if (unlikely(err))
19355b057c6bSHerbert Xu 		goto free_skb;
19365b057c6bSHerbert Xu 
19375b057c6bSHerbert Xu 	memset(skb->data + skb->len, 0, pad);
19385b057c6bSHerbert Xu 	return 0;
19395b057c6bSHerbert Xu 
19405b057c6bSHerbert Xu free_skb:
1941cd0a137aSFlorian Fainelli 	if (free_on_error)
19421da177e4SLinus Torvalds 		kfree_skb(skb);
19435b057c6bSHerbert Xu 	return err;
19441da177e4SLinus Torvalds }
1945cd0a137aSFlorian Fainelli EXPORT_SYMBOL(__skb_pad);
19461da177e4SLinus Torvalds 
19470dde3e16SIlpo Järvinen /**
19480c7ddf36SMathias Krause  *	pskb_put - add data to the tail of a potentially fragmented buffer
19490c7ddf36SMathias Krause  *	@skb: start of the buffer to use
19500c7ddf36SMathias Krause  *	@tail: tail fragment of the buffer to use
19510c7ddf36SMathias Krause  *	@len: amount of data to add
19520c7ddf36SMathias Krause  *
19530c7ddf36SMathias Krause  *	This function extends the used data area of the potentially
19540c7ddf36SMathias Krause  *	fragmented buffer. @tail must be the last fragment of @skb -- or
19550c7ddf36SMathias Krause  *	@skb itself. If this would exceed the total buffer size the kernel
19560c7ddf36SMathias Krause  *	will panic. A pointer to the first byte of the extra data is
19570c7ddf36SMathias Krause  *	returned.
19580c7ddf36SMathias Krause  */
19590c7ddf36SMathias Krause 
19604df864c1SJohannes Berg void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
19610c7ddf36SMathias Krause {
19620c7ddf36SMathias Krause 	if (tail != skb) {
19630c7ddf36SMathias Krause 		skb->data_len += len;
19640c7ddf36SMathias Krause 		skb->len += len;
19650c7ddf36SMathias Krause 	}
19660c7ddf36SMathias Krause 	return skb_put(tail, len);
19670c7ddf36SMathias Krause }
19680c7ddf36SMathias Krause EXPORT_SYMBOL_GPL(pskb_put);
19690c7ddf36SMathias Krause 
19700c7ddf36SMathias Krause /**
19710dde3e16SIlpo Järvinen  *	skb_put - add data to a buffer
19720dde3e16SIlpo Järvinen  *	@skb: buffer to use
19730dde3e16SIlpo Järvinen  *	@len: amount of data to add
19740dde3e16SIlpo Järvinen  *
19750dde3e16SIlpo Järvinen  *	This function extends the used data area of the buffer. If this would
19760dde3e16SIlpo Järvinen  *	exceed the total buffer size the kernel will panic. A pointer to the
19770dde3e16SIlpo Järvinen  *	first byte of the extra data is returned.
19780dde3e16SIlpo Järvinen  */
19794df864c1SJohannes Berg void *skb_put(struct sk_buff *skb, unsigned int len)
19800dde3e16SIlpo Järvinen {
19814df864c1SJohannes Berg 	void *tmp = skb_tail_pointer(skb);
19820dde3e16SIlpo Järvinen 	SKB_LINEAR_ASSERT(skb);
19830dde3e16SIlpo Järvinen 	skb->tail += len;
19840dde3e16SIlpo Järvinen 	skb->len  += len;
19850dde3e16SIlpo Järvinen 	if (unlikely(skb->tail > skb->end))
19860dde3e16SIlpo Järvinen 		skb_over_panic(skb, len, __builtin_return_address(0));
19870dde3e16SIlpo Järvinen 	return tmp;
19880dde3e16SIlpo Järvinen }
19890dde3e16SIlpo Järvinen EXPORT_SYMBOL(skb_put);
19900dde3e16SIlpo Järvinen 
19916be8ac2fSIlpo Järvinen /**
1992c2aa270aSIlpo Järvinen  *	skb_push - add data to the start of a buffer
1993c2aa270aSIlpo Järvinen  *	@skb: buffer to use
1994c2aa270aSIlpo Järvinen  *	@len: amount of data to add
1995c2aa270aSIlpo Järvinen  *
1996c2aa270aSIlpo Järvinen  *	This function extends the used data area of the buffer at the buffer
1997c2aa270aSIlpo Järvinen  *	start. If this would exceed the total buffer headroom the kernel will
1998c2aa270aSIlpo Järvinen  *	panic. A pointer to the first byte of the extra data is returned.
1999c2aa270aSIlpo Järvinen  */
2000d58ff351SJohannes Berg void *skb_push(struct sk_buff *skb, unsigned int len)
2001c2aa270aSIlpo Järvinen {
2002c2aa270aSIlpo Järvinen 	skb->data -= len;
2003c2aa270aSIlpo Järvinen 	skb->len  += len;
2004c2aa270aSIlpo Järvinen 	if (unlikely(skb->data < skb->head))
2005c2aa270aSIlpo Järvinen 		skb_under_panic(skb, len, __builtin_return_address(0));
2006c2aa270aSIlpo Järvinen 	return skb->data;
2007c2aa270aSIlpo Järvinen }
2008c2aa270aSIlpo Järvinen EXPORT_SYMBOL(skb_push);
2009c2aa270aSIlpo Järvinen 
2010c2aa270aSIlpo Järvinen /**
20116be8ac2fSIlpo Järvinen  *	skb_pull - remove data from the start of a buffer
20126be8ac2fSIlpo Järvinen  *	@skb: buffer to use
20136be8ac2fSIlpo Järvinen  *	@len: amount of data to remove
20146be8ac2fSIlpo Järvinen  *
20156be8ac2fSIlpo Järvinen  *	This function removes data from the start of a buffer, returning
20166be8ac2fSIlpo Järvinen  *	the memory to the headroom. A pointer to the next data in the buffer
20176be8ac2fSIlpo Järvinen  *	is returned. Once the data has been pulled future pushes will overwrite
20186be8ac2fSIlpo Järvinen  *	the old data.
20196be8ac2fSIlpo Järvinen  */
2020af72868bSJohannes Berg void *skb_pull(struct sk_buff *skb, unsigned int len)
20216be8ac2fSIlpo Järvinen {
202247d29646SDavid S. Miller 	return skb_pull_inline(skb, len);
20236be8ac2fSIlpo Järvinen }
20246be8ac2fSIlpo Järvinen EXPORT_SYMBOL(skb_pull);
20256be8ac2fSIlpo Järvinen 
2026419ae74eSIlpo Järvinen /**
2027419ae74eSIlpo Järvinen  *	skb_trim - remove end from a buffer
2028419ae74eSIlpo Järvinen  *	@skb: buffer to alter
2029419ae74eSIlpo Järvinen  *	@len: new length
2030419ae74eSIlpo Järvinen  *
2031419ae74eSIlpo Järvinen  *	Cut the length of a buffer down by removing data from the tail. If
2032419ae74eSIlpo Järvinen  *	the buffer is already under the length specified it is not modified.
2033419ae74eSIlpo Järvinen  *	The skb must be linear.
2034419ae74eSIlpo Järvinen  */
2035419ae74eSIlpo Järvinen void skb_trim(struct sk_buff *skb, unsigned int len)
2036419ae74eSIlpo Järvinen {
2037419ae74eSIlpo Järvinen 	if (skb->len > len)
2038419ae74eSIlpo Järvinen 		__skb_trim(skb, len);
2039419ae74eSIlpo Järvinen }
2040419ae74eSIlpo Järvinen EXPORT_SYMBOL(skb_trim);
2041419ae74eSIlpo Järvinen 
20423cc0e873SHerbert Xu /* Trims skb to length len. It can change skb pointers.
20431da177e4SLinus Torvalds  */
20441da177e4SLinus Torvalds 
20453cc0e873SHerbert Xu int ___pskb_trim(struct sk_buff *skb, unsigned int len)
20461da177e4SLinus Torvalds {
204727b437c8SHerbert Xu 	struct sk_buff **fragp;
204827b437c8SHerbert Xu 	struct sk_buff *frag;
20491da177e4SLinus Torvalds 	int offset = skb_headlen(skb);
20501da177e4SLinus Torvalds 	int nfrags = skb_shinfo(skb)->nr_frags;
20511da177e4SLinus Torvalds 	int i;
205227b437c8SHerbert Xu 	int err;
205327b437c8SHerbert Xu 
205427b437c8SHerbert Xu 	if (skb_cloned(skb) &&
205527b437c8SHerbert Xu 	    unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
205627b437c8SHerbert Xu 		return err;
20571da177e4SLinus Torvalds 
2058f4d26fb3SHerbert Xu 	i = 0;
2059f4d26fb3SHerbert Xu 	if (offset >= len)
2060f4d26fb3SHerbert Xu 		goto drop_pages;
2061f4d26fb3SHerbert Xu 
2062f4d26fb3SHerbert Xu 	for (; i < nfrags; i++) {
20639e903e08SEric Dumazet 		int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
206427b437c8SHerbert Xu 
206527b437c8SHerbert Xu 		if (end < len) {
20661da177e4SLinus Torvalds 			offset = end;
206727b437c8SHerbert Xu 			continue;
20681da177e4SLinus Torvalds 		}
20691da177e4SLinus Torvalds 
20709e903e08SEric Dumazet 		skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
207127b437c8SHerbert Xu 
2072f4d26fb3SHerbert Xu drop_pages:
207327b437c8SHerbert Xu 		skb_shinfo(skb)->nr_frags = i;
207427b437c8SHerbert Xu 
207527b437c8SHerbert Xu 		for (; i < nfrags; i++)
2076ea2ab693SIan Campbell 			skb_frag_unref(skb, i);
207727b437c8SHerbert Xu 
207821dc3301SDavid S. Miller 		if (skb_has_frag_list(skb))
207927b437c8SHerbert Xu 			skb_drop_fraglist(skb);
2080f4d26fb3SHerbert Xu 		goto done;
208127b437c8SHerbert Xu 	}
208227b437c8SHerbert Xu 
208327b437c8SHerbert Xu 	for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
208427b437c8SHerbert Xu 	     fragp = &frag->next) {
208527b437c8SHerbert Xu 		int end = offset + frag->len;
208627b437c8SHerbert Xu 
208727b437c8SHerbert Xu 		if (skb_shared(frag)) {
208827b437c8SHerbert Xu 			struct sk_buff *nfrag;
208927b437c8SHerbert Xu 
209027b437c8SHerbert Xu 			nfrag = skb_clone(frag, GFP_ATOMIC);
209127b437c8SHerbert Xu 			if (unlikely(!nfrag))
209227b437c8SHerbert Xu 				return -ENOMEM;
209327b437c8SHerbert Xu 
209427b437c8SHerbert Xu 			nfrag->next = frag->next;
209585bb2a60SEric Dumazet 			consume_skb(frag);
209627b437c8SHerbert Xu 			frag = nfrag;
209727b437c8SHerbert Xu 			*fragp = frag;
209827b437c8SHerbert Xu 		}
209927b437c8SHerbert Xu 
210027b437c8SHerbert Xu 		if (end < len) {
210127b437c8SHerbert Xu 			offset = end;
210227b437c8SHerbert Xu 			continue;
210327b437c8SHerbert Xu 		}
210427b437c8SHerbert Xu 
210527b437c8SHerbert Xu 		if (end > len &&
210627b437c8SHerbert Xu 		    unlikely((err = pskb_trim(frag, len - offset))))
210727b437c8SHerbert Xu 			return err;
210827b437c8SHerbert Xu 
210927b437c8SHerbert Xu 		if (frag->next)
211027b437c8SHerbert Xu 			skb_drop_list(&frag->next);
211127b437c8SHerbert Xu 		break;
211227b437c8SHerbert Xu 	}
211327b437c8SHerbert Xu 
2114f4d26fb3SHerbert Xu done:
211527b437c8SHerbert Xu 	if (len > skb_headlen(skb)) {
21161da177e4SLinus Torvalds 		skb->data_len -= skb->len - len;
21171da177e4SLinus Torvalds 		skb->len       = len;
21181da177e4SLinus Torvalds 	} else {
21191da177e4SLinus Torvalds 		skb->len       = len;
21201da177e4SLinus Torvalds 		skb->data_len  = 0;
212127a884dcSArnaldo Carvalho de Melo 		skb_set_tail_pointer(skb, len);
21221da177e4SLinus Torvalds 	}
21231da177e4SLinus Torvalds 
2124c21b48ccSEric Dumazet 	if (!skb->sk || skb->destructor == sock_edemux)
2125c21b48ccSEric Dumazet 		skb_condense(skb);
21261da177e4SLinus Torvalds 	return 0;
21271da177e4SLinus Torvalds }
2128b4ac530fSDavid S. Miller EXPORT_SYMBOL(___pskb_trim);
21291da177e4SLinus Torvalds 
213088078d98SEric Dumazet /* Note : use pskb_trim_rcsum() instead of calling this directly
213188078d98SEric Dumazet  */
213288078d98SEric Dumazet int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
213388078d98SEric Dumazet {
213488078d98SEric Dumazet 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
213588078d98SEric Dumazet 		int delta = skb->len - len;
213688078d98SEric Dumazet 
2137d55bef50SDimitris Michailidis 		skb->csum = csum_block_sub(skb->csum,
2138d55bef50SDimitris Michailidis 					   skb_checksum(skb, len, delta, 0),
2139d55bef50SDimitris Michailidis 					   len);
214054970a2fSVasily Averin 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
214154970a2fSVasily Averin 		int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
214254970a2fSVasily Averin 		int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
214354970a2fSVasily Averin 
214454970a2fSVasily Averin 		if (offset + sizeof(__sum16) > hdlen)
214554970a2fSVasily Averin 			return -EINVAL;
214688078d98SEric Dumazet 	}
214788078d98SEric Dumazet 	return __pskb_trim(skb, len);
214888078d98SEric Dumazet }
214988078d98SEric Dumazet EXPORT_SYMBOL(pskb_trim_rcsum_slow);
215088078d98SEric Dumazet 
21511da177e4SLinus Torvalds /**
21521da177e4SLinus Torvalds  *	__pskb_pull_tail - advance tail of skb header
21531da177e4SLinus Torvalds  *	@skb: buffer to reallocate
21541da177e4SLinus Torvalds  *	@delta: number of bytes to advance tail
21551da177e4SLinus Torvalds  *
21561da177e4SLinus Torvalds  *	The function makes a sense only on a fragmented &sk_buff,
21571da177e4SLinus Torvalds  *	it expands header moving its tail forward and copying necessary
21581da177e4SLinus Torvalds  *	data from fragmented part.
21591da177e4SLinus Torvalds  *
21601da177e4SLinus Torvalds  *	&sk_buff MUST have reference count of 1.
21611da177e4SLinus Torvalds  *
21621da177e4SLinus Torvalds  *	Returns %NULL (and &sk_buff does not change) if pull failed
21631da177e4SLinus Torvalds  *	or value of new tail of skb in the case of success.
21641da177e4SLinus Torvalds  *
21651da177e4SLinus Torvalds  *	All the pointers pointing into skb header may change and must be
21661da177e4SLinus Torvalds  *	reloaded after call to this function.
21671da177e4SLinus Torvalds  */
21681da177e4SLinus Torvalds 
21691da177e4SLinus Torvalds /* Moves tail of skb head forward, copying data from fragmented part,
21701da177e4SLinus Torvalds  * when it is necessary.
21711da177e4SLinus Torvalds  * 1. It may fail due to malloc failure.
21721da177e4SLinus Torvalds  * 2. It may change skb pointers.
21731da177e4SLinus Torvalds  *
21741da177e4SLinus Torvalds  * It is pretty complicated. Luckily, it is called only in exceptional cases.
21751da177e4SLinus Torvalds  */
2176af72868bSJohannes Berg void *__pskb_pull_tail(struct sk_buff *skb, int delta)
21771da177e4SLinus Torvalds {
21781da177e4SLinus Torvalds 	/* If skb has not enough free space at tail, get new one
21791da177e4SLinus Torvalds 	 * plus 128 bytes for future expansions. If we have enough
21801da177e4SLinus Torvalds 	 * room at tail, reallocate without expansion only if skb is cloned.
21811da177e4SLinus Torvalds 	 */
21824305b541SArnaldo Carvalho de Melo 	int i, k, eat = (skb->tail + delta) - skb->end;
21831da177e4SLinus Torvalds 
21841da177e4SLinus Torvalds 	if (eat > 0 || skb_cloned(skb)) {
21851da177e4SLinus Torvalds 		if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
21861da177e4SLinus Torvalds 				     GFP_ATOMIC))
21871da177e4SLinus Torvalds 			return NULL;
21881da177e4SLinus Torvalds 	}
21891da177e4SLinus Torvalds 
21909f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
21919f77fad3STim Hansen 			     skb_tail_pointer(skb), delta));
21921da177e4SLinus Torvalds 
21931da177e4SLinus Torvalds 	/* Optimization: no fragments, no reasons to preestimate
21941da177e4SLinus Torvalds 	 * size of pulled pages. Superb.
21951da177e4SLinus Torvalds 	 */
219621dc3301SDavid S. Miller 	if (!skb_has_frag_list(skb))
21971da177e4SLinus Torvalds 		goto pull_pages;
21981da177e4SLinus Torvalds 
21991da177e4SLinus Torvalds 	/* Estimate size of pulled pages. */
22001da177e4SLinus Torvalds 	eat = delta;
22011da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
22029e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
22039e903e08SEric Dumazet 
22049e903e08SEric Dumazet 		if (size >= eat)
22051da177e4SLinus Torvalds 			goto pull_pages;
22069e903e08SEric Dumazet 		eat -= size;
22071da177e4SLinus Torvalds 	}
22081da177e4SLinus Torvalds 
22091da177e4SLinus Torvalds 	/* If we need update frag list, we are in troubles.
221009001b03SWenhua Shi 	 * Certainly, it is possible to add an offset to skb data,
22111da177e4SLinus Torvalds 	 * but taking into account that pulling is expected to
22121da177e4SLinus Torvalds 	 * be very rare operation, it is worth to fight against
22131da177e4SLinus Torvalds 	 * further bloating skb head and crucify ourselves here instead.
22141da177e4SLinus Torvalds 	 * Pure masohism, indeed. 8)8)
22151da177e4SLinus Torvalds 	 */
22161da177e4SLinus Torvalds 	if (eat) {
22171da177e4SLinus Torvalds 		struct sk_buff *list = skb_shinfo(skb)->frag_list;
22181da177e4SLinus Torvalds 		struct sk_buff *clone = NULL;
22191da177e4SLinus Torvalds 		struct sk_buff *insp = NULL;
22201da177e4SLinus Torvalds 
22211da177e4SLinus Torvalds 		do {
22221da177e4SLinus Torvalds 			if (list->len <= eat) {
22231da177e4SLinus Torvalds 				/* Eaten as whole. */
22241da177e4SLinus Torvalds 				eat -= list->len;
22251da177e4SLinus Torvalds 				list = list->next;
22261da177e4SLinus Torvalds 				insp = list;
22271da177e4SLinus Torvalds 			} else {
22281da177e4SLinus Torvalds 				/* Eaten partially. */
22291da177e4SLinus Torvalds 
22301da177e4SLinus Torvalds 				if (skb_shared(list)) {
22311da177e4SLinus Torvalds 					/* Sucks! We need to fork list. :-( */
22321da177e4SLinus Torvalds 					clone = skb_clone(list, GFP_ATOMIC);
22331da177e4SLinus Torvalds 					if (!clone)
22341da177e4SLinus Torvalds 						return NULL;
22351da177e4SLinus Torvalds 					insp = list->next;
22361da177e4SLinus Torvalds 					list = clone;
22371da177e4SLinus Torvalds 				} else {
22381da177e4SLinus Torvalds 					/* This may be pulled without
22391da177e4SLinus Torvalds 					 * problems. */
22401da177e4SLinus Torvalds 					insp = list;
22411da177e4SLinus Torvalds 				}
22421da177e4SLinus Torvalds 				if (!pskb_pull(list, eat)) {
22431da177e4SLinus Torvalds 					kfree_skb(clone);
22441da177e4SLinus Torvalds 					return NULL;
22451da177e4SLinus Torvalds 				}
22461da177e4SLinus Torvalds 				break;
22471da177e4SLinus Torvalds 			}
22481da177e4SLinus Torvalds 		} while (eat);
22491da177e4SLinus Torvalds 
22501da177e4SLinus Torvalds 		/* Free pulled out fragments. */
22511da177e4SLinus Torvalds 		while ((list = skb_shinfo(skb)->frag_list) != insp) {
22521da177e4SLinus Torvalds 			skb_shinfo(skb)->frag_list = list->next;
22531da177e4SLinus Torvalds 			kfree_skb(list);
22541da177e4SLinus Torvalds 		}
22551da177e4SLinus Torvalds 		/* And insert new clone at head. */
22561da177e4SLinus Torvalds 		if (clone) {
22571da177e4SLinus Torvalds 			clone->next = list;
22581da177e4SLinus Torvalds 			skb_shinfo(skb)->frag_list = clone;
22591da177e4SLinus Torvalds 		}
22601da177e4SLinus Torvalds 	}
22611da177e4SLinus Torvalds 	/* Success! Now we may commit changes to skb data. */
22621da177e4SLinus Torvalds 
22631da177e4SLinus Torvalds pull_pages:
22641da177e4SLinus Torvalds 	eat = delta;
22651da177e4SLinus Torvalds 	k = 0;
22661da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
22679e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
22689e903e08SEric Dumazet 
22699e903e08SEric Dumazet 		if (size <= eat) {
2270ea2ab693SIan Campbell 			skb_frag_unref(skb, i);
22719e903e08SEric Dumazet 			eat -= size;
22721da177e4SLinus Torvalds 		} else {
2273b54c9d5bSJonathan Lemon 			skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2274b54c9d5bSJonathan Lemon 
2275b54c9d5bSJonathan Lemon 			*frag = skb_shinfo(skb)->frags[i];
22761da177e4SLinus Torvalds 			if (eat) {
2277b54c9d5bSJonathan Lemon 				skb_frag_off_add(frag, eat);
2278b54c9d5bSJonathan Lemon 				skb_frag_size_sub(frag, eat);
22793ccc6c6fSlinzhang 				if (!i)
22803ccc6c6fSlinzhang 					goto end;
22811da177e4SLinus Torvalds 				eat = 0;
22821da177e4SLinus Torvalds 			}
22831da177e4SLinus Torvalds 			k++;
22841da177e4SLinus Torvalds 		}
22851da177e4SLinus Torvalds 	}
22861da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags = k;
22871da177e4SLinus Torvalds 
22883ccc6c6fSlinzhang end:
22891da177e4SLinus Torvalds 	skb->tail     += delta;
22901da177e4SLinus Torvalds 	skb->data_len -= delta;
22911da177e4SLinus Torvalds 
22921f8b977aSWillem de Bruijn 	if (!skb->data_len)
22931f8b977aSWillem de Bruijn 		skb_zcopy_clear(skb, false);
22941f8b977aSWillem de Bruijn 
229527a884dcSArnaldo Carvalho de Melo 	return skb_tail_pointer(skb);
22961da177e4SLinus Torvalds }
2297b4ac530fSDavid S. Miller EXPORT_SYMBOL(__pskb_pull_tail);
22981da177e4SLinus Torvalds 
229922019b17SEric Dumazet /**
230022019b17SEric Dumazet  *	skb_copy_bits - copy bits from skb to kernel buffer
230122019b17SEric Dumazet  *	@skb: source skb
230222019b17SEric Dumazet  *	@offset: offset in source
230322019b17SEric Dumazet  *	@to: destination buffer
230422019b17SEric Dumazet  *	@len: number of bytes to copy
230522019b17SEric Dumazet  *
230622019b17SEric Dumazet  *	Copy the specified number of bytes from the source skb to the
230722019b17SEric Dumazet  *	destination buffer.
230822019b17SEric Dumazet  *
230922019b17SEric Dumazet  *	CAUTION ! :
231022019b17SEric Dumazet  *		If its prototype is ever changed,
231122019b17SEric Dumazet  *		check arch/{*}/net/{*}.S files,
231222019b17SEric Dumazet  *		since it is called from BPF assembly code.
231322019b17SEric Dumazet  */
23141da177e4SLinus Torvalds int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
23151da177e4SLinus Torvalds {
23161a028e50SDavid S. Miller 	int start = skb_headlen(skb);
2317fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
2318fbb398a8SDavid S. Miller 	int i, copy;
23191da177e4SLinus Torvalds 
23201da177e4SLinus Torvalds 	if (offset > (int)skb->len - len)
23211da177e4SLinus Torvalds 		goto fault;
23221da177e4SLinus Torvalds 
23231da177e4SLinus Torvalds 	/* Copy header. */
23241a028e50SDavid S. Miller 	if ((copy = start - offset) > 0) {
23251da177e4SLinus Torvalds 		if (copy > len)
23261da177e4SLinus Torvalds 			copy = len;
2327d626f62bSArnaldo Carvalho de Melo 		skb_copy_from_linear_data_offset(skb, offset, to, copy);
23281da177e4SLinus Torvalds 		if ((len -= copy) == 0)
23291da177e4SLinus Torvalds 			return 0;
23301da177e4SLinus Torvalds 		offset += copy;
23311da177e4SLinus Torvalds 		to     += copy;
23321da177e4SLinus Torvalds 	}
23331da177e4SLinus Torvalds 
23341da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
23351a028e50SDavid S. Miller 		int end;
233651c56b00SEric Dumazet 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
23371da177e4SLinus Torvalds 
2338547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
23391a028e50SDavid S. Miller 
234051c56b00SEric Dumazet 		end = start + skb_frag_size(f);
23411da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
2342c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2343c613c209SWillem de Bruijn 			struct page *p;
23441da177e4SLinus Torvalds 			u8 *vaddr;
23451da177e4SLinus Torvalds 
23461da177e4SLinus Torvalds 			if (copy > len)
23471da177e4SLinus Torvalds 				copy = len;
23481da177e4SLinus Torvalds 
2349c613c209SWillem de Bruijn 			skb_frag_foreach_page(f,
2350b54c9d5bSJonathan Lemon 					      skb_frag_off(f) + offset - start,
2351c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2352c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
2353c613c209SWillem de Bruijn 				memcpy(to + copied, vaddr + p_off, p_len);
235451c56b00SEric Dumazet 				kunmap_atomic(vaddr);
2355c613c209SWillem de Bruijn 			}
23561da177e4SLinus Torvalds 
23571da177e4SLinus Torvalds 			if ((len -= copy) == 0)
23581da177e4SLinus Torvalds 				return 0;
23591da177e4SLinus Torvalds 			offset += copy;
23601da177e4SLinus Torvalds 			to     += copy;
23611da177e4SLinus Torvalds 		}
23621a028e50SDavid S. Miller 		start = end;
23631da177e4SLinus Torvalds 	}
23641da177e4SLinus Torvalds 
2365fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
23661a028e50SDavid S. Miller 		int end;
23671da177e4SLinus Torvalds 
2368547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
23691a028e50SDavid S. Miller 
2370fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
23711da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
23721da177e4SLinus Torvalds 			if (copy > len)
23731da177e4SLinus Torvalds 				copy = len;
2374fbb398a8SDavid S. Miller 			if (skb_copy_bits(frag_iter, offset - start, to, copy))
23751da177e4SLinus Torvalds 				goto fault;
23761da177e4SLinus Torvalds 			if ((len -= copy) == 0)
23771da177e4SLinus Torvalds 				return 0;
23781da177e4SLinus Torvalds 			offset += copy;
23791da177e4SLinus Torvalds 			to     += copy;
23801da177e4SLinus Torvalds 		}
23811a028e50SDavid S. Miller 		start = end;
23821da177e4SLinus Torvalds 	}
2383a6686f2fSShirley Ma 
23841da177e4SLinus Torvalds 	if (!len)
23851da177e4SLinus Torvalds 		return 0;
23861da177e4SLinus Torvalds 
23871da177e4SLinus Torvalds fault:
23881da177e4SLinus Torvalds 	return -EFAULT;
23891da177e4SLinus Torvalds }
2390b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_bits);
23911da177e4SLinus Torvalds 
23929c55e01cSJens Axboe /*
23939c55e01cSJens Axboe  * Callback from splice_to_pipe(), if we need to release some pages
23949c55e01cSJens Axboe  * at the end of the spd in case we error'ed out in filling the pipe.
23959c55e01cSJens Axboe  */
23969c55e01cSJens Axboe static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
23979c55e01cSJens Axboe {
23988b9d3728SJarek Poplawski 	put_page(spd->pages[i]);
23998b9d3728SJarek Poplawski }
24009c55e01cSJens Axboe 
2401a108d5f3SDavid S. Miller static struct page *linear_to_page(struct page *page, unsigned int *len,
24024fb66994SJarek Poplawski 				   unsigned int *offset,
240318aafc62SEric Dumazet 				   struct sock *sk)
24048b9d3728SJarek Poplawski {
24055640f768SEric Dumazet 	struct page_frag *pfrag = sk_page_frag(sk);
24068b9d3728SJarek Poplawski 
24075640f768SEric Dumazet 	if (!sk_page_frag_refill(sk, pfrag))
24088b9d3728SJarek Poplawski 		return NULL;
24094fb66994SJarek Poplawski 
24105640f768SEric Dumazet 	*len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
24114fb66994SJarek Poplawski 
24125640f768SEric Dumazet 	memcpy(page_address(pfrag->page) + pfrag->offset,
24135640f768SEric Dumazet 	       page_address(page) + *offset, *len);
24145640f768SEric Dumazet 	*offset = pfrag->offset;
24155640f768SEric Dumazet 	pfrag->offset += *len;
24164fb66994SJarek Poplawski 
24175640f768SEric Dumazet 	return pfrag->page;
24189c55e01cSJens Axboe }
24199c55e01cSJens Axboe 
242041c73a0dSEric Dumazet static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
242141c73a0dSEric Dumazet 			     struct page *page,
242241c73a0dSEric Dumazet 			     unsigned int offset)
242341c73a0dSEric Dumazet {
242441c73a0dSEric Dumazet 	return	spd->nr_pages &&
242541c73a0dSEric Dumazet 		spd->pages[spd->nr_pages - 1] == page &&
242641c73a0dSEric Dumazet 		(spd->partial[spd->nr_pages - 1].offset +
242741c73a0dSEric Dumazet 		 spd->partial[spd->nr_pages - 1].len == offset);
242841c73a0dSEric Dumazet }
242941c73a0dSEric Dumazet 
24309c55e01cSJens Axboe /*
24319c55e01cSJens Axboe  * Fill page/offset/length into spd, if it can hold more pages.
24329c55e01cSJens Axboe  */
2433a108d5f3SDavid S. Miller static bool spd_fill_page(struct splice_pipe_desc *spd,
243435f3d14dSJens Axboe 			  struct pipe_inode_info *pipe, struct page *page,
24354fb66994SJarek Poplawski 			  unsigned int *len, unsigned int offset,
243618aafc62SEric Dumazet 			  bool linear,
24377a67e56fSJarek Poplawski 			  struct sock *sk)
24389c55e01cSJens Axboe {
243941c73a0dSEric Dumazet 	if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2440a108d5f3SDavid S. Miller 		return true;
24419c55e01cSJens Axboe 
24428b9d3728SJarek Poplawski 	if (linear) {
244318aafc62SEric Dumazet 		page = linear_to_page(page, len, &offset, sk);
24448b9d3728SJarek Poplawski 		if (!page)
2445a108d5f3SDavid S. Miller 			return true;
244641c73a0dSEric Dumazet 	}
244741c73a0dSEric Dumazet 	if (spd_can_coalesce(spd, page, offset)) {
244841c73a0dSEric Dumazet 		spd->partial[spd->nr_pages - 1].len += *len;
2449a108d5f3SDavid S. Miller 		return false;
245041c73a0dSEric Dumazet 	}
24518b9d3728SJarek Poplawski 	get_page(page);
24529c55e01cSJens Axboe 	spd->pages[spd->nr_pages] = page;
24534fb66994SJarek Poplawski 	spd->partial[spd->nr_pages].len = *len;
24549c55e01cSJens Axboe 	spd->partial[spd->nr_pages].offset = offset;
24559c55e01cSJens Axboe 	spd->nr_pages++;
24568b9d3728SJarek Poplawski 
2457a108d5f3SDavid S. Miller 	return false;
24589c55e01cSJens Axboe }
24599c55e01cSJens Axboe 
2460a108d5f3SDavid S. Miller static bool __splice_segment(struct page *page, unsigned int poff,
24612870c43dSOctavian Purdila 			     unsigned int plen, unsigned int *off,
246218aafc62SEric Dumazet 			     unsigned int *len,
2463d7ccf7c0SEric Dumazet 			     struct splice_pipe_desc *spd, bool linear,
246435f3d14dSJens Axboe 			     struct sock *sk,
246535f3d14dSJens Axboe 			     struct pipe_inode_info *pipe)
24669c55e01cSJens Axboe {
24672870c43dSOctavian Purdila 	if (!*len)
2468a108d5f3SDavid S. Miller 		return true;
24699c55e01cSJens Axboe 
24702870c43dSOctavian Purdila 	/* skip this segment if already processed */
24712870c43dSOctavian Purdila 	if (*off >= plen) {
24722870c43dSOctavian Purdila 		*off -= plen;
2473a108d5f3SDavid S. Miller 		return false;
24742870c43dSOctavian Purdila 	}
24752870c43dSOctavian Purdila 
24762870c43dSOctavian Purdila 	/* ignore any bits we already processed */
24779ca1b22dSEric Dumazet 	poff += *off;
24789ca1b22dSEric Dumazet 	plen -= *off;
24792870c43dSOctavian Purdila 	*off = 0;
24802870c43dSOctavian Purdila 
248118aafc62SEric Dumazet 	do {
248218aafc62SEric Dumazet 		unsigned int flen = min(*len, plen);
24832870c43dSOctavian Purdila 
248418aafc62SEric Dumazet 		if (spd_fill_page(spd, pipe, page, &flen, poff,
248518aafc62SEric Dumazet 				  linear, sk))
2486a108d5f3SDavid S. Miller 			return true;
248718aafc62SEric Dumazet 		poff += flen;
248818aafc62SEric Dumazet 		plen -= flen;
24892870c43dSOctavian Purdila 		*len -= flen;
249018aafc62SEric Dumazet 	} while (*len && plen);
24912870c43dSOctavian Purdila 
2492a108d5f3SDavid S. Miller 	return false;
2493db43a282SOctavian Purdila }
24949c55e01cSJens Axboe 
24959c55e01cSJens Axboe /*
2496a108d5f3SDavid S. Miller  * Map linear and fragment data from the skb to spd. It reports true if the
24972870c43dSOctavian Purdila  * pipe is full or if we already spliced the requested length.
24989c55e01cSJens Axboe  */
2499a108d5f3SDavid S. Miller static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
250035f3d14dSJens Axboe 			      unsigned int *offset, unsigned int *len,
250135f3d14dSJens Axboe 			      struct splice_pipe_desc *spd, struct sock *sk)
25022870c43dSOctavian Purdila {
25032870c43dSOctavian Purdila 	int seg;
2504fa9835e5STom Herbert 	struct sk_buff *iter;
25059c55e01cSJens Axboe 
25061d0c0b32SEric Dumazet 	/* map the linear part :
25072996d31fSAlexander Duyck 	 * If skb->head_frag is set, this 'linear' part is backed by a
25082996d31fSAlexander Duyck 	 * fragment, and if the head is not shared with any clones then
25092996d31fSAlexander Duyck 	 * we can avoid a copy since we own the head portion of this page.
25109c55e01cSJens Axboe 	 */
25112870c43dSOctavian Purdila 	if (__splice_segment(virt_to_page(skb->data),
25122870c43dSOctavian Purdila 			     (unsigned long) skb->data & (PAGE_SIZE - 1),
25132870c43dSOctavian Purdila 			     skb_headlen(skb),
251418aafc62SEric Dumazet 			     offset, len, spd,
25153a7c1ee4SAlexander Duyck 			     skb_head_is_locked(skb),
25161d0c0b32SEric Dumazet 			     sk, pipe))
2517a108d5f3SDavid S. Miller 		return true;
25189c55e01cSJens Axboe 
25199c55e01cSJens Axboe 	/*
25209c55e01cSJens Axboe 	 * then map the fragments
25219c55e01cSJens Axboe 	 */
25229c55e01cSJens Axboe 	for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
25239c55e01cSJens Axboe 		const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
25249c55e01cSJens Axboe 
2525ea2ab693SIan Campbell 		if (__splice_segment(skb_frag_page(f),
2526b54c9d5bSJonathan Lemon 				     skb_frag_off(f), skb_frag_size(f),
252718aafc62SEric Dumazet 				     offset, len, spd, false, sk, pipe))
2528a108d5f3SDavid S. Miller 			return true;
25299c55e01cSJens Axboe 	}
25309c55e01cSJens Axboe 
2531fa9835e5STom Herbert 	skb_walk_frags(skb, iter) {
2532fa9835e5STom Herbert 		if (*offset >= iter->len) {
2533fa9835e5STom Herbert 			*offset -= iter->len;
2534fa9835e5STom Herbert 			continue;
2535fa9835e5STom Herbert 		}
2536fa9835e5STom Herbert 		/* __skb_splice_bits() only fails if the output has no room
2537fa9835e5STom Herbert 		 * left, so no point in going over the frag_list for the error
2538fa9835e5STom Herbert 		 * case.
2539fa9835e5STom Herbert 		 */
2540fa9835e5STom Herbert 		if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2541fa9835e5STom Herbert 			return true;
2542fa9835e5STom Herbert 	}
2543fa9835e5STom Herbert 
2544a108d5f3SDavid S. Miller 	return false;
25459c55e01cSJens Axboe }
25469c55e01cSJens Axboe 
25479c55e01cSJens Axboe /*
25489c55e01cSJens Axboe  * Map data from the skb to a pipe. Should handle both the linear part,
2549fa9835e5STom Herbert  * the fragments, and the frag list.
25509c55e01cSJens Axboe  */
2551a60e3cc7SHannes Frederic Sowa int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
25529c55e01cSJens Axboe 		    struct pipe_inode_info *pipe, unsigned int tlen,
255325869262SAl Viro 		    unsigned int flags)
25549c55e01cSJens Axboe {
255541c73a0dSEric Dumazet 	struct partial_page partial[MAX_SKB_FRAGS];
255641c73a0dSEric Dumazet 	struct page *pages[MAX_SKB_FRAGS];
25579c55e01cSJens Axboe 	struct splice_pipe_desc spd = {
25589c55e01cSJens Axboe 		.pages = pages,
25599c55e01cSJens Axboe 		.partial = partial,
2560047fe360SEric Dumazet 		.nr_pages_max = MAX_SKB_FRAGS,
256128a625cbSMiklos Szeredi 		.ops = &nosteal_pipe_buf_ops,
25629c55e01cSJens Axboe 		.spd_release = sock_spd_release,
25639c55e01cSJens Axboe 	};
256435f3d14dSJens Axboe 	int ret = 0;
256535f3d14dSJens Axboe 
2566fa9835e5STom Herbert 	__skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
25679c55e01cSJens Axboe 
2568a60e3cc7SHannes Frederic Sowa 	if (spd.nr_pages)
256925869262SAl Viro 		ret = splice_to_pipe(pipe, &spd);
25709c55e01cSJens Axboe 
257135f3d14dSJens Axboe 	return ret;
25729c55e01cSJens Axboe }
25732b514574SHannes Frederic Sowa EXPORT_SYMBOL_GPL(skb_splice_bits);
25749c55e01cSJens Axboe 
25750739cd28SCong Wang static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
25760739cd28SCong Wang 			    struct kvec *vec, size_t num, size_t size)
25770739cd28SCong Wang {
25780739cd28SCong Wang 	struct socket *sock = sk->sk_socket;
25790739cd28SCong Wang 
25800739cd28SCong Wang 	if (!sock)
25810739cd28SCong Wang 		return -EINVAL;
25820739cd28SCong Wang 	return kernel_sendmsg(sock, msg, vec, num, size);
25830739cd28SCong Wang }
25840739cd28SCong Wang 
25850739cd28SCong Wang static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
25860739cd28SCong Wang 			     size_t size, int flags)
25870739cd28SCong Wang {
25880739cd28SCong Wang 	struct socket *sock = sk->sk_socket;
25890739cd28SCong Wang 
25900739cd28SCong Wang 	if (!sock)
25910739cd28SCong Wang 		return -EINVAL;
25920739cd28SCong Wang 	return kernel_sendpage(sock, page, offset, size, flags);
25930739cd28SCong Wang }
25940739cd28SCong Wang 
25950739cd28SCong Wang typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
25960739cd28SCong Wang 			    struct kvec *vec, size_t num, size_t size);
25970739cd28SCong Wang typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
25980739cd28SCong Wang 			     size_t size, int flags);
25990739cd28SCong Wang static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
26000739cd28SCong Wang 			   int len, sendmsg_func sendmsg, sendpage_func sendpage)
260120bf50deSTom Herbert {
260220bf50deSTom Herbert 	unsigned int orig_len = len;
260320bf50deSTom Herbert 	struct sk_buff *head = skb;
260420bf50deSTom Herbert 	unsigned short fragidx;
260520bf50deSTom Herbert 	int slen, ret;
260620bf50deSTom Herbert 
260720bf50deSTom Herbert do_frag_list:
260820bf50deSTom Herbert 
260920bf50deSTom Herbert 	/* Deal with head data */
261020bf50deSTom Herbert 	while (offset < skb_headlen(skb) && len) {
261120bf50deSTom Herbert 		struct kvec kv;
261220bf50deSTom Herbert 		struct msghdr msg;
261320bf50deSTom Herbert 
261420bf50deSTom Herbert 		slen = min_t(int, len, skb_headlen(skb) - offset);
261520bf50deSTom Herbert 		kv.iov_base = skb->data + offset;
2616db5980d8SJohn Fastabend 		kv.iov_len = slen;
261720bf50deSTom Herbert 		memset(&msg, 0, sizeof(msg));
2618bd95e678SJohn Fastabend 		msg.msg_flags = MSG_DONTWAIT;
261920bf50deSTom Herbert 
26200739cd28SCong Wang 		ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
26210739cd28SCong Wang 				      sendmsg_unlocked, sk, &msg, &kv, 1, slen);
262220bf50deSTom Herbert 		if (ret <= 0)
262320bf50deSTom Herbert 			goto error;
262420bf50deSTom Herbert 
262520bf50deSTom Herbert 		offset += ret;
262620bf50deSTom Herbert 		len -= ret;
262720bf50deSTom Herbert 	}
262820bf50deSTom Herbert 
262920bf50deSTom Herbert 	/* All the data was skb head? */
263020bf50deSTom Herbert 	if (!len)
263120bf50deSTom Herbert 		goto out;
263220bf50deSTom Herbert 
263320bf50deSTom Herbert 	/* Make offset relative to start of frags */
263420bf50deSTom Herbert 	offset -= skb_headlen(skb);
263520bf50deSTom Herbert 
263620bf50deSTom Herbert 	/* Find where we are in frag list */
263720bf50deSTom Herbert 	for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
263820bf50deSTom Herbert 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
263920bf50deSTom Herbert 
2640d8e18a51SMatthew Wilcox (Oracle) 		if (offset < skb_frag_size(frag))
264120bf50deSTom Herbert 			break;
264220bf50deSTom Herbert 
2643d8e18a51SMatthew Wilcox (Oracle) 		offset -= skb_frag_size(frag);
264420bf50deSTom Herbert 	}
264520bf50deSTom Herbert 
264620bf50deSTom Herbert 	for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
264720bf50deSTom Herbert 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
264820bf50deSTom Herbert 
2649d8e18a51SMatthew Wilcox (Oracle) 		slen = min_t(size_t, len, skb_frag_size(frag) - offset);
265020bf50deSTom Herbert 
265120bf50deSTom Herbert 		while (slen) {
26520739cd28SCong Wang 			ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
26530739cd28SCong Wang 					      sendpage_unlocked, sk,
26540739cd28SCong Wang 					      skb_frag_page(frag),
2655b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset,
265620bf50deSTom Herbert 					      slen, MSG_DONTWAIT);
265720bf50deSTom Herbert 			if (ret <= 0)
265820bf50deSTom Herbert 				goto error;
265920bf50deSTom Herbert 
266020bf50deSTom Herbert 			len -= ret;
266120bf50deSTom Herbert 			offset += ret;
266220bf50deSTom Herbert 			slen -= ret;
266320bf50deSTom Herbert 		}
266420bf50deSTom Herbert 
266520bf50deSTom Herbert 		offset = 0;
266620bf50deSTom Herbert 	}
266720bf50deSTom Herbert 
266820bf50deSTom Herbert 	if (len) {
266920bf50deSTom Herbert 		/* Process any frag lists */
267020bf50deSTom Herbert 
267120bf50deSTom Herbert 		if (skb == head) {
267220bf50deSTom Herbert 			if (skb_has_frag_list(skb)) {
267320bf50deSTom Herbert 				skb = skb_shinfo(skb)->frag_list;
267420bf50deSTom Herbert 				goto do_frag_list;
267520bf50deSTom Herbert 			}
267620bf50deSTom Herbert 		} else if (skb->next) {
267720bf50deSTom Herbert 			skb = skb->next;
267820bf50deSTom Herbert 			goto do_frag_list;
267920bf50deSTom Herbert 		}
268020bf50deSTom Herbert 	}
268120bf50deSTom Herbert 
268220bf50deSTom Herbert out:
268320bf50deSTom Herbert 	return orig_len - len;
268420bf50deSTom Herbert 
268520bf50deSTom Herbert error:
268620bf50deSTom Herbert 	return orig_len == len ? ret : orig_len - len;
268720bf50deSTom Herbert }
26880739cd28SCong Wang 
26890739cd28SCong Wang /* Send skb data on a socket. Socket must be locked. */
26900739cd28SCong Wang int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
26910739cd28SCong Wang 			 int len)
26920739cd28SCong Wang {
26930739cd28SCong Wang 	return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
26940739cd28SCong Wang 			       kernel_sendpage_locked);
26950739cd28SCong Wang }
269620bf50deSTom Herbert EXPORT_SYMBOL_GPL(skb_send_sock_locked);
269720bf50deSTom Herbert 
26980739cd28SCong Wang /* Send skb data on a socket. Socket must be unlocked. */
26990739cd28SCong Wang int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
27000739cd28SCong Wang {
27010739cd28SCong Wang 	return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
27020739cd28SCong Wang 			       sendpage_unlocked);
27030739cd28SCong Wang }
27040739cd28SCong Wang 
2705357b40a1SHerbert Xu /**
2706357b40a1SHerbert Xu  *	skb_store_bits - store bits from kernel buffer to skb
2707357b40a1SHerbert Xu  *	@skb: destination buffer
2708357b40a1SHerbert Xu  *	@offset: offset in destination
2709357b40a1SHerbert Xu  *	@from: source buffer
2710357b40a1SHerbert Xu  *	@len: number of bytes to copy
2711357b40a1SHerbert Xu  *
2712357b40a1SHerbert Xu  *	Copy the specified number of bytes from the source buffer to the
2713357b40a1SHerbert Xu  *	destination skb.  This function handles all the messy bits of
2714357b40a1SHerbert Xu  *	traversing fragment lists and such.
2715357b40a1SHerbert Xu  */
2716357b40a1SHerbert Xu 
27170c6fcc8aSStephen Hemminger int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2718357b40a1SHerbert Xu {
27191a028e50SDavid S. Miller 	int start = skb_headlen(skb);
2720fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
2721fbb398a8SDavid S. Miller 	int i, copy;
2722357b40a1SHerbert Xu 
2723357b40a1SHerbert Xu 	if (offset > (int)skb->len - len)
2724357b40a1SHerbert Xu 		goto fault;
2725357b40a1SHerbert Xu 
27261a028e50SDavid S. Miller 	if ((copy = start - offset) > 0) {
2727357b40a1SHerbert Xu 		if (copy > len)
2728357b40a1SHerbert Xu 			copy = len;
272927d7ff46SArnaldo Carvalho de Melo 		skb_copy_to_linear_data_offset(skb, offset, from, copy);
2730357b40a1SHerbert Xu 		if ((len -= copy) == 0)
2731357b40a1SHerbert Xu 			return 0;
2732357b40a1SHerbert Xu 		offset += copy;
2733357b40a1SHerbert Xu 		from += copy;
2734357b40a1SHerbert Xu 	}
2735357b40a1SHerbert Xu 
2736357b40a1SHerbert Xu 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2737357b40a1SHerbert Xu 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
27381a028e50SDavid S. Miller 		int end;
2739357b40a1SHerbert Xu 
2740547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
27411a028e50SDavid S. Miller 
27429e903e08SEric Dumazet 		end = start + skb_frag_size(frag);
2743357b40a1SHerbert Xu 		if ((copy = end - offset) > 0) {
2744c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2745c613c209SWillem de Bruijn 			struct page *p;
2746357b40a1SHerbert Xu 			u8 *vaddr;
2747357b40a1SHerbert Xu 
2748357b40a1SHerbert Xu 			if (copy > len)
2749357b40a1SHerbert Xu 				copy = len;
2750357b40a1SHerbert Xu 
2751c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
2752b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
2753c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2754c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
2755c613c209SWillem de Bruijn 				memcpy(vaddr + p_off, from + copied, p_len);
275651c56b00SEric Dumazet 				kunmap_atomic(vaddr);
2757c613c209SWillem de Bruijn 			}
2758357b40a1SHerbert Xu 
2759357b40a1SHerbert Xu 			if ((len -= copy) == 0)
2760357b40a1SHerbert Xu 				return 0;
2761357b40a1SHerbert Xu 			offset += copy;
2762357b40a1SHerbert Xu 			from += copy;
2763357b40a1SHerbert Xu 		}
27641a028e50SDavid S. Miller 		start = end;
2765357b40a1SHerbert Xu 	}
2766357b40a1SHerbert Xu 
2767fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
27681a028e50SDavid S. Miller 		int end;
2769357b40a1SHerbert Xu 
2770547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
27711a028e50SDavid S. Miller 
2772fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
2773357b40a1SHerbert Xu 		if ((copy = end - offset) > 0) {
2774357b40a1SHerbert Xu 			if (copy > len)
2775357b40a1SHerbert Xu 				copy = len;
2776fbb398a8SDavid S. Miller 			if (skb_store_bits(frag_iter, offset - start,
27771a028e50SDavid S. Miller 					   from, copy))
2778357b40a1SHerbert Xu 				goto fault;
2779357b40a1SHerbert Xu 			if ((len -= copy) == 0)
2780357b40a1SHerbert Xu 				return 0;
2781357b40a1SHerbert Xu 			offset += copy;
2782357b40a1SHerbert Xu 			from += copy;
2783357b40a1SHerbert Xu 		}
27841a028e50SDavid S. Miller 		start = end;
2785357b40a1SHerbert Xu 	}
2786357b40a1SHerbert Xu 	if (!len)
2787357b40a1SHerbert Xu 		return 0;
2788357b40a1SHerbert Xu 
2789357b40a1SHerbert Xu fault:
2790357b40a1SHerbert Xu 	return -EFAULT;
2791357b40a1SHerbert Xu }
2792357b40a1SHerbert Xu EXPORT_SYMBOL(skb_store_bits);
2793357b40a1SHerbert Xu 
27941da177e4SLinus Torvalds /* Checksum skb data. */
27952817a336SDaniel Borkmann __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
27962817a336SDaniel Borkmann 		      __wsum csum, const struct skb_checksum_ops *ops)
27971da177e4SLinus Torvalds {
27981a028e50SDavid S. Miller 	int start = skb_headlen(skb);
27991a028e50SDavid S. Miller 	int i, copy = start - offset;
2800fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
28011da177e4SLinus Torvalds 	int pos = 0;
28021da177e4SLinus Torvalds 
28031da177e4SLinus Torvalds 	/* Checksum header. */
28041da177e4SLinus Torvalds 	if (copy > 0) {
28051da177e4SLinus Torvalds 		if (copy > len)
28061da177e4SLinus Torvalds 			copy = len;
28072544af03SMatteo Croce 		csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
28082544af03SMatteo Croce 				       skb->data + offset, copy, csum);
28091da177e4SLinus Torvalds 		if ((len -= copy) == 0)
28101da177e4SLinus Torvalds 			return csum;
28111da177e4SLinus Torvalds 		offset += copy;
28121da177e4SLinus Torvalds 		pos	= copy;
28131da177e4SLinus Torvalds 	}
28141da177e4SLinus Torvalds 
28151da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
28161a028e50SDavid S. Miller 		int end;
281751c56b00SEric Dumazet 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
28181da177e4SLinus Torvalds 
2819547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
28201a028e50SDavid S. Miller 
282151c56b00SEric Dumazet 		end = start + skb_frag_size(frag);
28221da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
2823c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2824c613c209SWillem de Bruijn 			struct page *p;
282544bb9363SAl Viro 			__wsum csum2;
28261da177e4SLinus Torvalds 			u8 *vaddr;
28271da177e4SLinus Torvalds 
28281da177e4SLinus Torvalds 			if (copy > len)
28291da177e4SLinus Torvalds 				copy = len;
2830c613c209SWillem de Bruijn 
2831c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
2832b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
2833c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2834c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
28352544af03SMatteo Croce 				csum2 = INDIRECT_CALL_1(ops->update,
28362544af03SMatteo Croce 							csum_partial_ext,
28372544af03SMatteo Croce 							vaddr + p_off, p_len, 0);
283851c56b00SEric Dumazet 				kunmap_atomic(vaddr);
28392544af03SMatteo Croce 				csum = INDIRECT_CALL_1(ops->combine,
28402544af03SMatteo Croce 						       csum_block_add_ext, csum,
28412544af03SMatteo Croce 						       csum2, pos, p_len);
2842c613c209SWillem de Bruijn 				pos += p_len;
2843c613c209SWillem de Bruijn 			}
2844c613c209SWillem de Bruijn 
28451da177e4SLinus Torvalds 			if (!(len -= copy))
28461da177e4SLinus Torvalds 				return csum;
28471da177e4SLinus Torvalds 			offset += copy;
28481da177e4SLinus Torvalds 		}
28491a028e50SDavid S. Miller 		start = end;
28501da177e4SLinus Torvalds 	}
28511da177e4SLinus Torvalds 
2852fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
28531a028e50SDavid S. Miller 		int end;
28541da177e4SLinus Torvalds 
2855547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
28561a028e50SDavid S. Miller 
2857fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
28581da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
28595f92a738SAl Viro 			__wsum csum2;
28601da177e4SLinus Torvalds 			if (copy > len)
28611da177e4SLinus Torvalds 				copy = len;
28622817a336SDaniel Borkmann 			csum2 = __skb_checksum(frag_iter, offset - start,
28632817a336SDaniel Borkmann 					       copy, 0, ops);
28642544af03SMatteo Croce 			csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
28652544af03SMatteo Croce 					       csum, csum2, pos, copy);
28661da177e4SLinus Torvalds 			if ((len -= copy) == 0)
28671da177e4SLinus Torvalds 				return csum;
28681da177e4SLinus Torvalds 			offset += copy;
28691da177e4SLinus Torvalds 			pos    += copy;
28701da177e4SLinus Torvalds 		}
28711a028e50SDavid S. Miller 		start = end;
28721da177e4SLinus Torvalds 	}
287309a62660SKris Katterjohn 	BUG_ON(len);
28741da177e4SLinus Torvalds 
28751da177e4SLinus Torvalds 	return csum;
28761da177e4SLinus Torvalds }
28772817a336SDaniel Borkmann EXPORT_SYMBOL(__skb_checksum);
28782817a336SDaniel Borkmann 
28792817a336SDaniel Borkmann __wsum skb_checksum(const struct sk_buff *skb, int offset,
28802817a336SDaniel Borkmann 		    int len, __wsum csum)
28812817a336SDaniel Borkmann {
28822817a336SDaniel Borkmann 	const struct skb_checksum_ops ops = {
2883cea80ea8SDaniel Borkmann 		.update  = csum_partial_ext,
28842817a336SDaniel Borkmann 		.combine = csum_block_add_ext,
28852817a336SDaniel Borkmann 	};
28862817a336SDaniel Borkmann 
28872817a336SDaniel Borkmann 	return __skb_checksum(skb, offset, len, csum, &ops);
28882817a336SDaniel Borkmann }
2889b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_checksum);
28901da177e4SLinus Torvalds 
28911da177e4SLinus Torvalds /* Both of above in one bottle. */
28921da177e4SLinus Torvalds 
289381d77662SAl Viro __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
28948d5930dfSAl Viro 				    u8 *to, int len)
28951da177e4SLinus Torvalds {
28961a028e50SDavid S. Miller 	int start = skb_headlen(skb);
28971a028e50SDavid S. Miller 	int i, copy = start - offset;
2898fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
28991da177e4SLinus Torvalds 	int pos = 0;
29008d5930dfSAl Viro 	__wsum csum = 0;
29011da177e4SLinus Torvalds 
29021da177e4SLinus Torvalds 	/* Copy header. */
29031da177e4SLinus Torvalds 	if (copy > 0) {
29041da177e4SLinus Torvalds 		if (copy > len)
29051da177e4SLinus Torvalds 			copy = len;
29061da177e4SLinus Torvalds 		csum = csum_partial_copy_nocheck(skb->data + offset, to,
2907cc44c17bSAl Viro 						 copy);
29081da177e4SLinus Torvalds 		if ((len -= copy) == 0)
29091da177e4SLinus Torvalds 			return csum;
29101da177e4SLinus Torvalds 		offset += copy;
29111da177e4SLinus Torvalds 		to     += copy;
29121da177e4SLinus Torvalds 		pos	= copy;
29131da177e4SLinus Torvalds 	}
29141da177e4SLinus Torvalds 
29151da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
29161a028e50SDavid S. Miller 		int end;
29171da177e4SLinus Torvalds 
2918547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
29191a028e50SDavid S. Miller 
29209e903e08SEric Dumazet 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
29211da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
2922c613c209SWillem de Bruijn 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
2923c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2924c613c209SWillem de Bruijn 			struct page *p;
29255084205fSAl Viro 			__wsum csum2;
29261da177e4SLinus Torvalds 			u8 *vaddr;
29271da177e4SLinus Torvalds 
29281da177e4SLinus Torvalds 			if (copy > len)
29291da177e4SLinus Torvalds 				copy = len;
2930c613c209SWillem de Bruijn 
2931c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
2932b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
2933c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2934c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
2935c613c209SWillem de Bruijn 				csum2 = csum_partial_copy_nocheck(vaddr + p_off,
2936c613c209SWillem de Bruijn 								  to + copied,
2937cc44c17bSAl Viro 								  p_len);
293851c56b00SEric Dumazet 				kunmap_atomic(vaddr);
29391da177e4SLinus Torvalds 				csum = csum_block_add(csum, csum2, pos);
2940c613c209SWillem de Bruijn 				pos += p_len;
2941c613c209SWillem de Bruijn 			}
2942c613c209SWillem de Bruijn 
29431da177e4SLinus Torvalds 			if (!(len -= copy))
29441da177e4SLinus Torvalds 				return csum;
29451da177e4SLinus Torvalds 			offset += copy;
29461da177e4SLinus Torvalds 			to     += copy;
29471da177e4SLinus Torvalds 		}
29481a028e50SDavid S. Miller 		start = end;
29491da177e4SLinus Torvalds 	}
29501da177e4SLinus Torvalds 
2951fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
295281d77662SAl Viro 		__wsum csum2;
29531a028e50SDavid S. Miller 		int end;
29541da177e4SLinus Torvalds 
2955547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
29561a028e50SDavid S. Miller 
2957fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
29581da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
29591da177e4SLinus Torvalds 			if (copy > len)
29601da177e4SLinus Torvalds 				copy = len;
2961fbb398a8SDavid S. Miller 			csum2 = skb_copy_and_csum_bits(frag_iter,
29621a028e50SDavid S. Miller 						       offset - start,
29638d5930dfSAl Viro 						       to, copy);
29641da177e4SLinus Torvalds 			csum = csum_block_add(csum, csum2, pos);
29651da177e4SLinus Torvalds 			if ((len -= copy) == 0)
29661da177e4SLinus Torvalds 				return csum;
29671da177e4SLinus Torvalds 			offset += copy;
29681da177e4SLinus Torvalds 			to     += copy;
29691da177e4SLinus Torvalds 			pos    += copy;
29701da177e4SLinus Torvalds 		}
29711a028e50SDavid S. Miller 		start = end;
29721da177e4SLinus Torvalds 	}
297309a62660SKris Katterjohn 	BUG_ON(len);
29741da177e4SLinus Torvalds 	return csum;
29751da177e4SLinus Torvalds }
2976b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_and_csum_bits);
29771da177e4SLinus Torvalds 
297849f8e832SCong Wang __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
297949f8e832SCong Wang {
298049f8e832SCong Wang 	__sum16 sum;
298149f8e832SCong Wang 
298249f8e832SCong Wang 	sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
298314641931SCong Wang 	/* See comments in __skb_checksum_complete(). */
298449f8e832SCong Wang 	if (likely(!sum)) {
298549f8e832SCong Wang 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
298649f8e832SCong Wang 		    !skb->csum_complete_sw)
29877fe50ac8SCong Wang 			netdev_rx_csum_fault(skb->dev, skb);
298849f8e832SCong Wang 	}
298949f8e832SCong Wang 	if (!skb_shared(skb))
299049f8e832SCong Wang 		skb->csum_valid = !sum;
299149f8e832SCong Wang 	return sum;
299249f8e832SCong Wang }
299349f8e832SCong Wang EXPORT_SYMBOL(__skb_checksum_complete_head);
299449f8e832SCong Wang 
299514641931SCong Wang /* This function assumes skb->csum already holds pseudo header's checksum,
299614641931SCong Wang  * which has been changed from the hardware checksum, for example, by
299714641931SCong Wang  * __skb_checksum_validate_complete(). And, the original skb->csum must
299814641931SCong Wang  * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
299914641931SCong Wang  *
300014641931SCong Wang  * It returns non-zero if the recomputed checksum is still invalid, otherwise
300114641931SCong Wang  * zero. The new checksum is stored back into skb->csum unless the skb is
300214641931SCong Wang  * shared.
300314641931SCong Wang  */
300449f8e832SCong Wang __sum16 __skb_checksum_complete(struct sk_buff *skb)
300549f8e832SCong Wang {
300649f8e832SCong Wang 	__wsum csum;
300749f8e832SCong Wang 	__sum16 sum;
300849f8e832SCong Wang 
300949f8e832SCong Wang 	csum = skb_checksum(skb, 0, skb->len, 0);
301049f8e832SCong Wang 
301149f8e832SCong Wang 	sum = csum_fold(csum_add(skb->csum, csum));
301214641931SCong Wang 	/* This check is inverted, because we already knew the hardware
301314641931SCong Wang 	 * checksum is invalid before calling this function. So, if the
301414641931SCong Wang 	 * re-computed checksum is valid instead, then we have a mismatch
301514641931SCong Wang 	 * between the original skb->csum and skb_checksum(). This means either
301614641931SCong Wang 	 * the original hardware checksum is incorrect or we screw up skb->csum
301714641931SCong Wang 	 * when moving skb->data around.
301814641931SCong Wang 	 */
301949f8e832SCong Wang 	if (likely(!sum)) {
302049f8e832SCong Wang 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
302149f8e832SCong Wang 		    !skb->csum_complete_sw)
30227fe50ac8SCong Wang 			netdev_rx_csum_fault(skb->dev, skb);
302349f8e832SCong Wang 	}
302449f8e832SCong Wang 
302549f8e832SCong Wang 	if (!skb_shared(skb)) {
302649f8e832SCong Wang 		/* Save full packet checksum */
302749f8e832SCong Wang 		skb->csum = csum;
302849f8e832SCong Wang 		skb->ip_summed = CHECKSUM_COMPLETE;
302949f8e832SCong Wang 		skb->csum_complete_sw = 1;
303049f8e832SCong Wang 		skb->csum_valid = !sum;
303149f8e832SCong Wang 	}
303249f8e832SCong Wang 
303349f8e832SCong Wang 	return sum;
303449f8e832SCong Wang }
303549f8e832SCong Wang EXPORT_SYMBOL(__skb_checksum_complete);
303649f8e832SCong Wang 
30379617813dSDavide Caratti static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
30389617813dSDavide Caratti {
30399617813dSDavide Caratti 	net_warn_ratelimited(
30409617813dSDavide Caratti 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
30419617813dSDavide Caratti 		__func__);
30429617813dSDavide Caratti 	return 0;
30439617813dSDavide Caratti }
30449617813dSDavide Caratti 
30459617813dSDavide Caratti static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
30469617813dSDavide Caratti 				       int offset, int len)
30479617813dSDavide Caratti {
30489617813dSDavide Caratti 	net_warn_ratelimited(
30499617813dSDavide Caratti 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
30509617813dSDavide Caratti 		__func__);
30519617813dSDavide Caratti 	return 0;
30529617813dSDavide Caratti }
30539617813dSDavide Caratti 
30549617813dSDavide Caratti static const struct skb_checksum_ops default_crc32c_ops = {
30559617813dSDavide Caratti 	.update  = warn_crc32c_csum_update,
30569617813dSDavide Caratti 	.combine = warn_crc32c_csum_combine,
30579617813dSDavide Caratti };
30589617813dSDavide Caratti 
30599617813dSDavide Caratti const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
30609617813dSDavide Caratti 	&default_crc32c_ops;
30619617813dSDavide Caratti EXPORT_SYMBOL(crc32c_csum_stub);
30629617813dSDavide Caratti 
3063af2806f8SThomas Graf  /**
3064af2806f8SThomas Graf  *	skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3065af2806f8SThomas Graf  *	@from: source buffer
3066af2806f8SThomas Graf  *
3067af2806f8SThomas Graf  *	Calculates the amount of linear headroom needed in the 'to' skb passed
3068af2806f8SThomas Graf  *	into skb_zerocopy().
3069af2806f8SThomas Graf  */
3070af2806f8SThomas Graf unsigned int
3071af2806f8SThomas Graf skb_zerocopy_headlen(const struct sk_buff *from)
3072af2806f8SThomas Graf {
3073af2806f8SThomas Graf 	unsigned int hlen = 0;
3074af2806f8SThomas Graf 
3075af2806f8SThomas Graf 	if (!from->head_frag ||
3076af2806f8SThomas Graf 	    skb_headlen(from) < L1_CACHE_BYTES ||
3077a17ad096SPravin B Shelar 	    skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3078af2806f8SThomas Graf 		hlen = skb_headlen(from);
3079a17ad096SPravin B Shelar 		if (!hlen)
3080a17ad096SPravin B Shelar 			hlen = from->len;
3081a17ad096SPravin B Shelar 	}
3082af2806f8SThomas Graf 
3083af2806f8SThomas Graf 	if (skb_has_frag_list(from))
3084af2806f8SThomas Graf 		hlen = from->len;
3085af2806f8SThomas Graf 
3086af2806f8SThomas Graf 	return hlen;
3087af2806f8SThomas Graf }
3088af2806f8SThomas Graf EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3089af2806f8SThomas Graf 
3090af2806f8SThomas Graf /**
3091af2806f8SThomas Graf  *	skb_zerocopy - Zero copy skb to skb
3092af2806f8SThomas Graf  *	@to: destination buffer
30937fceb4deSMasanari Iida  *	@from: source buffer
3094af2806f8SThomas Graf  *	@len: number of bytes to copy from source buffer
3095af2806f8SThomas Graf  *	@hlen: size of linear headroom in destination buffer
3096af2806f8SThomas Graf  *
3097af2806f8SThomas Graf  *	Copies up to `len` bytes from `from` to `to` by creating references
3098af2806f8SThomas Graf  *	to the frags in the source buffer.
3099af2806f8SThomas Graf  *
3100af2806f8SThomas Graf  *	The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3101af2806f8SThomas Graf  *	headroom in the `to` buffer.
310236d5fe6aSZoltan Kiss  *
310336d5fe6aSZoltan Kiss  *	Return value:
310436d5fe6aSZoltan Kiss  *	0: everything is OK
310536d5fe6aSZoltan Kiss  *	-ENOMEM: couldn't orphan frags of @from due to lack of memory
310636d5fe6aSZoltan Kiss  *	-EFAULT: skb_copy_bits() found some problem with skb geometry
3107af2806f8SThomas Graf  */
310836d5fe6aSZoltan Kiss int
310936d5fe6aSZoltan Kiss skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3110af2806f8SThomas Graf {
3111af2806f8SThomas Graf 	int i, j = 0;
3112af2806f8SThomas Graf 	int plen = 0; /* length of skb->head fragment */
311336d5fe6aSZoltan Kiss 	int ret;
3114af2806f8SThomas Graf 	struct page *page;
3115af2806f8SThomas Graf 	unsigned int offset;
3116af2806f8SThomas Graf 
3117af2806f8SThomas Graf 	BUG_ON(!from->head_frag && !hlen);
3118af2806f8SThomas Graf 
3119af2806f8SThomas Graf 	/* dont bother with small payloads */
312036d5fe6aSZoltan Kiss 	if (len <= skb_tailroom(to))
312136d5fe6aSZoltan Kiss 		return skb_copy_bits(from, 0, skb_put(to, len), len);
3122af2806f8SThomas Graf 
3123af2806f8SThomas Graf 	if (hlen) {
312436d5fe6aSZoltan Kiss 		ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
312536d5fe6aSZoltan Kiss 		if (unlikely(ret))
312636d5fe6aSZoltan Kiss 			return ret;
3127af2806f8SThomas Graf 		len -= hlen;
3128af2806f8SThomas Graf 	} else {
3129af2806f8SThomas Graf 		plen = min_t(int, skb_headlen(from), len);
3130af2806f8SThomas Graf 		if (plen) {
3131af2806f8SThomas Graf 			page = virt_to_head_page(from->head);
3132af2806f8SThomas Graf 			offset = from->data - (unsigned char *)page_address(page);
3133af2806f8SThomas Graf 			__skb_fill_page_desc(to, 0, page, offset, plen);
3134af2806f8SThomas Graf 			get_page(page);
3135af2806f8SThomas Graf 			j = 1;
3136af2806f8SThomas Graf 			len -= plen;
3137af2806f8SThomas Graf 		}
3138af2806f8SThomas Graf 	}
3139af2806f8SThomas Graf 
3140af2806f8SThomas Graf 	to->truesize += len + plen;
3141af2806f8SThomas Graf 	to->len += len + plen;
3142af2806f8SThomas Graf 	to->data_len += len + plen;
3143af2806f8SThomas Graf 
314436d5fe6aSZoltan Kiss 	if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
314536d5fe6aSZoltan Kiss 		skb_tx_error(from);
314636d5fe6aSZoltan Kiss 		return -ENOMEM;
314736d5fe6aSZoltan Kiss 	}
31481f8b977aSWillem de Bruijn 	skb_zerocopy_clone(to, from, GFP_ATOMIC);
314936d5fe6aSZoltan Kiss 
3150af2806f8SThomas Graf 	for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3151d8e18a51SMatthew Wilcox (Oracle) 		int size;
3152d8e18a51SMatthew Wilcox (Oracle) 
3153af2806f8SThomas Graf 		if (!len)
3154af2806f8SThomas Graf 			break;
3155af2806f8SThomas Graf 		skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3156d8e18a51SMatthew Wilcox (Oracle) 		size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3157d8e18a51SMatthew Wilcox (Oracle) 					len);
3158d8e18a51SMatthew Wilcox (Oracle) 		skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3159d8e18a51SMatthew Wilcox (Oracle) 		len -= size;
3160af2806f8SThomas Graf 		skb_frag_ref(to, j);
3161af2806f8SThomas Graf 		j++;
3162af2806f8SThomas Graf 	}
3163af2806f8SThomas Graf 	skb_shinfo(to)->nr_frags = j;
316436d5fe6aSZoltan Kiss 
316536d5fe6aSZoltan Kiss 	return 0;
3166af2806f8SThomas Graf }
3167af2806f8SThomas Graf EXPORT_SYMBOL_GPL(skb_zerocopy);
3168af2806f8SThomas Graf 
31691da177e4SLinus Torvalds void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
31701da177e4SLinus Torvalds {
3171d3bc23e7SAl Viro 	__wsum csum;
31721da177e4SLinus Torvalds 	long csstart;
31731da177e4SLinus Torvalds 
317484fa7933SPatrick McHardy 	if (skb->ip_summed == CHECKSUM_PARTIAL)
317555508d60SMichał Mirosław 		csstart = skb_checksum_start_offset(skb);
31761da177e4SLinus Torvalds 	else
31771da177e4SLinus Torvalds 		csstart = skb_headlen(skb);
31781da177e4SLinus Torvalds 
317909a62660SKris Katterjohn 	BUG_ON(csstart > skb_headlen(skb));
31801da177e4SLinus Torvalds 
3181d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data(skb, to, csstart);
31821da177e4SLinus Torvalds 
31831da177e4SLinus Torvalds 	csum = 0;
31841da177e4SLinus Torvalds 	if (csstart != skb->len)
31851da177e4SLinus Torvalds 		csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
31868d5930dfSAl Viro 					      skb->len - csstart);
31871da177e4SLinus Torvalds 
318884fa7933SPatrick McHardy 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
3189ff1dcadbSAl Viro 		long csstuff = csstart + skb->csum_offset;
31901da177e4SLinus Torvalds 
3191d3bc23e7SAl Viro 		*((__sum16 *)(to + csstuff)) = csum_fold(csum);
31921da177e4SLinus Torvalds 	}
31931da177e4SLinus Torvalds }
3194b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_and_csum_dev);
31951da177e4SLinus Torvalds 
31961da177e4SLinus Torvalds /**
31971da177e4SLinus Torvalds  *	skb_dequeue - remove from the head of the queue
31981da177e4SLinus Torvalds  *	@list: list to dequeue from
31991da177e4SLinus Torvalds  *
32001da177e4SLinus Torvalds  *	Remove the head of the list. The list lock is taken so the function
32011da177e4SLinus Torvalds  *	may be used safely with other locking list functions. The head item is
32021da177e4SLinus Torvalds  *	returned or %NULL if the list is empty.
32031da177e4SLinus Torvalds  */
32041da177e4SLinus Torvalds 
32051da177e4SLinus Torvalds struct sk_buff *skb_dequeue(struct sk_buff_head *list)
32061da177e4SLinus Torvalds {
32071da177e4SLinus Torvalds 	unsigned long flags;
32081da177e4SLinus Torvalds 	struct sk_buff *result;
32091da177e4SLinus Torvalds 
32101da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
32111da177e4SLinus Torvalds 	result = __skb_dequeue(list);
32121da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
32131da177e4SLinus Torvalds 	return result;
32141da177e4SLinus Torvalds }
3215b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_dequeue);
32161da177e4SLinus Torvalds 
32171da177e4SLinus Torvalds /**
32181da177e4SLinus Torvalds  *	skb_dequeue_tail - remove from the tail of the queue
32191da177e4SLinus Torvalds  *	@list: list to dequeue from
32201da177e4SLinus Torvalds  *
32211da177e4SLinus Torvalds  *	Remove the tail of the list. The list lock is taken so the function
32221da177e4SLinus Torvalds  *	may be used safely with other locking list functions. The tail item is
32231da177e4SLinus Torvalds  *	returned or %NULL if the list is empty.
32241da177e4SLinus Torvalds  */
32251da177e4SLinus Torvalds struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
32261da177e4SLinus Torvalds {
32271da177e4SLinus Torvalds 	unsigned long flags;
32281da177e4SLinus Torvalds 	struct sk_buff *result;
32291da177e4SLinus Torvalds 
32301da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
32311da177e4SLinus Torvalds 	result = __skb_dequeue_tail(list);
32321da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
32331da177e4SLinus Torvalds 	return result;
32341da177e4SLinus Torvalds }
3235b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_dequeue_tail);
32361da177e4SLinus Torvalds 
32371da177e4SLinus Torvalds /**
32381da177e4SLinus Torvalds  *	skb_queue_purge - empty a list
32391da177e4SLinus Torvalds  *	@list: list to empty
32401da177e4SLinus Torvalds  *
32411da177e4SLinus Torvalds  *	Delete all buffers on an &sk_buff list. Each buffer is removed from
32421da177e4SLinus Torvalds  *	the list and one reference dropped. This function takes the list
32431da177e4SLinus Torvalds  *	lock and is atomic with respect to other list locking functions.
32441da177e4SLinus Torvalds  */
32451da177e4SLinus Torvalds void skb_queue_purge(struct sk_buff_head *list)
32461da177e4SLinus Torvalds {
32471da177e4SLinus Torvalds 	struct sk_buff *skb;
32481da177e4SLinus Torvalds 	while ((skb = skb_dequeue(list)) != NULL)
32491da177e4SLinus Torvalds 		kfree_skb(skb);
32501da177e4SLinus Torvalds }
3251b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_purge);
32521da177e4SLinus Torvalds 
32531da177e4SLinus Torvalds /**
32549f5afeaeSYaogong Wang  *	skb_rbtree_purge - empty a skb rbtree
32559f5afeaeSYaogong Wang  *	@root: root of the rbtree to empty
3256385114deSPeter Oskolkov  *	Return value: the sum of truesizes of all purged skbs.
32579f5afeaeSYaogong Wang  *
32589f5afeaeSYaogong Wang  *	Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
32599f5afeaeSYaogong Wang  *	the list and one reference dropped. This function does not take
32609f5afeaeSYaogong Wang  *	any lock. Synchronization should be handled by the caller (e.g., TCP
32619f5afeaeSYaogong Wang  *	out-of-order queue is protected by the socket lock).
32629f5afeaeSYaogong Wang  */
3263385114deSPeter Oskolkov unsigned int skb_rbtree_purge(struct rb_root *root)
32649f5afeaeSYaogong Wang {
32657c90584cSEric Dumazet 	struct rb_node *p = rb_first(root);
3266385114deSPeter Oskolkov 	unsigned int sum = 0;
32679f5afeaeSYaogong Wang 
32687c90584cSEric Dumazet 	while (p) {
32697c90584cSEric Dumazet 		struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
32707c90584cSEric Dumazet 
32717c90584cSEric Dumazet 		p = rb_next(p);
32727c90584cSEric Dumazet 		rb_erase(&skb->rbnode, root);
3273385114deSPeter Oskolkov 		sum += skb->truesize;
32749f5afeaeSYaogong Wang 		kfree_skb(skb);
32757c90584cSEric Dumazet 	}
3276385114deSPeter Oskolkov 	return sum;
32779f5afeaeSYaogong Wang }
32789f5afeaeSYaogong Wang 
32799f5afeaeSYaogong Wang /**
32801da177e4SLinus Torvalds  *	skb_queue_head - queue a buffer at the list head
32811da177e4SLinus Torvalds  *	@list: list to use
32821da177e4SLinus Torvalds  *	@newsk: buffer to queue
32831da177e4SLinus Torvalds  *
32841da177e4SLinus Torvalds  *	Queue a buffer at the start of the list. This function takes the
32851da177e4SLinus Torvalds  *	list lock and can be used safely with other locking &sk_buff functions
32861da177e4SLinus Torvalds  *	safely.
32871da177e4SLinus Torvalds  *
32881da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
32891da177e4SLinus Torvalds  */
32901da177e4SLinus Torvalds void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
32911da177e4SLinus Torvalds {
32921da177e4SLinus Torvalds 	unsigned long flags;
32931da177e4SLinus Torvalds 
32941da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
32951da177e4SLinus Torvalds 	__skb_queue_head(list, newsk);
32961da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
32971da177e4SLinus Torvalds }
3298b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_head);
32991da177e4SLinus Torvalds 
33001da177e4SLinus Torvalds /**
33011da177e4SLinus Torvalds  *	skb_queue_tail - queue a buffer at the list tail
33021da177e4SLinus Torvalds  *	@list: list to use
33031da177e4SLinus Torvalds  *	@newsk: buffer to queue
33041da177e4SLinus Torvalds  *
33051da177e4SLinus Torvalds  *	Queue a buffer at the tail of the list. This function takes the
33061da177e4SLinus Torvalds  *	list lock and can be used safely with other locking &sk_buff functions
33071da177e4SLinus Torvalds  *	safely.
33081da177e4SLinus Torvalds  *
33091da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
33101da177e4SLinus Torvalds  */
33111da177e4SLinus Torvalds void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
33121da177e4SLinus Torvalds {
33131da177e4SLinus Torvalds 	unsigned long flags;
33141da177e4SLinus Torvalds 
33151da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
33161da177e4SLinus Torvalds 	__skb_queue_tail(list, newsk);
33171da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
33181da177e4SLinus Torvalds }
3319b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_tail);
33208728b834SDavid S. Miller 
33211da177e4SLinus Torvalds /**
33221da177e4SLinus Torvalds  *	skb_unlink	-	remove a buffer from a list
33231da177e4SLinus Torvalds  *	@skb: buffer to remove
33248728b834SDavid S. Miller  *	@list: list to use
33251da177e4SLinus Torvalds  *
33268728b834SDavid S. Miller  *	Remove a packet from a list. The list locks are taken and this
33278728b834SDavid S. Miller  *	function is atomic with respect to other list locked calls
33281da177e4SLinus Torvalds  *
33298728b834SDavid S. Miller  *	You must know what list the SKB is on.
33301da177e4SLinus Torvalds  */
33318728b834SDavid S. Miller void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
33321da177e4SLinus Torvalds {
33331da177e4SLinus Torvalds 	unsigned long flags;
33341da177e4SLinus Torvalds 
33351da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
33368728b834SDavid S. Miller 	__skb_unlink(skb, list);
33371da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
33381da177e4SLinus Torvalds }
3339b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_unlink);
33401da177e4SLinus Torvalds 
33411da177e4SLinus Torvalds /**
33421da177e4SLinus Torvalds  *	skb_append	-	append a buffer
33431da177e4SLinus Torvalds  *	@old: buffer to insert after
33441da177e4SLinus Torvalds  *	@newsk: buffer to insert
33458728b834SDavid S. Miller  *	@list: list to use
33461da177e4SLinus Torvalds  *
33471da177e4SLinus Torvalds  *	Place a packet after a given packet in a list. The list locks are taken
33481da177e4SLinus Torvalds  *	and this function is atomic with respect to other list locked calls.
33491da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
33501da177e4SLinus Torvalds  */
33518728b834SDavid S. Miller void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
33521da177e4SLinus Torvalds {
33531da177e4SLinus Torvalds 	unsigned long flags;
33541da177e4SLinus Torvalds 
33558728b834SDavid S. Miller 	spin_lock_irqsave(&list->lock, flags);
33567de6c033SGerrit Renker 	__skb_queue_after(list, old, newsk);
33578728b834SDavid S. Miller 	spin_unlock_irqrestore(&list->lock, flags);
33581da177e4SLinus Torvalds }
3359b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_append);
33601da177e4SLinus Torvalds 
33611da177e4SLinus Torvalds static inline void skb_split_inside_header(struct sk_buff *skb,
33621da177e4SLinus Torvalds 					   struct sk_buff* skb1,
33631da177e4SLinus Torvalds 					   const u32 len, const int pos)
33641da177e4SLinus Torvalds {
33651da177e4SLinus Torvalds 	int i;
33661da177e4SLinus Torvalds 
3367d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3368d626f62bSArnaldo Carvalho de Melo 					 pos - len);
33691da177e4SLinus Torvalds 	/* And move data appendix as is. */
33701da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
33711da177e4SLinus Torvalds 		skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
33721da177e4SLinus Torvalds 
33731da177e4SLinus Torvalds 	skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
33741da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags  = 0;
33751da177e4SLinus Torvalds 	skb1->data_len		   = skb->data_len;
33761da177e4SLinus Torvalds 	skb1->len		   += skb1->data_len;
33771da177e4SLinus Torvalds 	skb->data_len		   = 0;
33781da177e4SLinus Torvalds 	skb->len		   = len;
337927a884dcSArnaldo Carvalho de Melo 	skb_set_tail_pointer(skb, len);
33801da177e4SLinus Torvalds }
33811da177e4SLinus Torvalds 
33821da177e4SLinus Torvalds static inline void skb_split_no_header(struct sk_buff *skb,
33831da177e4SLinus Torvalds 				       struct sk_buff* skb1,
33841da177e4SLinus Torvalds 				       const u32 len, int pos)
33851da177e4SLinus Torvalds {
33861da177e4SLinus Torvalds 	int i, k = 0;
33871da177e4SLinus Torvalds 	const int nfrags = skb_shinfo(skb)->nr_frags;
33881da177e4SLinus Torvalds 
33891da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags = 0;
33901da177e4SLinus Torvalds 	skb1->len		  = skb1->data_len = skb->len - len;
33911da177e4SLinus Torvalds 	skb->len		  = len;
33921da177e4SLinus Torvalds 	skb->data_len		  = len - pos;
33931da177e4SLinus Torvalds 
33941da177e4SLinus Torvalds 	for (i = 0; i < nfrags; i++) {
33959e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
33961da177e4SLinus Torvalds 
33971da177e4SLinus Torvalds 		if (pos + size > len) {
33981da177e4SLinus Torvalds 			skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
33991da177e4SLinus Torvalds 
34001da177e4SLinus Torvalds 			if (pos < len) {
34011da177e4SLinus Torvalds 				/* Split frag.
34021da177e4SLinus Torvalds 				 * We have two variants in this case:
34031da177e4SLinus Torvalds 				 * 1. Move all the frag to the second
34041da177e4SLinus Torvalds 				 *    part, if it is possible. F.e.
34051da177e4SLinus Torvalds 				 *    this approach is mandatory for TUX,
34061da177e4SLinus Torvalds 				 *    where splitting is expensive.
34071da177e4SLinus Torvalds 				 * 2. Split is accurately. We make this.
34081da177e4SLinus Torvalds 				 */
3409ea2ab693SIan Campbell 				skb_frag_ref(skb, i);
3410b54c9d5bSJonathan Lemon 				skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
34119e903e08SEric Dumazet 				skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
34129e903e08SEric Dumazet 				skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
34131da177e4SLinus Torvalds 				skb_shinfo(skb)->nr_frags++;
34141da177e4SLinus Torvalds 			}
34151da177e4SLinus Torvalds 			k++;
34161da177e4SLinus Torvalds 		} else
34171da177e4SLinus Torvalds 			skb_shinfo(skb)->nr_frags++;
34181da177e4SLinus Torvalds 		pos += size;
34191da177e4SLinus Torvalds 	}
34201da177e4SLinus Torvalds 	skb_shinfo(skb1)->nr_frags = k;
34211da177e4SLinus Torvalds }
34221da177e4SLinus Torvalds 
34231da177e4SLinus Torvalds /**
34241da177e4SLinus Torvalds  * skb_split - Split fragmented skb to two parts at length len.
34251da177e4SLinus Torvalds  * @skb: the buffer to split
34261da177e4SLinus Torvalds  * @skb1: the buffer to receive the second part
34271da177e4SLinus Torvalds  * @len: new length for skb
34281da177e4SLinus Torvalds  */
34291da177e4SLinus Torvalds void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
34301da177e4SLinus Torvalds {
34311da177e4SLinus Torvalds 	int pos = skb_headlen(skb);
34329b65b17dSTalal Ahmad 	const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
34331da177e4SLinus Torvalds 
34349b65b17dSTalal Ahmad 	skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
34351f8b977aSWillem de Bruijn 	skb_zerocopy_clone(skb1, skb, 0);
34361da177e4SLinus Torvalds 	if (len < pos)	/* Split line is inside header. */
34371da177e4SLinus Torvalds 		skb_split_inside_header(skb, skb1, len, pos);
34381da177e4SLinus Torvalds 	else		/* Second chunk has no header, nothing to copy. */
34391da177e4SLinus Torvalds 		skb_split_no_header(skb, skb1, len, pos);
34401da177e4SLinus Torvalds }
3441b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_split);
34421da177e4SLinus Torvalds 
34439f782db3SIlpo Järvinen /* Shifting from/to a cloned skb is a no-go.
34449f782db3SIlpo Järvinen  *
34459f782db3SIlpo Järvinen  * Caller cannot keep skb_shinfo related pointers past calling here!
34469f782db3SIlpo Järvinen  */
3447832d11c5SIlpo Järvinen static int skb_prepare_for_shift(struct sk_buff *skb)
3448832d11c5SIlpo Järvinen {
3449c4777efaSEric Dumazet 	return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3450832d11c5SIlpo Järvinen }
3451832d11c5SIlpo Järvinen 
3452832d11c5SIlpo Järvinen /**
3453832d11c5SIlpo Järvinen  * skb_shift - Shifts paged data partially from skb to another
3454832d11c5SIlpo Järvinen  * @tgt: buffer into which tail data gets added
3455832d11c5SIlpo Järvinen  * @skb: buffer from which the paged data comes from
3456832d11c5SIlpo Järvinen  * @shiftlen: shift up to this many bytes
3457832d11c5SIlpo Järvinen  *
3458832d11c5SIlpo Järvinen  * Attempts to shift up to shiftlen worth of bytes, which may be less than
345920e994a0SFeng King  * the length of the skb, from skb to tgt. Returns number bytes shifted.
3460832d11c5SIlpo Järvinen  * It's up to caller to free skb if everything was shifted.
3461832d11c5SIlpo Järvinen  *
3462832d11c5SIlpo Järvinen  * If @tgt runs out of frags, the whole operation is aborted.
3463832d11c5SIlpo Järvinen  *
3464832d11c5SIlpo Järvinen  * Skb cannot include anything else but paged data while tgt is allowed
3465832d11c5SIlpo Järvinen  * to have non-paged data as well.
3466832d11c5SIlpo Järvinen  *
3467832d11c5SIlpo Järvinen  * TODO: full sized shift could be optimized but that would need
3468832d11c5SIlpo Järvinen  * specialized skb free'er to handle frags without up-to-date nr_frags.
3469832d11c5SIlpo Järvinen  */
3470832d11c5SIlpo Järvinen int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3471832d11c5SIlpo Järvinen {
3472832d11c5SIlpo Järvinen 	int from, to, merge, todo;
3473d8e18a51SMatthew Wilcox (Oracle) 	skb_frag_t *fragfrom, *fragto;
3474832d11c5SIlpo Järvinen 
3475832d11c5SIlpo Järvinen 	BUG_ON(shiftlen > skb->len);
3476f8071cdeSEric Dumazet 
3477f8071cdeSEric Dumazet 	if (skb_headlen(skb))
3478f8071cdeSEric Dumazet 		return 0;
34791f8b977aSWillem de Bruijn 	if (skb_zcopy(tgt) || skb_zcopy(skb))
34801f8b977aSWillem de Bruijn 		return 0;
3481832d11c5SIlpo Järvinen 
3482832d11c5SIlpo Järvinen 	todo = shiftlen;
3483832d11c5SIlpo Järvinen 	from = 0;
3484832d11c5SIlpo Järvinen 	to = skb_shinfo(tgt)->nr_frags;
3485832d11c5SIlpo Järvinen 	fragfrom = &skb_shinfo(skb)->frags[from];
3486832d11c5SIlpo Järvinen 
3487832d11c5SIlpo Järvinen 	/* Actual merge is delayed until the point when we know we can
3488832d11c5SIlpo Järvinen 	 * commit all, so that we don't have to undo partial changes
3489832d11c5SIlpo Järvinen 	 */
3490832d11c5SIlpo Järvinen 	if (!to ||
3491ea2ab693SIan Campbell 	    !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3492b54c9d5bSJonathan Lemon 			      skb_frag_off(fragfrom))) {
3493832d11c5SIlpo Järvinen 		merge = -1;
3494832d11c5SIlpo Järvinen 	} else {
3495832d11c5SIlpo Järvinen 		merge = to - 1;
3496832d11c5SIlpo Järvinen 
34979e903e08SEric Dumazet 		todo -= skb_frag_size(fragfrom);
3498832d11c5SIlpo Järvinen 		if (todo < 0) {
3499832d11c5SIlpo Järvinen 			if (skb_prepare_for_shift(skb) ||
3500832d11c5SIlpo Järvinen 			    skb_prepare_for_shift(tgt))
3501832d11c5SIlpo Järvinen 				return 0;
3502832d11c5SIlpo Järvinen 
35039f782db3SIlpo Järvinen 			/* All previous frag pointers might be stale! */
35049f782db3SIlpo Järvinen 			fragfrom = &skb_shinfo(skb)->frags[from];
3505832d11c5SIlpo Järvinen 			fragto = &skb_shinfo(tgt)->frags[merge];
3506832d11c5SIlpo Järvinen 
35079e903e08SEric Dumazet 			skb_frag_size_add(fragto, shiftlen);
35089e903e08SEric Dumazet 			skb_frag_size_sub(fragfrom, shiftlen);
3509b54c9d5bSJonathan Lemon 			skb_frag_off_add(fragfrom, shiftlen);
3510832d11c5SIlpo Järvinen 
3511832d11c5SIlpo Järvinen 			goto onlymerged;
3512832d11c5SIlpo Järvinen 		}
3513832d11c5SIlpo Järvinen 
3514832d11c5SIlpo Järvinen 		from++;
3515832d11c5SIlpo Järvinen 	}
3516832d11c5SIlpo Järvinen 
3517832d11c5SIlpo Järvinen 	/* Skip full, not-fitting skb to avoid expensive operations */
3518832d11c5SIlpo Järvinen 	if ((shiftlen == skb->len) &&
3519832d11c5SIlpo Järvinen 	    (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3520832d11c5SIlpo Järvinen 		return 0;
3521832d11c5SIlpo Järvinen 
3522832d11c5SIlpo Järvinen 	if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3523832d11c5SIlpo Järvinen 		return 0;
3524832d11c5SIlpo Järvinen 
3525832d11c5SIlpo Järvinen 	while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3526832d11c5SIlpo Järvinen 		if (to == MAX_SKB_FRAGS)
3527832d11c5SIlpo Järvinen 			return 0;
3528832d11c5SIlpo Järvinen 
3529832d11c5SIlpo Järvinen 		fragfrom = &skb_shinfo(skb)->frags[from];
3530832d11c5SIlpo Järvinen 		fragto = &skb_shinfo(tgt)->frags[to];
3531832d11c5SIlpo Järvinen 
35329e903e08SEric Dumazet 		if (todo >= skb_frag_size(fragfrom)) {
3533832d11c5SIlpo Järvinen 			*fragto = *fragfrom;
35349e903e08SEric Dumazet 			todo -= skb_frag_size(fragfrom);
3535832d11c5SIlpo Järvinen 			from++;
3536832d11c5SIlpo Järvinen 			to++;
3537832d11c5SIlpo Järvinen 
3538832d11c5SIlpo Järvinen 		} else {
3539ea2ab693SIan Campbell 			__skb_frag_ref(fragfrom);
3540b54c9d5bSJonathan Lemon 			skb_frag_page_copy(fragto, fragfrom);
3541b54c9d5bSJonathan Lemon 			skb_frag_off_copy(fragto, fragfrom);
35429e903e08SEric Dumazet 			skb_frag_size_set(fragto, todo);
3543832d11c5SIlpo Järvinen 
3544b54c9d5bSJonathan Lemon 			skb_frag_off_add(fragfrom, todo);
35459e903e08SEric Dumazet 			skb_frag_size_sub(fragfrom, todo);
3546832d11c5SIlpo Järvinen 			todo = 0;
3547832d11c5SIlpo Järvinen 
3548832d11c5SIlpo Järvinen 			to++;
3549832d11c5SIlpo Järvinen 			break;
3550832d11c5SIlpo Järvinen 		}
3551832d11c5SIlpo Järvinen 	}
3552832d11c5SIlpo Järvinen 
3553832d11c5SIlpo Järvinen 	/* Ready to "commit" this state change to tgt */
3554832d11c5SIlpo Järvinen 	skb_shinfo(tgt)->nr_frags = to;
3555832d11c5SIlpo Järvinen 
3556832d11c5SIlpo Järvinen 	if (merge >= 0) {
3557832d11c5SIlpo Järvinen 		fragfrom = &skb_shinfo(skb)->frags[0];
3558832d11c5SIlpo Järvinen 		fragto = &skb_shinfo(tgt)->frags[merge];
3559832d11c5SIlpo Järvinen 
35609e903e08SEric Dumazet 		skb_frag_size_add(fragto, skb_frag_size(fragfrom));
35616a5bcd84SIlias Apalodimas 		__skb_frag_unref(fragfrom, skb->pp_recycle);
3562832d11c5SIlpo Järvinen 	}
3563832d11c5SIlpo Järvinen 
3564832d11c5SIlpo Järvinen 	/* Reposition in the original skb */
3565832d11c5SIlpo Järvinen 	to = 0;
3566832d11c5SIlpo Järvinen 	while (from < skb_shinfo(skb)->nr_frags)
3567832d11c5SIlpo Järvinen 		skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3568832d11c5SIlpo Järvinen 	skb_shinfo(skb)->nr_frags = to;
3569832d11c5SIlpo Järvinen 
3570832d11c5SIlpo Järvinen 	BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3571832d11c5SIlpo Järvinen 
3572832d11c5SIlpo Järvinen onlymerged:
3573832d11c5SIlpo Järvinen 	/* Most likely the tgt won't ever need its checksum anymore, skb on
3574832d11c5SIlpo Järvinen 	 * the other hand might need it if it needs to be resent
3575832d11c5SIlpo Järvinen 	 */
3576832d11c5SIlpo Järvinen 	tgt->ip_summed = CHECKSUM_PARTIAL;
3577832d11c5SIlpo Järvinen 	skb->ip_summed = CHECKSUM_PARTIAL;
3578832d11c5SIlpo Järvinen 
3579832d11c5SIlpo Järvinen 	/* Yak, is it really working this way? Some helper please? */
3580832d11c5SIlpo Järvinen 	skb->len -= shiftlen;
3581832d11c5SIlpo Järvinen 	skb->data_len -= shiftlen;
3582832d11c5SIlpo Järvinen 	skb->truesize -= shiftlen;
3583832d11c5SIlpo Järvinen 	tgt->len += shiftlen;
3584832d11c5SIlpo Järvinen 	tgt->data_len += shiftlen;
3585832d11c5SIlpo Järvinen 	tgt->truesize += shiftlen;
3586832d11c5SIlpo Järvinen 
3587832d11c5SIlpo Järvinen 	return shiftlen;
3588832d11c5SIlpo Järvinen }
3589832d11c5SIlpo Järvinen 
3590677e90edSThomas Graf /**
3591677e90edSThomas Graf  * skb_prepare_seq_read - Prepare a sequential read of skb data
3592677e90edSThomas Graf  * @skb: the buffer to read
3593677e90edSThomas Graf  * @from: lower offset of data to be read
3594677e90edSThomas Graf  * @to: upper offset of data to be read
3595677e90edSThomas Graf  * @st: state variable
3596677e90edSThomas Graf  *
3597677e90edSThomas Graf  * Initializes the specified state variable. Must be called before
3598677e90edSThomas Graf  * invoking skb_seq_read() for the first time.
3599677e90edSThomas Graf  */
3600677e90edSThomas Graf void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3601677e90edSThomas Graf 			  unsigned int to, struct skb_seq_state *st)
3602677e90edSThomas Graf {
3603677e90edSThomas Graf 	st->lower_offset = from;
3604677e90edSThomas Graf 	st->upper_offset = to;
3605677e90edSThomas Graf 	st->root_skb = st->cur_skb = skb;
3606677e90edSThomas Graf 	st->frag_idx = st->stepped_offset = 0;
3607677e90edSThomas Graf 	st->frag_data = NULL;
360897550f6fSWillem de Bruijn 	st->frag_off = 0;
3609677e90edSThomas Graf }
3610b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_prepare_seq_read);
3611677e90edSThomas Graf 
3612677e90edSThomas Graf /**
3613677e90edSThomas Graf  * skb_seq_read - Sequentially read skb data
3614677e90edSThomas Graf  * @consumed: number of bytes consumed by the caller so far
3615677e90edSThomas Graf  * @data: destination pointer for data to be returned
3616677e90edSThomas Graf  * @st: state variable
3617677e90edSThomas Graf  *
3618bc32383cSMathias Krause  * Reads a block of skb data at @consumed relative to the
3619677e90edSThomas Graf  * lower offset specified to skb_prepare_seq_read(). Assigns
3620bc32383cSMathias Krause  * the head of the data block to @data and returns the length
3621677e90edSThomas Graf  * of the block or 0 if the end of the skb data or the upper
3622677e90edSThomas Graf  * offset has been reached.
3623677e90edSThomas Graf  *
3624677e90edSThomas Graf  * The caller is not required to consume all of the data
3625bc32383cSMathias Krause  * returned, i.e. @consumed is typically set to the number
3626677e90edSThomas Graf  * of bytes already consumed and the next call to
3627677e90edSThomas Graf  * skb_seq_read() will return the remaining part of the block.
3628677e90edSThomas Graf  *
362925985edcSLucas De Marchi  * Note 1: The size of each block of data returned can be arbitrary,
3630e793c0f7SMasanari Iida  *       this limitation is the cost for zerocopy sequential
3631677e90edSThomas Graf  *       reads of potentially non linear data.
3632677e90edSThomas Graf  *
3633bc2cda1eSRandy Dunlap  * Note 2: Fragment lists within fragments are not implemented
3634677e90edSThomas Graf  *       at the moment, state->root_skb could be replaced with
3635677e90edSThomas Graf  *       a stack for this purpose.
3636677e90edSThomas Graf  */
3637677e90edSThomas Graf unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3638677e90edSThomas Graf 			  struct skb_seq_state *st)
3639677e90edSThomas Graf {
3640677e90edSThomas Graf 	unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3641677e90edSThomas Graf 	skb_frag_t *frag;
3642677e90edSThomas Graf 
3643aeb193eaSWedson Almeida Filho 	if (unlikely(abs_offset >= st->upper_offset)) {
3644aeb193eaSWedson Almeida Filho 		if (st->frag_data) {
3645aeb193eaSWedson Almeida Filho 			kunmap_atomic(st->frag_data);
3646aeb193eaSWedson Almeida Filho 			st->frag_data = NULL;
3647aeb193eaSWedson Almeida Filho 		}
3648677e90edSThomas Graf 		return 0;
3649aeb193eaSWedson Almeida Filho 	}
3650677e90edSThomas Graf 
3651677e90edSThomas Graf next_skb:
365295e3b24cSHerbert Xu 	block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3653677e90edSThomas Graf 
3654995b3379SThomas Chenault 	if (abs_offset < block_limit && !st->frag_data) {
365595e3b24cSHerbert Xu 		*data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3656677e90edSThomas Graf 		return block_limit - abs_offset;
3657677e90edSThomas Graf 	}
3658677e90edSThomas Graf 
3659677e90edSThomas Graf 	if (st->frag_idx == 0 && !st->frag_data)
3660677e90edSThomas Graf 		st->stepped_offset += skb_headlen(st->cur_skb);
3661677e90edSThomas Graf 
3662677e90edSThomas Graf 	while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
366397550f6fSWillem de Bruijn 		unsigned int pg_idx, pg_off, pg_sz;
3664677e90edSThomas Graf 
366597550f6fSWillem de Bruijn 		frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
366697550f6fSWillem de Bruijn 
366797550f6fSWillem de Bruijn 		pg_idx = 0;
366897550f6fSWillem de Bruijn 		pg_off = skb_frag_off(frag);
366997550f6fSWillem de Bruijn 		pg_sz = skb_frag_size(frag);
367097550f6fSWillem de Bruijn 
367197550f6fSWillem de Bruijn 		if (skb_frag_must_loop(skb_frag_page(frag))) {
367297550f6fSWillem de Bruijn 			pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
367397550f6fSWillem de Bruijn 			pg_off = offset_in_page(pg_off + st->frag_off);
367497550f6fSWillem de Bruijn 			pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
367597550f6fSWillem de Bruijn 						    PAGE_SIZE - pg_off);
367697550f6fSWillem de Bruijn 		}
367797550f6fSWillem de Bruijn 
367897550f6fSWillem de Bruijn 		block_limit = pg_sz + st->stepped_offset;
3679677e90edSThomas Graf 		if (abs_offset < block_limit) {
3680677e90edSThomas Graf 			if (!st->frag_data)
368197550f6fSWillem de Bruijn 				st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3682677e90edSThomas Graf 
368397550f6fSWillem de Bruijn 			*data = (u8 *)st->frag_data + pg_off +
3684677e90edSThomas Graf 				(abs_offset - st->stepped_offset);
3685677e90edSThomas Graf 
3686677e90edSThomas Graf 			return block_limit - abs_offset;
3687677e90edSThomas Graf 		}
3688677e90edSThomas Graf 
3689677e90edSThomas Graf 		if (st->frag_data) {
369051c56b00SEric Dumazet 			kunmap_atomic(st->frag_data);
3691677e90edSThomas Graf 			st->frag_data = NULL;
3692677e90edSThomas Graf 		}
3693677e90edSThomas Graf 
369497550f6fSWillem de Bruijn 		st->stepped_offset += pg_sz;
369597550f6fSWillem de Bruijn 		st->frag_off += pg_sz;
369697550f6fSWillem de Bruijn 		if (st->frag_off == skb_frag_size(frag)) {
369797550f6fSWillem de Bruijn 			st->frag_off = 0;
3698677e90edSThomas Graf 			st->frag_idx++;
369997550f6fSWillem de Bruijn 		}
3700677e90edSThomas Graf 	}
3701677e90edSThomas Graf 
37025b5a60daSOlaf Kirch 	if (st->frag_data) {
370351c56b00SEric Dumazet 		kunmap_atomic(st->frag_data);
37045b5a60daSOlaf Kirch 		st->frag_data = NULL;
37055b5a60daSOlaf Kirch 	}
37065b5a60daSOlaf Kirch 
370721dc3301SDavid S. Miller 	if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3708677e90edSThomas Graf 		st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
370995e3b24cSHerbert Xu 		st->frag_idx = 0;
3710677e90edSThomas Graf 		goto next_skb;
371171b3346dSShyam Iyer 	} else if (st->cur_skb->next) {
371271b3346dSShyam Iyer 		st->cur_skb = st->cur_skb->next;
371371b3346dSShyam Iyer 		st->frag_idx = 0;
3714677e90edSThomas Graf 		goto next_skb;
3715677e90edSThomas Graf 	}
3716677e90edSThomas Graf 
3717677e90edSThomas Graf 	return 0;
3718677e90edSThomas Graf }
3719b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_seq_read);
3720677e90edSThomas Graf 
3721677e90edSThomas Graf /**
3722677e90edSThomas Graf  * skb_abort_seq_read - Abort a sequential read of skb data
3723677e90edSThomas Graf  * @st: state variable
3724677e90edSThomas Graf  *
3725677e90edSThomas Graf  * Must be called if skb_seq_read() was not called until it
3726677e90edSThomas Graf  * returned 0.
3727677e90edSThomas Graf  */
3728677e90edSThomas Graf void skb_abort_seq_read(struct skb_seq_state *st)
3729677e90edSThomas Graf {
3730677e90edSThomas Graf 	if (st->frag_data)
373151c56b00SEric Dumazet 		kunmap_atomic(st->frag_data);
3732677e90edSThomas Graf }
3733b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_abort_seq_read);
3734677e90edSThomas Graf 
37353fc7e8a6SThomas Graf #define TS_SKB_CB(state)	((struct skb_seq_state *) &((state)->cb))
37363fc7e8a6SThomas Graf 
37373fc7e8a6SThomas Graf static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
37383fc7e8a6SThomas Graf 					  struct ts_config *conf,
37393fc7e8a6SThomas Graf 					  struct ts_state *state)
37403fc7e8a6SThomas Graf {
37413fc7e8a6SThomas Graf 	return skb_seq_read(offset, text, TS_SKB_CB(state));
37423fc7e8a6SThomas Graf }
37433fc7e8a6SThomas Graf 
37443fc7e8a6SThomas Graf static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
37453fc7e8a6SThomas Graf {
37463fc7e8a6SThomas Graf 	skb_abort_seq_read(TS_SKB_CB(state));
37473fc7e8a6SThomas Graf }
37483fc7e8a6SThomas Graf 
37493fc7e8a6SThomas Graf /**
37503fc7e8a6SThomas Graf  * skb_find_text - Find a text pattern in skb data
37513fc7e8a6SThomas Graf  * @skb: the buffer to look in
37523fc7e8a6SThomas Graf  * @from: search offset
37533fc7e8a6SThomas Graf  * @to: search limit
37543fc7e8a6SThomas Graf  * @config: textsearch configuration
37553fc7e8a6SThomas Graf  *
37563fc7e8a6SThomas Graf  * Finds a pattern in the skb data according to the specified
37573fc7e8a6SThomas Graf  * textsearch configuration. Use textsearch_next() to retrieve
37583fc7e8a6SThomas Graf  * subsequent occurrences of the pattern. Returns the offset
37593fc7e8a6SThomas Graf  * to the first occurrence or UINT_MAX if no match was found.
37603fc7e8a6SThomas Graf  */
37613fc7e8a6SThomas Graf unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3762059a2440SBojan Prtvar 			   unsigned int to, struct ts_config *config)
37633fc7e8a6SThomas Graf {
3764059a2440SBojan Prtvar 	struct ts_state state;
3765f72b948dSPhil Oester 	unsigned int ret;
3766f72b948dSPhil Oester 
3767b228c9b0SWillem de Bruijn 	BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3768b228c9b0SWillem de Bruijn 
37693fc7e8a6SThomas Graf 	config->get_next_block = skb_ts_get_next_block;
37703fc7e8a6SThomas Graf 	config->finish = skb_ts_finish;
37713fc7e8a6SThomas Graf 
3772059a2440SBojan Prtvar 	skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
37733fc7e8a6SThomas Graf 
3774059a2440SBojan Prtvar 	ret = textsearch_find(config, &state);
3775f72b948dSPhil Oester 	return (ret <= to - from ? ret : UINT_MAX);
37763fc7e8a6SThomas Graf }
3777b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_find_text);
37783fc7e8a6SThomas Graf 
3779be12a1feSHannes Frederic Sowa int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3780be12a1feSHannes Frederic Sowa 			 int offset, size_t size)
3781be12a1feSHannes Frederic Sowa {
3782be12a1feSHannes Frederic Sowa 	int i = skb_shinfo(skb)->nr_frags;
3783be12a1feSHannes Frederic Sowa 
3784be12a1feSHannes Frederic Sowa 	if (skb_can_coalesce(skb, i, page, offset)) {
3785be12a1feSHannes Frederic Sowa 		skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3786be12a1feSHannes Frederic Sowa 	} else if (i < MAX_SKB_FRAGS) {
3787be12a1feSHannes Frederic Sowa 		get_page(page);
3788be12a1feSHannes Frederic Sowa 		skb_fill_page_desc(skb, i, page, offset, size);
3789be12a1feSHannes Frederic Sowa 	} else {
3790be12a1feSHannes Frederic Sowa 		return -EMSGSIZE;
3791be12a1feSHannes Frederic Sowa 	}
3792be12a1feSHannes Frederic Sowa 
3793be12a1feSHannes Frederic Sowa 	return 0;
3794be12a1feSHannes Frederic Sowa }
3795be12a1feSHannes Frederic Sowa EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3796be12a1feSHannes Frederic Sowa 
3797cbb042f9SHerbert Xu /**
3798cbb042f9SHerbert Xu  *	skb_pull_rcsum - pull skb and update receive checksum
3799cbb042f9SHerbert Xu  *	@skb: buffer to update
3800cbb042f9SHerbert Xu  *	@len: length of data pulled
3801cbb042f9SHerbert Xu  *
3802cbb042f9SHerbert Xu  *	This function performs an skb_pull on the packet and updates
3803fee54fa5SUrs Thuermann  *	the CHECKSUM_COMPLETE checksum.  It should be used on
380484fa7933SPatrick McHardy  *	receive path processing instead of skb_pull unless you know
380584fa7933SPatrick McHardy  *	that the checksum difference is zero (e.g., a valid IP header)
380684fa7933SPatrick McHardy  *	or you are setting ip_summed to CHECKSUM_NONE.
3807cbb042f9SHerbert Xu  */
3808af72868bSJohannes Berg void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3809cbb042f9SHerbert Xu {
381031b33dfbSPravin B Shelar 	unsigned char *data = skb->data;
381131b33dfbSPravin B Shelar 
3812cbb042f9SHerbert Xu 	BUG_ON(len > skb->len);
381331b33dfbSPravin B Shelar 	__skb_pull(skb, len);
381431b33dfbSPravin B Shelar 	skb_postpull_rcsum(skb, data, len);
381531b33dfbSPravin B Shelar 	return skb->data;
3816cbb042f9SHerbert Xu }
3817f94691acSArnaldo Carvalho de Melo EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3818f94691acSArnaldo Carvalho de Melo 
381913acc94eSYonghong Song static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
382013acc94eSYonghong Song {
382113acc94eSYonghong Song 	skb_frag_t head_frag;
382213acc94eSYonghong Song 	struct page *page;
382313acc94eSYonghong Song 
382413acc94eSYonghong Song 	page = virt_to_head_page(frag_skb->head);
3825d8e18a51SMatthew Wilcox (Oracle) 	__skb_frag_set_page(&head_frag, page);
3826b54c9d5bSJonathan Lemon 	skb_frag_off_set(&head_frag, frag_skb->data -
3827b54c9d5bSJonathan Lemon 			 (unsigned char *)page_address(page));
3828d8e18a51SMatthew Wilcox (Oracle) 	skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
382913acc94eSYonghong Song 	return head_frag;
383013acc94eSYonghong Song }
383113acc94eSYonghong Song 
38323a1296a3SSteffen Klassert struct sk_buff *skb_segment_list(struct sk_buff *skb,
38333a1296a3SSteffen Klassert 				 netdev_features_t features,
38343a1296a3SSteffen Klassert 				 unsigned int offset)
38353a1296a3SSteffen Klassert {
38363a1296a3SSteffen Klassert 	struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
38373a1296a3SSteffen Klassert 	unsigned int tnl_hlen = skb_tnl_header_len(skb);
38383a1296a3SSteffen Klassert 	unsigned int delta_truesize = 0;
38393a1296a3SSteffen Klassert 	unsigned int delta_len = 0;
38403a1296a3SSteffen Klassert 	struct sk_buff *tail = NULL;
384153475c5dSDongseok Yi 	struct sk_buff *nskb, *tmp;
384253475c5dSDongseok Yi 	int err;
38433a1296a3SSteffen Klassert 
38443a1296a3SSteffen Klassert 	skb_push(skb, -skb_network_offset(skb) + offset);
38453a1296a3SSteffen Klassert 
38463a1296a3SSteffen Klassert 	skb_shinfo(skb)->frag_list = NULL;
38473a1296a3SSteffen Klassert 
38483a1296a3SSteffen Klassert 	do {
38493a1296a3SSteffen Klassert 		nskb = list_skb;
38503a1296a3SSteffen Klassert 		list_skb = list_skb->next;
38513a1296a3SSteffen Klassert 
385253475c5dSDongseok Yi 		err = 0;
385353475c5dSDongseok Yi 		if (skb_shared(nskb)) {
385453475c5dSDongseok Yi 			tmp = skb_clone(nskb, GFP_ATOMIC);
385553475c5dSDongseok Yi 			if (tmp) {
385653475c5dSDongseok Yi 				consume_skb(nskb);
385753475c5dSDongseok Yi 				nskb = tmp;
385853475c5dSDongseok Yi 				err = skb_unclone(nskb, GFP_ATOMIC);
385953475c5dSDongseok Yi 			} else {
386053475c5dSDongseok Yi 				err = -ENOMEM;
386153475c5dSDongseok Yi 			}
386253475c5dSDongseok Yi 		}
386353475c5dSDongseok Yi 
38643a1296a3SSteffen Klassert 		if (!tail)
38653a1296a3SSteffen Klassert 			skb->next = nskb;
38663a1296a3SSteffen Klassert 		else
38673a1296a3SSteffen Klassert 			tail->next = nskb;
38683a1296a3SSteffen Klassert 
386953475c5dSDongseok Yi 		if (unlikely(err)) {
387053475c5dSDongseok Yi 			nskb->next = list_skb;
387153475c5dSDongseok Yi 			goto err_linearize;
387253475c5dSDongseok Yi 		}
387353475c5dSDongseok Yi 
38743a1296a3SSteffen Klassert 		tail = nskb;
38753a1296a3SSteffen Klassert 
38763a1296a3SSteffen Klassert 		delta_len += nskb->len;
38773a1296a3SSteffen Klassert 		delta_truesize += nskb->truesize;
38783a1296a3SSteffen Klassert 
38793a1296a3SSteffen Klassert 		skb_push(nskb, -skb_network_offset(nskb) + offset);
38803a1296a3SSteffen Klassert 
3881cf673ed0SFlorian Westphal 		skb_release_head_state(nskb);
38823a1296a3SSteffen Klassert 		__copy_skb_header(nskb, skb);
38833a1296a3SSteffen Klassert 
38843a1296a3SSteffen Klassert 		skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
38853a1296a3SSteffen Klassert 		skb_copy_from_linear_data_offset(skb, -tnl_hlen,
38863a1296a3SSteffen Klassert 						 nskb->data - tnl_hlen,
38873a1296a3SSteffen Klassert 						 offset + tnl_hlen);
38883a1296a3SSteffen Klassert 
38893a1296a3SSteffen Klassert 		if (skb_needs_linearize(nskb, features) &&
38903a1296a3SSteffen Klassert 		    __skb_linearize(nskb))
38913a1296a3SSteffen Klassert 			goto err_linearize;
38923a1296a3SSteffen Klassert 
38933a1296a3SSteffen Klassert 	} while (list_skb);
38943a1296a3SSteffen Klassert 
38953a1296a3SSteffen Klassert 	skb->truesize = skb->truesize - delta_truesize;
38963a1296a3SSteffen Klassert 	skb->data_len = skb->data_len - delta_len;
38973a1296a3SSteffen Klassert 	skb->len = skb->len - delta_len;
38983a1296a3SSteffen Klassert 
38993a1296a3SSteffen Klassert 	skb_gso_reset(skb);
39003a1296a3SSteffen Klassert 
39013a1296a3SSteffen Klassert 	skb->prev = tail;
39023a1296a3SSteffen Klassert 
39033a1296a3SSteffen Klassert 	if (skb_needs_linearize(skb, features) &&
39043a1296a3SSteffen Klassert 	    __skb_linearize(skb))
39053a1296a3SSteffen Klassert 		goto err_linearize;
39063a1296a3SSteffen Klassert 
39073a1296a3SSteffen Klassert 	skb_get(skb);
39083a1296a3SSteffen Klassert 
39093a1296a3SSteffen Klassert 	return skb;
39103a1296a3SSteffen Klassert 
39113a1296a3SSteffen Klassert err_linearize:
39123a1296a3SSteffen Klassert 	kfree_skb_list(skb->next);
39133a1296a3SSteffen Klassert 	skb->next = NULL;
39143a1296a3SSteffen Klassert 	return ERR_PTR(-ENOMEM);
39153a1296a3SSteffen Klassert }
39163a1296a3SSteffen Klassert EXPORT_SYMBOL_GPL(skb_segment_list);
39173a1296a3SSteffen Klassert 
3918f4c50d99SHerbert Xu /**
3919f4c50d99SHerbert Xu  *	skb_segment - Perform protocol segmentation on skb.
3920df5771ffSMichael S. Tsirkin  *	@head_skb: buffer to segment
3921576a30ebSHerbert Xu  *	@features: features for the output path (see dev->features)
3922f4c50d99SHerbert Xu  *
3923f4c50d99SHerbert Xu  *	This function performs segmentation on the given skb.  It returns
39244c821d75SBen Hutchings  *	a pointer to the first in a list of new skbs for the segments.
39254c821d75SBen Hutchings  *	In case of error it returns ERR_PTR(err).
3926f4c50d99SHerbert Xu  */
3927df5771ffSMichael S. Tsirkin struct sk_buff *skb_segment(struct sk_buff *head_skb,
3928df5771ffSMichael S. Tsirkin 			    netdev_features_t features)
3929f4c50d99SHerbert Xu {
3930f4c50d99SHerbert Xu 	struct sk_buff *segs = NULL;
3931f4c50d99SHerbert Xu 	struct sk_buff *tail = NULL;
39321a4cedafSMichael S. Tsirkin 	struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
3933df5771ffSMichael S. Tsirkin 	skb_frag_t *frag = skb_shinfo(head_skb)->frags;
3934df5771ffSMichael S. Tsirkin 	unsigned int mss = skb_shinfo(head_skb)->gso_size;
3935df5771ffSMichael S. Tsirkin 	unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
39361fd819ecSMichael S. Tsirkin 	struct sk_buff *frag_skb = head_skb;
3937f4c50d99SHerbert Xu 	unsigned int offset = doffset;
3938df5771ffSMichael S. Tsirkin 	unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
3939802ab55aSAlexander Duyck 	unsigned int partial_segs = 0;
3940f4c50d99SHerbert Xu 	unsigned int headroom;
3941802ab55aSAlexander Duyck 	unsigned int len = head_skb->len;
3942ec5f0615SPravin B Shelar 	__be16 proto;
394336c98382SAlexander Duyck 	bool csum, sg;
3944df5771ffSMichael S. Tsirkin 	int nfrags = skb_shinfo(head_skb)->nr_frags;
3945f4c50d99SHerbert Xu 	int err = -ENOMEM;
3946f4c50d99SHerbert Xu 	int i = 0;
3947f4c50d99SHerbert Xu 	int pos;
3948f4c50d99SHerbert Xu 
39493dcbdb13SShmulik Ladkani 	if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
39503dcbdb13SShmulik Ladkani 	    (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
39513dcbdb13SShmulik Ladkani 		/* gso_size is untrusted, and we have a frag_list with a linear
39523dcbdb13SShmulik Ladkani 		 * non head_frag head.
39533dcbdb13SShmulik Ladkani 		 *
39543dcbdb13SShmulik Ladkani 		 * (we assume checking the first list_skb member suffices;
39553dcbdb13SShmulik Ladkani 		 * i.e if either of the list_skb members have non head_frag
39563dcbdb13SShmulik Ladkani 		 * head, then the first one has too).
39573dcbdb13SShmulik Ladkani 		 *
39583dcbdb13SShmulik Ladkani 		 * If head_skb's headlen does not fit requested gso_size, it
39593dcbdb13SShmulik Ladkani 		 * means that the frag_list members do NOT terminate on exact
39603dcbdb13SShmulik Ladkani 		 * gso_size boundaries. Hence we cannot perform skb_frag_t page
39613dcbdb13SShmulik Ladkani 		 * sharing. Therefore we must fallback to copying the frag_list
39623dcbdb13SShmulik Ladkani 		 * skbs; we do so by disabling SG.
39633dcbdb13SShmulik Ladkani 		 */
39643dcbdb13SShmulik Ladkani 		if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
39653dcbdb13SShmulik Ladkani 			features &= ~NETIF_F_SG;
39663dcbdb13SShmulik Ladkani 	}
39673dcbdb13SShmulik Ladkani 
39685882a07cSWei-Chun Chao 	__skb_push(head_skb, doffset);
39692f631133SMiaohe Lin 	proto = skb_network_protocol(head_skb, NULL);
3970ec5f0615SPravin B Shelar 	if (unlikely(!proto))
3971ec5f0615SPravin B Shelar 		return ERR_PTR(-EINVAL);
3972ec5f0615SPravin B Shelar 
397336c98382SAlexander Duyck 	sg = !!(features & NETIF_F_SG);
3974f245d079SAlexander Duyck 	csum = !!can_checksum_protocol(features, proto);
39757e2b10c1STom Herbert 
397607b26c94SSteffen Klassert 	if (sg && csum && (mss != GSO_BY_FRAGS))  {
397707b26c94SSteffen Klassert 		if (!(features & NETIF_F_GSO_PARTIAL)) {
397807b26c94SSteffen Klassert 			struct sk_buff *iter;
397943170c4eSIlan Tayari 			unsigned int frag_len;
398007b26c94SSteffen Klassert 
398107b26c94SSteffen Klassert 			if (!list_skb ||
398207b26c94SSteffen Klassert 			    !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
398307b26c94SSteffen Klassert 				goto normal;
398407b26c94SSteffen Klassert 
398543170c4eSIlan Tayari 			/* If we get here then all the required
398643170c4eSIlan Tayari 			 * GSO features except frag_list are supported.
398743170c4eSIlan Tayari 			 * Try to split the SKB to multiple GSO SKBs
398843170c4eSIlan Tayari 			 * with no frag_list.
398943170c4eSIlan Tayari 			 * Currently we can do that only when the buffers don't
399043170c4eSIlan Tayari 			 * have a linear part and all the buffers except
399143170c4eSIlan Tayari 			 * the last are of the same length.
399207b26c94SSteffen Klassert 			 */
399343170c4eSIlan Tayari 			frag_len = list_skb->len;
399407b26c94SSteffen Klassert 			skb_walk_frags(head_skb, iter) {
399543170c4eSIlan Tayari 				if (frag_len != iter->len && iter->next)
399643170c4eSIlan Tayari 					goto normal;
3997eaffadbbSIlan Tayari 				if (skb_headlen(iter) && !iter->head_frag)
399807b26c94SSteffen Klassert 					goto normal;
399907b26c94SSteffen Klassert 
400007b26c94SSteffen Klassert 				len -= iter->len;
400107b26c94SSteffen Klassert 			}
400243170c4eSIlan Tayari 
400343170c4eSIlan Tayari 			if (len != frag_len)
400443170c4eSIlan Tayari 				goto normal;
400507b26c94SSteffen Klassert 		}
400607b26c94SSteffen Klassert 
4007802ab55aSAlexander Duyck 		/* GSO partial only requires that we trim off any excess that
4008802ab55aSAlexander Duyck 		 * doesn't fit into an MSS sized block, so take care of that
4009802ab55aSAlexander Duyck 		 * now.
4010802ab55aSAlexander Duyck 		 */
4011802ab55aSAlexander Duyck 		partial_segs = len / mss;
4012d7fb5a80SAlexander Duyck 		if (partial_segs > 1)
4013802ab55aSAlexander Duyck 			mss *= partial_segs;
4014d7fb5a80SAlexander Duyck 		else
4015d7fb5a80SAlexander Duyck 			partial_segs = 0;
4016802ab55aSAlexander Duyck 	}
4017802ab55aSAlexander Duyck 
401807b26c94SSteffen Klassert normal:
4019df5771ffSMichael S. Tsirkin 	headroom = skb_headroom(head_skb);
4020df5771ffSMichael S. Tsirkin 	pos = skb_headlen(head_skb);
4021f4c50d99SHerbert Xu 
4022f4c50d99SHerbert Xu 	do {
4023f4c50d99SHerbert Xu 		struct sk_buff *nskb;
40248cb19905SMichael S. Tsirkin 		skb_frag_t *nskb_frag;
4025c8884eddSHerbert Xu 		int hsize;
4026f4c50d99SHerbert Xu 		int size;
4027f4c50d99SHerbert Xu 
40283953c46cSMarcelo Ricardo Leitner 		if (unlikely(mss == GSO_BY_FRAGS)) {
40293953c46cSMarcelo Ricardo Leitner 			len = list_skb->len;
40303953c46cSMarcelo Ricardo Leitner 		} else {
4031df5771ffSMichael S. Tsirkin 			len = head_skb->len - offset;
4032f4c50d99SHerbert Xu 			if (len > mss)
4033f4c50d99SHerbert Xu 				len = mss;
40343953c46cSMarcelo Ricardo Leitner 		}
4035f4c50d99SHerbert Xu 
4036df5771ffSMichael S. Tsirkin 		hsize = skb_headlen(head_skb) - offset;
4037f4c50d99SHerbert Xu 
4038dbd50f23SXin Long 		if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
40391a4cedafSMichael S. Tsirkin 		    (skb_headlen(list_skb) == len || sg)) {
40401a4cedafSMichael S. Tsirkin 			BUG_ON(skb_headlen(list_skb) > len);
404189319d38SHerbert Xu 
40429d8506ccSHerbert Xu 			i = 0;
40431a4cedafSMichael S. Tsirkin 			nfrags = skb_shinfo(list_skb)->nr_frags;
40441a4cedafSMichael S. Tsirkin 			frag = skb_shinfo(list_skb)->frags;
40451fd819ecSMichael S. Tsirkin 			frag_skb = list_skb;
40461a4cedafSMichael S. Tsirkin 			pos += skb_headlen(list_skb);
40479d8506ccSHerbert Xu 
40489d8506ccSHerbert Xu 			while (pos < offset + len) {
40499d8506ccSHerbert Xu 				BUG_ON(i >= nfrags);
40509d8506ccSHerbert Xu 
40514e1beba1SMichael S. Tsirkin 				size = skb_frag_size(frag);
40529d8506ccSHerbert Xu 				if (pos + size > offset + len)
40539d8506ccSHerbert Xu 					break;
40549d8506ccSHerbert Xu 
40559d8506ccSHerbert Xu 				i++;
40569d8506ccSHerbert Xu 				pos += size;
40574e1beba1SMichael S. Tsirkin 				frag++;
40589d8506ccSHerbert Xu 			}
40599d8506ccSHerbert Xu 
40601a4cedafSMichael S. Tsirkin 			nskb = skb_clone(list_skb, GFP_ATOMIC);
40611a4cedafSMichael S. Tsirkin 			list_skb = list_skb->next;
406289319d38SHerbert Xu 
4063f4c50d99SHerbert Xu 			if (unlikely(!nskb))
4064f4c50d99SHerbert Xu 				goto err;
4065f4c50d99SHerbert Xu 
40669d8506ccSHerbert Xu 			if (unlikely(pskb_trim(nskb, len))) {
40679d8506ccSHerbert Xu 				kfree_skb(nskb);
40689d8506ccSHerbert Xu 				goto err;
40699d8506ccSHerbert Xu 			}
40709d8506ccSHerbert Xu 
4071ec47ea82SAlexander Duyck 			hsize = skb_end_offset(nskb);
407289319d38SHerbert Xu 			if (skb_cow_head(nskb, doffset + headroom)) {
407389319d38SHerbert Xu 				kfree_skb(nskb);
407489319d38SHerbert Xu 				goto err;
407589319d38SHerbert Xu 			}
407689319d38SHerbert Xu 
4077ec47ea82SAlexander Duyck 			nskb->truesize += skb_end_offset(nskb) - hsize;
407889319d38SHerbert Xu 			skb_release_head_state(nskb);
407989319d38SHerbert Xu 			__skb_push(nskb, doffset);
408089319d38SHerbert Xu 		} else {
408100b229f7SPaolo Abeni 			if (hsize < 0)
408200b229f7SPaolo Abeni 				hsize = 0;
4083dbd50f23SXin Long 			if (hsize > len || !sg)
4084dbd50f23SXin Long 				hsize = len;
4085dbd50f23SXin Long 
4086c93bdd0eSMel Gorman 			nskb = __alloc_skb(hsize + doffset + headroom,
4087df5771ffSMichael S. Tsirkin 					   GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4088c93bdd0eSMel Gorman 					   NUMA_NO_NODE);
408989319d38SHerbert Xu 
409089319d38SHerbert Xu 			if (unlikely(!nskb))
409189319d38SHerbert Xu 				goto err;
409289319d38SHerbert Xu 
409389319d38SHerbert Xu 			skb_reserve(nskb, headroom);
409489319d38SHerbert Xu 			__skb_put(nskb, doffset);
409589319d38SHerbert Xu 		}
409689319d38SHerbert Xu 
4097f4c50d99SHerbert Xu 		if (segs)
4098f4c50d99SHerbert Xu 			tail->next = nskb;
4099f4c50d99SHerbert Xu 		else
4100f4c50d99SHerbert Xu 			segs = nskb;
4101f4c50d99SHerbert Xu 		tail = nskb;
4102f4c50d99SHerbert Xu 
4103df5771ffSMichael S. Tsirkin 		__copy_skb_header(nskb, head_skb);
4104f4c50d99SHerbert Xu 
4105030737bcSEric Dumazet 		skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4106fcdfe3a7SVlad Yasevich 		skb_reset_mac_len(nskb);
410768c33163SPravin B Shelar 
4108df5771ffSMichael S. Tsirkin 		skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
410968c33163SPravin B Shelar 						 nskb->data - tnl_hlen,
411068c33163SPravin B Shelar 						 doffset + tnl_hlen);
411189319d38SHerbert Xu 
41129d8506ccSHerbert Xu 		if (nskb->len == len + doffset)
41131cdbcb79SSimon Horman 			goto perform_csum_check;
411489319d38SHerbert Xu 
41157fbeffedSAlexander Duyck 		if (!sg) {
41161454c9faSYadu Kishore 			if (!csum) {
41177fbeffedSAlexander Duyck 				if (!nskb->remcsum_offload)
41186f85a124SHerbert Xu 					nskb->ip_summed = CHECKSUM_NONE;
411976443456SAlexander Duyck 				SKB_GSO_CB(nskb)->csum =
412076443456SAlexander Duyck 					skb_copy_and_csum_bits(head_skb, offset,
41211454c9faSYadu Kishore 							       skb_put(nskb,
41221454c9faSYadu Kishore 								       len),
41238d5930dfSAl Viro 							       len);
41247e2b10c1STom Herbert 				SKB_GSO_CB(nskb)->csum_start =
4125de843723STom Herbert 					skb_headroom(nskb) + doffset;
41261454c9faSYadu Kishore 			} else {
41271454c9faSYadu Kishore 				skb_copy_bits(head_skb, offset,
41281454c9faSYadu Kishore 					      skb_put(nskb, len),
41291454c9faSYadu Kishore 					      len);
41301454c9faSYadu Kishore 			}
4131f4c50d99SHerbert Xu 			continue;
4132f4c50d99SHerbert Xu 		}
4133f4c50d99SHerbert Xu 
41348cb19905SMichael S. Tsirkin 		nskb_frag = skb_shinfo(nskb)->frags;
4135f4c50d99SHerbert Xu 
4136df5771ffSMichael S. Tsirkin 		skb_copy_from_linear_data_offset(head_skb, offset,
4137d626f62bSArnaldo Carvalho de Melo 						 skb_put(nskb, hsize), hsize);
4138f4c50d99SHerbert Xu 
413906b4feb3SJonathan Lemon 		skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
414006b4feb3SJonathan Lemon 					   SKBFL_SHARED_FRAG;
4141cef401deSEric Dumazet 
4142bf5c25d6SWillem de Bruijn 		if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4143bf5c25d6SWillem de Bruijn 		    skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4144bf5c25d6SWillem de Bruijn 			goto err;
4145bf5c25d6SWillem de Bruijn 
41469d8506ccSHerbert Xu 		while (pos < offset + len) {
41479d8506ccSHerbert Xu 			if (i >= nfrags) {
41489d8506ccSHerbert Xu 				i = 0;
41491a4cedafSMichael S. Tsirkin 				nfrags = skb_shinfo(list_skb)->nr_frags;
41501a4cedafSMichael S. Tsirkin 				frag = skb_shinfo(list_skb)->frags;
41511fd819ecSMichael S. Tsirkin 				frag_skb = list_skb;
415213acc94eSYonghong Song 				if (!skb_headlen(list_skb)) {
41539d8506ccSHerbert Xu 					BUG_ON(!nfrags);
415413acc94eSYonghong Song 				} else {
415513acc94eSYonghong Song 					BUG_ON(!list_skb->head_frag);
41569d8506ccSHerbert Xu 
415713acc94eSYonghong Song 					/* to make room for head_frag. */
415813acc94eSYonghong Song 					i--;
415913acc94eSYonghong Song 					frag--;
416013acc94eSYonghong Song 				}
4161bf5c25d6SWillem de Bruijn 				if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4162bf5c25d6SWillem de Bruijn 				    skb_zerocopy_clone(nskb, frag_skb,
4163bf5c25d6SWillem de Bruijn 						       GFP_ATOMIC))
4164bf5c25d6SWillem de Bruijn 					goto err;
4165bf5c25d6SWillem de Bruijn 
41661a4cedafSMichael S. Tsirkin 				list_skb = list_skb->next;
41679d8506ccSHerbert Xu 			}
41689d8506ccSHerbert Xu 
41699d8506ccSHerbert Xu 			if (unlikely(skb_shinfo(nskb)->nr_frags >=
41709d8506ccSHerbert Xu 				     MAX_SKB_FRAGS)) {
41719d8506ccSHerbert Xu 				net_warn_ratelimited(
41729d8506ccSHerbert Xu 					"skb_segment: too many frags: %u %u\n",
41739d8506ccSHerbert Xu 					pos, mss);
4174ff907a11SEric Dumazet 				err = -EINVAL;
41759d8506ccSHerbert Xu 				goto err;
41769d8506ccSHerbert Xu 			}
41779d8506ccSHerbert Xu 
417813acc94eSYonghong Song 			*nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
41798cb19905SMichael S. Tsirkin 			__skb_frag_ref(nskb_frag);
41808cb19905SMichael S. Tsirkin 			size = skb_frag_size(nskb_frag);
4181f4c50d99SHerbert Xu 
4182f4c50d99SHerbert Xu 			if (pos < offset) {
4183b54c9d5bSJonathan Lemon 				skb_frag_off_add(nskb_frag, offset - pos);
41848cb19905SMichael S. Tsirkin 				skb_frag_size_sub(nskb_frag, offset - pos);
4185f4c50d99SHerbert Xu 			}
4186f4c50d99SHerbert Xu 
418789319d38SHerbert Xu 			skb_shinfo(nskb)->nr_frags++;
4188f4c50d99SHerbert Xu 
4189f4c50d99SHerbert Xu 			if (pos + size <= offset + len) {
4190f4c50d99SHerbert Xu 				i++;
41914e1beba1SMichael S. Tsirkin 				frag++;
4192f4c50d99SHerbert Xu 				pos += size;
4193f4c50d99SHerbert Xu 			} else {
41948cb19905SMichael S. Tsirkin 				skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
419589319d38SHerbert Xu 				goto skip_fraglist;
4196f4c50d99SHerbert Xu 			}
4197f4c50d99SHerbert Xu 
41988cb19905SMichael S. Tsirkin 			nskb_frag++;
4199f4c50d99SHerbert Xu 		}
4200f4c50d99SHerbert Xu 
420189319d38SHerbert Xu skip_fraglist:
4202f4c50d99SHerbert Xu 		nskb->data_len = len - hsize;
4203f4c50d99SHerbert Xu 		nskb->len += nskb->data_len;
4204f4c50d99SHerbert Xu 		nskb->truesize += nskb->data_len;
4205ec5f0615SPravin B Shelar 
42061cdbcb79SSimon Horman perform_csum_check:
42077fbeffedSAlexander Duyck 		if (!csum) {
4208ff907a11SEric Dumazet 			if (skb_has_shared_frag(nskb) &&
4209ff907a11SEric Dumazet 			    __skb_linearize(nskb))
4210ddff00d4SAlexander Duyck 				goto err;
4211ff907a11SEric Dumazet 
42127fbeffedSAlexander Duyck 			if (!nskb->remcsum_offload)
4213ec5f0615SPravin B Shelar 				nskb->ip_summed = CHECKSUM_NONE;
421476443456SAlexander Duyck 			SKB_GSO_CB(nskb)->csum =
421576443456SAlexander Duyck 				skb_checksum(nskb, doffset,
421676443456SAlexander Duyck 					     nskb->len - doffset, 0);
42177e2b10c1STom Herbert 			SKB_GSO_CB(nskb)->csum_start =
42187e2b10c1STom Herbert 				skb_headroom(nskb) + doffset;
4219ec5f0615SPravin B Shelar 		}
4220df5771ffSMichael S. Tsirkin 	} while ((offset += len) < head_skb->len);
4221f4c50d99SHerbert Xu 
4222bec3cfdcSEric Dumazet 	/* Some callers want to get the end of the list.
4223bec3cfdcSEric Dumazet 	 * Put it in segs->prev to avoid walking the list.
4224bec3cfdcSEric Dumazet 	 * (see validate_xmit_skb_list() for example)
4225bec3cfdcSEric Dumazet 	 */
4226bec3cfdcSEric Dumazet 	segs->prev = tail;
4227432c856fSToshiaki Makita 
4228802ab55aSAlexander Duyck 	if (partial_segs) {
422907b26c94SSteffen Klassert 		struct sk_buff *iter;
4230802ab55aSAlexander Duyck 		int type = skb_shinfo(head_skb)->gso_type;
423107b26c94SSteffen Klassert 		unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4232802ab55aSAlexander Duyck 
4233802ab55aSAlexander Duyck 		/* Update type to add partial and then remove dodgy if set */
423407b26c94SSteffen Klassert 		type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4235802ab55aSAlexander Duyck 		type &= ~SKB_GSO_DODGY;
4236802ab55aSAlexander Duyck 
4237802ab55aSAlexander Duyck 		/* Update GSO info and prepare to start updating headers on
4238802ab55aSAlexander Duyck 		 * our way back down the stack of protocols.
4239802ab55aSAlexander Duyck 		 */
424007b26c94SSteffen Klassert 		for (iter = segs; iter; iter = iter->next) {
424107b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_size = gso_size;
424207b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_segs = partial_segs;
424307b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_type = type;
424407b26c94SSteffen Klassert 			SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
424507b26c94SSteffen Klassert 		}
424607b26c94SSteffen Klassert 
424707b26c94SSteffen Klassert 		if (tail->len - doffset <= gso_size)
424807b26c94SSteffen Klassert 			skb_shinfo(tail)->gso_size = 0;
424907b26c94SSteffen Klassert 		else if (tail != segs)
425007b26c94SSteffen Klassert 			skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4251802ab55aSAlexander Duyck 	}
4252802ab55aSAlexander Duyck 
4253432c856fSToshiaki Makita 	/* Following permits correct backpressure, for protocols
4254432c856fSToshiaki Makita 	 * using skb_set_owner_w().
4255432c856fSToshiaki Makita 	 * Idea is to tranfert ownership from head_skb to last segment.
4256432c856fSToshiaki Makita 	 */
4257432c856fSToshiaki Makita 	if (head_skb->destructor == sock_wfree) {
4258432c856fSToshiaki Makita 		swap(tail->truesize, head_skb->truesize);
4259432c856fSToshiaki Makita 		swap(tail->destructor, head_skb->destructor);
4260432c856fSToshiaki Makita 		swap(tail->sk, head_skb->sk);
4261432c856fSToshiaki Makita 	}
4262f4c50d99SHerbert Xu 	return segs;
4263f4c50d99SHerbert Xu 
4264f4c50d99SHerbert Xu err:
4265289dccbeSEric Dumazet 	kfree_skb_list(segs);
4266f4c50d99SHerbert Xu 	return ERR_PTR(err);
4267f4c50d99SHerbert Xu }
4268f4c50d99SHerbert Xu EXPORT_SYMBOL_GPL(skb_segment);
4269f4c50d99SHerbert Xu 
4270df5042f4SFlorian Westphal #ifdef CONFIG_SKB_EXTENSIONS
4271df5042f4SFlorian Westphal #define SKB_EXT_ALIGN_VALUE	8
4272df5042f4SFlorian Westphal #define SKB_EXT_CHUNKSIZEOF(x)	(ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4273df5042f4SFlorian Westphal 
4274df5042f4SFlorian Westphal static const u8 skb_ext_type_len[] = {
4275df5042f4SFlorian Westphal #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4276df5042f4SFlorian Westphal 	[SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4277df5042f4SFlorian Westphal #endif
42784165079bSFlorian Westphal #ifdef CONFIG_XFRM
42794165079bSFlorian Westphal 	[SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
42804165079bSFlorian Westphal #endif
428195a7233cSPaul Blakey #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
428295a7233cSPaul Blakey 	[TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
428395a7233cSPaul Blakey #endif
42843ee17bc7SMat Martineau #if IS_ENABLED(CONFIG_MPTCP)
42853ee17bc7SMat Martineau 	[SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
42863ee17bc7SMat Martineau #endif
428778476d31SJeremy Kerr #if IS_ENABLED(CONFIG_MCTP_FLOWS)
428878476d31SJeremy Kerr 	[SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
428978476d31SJeremy Kerr #endif
4290df5042f4SFlorian Westphal };
4291df5042f4SFlorian Westphal 
4292df5042f4SFlorian Westphal static __always_inline unsigned int skb_ext_total_length(void)
4293df5042f4SFlorian Westphal {
4294df5042f4SFlorian Westphal 	return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4295df5042f4SFlorian Westphal #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4296df5042f4SFlorian Westphal 		skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4297df5042f4SFlorian Westphal #endif
42984165079bSFlorian Westphal #ifdef CONFIG_XFRM
42994165079bSFlorian Westphal 		skb_ext_type_len[SKB_EXT_SEC_PATH] +
43004165079bSFlorian Westphal #endif
430195a7233cSPaul Blakey #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
430295a7233cSPaul Blakey 		skb_ext_type_len[TC_SKB_EXT] +
430395a7233cSPaul Blakey #endif
43043ee17bc7SMat Martineau #if IS_ENABLED(CONFIG_MPTCP)
43053ee17bc7SMat Martineau 		skb_ext_type_len[SKB_EXT_MPTCP] +
43063ee17bc7SMat Martineau #endif
430778476d31SJeremy Kerr #if IS_ENABLED(CONFIG_MCTP_FLOWS)
430878476d31SJeremy Kerr 		skb_ext_type_len[SKB_EXT_MCTP] +
430978476d31SJeremy Kerr #endif
4310df5042f4SFlorian Westphal 		0;
4311df5042f4SFlorian Westphal }
4312df5042f4SFlorian Westphal 
4313df5042f4SFlorian Westphal static void skb_extensions_init(void)
4314df5042f4SFlorian Westphal {
4315df5042f4SFlorian Westphal 	BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4316df5042f4SFlorian Westphal 	BUILD_BUG_ON(skb_ext_total_length() > 255);
4317df5042f4SFlorian Westphal 
4318df5042f4SFlorian Westphal 	skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4319df5042f4SFlorian Westphal 					     SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4320df5042f4SFlorian Westphal 					     0,
4321df5042f4SFlorian Westphal 					     SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4322df5042f4SFlorian Westphal 					     NULL);
4323df5042f4SFlorian Westphal }
4324df5042f4SFlorian Westphal #else
4325df5042f4SFlorian Westphal static void skb_extensions_init(void) {}
4326df5042f4SFlorian Westphal #endif
4327df5042f4SFlorian Westphal 
43281da177e4SLinus Torvalds void __init skb_init(void)
43291da177e4SLinus Torvalds {
433079a8a642SKees Cook 	skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
43311da177e4SLinus Torvalds 					      sizeof(struct sk_buff),
43321da177e4SLinus Torvalds 					      0,
4333e5d679f3SAlexey Dobriyan 					      SLAB_HWCACHE_ALIGN|SLAB_PANIC,
433479a8a642SKees Cook 					      offsetof(struct sk_buff, cb),
433579a8a642SKees Cook 					      sizeof_field(struct sk_buff, cb),
433620c2df83SPaul Mundt 					      NULL);
4337d179cd12SDavid S. Miller 	skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4338d0bf4a9eSEric Dumazet 						sizeof(struct sk_buff_fclones),
4339d179cd12SDavid S. Miller 						0,
4340e5d679f3SAlexey Dobriyan 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
434120c2df83SPaul Mundt 						NULL);
4342df5042f4SFlorian Westphal 	skb_extensions_init();
43431da177e4SLinus Torvalds }
43441da177e4SLinus Torvalds 
434551c739d1SDavid S. Miller static int
434648a1df65SJason A. Donenfeld __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
434748a1df65SJason A. Donenfeld 	       unsigned int recursion_level)
4348716ea3a7SDavid Howells {
43491a028e50SDavid S. Miller 	int start = skb_headlen(skb);
43501a028e50SDavid S. Miller 	int i, copy = start - offset;
4351fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
4352716ea3a7SDavid Howells 	int elt = 0;
4353716ea3a7SDavid Howells 
435448a1df65SJason A. Donenfeld 	if (unlikely(recursion_level >= 24))
435548a1df65SJason A. Donenfeld 		return -EMSGSIZE;
435648a1df65SJason A. Donenfeld 
4357716ea3a7SDavid Howells 	if (copy > 0) {
4358716ea3a7SDavid Howells 		if (copy > len)
4359716ea3a7SDavid Howells 			copy = len;
4360642f1490SJens Axboe 		sg_set_buf(sg, skb->data + offset, copy);
4361716ea3a7SDavid Howells 		elt++;
4362716ea3a7SDavid Howells 		if ((len -= copy) == 0)
4363716ea3a7SDavid Howells 			return elt;
4364716ea3a7SDavid Howells 		offset += copy;
4365716ea3a7SDavid Howells 	}
4366716ea3a7SDavid Howells 
4367716ea3a7SDavid Howells 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
43681a028e50SDavid S. Miller 		int end;
4369716ea3a7SDavid Howells 
4370547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
43711a028e50SDavid S. Miller 
43729e903e08SEric Dumazet 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4373716ea3a7SDavid Howells 		if ((copy = end - offset) > 0) {
4374716ea3a7SDavid Howells 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
437548a1df65SJason A. Donenfeld 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
437648a1df65SJason A. Donenfeld 				return -EMSGSIZE;
4377716ea3a7SDavid Howells 
4378716ea3a7SDavid Howells 			if (copy > len)
4379716ea3a7SDavid Howells 				copy = len;
4380ea2ab693SIan Campbell 			sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4381b54c9d5bSJonathan Lemon 				    skb_frag_off(frag) + offset - start);
4382716ea3a7SDavid Howells 			elt++;
4383716ea3a7SDavid Howells 			if (!(len -= copy))
4384716ea3a7SDavid Howells 				return elt;
4385716ea3a7SDavid Howells 			offset += copy;
4386716ea3a7SDavid Howells 		}
43871a028e50SDavid S. Miller 		start = end;
4388716ea3a7SDavid Howells 	}
4389716ea3a7SDavid Howells 
4390fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
439148a1df65SJason A. Donenfeld 		int end, ret;
4392716ea3a7SDavid Howells 
4393547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
43941a028e50SDavid S. Miller 
4395fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
4396716ea3a7SDavid Howells 		if ((copy = end - offset) > 0) {
439748a1df65SJason A. Donenfeld 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
439848a1df65SJason A. Donenfeld 				return -EMSGSIZE;
439948a1df65SJason A. Donenfeld 
4400716ea3a7SDavid Howells 			if (copy > len)
4401716ea3a7SDavid Howells 				copy = len;
440248a1df65SJason A. Donenfeld 			ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
440348a1df65SJason A. Donenfeld 					      copy, recursion_level + 1);
440448a1df65SJason A. Donenfeld 			if (unlikely(ret < 0))
440548a1df65SJason A. Donenfeld 				return ret;
440648a1df65SJason A. Donenfeld 			elt += ret;
4407716ea3a7SDavid Howells 			if ((len -= copy) == 0)
4408716ea3a7SDavid Howells 				return elt;
4409716ea3a7SDavid Howells 			offset += copy;
4410716ea3a7SDavid Howells 		}
44111a028e50SDavid S. Miller 		start = end;
4412716ea3a7SDavid Howells 	}
4413716ea3a7SDavid Howells 	BUG_ON(len);
4414716ea3a7SDavid Howells 	return elt;
4415716ea3a7SDavid Howells }
4416716ea3a7SDavid Howells 
441748a1df65SJason A. Donenfeld /**
441848a1df65SJason A. Donenfeld  *	skb_to_sgvec - Fill a scatter-gather list from a socket buffer
441948a1df65SJason A. Donenfeld  *	@skb: Socket buffer containing the buffers to be mapped
442048a1df65SJason A. Donenfeld  *	@sg: The scatter-gather list to map into
442148a1df65SJason A. Donenfeld  *	@offset: The offset into the buffer's contents to start mapping
442248a1df65SJason A. Donenfeld  *	@len: Length of buffer space to be mapped
442348a1df65SJason A. Donenfeld  *
442448a1df65SJason A. Donenfeld  *	Fill the specified scatter-gather list with mappings/pointers into a
442548a1df65SJason A. Donenfeld  *	region of the buffer space attached to a socket buffer. Returns either
442648a1df65SJason A. Donenfeld  *	the number of scatterlist items used, or -EMSGSIZE if the contents
442748a1df65SJason A. Donenfeld  *	could not fit.
442848a1df65SJason A. Donenfeld  */
442948a1df65SJason A. Donenfeld int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
443048a1df65SJason A. Donenfeld {
443148a1df65SJason A. Donenfeld 	int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
443248a1df65SJason A. Donenfeld 
443348a1df65SJason A. Donenfeld 	if (nsg <= 0)
443448a1df65SJason A. Donenfeld 		return nsg;
443548a1df65SJason A. Donenfeld 
443648a1df65SJason A. Donenfeld 	sg_mark_end(&sg[nsg - 1]);
443748a1df65SJason A. Donenfeld 
443848a1df65SJason A. Donenfeld 	return nsg;
443948a1df65SJason A. Donenfeld }
444048a1df65SJason A. Donenfeld EXPORT_SYMBOL_GPL(skb_to_sgvec);
444148a1df65SJason A. Donenfeld 
444225a91d8dSFan Du /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
444325a91d8dSFan Du  * sglist without mark the sg which contain last skb data as the end.
444425a91d8dSFan Du  * So the caller can mannipulate sg list as will when padding new data after
444525a91d8dSFan Du  * the first call without calling sg_unmark_end to expend sg list.
444625a91d8dSFan Du  *
444725a91d8dSFan Du  * Scenario to use skb_to_sgvec_nomark:
444825a91d8dSFan Du  * 1. sg_init_table
444925a91d8dSFan Du  * 2. skb_to_sgvec_nomark(payload1)
445025a91d8dSFan Du  * 3. skb_to_sgvec_nomark(payload2)
445125a91d8dSFan Du  *
445225a91d8dSFan Du  * This is equivalent to:
445325a91d8dSFan Du  * 1. sg_init_table
445425a91d8dSFan Du  * 2. skb_to_sgvec(payload1)
445525a91d8dSFan Du  * 3. sg_unmark_end
445625a91d8dSFan Du  * 4. skb_to_sgvec(payload2)
445725a91d8dSFan Du  *
445825a91d8dSFan Du  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
445925a91d8dSFan Du  * is more preferable.
446025a91d8dSFan Du  */
446125a91d8dSFan Du int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
446225a91d8dSFan Du 			int offset, int len)
446325a91d8dSFan Du {
446448a1df65SJason A. Donenfeld 	return __skb_to_sgvec(skb, sg, offset, len, 0);
446525a91d8dSFan Du }
446625a91d8dSFan Du EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
446725a91d8dSFan Du 
446851c739d1SDavid S. Miller 
446951c739d1SDavid S. Miller 
4470716ea3a7SDavid Howells /**
4471716ea3a7SDavid Howells  *	skb_cow_data - Check that a socket buffer's data buffers are writable
4472716ea3a7SDavid Howells  *	@skb: The socket buffer to check.
4473716ea3a7SDavid Howells  *	@tailbits: Amount of trailing space to be added
4474716ea3a7SDavid Howells  *	@trailer: Returned pointer to the skb where the @tailbits space begins
4475716ea3a7SDavid Howells  *
4476716ea3a7SDavid Howells  *	Make sure that the data buffers attached to a socket buffer are
4477716ea3a7SDavid Howells  *	writable. If they are not, private copies are made of the data buffers
4478716ea3a7SDavid Howells  *	and the socket buffer is set to use these instead.
4479716ea3a7SDavid Howells  *
4480716ea3a7SDavid Howells  *	If @tailbits is given, make sure that there is space to write @tailbits
4481716ea3a7SDavid Howells  *	bytes of data beyond current end of socket buffer.  @trailer will be
4482716ea3a7SDavid Howells  *	set to point to the skb in which this space begins.
4483716ea3a7SDavid Howells  *
4484716ea3a7SDavid Howells  *	The number of scatterlist elements required to completely map the
4485716ea3a7SDavid Howells  *	COW'd and extended socket buffer will be returned.
4486716ea3a7SDavid Howells  */
4487716ea3a7SDavid Howells int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4488716ea3a7SDavid Howells {
4489716ea3a7SDavid Howells 	int copyflag;
4490716ea3a7SDavid Howells 	int elt;
4491716ea3a7SDavid Howells 	struct sk_buff *skb1, **skb_p;
4492716ea3a7SDavid Howells 
4493716ea3a7SDavid Howells 	/* If skb is cloned or its head is paged, reallocate
4494716ea3a7SDavid Howells 	 * head pulling out all the pages (pages are considered not writable
4495716ea3a7SDavid Howells 	 * at the moment even if they are anonymous).
4496716ea3a7SDavid Howells 	 */
4497716ea3a7SDavid Howells 	if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4498c15fc199SMiaohe Lin 	    !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4499716ea3a7SDavid Howells 		return -ENOMEM;
4500716ea3a7SDavid Howells 
4501716ea3a7SDavid Howells 	/* Easy case. Most of packets will go this way. */
450221dc3301SDavid S. Miller 	if (!skb_has_frag_list(skb)) {
4503716ea3a7SDavid Howells 		/* A little of trouble, not enough of space for trailer.
4504716ea3a7SDavid Howells 		 * This should not happen, when stack is tuned to generate
4505716ea3a7SDavid Howells 		 * good frames. OK, on miss we reallocate and reserve even more
4506716ea3a7SDavid Howells 		 * space, 128 bytes is fair. */
4507716ea3a7SDavid Howells 
4508716ea3a7SDavid Howells 		if (skb_tailroom(skb) < tailbits &&
4509716ea3a7SDavid Howells 		    pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4510716ea3a7SDavid Howells 			return -ENOMEM;
4511716ea3a7SDavid Howells 
4512716ea3a7SDavid Howells 		/* Voila! */
4513716ea3a7SDavid Howells 		*trailer = skb;
4514716ea3a7SDavid Howells 		return 1;
4515716ea3a7SDavid Howells 	}
4516716ea3a7SDavid Howells 
4517716ea3a7SDavid Howells 	/* Misery. We are in troubles, going to mincer fragments... */
4518716ea3a7SDavid Howells 
4519716ea3a7SDavid Howells 	elt = 1;
4520716ea3a7SDavid Howells 	skb_p = &skb_shinfo(skb)->frag_list;
4521716ea3a7SDavid Howells 	copyflag = 0;
4522716ea3a7SDavid Howells 
4523716ea3a7SDavid Howells 	while ((skb1 = *skb_p) != NULL) {
4524716ea3a7SDavid Howells 		int ntail = 0;
4525716ea3a7SDavid Howells 
4526716ea3a7SDavid Howells 		/* The fragment is partially pulled by someone,
4527716ea3a7SDavid Howells 		 * this can happen on input. Copy it and everything
4528716ea3a7SDavid Howells 		 * after it. */
4529716ea3a7SDavid Howells 
4530716ea3a7SDavid Howells 		if (skb_shared(skb1))
4531716ea3a7SDavid Howells 			copyflag = 1;
4532716ea3a7SDavid Howells 
4533716ea3a7SDavid Howells 		/* If the skb is the last, worry about trailer. */
4534716ea3a7SDavid Howells 
4535716ea3a7SDavid Howells 		if (skb1->next == NULL && tailbits) {
4536716ea3a7SDavid Howells 			if (skb_shinfo(skb1)->nr_frags ||
453721dc3301SDavid S. Miller 			    skb_has_frag_list(skb1) ||
4538716ea3a7SDavid Howells 			    skb_tailroom(skb1) < tailbits)
4539716ea3a7SDavid Howells 				ntail = tailbits + 128;
4540716ea3a7SDavid Howells 		}
4541716ea3a7SDavid Howells 
4542716ea3a7SDavid Howells 		if (copyflag ||
4543716ea3a7SDavid Howells 		    skb_cloned(skb1) ||
4544716ea3a7SDavid Howells 		    ntail ||
4545716ea3a7SDavid Howells 		    skb_shinfo(skb1)->nr_frags ||
454621dc3301SDavid S. Miller 		    skb_has_frag_list(skb1)) {
4547716ea3a7SDavid Howells 			struct sk_buff *skb2;
4548716ea3a7SDavid Howells 
4549716ea3a7SDavid Howells 			/* Fuck, we are miserable poor guys... */
4550716ea3a7SDavid Howells 			if (ntail == 0)
4551716ea3a7SDavid Howells 				skb2 = skb_copy(skb1, GFP_ATOMIC);
4552716ea3a7SDavid Howells 			else
4553716ea3a7SDavid Howells 				skb2 = skb_copy_expand(skb1,
4554716ea3a7SDavid Howells 						       skb_headroom(skb1),
4555716ea3a7SDavid Howells 						       ntail,
4556716ea3a7SDavid Howells 						       GFP_ATOMIC);
4557716ea3a7SDavid Howells 			if (unlikely(skb2 == NULL))
4558716ea3a7SDavid Howells 				return -ENOMEM;
4559716ea3a7SDavid Howells 
4560716ea3a7SDavid Howells 			if (skb1->sk)
4561716ea3a7SDavid Howells 				skb_set_owner_w(skb2, skb1->sk);
4562716ea3a7SDavid Howells 
4563716ea3a7SDavid Howells 			/* Looking around. Are we still alive?
4564716ea3a7SDavid Howells 			 * OK, link new skb, drop old one */
4565716ea3a7SDavid Howells 
4566716ea3a7SDavid Howells 			skb2->next = skb1->next;
4567716ea3a7SDavid Howells 			*skb_p = skb2;
4568716ea3a7SDavid Howells 			kfree_skb(skb1);
4569716ea3a7SDavid Howells 			skb1 = skb2;
4570716ea3a7SDavid Howells 		}
4571716ea3a7SDavid Howells 		elt++;
4572716ea3a7SDavid Howells 		*trailer = skb1;
4573716ea3a7SDavid Howells 		skb_p = &skb1->next;
4574716ea3a7SDavid Howells 	}
4575716ea3a7SDavid Howells 
4576716ea3a7SDavid Howells 	return elt;
4577716ea3a7SDavid Howells }
4578b4ac530fSDavid S. Miller EXPORT_SYMBOL_GPL(skb_cow_data);
4579716ea3a7SDavid Howells 
4580b1faf566SEric Dumazet static void sock_rmem_free(struct sk_buff *skb)
4581b1faf566SEric Dumazet {
4582b1faf566SEric Dumazet 	struct sock *sk = skb->sk;
4583b1faf566SEric Dumazet 
4584b1faf566SEric Dumazet 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4585b1faf566SEric Dumazet }
4586b1faf566SEric Dumazet 
45878605330aSSoheil Hassas Yeganeh static void skb_set_err_queue(struct sk_buff *skb)
45888605330aSSoheil Hassas Yeganeh {
45898605330aSSoheil Hassas Yeganeh 	/* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
45908605330aSSoheil Hassas Yeganeh 	 * So, it is safe to (mis)use it to mark skbs on the error queue.
45918605330aSSoheil Hassas Yeganeh 	 */
45928605330aSSoheil Hassas Yeganeh 	skb->pkt_type = PACKET_OUTGOING;
45938605330aSSoheil Hassas Yeganeh 	BUILD_BUG_ON(PACKET_OUTGOING == 0);
45948605330aSSoheil Hassas Yeganeh }
45958605330aSSoheil Hassas Yeganeh 
4596b1faf566SEric Dumazet /*
4597b1faf566SEric Dumazet  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4598b1faf566SEric Dumazet  */
4599b1faf566SEric Dumazet int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4600b1faf566SEric Dumazet {
4601b1faf566SEric Dumazet 	if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4602ebb3b78dSEric Dumazet 	    (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4603b1faf566SEric Dumazet 		return -ENOMEM;
4604b1faf566SEric Dumazet 
4605b1faf566SEric Dumazet 	skb_orphan(skb);
4606b1faf566SEric Dumazet 	skb->sk = sk;
4607b1faf566SEric Dumazet 	skb->destructor = sock_rmem_free;
4608b1faf566SEric Dumazet 	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
46098605330aSSoheil Hassas Yeganeh 	skb_set_err_queue(skb);
4610b1faf566SEric Dumazet 
4611abb57ea4SEric Dumazet 	/* before exiting rcu section, make sure dst is refcounted */
4612abb57ea4SEric Dumazet 	skb_dst_force(skb);
4613abb57ea4SEric Dumazet 
4614b1faf566SEric Dumazet 	skb_queue_tail(&sk->sk_error_queue, skb);
4615b1faf566SEric Dumazet 	if (!sock_flag(sk, SOCK_DEAD))
4616e3ae2365SAlexander Aring 		sk_error_report(sk);
4617b1faf566SEric Dumazet 	return 0;
4618b1faf566SEric Dumazet }
4619b1faf566SEric Dumazet EXPORT_SYMBOL(sock_queue_err_skb);
4620b1faf566SEric Dumazet 
462183a1a1a7SSoheil Hassas Yeganeh static bool is_icmp_err_skb(const struct sk_buff *skb)
462283a1a1a7SSoheil Hassas Yeganeh {
462383a1a1a7SSoheil Hassas Yeganeh 	return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
462483a1a1a7SSoheil Hassas Yeganeh 		       SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
462583a1a1a7SSoheil Hassas Yeganeh }
462683a1a1a7SSoheil Hassas Yeganeh 
4627364a9e93SWillem de Bruijn struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4628364a9e93SWillem de Bruijn {
4629364a9e93SWillem de Bruijn 	struct sk_buff_head *q = &sk->sk_error_queue;
463083a1a1a7SSoheil Hassas Yeganeh 	struct sk_buff *skb, *skb_next = NULL;
463183a1a1a7SSoheil Hassas Yeganeh 	bool icmp_next = false;
4632997d5c3fSEric Dumazet 	unsigned long flags;
4633364a9e93SWillem de Bruijn 
4634997d5c3fSEric Dumazet 	spin_lock_irqsave(&q->lock, flags);
4635364a9e93SWillem de Bruijn 	skb = __skb_dequeue(q);
463638b25793SSoheil Hassas Yeganeh 	if (skb && (skb_next = skb_peek(q))) {
463783a1a1a7SSoheil Hassas Yeganeh 		icmp_next = is_icmp_err_skb(skb_next);
463838b25793SSoheil Hassas Yeganeh 		if (icmp_next)
4639985f7337SWillem de Bruijn 			sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
464038b25793SSoheil Hassas Yeganeh 	}
4641997d5c3fSEric Dumazet 	spin_unlock_irqrestore(&q->lock, flags);
4642364a9e93SWillem de Bruijn 
464383a1a1a7SSoheil Hassas Yeganeh 	if (is_icmp_err_skb(skb) && !icmp_next)
464483a1a1a7SSoheil Hassas Yeganeh 		sk->sk_err = 0;
464583a1a1a7SSoheil Hassas Yeganeh 
464683a1a1a7SSoheil Hassas Yeganeh 	if (skb_next)
4647e3ae2365SAlexander Aring 		sk_error_report(sk);
4648364a9e93SWillem de Bruijn 
4649364a9e93SWillem de Bruijn 	return skb;
4650364a9e93SWillem de Bruijn }
4651364a9e93SWillem de Bruijn EXPORT_SYMBOL(sock_dequeue_err_skb);
4652364a9e93SWillem de Bruijn 
4653cab41c47SAlexander Duyck /**
4654cab41c47SAlexander Duyck  * skb_clone_sk - create clone of skb, and take reference to socket
4655cab41c47SAlexander Duyck  * @skb: the skb to clone
4656cab41c47SAlexander Duyck  *
4657cab41c47SAlexander Duyck  * This function creates a clone of a buffer that holds a reference on
4658cab41c47SAlexander Duyck  * sk_refcnt.  Buffers created via this function are meant to be
4659cab41c47SAlexander Duyck  * returned using sock_queue_err_skb, or free via kfree_skb.
4660cab41c47SAlexander Duyck  *
4661cab41c47SAlexander Duyck  * When passing buffers allocated with this function to sock_queue_err_skb
4662cab41c47SAlexander Duyck  * it is necessary to wrap the call with sock_hold/sock_put in order to
4663cab41c47SAlexander Duyck  * prevent the socket from being released prior to being enqueued on
4664cab41c47SAlexander Duyck  * the sk_error_queue.
4665cab41c47SAlexander Duyck  */
466662bccb8cSAlexander Duyck struct sk_buff *skb_clone_sk(struct sk_buff *skb)
466762bccb8cSAlexander Duyck {
466862bccb8cSAlexander Duyck 	struct sock *sk = skb->sk;
466962bccb8cSAlexander Duyck 	struct sk_buff *clone;
467062bccb8cSAlexander Duyck 
467141c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
467262bccb8cSAlexander Duyck 		return NULL;
467362bccb8cSAlexander Duyck 
467462bccb8cSAlexander Duyck 	clone = skb_clone(skb, GFP_ATOMIC);
467562bccb8cSAlexander Duyck 	if (!clone) {
467662bccb8cSAlexander Duyck 		sock_put(sk);
467762bccb8cSAlexander Duyck 		return NULL;
467862bccb8cSAlexander Duyck 	}
467962bccb8cSAlexander Duyck 
468062bccb8cSAlexander Duyck 	clone->sk = sk;
468162bccb8cSAlexander Duyck 	clone->destructor = sock_efree;
468262bccb8cSAlexander Duyck 
468362bccb8cSAlexander Duyck 	return clone;
468462bccb8cSAlexander Duyck }
468562bccb8cSAlexander Duyck EXPORT_SYMBOL(skb_clone_sk);
468662bccb8cSAlexander Duyck 
468737846ef0SAlexander Duyck static void __skb_complete_tx_timestamp(struct sk_buff *skb,
468837846ef0SAlexander Duyck 					struct sock *sk,
46894ef1b286SSoheil Hassas Yeganeh 					int tstype,
46904ef1b286SSoheil Hassas Yeganeh 					bool opt_stats)
4691ac45f602SPatrick Ohly {
4692ac45f602SPatrick Ohly 	struct sock_exterr_skb *serr;
4693ac45f602SPatrick Ohly 	int err;
4694ac45f602SPatrick Ohly 
46954ef1b286SSoheil Hassas Yeganeh 	BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
46964ef1b286SSoheil Hassas Yeganeh 
4697ac45f602SPatrick Ohly 	serr = SKB_EXT_ERR(skb);
4698ac45f602SPatrick Ohly 	memset(serr, 0, sizeof(*serr));
4699ac45f602SPatrick Ohly 	serr->ee.ee_errno = ENOMSG;
4700ac45f602SPatrick Ohly 	serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4701e7fd2885SWillem de Bruijn 	serr->ee.ee_info = tstype;
47024ef1b286SSoheil Hassas Yeganeh 	serr->opt_stats = opt_stats;
47031862d620SWillem de Bruijn 	serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
47044ed2d765SWillem de Bruijn 	if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
470509c2d251SWillem de Bruijn 		serr->ee.ee_data = skb_shinfo(skb)->tskey;
470642f67eeaSEric Dumazet 		if (sk_is_tcp(sk))
47074ed2d765SWillem de Bruijn 			serr->ee.ee_data -= sk->sk_tskey;
47084ed2d765SWillem de Bruijn 	}
470929030374SEric Dumazet 
4710ac45f602SPatrick Ohly 	err = sock_queue_err_skb(sk, skb);
471129030374SEric Dumazet 
4712ac45f602SPatrick Ohly 	if (err)
4713ac45f602SPatrick Ohly 		kfree_skb(skb);
4714ac45f602SPatrick Ohly }
471537846ef0SAlexander Duyck 
4716b245be1fSWillem de Bruijn static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4717b245be1fSWillem de Bruijn {
4718b245be1fSWillem de Bruijn 	bool ret;
4719b245be1fSWillem de Bruijn 
4720b245be1fSWillem de Bruijn 	if (likely(sysctl_tstamp_allow_data || tsonly))
4721b245be1fSWillem de Bruijn 		return true;
4722b245be1fSWillem de Bruijn 
4723b245be1fSWillem de Bruijn 	read_lock_bh(&sk->sk_callback_lock);
4724b245be1fSWillem de Bruijn 	ret = sk->sk_socket && sk->sk_socket->file &&
4725b245be1fSWillem de Bruijn 	      file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4726b245be1fSWillem de Bruijn 	read_unlock_bh(&sk->sk_callback_lock);
4727b245be1fSWillem de Bruijn 	return ret;
4728b245be1fSWillem de Bruijn }
4729b245be1fSWillem de Bruijn 
473037846ef0SAlexander Duyck void skb_complete_tx_timestamp(struct sk_buff *skb,
473137846ef0SAlexander Duyck 			       struct skb_shared_hwtstamps *hwtstamps)
473237846ef0SAlexander Duyck {
473337846ef0SAlexander Duyck 	struct sock *sk = skb->sk;
473437846ef0SAlexander Duyck 
4735b245be1fSWillem de Bruijn 	if (!skb_may_tx_timestamp(sk, false))
473635b99dffSWillem de Bruijn 		goto err;
4737b245be1fSWillem de Bruijn 
47389ac25fc0SEric Dumazet 	/* Take a reference to prevent skb_orphan() from freeing the socket,
47399ac25fc0SEric Dumazet 	 * but only if the socket refcount is not zero.
47409ac25fc0SEric Dumazet 	 */
474141c6d650SReshetova, Elena 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
474237846ef0SAlexander Duyck 		*skb_hwtstamps(skb) = *hwtstamps;
47434ef1b286SSoheil Hassas Yeganeh 		__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
474437846ef0SAlexander Duyck 		sock_put(sk);
474535b99dffSWillem de Bruijn 		return;
474637846ef0SAlexander Duyck 	}
474735b99dffSWillem de Bruijn 
474835b99dffSWillem de Bruijn err:
474935b99dffSWillem de Bruijn 	kfree_skb(skb);
47509ac25fc0SEric Dumazet }
475137846ef0SAlexander Duyck EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
475237846ef0SAlexander Duyck 
475337846ef0SAlexander Duyck void __skb_tstamp_tx(struct sk_buff *orig_skb,
4754e7ed11eeSYousuk Seung 		     const struct sk_buff *ack_skb,
475537846ef0SAlexander Duyck 		     struct skb_shared_hwtstamps *hwtstamps,
475637846ef0SAlexander Duyck 		     struct sock *sk, int tstype)
475737846ef0SAlexander Duyck {
475837846ef0SAlexander Duyck 	struct sk_buff *skb;
47594ef1b286SSoheil Hassas Yeganeh 	bool tsonly, opt_stats = false;
476037846ef0SAlexander Duyck 
47613a8dd971SWillem de Bruijn 	if (!sk)
47623a8dd971SWillem de Bruijn 		return;
47633a8dd971SWillem de Bruijn 
4764b50a5c70SMiroslav Lichvar 	if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4765b50a5c70SMiroslav Lichvar 	    skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4766b50a5c70SMiroslav Lichvar 		return;
4767b50a5c70SMiroslav Lichvar 
47683a8dd971SWillem de Bruijn 	tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
47693a8dd971SWillem de Bruijn 	if (!skb_may_tx_timestamp(sk, tsonly))
477037846ef0SAlexander Duyck 		return;
477137846ef0SAlexander Duyck 
47721c885808SFrancis Yan 	if (tsonly) {
47731c885808SFrancis Yan #ifdef CONFIG_INET
47741c885808SFrancis Yan 		if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
477542f67eeaSEric Dumazet 		    sk_is_tcp(sk)) {
4776e7ed11eeSYousuk Seung 			skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4777e7ed11eeSYousuk Seung 							     ack_skb);
47784ef1b286SSoheil Hassas Yeganeh 			opt_stats = true;
47794ef1b286SSoheil Hassas Yeganeh 		} else
47801c885808SFrancis Yan #endif
47811c885808SFrancis Yan 			skb = alloc_skb(0, GFP_ATOMIC);
47821c885808SFrancis Yan 	} else {
478337846ef0SAlexander Duyck 		skb = skb_clone(orig_skb, GFP_ATOMIC);
47841c885808SFrancis Yan 	}
478537846ef0SAlexander Duyck 	if (!skb)
478637846ef0SAlexander Duyck 		return;
478737846ef0SAlexander Duyck 
478849ca0d8bSWillem de Bruijn 	if (tsonly) {
4789fff88030SWillem de Bruijn 		skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4790fff88030SWillem de Bruijn 					     SKBTX_ANY_TSTAMP;
479149ca0d8bSWillem de Bruijn 		skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
479249ca0d8bSWillem de Bruijn 	}
479349ca0d8bSWillem de Bruijn 
479449ca0d8bSWillem de Bruijn 	if (hwtstamps)
479549ca0d8bSWillem de Bruijn 		*skb_hwtstamps(skb) = *hwtstamps;
479649ca0d8bSWillem de Bruijn 	else
479749ca0d8bSWillem de Bruijn 		skb->tstamp = ktime_get_real();
479849ca0d8bSWillem de Bruijn 
47994ef1b286SSoheil Hassas Yeganeh 	__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
480037846ef0SAlexander Duyck }
4801e7fd2885SWillem de Bruijn EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4802e7fd2885SWillem de Bruijn 
4803e7fd2885SWillem de Bruijn void skb_tstamp_tx(struct sk_buff *orig_skb,
4804e7fd2885SWillem de Bruijn 		   struct skb_shared_hwtstamps *hwtstamps)
4805e7fd2885SWillem de Bruijn {
4806e7ed11eeSYousuk Seung 	return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4807e7fd2885SWillem de Bruijn 			       SCM_TSTAMP_SND);
4808e7fd2885SWillem de Bruijn }
4809ac45f602SPatrick Ohly EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4810ac45f602SPatrick Ohly 
48116e3e939fSJohannes Berg void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
48126e3e939fSJohannes Berg {
48136e3e939fSJohannes Berg 	struct sock *sk = skb->sk;
48146e3e939fSJohannes Berg 	struct sock_exterr_skb *serr;
4815dd4f1072SEric Dumazet 	int err = 1;
48166e3e939fSJohannes Berg 
48176e3e939fSJohannes Berg 	skb->wifi_acked_valid = 1;
48186e3e939fSJohannes Berg 	skb->wifi_acked = acked;
48196e3e939fSJohannes Berg 
48206e3e939fSJohannes Berg 	serr = SKB_EXT_ERR(skb);
48216e3e939fSJohannes Berg 	memset(serr, 0, sizeof(*serr));
48226e3e939fSJohannes Berg 	serr->ee.ee_errno = ENOMSG;
48236e3e939fSJohannes Berg 	serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
48246e3e939fSJohannes Berg 
4825dd4f1072SEric Dumazet 	/* Take a reference to prevent skb_orphan() from freeing the socket,
4826dd4f1072SEric Dumazet 	 * but only if the socket refcount is not zero.
4827dd4f1072SEric Dumazet 	 */
482841c6d650SReshetova, Elena 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
48296e3e939fSJohannes Berg 		err = sock_queue_err_skb(sk, skb);
4830dd4f1072SEric Dumazet 		sock_put(sk);
4831dd4f1072SEric Dumazet 	}
48326e3e939fSJohannes Berg 	if (err)
48336e3e939fSJohannes Berg 		kfree_skb(skb);
48346e3e939fSJohannes Berg }
48356e3e939fSJohannes Berg EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
48366e3e939fSJohannes Berg 
4837f35d9d8aSRusty Russell /**
4838f35d9d8aSRusty Russell  * skb_partial_csum_set - set up and verify partial csum values for packet
4839f35d9d8aSRusty Russell  * @skb: the skb to set
4840f35d9d8aSRusty Russell  * @start: the number of bytes after skb->data to start checksumming.
4841f35d9d8aSRusty Russell  * @off: the offset from start to place the checksum.
4842f35d9d8aSRusty Russell  *
4843f35d9d8aSRusty Russell  * For untrusted partially-checksummed packets, we need to make sure the values
4844f35d9d8aSRusty Russell  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4845f35d9d8aSRusty Russell  *
4846f35d9d8aSRusty Russell  * This function checks and sets those values and skb->ip_summed: if this
4847f35d9d8aSRusty Russell  * returns false you should drop the packet.
4848f35d9d8aSRusty Russell  */
4849f35d9d8aSRusty Russell bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4850f35d9d8aSRusty Russell {
485152b5d6f5SEric Dumazet 	u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
485252b5d6f5SEric Dumazet 	u32 csum_start = skb_headroom(skb) + (u32)start;
485352b5d6f5SEric Dumazet 
485452b5d6f5SEric Dumazet 	if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
485552b5d6f5SEric Dumazet 		net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
485652b5d6f5SEric Dumazet 				     start, off, skb_headroom(skb), skb_headlen(skb));
4857f35d9d8aSRusty Russell 		return false;
4858f35d9d8aSRusty Russell 	}
4859f35d9d8aSRusty Russell 	skb->ip_summed = CHECKSUM_PARTIAL;
486052b5d6f5SEric Dumazet 	skb->csum_start = csum_start;
4861f35d9d8aSRusty Russell 	skb->csum_offset = off;
4862e5d5decaSJason Wang 	skb_set_transport_header(skb, start);
4863f35d9d8aSRusty Russell 	return true;
4864f35d9d8aSRusty Russell }
4865b4ac530fSDavid S. Miller EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4866f35d9d8aSRusty Russell 
4867ed1f50c3SPaul Durrant static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4868ed1f50c3SPaul Durrant 			       unsigned int max)
4869ed1f50c3SPaul Durrant {
4870ed1f50c3SPaul Durrant 	if (skb_headlen(skb) >= len)
4871ed1f50c3SPaul Durrant 		return 0;
4872ed1f50c3SPaul Durrant 
4873ed1f50c3SPaul Durrant 	/* If we need to pullup then pullup to the max, so we
4874ed1f50c3SPaul Durrant 	 * won't need to do it again.
4875ed1f50c3SPaul Durrant 	 */
4876ed1f50c3SPaul Durrant 	if (max > skb->len)
4877ed1f50c3SPaul Durrant 		max = skb->len;
4878ed1f50c3SPaul Durrant 
4879ed1f50c3SPaul Durrant 	if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4880ed1f50c3SPaul Durrant 		return -ENOMEM;
4881ed1f50c3SPaul Durrant 
4882ed1f50c3SPaul Durrant 	if (skb_headlen(skb) < len)
4883ed1f50c3SPaul Durrant 		return -EPROTO;
4884ed1f50c3SPaul Durrant 
4885ed1f50c3SPaul Durrant 	return 0;
4886ed1f50c3SPaul Durrant }
4887ed1f50c3SPaul Durrant 
4888f9708b43SJan Beulich #define MAX_TCP_HDR_LEN (15 * 4)
4889f9708b43SJan Beulich 
4890f9708b43SJan Beulich static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4891f9708b43SJan Beulich 				      typeof(IPPROTO_IP) proto,
4892f9708b43SJan Beulich 				      unsigned int off)
4893f9708b43SJan Beulich {
4894f9708b43SJan Beulich 	int err;
4895f9708b43SJan Beulich 
4896161d1792SKees Cook 	switch (proto) {
4897f9708b43SJan Beulich 	case IPPROTO_TCP:
4898f9708b43SJan Beulich 		err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4899f9708b43SJan Beulich 					  off + MAX_TCP_HDR_LEN);
4900f9708b43SJan Beulich 		if (!err && !skb_partial_csum_set(skb, off,
4901f9708b43SJan Beulich 						  offsetof(struct tcphdr,
4902f9708b43SJan Beulich 							   check)))
4903f9708b43SJan Beulich 			err = -EPROTO;
4904f9708b43SJan Beulich 		return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4905f9708b43SJan Beulich 
4906f9708b43SJan Beulich 	case IPPROTO_UDP:
4907f9708b43SJan Beulich 		err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4908f9708b43SJan Beulich 					  off + sizeof(struct udphdr));
4909f9708b43SJan Beulich 		if (!err && !skb_partial_csum_set(skb, off,
4910f9708b43SJan Beulich 						  offsetof(struct udphdr,
4911f9708b43SJan Beulich 							   check)))
4912f9708b43SJan Beulich 			err = -EPROTO;
4913f9708b43SJan Beulich 		return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4914f9708b43SJan Beulich 	}
4915f9708b43SJan Beulich 
4916f9708b43SJan Beulich 	return ERR_PTR(-EPROTO);
4917f9708b43SJan Beulich }
4918f9708b43SJan Beulich 
4919ed1f50c3SPaul Durrant /* This value should be large enough to cover a tagged ethernet header plus
4920ed1f50c3SPaul Durrant  * maximally sized IP and TCP or UDP headers.
4921ed1f50c3SPaul Durrant  */
4922ed1f50c3SPaul Durrant #define MAX_IP_HDR_LEN 128
4923ed1f50c3SPaul Durrant 
4924f9708b43SJan Beulich static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
4925ed1f50c3SPaul Durrant {
4926ed1f50c3SPaul Durrant 	unsigned int off;
4927ed1f50c3SPaul Durrant 	bool fragment;
4928f9708b43SJan Beulich 	__sum16 *csum;
4929ed1f50c3SPaul Durrant 	int err;
4930ed1f50c3SPaul Durrant 
4931ed1f50c3SPaul Durrant 	fragment = false;
4932ed1f50c3SPaul Durrant 
4933ed1f50c3SPaul Durrant 	err = skb_maybe_pull_tail(skb,
4934ed1f50c3SPaul Durrant 				  sizeof(struct iphdr),
4935ed1f50c3SPaul Durrant 				  MAX_IP_HDR_LEN);
4936ed1f50c3SPaul Durrant 	if (err < 0)
4937ed1f50c3SPaul Durrant 		goto out;
4938ed1f50c3SPaul Durrant 
493911f920d2SMiaohe Lin 	if (ip_is_fragment(ip_hdr(skb)))
4940ed1f50c3SPaul Durrant 		fragment = true;
4941ed1f50c3SPaul Durrant 
4942ed1f50c3SPaul Durrant 	off = ip_hdrlen(skb);
4943ed1f50c3SPaul Durrant 
4944ed1f50c3SPaul Durrant 	err = -EPROTO;
4945ed1f50c3SPaul Durrant 
4946ed1f50c3SPaul Durrant 	if (fragment)
4947ed1f50c3SPaul Durrant 		goto out;
4948ed1f50c3SPaul Durrant 
4949f9708b43SJan Beulich 	csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
4950f9708b43SJan Beulich 	if (IS_ERR(csum))
4951f9708b43SJan Beulich 		return PTR_ERR(csum);
4952ed1f50c3SPaul Durrant 
4953ed1f50c3SPaul Durrant 	if (recalculate)
4954f9708b43SJan Beulich 		*csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
4955ed1f50c3SPaul Durrant 					   ip_hdr(skb)->daddr,
4956ed1f50c3SPaul Durrant 					   skb->len - off,
4957f9708b43SJan Beulich 					   ip_hdr(skb)->protocol, 0);
4958ed1f50c3SPaul Durrant 	err = 0;
4959ed1f50c3SPaul Durrant 
4960ed1f50c3SPaul Durrant out:
4961ed1f50c3SPaul Durrant 	return err;
4962ed1f50c3SPaul Durrant }
4963ed1f50c3SPaul Durrant 
4964ed1f50c3SPaul Durrant /* This value should be large enough to cover a tagged ethernet header plus
4965ed1f50c3SPaul Durrant  * an IPv6 header, all options, and a maximal TCP or UDP header.
4966ed1f50c3SPaul Durrant  */
4967ed1f50c3SPaul Durrant #define MAX_IPV6_HDR_LEN 256
4968ed1f50c3SPaul Durrant 
4969ed1f50c3SPaul Durrant #define OPT_HDR(type, skb, off) \
4970ed1f50c3SPaul Durrant 	(type *)(skb_network_header(skb) + (off))
4971ed1f50c3SPaul Durrant 
4972ed1f50c3SPaul Durrant static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
4973ed1f50c3SPaul Durrant {
4974ed1f50c3SPaul Durrant 	int err;
4975ed1f50c3SPaul Durrant 	u8 nexthdr;
4976ed1f50c3SPaul Durrant 	unsigned int off;
4977ed1f50c3SPaul Durrant 	unsigned int len;
4978ed1f50c3SPaul Durrant 	bool fragment;
4979ed1f50c3SPaul Durrant 	bool done;
4980f9708b43SJan Beulich 	__sum16 *csum;
4981ed1f50c3SPaul Durrant 
4982ed1f50c3SPaul Durrant 	fragment = false;
4983ed1f50c3SPaul Durrant 	done = false;
4984ed1f50c3SPaul Durrant 
4985ed1f50c3SPaul Durrant 	off = sizeof(struct ipv6hdr);
4986ed1f50c3SPaul Durrant 
4987ed1f50c3SPaul Durrant 	err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
4988ed1f50c3SPaul Durrant 	if (err < 0)
4989ed1f50c3SPaul Durrant 		goto out;
4990ed1f50c3SPaul Durrant 
4991ed1f50c3SPaul Durrant 	nexthdr = ipv6_hdr(skb)->nexthdr;
4992ed1f50c3SPaul Durrant 
4993ed1f50c3SPaul Durrant 	len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
4994ed1f50c3SPaul Durrant 	while (off <= len && !done) {
4995ed1f50c3SPaul Durrant 		switch (nexthdr) {
4996ed1f50c3SPaul Durrant 		case IPPROTO_DSTOPTS:
4997ed1f50c3SPaul Durrant 		case IPPROTO_HOPOPTS:
4998ed1f50c3SPaul Durrant 		case IPPROTO_ROUTING: {
4999ed1f50c3SPaul Durrant 			struct ipv6_opt_hdr *hp;
5000ed1f50c3SPaul Durrant 
5001ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5002ed1f50c3SPaul Durrant 						  off +
5003ed1f50c3SPaul Durrant 						  sizeof(struct ipv6_opt_hdr),
5004ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5005ed1f50c3SPaul Durrant 			if (err < 0)
5006ed1f50c3SPaul Durrant 				goto out;
5007ed1f50c3SPaul Durrant 
5008ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5009ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5010ed1f50c3SPaul Durrant 			off += ipv6_optlen(hp);
5011ed1f50c3SPaul Durrant 			break;
5012ed1f50c3SPaul Durrant 		}
5013ed1f50c3SPaul Durrant 		case IPPROTO_AH: {
5014ed1f50c3SPaul Durrant 			struct ip_auth_hdr *hp;
5015ed1f50c3SPaul Durrant 
5016ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5017ed1f50c3SPaul Durrant 						  off +
5018ed1f50c3SPaul Durrant 						  sizeof(struct ip_auth_hdr),
5019ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5020ed1f50c3SPaul Durrant 			if (err < 0)
5021ed1f50c3SPaul Durrant 				goto out;
5022ed1f50c3SPaul Durrant 
5023ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5024ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5025ed1f50c3SPaul Durrant 			off += ipv6_authlen(hp);
5026ed1f50c3SPaul Durrant 			break;
5027ed1f50c3SPaul Durrant 		}
5028ed1f50c3SPaul Durrant 		case IPPROTO_FRAGMENT: {
5029ed1f50c3SPaul Durrant 			struct frag_hdr *hp;
5030ed1f50c3SPaul Durrant 
5031ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5032ed1f50c3SPaul Durrant 						  off +
5033ed1f50c3SPaul Durrant 						  sizeof(struct frag_hdr),
5034ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5035ed1f50c3SPaul Durrant 			if (err < 0)
5036ed1f50c3SPaul Durrant 				goto out;
5037ed1f50c3SPaul Durrant 
5038ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct frag_hdr, skb, off);
5039ed1f50c3SPaul Durrant 
5040ed1f50c3SPaul Durrant 			if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5041ed1f50c3SPaul Durrant 				fragment = true;
5042ed1f50c3SPaul Durrant 
5043ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5044ed1f50c3SPaul Durrant 			off += sizeof(struct frag_hdr);
5045ed1f50c3SPaul Durrant 			break;
5046ed1f50c3SPaul Durrant 		}
5047ed1f50c3SPaul Durrant 		default:
5048ed1f50c3SPaul Durrant 			done = true;
5049ed1f50c3SPaul Durrant 			break;
5050ed1f50c3SPaul Durrant 		}
5051ed1f50c3SPaul Durrant 	}
5052ed1f50c3SPaul Durrant 
5053ed1f50c3SPaul Durrant 	err = -EPROTO;
5054ed1f50c3SPaul Durrant 
5055ed1f50c3SPaul Durrant 	if (!done || fragment)
5056ed1f50c3SPaul Durrant 		goto out;
5057ed1f50c3SPaul Durrant 
5058f9708b43SJan Beulich 	csum = skb_checksum_setup_ip(skb, nexthdr, off);
5059f9708b43SJan Beulich 	if (IS_ERR(csum))
5060f9708b43SJan Beulich 		return PTR_ERR(csum);
5061ed1f50c3SPaul Durrant 
5062ed1f50c3SPaul Durrant 	if (recalculate)
5063f9708b43SJan Beulich 		*csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5064ed1f50c3SPaul Durrant 					 &ipv6_hdr(skb)->daddr,
5065f9708b43SJan Beulich 					 skb->len - off, nexthdr, 0);
5066ed1f50c3SPaul Durrant 	err = 0;
5067ed1f50c3SPaul Durrant 
5068ed1f50c3SPaul Durrant out:
5069ed1f50c3SPaul Durrant 	return err;
5070ed1f50c3SPaul Durrant }
5071ed1f50c3SPaul Durrant 
5072ed1f50c3SPaul Durrant /**
5073ed1f50c3SPaul Durrant  * skb_checksum_setup - set up partial checksum offset
5074ed1f50c3SPaul Durrant  * @skb: the skb to set up
5075ed1f50c3SPaul Durrant  * @recalculate: if true the pseudo-header checksum will be recalculated
5076ed1f50c3SPaul Durrant  */
5077ed1f50c3SPaul Durrant int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5078ed1f50c3SPaul Durrant {
5079ed1f50c3SPaul Durrant 	int err;
5080ed1f50c3SPaul Durrant 
5081ed1f50c3SPaul Durrant 	switch (skb->protocol) {
5082ed1f50c3SPaul Durrant 	case htons(ETH_P_IP):
5083f9708b43SJan Beulich 		err = skb_checksum_setup_ipv4(skb, recalculate);
5084ed1f50c3SPaul Durrant 		break;
5085ed1f50c3SPaul Durrant 
5086ed1f50c3SPaul Durrant 	case htons(ETH_P_IPV6):
5087ed1f50c3SPaul Durrant 		err = skb_checksum_setup_ipv6(skb, recalculate);
5088ed1f50c3SPaul Durrant 		break;
5089ed1f50c3SPaul Durrant 
5090ed1f50c3SPaul Durrant 	default:
5091ed1f50c3SPaul Durrant 		err = -EPROTO;
5092ed1f50c3SPaul Durrant 		break;
5093ed1f50c3SPaul Durrant 	}
5094ed1f50c3SPaul Durrant 
5095ed1f50c3SPaul Durrant 	return err;
5096ed1f50c3SPaul Durrant }
5097ed1f50c3SPaul Durrant EXPORT_SYMBOL(skb_checksum_setup);
5098ed1f50c3SPaul Durrant 
50999afd85c9SLinus Lüssing /**
51009afd85c9SLinus Lüssing  * skb_checksum_maybe_trim - maybe trims the given skb
51019afd85c9SLinus Lüssing  * @skb: the skb to check
51029afd85c9SLinus Lüssing  * @transport_len: the data length beyond the network header
51039afd85c9SLinus Lüssing  *
51049afd85c9SLinus Lüssing  * Checks whether the given skb has data beyond the given transport length.
51059afd85c9SLinus Lüssing  * If so, returns a cloned skb trimmed to this transport length.
51069afd85c9SLinus Lüssing  * Otherwise returns the provided skb. Returns NULL in error cases
51079afd85c9SLinus Lüssing  * (e.g. transport_len exceeds skb length or out-of-memory).
51089afd85c9SLinus Lüssing  *
5109a516993fSLinus Lüssing  * Caller needs to set the skb transport header and free any returned skb if it
5110a516993fSLinus Lüssing  * differs from the provided skb.
51119afd85c9SLinus Lüssing  */
51129afd85c9SLinus Lüssing static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
51139afd85c9SLinus Lüssing 					       unsigned int transport_len)
51149afd85c9SLinus Lüssing {
51159afd85c9SLinus Lüssing 	struct sk_buff *skb_chk;
51169afd85c9SLinus Lüssing 	unsigned int len = skb_transport_offset(skb) + transport_len;
51179afd85c9SLinus Lüssing 	int ret;
51189afd85c9SLinus Lüssing 
5119a516993fSLinus Lüssing 	if (skb->len < len)
51209afd85c9SLinus Lüssing 		return NULL;
5121a516993fSLinus Lüssing 	else if (skb->len == len)
51229afd85c9SLinus Lüssing 		return skb;
51239afd85c9SLinus Lüssing 
51249afd85c9SLinus Lüssing 	skb_chk = skb_clone(skb, GFP_ATOMIC);
51259afd85c9SLinus Lüssing 	if (!skb_chk)
51269afd85c9SLinus Lüssing 		return NULL;
51279afd85c9SLinus Lüssing 
51289afd85c9SLinus Lüssing 	ret = pskb_trim_rcsum(skb_chk, len);
51299afd85c9SLinus Lüssing 	if (ret) {
51309afd85c9SLinus Lüssing 		kfree_skb(skb_chk);
51319afd85c9SLinus Lüssing 		return NULL;
51329afd85c9SLinus Lüssing 	}
51339afd85c9SLinus Lüssing 
51349afd85c9SLinus Lüssing 	return skb_chk;
51359afd85c9SLinus Lüssing }
51369afd85c9SLinus Lüssing 
51379afd85c9SLinus Lüssing /**
51389afd85c9SLinus Lüssing  * skb_checksum_trimmed - validate checksum of an skb
51399afd85c9SLinus Lüssing  * @skb: the skb to check
51409afd85c9SLinus Lüssing  * @transport_len: the data length beyond the network header
51419afd85c9SLinus Lüssing  * @skb_chkf: checksum function to use
51429afd85c9SLinus Lüssing  *
51439afd85c9SLinus Lüssing  * Applies the given checksum function skb_chkf to the provided skb.
51449afd85c9SLinus Lüssing  * Returns a checked and maybe trimmed skb. Returns NULL on error.
51459afd85c9SLinus Lüssing  *
51469afd85c9SLinus Lüssing  * If the skb has data beyond the given transport length, then a
51479afd85c9SLinus Lüssing  * trimmed & cloned skb is checked and returned.
51489afd85c9SLinus Lüssing  *
5149a516993fSLinus Lüssing  * Caller needs to set the skb transport header and free any returned skb if it
5150a516993fSLinus Lüssing  * differs from the provided skb.
51519afd85c9SLinus Lüssing  */
51529afd85c9SLinus Lüssing struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
51539afd85c9SLinus Lüssing 				     unsigned int transport_len,
51549afd85c9SLinus Lüssing 				     __sum16(*skb_chkf)(struct sk_buff *skb))
51559afd85c9SLinus Lüssing {
51569afd85c9SLinus Lüssing 	struct sk_buff *skb_chk;
51579afd85c9SLinus Lüssing 	unsigned int offset = skb_transport_offset(skb);
5158fcba67c9SLinus Lüssing 	__sum16 ret;
51599afd85c9SLinus Lüssing 
51609afd85c9SLinus Lüssing 	skb_chk = skb_checksum_maybe_trim(skb, transport_len);
51619afd85c9SLinus Lüssing 	if (!skb_chk)
5162a516993fSLinus Lüssing 		goto err;
51639afd85c9SLinus Lüssing 
5164a516993fSLinus Lüssing 	if (!pskb_may_pull(skb_chk, offset))
5165a516993fSLinus Lüssing 		goto err;
51669afd85c9SLinus Lüssing 
51679b368814SLinus Lüssing 	skb_pull_rcsum(skb_chk, offset);
51689afd85c9SLinus Lüssing 	ret = skb_chkf(skb_chk);
51699b368814SLinus Lüssing 	skb_push_rcsum(skb_chk, offset);
51709afd85c9SLinus Lüssing 
5171a516993fSLinus Lüssing 	if (ret)
5172a516993fSLinus Lüssing 		goto err;
51739afd85c9SLinus Lüssing 
51749afd85c9SLinus Lüssing 	return skb_chk;
5175a516993fSLinus Lüssing 
5176a516993fSLinus Lüssing err:
5177a516993fSLinus Lüssing 	if (skb_chk && skb_chk != skb)
5178a516993fSLinus Lüssing 		kfree_skb(skb_chk);
5179a516993fSLinus Lüssing 
5180a516993fSLinus Lüssing 	return NULL;
5181a516993fSLinus Lüssing 
51829afd85c9SLinus Lüssing }
51839afd85c9SLinus Lüssing EXPORT_SYMBOL(skb_checksum_trimmed);
51849afd85c9SLinus Lüssing 
51854497b076SBen Hutchings void __skb_warn_lro_forwarding(const struct sk_buff *skb)
51864497b076SBen Hutchings {
5187e87cc472SJoe Perches 	net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5188e87cc472SJoe Perches 			     skb->dev->name);
51894497b076SBen Hutchings }
51904497b076SBen Hutchings EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5191bad43ca8SEric Dumazet 
5192bad43ca8SEric Dumazet void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5193bad43ca8SEric Dumazet {
51943d861f66SEric Dumazet 	if (head_stolen) {
51953d861f66SEric Dumazet 		skb_release_head_state(skb);
5196bad43ca8SEric Dumazet 		kmem_cache_free(skbuff_head_cache, skb);
51973d861f66SEric Dumazet 	} else {
5198bad43ca8SEric Dumazet 		__kfree_skb(skb);
5199bad43ca8SEric Dumazet 	}
52003d861f66SEric Dumazet }
5201bad43ca8SEric Dumazet EXPORT_SYMBOL(kfree_skb_partial);
5202bad43ca8SEric Dumazet 
5203bad43ca8SEric Dumazet /**
5204bad43ca8SEric Dumazet  * skb_try_coalesce - try to merge skb to prior one
5205bad43ca8SEric Dumazet  * @to: prior buffer
5206bad43ca8SEric Dumazet  * @from: buffer to add
5207bad43ca8SEric Dumazet  * @fragstolen: pointer to boolean
5208c6c4b97cSRandy Dunlap  * @delta_truesize: how much more was allocated than was requested
5209bad43ca8SEric Dumazet  */
5210bad43ca8SEric Dumazet bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5211bad43ca8SEric Dumazet 		      bool *fragstolen, int *delta_truesize)
5212bad43ca8SEric Dumazet {
5213c818fa9eSEric Dumazet 	struct skb_shared_info *to_shinfo, *from_shinfo;
5214bad43ca8SEric Dumazet 	int i, delta, len = from->len;
5215bad43ca8SEric Dumazet 
5216bad43ca8SEric Dumazet 	*fragstolen = false;
5217bad43ca8SEric Dumazet 
5218bad43ca8SEric Dumazet 	if (skb_cloned(to))
5219bad43ca8SEric Dumazet 		return false;
5220bad43ca8SEric Dumazet 
52216a5bcd84SIlias Apalodimas 	/* The page pool signature of struct page will eventually figure out
52226a5bcd84SIlias Apalodimas 	 * which pages can be recycled or not but for now let's prohibit slab
52236a5bcd84SIlias Apalodimas 	 * allocated and page_pool allocated SKBs from being coalesced.
52246a5bcd84SIlias Apalodimas 	 */
52256a5bcd84SIlias Apalodimas 	if (to->pp_recycle != from->pp_recycle)
52266a5bcd84SIlias Apalodimas 		return false;
52276a5bcd84SIlias Apalodimas 
5228bad43ca8SEric Dumazet 	if (len <= skb_tailroom(to)) {
5229e93a0435SEric Dumazet 		if (len)
5230bad43ca8SEric Dumazet 			BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5231bad43ca8SEric Dumazet 		*delta_truesize = 0;
5232bad43ca8SEric Dumazet 		return true;
5233bad43ca8SEric Dumazet 	}
5234bad43ca8SEric Dumazet 
5235c818fa9eSEric Dumazet 	to_shinfo = skb_shinfo(to);
5236c818fa9eSEric Dumazet 	from_shinfo = skb_shinfo(from);
5237c818fa9eSEric Dumazet 	if (to_shinfo->frag_list || from_shinfo->frag_list)
5238bad43ca8SEric Dumazet 		return false;
52391f8b977aSWillem de Bruijn 	if (skb_zcopy(to) || skb_zcopy(from))
52401f8b977aSWillem de Bruijn 		return false;
5241bad43ca8SEric Dumazet 
5242bad43ca8SEric Dumazet 	if (skb_headlen(from) != 0) {
5243bad43ca8SEric Dumazet 		struct page *page;
5244bad43ca8SEric Dumazet 		unsigned int offset;
5245bad43ca8SEric Dumazet 
5246c818fa9eSEric Dumazet 		if (to_shinfo->nr_frags +
5247c818fa9eSEric Dumazet 		    from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5248bad43ca8SEric Dumazet 			return false;
5249bad43ca8SEric Dumazet 
5250bad43ca8SEric Dumazet 		if (skb_head_is_locked(from))
5251bad43ca8SEric Dumazet 			return false;
5252bad43ca8SEric Dumazet 
5253bad43ca8SEric Dumazet 		delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5254bad43ca8SEric Dumazet 
5255bad43ca8SEric Dumazet 		page = virt_to_head_page(from->head);
5256bad43ca8SEric Dumazet 		offset = from->data - (unsigned char *)page_address(page);
5257bad43ca8SEric Dumazet 
5258c818fa9eSEric Dumazet 		skb_fill_page_desc(to, to_shinfo->nr_frags,
5259bad43ca8SEric Dumazet 				   page, offset, skb_headlen(from));
5260bad43ca8SEric Dumazet 		*fragstolen = true;
5261bad43ca8SEric Dumazet 	} else {
5262c818fa9eSEric Dumazet 		if (to_shinfo->nr_frags +
5263c818fa9eSEric Dumazet 		    from_shinfo->nr_frags > MAX_SKB_FRAGS)
5264bad43ca8SEric Dumazet 			return false;
5265bad43ca8SEric Dumazet 
5266f4b549a5SWeiping Pan 		delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5267bad43ca8SEric Dumazet 	}
5268bad43ca8SEric Dumazet 
5269bad43ca8SEric Dumazet 	WARN_ON_ONCE(delta < len);
5270bad43ca8SEric Dumazet 
5271c818fa9eSEric Dumazet 	memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5272c818fa9eSEric Dumazet 	       from_shinfo->frags,
5273c818fa9eSEric Dumazet 	       from_shinfo->nr_frags * sizeof(skb_frag_t));
5274c818fa9eSEric Dumazet 	to_shinfo->nr_frags += from_shinfo->nr_frags;
5275bad43ca8SEric Dumazet 
5276bad43ca8SEric Dumazet 	if (!skb_cloned(from))
5277c818fa9eSEric Dumazet 		from_shinfo->nr_frags = 0;
5278bad43ca8SEric Dumazet 
52798ea853fdSLi RongQing 	/* if the skb is not cloned this does nothing
52808ea853fdSLi RongQing 	 * since we set nr_frags to 0.
52818ea853fdSLi RongQing 	 */
5282c818fa9eSEric Dumazet 	for (i = 0; i < from_shinfo->nr_frags; i++)
5283c818fa9eSEric Dumazet 		__skb_frag_ref(&from_shinfo->frags[i]);
5284bad43ca8SEric Dumazet 
5285bad43ca8SEric Dumazet 	to->truesize += delta;
5286bad43ca8SEric Dumazet 	to->len += len;
5287bad43ca8SEric Dumazet 	to->data_len += len;
5288bad43ca8SEric Dumazet 
5289bad43ca8SEric Dumazet 	*delta_truesize = delta;
5290bad43ca8SEric Dumazet 	return true;
5291bad43ca8SEric Dumazet }
5292bad43ca8SEric Dumazet EXPORT_SYMBOL(skb_try_coalesce);
5293621e84d6SNicolas Dichtel 
5294621e84d6SNicolas Dichtel /**
52958b27f277SNicolas Dichtel  * skb_scrub_packet - scrub an skb
5296621e84d6SNicolas Dichtel  *
5297621e84d6SNicolas Dichtel  * @skb: buffer to clean
52988b27f277SNicolas Dichtel  * @xnet: packet is crossing netns
5299621e84d6SNicolas Dichtel  *
53008b27f277SNicolas Dichtel  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
53018b27f277SNicolas Dichtel  * into/from a tunnel. Some information have to be cleared during these
53028b27f277SNicolas Dichtel  * operations.
53038b27f277SNicolas Dichtel  * skb_scrub_packet can also be used to clean a skb before injecting it in
53048b27f277SNicolas Dichtel  * another namespace (@xnet == true). We have to clear all information in the
53058b27f277SNicolas Dichtel  * skb that could impact namespace isolation.
5306621e84d6SNicolas Dichtel  */
53078b27f277SNicolas Dichtel void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5308621e84d6SNicolas Dichtel {
5309621e84d6SNicolas Dichtel 	skb->pkt_type = PACKET_HOST;
5310621e84d6SNicolas Dichtel 	skb->skb_iif = 0;
531160ff7467SWANG Cong 	skb->ignore_df = 0;
5312621e84d6SNicolas Dichtel 	skb_dst_drop(skb);
5313174e2381SFlorian Westphal 	skb_ext_reset(skb);
5314895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
5315621e84d6SNicolas Dichtel 	nf_reset_trace(skb);
5316213dd74aSHerbert Xu 
53176f9a5069SPetr Machata #ifdef CONFIG_NET_SWITCHDEV
53186f9a5069SPetr Machata 	skb->offload_fwd_mark = 0;
5319875e8939SIdo Schimmel 	skb->offload_l3_fwd_mark = 0;
53206f9a5069SPetr Machata #endif
53216f9a5069SPetr Machata 
5322213dd74aSHerbert Xu 	if (!xnet)
5323213dd74aSHerbert Xu 		return;
5324213dd74aSHerbert Xu 
53252b5ec1a5SYe Yin 	ipvs_reset(skb);
5326213dd74aSHerbert Xu 	skb->mark = 0;
5327c47d8c2fSJesus Sanchez-Palencia 	skb->tstamp = 0;
5328621e84d6SNicolas Dichtel }
5329621e84d6SNicolas Dichtel EXPORT_SYMBOL_GPL(skb_scrub_packet);
5330de960aa9SFlorian Westphal 
5331de960aa9SFlorian Westphal /**
5332de960aa9SFlorian Westphal  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5333de960aa9SFlorian Westphal  *
5334de960aa9SFlorian Westphal  * @skb: GSO skb
5335de960aa9SFlorian Westphal  *
5336de960aa9SFlorian Westphal  * skb_gso_transport_seglen is used to determine the real size of the
5337de960aa9SFlorian Westphal  * individual segments, including Layer4 headers (TCP/UDP).
5338de960aa9SFlorian Westphal  *
5339de960aa9SFlorian Westphal  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5340de960aa9SFlorian Westphal  */
5341a4a77718SDaniel Axtens static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5342de960aa9SFlorian Westphal {
5343de960aa9SFlorian Westphal 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
5344f993bc25SFlorian Westphal 	unsigned int thlen = 0;
5345f993bc25SFlorian Westphal 
5346f993bc25SFlorian Westphal 	if (skb->encapsulation) {
5347f993bc25SFlorian Westphal 		thlen = skb_inner_transport_header(skb) -
5348f993bc25SFlorian Westphal 			skb_transport_header(skb);
5349de960aa9SFlorian Westphal 
5350de960aa9SFlorian Westphal 		if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5351f993bc25SFlorian Westphal 			thlen += inner_tcp_hdrlen(skb);
5352f993bc25SFlorian Westphal 	} else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5353f993bc25SFlorian Westphal 		thlen = tcp_hdrlen(skb);
53541dd27cdeSDaniel Axtens 	} else if (unlikely(skb_is_gso_sctp(skb))) {
535590017accSMarcelo Ricardo Leitner 		thlen = sizeof(struct sctphdr);
5356ee80d1ebSWillem de Bruijn 	} else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5357ee80d1ebSWillem de Bruijn 		thlen = sizeof(struct udphdr);
5358f993bc25SFlorian Westphal 	}
53596d39d589SFlorian Westphal 	/* UFO sets gso_size to the size of the fragmentation
53606d39d589SFlorian Westphal 	 * payload, i.e. the size of the L4 (UDP) header is already
53616d39d589SFlorian Westphal 	 * accounted for.
53626d39d589SFlorian Westphal 	 */
5363f993bc25SFlorian Westphal 	return thlen + shinfo->gso_size;
5364de960aa9SFlorian Westphal }
5365a4a77718SDaniel Axtens 
5366a4a77718SDaniel Axtens /**
5367a4a77718SDaniel Axtens  * skb_gso_network_seglen - Return length of individual segments of a gso packet
5368a4a77718SDaniel Axtens  *
5369a4a77718SDaniel Axtens  * @skb: GSO skb
5370a4a77718SDaniel Axtens  *
5371a4a77718SDaniel Axtens  * skb_gso_network_seglen is used to determine the real size of the
5372a4a77718SDaniel Axtens  * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5373a4a77718SDaniel Axtens  *
5374a4a77718SDaniel Axtens  * The MAC/L2 header is not accounted for.
5375a4a77718SDaniel Axtens  */
5376a4a77718SDaniel Axtens static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5377a4a77718SDaniel Axtens {
5378a4a77718SDaniel Axtens 	unsigned int hdr_len = skb_transport_header(skb) -
5379a4a77718SDaniel Axtens 			       skb_network_header(skb);
5380a4a77718SDaniel Axtens 
5381a4a77718SDaniel Axtens 	return hdr_len + skb_gso_transport_seglen(skb);
5382a4a77718SDaniel Axtens }
5383a4a77718SDaniel Axtens 
5384a4a77718SDaniel Axtens /**
5385a4a77718SDaniel Axtens  * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5386a4a77718SDaniel Axtens  *
5387a4a77718SDaniel Axtens  * @skb: GSO skb
5388a4a77718SDaniel Axtens  *
5389a4a77718SDaniel Axtens  * skb_gso_mac_seglen is used to determine the real size of the
5390a4a77718SDaniel Axtens  * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5391a4a77718SDaniel Axtens  * headers (TCP/UDP).
5392a4a77718SDaniel Axtens  */
5393a4a77718SDaniel Axtens static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5394a4a77718SDaniel Axtens {
5395a4a77718SDaniel Axtens 	unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5396a4a77718SDaniel Axtens 
5397a4a77718SDaniel Axtens 	return hdr_len + skb_gso_transport_seglen(skb);
5398a4a77718SDaniel Axtens }
53990d5501c1SVlad Yasevich 
5400ae7ef81eSMarcelo Ricardo Leitner /**
54012b16f048SDaniel Axtens  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
54022b16f048SDaniel Axtens  *
54032b16f048SDaniel Axtens  * There are a couple of instances where we have a GSO skb, and we
54042b16f048SDaniel Axtens  * want to determine what size it would be after it is segmented.
54052b16f048SDaniel Axtens  *
54062b16f048SDaniel Axtens  * We might want to check:
54072b16f048SDaniel Axtens  * -    L3+L4+payload size (e.g. IP forwarding)
54082b16f048SDaniel Axtens  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
54092b16f048SDaniel Axtens  *
54102b16f048SDaniel Axtens  * This is a helper to do that correctly considering GSO_BY_FRAGS.
54112b16f048SDaniel Axtens  *
541249682bfaSMathieu Malaterre  * @skb: GSO skb
541349682bfaSMathieu Malaterre  *
54142b16f048SDaniel Axtens  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
54152b16f048SDaniel Axtens  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
54162b16f048SDaniel Axtens  *
54172b16f048SDaniel Axtens  * @max_len: The maximum permissible length.
54182b16f048SDaniel Axtens  *
54192b16f048SDaniel Axtens  * Returns true if the segmented length <= max length.
54202b16f048SDaniel Axtens  */
54212b16f048SDaniel Axtens static inline bool skb_gso_size_check(const struct sk_buff *skb,
54222b16f048SDaniel Axtens 				      unsigned int seg_len,
54232b16f048SDaniel Axtens 				      unsigned int max_len) {
54242b16f048SDaniel Axtens 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
54252b16f048SDaniel Axtens 	const struct sk_buff *iter;
54262b16f048SDaniel Axtens 
54272b16f048SDaniel Axtens 	if (shinfo->gso_size != GSO_BY_FRAGS)
54282b16f048SDaniel Axtens 		return seg_len <= max_len;
54292b16f048SDaniel Axtens 
54302b16f048SDaniel Axtens 	/* Undo this so we can re-use header sizes */
54312b16f048SDaniel Axtens 	seg_len -= GSO_BY_FRAGS;
54322b16f048SDaniel Axtens 
54332b16f048SDaniel Axtens 	skb_walk_frags(skb, iter) {
54342b16f048SDaniel Axtens 		if (seg_len + skb_headlen(iter) > max_len)
54352b16f048SDaniel Axtens 			return false;
54362b16f048SDaniel Axtens 	}
54372b16f048SDaniel Axtens 
54382b16f048SDaniel Axtens 	return true;
54392b16f048SDaniel Axtens }
54402b16f048SDaniel Axtens 
54412b16f048SDaniel Axtens /**
5442779b7931SDaniel Axtens  * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5443ae7ef81eSMarcelo Ricardo Leitner  *
5444ae7ef81eSMarcelo Ricardo Leitner  * @skb: GSO skb
544576f21b99SDavid S. Miller  * @mtu: MTU to validate against
5446ae7ef81eSMarcelo Ricardo Leitner  *
5447779b7931SDaniel Axtens  * skb_gso_validate_network_len validates if a given skb will fit a
5448779b7931SDaniel Axtens  * wanted MTU once split. It considers L3 headers, L4 headers, and the
5449779b7931SDaniel Axtens  * payload.
5450ae7ef81eSMarcelo Ricardo Leitner  */
5451779b7931SDaniel Axtens bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5452ae7ef81eSMarcelo Ricardo Leitner {
54532b16f048SDaniel Axtens 	return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5454ae7ef81eSMarcelo Ricardo Leitner }
5455779b7931SDaniel Axtens EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5456ae7ef81eSMarcelo Ricardo Leitner 
54572b16f048SDaniel Axtens /**
54582b16f048SDaniel Axtens  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
54592b16f048SDaniel Axtens  *
54602b16f048SDaniel Axtens  * @skb: GSO skb
54612b16f048SDaniel Axtens  * @len: length to validate against
54622b16f048SDaniel Axtens  *
54632b16f048SDaniel Axtens  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
54642b16f048SDaniel Axtens  * length once split, including L2, L3 and L4 headers and the payload.
54652b16f048SDaniel Axtens  */
54662b16f048SDaniel Axtens bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
54672b16f048SDaniel Axtens {
54682b16f048SDaniel Axtens 	return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
54692b16f048SDaniel Axtens }
54702b16f048SDaniel Axtens EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
54712b16f048SDaniel Axtens 
54720d5501c1SVlad Yasevich static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
54730d5501c1SVlad Yasevich {
5474d85e8be2SYuya Kusakabe 	int mac_len, meta_len;
5475d85e8be2SYuya Kusakabe 	void *meta;
54764bbb3e0eSToshiaki Makita 
54770d5501c1SVlad Yasevich 	if (skb_cow(skb, skb_headroom(skb)) < 0) {
54780d5501c1SVlad Yasevich 		kfree_skb(skb);
54790d5501c1SVlad Yasevich 		return NULL;
54800d5501c1SVlad Yasevich 	}
54810d5501c1SVlad Yasevich 
54824bbb3e0eSToshiaki Makita 	mac_len = skb->data - skb_mac_header(skb);
5483ae474573SToshiaki Makita 	if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
54844bbb3e0eSToshiaki Makita 		memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
54854bbb3e0eSToshiaki Makita 			mac_len - VLAN_HLEN - ETH_TLEN);
5486ae474573SToshiaki Makita 	}
5487d85e8be2SYuya Kusakabe 
5488d85e8be2SYuya Kusakabe 	meta_len = skb_metadata_len(skb);
5489d85e8be2SYuya Kusakabe 	if (meta_len) {
5490d85e8be2SYuya Kusakabe 		meta = skb_metadata_end(skb) - meta_len;
5491d85e8be2SYuya Kusakabe 		memmove(meta + VLAN_HLEN, meta, meta_len);
5492d85e8be2SYuya Kusakabe 	}
5493d85e8be2SYuya Kusakabe 
54940d5501c1SVlad Yasevich 	skb->mac_header += VLAN_HLEN;
54950d5501c1SVlad Yasevich 	return skb;
54960d5501c1SVlad Yasevich }
54970d5501c1SVlad Yasevich 
54980d5501c1SVlad Yasevich struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
54990d5501c1SVlad Yasevich {
55000d5501c1SVlad Yasevich 	struct vlan_hdr *vhdr;
55010d5501c1SVlad Yasevich 	u16 vlan_tci;
55020d5501c1SVlad Yasevich 
5503df8a39deSJiri Pirko 	if (unlikely(skb_vlan_tag_present(skb))) {
55040d5501c1SVlad Yasevich 		/* vlan_tci is already set-up so leave this for another time */
55050d5501c1SVlad Yasevich 		return skb;
55060d5501c1SVlad Yasevich 	}
55070d5501c1SVlad Yasevich 
55080d5501c1SVlad Yasevich 	skb = skb_share_check(skb, GFP_ATOMIC);
55090d5501c1SVlad Yasevich 	if (unlikely(!skb))
55100d5501c1SVlad Yasevich 		goto err_free;
551155eff0ebSMiaohe Lin 	/* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
551255eff0ebSMiaohe Lin 	if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
55130d5501c1SVlad Yasevich 		goto err_free;
55140d5501c1SVlad Yasevich 
55150d5501c1SVlad Yasevich 	vhdr = (struct vlan_hdr *)skb->data;
55160d5501c1SVlad Yasevich 	vlan_tci = ntohs(vhdr->h_vlan_TCI);
55170d5501c1SVlad Yasevich 	__vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
55180d5501c1SVlad Yasevich 
55190d5501c1SVlad Yasevich 	skb_pull_rcsum(skb, VLAN_HLEN);
55200d5501c1SVlad Yasevich 	vlan_set_encap_proto(skb, vhdr);
55210d5501c1SVlad Yasevich 
55220d5501c1SVlad Yasevich 	skb = skb_reorder_vlan_header(skb);
55230d5501c1SVlad Yasevich 	if (unlikely(!skb))
55240d5501c1SVlad Yasevich 		goto err_free;
55250d5501c1SVlad Yasevich 
55260d5501c1SVlad Yasevich 	skb_reset_network_header(skb);
55278be33ecfSAlexander Lobakin 	if (!skb_transport_header_was_set(skb))
55280d5501c1SVlad Yasevich 		skb_reset_transport_header(skb);
55290d5501c1SVlad Yasevich 	skb_reset_mac_len(skb);
55300d5501c1SVlad Yasevich 
55310d5501c1SVlad Yasevich 	return skb;
55320d5501c1SVlad Yasevich 
55330d5501c1SVlad Yasevich err_free:
55340d5501c1SVlad Yasevich 	kfree_skb(skb);
55350d5501c1SVlad Yasevich 	return NULL;
55360d5501c1SVlad Yasevich }
55370d5501c1SVlad Yasevich EXPORT_SYMBOL(skb_vlan_untag);
55382e4e4410SEric Dumazet 
5539e2195121SJiri Pirko int skb_ensure_writable(struct sk_buff *skb, int write_len)
5540e2195121SJiri Pirko {
5541e2195121SJiri Pirko 	if (!pskb_may_pull(skb, write_len))
5542e2195121SJiri Pirko 		return -ENOMEM;
5543e2195121SJiri Pirko 
5544e2195121SJiri Pirko 	if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5545e2195121SJiri Pirko 		return 0;
5546e2195121SJiri Pirko 
5547e2195121SJiri Pirko 	return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5548e2195121SJiri Pirko }
5549e2195121SJiri Pirko EXPORT_SYMBOL(skb_ensure_writable);
5550e2195121SJiri Pirko 
5551bfca4c52SShmulik Ladkani /* remove VLAN header from packet and update csum accordingly.
5552bfca4c52SShmulik Ladkani  * expects a non skb_vlan_tag_present skb with a vlan tag payload
5553bfca4c52SShmulik Ladkani  */
5554bfca4c52SShmulik Ladkani int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
555593515d53SJiri Pirko {
555693515d53SJiri Pirko 	struct vlan_hdr *vhdr;
5557b6a79208SShmulik Ladkani 	int offset = skb->data - skb_mac_header(skb);
555893515d53SJiri Pirko 	int err;
555993515d53SJiri Pirko 
5560b6a79208SShmulik Ladkani 	if (WARN_ONCE(offset,
5561b6a79208SShmulik Ladkani 		      "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5562b6a79208SShmulik Ladkani 		      offset)) {
5563b6a79208SShmulik Ladkani 		return -EINVAL;
5564b6a79208SShmulik Ladkani 	}
5565b6a79208SShmulik Ladkani 
556693515d53SJiri Pirko 	err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
556793515d53SJiri Pirko 	if (unlikely(err))
5568b6a79208SShmulik Ladkani 		return err;
556993515d53SJiri Pirko 
557093515d53SJiri Pirko 	skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
557193515d53SJiri Pirko 
557293515d53SJiri Pirko 	vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
557393515d53SJiri Pirko 	*vlan_tci = ntohs(vhdr->h_vlan_TCI);
557493515d53SJiri Pirko 
557593515d53SJiri Pirko 	memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
557693515d53SJiri Pirko 	__skb_pull(skb, VLAN_HLEN);
557793515d53SJiri Pirko 
557893515d53SJiri Pirko 	vlan_set_encap_proto(skb, vhdr);
557993515d53SJiri Pirko 	skb->mac_header += VLAN_HLEN;
558093515d53SJiri Pirko 
558193515d53SJiri Pirko 	if (skb_network_offset(skb) < ETH_HLEN)
558293515d53SJiri Pirko 		skb_set_network_header(skb, ETH_HLEN);
558393515d53SJiri Pirko 
558493515d53SJiri Pirko 	skb_reset_mac_len(skb);
558593515d53SJiri Pirko 
558693515d53SJiri Pirko 	return err;
558793515d53SJiri Pirko }
5588bfca4c52SShmulik Ladkani EXPORT_SYMBOL(__skb_vlan_pop);
558993515d53SJiri Pirko 
5590b6a79208SShmulik Ladkani /* Pop a vlan tag either from hwaccel or from payload.
5591b6a79208SShmulik Ladkani  * Expects skb->data at mac header.
5592b6a79208SShmulik Ladkani  */
559393515d53SJiri Pirko int skb_vlan_pop(struct sk_buff *skb)
559493515d53SJiri Pirko {
559593515d53SJiri Pirko 	u16 vlan_tci;
559693515d53SJiri Pirko 	__be16 vlan_proto;
559793515d53SJiri Pirko 	int err;
559893515d53SJiri Pirko 
5599df8a39deSJiri Pirko 	if (likely(skb_vlan_tag_present(skb))) {
5600b1817524SMichał Mirosław 		__vlan_hwaccel_clear_tag(skb);
560193515d53SJiri Pirko 	} else {
5602ecf4ee41SShmulik Ladkani 		if (unlikely(!eth_type_vlan(skb->protocol)))
560393515d53SJiri Pirko 			return 0;
560493515d53SJiri Pirko 
560593515d53SJiri Pirko 		err = __skb_vlan_pop(skb, &vlan_tci);
560693515d53SJiri Pirko 		if (err)
560793515d53SJiri Pirko 			return err;
560893515d53SJiri Pirko 	}
560993515d53SJiri Pirko 	/* move next vlan tag to hw accel tag */
5610ecf4ee41SShmulik Ladkani 	if (likely(!eth_type_vlan(skb->protocol)))
561193515d53SJiri Pirko 		return 0;
561293515d53SJiri Pirko 
561393515d53SJiri Pirko 	vlan_proto = skb->protocol;
561493515d53SJiri Pirko 	err = __skb_vlan_pop(skb, &vlan_tci);
561593515d53SJiri Pirko 	if (unlikely(err))
561693515d53SJiri Pirko 		return err;
561793515d53SJiri Pirko 
561893515d53SJiri Pirko 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
561993515d53SJiri Pirko 	return 0;
562093515d53SJiri Pirko }
562193515d53SJiri Pirko EXPORT_SYMBOL(skb_vlan_pop);
562293515d53SJiri Pirko 
5623b6a79208SShmulik Ladkani /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5624b6a79208SShmulik Ladkani  * Expects skb->data at mac header.
5625b6a79208SShmulik Ladkani  */
562693515d53SJiri Pirko int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
562793515d53SJiri Pirko {
5628df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb)) {
5629b6a79208SShmulik Ladkani 		int offset = skb->data - skb_mac_header(skb);
563093515d53SJiri Pirko 		int err;
563193515d53SJiri Pirko 
5632b6a79208SShmulik Ladkani 		if (WARN_ONCE(offset,
5633b6a79208SShmulik Ladkani 			      "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5634b6a79208SShmulik Ladkani 			      offset)) {
5635b6a79208SShmulik Ladkani 			return -EINVAL;
5636b6a79208SShmulik Ladkani 		}
5637b6a79208SShmulik Ladkani 
563893515d53SJiri Pirko 		err = __vlan_insert_tag(skb, skb->vlan_proto,
5639df8a39deSJiri Pirko 					skb_vlan_tag_get(skb));
5640b6a79208SShmulik Ladkani 		if (err)
564193515d53SJiri Pirko 			return err;
56429241e2dfSDaniel Borkmann 
564393515d53SJiri Pirko 		skb->protocol = skb->vlan_proto;
564493515d53SJiri Pirko 		skb->mac_len += VLAN_HLEN;
564593515d53SJiri Pirko 
56466b83d28aSDaniel Borkmann 		skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
564793515d53SJiri Pirko 	}
564893515d53SJiri Pirko 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
564993515d53SJiri Pirko 	return 0;
565093515d53SJiri Pirko }
565193515d53SJiri Pirko EXPORT_SYMBOL(skb_vlan_push);
565293515d53SJiri Pirko 
565319fbcb36SGuillaume Nault /**
565419fbcb36SGuillaume Nault  * skb_eth_pop() - Drop the Ethernet header at the head of a packet
565519fbcb36SGuillaume Nault  *
565619fbcb36SGuillaume Nault  * @skb: Socket buffer to modify
565719fbcb36SGuillaume Nault  *
565819fbcb36SGuillaume Nault  * Drop the Ethernet header of @skb.
565919fbcb36SGuillaume Nault  *
566019fbcb36SGuillaume Nault  * Expects that skb->data points to the mac header and that no VLAN tags are
566119fbcb36SGuillaume Nault  * present.
566219fbcb36SGuillaume Nault  *
566319fbcb36SGuillaume Nault  * Returns 0 on success, -errno otherwise.
566419fbcb36SGuillaume Nault  */
566519fbcb36SGuillaume Nault int skb_eth_pop(struct sk_buff *skb)
566619fbcb36SGuillaume Nault {
566719fbcb36SGuillaume Nault 	if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
566819fbcb36SGuillaume Nault 	    skb_network_offset(skb) < ETH_HLEN)
566919fbcb36SGuillaume Nault 		return -EPROTO;
567019fbcb36SGuillaume Nault 
567119fbcb36SGuillaume Nault 	skb_pull_rcsum(skb, ETH_HLEN);
567219fbcb36SGuillaume Nault 	skb_reset_mac_header(skb);
567319fbcb36SGuillaume Nault 	skb_reset_mac_len(skb);
567419fbcb36SGuillaume Nault 
567519fbcb36SGuillaume Nault 	return 0;
567619fbcb36SGuillaume Nault }
567719fbcb36SGuillaume Nault EXPORT_SYMBOL(skb_eth_pop);
567819fbcb36SGuillaume Nault 
567919fbcb36SGuillaume Nault /**
568019fbcb36SGuillaume Nault  * skb_eth_push() - Add a new Ethernet header at the head of a packet
568119fbcb36SGuillaume Nault  *
568219fbcb36SGuillaume Nault  * @skb: Socket buffer to modify
568319fbcb36SGuillaume Nault  * @dst: Destination MAC address of the new header
568419fbcb36SGuillaume Nault  * @src: Source MAC address of the new header
568519fbcb36SGuillaume Nault  *
568619fbcb36SGuillaume Nault  * Prepend @skb with a new Ethernet header.
568719fbcb36SGuillaume Nault  *
568819fbcb36SGuillaume Nault  * Expects that skb->data points to the mac header, which must be empty.
568919fbcb36SGuillaume Nault  *
569019fbcb36SGuillaume Nault  * Returns 0 on success, -errno otherwise.
569119fbcb36SGuillaume Nault  */
569219fbcb36SGuillaume Nault int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
569319fbcb36SGuillaume Nault 		 const unsigned char *src)
569419fbcb36SGuillaume Nault {
569519fbcb36SGuillaume Nault 	struct ethhdr *eth;
569619fbcb36SGuillaume Nault 	int err;
569719fbcb36SGuillaume Nault 
569819fbcb36SGuillaume Nault 	if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
569919fbcb36SGuillaume Nault 		return -EPROTO;
570019fbcb36SGuillaume Nault 
570119fbcb36SGuillaume Nault 	err = skb_cow_head(skb, sizeof(*eth));
570219fbcb36SGuillaume Nault 	if (err < 0)
570319fbcb36SGuillaume Nault 		return err;
570419fbcb36SGuillaume Nault 
570519fbcb36SGuillaume Nault 	skb_push(skb, sizeof(*eth));
570619fbcb36SGuillaume Nault 	skb_reset_mac_header(skb);
570719fbcb36SGuillaume Nault 	skb_reset_mac_len(skb);
570819fbcb36SGuillaume Nault 
570919fbcb36SGuillaume Nault 	eth = eth_hdr(skb);
571019fbcb36SGuillaume Nault 	ether_addr_copy(eth->h_dest, dst);
571119fbcb36SGuillaume Nault 	ether_addr_copy(eth->h_source, src);
571219fbcb36SGuillaume Nault 	eth->h_proto = skb->protocol;
571319fbcb36SGuillaume Nault 
571419fbcb36SGuillaume Nault 	skb_postpush_rcsum(skb, eth, sizeof(*eth));
571519fbcb36SGuillaume Nault 
571619fbcb36SGuillaume Nault 	return 0;
571719fbcb36SGuillaume Nault }
571819fbcb36SGuillaume Nault EXPORT_SYMBOL(skb_eth_push);
571919fbcb36SGuillaume Nault 
57208822e270SJohn Hurley /* Update the ethertype of hdr and the skb csum value if required. */
57218822e270SJohn Hurley static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
57228822e270SJohn Hurley 			     __be16 ethertype)
57238822e270SJohn Hurley {
57248822e270SJohn Hurley 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
57258822e270SJohn Hurley 		__be16 diff[] = { ~hdr->h_proto, ethertype };
57268822e270SJohn Hurley 
57278822e270SJohn Hurley 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
57288822e270SJohn Hurley 	}
57298822e270SJohn Hurley 
57308822e270SJohn Hurley 	hdr->h_proto = ethertype;
57318822e270SJohn Hurley }
57328822e270SJohn Hurley 
57338822e270SJohn Hurley /**
5734e7dbfed1SMartin Varghese  * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5735e7dbfed1SMartin Varghese  *                   the packet
57368822e270SJohn Hurley  *
57378822e270SJohn Hurley  * @skb: buffer
57388822e270SJohn Hurley  * @mpls_lse: MPLS label stack entry to push
57398822e270SJohn Hurley  * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5740fa4e0f88SDavide Caratti  * @mac_len: length of the MAC header
5741e7dbfed1SMartin Varghese  * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5742e7dbfed1SMartin Varghese  *            ethernet
57438822e270SJohn Hurley  *
57448822e270SJohn Hurley  * Expects skb->data at mac header.
57458822e270SJohn Hurley  *
57468822e270SJohn Hurley  * Returns 0 on success, -errno otherwise.
57478822e270SJohn Hurley  */
5748fa4e0f88SDavide Caratti int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5749d04ac224SMartin Varghese 		  int mac_len, bool ethernet)
57508822e270SJohn Hurley {
57518822e270SJohn Hurley 	struct mpls_shim_hdr *lse;
57528822e270SJohn Hurley 	int err;
57538822e270SJohn Hurley 
57548822e270SJohn Hurley 	if (unlikely(!eth_p_mpls(mpls_proto)))
57558822e270SJohn Hurley 		return -EINVAL;
57568822e270SJohn Hurley 
57578822e270SJohn Hurley 	/* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
57588822e270SJohn Hurley 	if (skb->encapsulation)
57598822e270SJohn Hurley 		return -EINVAL;
57608822e270SJohn Hurley 
57618822e270SJohn Hurley 	err = skb_cow_head(skb, MPLS_HLEN);
57628822e270SJohn Hurley 	if (unlikely(err))
57638822e270SJohn Hurley 		return err;
57648822e270SJohn Hurley 
57658822e270SJohn Hurley 	if (!skb->inner_protocol) {
5766e7dbfed1SMartin Varghese 		skb_set_inner_network_header(skb, skb_network_offset(skb));
57678822e270SJohn Hurley 		skb_set_inner_protocol(skb, skb->protocol);
57688822e270SJohn Hurley 	}
57698822e270SJohn Hurley 
57708822e270SJohn Hurley 	skb_push(skb, MPLS_HLEN);
57718822e270SJohn Hurley 	memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5772fa4e0f88SDavide Caratti 		mac_len);
57738822e270SJohn Hurley 	skb_reset_mac_header(skb);
5774fa4e0f88SDavide Caratti 	skb_set_network_header(skb, mac_len);
5775e7dbfed1SMartin Varghese 	skb_reset_mac_len(skb);
57768822e270SJohn Hurley 
57778822e270SJohn Hurley 	lse = mpls_hdr(skb);
57788822e270SJohn Hurley 	lse->label_stack_entry = mpls_lse;
57798822e270SJohn Hurley 	skb_postpush_rcsum(skb, lse, MPLS_HLEN);
57808822e270SJohn Hurley 
57814296adc3SGuillaume Nault 	if (ethernet && mac_len >= ETH_HLEN)
57828822e270SJohn Hurley 		skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
57838822e270SJohn Hurley 	skb->protocol = mpls_proto;
57848822e270SJohn Hurley 
57858822e270SJohn Hurley 	return 0;
57868822e270SJohn Hurley }
57878822e270SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_push);
57888822e270SJohn Hurley 
57892e4e4410SEric Dumazet /**
5790ed246ceeSJohn Hurley  * skb_mpls_pop() - pop the outermost MPLS header
5791ed246ceeSJohn Hurley  *
5792ed246ceeSJohn Hurley  * @skb: buffer
5793ed246ceeSJohn Hurley  * @next_proto: ethertype of header after popped MPLS header
5794fa4e0f88SDavide Caratti  * @mac_len: length of the MAC header
579576f99f98SMartin Varghese  * @ethernet: flag to indicate if the packet is ethernet
5796ed246ceeSJohn Hurley  *
5797ed246ceeSJohn Hurley  * Expects skb->data at mac header.
5798ed246ceeSJohn Hurley  *
5799ed246ceeSJohn Hurley  * Returns 0 on success, -errno otherwise.
5800ed246ceeSJohn Hurley  */
5801040b5cfbSMartin Varghese int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5802040b5cfbSMartin Varghese 		 bool ethernet)
5803ed246ceeSJohn Hurley {
5804ed246ceeSJohn Hurley 	int err;
5805ed246ceeSJohn Hurley 
5806ed246ceeSJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
5807dedc5a08SDavide Caratti 		return 0;
5808ed246ceeSJohn Hurley 
5809fa4e0f88SDavide Caratti 	err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5810ed246ceeSJohn Hurley 	if (unlikely(err))
5811ed246ceeSJohn Hurley 		return err;
5812ed246ceeSJohn Hurley 
5813ed246ceeSJohn Hurley 	skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5814ed246ceeSJohn Hurley 	memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5815fa4e0f88SDavide Caratti 		mac_len);
5816ed246ceeSJohn Hurley 
5817ed246ceeSJohn Hurley 	__skb_pull(skb, MPLS_HLEN);
5818ed246ceeSJohn Hurley 	skb_reset_mac_header(skb);
5819fa4e0f88SDavide Caratti 	skb_set_network_header(skb, mac_len);
5820ed246ceeSJohn Hurley 
58214296adc3SGuillaume Nault 	if (ethernet && mac_len >= ETH_HLEN) {
5822ed246ceeSJohn Hurley 		struct ethhdr *hdr;
5823ed246ceeSJohn Hurley 
5824ed246ceeSJohn Hurley 		/* use mpls_hdr() to get ethertype to account for VLANs. */
5825ed246ceeSJohn Hurley 		hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5826ed246ceeSJohn Hurley 		skb_mod_eth_type(skb, hdr, next_proto);
5827ed246ceeSJohn Hurley 	}
5828ed246ceeSJohn Hurley 	skb->protocol = next_proto;
5829ed246ceeSJohn Hurley 
5830ed246ceeSJohn Hurley 	return 0;
5831ed246ceeSJohn Hurley }
5832ed246ceeSJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_pop);
5833ed246ceeSJohn Hurley 
5834ed246ceeSJohn Hurley /**
5835d27cf5c5SJohn Hurley  * skb_mpls_update_lse() - modify outermost MPLS header and update csum
5836d27cf5c5SJohn Hurley  *
5837d27cf5c5SJohn Hurley  * @skb: buffer
5838d27cf5c5SJohn Hurley  * @mpls_lse: new MPLS label stack entry to update to
5839d27cf5c5SJohn Hurley  *
5840d27cf5c5SJohn Hurley  * Expects skb->data at mac header.
5841d27cf5c5SJohn Hurley  *
5842d27cf5c5SJohn Hurley  * Returns 0 on success, -errno otherwise.
5843d27cf5c5SJohn Hurley  */
5844d27cf5c5SJohn Hurley int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
5845d27cf5c5SJohn Hurley {
5846d27cf5c5SJohn Hurley 	int err;
5847d27cf5c5SJohn Hurley 
5848d27cf5c5SJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
5849d27cf5c5SJohn Hurley 		return -EINVAL;
5850d27cf5c5SJohn Hurley 
5851d27cf5c5SJohn Hurley 	err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
5852d27cf5c5SJohn Hurley 	if (unlikely(err))
5853d27cf5c5SJohn Hurley 		return err;
5854d27cf5c5SJohn Hurley 
5855d27cf5c5SJohn Hurley 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
5856d27cf5c5SJohn Hurley 		__be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
5857d27cf5c5SJohn Hurley 
5858d27cf5c5SJohn Hurley 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5859d27cf5c5SJohn Hurley 	}
5860d27cf5c5SJohn Hurley 
5861d27cf5c5SJohn Hurley 	mpls_hdr(skb)->label_stack_entry = mpls_lse;
5862d27cf5c5SJohn Hurley 
5863d27cf5c5SJohn Hurley 	return 0;
5864d27cf5c5SJohn Hurley }
5865d27cf5c5SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
5866d27cf5c5SJohn Hurley 
5867d27cf5c5SJohn Hurley /**
58682a2ea508SJohn Hurley  * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
58692a2ea508SJohn Hurley  *
58702a2ea508SJohn Hurley  * @skb: buffer
58712a2ea508SJohn Hurley  *
58722a2ea508SJohn Hurley  * Expects skb->data at mac header.
58732a2ea508SJohn Hurley  *
58742a2ea508SJohn Hurley  * Returns 0 on success, -errno otherwise.
58752a2ea508SJohn Hurley  */
58762a2ea508SJohn Hurley int skb_mpls_dec_ttl(struct sk_buff *skb)
58772a2ea508SJohn Hurley {
58782a2ea508SJohn Hurley 	u32 lse;
58792a2ea508SJohn Hurley 	u8 ttl;
58802a2ea508SJohn Hurley 
58812a2ea508SJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
58822a2ea508SJohn Hurley 		return -EINVAL;
58832a2ea508SJohn Hurley 
588413de4ed9SDavide Caratti 	if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
588513de4ed9SDavide Caratti 		return -ENOMEM;
588613de4ed9SDavide Caratti 
58872a2ea508SJohn Hurley 	lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
58882a2ea508SJohn Hurley 	ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
58892a2ea508SJohn Hurley 	if (!--ttl)
58902a2ea508SJohn Hurley 		return -EINVAL;
58912a2ea508SJohn Hurley 
58922a2ea508SJohn Hurley 	lse &= ~MPLS_LS_TTL_MASK;
58932a2ea508SJohn Hurley 	lse |= ttl << MPLS_LS_TTL_SHIFT;
58942a2ea508SJohn Hurley 
58952a2ea508SJohn Hurley 	return skb_mpls_update_lse(skb, cpu_to_be32(lse));
58962a2ea508SJohn Hurley }
58972a2ea508SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
58982a2ea508SJohn Hurley 
58992a2ea508SJohn Hurley /**
59002e4e4410SEric Dumazet  * alloc_skb_with_frags - allocate skb with page frags
59012e4e4410SEric Dumazet  *
5902de3f0d0eSMasanari Iida  * @header_len: size of linear part
5903de3f0d0eSMasanari Iida  * @data_len: needed length in frags
5904de3f0d0eSMasanari Iida  * @max_page_order: max page order desired.
5905de3f0d0eSMasanari Iida  * @errcode: pointer to error code if any
5906de3f0d0eSMasanari Iida  * @gfp_mask: allocation mask
59072e4e4410SEric Dumazet  *
59082e4e4410SEric Dumazet  * This can be used to allocate a paged skb, given a maximal order for frags.
59092e4e4410SEric Dumazet  */
59102e4e4410SEric Dumazet struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
59112e4e4410SEric Dumazet 				     unsigned long data_len,
59122e4e4410SEric Dumazet 				     int max_page_order,
59132e4e4410SEric Dumazet 				     int *errcode,
59142e4e4410SEric Dumazet 				     gfp_t gfp_mask)
59152e4e4410SEric Dumazet {
59162e4e4410SEric Dumazet 	int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
59172e4e4410SEric Dumazet 	unsigned long chunk;
59182e4e4410SEric Dumazet 	struct sk_buff *skb;
59192e4e4410SEric Dumazet 	struct page *page;
59202e4e4410SEric Dumazet 	int i;
59212e4e4410SEric Dumazet 
59222e4e4410SEric Dumazet 	*errcode = -EMSGSIZE;
59232e4e4410SEric Dumazet 	/* Note this test could be relaxed, if we succeed to allocate
59242e4e4410SEric Dumazet 	 * high order pages...
59252e4e4410SEric Dumazet 	 */
59262e4e4410SEric Dumazet 	if (npages > MAX_SKB_FRAGS)
59272e4e4410SEric Dumazet 		return NULL;
59282e4e4410SEric Dumazet 
59292e4e4410SEric Dumazet 	*errcode = -ENOBUFS;
5930f8c468e8SDavid Rientjes 	skb = alloc_skb(header_len, gfp_mask);
59312e4e4410SEric Dumazet 	if (!skb)
59322e4e4410SEric Dumazet 		return NULL;
59332e4e4410SEric Dumazet 
59342e4e4410SEric Dumazet 	skb->truesize += npages << PAGE_SHIFT;
59352e4e4410SEric Dumazet 
59362e4e4410SEric Dumazet 	for (i = 0; npages > 0; i++) {
59372e4e4410SEric Dumazet 		int order = max_page_order;
59382e4e4410SEric Dumazet 
59392e4e4410SEric Dumazet 		while (order) {
59402e4e4410SEric Dumazet 			if (npages >= 1 << order) {
5941d0164adcSMel Gorman 				page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
59422e4e4410SEric Dumazet 						   __GFP_COMP |
5943d14b56f5SMichal Hocko 						   __GFP_NOWARN,
59442e4e4410SEric Dumazet 						   order);
59452e4e4410SEric Dumazet 				if (page)
59462e4e4410SEric Dumazet 					goto fill_page;
59472e4e4410SEric Dumazet 				/* Do not retry other high order allocations */
59482e4e4410SEric Dumazet 				order = 1;
59492e4e4410SEric Dumazet 				max_page_order = 0;
59502e4e4410SEric Dumazet 			}
59512e4e4410SEric Dumazet 			order--;
59522e4e4410SEric Dumazet 		}
59532e4e4410SEric Dumazet 		page = alloc_page(gfp_mask);
59542e4e4410SEric Dumazet 		if (!page)
59552e4e4410SEric Dumazet 			goto failure;
59562e4e4410SEric Dumazet fill_page:
59572e4e4410SEric Dumazet 		chunk = min_t(unsigned long, data_len,
59582e4e4410SEric Dumazet 			      PAGE_SIZE << order);
59592e4e4410SEric Dumazet 		skb_fill_page_desc(skb, i, page, 0, chunk);
59602e4e4410SEric Dumazet 		data_len -= chunk;
59612e4e4410SEric Dumazet 		npages -= 1 << order;
59622e4e4410SEric Dumazet 	}
59632e4e4410SEric Dumazet 	return skb;
59642e4e4410SEric Dumazet 
59652e4e4410SEric Dumazet failure:
59662e4e4410SEric Dumazet 	kfree_skb(skb);
59672e4e4410SEric Dumazet 	return NULL;
59682e4e4410SEric Dumazet }
59692e4e4410SEric Dumazet EXPORT_SYMBOL(alloc_skb_with_frags);
59706fa01ccdSSowmini Varadhan 
59716fa01ccdSSowmini Varadhan /* carve out the first off bytes from skb when off < headlen */
59726fa01ccdSSowmini Varadhan static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
59736fa01ccdSSowmini Varadhan 				    const int headlen, gfp_t gfp_mask)
59746fa01ccdSSowmini Varadhan {
59756fa01ccdSSowmini Varadhan 	int i;
59766fa01ccdSSowmini Varadhan 	int size = skb_end_offset(skb);
59776fa01ccdSSowmini Varadhan 	int new_hlen = headlen - off;
59786fa01ccdSSowmini Varadhan 	u8 *data;
59796fa01ccdSSowmini Varadhan 
59806fa01ccdSSowmini Varadhan 	size = SKB_DATA_ALIGN(size);
59816fa01ccdSSowmini Varadhan 
59826fa01ccdSSowmini Varadhan 	if (skb_pfmemalloc(skb))
59836fa01ccdSSowmini Varadhan 		gfp_mask |= __GFP_MEMALLOC;
59846fa01ccdSSowmini Varadhan 	data = kmalloc_reserve(size +
59856fa01ccdSSowmini Varadhan 			       SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
59866fa01ccdSSowmini Varadhan 			       gfp_mask, NUMA_NO_NODE, NULL);
59876fa01ccdSSowmini Varadhan 	if (!data)
59886fa01ccdSSowmini Varadhan 		return -ENOMEM;
59896fa01ccdSSowmini Varadhan 
59906fa01ccdSSowmini Varadhan 	size = SKB_WITH_OVERHEAD(ksize(data));
59916fa01ccdSSowmini Varadhan 
59926fa01ccdSSowmini Varadhan 	/* Copy real data, and all frags */
59936fa01ccdSSowmini Varadhan 	skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
59946fa01ccdSSowmini Varadhan 	skb->len -= off;
59956fa01ccdSSowmini Varadhan 
59966fa01ccdSSowmini Varadhan 	memcpy((struct skb_shared_info *)(data + size),
59976fa01ccdSSowmini Varadhan 	       skb_shinfo(skb),
59986fa01ccdSSowmini Varadhan 	       offsetof(struct skb_shared_info,
59996fa01ccdSSowmini Varadhan 			frags[skb_shinfo(skb)->nr_frags]));
60006fa01ccdSSowmini Varadhan 	if (skb_cloned(skb)) {
60016fa01ccdSSowmini Varadhan 		/* drop the old head gracefully */
60026fa01ccdSSowmini Varadhan 		if (skb_orphan_frags(skb, gfp_mask)) {
60036fa01ccdSSowmini Varadhan 			kfree(data);
60046fa01ccdSSowmini Varadhan 			return -ENOMEM;
60056fa01ccdSSowmini Varadhan 		}
60066fa01ccdSSowmini Varadhan 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
60076fa01ccdSSowmini Varadhan 			skb_frag_ref(skb, i);
60086fa01ccdSSowmini Varadhan 		if (skb_has_frag_list(skb))
60096fa01ccdSSowmini Varadhan 			skb_clone_fraglist(skb);
60106fa01ccdSSowmini Varadhan 		skb_release_data(skb);
60116fa01ccdSSowmini Varadhan 	} else {
60126fa01ccdSSowmini Varadhan 		/* we can reuse existing recount- all we did was
60136fa01ccdSSowmini Varadhan 		 * relocate values
60146fa01ccdSSowmini Varadhan 		 */
60156fa01ccdSSowmini Varadhan 		skb_free_head(skb);
60166fa01ccdSSowmini Varadhan 	}
60176fa01ccdSSowmini Varadhan 
60186fa01ccdSSowmini Varadhan 	skb->head = data;
60196fa01ccdSSowmini Varadhan 	skb->data = data;
60206fa01ccdSSowmini Varadhan 	skb->head_frag = 0;
60216fa01ccdSSowmini Varadhan #ifdef NET_SKBUFF_DATA_USES_OFFSET
60226fa01ccdSSowmini Varadhan 	skb->end = size;
60236fa01ccdSSowmini Varadhan #else
60246fa01ccdSSowmini Varadhan 	skb->end = skb->head + size;
60256fa01ccdSSowmini Varadhan #endif
60266fa01ccdSSowmini Varadhan 	skb_set_tail_pointer(skb, skb_headlen(skb));
60276fa01ccdSSowmini Varadhan 	skb_headers_offset_update(skb, 0);
60286fa01ccdSSowmini Varadhan 	skb->cloned = 0;
60296fa01ccdSSowmini Varadhan 	skb->hdr_len = 0;
60306fa01ccdSSowmini Varadhan 	skb->nohdr = 0;
60316fa01ccdSSowmini Varadhan 	atomic_set(&skb_shinfo(skb)->dataref, 1);
60326fa01ccdSSowmini Varadhan 
60336fa01ccdSSowmini Varadhan 	return 0;
60346fa01ccdSSowmini Varadhan }
60356fa01ccdSSowmini Varadhan 
60366fa01ccdSSowmini Varadhan static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
60376fa01ccdSSowmini Varadhan 
60386fa01ccdSSowmini Varadhan /* carve out the first eat bytes from skb's frag_list. May recurse into
60396fa01ccdSSowmini Varadhan  * pskb_carve()
60406fa01ccdSSowmini Varadhan  */
60416fa01ccdSSowmini Varadhan static int pskb_carve_frag_list(struct sk_buff *skb,
60426fa01ccdSSowmini Varadhan 				struct skb_shared_info *shinfo, int eat,
60436fa01ccdSSowmini Varadhan 				gfp_t gfp_mask)
60446fa01ccdSSowmini Varadhan {
60456fa01ccdSSowmini Varadhan 	struct sk_buff *list = shinfo->frag_list;
60466fa01ccdSSowmini Varadhan 	struct sk_buff *clone = NULL;
60476fa01ccdSSowmini Varadhan 	struct sk_buff *insp = NULL;
60486fa01ccdSSowmini Varadhan 
60496fa01ccdSSowmini Varadhan 	do {
60506fa01ccdSSowmini Varadhan 		if (!list) {
60516fa01ccdSSowmini Varadhan 			pr_err("Not enough bytes to eat. Want %d\n", eat);
60526fa01ccdSSowmini Varadhan 			return -EFAULT;
60536fa01ccdSSowmini Varadhan 		}
60546fa01ccdSSowmini Varadhan 		if (list->len <= eat) {
60556fa01ccdSSowmini Varadhan 			/* Eaten as whole. */
60566fa01ccdSSowmini Varadhan 			eat -= list->len;
60576fa01ccdSSowmini Varadhan 			list = list->next;
60586fa01ccdSSowmini Varadhan 			insp = list;
60596fa01ccdSSowmini Varadhan 		} else {
60606fa01ccdSSowmini Varadhan 			/* Eaten partially. */
60616fa01ccdSSowmini Varadhan 			if (skb_shared(list)) {
60626fa01ccdSSowmini Varadhan 				clone = skb_clone(list, gfp_mask);
60636fa01ccdSSowmini Varadhan 				if (!clone)
60646fa01ccdSSowmini Varadhan 					return -ENOMEM;
60656fa01ccdSSowmini Varadhan 				insp = list->next;
60666fa01ccdSSowmini Varadhan 				list = clone;
60676fa01ccdSSowmini Varadhan 			} else {
60686fa01ccdSSowmini Varadhan 				/* This may be pulled without problems. */
60696fa01ccdSSowmini Varadhan 				insp = list;
60706fa01ccdSSowmini Varadhan 			}
60716fa01ccdSSowmini Varadhan 			if (pskb_carve(list, eat, gfp_mask) < 0) {
60726fa01ccdSSowmini Varadhan 				kfree_skb(clone);
60736fa01ccdSSowmini Varadhan 				return -ENOMEM;
60746fa01ccdSSowmini Varadhan 			}
60756fa01ccdSSowmini Varadhan 			break;
60766fa01ccdSSowmini Varadhan 		}
60776fa01ccdSSowmini Varadhan 	} while (eat);
60786fa01ccdSSowmini Varadhan 
60796fa01ccdSSowmini Varadhan 	/* Free pulled out fragments. */
60806fa01ccdSSowmini Varadhan 	while ((list = shinfo->frag_list) != insp) {
60816fa01ccdSSowmini Varadhan 		shinfo->frag_list = list->next;
60826fa01ccdSSowmini Varadhan 		kfree_skb(list);
60836fa01ccdSSowmini Varadhan 	}
60846fa01ccdSSowmini Varadhan 	/* And insert new clone at head. */
60856fa01ccdSSowmini Varadhan 	if (clone) {
60866fa01ccdSSowmini Varadhan 		clone->next = list;
60876fa01ccdSSowmini Varadhan 		shinfo->frag_list = clone;
60886fa01ccdSSowmini Varadhan 	}
60896fa01ccdSSowmini Varadhan 	return 0;
60906fa01ccdSSowmini Varadhan }
60916fa01ccdSSowmini Varadhan 
60926fa01ccdSSowmini Varadhan /* carve off first len bytes from skb. Split line (off) is in the
60936fa01ccdSSowmini Varadhan  * non-linear part of skb
60946fa01ccdSSowmini Varadhan  */
60956fa01ccdSSowmini Varadhan static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
60966fa01ccdSSowmini Varadhan 				       int pos, gfp_t gfp_mask)
60976fa01ccdSSowmini Varadhan {
60986fa01ccdSSowmini Varadhan 	int i, k = 0;
60996fa01ccdSSowmini Varadhan 	int size = skb_end_offset(skb);
61006fa01ccdSSowmini Varadhan 	u8 *data;
61016fa01ccdSSowmini Varadhan 	const int nfrags = skb_shinfo(skb)->nr_frags;
61026fa01ccdSSowmini Varadhan 	struct skb_shared_info *shinfo;
61036fa01ccdSSowmini Varadhan 
61046fa01ccdSSowmini Varadhan 	size = SKB_DATA_ALIGN(size);
61056fa01ccdSSowmini Varadhan 
61066fa01ccdSSowmini Varadhan 	if (skb_pfmemalloc(skb))
61076fa01ccdSSowmini Varadhan 		gfp_mask |= __GFP_MEMALLOC;
61086fa01ccdSSowmini Varadhan 	data = kmalloc_reserve(size +
61096fa01ccdSSowmini Varadhan 			       SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
61106fa01ccdSSowmini Varadhan 			       gfp_mask, NUMA_NO_NODE, NULL);
61116fa01ccdSSowmini Varadhan 	if (!data)
61126fa01ccdSSowmini Varadhan 		return -ENOMEM;
61136fa01ccdSSowmini Varadhan 
61146fa01ccdSSowmini Varadhan 	size = SKB_WITH_OVERHEAD(ksize(data));
61156fa01ccdSSowmini Varadhan 
61166fa01ccdSSowmini Varadhan 	memcpy((struct skb_shared_info *)(data + size),
6117e3ec1e8cSMiaohe Lin 	       skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
61186fa01ccdSSowmini Varadhan 	if (skb_orphan_frags(skb, gfp_mask)) {
61196fa01ccdSSowmini Varadhan 		kfree(data);
61206fa01ccdSSowmini Varadhan 		return -ENOMEM;
61216fa01ccdSSowmini Varadhan 	}
61226fa01ccdSSowmini Varadhan 	shinfo = (struct skb_shared_info *)(data + size);
61236fa01ccdSSowmini Varadhan 	for (i = 0; i < nfrags; i++) {
61246fa01ccdSSowmini Varadhan 		int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
61256fa01ccdSSowmini Varadhan 
61266fa01ccdSSowmini Varadhan 		if (pos + fsize > off) {
61276fa01ccdSSowmini Varadhan 			shinfo->frags[k] = skb_shinfo(skb)->frags[i];
61286fa01ccdSSowmini Varadhan 
61296fa01ccdSSowmini Varadhan 			if (pos < off) {
61306fa01ccdSSowmini Varadhan 				/* Split frag.
61316fa01ccdSSowmini Varadhan 				 * We have two variants in this case:
61326fa01ccdSSowmini Varadhan 				 * 1. Move all the frag to the second
61336fa01ccdSSowmini Varadhan 				 *    part, if it is possible. F.e.
61346fa01ccdSSowmini Varadhan 				 *    this approach is mandatory for TUX,
61356fa01ccdSSowmini Varadhan 				 *    where splitting is expensive.
61366fa01ccdSSowmini Varadhan 				 * 2. Split is accurately. We make this.
61376fa01ccdSSowmini Varadhan 				 */
6138b54c9d5bSJonathan Lemon 				skb_frag_off_add(&shinfo->frags[0], off - pos);
61396fa01ccdSSowmini Varadhan 				skb_frag_size_sub(&shinfo->frags[0], off - pos);
61406fa01ccdSSowmini Varadhan 			}
61416fa01ccdSSowmini Varadhan 			skb_frag_ref(skb, i);
61426fa01ccdSSowmini Varadhan 			k++;
61436fa01ccdSSowmini Varadhan 		}
61446fa01ccdSSowmini Varadhan 		pos += fsize;
61456fa01ccdSSowmini Varadhan 	}
61466fa01ccdSSowmini Varadhan 	shinfo->nr_frags = k;
61476fa01ccdSSowmini Varadhan 	if (skb_has_frag_list(skb))
61486fa01ccdSSowmini Varadhan 		skb_clone_fraglist(skb);
61496fa01ccdSSowmini Varadhan 
61506fa01ccdSSowmini Varadhan 	/* split line is in frag list */
6151eabe8618SMiaohe Lin 	if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6152eabe8618SMiaohe Lin 		/* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6153eabe8618SMiaohe Lin 		if (skb_has_frag_list(skb))
6154eabe8618SMiaohe Lin 			kfree_skb_list(skb_shinfo(skb)->frag_list);
6155eabe8618SMiaohe Lin 		kfree(data);
6156eabe8618SMiaohe Lin 		return -ENOMEM;
61576fa01ccdSSowmini Varadhan 	}
61586fa01ccdSSowmini Varadhan 	skb_release_data(skb);
61596fa01ccdSSowmini Varadhan 
61606fa01ccdSSowmini Varadhan 	skb->head = data;
61616fa01ccdSSowmini Varadhan 	skb->head_frag = 0;
61626fa01ccdSSowmini Varadhan 	skb->data = data;
61636fa01ccdSSowmini Varadhan #ifdef NET_SKBUFF_DATA_USES_OFFSET
61646fa01ccdSSowmini Varadhan 	skb->end = size;
61656fa01ccdSSowmini Varadhan #else
61666fa01ccdSSowmini Varadhan 	skb->end = skb->head + size;
61676fa01ccdSSowmini Varadhan #endif
61686fa01ccdSSowmini Varadhan 	skb_reset_tail_pointer(skb);
61696fa01ccdSSowmini Varadhan 	skb_headers_offset_update(skb, 0);
61706fa01ccdSSowmini Varadhan 	skb->cloned   = 0;
61716fa01ccdSSowmini Varadhan 	skb->hdr_len  = 0;
61726fa01ccdSSowmini Varadhan 	skb->nohdr    = 0;
61736fa01ccdSSowmini Varadhan 	skb->len -= off;
61746fa01ccdSSowmini Varadhan 	skb->data_len = skb->len;
61756fa01ccdSSowmini Varadhan 	atomic_set(&skb_shinfo(skb)->dataref, 1);
61766fa01ccdSSowmini Varadhan 	return 0;
61776fa01ccdSSowmini Varadhan }
61786fa01ccdSSowmini Varadhan 
61796fa01ccdSSowmini Varadhan /* remove len bytes from the beginning of the skb */
61806fa01ccdSSowmini Varadhan static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
61816fa01ccdSSowmini Varadhan {
61826fa01ccdSSowmini Varadhan 	int headlen = skb_headlen(skb);
61836fa01ccdSSowmini Varadhan 
61846fa01ccdSSowmini Varadhan 	if (len < headlen)
61856fa01ccdSSowmini Varadhan 		return pskb_carve_inside_header(skb, len, headlen, gfp);
61866fa01ccdSSowmini Varadhan 	else
61876fa01ccdSSowmini Varadhan 		return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
61886fa01ccdSSowmini Varadhan }
61896fa01ccdSSowmini Varadhan 
61906fa01ccdSSowmini Varadhan /* Extract to_copy bytes starting at off from skb, and return this in
61916fa01ccdSSowmini Varadhan  * a new skb
61926fa01ccdSSowmini Varadhan  */
61936fa01ccdSSowmini Varadhan struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
61946fa01ccdSSowmini Varadhan 			     int to_copy, gfp_t gfp)
61956fa01ccdSSowmini Varadhan {
61966fa01ccdSSowmini Varadhan 	struct sk_buff  *clone = skb_clone(skb, gfp);
61976fa01ccdSSowmini Varadhan 
61986fa01ccdSSowmini Varadhan 	if (!clone)
61996fa01ccdSSowmini Varadhan 		return NULL;
62006fa01ccdSSowmini Varadhan 
62016fa01ccdSSowmini Varadhan 	if (pskb_carve(clone, off, gfp) < 0 ||
62026fa01ccdSSowmini Varadhan 	    pskb_trim(clone, to_copy)) {
62036fa01ccdSSowmini Varadhan 		kfree_skb(clone);
62046fa01ccdSSowmini Varadhan 		return NULL;
62056fa01ccdSSowmini Varadhan 	}
62066fa01ccdSSowmini Varadhan 	return clone;
62076fa01ccdSSowmini Varadhan }
62086fa01ccdSSowmini Varadhan EXPORT_SYMBOL(pskb_extract);
6209c8c8b127SEric Dumazet 
6210c8c8b127SEric Dumazet /**
6211c8c8b127SEric Dumazet  * skb_condense - try to get rid of fragments/frag_list if possible
6212c8c8b127SEric Dumazet  * @skb: buffer
6213c8c8b127SEric Dumazet  *
6214c8c8b127SEric Dumazet  * Can be used to save memory before skb is added to a busy queue.
6215c8c8b127SEric Dumazet  * If packet has bytes in frags and enough tail room in skb->head,
6216c8c8b127SEric Dumazet  * pull all of them, so that we can free the frags right now and adjust
6217c8c8b127SEric Dumazet  * truesize.
6218c8c8b127SEric Dumazet  * Notes:
6219c8c8b127SEric Dumazet  *	We do not reallocate skb->head thus can not fail.
6220c8c8b127SEric Dumazet  *	Caller must re-evaluate skb->truesize if needed.
6221c8c8b127SEric Dumazet  */
6222c8c8b127SEric Dumazet void skb_condense(struct sk_buff *skb)
6223c8c8b127SEric Dumazet {
62243174fed9SEric Dumazet 	if (skb->data_len) {
62253174fed9SEric Dumazet 		if (skb->data_len > skb->end - skb->tail ||
6226c8c8b127SEric Dumazet 		    skb_cloned(skb))
6227c8c8b127SEric Dumazet 			return;
6228c8c8b127SEric Dumazet 
6229c8c8b127SEric Dumazet 		/* Nice, we can free page frag(s) right now */
6230c8c8b127SEric Dumazet 		__pskb_pull_tail(skb, skb->data_len);
62313174fed9SEric Dumazet 	}
62323174fed9SEric Dumazet 	/* At this point, skb->truesize might be over estimated,
62333174fed9SEric Dumazet 	 * because skb had a fragment, and fragments do not tell
62343174fed9SEric Dumazet 	 * their truesize.
62353174fed9SEric Dumazet 	 * When we pulled its content into skb->head, fragment
62363174fed9SEric Dumazet 	 * was freed, but __pskb_pull_tail() could not possibly
62373174fed9SEric Dumazet 	 * adjust skb->truesize, not knowing the frag truesize.
6238c8c8b127SEric Dumazet 	 */
6239c8c8b127SEric Dumazet 	skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6240c8c8b127SEric Dumazet }
6241df5042f4SFlorian Westphal 
6242df5042f4SFlorian Westphal #ifdef CONFIG_SKB_EXTENSIONS
6243df5042f4SFlorian Westphal static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6244df5042f4SFlorian Westphal {
6245df5042f4SFlorian Westphal 	return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6246df5042f4SFlorian Westphal }
6247df5042f4SFlorian Westphal 
62488b69a803SPaolo Abeni /**
62498b69a803SPaolo Abeni  * __skb_ext_alloc - allocate a new skb extensions storage
62508b69a803SPaolo Abeni  *
62514930f483SFlorian Westphal  * @flags: See kmalloc().
62524930f483SFlorian Westphal  *
62538b69a803SPaolo Abeni  * Returns the newly allocated pointer. The pointer can later attached to a
62548b69a803SPaolo Abeni  * skb via __skb_ext_set().
62558b69a803SPaolo Abeni  * Note: caller must handle the skb_ext as an opaque data.
62568b69a803SPaolo Abeni  */
62574930f483SFlorian Westphal struct skb_ext *__skb_ext_alloc(gfp_t flags)
6258df5042f4SFlorian Westphal {
62594930f483SFlorian Westphal 	struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6260df5042f4SFlorian Westphal 
6261df5042f4SFlorian Westphal 	if (new) {
6262df5042f4SFlorian Westphal 		memset(new->offset, 0, sizeof(new->offset));
6263df5042f4SFlorian Westphal 		refcount_set(&new->refcnt, 1);
6264df5042f4SFlorian Westphal 	}
6265df5042f4SFlorian Westphal 
6266df5042f4SFlorian Westphal 	return new;
6267df5042f4SFlorian Westphal }
6268df5042f4SFlorian Westphal 
62694165079bSFlorian Westphal static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
62704165079bSFlorian Westphal 					 unsigned int old_active)
6271df5042f4SFlorian Westphal {
6272df5042f4SFlorian Westphal 	struct skb_ext *new;
6273df5042f4SFlorian Westphal 
6274df5042f4SFlorian Westphal 	if (refcount_read(&old->refcnt) == 1)
6275df5042f4SFlorian Westphal 		return old;
6276df5042f4SFlorian Westphal 
6277df5042f4SFlorian Westphal 	new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6278df5042f4SFlorian Westphal 	if (!new)
6279df5042f4SFlorian Westphal 		return NULL;
6280df5042f4SFlorian Westphal 
6281df5042f4SFlorian Westphal 	memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6282df5042f4SFlorian Westphal 	refcount_set(&new->refcnt, 1);
6283df5042f4SFlorian Westphal 
62844165079bSFlorian Westphal #ifdef CONFIG_XFRM
62854165079bSFlorian Westphal 	if (old_active & (1 << SKB_EXT_SEC_PATH)) {
62864165079bSFlorian Westphal 		struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
62874165079bSFlorian Westphal 		unsigned int i;
62884165079bSFlorian Westphal 
62894165079bSFlorian Westphal 		for (i = 0; i < sp->len; i++)
62904165079bSFlorian Westphal 			xfrm_state_hold(sp->xvec[i]);
62914165079bSFlorian Westphal 	}
62924165079bSFlorian Westphal #endif
6293df5042f4SFlorian Westphal 	__skb_ext_put(old);
6294df5042f4SFlorian Westphal 	return new;
6295df5042f4SFlorian Westphal }
6296df5042f4SFlorian Westphal 
6297df5042f4SFlorian Westphal /**
62988b69a803SPaolo Abeni  * __skb_ext_set - attach the specified extension storage to this skb
62998b69a803SPaolo Abeni  * @skb: buffer
63008b69a803SPaolo Abeni  * @id: extension id
63018b69a803SPaolo Abeni  * @ext: extension storage previously allocated via __skb_ext_alloc()
63028b69a803SPaolo Abeni  *
63038b69a803SPaolo Abeni  * Existing extensions, if any, are cleared.
63048b69a803SPaolo Abeni  *
63058b69a803SPaolo Abeni  * Returns the pointer to the extension.
63068b69a803SPaolo Abeni  */
63078b69a803SPaolo Abeni void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
63088b69a803SPaolo Abeni 		    struct skb_ext *ext)
63098b69a803SPaolo Abeni {
63108b69a803SPaolo Abeni 	unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
63118b69a803SPaolo Abeni 
63128b69a803SPaolo Abeni 	skb_ext_put(skb);
63138b69a803SPaolo Abeni 	newlen = newoff + skb_ext_type_len[id];
63148b69a803SPaolo Abeni 	ext->chunks = newlen;
63158b69a803SPaolo Abeni 	ext->offset[id] = newoff;
63168b69a803SPaolo Abeni 	skb->extensions = ext;
63178b69a803SPaolo Abeni 	skb->active_extensions = 1 << id;
63188b69a803SPaolo Abeni 	return skb_ext_get_ptr(ext, id);
63198b69a803SPaolo Abeni }
63208b69a803SPaolo Abeni 
63218b69a803SPaolo Abeni /**
6322df5042f4SFlorian Westphal  * skb_ext_add - allocate space for given extension, COW if needed
6323df5042f4SFlorian Westphal  * @skb: buffer
6324df5042f4SFlorian Westphal  * @id: extension to allocate space for
6325df5042f4SFlorian Westphal  *
6326df5042f4SFlorian Westphal  * Allocates enough space for the given extension.
6327df5042f4SFlorian Westphal  * If the extension is already present, a pointer to that extension
6328df5042f4SFlorian Westphal  * is returned.
6329df5042f4SFlorian Westphal  *
6330df5042f4SFlorian Westphal  * If the skb was cloned, COW applies and the returned memory can be
6331df5042f4SFlorian Westphal  * modified without changing the extension space of clones buffers.
6332df5042f4SFlorian Westphal  *
6333df5042f4SFlorian Westphal  * Returns pointer to the extension or NULL on allocation failure.
6334df5042f4SFlorian Westphal  */
6335df5042f4SFlorian Westphal void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6336df5042f4SFlorian Westphal {
6337df5042f4SFlorian Westphal 	struct skb_ext *new, *old = NULL;
6338df5042f4SFlorian Westphal 	unsigned int newlen, newoff;
6339df5042f4SFlorian Westphal 
6340df5042f4SFlorian Westphal 	if (skb->active_extensions) {
6341df5042f4SFlorian Westphal 		old = skb->extensions;
6342df5042f4SFlorian Westphal 
63434165079bSFlorian Westphal 		new = skb_ext_maybe_cow(old, skb->active_extensions);
6344df5042f4SFlorian Westphal 		if (!new)
6345df5042f4SFlorian Westphal 			return NULL;
6346df5042f4SFlorian Westphal 
6347682ec859SPaolo Abeni 		if (__skb_ext_exist(new, id))
6348df5042f4SFlorian Westphal 			goto set_active;
6349df5042f4SFlorian Westphal 
6350e94e50bdSPaolo Abeni 		newoff = new->chunks;
6351df5042f4SFlorian Westphal 	} else {
6352df5042f4SFlorian Westphal 		newoff = SKB_EXT_CHUNKSIZEOF(*new);
6353df5042f4SFlorian Westphal 
63544930f483SFlorian Westphal 		new = __skb_ext_alloc(GFP_ATOMIC);
6355df5042f4SFlorian Westphal 		if (!new)
6356df5042f4SFlorian Westphal 			return NULL;
6357df5042f4SFlorian Westphal 	}
6358df5042f4SFlorian Westphal 
6359df5042f4SFlorian Westphal 	newlen = newoff + skb_ext_type_len[id];
6360df5042f4SFlorian Westphal 	new->chunks = newlen;
6361df5042f4SFlorian Westphal 	new->offset[id] = newoff;
6362df5042f4SFlorian Westphal set_active:
6363b0999f38SPaolo Abeni 	skb->slow_gro = 1;
6364682ec859SPaolo Abeni 	skb->extensions = new;
6365df5042f4SFlorian Westphal 	skb->active_extensions |= 1 << id;
6366df5042f4SFlorian Westphal 	return skb_ext_get_ptr(new, id);
6367df5042f4SFlorian Westphal }
6368df5042f4SFlorian Westphal EXPORT_SYMBOL(skb_ext_add);
6369df5042f4SFlorian Westphal 
63704165079bSFlorian Westphal #ifdef CONFIG_XFRM
63714165079bSFlorian Westphal static void skb_ext_put_sp(struct sec_path *sp)
63724165079bSFlorian Westphal {
63734165079bSFlorian Westphal 	unsigned int i;
63744165079bSFlorian Westphal 
63754165079bSFlorian Westphal 	for (i = 0; i < sp->len; i++)
63764165079bSFlorian Westphal 		xfrm_state_put(sp->xvec[i]);
63774165079bSFlorian Westphal }
63784165079bSFlorian Westphal #endif
63794165079bSFlorian Westphal 
638078476d31SJeremy Kerr #ifdef CONFIG_MCTP_FLOWS
638178476d31SJeremy Kerr static void skb_ext_put_mctp(struct mctp_flow *flow)
638278476d31SJeremy Kerr {
638378476d31SJeremy Kerr 	if (flow->key)
638478476d31SJeremy Kerr 		mctp_key_unref(flow->key);
638578476d31SJeremy Kerr }
638678476d31SJeremy Kerr #endif
638778476d31SJeremy Kerr 
6388df5042f4SFlorian Westphal void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6389df5042f4SFlorian Westphal {
6390df5042f4SFlorian Westphal 	struct skb_ext *ext = skb->extensions;
6391df5042f4SFlorian Westphal 
6392df5042f4SFlorian Westphal 	skb->active_extensions &= ~(1 << id);
6393df5042f4SFlorian Westphal 	if (skb->active_extensions == 0) {
6394df5042f4SFlorian Westphal 		skb->extensions = NULL;
6395df5042f4SFlorian Westphal 		__skb_ext_put(ext);
63964165079bSFlorian Westphal #ifdef CONFIG_XFRM
63974165079bSFlorian Westphal 	} else if (id == SKB_EXT_SEC_PATH &&
63984165079bSFlorian Westphal 		   refcount_read(&ext->refcnt) == 1) {
63994165079bSFlorian Westphal 		struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
64004165079bSFlorian Westphal 
64014165079bSFlorian Westphal 		skb_ext_put_sp(sp);
64024165079bSFlorian Westphal 		sp->len = 0;
64034165079bSFlorian Westphal #endif
6404df5042f4SFlorian Westphal 	}
6405df5042f4SFlorian Westphal }
6406df5042f4SFlorian Westphal EXPORT_SYMBOL(__skb_ext_del);
6407df5042f4SFlorian Westphal 
6408df5042f4SFlorian Westphal void __skb_ext_put(struct skb_ext *ext)
6409df5042f4SFlorian Westphal {
6410df5042f4SFlorian Westphal 	/* If this is last clone, nothing can increment
6411df5042f4SFlorian Westphal 	 * it after check passes.  Avoids one atomic op.
6412df5042f4SFlorian Westphal 	 */
6413df5042f4SFlorian Westphal 	if (refcount_read(&ext->refcnt) == 1)
6414df5042f4SFlorian Westphal 		goto free_now;
6415df5042f4SFlorian Westphal 
6416df5042f4SFlorian Westphal 	if (!refcount_dec_and_test(&ext->refcnt))
6417df5042f4SFlorian Westphal 		return;
6418df5042f4SFlorian Westphal free_now:
64194165079bSFlorian Westphal #ifdef CONFIG_XFRM
64204165079bSFlorian Westphal 	if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
64214165079bSFlorian Westphal 		skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
64224165079bSFlorian Westphal #endif
642378476d31SJeremy Kerr #ifdef CONFIG_MCTP_FLOWS
642478476d31SJeremy Kerr 	if (__skb_ext_exist(ext, SKB_EXT_MCTP))
642578476d31SJeremy Kerr 		skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
642678476d31SJeremy Kerr #endif
64274165079bSFlorian Westphal 
6428df5042f4SFlorian Westphal 	kmem_cache_free(skbuff_ext_cache, ext);
6429df5042f4SFlorian Westphal }
6430df5042f4SFlorian Westphal EXPORT_SYMBOL(__skb_ext_put);
6431df5042f4SFlorian Westphal #endif /* CONFIG_SKB_EXTENSIONS */
6432