xref: /openbmc/linux/net/core/skbuff.c (revision 12c1604a)
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 
8339564c3fSEric Dumazet #include "dev.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 
949cb252c4SMenglong Dong #undef FN
959cb252c4SMenglong Dong #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
969cb252c4SMenglong Dong const char * const drop_reasons[] = {
970e84afe8SEric Dumazet 	[SKB_CONSUMED] = "CONSUMED",
989cb252c4SMenglong Dong 	DEFINE_DROP_REASON(FN, FN)
999cb252c4SMenglong Dong };
100ec43908dSMenglong Dong EXPORT_SYMBOL(drop_reasons);
101ec43908dSMenglong Dong 
1021da177e4SLinus Torvalds /**
103f05de73bSJean Sacren  *	skb_panic - private function for out-of-line support
1041da177e4SLinus Torvalds  *	@skb:	buffer
1051da177e4SLinus Torvalds  *	@sz:	size
106f05de73bSJean Sacren  *	@addr:	address
10799d5851eSJames Hogan  *	@msg:	skb_over_panic or skb_under_panic
1081da177e4SLinus Torvalds  *
109f05de73bSJean Sacren  *	Out-of-line support for skb_put() and skb_push().
110f05de73bSJean Sacren  *	Called via the wrapper skb_over_panic() or skb_under_panic().
111f05de73bSJean Sacren  *	Keep out of line to prevent kernel bloat.
112f05de73bSJean Sacren  *	__builtin_return_address is not used because it is not always reliable.
1131da177e4SLinus Torvalds  */
114f05de73bSJean Sacren static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
11599d5851eSJames Hogan 		      const char msg[])
1161da177e4SLinus Torvalds {
11741a46913SJesper Dangaard Brouer 	pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
11899d5851eSJames Hogan 		 msg, addr, skb->len, sz, skb->head, skb->data,
1194305b541SArnaldo Carvalho de Melo 		 (unsigned long)skb->tail, (unsigned long)skb->end,
12026095455SPatrick McHardy 		 skb->dev ? skb->dev->name : "<NULL>");
1211da177e4SLinus Torvalds 	BUG();
1221da177e4SLinus Torvalds }
1231da177e4SLinus Torvalds 
124f05de73bSJean Sacren static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
1251da177e4SLinus Torvalds {
126f05de73bSJean Sacren 	skb_panic(skb, sz, addr, __func__);
1271da177e4SLinus Torvalds }
1281da177e4SLinus Torvalds 
129f05de73bSJean Sacren static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
130f05de73bSJean Sacren {
131f05de73bSJean Sacren 	skb_panic(skb, sz, addr, __func__);
132f05de73bSJean Sacren }
133c93bdd0eSMel Gorman 
13450fad4b5SAlexander Lobakin #define NAPI_SKB_CACHE_SIZE	64
135f450d539SAlexander Lobakin #define NAPI_SKB_CACHE_BULK	16
136f450d539SAlexander Lobakin #define NAPI_SKB_CACHE_HALF	(NAPI_SKB_CACHE_SIZE / 2)
13750fad4b5SAlexander Lobakin 
138dbae2b06SPaolo Abeni #if PAGE_SIZE == SZ_4K
139dbae2b06SPaolo Abeni 
140dbae2b06SPaolo Abeni #define NAPI_HAS_SMALL_PAGE_FRAG	1
141dbae2b06SPaolo Abeni #define NAPI_SMALL_PAGE_PFMEMALLOC(nc)	((nc).pfmemalloc)
142dbae2b06SPaolo Abeni 
143dbae2b06SPaolo Abeni /* specialized page frag allocator using a single order 0 page
144dbae2b06SPaolo Abeni  * and slicing it into 1K sized fragment. Constrained to systems
145dbae2b06SPaolo Abeni  * with a very limited amount of 1K fragments fitting a single
146dbae2b06SPaolo Abeni  * page - to avoid excessive truesize underestimation
147dbae2b06SPaolo Abeni  */
148dbae2b06SPaolo Abeni 
149dbae2b06SPaolo Abeni struct page_frag_1k {
150dbae2b06SPaolo Abeni 	void *va;
151dbae2b06SPaolo Abeni 	u16 offset;
152dbae2b06SPaolo Abeni 	bool pfmemalloc;
153dbae2b06SPaolo Abeni };
154dbae2b06SPaolo Abeni 
155dbae2b06SPaolo Abeni static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
156dbae2b06SPaolo Abeni {
157dbae2b06SPaolo Abeni 	struct page *page;
158dbae2b06SPaolo Abeni 	int offset;
159dbae2b06SPaolo Abeni 
160dbae2b06SPaolo Abeni 	offset = nc->offset - SZ_1K;
161dbae2b06SPaolo Abeni 	if (likely(offset >= 0))
162dbae2b06SPaolo Abeni 		goto use_frag;
163dbae2b06SPaolo Abeni 
164dbae2b06SPaolo Abeni 	page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
165dbae2b06SPaolo Abeni 	if (!page)
166dbae2b06SPaolo Abeni 		return NULL;
167dbae2b06SPaolo Abeni 
168dbae2b06SPaolo Abeni 	nc->va = page_address(page);
169dbae2b06SPaolo Abeni 	nc->pfmemalloc = page_is_pfmemalloc(page);
170dbae2b06SPaolo Abeni 	offset = PAGE_SIZE - SZ_1K;
171dbae2b06SPaolo Abeni 	page_ref_add(page, offset / SZ_1K);
172dbae2b06SPaolo Abeni 
173dbae2b06SPaolo Abeni use_frag:
174dbae2b06SPaolo Abeni 	nc->offset = offset;
175dbae2b06SPaolo Abeni 	return nc->va + offset;
176dbae2b06SPaolo Abeni }
177dbae2b06SPaolo Abeni #else
178dbae2b06SPaolo Abeni 
179dbae2b06SPaolo Abeni /* the small page is actually unused in this build; add dummy helpers
180dbae2b06SPaolo Abeni  * to please the compiler and avoid later preprocessor's conditionals
181dbae2b06SPaolo Abeni  */
182dbae2b06SPaolo Abeni #define NAPI_HAS_SMALL_PAGE_FRAG	0
183dbae2b06SPaolo Abeni #define NAPI_SMALL_PAGE_PFMEMALLOC(nc)	false
184dbae2b06SPaolo Abeni 
185dbae2b06SPaolo Abeni struct page_frag_1k {
186dbae2b06SPaolo Abeni };
187dbae2b06SPaolo Abeni 
188dbae2b06SPaolo Abeni static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
189dbae2b06SPaolo Abeni {
190dbae2b06SPaolo Abeni 	return NULL;
191dbae2b06SPaolo Abeni }
192dbae2b06SPaolo Abeni 
193dbae2b06SPaolo Abeni #endif
194dbae2b06SPaolo Abeni 
19550fad4b5SAlexander Lobakin struct napi_alloc_cache {
19650fad4b5SAlexander Lobakin 	struct page_frag_cache page;
197dbae2b06SPaolo Abeni 	struct page_frag_1k page_small;
19850fad4b5SAlexander Lobakin 	unsigned int skb_count;
19950fad4b5SAlexander Lobakin 	void *skb_cache[NAPI_SKB_CACHE_SIZE];
20050fad4b5SAlexander Lobakin };
20150fad4b5SAlexander Lobakin 
20250fad4b5SAlexander Lobakin static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
20350fad4b5SAlexander Lobakin static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
20450fad4b5SAlexander Lobakin 
205dbae2b06SPaolo Abeni /* Double check that napi_get_frags() allocates skbs with
206dbae2b06SPaolo Abeni  * skb->head being backed by slab, not a page fragment.
207dbae2b06SPaolo Abeni  * This is to make sure bug fixed in 3226b158e67c
208dbae2b06SPaolo Abeni  * ("net: avoid 32 x truesize under-estimation for tiny skbs")
209dbae2b06SPaolo Abeni  * does not accidentally come back.
210dbae2b06SPaolo Abeni  */
211dbae2b06SPaolo Abeni void napi_get_frags_check(struct napi_struct *napi)
212dbae2b06SPaolo Abeni {
213dbae2b06SPaolo Abeni 	struct sk_buff *skb;
214dbae2b06SPaolo Abeni 
215dbae2b06SPaolo Abeni 	local_bh_disable();
216dbae2b06SPaolo Abeni 	skb = napi_get_frags(napi);
217dbae2b06SPaolo Abeni 	WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
218dbae2b06SPaolo Abeni 	napi_free_frags(napi);
219dbae2b06SPaolo Abeni 	local_bh_enable();
220dbae2b06SPaolo Abeni }
221dbae2b06SPaolo Abeni 
22232e3573fSYajun Deng void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
22350fad4b5SAlexander Lobakin {
22450fad4b5SAlexander Lobakin 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
22550fad4b5SAlexander Lobakin 
22650fad4b5SAlexander Lobakin 	fragsz = SKB_DATA_ALIGN(fragsz);
22750fad4b5SAlexander Lobakin 
22832e3573fSYajun Deng 	return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
22950fad4b5SAlexander Lobakin }
23050fad4b5SAlexander Lobakin EXPORT_SYMBOL(__napi_alloc_frag_align);
23150fad4b5SAlexander Lobakin 
23250fad4b5SAlexander Lobakin void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
23350fad4b5SAlexander Lobakin {
23450fad4b5SAlexander Lobakin 	void *data;
23550fad4b5SAlexander Lobakin 
23650fad4b5SAlexander Lobakin 	fragsz = SKB_DATA_ALIGN(fragsz);
237afa79d08SChangbin Du 	if (in_hardirq() || irqs_disabled()) {
23832e3573fSYajun Deng 		struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
23932e3573fSYajun Deng 
24050fad4b5SAlexander Lobakin 		data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
24150fad4b5SAlexander Lobakin 	} else {
24232e3573fSYajun Deng 		struct napi_alloc_cache *nc;
24332e3573fSYajun Deng 
24450fad4b5SAlexander Lobakin 		local_bh_disable();
24532e3573fSYajun Deng 		nc = this_cpu_ptr(&napi_alloc_cache);
24632e3573fSYajun Deng 		data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
24750fad4b5SAlexander Lobakin 		local_bh_enable();
24850fad4b5SAlexander Lobakin 	}
24950fad4b5SAlexander Lobakin 	return data;
25050fad4b5SAlexander Lobakin }
25150fad4b5SAlexander Lobakin EXPORT_SYMBOL(__netdev_alloc_frag_align);
25250fad4b5SAlexander Lobakin 
253f450d539SAlexander Lobakin static struct sk_buff *napi_skb_cache_get(void)
254f450d539SAlexander Lobakin {
255f450d539SAlexander Lobakin 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
256f450d539SAlexander Lobakin 	struct sk_buff *skb;
257f450d539SAlexander Lobakin 
25849ae83fcSSieng Piaw Liew 	if (unlikely(!nc->skb_count)) {
259f450d539SAlexander Lobakin 		nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
260f450d539SAlexander Lobakin 						      GFP_ATOMIC,
261f450d539SAlexander Lobakin 						      NAPI_SKB_CACHE_BULK,
262f450d539SAlexander Lobakin 						      nc->skb_cache);
263f450d539SAlexander Lobakin 		if (unlikely(!nc->skb_count))
264f450d539SAlexander Lobakin 			return NULL;
26549ae83fcSSieng Piaw Liew 	}
266f450d539SAlexander Lobakin 
267f450d539SAlexander Lobakin 	skb = nc->skb_cache[--nc->skb_count];
268f450d539SAlexander Lobakin 	kasan_unpoison_object_data(skbuff_head_cache, skb);
269f450d539SAlexander Lobakin 
270f450d539SAlexander Lobakin 	return skb;
271f450d539SAlexander Lobakin }
272f450d539SAlexander Lobakin 
273ce098da1SKees Cook static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
274ce098da1SKees Cook 					 unsigned int size)
275ba0509b6SJesper Dangaard Brouer {
276ba0509b6SJesper Dangaard Brouer 	struct skb_shared_info *shinfo;
277ba0509b6SJesper Dangaard Brouer 
278ba0509b6SJesper Dangaard Brouer 	size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
279ba0509b6SJesper Dangaard Brouer 
280ba0509b6SJesper Dangaard Brouer 	/* Assumes caller memset cleared SKB */
281ba0509b6SJesper Dangaard Brouer 	skb->truesize = SKB_TRUESIZE(size);
282ba0509b6SJesper Dangaard Brouer 	refcount_set(&skb->users, 1);
283ba0509b6SJesper Dangaard Brouer 	skb->head = data;
284ba0509b6SJesper Dangaard Brouer 	skb->data = data;
285ba0509b6SJesper Dangaard Brouer 	skb_reset_tail_pointer(skb);
286763087daSEric Dumazet 	skb_set_end_offset(skb, size);
287ba0509b6SJesper Dangaard Brouer 	skb->mac_header = (typeof(skb->mac_header))~0U;
288ba0509b6SJesper Dangaard Brouer 	skb->transport_header = (typeof(skb->transport_header))~0U;
28968822bdfSEric Dumazet 	skb->alloc_cpu = raw_smp_processor_id();
290ba0509b6SJesper Dangaard Brouer 	/* make sure we initialize shinfo sequentially */
291ba0509b6SJesper Dangaard Brouer 	shinfo = skb_shinfo(skb);
292ba0509b6SJesper Dangaard Brouer 	memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
293ba0509b6SJesper Dangaard Brouer 	atomic_set(&shinfo->dataref, 1);
294ba0509b6SJesper Dangaard Brouer 
2956370cc3bSAleksandr Nogikh 	skb_set_kcov_handle(skb, kcov_common_handle());
296ba0509b6SJesper Dangaard Brouer }
297ba0509b6SJesper Dangaard Brouer 
298ce098da1SKees Cook static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
299ce098da1SKees Cook 				     unsigned int *size)
300ce098da1SKees Cook {
301ce098da1SKees Cook 	void *resized;
302ce098da1SKees Cook 
303ce098da1SKees Cook 	/* Must find the allocation size (and grow it to match). */
304ce098da1SKees Cook 	*size = ksize(data);
305ce098da1SKees Cook 	/* krealloc() will immediately return "data" when
306ce098da1SKees Cook 	 * "ksize(data)" is requested: it is the existing upper
307ce098da1SKees Cook 	 * bounds. As a result, GFP_ATOMIC will be ignored. Note
308ce098da1SKees Cook 	 * that this "new" pointer needs to be passed back to the
309ce098da1SKees Cook 	 * caller for use so the __alloc_size hinting will be
310ce098da1SKees Cook 	 * tracked correctly.
311ce098da1SKees Cook 	 */
312ce098da1SKees Cook 	resized = krealloc(data, *size, GFP_ATOMIC);
313ce098da1SKees Cook 	WARN_ON_ONCE(resized != data);
314ce098da1SKees Cook 	return resized;
315ce098da1SKees Cook }
316ce098da1SKees Cook 
317ce098da1SKees Cook /* build_skb() variant which can operate on slab buffers.
318ce098da1SKees Cook  * Note that this should be used sparingly as slab buffers
319ce098da1SKees Cook  * cannot be combined efficiently by GRO!
320ce098da1SKees Cook  */
321ce098da1SKees Cook struct sk_buff *slab_build_skb(void *data)
322ce098da1SKees Cook {
323ce098da1SKees Cook 	struct sk_buff *skb;
324ce098da1SKees Cook 	unsigned int size;
325ce098da1SKees Cook 
326ce098da1SKees Cook 	skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
327ce098da1SKees Cook 	if (unlikely(!skb))
328ce098da1SKees Cook 		return NULL;
329ce098da1SKees Cook 
330ce098da1SKees Cook 	memset(skb, 0, offsetof(struct sk_buff, tail));
331ce098da1SKees Cook 	data = __slab_build_skb(skb, data, &size);
332ce098da1SKees Cook 	__finalize_skb_around(skb, data, size);
333ce098da1SKees Cook 
334ce098da1SKees Cook 	return skb;
335ce098da1SKees Cook }
336ce098da1SKees Cook EXPORT_SYMBOL(slab_build_skb);
337ce098da1SKees Cook 
338ce098da1SKees Cook /* Caller must provide SKB that is memset cleared */
339ce098da1SKees Cook static void __build_skb_around(struct sk_buff *skb, void *data,
340ce098da1SKees Cook 			       unsigned int frag_size)
341ce098da1SKees Cook {
342ce098da1SKees Cook 	unsigned int size = frag_size;
343ce098da1SKees Cook 
344ce098da1SKees Cook 	/* frag_size == 0 is considered deprecated now. Callers
345ce098da1SKees Cook 	 * using slab buffer should use slab_build_skb() instead.
346ce098da1SKees Cook 	 */
347ce098da1SKees Cook 	if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
348ce098da1SKees Cook 		data = __slab_build_skb(skb, data, &size);
349ce098da1SKees Cook 
350ce098da1SKees Cook 	__finalize_skb_around(skb, data, size);
351ce098da1SKees Cook }
352ce098da1SKees Cook 
3531da177e4SLinus Torvalds /**
3542ea2f62cSEric Dumazet  * __build_skb - build a network buffer
355b2b5ce9dSEric Dumazet  * @data: data buffer provided by caller
356ce098da1SKees Cook  * @frag_size: size of data (must not be 0)
357b2b5ce9dSEric Dumazet  *
358b2b5ce9dSEric Dumazet  * Allocate a new &sk_buff. Caller provides space holding head and
359ce098da1SKees Cook  * skb_shared_info. @data must have been allocated from the page
360ce098da1SKees Cook  * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
361ce098da1SKees Cook  * allocation is deprecated, and callers should use slab_build_skb()
362ce098da1SKees Cook  * instead.)
363b2b5ce9dSEric Dumazet  * The return is the new skb buffer.
364b2b5ce9dSEric Dumazet  * On a failure the return is %NULL, and @data is not freed.
365b2b5ce9dSEric Dumazet  * Notes :
366b2b5ce9dSEric Dumazet  *  Before IO, driver allocates only data buffer where NIC put incoming frame
367b2b5ce9dSEric Dumazet  *  Driver should add room at head (NET_SKB_PAD) and
368b2b5ce9dSEric Dumazet  *  MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
369b2b5ce9dSEric Dumazet  *  After IO, driver calls build_skb(), to allocate sk_buff and populate it
370b2b5ce9dSEric Dumazet  *  before giving packet to stack.
371b2b5ce9dSEric Dumazet  *  RX rings only contains data buffers, not full skbs.
372b2b5ce9dSEric Dumazet  */
3732ea2f62cSEric Dumazet struct sk_buff *__build_skb(void *data, unsigned int frag_size)
374b2b5ce9dSEric Dumazet {
375b2b5ce9dSEric Dumazet 	struct sk_buff *skb;
376b2b5ce9dSEric Dumazet 
377b2b5ce9dSEric Dumazet 	skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
378ba0509b6SJesper Dangaard Brouer 	if (unlikely(!skb))
379b2b5ce9dSEric Dumazet 		return NULL;
380b2b5ce9dSEric Dumazet 
381b2b5ce9dSEric Dumazet 	memset(skb, 0, offsetof(struct sk_buff, tail));
382483126b3SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
383b2b5ce9dSEric Dumazet 
384483126b3SAlexander Lobakin 	return skb;
385b2b5ce9dSEric Dumazet }
3862ea2f62cSEric Dumazet 
3872ea2f62cSEric Dumazet /* build_skb() is wrapper over __build_skb(), that specifically
3882ea2f62cSEric Dumazet  * takes care of skb->head and skb->pfmemalloc
3892ea2f62cSEric Dumazet  */
3902ea2f62cSEric Dumazet struct sk_buff *build_skb(void *data, unsigned int frag_size)
3912ea2f62cSEric Dumazet {
3922ea2f62cSEric Dumazet 	struct sk_buff *skb = __build_skb(data, frag_size);
3932ea2f62cSEric Dumazet 
3942ea2f62cSEric Dumazet 	if (skb && frag_size) {
3952ea2f62cSEric Dumazet 		skb->head_frag = 1;
3962f064f34SMichal Hocko 		if (page_is_pfmemalloc(virt_to_head_page(data)))
3972ea2f62cSEric Dumazet 			skb->pfmemalloc = 1;
3982ea2f62cSEric Dumazet 	}
3992ea2f62cSEric Dumazet 	return skb;
4002ea2f62cSEric Dumazet }
401b2b5ce9dSEric Dumazet EXPORT_SYMBOL(build_skb);
402b2b5ce9dSEric Dumazet 
403ba0509b6SJesper Dangaard Brouer /**
404ba0509b6SJesper Dangaard Brouer  * build_skb_around - build a network buffer around provided skb
405ba0509b6SJesper Dangaard Brouer  * @skb: sk_buff provide by caller, must be memset cleared
406ba0509b6SJesper Dangaard Brouer  * @data: data buffer provided by caller
407*12c1604aSJakub Kicinski  * @frag_size: size of data
408ba0509b6SJesper Dangaard Brouer  */
409ba0509b6SJesper Dangaard Brouer struct sk_buff *build_skb_around(struct sk_buff *skb,
410ba0509b6SJesper Dangaard Brouer 				 void *data, unsigned int frag_size)
411ba0509b6SJesper Dangaard Brouer {
412ba0509b6SJesper Dangaard Brouer 	if (unlikely(!skb))
413ba0509b6SJesper Dangaard Brouer 		return NULL;
414ba0509b6SJesper Dangaard Brouer 
415483126b3SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
416ba0509b6SJesper Dangaard Brouer 
417483126b3SAlexander Lobakin 	if (frag_size) {
418ba0509b6SJesper Dangaard Brouer 		skb->head_frag = 1;
419ba0509b6SJesper Dangaard Brouer 		if (page_is_pfmemalloc(virt_to_head_page(data)))
420ba0509b6SJesper Dangaard Brouer 			skb->pfmemalloc = 1;
421ba0509b6SJesper Dangaard Brouer 	}
422ba0509b6SJesper Dangaard Brouer 	return skb;
423ba0509b6SJesper Dangaard Brouer }
424ba0509b6SJesper Dangaard Brouer EXPORT_SYMBOL(build_skb_around);
425ba0509b6SJesper Dangaard Brouer 
426f450d539SAlexander Lobakin /**
427f450d539SAlexander Lobakin  * __napi_build_skb - build a network buffer
428f450d539SAlexander Lobakin  * @data: data buffer provided by caller
429*12c1604aSJakub Kicinski  * @frag_size: size of data
430f450d539SAlexander Lobakin  *
431f450d539SAlexander Lobakin  * Version of __build_skb() that uses NAPI percpu caches to obtain
432f450d539SAlexander Lobakin  * skbuff_head instead of inplace allocation.
433f450d539SAlexander Lobakin  *
434f450d539SAlexander Lobakin  * Returns a new &sk_buff on success, %NULL on allocation failure.
435f450d539SAlexander Lobakin  */
436f450d539SAlexander Lobakin static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
437f450d539SAlexander Lobakin {
438f450d539SAlexander Lobakin 	struct sk_buff *skb;
439f450d539SAlexander Lobakin 
440f450d539SAlexander Lobakin 	skb = napi_skb_cache_get();
441f450d539SAlexander Lobakin 	if (unlikely(!skb))
442f450d539SAlexander Lobakin 		return NULL;
443f450d539SAlexander Lobakin 
444f450d539SAlexander Lobakin 	memset(skb, 0, offsetof(struct sk_buff, tail));
445f450d539SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
446f450d539SAlexander Lobakin 
447f450d539SAlexander Lobakin 	return skb;
448f450d539SAlexander Lobakin }
449f450d539SAlexander Lobakin 
450f450d539SAlexander Lobakin /**
451f450d539SAlexander Lobakin  * napi_build_skb - build a network buffer
452f450d539SAlexander Lobakin  * @data: data buffer provided by caller
453*12c1604aSJakub Kicinski  * @frag_size: size of data
454f450d539SAlexander Lobakin  *
455f450d539SAlexander Lobakin  * Version of __napi_build_skb() that takes care of skb->head_frag
456f450d539SAlexander Lobakin  * and skb->pfmemalloc when the data is a page or page fragment.
457f450d539SAlexander Lobakin  *
458f450d539SAlexander Lobakin  * Returns a new &sk_buff on success, %NULL on allocation failure.
459f450d539SAlexander Lobakin  */
460f450d539SAlexander Lobakin struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
461f450d539SAlexander Lobakin {
462f450d539SAlexander Lobakin 	struct sk_buff *skb = __napi_build_skb(data, frag_size);
463f450d539SAlexander Lobakin 
464f450d539SAlexander Lobakin 	if (likely(skb) && frag_size) {
465f450d539SAlexander Lobakin 		skb->head_frag = 1;
466f450d539SAlexander Lobakin 		skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
467f450d539SAlexander Lobakin 	}
468f450d539SAlexander Lobakin 
469f450d539SAlexander Lobakin 	return skb;
470f450d539SAlexander Lobakin }
471f450d539SAlexander Lobakin EXPORT_SYMBOL(napi_build_skb);
472f450d539SAlexander Lobakin 
4735381b23dSAlexander Lobakin /*
4745381b23dSAlexander Lobakin  * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
4755381b23dSAlexander Lobakin  * the caller if emergency pfmemalloc reserves are being used. If it is and
4765381b23dSAlexander Lobakin  * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
4775381b23dSAlexander Lobakin  * may be used. Otherwise, the packet data may be discarded until enough
4785381b23dSAlexander Lobakin  * memory is free
4795381b23dSAlexander Lobakin  */
480ef28095fSAlexander Lobakin static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
481ef28095fSAlexander Lobakin 			     bool *pfmemalloc)
4825381b23dSAlexander Lobakin {
4835381b23dSAlexander Lobakin 	void *obj;
4845381b23dSAlexander Lobakin 	bool ret_pfmemalloc = false;
4855381b23dSAlexander Lobakin 
4865381b23dSAlexander Lobakin 	/*
4875381b23dSAlexander Lobakin 	 * Try a regular allocation, when that fails and we're not entitled
4885381b23dSAlexander Lobakin 	 * to the reserves, fail.
4895381b23dSAlexander Lobakin 	 */
4905381b23dSAlexander Lobakin 	obj = kmalloc_node_track_caller(size,
4915381b23dSAlexander Lobakin 					flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
4925381b23dSAlexander Lobakin 					node);
4935381b23dSAlexander Lobakin 	if (obj || !(gfp_pfmemalloc_allowed(flags)))
4945381b23dSAlexander Lobakin 		goto out;
4955381b23dSAlexander Lobakin 
4965381b23dSAlexander Lobakin 	/* Try again but now we are using pfmemalloc reserves */
4975381b23dSAlexander Lobakin 	ret_pfmemalloc = true;
4985381b23dSAlexander Lobakin 	obj = kmalloc_node_track_caller(size, flags, node);
4995381b23dSAlexander Lobakin 
5005381b23dSAlexander Lobakin out:
5015381b23dSAlexander Lobakin 	if (pfmemalloc)
5025381b23dSAlexander Lobakin 		*pfmemalloc = ret_pfmemalloc;
5035381b23dSAlexander Lobakin 
5045381b23dSAlexander Lobakin 	return obj;
5055381b23dSAlexander Lobakin }
5065381b23dSAlexander Lobakin 
5075381b23dSAlexander Lobakin /* 	Allocate a new skbuff. We do this ourselves so we can fill in a few
5085381b23dSAlexander Lobakin  *	'private' fields and also do memory statistics to find all the
5095381b23dSAlexander Lobakin  *	[BEEP] leaks.
5105381b23dSAlexander Lobakin  *
5115381b23dSAlexander Lobakin  */
5125381b23dSAlexander Lobakin 
5135381b23dSAlexander Lobakin /**
5145381b23dSAlexander Lobakin  *	__alloc_skb	-	allocate a network buffer
5155381b23dSAlexander Lobakin  *	@size: size to allocate
5165381b23dSAlexander Lobakin  *	@gfp_mask: allocation mask
5175381b23dSAlexander Lobakin  *	@flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
5185381b23dSAlexander Lobakin  *		instead of head cache and allocate a cloned (child) skb.
5195381b23dSAlexander Lobakin  *		If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
5205381b23dSAlexander Lobakin  *		allocations in case the data is required for writeback
5215381b23dSAlexander Lobakin  *	@node: numa node to allocate memory on
5225381b23dSAlexander Lobakin  *
5235381b23dSAlexander Lobakin  *	Allocate a new &sk_buff. The returned buffer has no headroom and a
5245381b23dSAlexander Lobakin  *	tail room of at least size bytes. The object has a reference count
5255381b23dSAlexander Lobakin  *	of one. The return is the buffer. On a failure the return is %NULL.
5265381b23dSAlexander Lobakin  *
5275381b23dSAlexander Lobakin  *	Buffers may only be allocated from interrupts using a @gfp_mask of
5285381b23dSAlexander Lobakin  *	%GFP_ATOMIC.
5295381b23dSAlexander Lobakin  */
5305381b23dSAlexander Lobakin struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
5315381b23dSAlexander Lobakin 			    int flags, int node)
5325381b23dSAlexander Lobakin {
5335381b23dSAlexander Lobakin 	struct kmem_cache *cache;
5345381b23dSAlexander Lobakin 	struct sk_buff *skb;
535a5df6333SLi RongQing 	unsigned int osize;
5365381b23dSAlexander Lobakin 	bool pfmemalloc;
537a5df6333SLi RongQing 	u8 *data;
5385381b23dSAlexander Lobakin 
5395381b23dSAlexander Lobakin 	cache = (flags & SKB_ALLOC_FCLONE)
5405381b23dSAlexander Lobakin 		? skbuff_fclone_cache : skbuff_head_cache;
5415381b23dSAlexander Lobakin 
5425381b23dSAlexander Lobakin 	if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
5435381b23dSAlexander Lobakin 		gfp_mask |= __GFP_MEMALLOC;
5445381b23dSAlexander Lobakin 
5455381b23dSAlexander Lobakin 	/* Get the HEAD */
546d13612b5SAlexander Lobakin 	if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
547d13612b5SAlexander Lobakin 	    likely(node == NUMA_NO_NODE || node == numa_mem_id()))
548d13612b5SAlexander Lobakin 		skb = napi_skb_cache_get();
549d13612b5SAlexander Lobakin 	else
550d13612b5SAlexander Lobakin 		skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
551df1ae022SAlexander Lobakin 	if (unlikely(!skb))
552df1ae022SAlexander Lobakin 		return NULL;
5535381b23dSAlexander Lobakin 	prefetchw(skb);
5545381b23dSAlexander Lobakin 
5555381b23dSAlexander Lobakin 	/* We do our best to align skb_shared_info on a separate cache
5565381b23dSAlexander Lobakin 	 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
5575381b23dSAlexander Lobakin 	 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
5585381b23dSAlexander Lobakin 	 * Both skb->head and skb_shared_info are cache line aligned.
5595381b23dSAlexander Lobakin 	 */
5605381b23dSAlexander Lobakin 	size = SKB_DATA_ALIGN(size);
5615381b23dSAlexander Lobakin 	size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
56212d6c1d3SKees Cook 	osize = kmalloc_size_roundup(size);
56312d6c1d3SKees Cook 	data = kmalloc_reserve(osize, gfp_mask, node, &pfmemalloc);
564df1ae022SAlexander Lobakin 	if (unlikely(!data))
5655381b23dSAlexander Lobakin 		goto nodata;
56612d6c1d3SKees Cook 	/* kmalloc_size_roundup() might give us more room than requested.
5675381b23dSAlexander Lobakin 	 * Put skb_shared_info exactly at the end of allocated zone,
5685381b23dSAlexander Lobakin 	 * to allow max possible filling before reallocation.
5695381b23dSAlexander Lobakin 	 */
570a5df6333SLi RongQing 	size = SKB_WITH_OVERHEAD(osize);
5715381b23dSAlexander Lobakin 	prefetchw(data + size);
5725381b23dSAlexander Lobakin 
5735381b23dSAlexander Lobakin 	/*
5745381b23dSAlexander Lobakin 	 * Only clear those fields we need to clear, not those that we will
5755381b23dSAlexander Lobakin 	 * actually initialise below. Hence, don't put any more fields after
5765381b23dSAlexander Lobakin 	 * the tail pointer in struct sk_buff!
5775381b23dSAlexander Lobakin 	 */
5785381b23dSAlexander Lobakin 	memset(skb, 0, offsetof(struct sk_buff, tail));
579a5df6333SLi RongQing 	__build_skb_around(skb, data, osize);
5805381b23dSAlexander Lobakin 	skb->pfmemalloc = pfmemalloc;
5815381b23dSAlexander Lobakin 
5825381b23dSAlexander Lobakin 	if (flags & SKB_ALLOC_FCLONE) {
5835381b23dSAlexander Lobakin 		struct sk_buff_fclones *fclones;
5845381b23dSAlexander Lobakin 
5855381b23dSAlexander Lobakin 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
5865381b23dSAlexander Lobakin 
5875381b23dSAlexander Lobakin 		skb->fclone = SKB_FCLONE_ORIG;
5885381b23dSAlexander Lobakin 		refcount_set(&fclones->fclone_ref, 1);
5895381b23dSAlexander Lobakin 	}
5905381b23dSAlexander Lobakin 
5915381b23dSAlexander Lobakin 	return skb;
592df1ae022SAlexander Lobakin 
5935381b23dSAlexander Lobakin nodata:
5945381b23dSAlexander Lobakin 	kmem_cache_free(cache, skb);
595df1ae022SAlexander Lobakin 	return NULL;
5965381b23dSAlexander Lobakin }
5975381b23dSAlexander Lobakin EXPORT_SYMBOL(__alloc_skb);
5985381b23dSAlexander Lobakin 
5997ba7aeabSSebastian Andrzej Siewior /**
600fd11a83dSAlexander Duyck  *	__netdev_alloc_skb - allocate an skbuff for rx on a specific device
601fd11a83dSAlexander Duyck  *	@dev: network device to receive on
602d7499160SMasanari Iida  *	@len: length to allocate
603fd11a83dSAlexander Duyck  *	@gfp_mask: get_free_pages mask, passed to alloc_skb
604fd11a83dSAlexander Duyck  *
605fd11a83dSAlexander Duyck  *	Allocate a new &sk_buff and assign it a usage count of one. The
606fd11a83dSAlexander Duyck  *	buffer has NET_SKB_PAD headroom built in. Users should allocate
607fd11a83dSAlexander Duyck  *	the headroom they think they need without accounting for the
608fd11a83dSAlexander Duyck  *	built in space. The built in space is used for optimisations.
609fd11a83dSAlexander Duyck  *
610fd11a83dSAlexander Duyck  *	%NULL is returned if there is no free memory.
611fd11a83dSAlexander Duyck  */
6129451980aSAlexander Duyck struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
6139451980aSAlexander Duyck 				   gfp_t gfp_mask)
614fd11a83dSAlexander Duyck {
615b63ae8caSAlexander Duyck 	struct page_frag_cache *nc;
616fd11a83dSAlexander Duyck 	struct sk_buff *skb;
6179451980aSAlexander Duyck 	bool pfmemalloc;
6189451980aSAlexander Duyck 	void *data;
619fd11a83dSAlexander Duyck 
6209451980aSAlexander Duyck 	len += NET_SKB_PAD;
621fd11a83dSAlexander Duyck 
62266c55602SAlexander Lobakin 	/* If requested length is either too small or too big,
62366c55602SAlexander Lobakin 	 * we use kmalloc() for skb->head allocation.
62466c55602SAlexander Lobakin 	 */
62566c55602SAlexander Lobakin 	if (len <= SKB_WITH_OVERHEAD(1024) ||
62666c55602SAlexander Lobakin 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
627d0164adcSMel Gorman 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
628a080e7bdSAlexander Duyck 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
629a080e7bdSAlexander Duyck 		if (!skb)
630a080e7bdSAlexander Duyck 			goto skb_fail;
631a080e7bdSAlexander Duyck 		goto skb_success;
632a080e7bdSAlexander Duyck 	}
6339451980aSAlexander Duyck 
6349451980aSAlexander Duyck 	len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
6359451980aSAlexander Duyck 	len = SKB_DATA_ALIGN(len);
6369451980aSAlexander Duyck 
6379451980aSAlexander Duyck 	if (sk_memalloc_socks())
6389451980aSAlexander Duyck 		gfp_mask |= __GFP_MEMALLOC;
6399451980aSAlexander Duyck 
640afa79d08SChangbin Du 	if (in_hardirq() || irqs_disabled()) {
6419451980aSAlexander Duyck 		nc = this_cpu_ptr(&netdev_alloc_cache);
6428c2dd3e4SAlexander Duyck 		data = page_frag_alloc(nc, len, gfp_mask);
6439451980aSAlexander Duyck 		pfmemalloc = nc->pfmemalloc;
64492dcabd7SSebastian Andrzej Siewior 	} else {
64592dcabd7SSebastian Andrzej Siewior 		local_bh_disable();
64692dcabd7SSebastian Andrzej Siewior 		nc = this_cpu_ptr(&napi_alloc_cache.page);
64792dcabd7SSebastian Andrzej Siewior 		data = page_frag_alloc(nc, len, gfp_mask);
64892dcabd7SSebastian Andrzej Siewior 		pfmemalloc = nc->pfmemalloc;
64992dcabd7SSebastian Andrzej Siewior 		local_bh_enable();
65092dcabd7SSebastian Andrzej Siewior 	}
6519451980aSAlexander Duyck 
6529451980aSAlexander Duyck 	if (unlikely(!data))
6539451980aSAlexander Duyck 		return NULL;
6549451980aSAlexander Duyck 
6559451980aSAlexander Duyck 	skb = __build_skb(data, len);
6569451980aSAlexander Duyck 	if (unlikely(!skb)) {
657181edb2bSAlexander Duyck 		skb_free_frag(data);
6589451980aSAlexander Duyck 		return NULL;
6599451980aSAlexander Duyck 	}
6609451980aSAlexander Duyck 
6619451980aSAlexander Duyck 	if (pfmemalloc)
6629451980aSAlexander Duyck 		skb->pfmemalloc = 1;
6639451980aSAlexander Duyck 	skb->head_frag = 1;
6649451980aSAlexander Duyck 
665a080e7bdSAlexander Duyck skb_success:
6668af27456SChristoph Hellwig 	skb_reserve(skb, NET_SKB_PAD);
6677b2e497aSChristoph Hellwig 	skb->dev = dev;
668fd11a83dSAlexander Duyck 
669a080e7bdSAlexander Duyck skb_fail:
6708af27456SChristoph Hellwig 	return skb;
6718af27456SChristoph Hellwig }
672b4ac530fSDavid S. Miller EXPORT_SYMBOL(__netdev_alloc_skb);
6731da177e4SLinus Torvalds 
674fd11a83dSAlexander Duyck /**
675fd11a83dSAlexander Duyck  *	__napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
676fd11a83dSAlexander Duyck  *	@napi: napi instance this buffer was allocated for
677d7499160SMasanari Iida  *	@len: length to allocate
678fd11a83dSAlexander Duyck  *	@gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
679fd11a83dSAlexander Duyck  *
680fd11a83dSAlexander Duyck  *	Allocate a new sk_buff for use in NAPI receive.  This buffer will
681fd11a83dSAlexander Duyck  *	attempt to allocate the head from a special reserved region used
682fd11a83dSAlexander Duyck  *	only for NAPI Rx allocation.  By doing this we can save several
683fd11a83dSAlexander Duyck  *	CPU cycles by avoiding having to disable and re-enable IRQs.
684fd11a83dSAlexander Duyck  *
685fd11a83dSAlexander Duyck  *	%NULL is returned if there is no free memory.
686fd11a83dSAlexander Duyck  */
6879451980aSAlexander Duyck struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
6889451980aSAlexander Duyck 				 gfp_t gfp_mask)
689fd11a83dSAlexander Duyck {
6903226b158SEric Dumazet 	struct napi_alloc_cache *nc;
691fd11a83dSAlexander Duyck 	struct sk_buff *skb;
692dbae2b06SPaolo Abeni 	bool pfmemalloc;
6939451980aSAlexander Duyck 	void *data;
694fd11a83dSAlexander Duyck 
695ee2640dfSEric Dumazet 	DEBUG_NET_WARN_ON_ONCE(!in_softirq());
6969451980aSAlexander Duyck 	len += NET_SKB_PAD + NET_IP_ALIGN;
697fd11a83dSAlexander Duyck 
6983226b158SEric Dumazet 	/* If requested length is either too small or too big,
6993226b158SEric Dumazet 	 * we use kmalloc() for skb->head allocation.
700dbae2b06SPaolo Abeni 	 * When the small frag allocator is available, prefer it over kmalloc
701dbae2b06SPaolo Abeni 	 * for small fragments
7023226b158SEric Dumazet 	 */
703dbae2b06SPaolo Abeni 	if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
7043226b158SEric Dumazet 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
705d0164adcSMel Gorman 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
706cfb8ec65SAlexander Lobakin 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
707cfb8ec65SAlexander Lobakin 				  NUMA_NO_NODE);
708a080e7bdSAlexander Duyck 		if (!skb)
709a080e7bdSAlexander Duyck 			goto skb_fail;
710a080e7bdSAlexander Duyck 		goto skb_success;
711a080e7bdSAlexander Duyck 	}
7129451980aSAlexander Duyck 
7133226b158SEric Dumazet 	nc = this_cpu_ptr(&napi_alloc_cache);
7149451980aSAlexander Duyck 
7159451980aSAlexander Duyck 	if (sk_memalloc_socks())
7169451980aSAlexander Duyck 		gfp_mask |= __GFP_MEMALLOC;
7179451980aSAlexander Duyck 
718dbae2b06SPaolo Abeni 	if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
719dbae2b06SPaolo Abeni 		/* we are artificially inflating the allocation size, but
720dbae2b06SPaolo Abeni 		 * that is not as bad as it may look like, as:
721dbae2b06SPaolo Abeni 		 * - 'len' less than GRO_MAX_HEAD makes little sense
722dbae2b06SPaolo Abeni 		 * - On most systems, larger 'len' values lead to fragment
723dbae2b06SPaolo Abeni 		 *   size above 512 bytes
724dbae2b06SPaolo Abeni 		 * - kmalloc would use the kmalloc-1k slab for such values
725dbae2b06SPaolo Abeni 		 * - Builds with smaller GRO_MAX_HEAD will very likely do
726dbae2b06SPaolo Abeni 		 *   little networking, as that implies no WiFi and no
727dbae2b06SPaolo Abeni 		 *   tunnels support, and 32 bits arches.
728dbae2b06SPaolo Abeni 		 */
729dbae2b06SPaolo Abeni 		len = SZ_1K;
730dbae2b06SPaolo Abeni 
731dbae2b06SPaolo Abeni 		data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
732dbae2b06SPaolo Abeni 		pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
733dbae2b06SPaolo Abeni 	} else {
734dbae2b06SPaolo Abeni 		len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
735dbae2b06SPaolo Abeni 		len = SKB_DATA_ALIGN(len);
736dbae2b06SPaolo Abeni 
7378c2dd3e4SAlexander Duyck 		data = page_frag_alloc(&nc->page, len, gfp_mask);
738dbae2b06SPaolo Abeni 		pfmemalloc = nc->page.pfmemalloc;
739dbae2b06SPaolo Abeni 	}
740dbae2b06SPaolo Abeni 
7419451980aSAlexander Duyck 	if (unlikely(!data))
7429451980aSAlexander Duyck 		return NULL;
7439451980aSAlexander Duyck 
744cfb8ec65SAlexander Lobakin 	skb = __napi_build_skb(data, len);
7459451980aSAlexander Duyck 	if (unlikely(!skb)) {
746181edb2bSAlexander Duyck 		skb_free_frag(data);
7479451980aSAlexander Duyck 		return NULL;
7489451980aSAlexander Duyck 	}
7499451980aSAlexander Duyck 
750dbae2b06SPaolo Abeni 	if (pfmemalloc)
7519451980aSAlexander Duyck 		skb->pfmemalloc = 1;
7529451980aSAlexander Duyck 	skb->head_frag = 1;
7539451980aSAlexander Duyck 
754a080e7bdSAlexander Duyck skb_success:
755fd11a83dSAlexander Duyck 	skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
756fd11a83dSAlexander Duyck 	skb->dev = napi->dev;
757fd11a83dSAlexander Duyck 
758a080e7bdSAlexander Duyck skb_fail:
759fd11a83dSAlexander Duyck 	return skb;
760fd11a83dSAlexander Duyck }
761fd11a83dSAlexander Duyck EXPORT_SYMBOL(__napi_alloc_skb);
762fd11a83dSAlexander Duyck 
763654bed16SPeter Zijlstra void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
76450269e19SEric Dumazet 		     int size, unsigned int truesize)
765654bed16SPeter Zijlstra {
766654bed16SPeter Zijlstra 	skb_fill_page_desc(skb, i, page, off, size);
767654bed16SPeter Zijlstra 	skb->len += size;
768654bed16SPeter Zijlstra 	skb->data_len += size;
76950269e19SEric Dumazet 	skb->truesize += truesize;
770654bed16SPeter Zijlstra }
771654bed16SPeter Zijlstra EXPORT_SYMBOL(skb_add_rx_frag);
772654bed16SPeter Zijlstra 
773f8e617e1SJason Wang void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
774f8e617e1SJason Wang 			  unsigned int truesize)
775f8e617e1SJason Wang {
776f8e617e1SJason Wang 	skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
777f8e617e1SJason Wang 
778f8e617e1SJason Wang 	skb_frag_size_add(frag, size);
779f8e617e1SJason Wang 	skb->len += size;
780f8e617e1SJason Wang 	skb->data_len += size;
781f8e617e1SJason Wang 	skb->truesize += truesize;
782f8e617e1SJason Wang }
783f8e617e1SJason Wang EXPORT_SYMBOL(skb_coalesce_rx_frag);
784f8e617e1SJason Wang 
78527b437c8SHerbert Xu static void skb_drop_list(struct sk_buff **listp)
7861da177e4SLinus Torvalds {
787bd8a7036SEric Dumazet 	kfree_skb_list(*listp);
78827b437c8SHerbert Xu 	*listp = NULL;
7891da177e4SLinus Torvalds }
7901da177e4SLinus Torvalds 
79127b437c8SHerbert Xu static inline void skb_drop_fraglist(struct sk_buff *skb)
79227b437c8SHerbert Xu {
79327b437c8SHerbert Xu 	skb_drop_list(&skb_shinfo(skb)->frag_list);
79427b437c8SHerbert Xu }
79527b437c8SHerbert Xu 
7961da177e4SLinus Torvalds static void skb_clone_fraglist(struct sk_buff *skb)
7971da177e4SLinus Torvalds {
7981da177e4SLinus Torvalds 	struct sk_buff *list;
7991da177e4SLinus Torvalds 
800fbb398a8SDavid S. Miller 	skb_walk_frags(skb, list)
8011da177e4SLinus Torvalds 		skb_get(list);
8021da177e4SLinus Torvalds }
8031da177e4SLinus Torvalds 
8044727bab4SYunsheng Lin static bool skb_pp_recycle(struct sk_buff *skb, void *data)
8054727bab4SYunsheng Lin {
8064727bab4SYunsheng Lin 	if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
8074727bab4SYunsheng Lin 		return false;
8084727bab4SYunsheng Lin 	return page_pool_return_skb_page(virt_to_page(data));
8094727bab4SYunsheng Lin }
8104727bab4SYunsheng Lin 
811d3836f21SEric Dumazet static void skb_free_head(struct sk_buff *skb)
812d3836f21SEric Dumazet {
813181edb2bSAlexander Duyck 	unsigned char *head = skb->head;
814181edb2bSAlexander Duyck 
8156a5bcd84SIlias Apalodimas 	if (skb->head_frag) {
8166a5bcd84SIlias Apalodimas 		if (skb_pp_recycle(skb, head))
8176a5bcd84SIlias Apalodimas 			return;
818181edb2bSAlexander Duyck 		skb_free_frag(head);
8196a5bcd84SIlias Apalodimas 	} else {
820181edb2bSAlexander Duyck 		kfree(head);
821d3836f21SEric Dumazet 	}
8226a5bcd84SIlias Apalodimas }
823d3836f21SEric Dumazet 
824511a3edaSEric Dumazet static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason)
8251da177e4SLinus Torvalds {
826ff04a771SEric Dumazet 	struct skb_shared_info *shinfo = skb_shinfo(skb);
8271da177e4SLinus Torvalds 	int i;
828ff04a771SEric Dumazet 
829ff04a771SEric Dumazet 	if (skb->cloned &&
830ff04a771SEric Dumazet 	    atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
831ff04a771SEric Dumazet 			      &shinfo->dataref))
8322cc3aeb5SIlias Apalodimas 		goto exit;
833ff04a771SEric Dumazet 
834753f1ca4SPavel Begunkov 	if (skb_zcopy(skb)) {
835753f1ca4SPavel Begunkov 		bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
836753f1ca4SPavel Begunkov 
83770c43167SJonathan Lemon 		skb_zcopy_clear(skb, true);
838753f1ca4SPavel Begunkov 		if (skip_unref)
839753f1ca4SPavel Begunkov 			goto free_head;
840753f1ca4SPavel Begunkov 	}
84170c43167SJonathan Lemon 
842ff04a771SEric Dumazet 	for (i = 0; i < shinfo->nr_frags; i++)
8436a5bcd84SIlias Apalodimas 		__skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
8441da177e4SLinus Torvalds 
845753f1ca4SPavel Begunkov free_head:
846ff04a771SEric Dumazet 	if (shinfo->frag_list)
847511a3edaSEric Dumazet 		kfree_skb_list_reason(shinfo->frag_list, reason);
8481da177e4SLinus Torvalds 
849d3836f21SEric Dumazet 	skb_free_head(skb);
8502cc3aeb5SIlias Apalodimas exit:
8512cc3aeb5SIlias Apalodimas 	/* When we clone an SKB we copy the reycling bit. The pp_recycle
8522cc3aeb5SIlias Apalodimas 	 * bit is only set on the head though, so in order to avoid races
8532cc3aeb5SIlias Apalodimas 	 * while trying to recycle fragments on __skb_frag_unref() we need
8542cc3aeb5SIlias Apalodimas 	 * to make one SKB responsible for triggering the recycle path.
8552cc3aeb5SIlias Apalodimas 	 * So disable the recycling bit if an SKB is cloned and we have
85658e61e41STom Rix 	 * additional references to the fragmented part of the SKB.
8572cc3aeb5SIlias Apalodimas 	 * Eventually the last SKB will have the recycling bit set and it's
8582cc3aeb5SIlias Apalodimas 	 * dataref set to 0, which will trigger the recycling
8592cc3aeb5SIlias Apalodimas 	 */
8602cc3aeb5SIlias Apalodimas 	skb->pp_recycle = 0;
8611da177e4SLinus Torvalds }
8621da177e4SLinus Torvalds 
8631da177e4SLinus Torvalds /*
8641da177e4SLinus Torvalds  *	Free an skbuff by memory without cleaning the state.
8651da177e4SLinus Torvalds  */
8662d4baff8SHerbert Xu static void kfree_skbmem(struct sk_buff *skb)
8671da177e4SLinus Torvalds {
868d0bf4a9eSEric Dumazet 	struct sk_buff_fclones *fclones;
869d179cd12SDavid S. Miller 
870d179cd12SDavid S. Miller 	switch (skb->fclone) {
871d179cd12SDavid S. Miller 	case SKB_FCLONE_UNAVAILABLE:
8721da177e4SLinus Torvalds 		kmem_cache_free(skbuff_head_cache, skb);
8736ffe75ebSEric Dumazet 		return;
874d179cd12SDavid S. Miller 
875d179cd12SDavid S. Miller 	case SKB_FCLONE_ORIG:
876d0bf4a9eSEric Dumazet 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
8776ffe75ebSEric Dumazet 
8786ffe75ebSEric Dumazet 		/* We usually free the clone (TX completion) before original skb
8796ffe75ebSEric Dumazet 		 * This test would have no chance to be true for the clone,
8806ffe75ebSEric Dumazet 		 * while here, branch prediction will be good.
8816ffe75ebSEric Dumazet 		 */
8822638595aSReshetova, Elena 		if (refcount_read(&fclones->fclone_ref) == 1)
8836ffe75ebSEric Dumazet 			goto fastpath;
884d179cd12SDavid S. Miller 		break;
885d179cd12SDavid S. Miller 
8866ffe75ebSEric Dumazet 	default: /* SKB_FCLONE_CLONE */
887d0bf4a9eSEric Dumazet 		fclones = container_of(skb, struct sk_buff_fclones, skb2);
888d179cd12SDavid S. Miller 		break;
8893ff50b79SStephen Hemminger 	}
8902638595aSReshetova, Elena 	if (!refcount_dec_and_test(&fclones->fclone_ref))
8916ffe75ebSEric Dumazet 		return;
8926ffe75ebSEric Dumazet fastpath:
8936ffe75ebSEric Dumazet 	kmem_cache_free(skbuff_fclone_cache, fclones);
8941da177e4SLinus Torvalds }
8951da177e4SLinus Torvalds 
8960a463c78SPaolo Abeni void skb_release_head_state(struct sk_buff *skb)
8971da177e4SLinus Torvalds {
898adf30907SEric Dumazet 	skb_dst_drop(skb);
8991da177e4SLinus Torvalds 	if (skb->destructor) {
9007890e2f0SEric Dumazet 		DEBUG_NET_WARN_ON_ONCE(in_hardirq());
9011da177e4SLinus Torvalds 		skb->destructor(skb);
9021da177e4SLinus Torvalds 	}
903a3bf7ae9SIgor Maravić #if IS_ENABLED(CONFIG_NF_CONNTRACK)
904cb9c6836SFlorian Westphal 	nf_conntrack_put(skb_nfct(skb));
9052fc72c7bSKOVACS Krisztian #endif
906df5042f4SFlorian Westphal 	skb_ext_put(skb);
90704a4bb55SLennert Buytenhek }
90804a4bb55SLennert Buytenhek 
90904a4bb55SLennert Buytenhek /* Free everything but the sk_buff shell. */
910511a3edaSEric Dumazet static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason)
91104a4bb55SLennert Buytenhek {
91204a4bb55SLennert Buytenhek 	skb_release_head_state(skb);
913a28b1b90SFlorian Westphal 	if (likely(skb->head))
914511a3edaSEric Dumazet 		skb_release_data(skb, reason);
9152d4baff8SHerbert Xu }
9161da177e4SLinus Torvalds 
9172d4baff8SHerbert Xu /**
9182d4baff8SHerbert Xu  *	__kfree_skb - private function
9192d4baff8SHerbert Xu  *	@skb: buffer
9202d4baff8SHerbert Xu  *
9212d4baff8SHerbert Xu  *	Free an sk_buff. Release anything attached to the buffer.
9222d4baff8SHerbert Xu  *	Clean the state. This is an internal helper function. Users should
9232d4baff8SHerbert Xu  *	always call kfree_skb
9242d4baff8SHerbert Xu  */
9252d4baff8SHerbert Xu 
9262d4baff8SHerbert Xu void __kfree_skb(struct sk_buff *skb)
9272d4baff8SHerbert Xu {
928511a3edaSEric Dumazet 	skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
9291da177e4SLinus Torvalds 	kfree_skbmem(skb);
9301da177e4SLinus Torvalds }
931b4ac530fSDavid S. Miller EXPORT_SYMBOL(__kfree_skb);
9321da177e4SLinus Torvalds 
9331da177e4SLinus Torvalds /**
934c504e5c2SMenglong Dong  *	kfree_skb_reason - free an sk_buff with special reason
935231d06aeSJörn Engel  *	@skb: buffer to free
936c504e5c2SMenglong Dong  *	@reason: reason why this skb is dropped
937231d06aeSJörn Engel  *
938231d06aeSJörn Engel  *	Drop a reference to the buffer and free it if the usage count has
939c504e5c2SMenglong Dong  *	hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
940c504e5c2SMenglong Dong  *	tracepoint.
941231d06aeSJörn Engel  */
942c205cc75SMenglong Dong void __fix_address
943c205cc75SMenglong Dong kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
944231d06aeSJörn Engel {
945c205cc75SMenglong Dong 	if (unlikely(!skb_unref(skb)))
946231d06aeSJörn Engel 		return;
9473889a803SPaolo Abeni 
94820bbcd0aSMenglong Dong 	DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
94920bbcd0aSMenglong Dong 
9500e84afe8SEric Dumazet 	if (reason == SKB_CONSUMED)
9510e84afe8SEric Dumazet 		trace_consume_skb(skb);
9520e84afe8SEric Dumazet 	else
953c504e5c2SMenglong Dong 		trace_kfree_skb(skb, __builtin_return_address(0), reason);
954231d06aeSJörn Engel 	__kfree_skb(skb);
955231d06aeSJörn Engel }
956c504e5c2SMenglong Dong EXPORT_SYMBOL(kfree_skb_reason);
957231d06aeSJörn Engel 
958215b0f19SMenglong Dong void kfree_skb_list_reason(struct sk_buff *segs,
959215b0f19SMenglong Dong 			   enum skb_drop_reason reason)
960bd8a7036SEric Dumazet {
961bd8a7036SEric Dumazet 	while (segs) {
962bd8a7036SEric Dumazet 		struct sk_buff *next = segs->next;
963bd8a7036SEric Dumazet 
964215b0f19SMenglong Dong 		kfree_skb_reason(segs, reason);
965bd8a7036SEric Dumazet 		segs = next;
966bd8a7036SEric Dumazet 	}
967bd8a7036SEric Dumazet }
968215b0f19SMenglong Dong EXPORT_SYMBOL(kfree_skb_list_reason);
969bd8a7036SEric Dumazet 
9706413139dSWillem de Bruijn /* Dump skb information and contents.
9716413139dSWillem de Bruijn  *
9726413139dSWillem de Bruijn  * Must only be called from net_ratelimit()-ed paths.
9736413139dSWillem de Bruijn  *
974302af7c6SVladimir Oltean  * Dumps whole packets if full_pkt, only headers otherwise.
9756413139dSWillem de Bruijn  */
9766413139dSWillem de Bruijn void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
9776413139dSWillem de Bruijn {
9786413139dSWillem de Bruijn 	struct skb_shared_info *sh = skb_shinfo(skb);
9796413139dSWillem de Bruijn 	struct net_device *dev = skb->dev;
9806413139dSWillem de Bruijn 	struct sock *sk = skb->sk;
9816413139dSWillem de Bruijn 	struct sk_buff *list_skb;
9826413139dSWillem de Bruijn 	bool has_mac, has_trans;
9836413139dSWillem de Bruijn 	int headroom, tailroom;
9846413139dSWillem de Bruijn 	int i, len, seg_len;
9856413139dSWillem de Bruijn 
9866413139dSWillem de Bruijn 	if (full_pkt)
9876413139dSWillem de Bruijn 		len = skb->len;
9886413139dSWillem de Bruijn 	else
9896413139dSWillem de Bruijn 		len = min_t(int, skb->len, MAX_HEADER + 128);
9906413139dSWillem de Bruijn 
9916413139dSWillem de Bruijn 	headroom = skb_headroom(skb);
9926413139dSWillem de Bruijn 	tailroom = skb_tailroom(skb);
9936413139dSWillem de Bruijn 
9946413139dSWillem de Bruijn 	has_mac = skb_mac_header_was_set(skb);
9956413139dSWillem de Bruijn 	has_trans = skb_transport_header_was_set(skb);
9966413139dSWillem de Bruijn 
9976413139dSWillem de Bruijn 	printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
9986413139dSWillem de Bruijn 	       "mac=(%d,%d) net=(%d,%d) trans=%d\n"
9996413139dSWillem de Bruijn 	       "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
10006413139dSWillem de Bruijn 	       "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
10016413139dSWillem de Bruijn 	       "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
10026413139dSWillem de Bruijn 	       level, skb->len, headroom, skb_headlen(skb), tailroom,
10036413139dSWillem de Bruijn 	       has_mac ? skb->mac_header : -1,
10046413139dSWillem de Bruijn 	       has_mac ? skb_mac_header_len(skb) : -1,
10056413139dSWillem de Bruijn 	       skb->network_header,
10066413139dSWillem de Bruijn 	       has_trans ? skb_network_header_len(skb) : -1,
10076413139dSWillem de Bruijn 	       has_trans ? skb->transport_header : -1,
10086413139dSWillem de Bruijn 	       sh->tx_flags, sh->nr_frags,
10096413139dSWillem de Bruijn 	       sh->gso_size, sh->gso_type, sh->gso_segs,
10106413139dSWillem de Bruijn 	       skb->csum, skb->ip_summed, skb->csum_complete_sw,
10116413139dSWillem de Bruijn 	       skb->csum_valid, skb->csum_level,
10126413139dSWillem de Bruijn 	       skb->hash, skb->sw_hash, skb->l4_hash,
10136413139dSWillem de Bruijn 	       ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
10146413139dSWillem de Bruijn 
10156413139dSWillem de Bruijn 	if (dev)
10168a03ef67SGal Pressman 		printk("%sdev name=%s feat=%pNF\n",
10176413139dSWillem de Bruijn 		       level, dev->name, &dev->features);
10186413139dSWillem de Bruijn 	if (sk)
1019db8051f3SQian Cai 		printk("%ssk family=%hu type=%u proto=%u\n",
10206413139dSWillem de Bruijn 		       level, sk->sk_family, sk->sk_type, sk->sk_protocol);
10216413139dSWillem de Bruijn 
10226413139dSWillem de Bruijn 	if (full_pkt && headroom)
10236413139dSWillem de Bruijn 		print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
10246413139dSWillem de Bruijn 			       16, 1, skb->head, headroom, false);
10256413139dSWillem de Bruijn 
10266413139dSWillem de Bruijn 	seg_len = min_t(int, skb_headlen(skb), len);
10276413139dSWillem de Bruijn 	if (seg_len)
10286413139dSWillem de Bruijn 		print_hex_dump(level, "skb linear:   ", DUMP_PREFIX_OFFSET,
10296413139dSWillem de Bruijn 			       16, 1, skb->data, seg_len, false);
10306413139dSWillem de Bruijn 	len -= seg_len;
10316413139dSWillem de Bruijn 
10326413139dSWillem de Bruijn 	if (full_pkt && tailroom)
10336413139dSWillem de Bruijn 		print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
10346413139dSWillem de Bruijn 			       16, 1, skb_tail_pointer(skb), tailroom, false);
10356413139dSWillem de Bruijn 
10366413139dSWillem de Bruijn 	for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
10376413139dSWillem de Bruijn 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
10386413139dSWillem de Bruijn 		u32 p_off, p_len, copied;
10396413139dSWillem de Bruijn 		struct page *p;
10406413139dSWillem de Bruijn 		u8 *vaddr;
10416413139dSWillem de Bruijn 
1042b54c9d5bSJonathan Lemon 		skb_frag_foreach_page(frag, skb_frag_off(frag),
10436413139dSWillem de Bruijn 				      skb_frag_size(frag), p, p_off, p_len,
10446413139dSWillem de Bruijn 				      copied) {
10456413139dSWillem de Bruijn 			seg_len = min_t(int, p_len, len);
10466413139dSWillem de Bruijn 			vaddr = kmap_atomic(p);
10476413139dSWillem de Bruijn 			print_hex_dump(level, "skb frag:     ",
10486413139dSWillem de Bruijn 				       DUMP_PREFIX_OFFSET,
10496413139dSWillem de Bruijn 				       16, 1, vaddr + p_off, seg_len, false);
10506413139dSWillem de Bruijn 			kunmap_atomic(vaddr);
10516413139dSWillem de Bruijn 			len -= seg_len;
10526413139dSWillem de Bruijn 			if (!len)
10536413139dSWillem de Bruijn 				break;
10546413139dSWillem de Bruijn 		}
10556413139dSWillem de Bruijn 	}
10566413139dSWillem de Bruijn 
10576413139dSWillem de Bruijn 	if (full_pkt && skb_has_frag_list(skb)) {
10586413139dSWillem de Bruijn 		printk("skb fraglist:\n");
10596413139dSWillem de Bruijn 		skb_walk_frags(skb, list_skb)
10606413139dSWillem de Bruijn 			skb_dump(level, list_skb, true);
10616413139dSWillem de Bruijn 	}
10626413139dSWillem de Bruijn }
10636413139dSWillem de Bruijn EXPORT_SYMBOL(skb_dump);
10646413139dSWillem de Bruijn 
1065d1a203eaSStephen Hemminger /**
106625121173SMichael S. Tsirkin  *	skb_tx_error - report an sk_buff xmit error
106725121173SMichael S. Tsirkin  *	@skb: buffer that triggered an error
106825121173SMichael S. Tsirkin  *
106925121173SMichael S. Tsirkin  *	Report xmit error if a device callback is tracking this skb.
107025121173SMichael S. Tsirkin  *	skb must be freed afterwards.
107125121173SMichael S. Tsirkin  */
107225121173SMichael S. Tsirkin void skb_tx_error(struct sk_buff *skb)
107325121173SMichael S. Tsirkin {
1074753f1ca4SPavel Begunkov 	if (skb) {
1075753f1ca4SPavel Begunkov 		skb_zcopy_downgrade_managed(skb);
10761f8b977aSWillem de Bruijn 		skb_zcopy_clear(skb, true);
107725121173SMichael S. Tsirkin 	}
1078753f1ca4SPavel Begunkov }
107925121173SMichael S. Tsirkin EXPORT_SYMBOL(skb_tx_error);
108025121173SMichael S. Tsirkin 
1081be769db2SHerbert Xu #ifdef CONFIG_TRACEPOINTS
108225121173SMichael S. Tsirkin /**
1083ead2ceb0SNeil Horman  *	consume_skb - free an skbuff
1084ead2ceb0SNeil Horman  *	@skb: buffer to free
1085ead2ceb0SNeil Horman  *
1086ead2ceb0SNeil Horman  *	Drop a ref to the buffer and free it if the usage count has hit zero
1087ead2ceb0SNeil Horman  *	Functions identically to kfree_skb, but kfree_skb assumes that the frame
1088ead2ceb0SNeil Horman  *	is being dropped after a failure and notes that
1089ead2ceb0SNeil Horman  */
1090ead2ceb0SNeil Horman void consume_skb(struct sk_buff *skb)
1091ead2ceb0SNeil Horman {
10923889a803SPaolo Abeni 	if (!skb_unref(skb))
1093ead2ceb0SNeil Horman 		return;
10943889a803SPaolo Abeni 
109507dc22e7SKoki Sanagi 	trace_consume_skb(skb);
1096ead2ceb0SNeil Horman 	__kfree_skb(skb);
1097ead2ceb0SNeil Horman }
1098ead2ceb0SNeil Horman EXPORT_SYMBOL(consume_skb);
1099be769db2SHerbert Xu #endif
1100ead2ceb0SNeil Horman 
11010a463c78SPaolo Abeni /**
1102c1639be9SMauro Carvalho Chehab  *	__consume_stateless_skb - free an skbuff, assuming it is stateless
11030a463c78SPaolo Abeni  *	@skb: buffer to free
11040a463c78SPaolo Abeni  *
1105ca2c1418SPaolo Abeni  *	Alike consume_skb(), but this variant assumes that this is the last
1106ca2c1418SPaolo Abeni  *	skb reference and all the head states have been already dropped
11070a463c78SPaolo Abeni  */
1108ca2c1418SPaolo Abeni void __consume_stateless_skb(struct sk_buff *skb)
11090a463c78SPaolo Abeni {
11100a463c78SPaolo Abeni 	trace_consume_skb(skb);
1111511a3edaSEric Dumazet 	skb_release_data(skb, SKB_CONSUMED);
11120a463c78SPaolo Abeni 	kfree_skbmem(skb);
11130a463c78SPaolo Abeni }
11140a463c78SPaolo Abeni 
1115f450d539SAlexander Lobakin static void napi_skb_cache_put(struct sk_buff *skb)
1116795bb1c0SJesper Dangaard Brouer {
1117795bb1c0SJesper Dangaard Brouer 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1118f450d539SAlexander Lobakin 	u32 i;
1119795bb1c0SJesper Dangaard Brouer 
1120f450d539SAlexander Lobakin 	kasan_poison_object_data(skbuff_head_cache, skb);
1121795bb1c0SJesper Dangaard Brouer 	nc->skb_cache[nc->skb_count++] = skb;
1122795bb1c0SJesper Dangaard Brouer 
1123795bb1c0SJesper Dangaard Brouer 	if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1124f450d539SAlexander Lobakin 		for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1125f450d539SAlexander Lobakin 			kasan_unpoison_object_data(skbuff_head_cache,
1126f450d539SAlexander Lobakin 						   nc->skb_cache[i]);
1127f450d539SAlexander Lobakin 
1128f450d539SAlexander Lobakin 		kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
1129f450d539SAlexander Lobakin 				     nc->skb_cache + NAPI_SKB_CACHE_HALF);
1130f450d539SAlexander Lobakin 		nc->skb_count = NAPI_SKB_CACHE_HALF;
1131795bb1c0SJesper Dangaard Brouer 	}
1132795bb1c0SJesper Dangaard Brouer }
1133f450d539SAlexander Lobakin 
113415fad714SJesper Dangaard Brouer void __kfree_skb_defer(struct sk_buff *skb)
113515fad714SJesper Dangaard Brouer {
1136511a3edaSEric Dumazet 	skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED);
11379243adfcSAlexander Lobakin 	napi_skb_cache_put(skb);
11389243adfcSAlexander Lobakin }
11399243adfcSAlexander Lobakin 
11409243adfcSAlexander Lobakin void napi_skb_free_stolen_head(struct sk_buff *skb)
11419243adfcSAlexander Lobakin {
11429efb4b5bSPaolo Abeni 	if (unlikely(skb->slow_gro)) {
11438550ff8dSPaul Blakey 		nf_reset_ct(skb);
11449243adfcSAlexander Lobakin 		skb_dst_drop(skb);
11459243adfcSAlexander Lobakin 		skb_ext_put(skb);
11465e10da53SPaolo Abeni 		skb_orphan(skb);
11479efb4b5bSPaolo Abeni 		skb->slow_gro = 0;
11489efb4b5bSPaolo Abeni 	}
1149f450d539SAlexander Lobakin 	napi_skb_cache_put(skb);
115015fad714SJesper Dangaard Brouer }
1151795bb1c0SJesper Dangaard Brouer 
1152795bb1c0SJesper Dangaard Brouer void napi_consume_skb(struct sk_buff *skb, int budget)
1153795bb1c0SJesper Dangaard Brouer {
1154885eb0a5SJesper Dangaard Brouer 	/* Zero budget indicate non-NAPI context called us, like netpoll */
1155795bb1c0SJesper Dangaard Brouer 	if (unlikely(!budget)) {
1156885eb0a5SJesper Dangaard Brouer 		dev_consume_skb_any(skb);
1157795bb1c0SJesper Dangaard Brouer 		return;
1158795bb1c0SJesper Dangaard Brouer 	}
1159795bb1c0SJesper Dangaard Brouer 
1160ee2640dfSEric Dumazet 	DEBUG_NET_WARN_ON_ONCE(!in_softirq());
11616454eca8SYunsheng Lin 
11627608894eSPaolo Abeni 	if (!skb_unref(skb))
1163795bb1c0SJesper Dangaard Brouer 		return;
11647608894eSPaolo Abeni 
1165795bb1c0SJesper Dangaard Brouer 	/* if reaching here SKB is ready to free */
1166795bb1c0SJesper Dangaard Brouer 	trace_consume_skb(skb);
1167795bb1c0SJesper Dangaard Brouer 
1168795bb1c0SJesper Dangaard Brouer 	/* if SKB is a clone, don't handle this case */
1169abbdb5a7SEric Dumazet 	if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1170795bb1c0SJesper Dangaard Brouer 		__kfree_skb(skb);
1171795bb1c0SJesper Dangaard Brouer 		return;
1172795bb1c0SJesper Dangaard Brouer 	}
1173795bb1c0SJesper Dangaard Brouer 
1174511a3edaSEric Dumazet 	skb_release_all(skb, SKB_CONSUMED);
1175f450d539SAlexander Lobakin 	napi_skb_cache_put(skb);
1176795bb1c0SJesper Dangaard Brouer }
1177795bb1c0SJesper Dangaard Brouer EXPORT_SYMBOL(napi_consume_skb);
1178795bb1c0SJesper Dangaard Brouer 
117903f61041SKees Cook /* Make sure a field is contained by headers group */
1180b1937227SEric Dumazet #define CHECK_SKB_FIELD(field) \
118103f61041SKees Cook 	BUILD_BUG_ON(offsetof(struct sk_buff, field) !=		\
118203f61041SKees Cook 		     offsetof(struct sk_buff, headers.field));	\
1183b1937227SEric Dumazet 
1184dec18810SHerbert Xu static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1185dec18810SHerbert Xu {
1186dec18810SHerbert Xu 	new->tstamp		= old->tstamp;
1187b1937227SEric Dumazet 	/* We do not copy old->sk */
1188dec18810SHerbert Xu 	new->dev		= old->dev;
1189b1937227SEric Dumazet 	memcpy(new->cb, old->cb, sizeof(old->cb));
11907fee226aSEric Dumazet 	skb_dst_copy(new, old);
1191df5042f4SFlorian Westphal 	__skb_ext_copy(new, old);
1192b1937227SEric Dumazet 	__nf_copy(new, old, false);
11936aa895b0SPatrick McHardy 
119403f61041SKees Cook 	/* Note : this field could be in the headers group.
1195b1937227SEric Dumazet 	 * It is not yet because we do not want to have a 16 bit hole
1196b1937227SEric Dumazet 	 */
1197b1937227SEric Dumazet 	new->queue_mapping = old->queue_mapping;
119806021292SEliezer Tamir 
119903f61041SKees Cook 	memcpy(&new->headers, &old->headers, sizeof(new->headers));
1200b1937227SEric Dumazet 	CHECK_SKB_FIELD(protocol);
1201b1937227SEric Dumazet 	CHECK_SKB_FIELD(csum);
1202b1937227SEric Dumazet 	CHECK_SKB_FIELD(hash);
1203b1937227SEric Dumazet 	CHECK_SKB_FIELD(priority);
1204b1937227SEric Dumazet 	CHECK_SKB_FIELD(skb_iif);
1205b1937227SEric Dumazet 	CHECK_SKB_FIELD(vlan_proto);
1206b1937227SEric Dumazet 	CHECK_SKB_FIELD(vlan_tci);
1207b1937227SEric Dumazet 	CHECK_SKB_FIELD(transport_header);
1208b1937227SEric Dumazet 	CHECK_SKB_FIELD(network_header);
1209b1937227SEric Dumazet 	CHECK_SKB_FIELD(mac_header);
1210b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_protocol);
1211b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_transport_header);
1212b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_network_header);
1213b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_mac_header);
1214b1937227SEric Dumazet 	CHECK_SKB_FIELD(mark);
1215b1937227SEric Dumazet #ifdef CONFIG_NETWORK_SECMARK
1216b1937227SEric Dumazet 	CHECK_SKB_FIELD(secmark);
1217b1937227SEric Dumazet #endif
1218e0d1095aSCong Wang #ifdef CONFIG_NET_RX_BUSY_POLL
1219b1937227SEric Dumazet 	CHECK_SKB_FIELD(napi_id);
122006021292SEliezer Tamir #endif
122168822bdfSEric Dumazet 	CHECK_SKB_FIELD(alloc_cpu);
12222bd82484SEric Dumazet #ifdef CONFIG_XPS
12232bd82484SEric Dumazet 	CHECK_SKB_FIELD(sender_cpu);
12242bd82484SEric Dumazet #endif
1225b1937227SEric Dumazet #ifdef CONFIG_NET_SCHED
1226b1937227SEric Dumazet 	CHECK_SKB_FIELD(tc_index);
1227b1937227SEric Dumazet #endif
1228b1937227SEric Dumazet 
1229dec18810SHerbert Xu }
1230dec18810SHerbert Xu 
123182c49a35SHerbert Xu /*
123282c49a35SHerbert Xu  * You should not add any new code to this function.  Add it to
123382c49a35SHerbert Xu  * __copy_skb_header above instead.
123482c49a35SHerbert Xu  */
1235e0053ec0SHerbert Xu static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
12361da177e4SLinus Torvalds {
12371da177e4SLinus Torvalds #define C(x) n->x = skb->x
12381da177e4SLinus Torvalds 
12391da177e4SLinus Torvalds 	n->next = n->prev = NULL;
12401da177e4SLinus Torvalds 	n->sk = NULL;
1241dec18810SHerbert Xu 	__copy_skb_header(n, skb);
1242dec18810SHerbert Xu 
12431da177e4SLinus Torvalds 	C(len);
12441da177e4SLinus Torvalds 	C(data_len);
12453e6b3b2eSAlexey Dobriyan 	C(mac_len);
1246334a8132SPatrick McHardy 	n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
124702f1c89dSPaul Moore 	n->cloned = 1;
12481da177e4SLinus Torvalds 	n->nohdr = 0;
1249b13dda9fSEric Dumazet 	n->peeked = 0;
1250e78bfb07SStefano Brivio 	C(pfmemalloc);
12516a5bcd84SIlias Apalodimas 	C(pp_recycle);
12521da177e4SLinus Torvalds 	n->destructor = NULL;
12531da177e4SLinus Torvalds 	C(tail);
12541da177e4SLinus Torvalds 	C(end);
125502f1c89dSPaul Moore 	C(head);
1256d3836f21SEric Dumazet 	C(head_frag);
125702f1c89dSPaul Moore 	C(data);
125802f1c89dSPaul Moore 	C(truesize);
125963354797SReshetova, Elena 	refcount_set(&n->users, 1);
12601da177e4SLinus Torvalds 
12611da177e4SLinus Torvalds 	atomic_inc(&(skb_shinfo(skb)->dataref));
12621da177e4SLinus Torvalds 	skb->cloned = 1;
12631da177e4SLinus Torvalds 
12641da177e4SLinus Torvalds 	return n;
1265e0053ec0SHerbert Xu #undef C
1266e0053ec0SHerbert Xu }
1267e0053ec0SHerbert Xu 
1268e0053ec0SHerbert Xu /**
1269da29e4b4SJakub Kicinski  * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1270da29e4b4SJakub Kicinski  * @first: first sk_buff of the msg
1271da29e4b4SJakub Kicinski  */
1272da29e4b4SJakub Kicinski struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1273da29e4b4SJakub Kicinski {
1274da29e4b4SJakub Kicinski 	struct sk_buff *n;
1275da29e4b4SJakub Kicinski 
1276da29e4b4SJakub Kicinski 	n = alloc_skb(0, GFP_ATOMIC);
1277da29e4b4SJakub Kicinski 	if (!n)
1278da29e4b4SJakub Kicinski 		return NULL;
1279da29e4b4SJakub Kicinski 
1280da29e4b4SJakub Kicinski 	n->len = first->len;
1281da29e4b4SJakub Kicinski 	n->data_len = first->len;
1282da29e4b4SJakub Kicinski 	n->truesize = first->truesize;
1283da29e4b4SJakub Kicinski 
1284da29e4b4SJakub Kicinski 	skb_shinfo(n)->frag_list = first;
1285da29e4b4SJakub Kicinski 
1286da29e4b4SJakub Kicinski 	__copy_skb_header(n, first);
1287da29e4b4SJakub Kicinski 	n->destructor = NULL;
1288da29e4b4SJakub Kicinski 
1289da29e4b4SJakub Kicinski 	return n;
1290da29e4b4SJakub Kicinski }
1291da29e4b4SJakub Kicinski EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1292da29e4b4SJakub Kicinski 
1293da29e4b4SJakub Kicinski /**
1294e0053ec0SHerbert Xu  *	skb_morph	-	morph one skb into another
1295e0053ec0SHerbert Xu  *	@dst: the skb to receive the contents
1296e0053ec0SHerbert Xu  *	@src: the skb to supply the contents
1297e0053ec0SHerbert Xu  *
1298e0053ec0SHerbert Xu  *	This is identical to skb_clone except that the target skb is
1299e0053ec0SHerbert Xu  *	supplied by the user.
1300e0053ec0SHerbert Xu  *
1301e0053ec0SHerbert Xu  *	The target skb is returned upon exit.
1302e0053ec0SHerbert Xu  */
1303e0053ec0SHerbert Xu struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1304e0053ec0SHerbert Xu {
1305511a3edaSEric Dumazet 	skb_release_all(dst, SKB_CONSUMED);
1306e0053ec0SHerbert Xu 	return __skb_clone(dst, src);
1307e0053ec0SHerbert Xu }
1308e0053ec0SHerbert Xu EXPORT_SYMBOL_GPL(skb_morph);
1309e0053ec0SHerbert Xu 
13106f89dbceSSowmini Varadhan int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1311a91dbff5SWillem de Bruijn {
1312a91dbff5SWillem de Bruijn 	unsigned long max_pg, num_pg, new_pg, old_pg;
1313a91dbff5SWillem de Bruijn 	struct user_struct *user;
1314a91dbff5SWillem de Bruijn 
1315a91dbff5SWillem de Bruijn 	if (capable(CAP_IPC_LOCK) || !size)
1316a91dbff5SWillem de Bruijn 		return 0;
1317a91dbff5SWillem de Bruijn 
1318a91dbff5SWillem de Bruijn 	num_pg = (size >> PAGE_SHIFT) + 2;	/* worst case */
1319a91dbff5SWillem de Bruijn 	max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1320a91dbff5SWillem de Bruijn 	user = mmp->user ? : current_user();
1321a91dbff5SWillem de Bruijn 
1322a91dbff5SWillem de Bruijn 	old_pg = atomic_long_read(&user->locked_vm);
132357fc05e8SEric Dumazet 	do {
1324a91dbff5SWillem de Bruijn 		new_pg = old_pg + num_pg;
1325a91dbff5SWillem de Bruijn 		if (new_pg > max_pg)
1326a91dbff5SWillem de Bruijn 			return -ENOBUFS;
132757fc05e8SEric Dumazet 	} while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1328a91dbff5SWillem de Bruijn 
1329a91dbff5SWillem de Bruijn 	if (!mmp->user) {
1330a91dbff5SWillem de Bruijn 		mmp->user = get_uid(user);
1331a91dbff5SWillem de Bruijn 		mmp->num_pg = num_pg;
1332a91dbff5SWillem de Bruijn 	} else {
1333a91dbff5SWillem de Bruijn 		mmp->num_pg += num_pg;
1334a91dbff5SWillem de Bruijn 	}
1335a91dbff5SWillem de Bruijn 
1336a91dbff5SWillem de Bruijn 	return 0;
1337a91dbff5SWillem de Bruijn }
13386f89dbceSSowmini Varadhan EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1339a91dbff5SWillem de Bruijn 
13406f89dbceSSowmini Varadhan void mm_unaccount_pinned_pages(struct mmpin *mmp)
1341a91dbff5SWillem de Bruijn {
1342a91dbff5SWillem de Bruijn 	if (mmp->user) {
1343a91dbff5SWillem de Bruijn 		atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1344a91dbff5SWillem de Bruijn 		free_uid(mmp->user);
1345a91dbff5SWillem de Bruijn 	}
1346a91dbff5SWillem de Bruijn }
13476f89dbceSSowmini Varadhan EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1348a91dbff5SWillem de Bruijn 
1349c67b627eSDavid Ahern static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
135052267790SWillem de Bruijn {
1351e7d2b510SPavel Begunkov 	struct ubuf_info_msgzc *uarg;
135252267790SWillem de Bruijn 	struct sk_buff *skb;
135352267790SWillem de Bruijn 
135452267790SWillem de Bruijn 	WARN_ON_ONCE(!in_task());
135552267790SWillem de Bruijn 
135652267790SWillem de Bruijn 	skb = sock_omalloc(sk, 0, GFP_KERNEL);
135752267790SWillem de Bruijn 	if (!skb)
135852267790SWillem de Bruijn 		return NULL;
135952267790SWillem de Bruijn 
136052267790SWillem de Bruijn 	BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
136152267790SWillem de Bruijn 	uarg = (void *)skb->cb;
1362a91dbff5SWillem de Bruijn 	uarg->mmp.user = NULL;
1363a91dbff5SWillem de Bruijn 
1364a91dbff5SWillem de Bruijn 	if (mm_account_pinned_pages(&uarg->mmp, size)) {
1365a91dbff5SWillem de Bruijn 		kfree_skb(skb);
1366a91dbff5SWillem de Bruijn 		return NULL;
1367a91dbff5SWillem de Bruijn 	}
136852267790SWillem de Bruijn 
1369e7d2b510SPavel Begunkov 	uarg->ubuf.callback = msg_zerocopy_callback;
13704ab6c99dSWillem de Bruijn 	uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
13714ab6c99dSWillem de Bruijn 	uarg->len = 1;
13724ab6c99dSWillem de Bruijn 	uarg->bytelen = size;
137352267790SWillem de Bruijn 	uarg->zerocopy = 1;
1374e7d2b510SPavel Begunkov 	uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1375e7d2b510SPavel Begunkov 	refcount_set(&uarg->ubuf.refcnt, 1);
137652267790SWillem de Bruijn 	sock_hold(sk);
137752267790SWillem de Bruijn 
1378e7d2b510SPavel Begunkov 	return &uarg->ubuf;
137952267790SWillem de Bruijn }
138052267790SWillem de Bruijn 
1381e7d2b510SPavel Begunkov static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
138252267790SWillem de Bruijn {
138352267790SWillem de Bruijn 	return container_of((void *)uarg, struct sk_buff, cb);
138452267790SWillem de Bruijn }
138552267790SWillem de Bruijn 
13868c793822SJonathan Lemon struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
13874ab6c99dSWillem de Bruijn 				       struct ubuf_info *uarg)
13884ab6c99dSWillem de Bruijn {
13894ab6c99dSWillem de Bruijn 	if (uarg) {
1390e7d2b510SPavel Begunkov 		struct ubuf_info_msgzc *uarg_zc;
13914ab6c99dSWillem de Bruijn 		const u32 byte_limit = 1 << 19;		/* limit to a few TSO */
13924ab6c99dSWillem de Bruijn 		u32 bytelen, next;
13934ab6c99dSWillem de Bruijn 
13941b4b2b09SPavel Begunkov 		/* there might be non MSG_ZEROCOPY users */
13951b4b2b09SPavel Begunkov 		if (uarg->callback != msg_zerocopy_callback)
13961b4b2b09SPavel Begunkov 			return NULL;
13971b4b2b09SPavel Begunkov 
13984ab6c99dSWillem de Bruijn 		/* realloc only when socket is locked (TCP, UDP cork),
13994ab6c99dSWillem de Bruijn 		 * so uarg->len and sk_zckey access is serialized
14004ab6c99dSWillem de Bruijn 		 */
14014ab6c99dSWillem de Bruijn 		if (!sock_owned_by_user(sk)) {
14024ab6c99dSWillem de Bruijn 			WARN_ON_ONCE(1);
14034ab6c99dSWillem de Bruijn 			return NULL;
14044ab6c99dSWillem de Bruijn 		}
14054ab6c99dSWillem de Bruijn 
1406e7d2b510SPavel Begunkov 		uarg_zc = uarg_to_msgzc(uarg);
1407e7d2b510SPavel Begunkov 		bytelen = uarg_zc->bytelen + size;
1408e7d2b510SPavel Begunkov 		if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
14094ab6c99dSWillem de Bruijn 			/* TCP can create new skb to attach new uarg */
14104ab6c99dSWillem de Bruijn 			if (sk->sk_type == SOCK_STREAM)
14114ab6c99dSWillem de Bruijn 				goto new_alloc;
14124ab6c99dSWillem de Bruijn 			return NULL;
14134ab6c99dSWillem de Bruijn 		}
14144ab6c99dSWillem de Bruijn 
14154ab6c99dSWillem de Bruijn 		next = (u32)atomic_read(&sk->sk_zckey);
1416e7d2b510SPavel Begunkov 		if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1417e7d2b510SPavel Begunkov 			if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1418a91dbff5SWillem de Bruijn 				return NULL;
1419e7d2b510SPavel Begunkov 			uarg_zc->len++;
1420e7d2b510SPavel Begunkov 			uarg_zc->bytelen = bytelen;
14214ab6c99dSWillem de Bruijn 			atomic_set(&sk->sk_zckey, ++next);
1422100f6d8eSWillem de Bruijn 
1423100f6d8eSWillem de Bruijn 			/* no extra ref when appending to datagram (MSG_MORE) */
1424100f6d8eSWillem de Bruijn 			if (sk->sk_type == SOCK_STREAM)
14258e044917SJonathan Lemon 				net_zcopy_get(uarg);
1426100f6d8eSWillem de Bruijn 
14274ab6c99dSWillem de Bruijn 			return uarg;
14284ab6c99dSWillem de Bruijn 		}
14294ab6c99dSWillem de Bruijn 	}
14304ab6c99dSWillem de Bruijn 
14314ab6c99dSWillem de Bruijn new_alloc:
14328c793822SJonathan Lemon 	return msg_zerocopy_alloc(sk, size);
14334ab6c99dSWillem de Bruijn }
14348c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
14354ab6c99dSWillem de Bruijn 
14364ab6c99dSWillem de Bruijn static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
14374ab6c99dSWillem de Bruijn {
14384ab6c99dSWillem de Bruijn 	struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
14394ab6c99dSWillem de Bruijn 	u32 old_lo, old_hi;
14404ab6c99dSWillem de Bruijn 	u64 sum_len;
14414ab6c99dSWillem de Bruijn 
14424ab6c99dSWillem de Bruijn 	old_lo = serr->ee.ee_info;
14434ab6c99dSWillem de Bruijn 	old_hi = serr->ee.ee_data;
14444ab6c99dSWillem de Bruijn 	sum_len = old_hi - old_lo + 1ULL + len;
14454ab6c99dSWillem de Bruijn 
14464ab6c99dSWillem de Bruijn 	if (sum_len >= (1ULL << 32))
14474ab6c99dSWillem de Bruijn 		return false;
14484ab6c99dSWillem de Bruijn 
14494ab6c99dSWillem de Bruijn 	if (lo != old_hi + 1)
14504ab6c99dSWillem de Bruijn 		return false;
14514ab6c99dSWillem de Bruijn 
14524ab6c99dSWillem de Bruijn 	serr->ee.ee_data += len;
14534ab6c99dSWillem de Bruijn 	return true;
14544ab6c99dSWillem de Bruijn }
14554ab6c99dSWillem de Bruijn 
1456e7d2b510SPavel Begunkov static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
145752267790SWillem de Bruijn {
14584ab6c99dSWillem de Bruijn 	struct sk_buff *tail, *skb = skb_from_uarg(uarg);
145952267790SWillem de Bruijn 	struct sock_exterr_skb *serr;
146052267790SWillem de Bruijn 	struct sock *sk = skb->sk;
14614ab6c99dSWillem de Bruijn 	struct sk_buff_head *q;
14624ab6c99dSWillem de Bruijn 	unsigned long flags;
14633bdd5ee0SWillem de Bruijn 	bool is_zerocopy;
14644ab6c99dSWillem de Bruijn 	u32 lo, hi;
14654ab6c99dSWillem de Bruijn 	u16 len;
146652267790SWillem de Bruijn 
1467ccaffff1SWillem de Bruijn 	mm_unaccount_pinned_pages(&uarg->mmp);
1468ccaffff1SWillem de Bruijn 
14694ab6c99dSWillem de Bruijn 	/* if !len, there was only 1 call, and it was aborted
14704ab6c99dSWillem de Bruijn 	 * so do not queue a completion notification
14714ab6c99dSWillem de Bruijn 	 */
14724ab6c99dSWillem de Bruijn 	if (!uarg->len || sock_flag(sk, SOCK_DEAD))
147352267790SWillem de Bruijn 		goto release;
147452267790SWillem de Bruijn 
14754ab6c99dSWillem de Bruijn 	len = uarg->len;
14764ab6c99dSWillem de Bruijn 	lo = uarg->id;
14774ab6c99dSWillem de Bruijn 	hi = uarg->id + len - 1;
14783bdd5ee0SWillem de Bruijn 	is_zerocopy = uarg->zerocopy;
14794ab6c99dSWillem de Bruijn 
148052267790SWillem de Bruijn 	serr = SKB_EXT_ERR(skb);
148152267790SWillem de Bruijn 	memset(serr, 0, sizeof(*serr));
148252267790SWillem de Bruijn 	serr->ee.ee_errno = 0;
148352267790SWillem de Bruijn 	serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
14844ab6c99dSWillem de Bruijn 	serr->ee.ee_data = hi;
14854ab6c99dSWillem de Bruijn 	serr->ee.ee_info = lo;
14863bdd5ee0SWillem de Bruijn 	if (!is_zerocopy)
148752267790SWillem de Bruijn 		serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
148852267790SWillem de Bruijn 
14894ab6c99dSWillem de Bruijn 	q = &sk->sk_error_queue;
14904ab6c99dSWillem de Bruijn 	spin_lock_irqsave(&q->lock, flags);
14914ab6c99dSWillem de Bruijn 	tail = skb_peek_tail(q);
14924ab6c99dSWillem de Bruijn 	if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
14934ab6c99dSWillem de Bruijn 	    !skb_zerocopy_notify_extend(tail, lo, len)) {
14944ab6c99dSWillem de Bruijn 		__skb_queue_tail(q, skb);
149552267790SWillem de Bruijn 		skb = NULL;
14964ab6c99dSWillem de Bruijn 	}
14974ab6c99dSWillem de Bruijn 	spin_unlock_irqrestore(&q->lock, flags);
149852267790SWillem de Bruijn 
1499e3ae2365SAlexander Aring 	sk_error_report(sk);
150052267790SWillem de Bruijn 
150152267790SWillem de Bruijn release:
150252267790SWillem de Bruijn 	consume_skb(skb);
150352267790SWillem de Bruijn 	sock_put(sk);
150452267790SWillem de Bruijn }
150575518851SJonathan Lemon 
15068c793822SJonathan Lemon void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
150736177832SJonathan Lemon 			   bool success)
150875518851SJonathan Lemon {
1509e7d2b510SPavel Begunkov 	struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1510e7d2b510SPavel Begunkov 
1511e7d2b510SPavel Begunkov 	uarg_zc->zerocopy = uarg_zc->zerocopy & success;
151275518851SJonathan Lemon 
151375518851SJonathan Lemon 	if (refcount_dec_and_test(&uarg->refcnt))
1514e7d2b510SPavel Begunkov 		__msg_zerocopy_callback(uarg_zc);
151575518851SJonathan Lemon }
15168c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
151752267790SWillem de Bruijn 
15188c793822SJonathan Lemon void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
151952267790SWillem de Bruijn {
1520e7d2b510SPavel Begunkov 	struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
152152267790SWillem de Bruijn 
152252267790SWillem de Bruijn 	atomic_dec(&sk->sk_zckey);
1523e7d2b510SPavel Begunkov 	uarg_to_msgzc(uarg)->len--;
152452267790SWillem de Bruijn 
152552900d22SWillem de Bruijn 	if (have_uref)
15268c793822SJonathan Lemon 		msg_zerocopy_callback(NULL, uarg, true);
152752267790SWillem de Bruijn }
15288c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
152952267790SWillem de Bruijn 
153052267790SWillem de Bruijn int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
153152267790SWillem de Bruijn 			     struct msghdr *msg, int len,
153252267790SWillem de Bruijn 			     struct ubuf_info *uarg)
153352267790SWillem de Bruijn {
15344ab6c99dSWillem de Bruijn 	struct ubuf_info *orig_uarg = skb_zcopy(skb);
153552267790SWillem de Bruijn 	int err, orig_len = skb->len;
153652267790SWillem de Bruijn 
15374ab6c99dSWillem de Bruijn 	/* An skb can only point to one uarg. This edge case happens when
15384ab6c99dSWillem de Bruijn 	 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
15394ab6c99dSWillem de Bruijn 	 */
15404ab6c99dSWillem de Bruijn 	if (orig_uarg && uarg != orig_uarg)
15414ab6c99dSWillem de Bruijn 		return -EEXIST;
15424ab6c99dSWillem de Bruijn 
1543ebe73a28SDavid Ahern 	err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
154452267790SWillem de Bruijn 	if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
154554d43117SWillem de Bruijn 		struct sock *save_sk = skb->sk;
154654d43117SWillem de Bruijn 
154752267790SWillem de Bruijn 		/* Streams do not free skb on error. Reset to prev state. */
1548829b7bddSPavel Begunkov 		iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
154954d43117SWillem de Bruijn 		skb->sk = sk;
155052267790SWillem de Bruijn 		___pskb_trim(skb, orig_len);
155154d43117SWillem de Bruijn 		skb->sk = save_sk;
155252267790SWillem de Bruijn 		return err;
155352267790SWillem de Bruijn 	}
155452267790SWillem de Bruijn 
155552900d22SWillem de Bruijn 	skb_zcopy_set(skb, uarg, NULL);
155652267790SWillem de Bruijn 	return skb->len - orig_len;
155752267790SWillem de Bruijn }
155852267790SWillem de Bruijn EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
155952267790SWillem de Bruijn 
1560753f1ca4SPavel Begunkov void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1561753f1ca4SPavel Begunkov {
1562753f1ca4SPavel Begunkov 	int i;
1563753f1ca4SPavel Begunkov 
1564753f1ca4SPavel Begunkov 	skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1565753f1ca4SPavel Begunkov 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1566753f1ca4SPavel Begunkov 		skb_frag_ref(skb, i);
1567753f1ca4SPavel Begunkov }
1568753f1ca4SPavel Begunkov EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1569753f1ca4SPavel Begunkov 
15701f8b977aSWillem de Bruijn static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
157152267790SWillem de Bruijn 			      gfp_t gfp_mask)
157252267790SWillem de Bruijn {
157352267790SWillem de Bruijn 	if (skb_zcopy(orig)) {
157452267790SWillem de Bruijn 		if (skb_zcopy(nskb)) {
157552267790SWillem de Bruijn 			/* !gfp_mask callers are verified to !skb_zcopy(nskb) */
157652267790SWillem de Bruijn 			if (!gfp_mask) {
157752267790SWillem de Bruijn 				WARN_ON_ONCE(1);
157852267790SWillem de Bruijn 				return -ENOMEM;
157952267790SWillem de Bruijn 			}
158052267790SWillem de Bruijn 			if (skb_uarg(nskb) == skb_uarg(orig))
158152267790SWillem de Bruijn 				return 0;
158252267790SWillem de Bruijn 			if (skb_copy_ubufs(nskb, GFP_ATOMIC))
158352267790SWillem de Bruijn 				return -EIO;
158452267790SWillem de Bruijn 		}
158552900d22SWillem de Bruijn 		skb_zcopy_set(nskb, skb_uarg(orig), NULL);
158652267790SWillem de Bruijn 	}
158752267790SWillem de Bruijn 	return 0;
158852267790SWillem de Bruijn }
158952267790SWillem de Bruijn 
15902c53040fSBen Hutchings /**
15912c53040fSBen Hutchings  *	skb_copy_ubufs	-	copy userspace skb frags buffers to kernel
159248c83012SMichael S. Tsirkin  *	@skb: the skb to modify
159348c83012SMichael S. Tsirkin  *	@gfp_mask: allocation priority
159448c83012SMichael S. Tsirkin  *
159506b4feb3SJonathan Lemon  *	This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
159648c83012SMichael S. Tsirkin  *	It will copy all frags into kernel and drop the reference
159748c83012SMichael S. Tsirkin  *	to userspace pages.
159848c83012SMichael S. Tsirkin  *
159948c83012SMichael S. Tsirkin  *	If this function is called from an interrupt gfp_mask() must be
160048c83012SMichael S. Tsirkin  *	%GFP_ATOMIC.
160148c83012SMichael S. Tsirkin  *
160248c83012SMichael S. Tsirkin  *	Returns 0 on success or a negative error code on failure
160348c83012SMichael S. Tsirkin  *	to allocate kernel memory to copy to.
160448c83012SMichael S. Tsirkin  */
160548c83012SMichael S. Tsirkin int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1606a6686f2fSShirley Ma {
1607a6686f2fSShirley Ma 	int num_frags = skb_shinfo(skb)->nr_frags;
1608a6686f2fSShirley Ma 	struct page *page, *head = NULL;
16093ece7826SWillem de Bruijn 	int i, new_frags;
16103ece7826SWillem de Bruijn 	u32 d_off;
1611a6686f2fSShirley Ma 
16123ece7826SWillem de Bruijn 	if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
16133ece7826SWillem de Bruijn 		return -EINVAL;
16143ece7826SWillem de Bruijn 
1615f72c4ac6SWillem de Bruijn 	if (!num_frags)
1616f72c4ac6SWillem de Bruijn 		goto release;
1617f72c4ac6SWillem de Bruijn 
16183ece7826SWillem de Bruijn 	new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
16193ece7826SWillem de Bruijn 	for (i = 0; i < new_frags; i++) {
162002756ed4SKrishna Kumar 		page = alloc_page(gfp_mask);
1621a6686f2fSShirley Ma 		if (!page) {
1622a6686f2fSShirley Ma 			while (head) {
162340dadff2SSunghan Suh 				struct page *next = (struct page *)page_private(head);
1624a6686f2fSShirley Ma 				put_page(head);
1625a6686f2fSShirley Ma 				head = next;
1626a6686f2fSShirley Ma 			}
1627a6686f2fSShirley Ma 			return -ENOMEM;
1628a6686f2fSShirley Ma 		}
16293ece7826SWillem de Bruijn 		set_page_private(page, (unsigned long)head);
16303ece7826SWillem de Bruijn 		head = page;
16313ece7826SWillem de Bruijn 	}
16323ece7826SWillem de Bruijn 
16333ece7826SWillem de Bruijn 	page = head;
16343ece7826SWillem de Bruijn 	d_off = 0;
16353ece7826SWillem de Bruijn 	for (i = 0; i < num_frags; i++) {
16363ece7826SWillem de Bruijn 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
16373ece7826SWillem de Bruijn 		u32 p_off, p_len, copied;
16383ece7826SWillem de Bruijn 		struct page *p;
16393ece7826SWillem de Bruijn 		u8 *vaddr;
1640c613c209SWillem de Bruijn 
1641b54c9d5bSJonathan Lemon 		skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1642c613c209SWillem de Bruijn 				      p, p_off, p_len, copied) {
16433ece7826SWillem de Bruijn 			u32 copy, done = 0;
1644c613c209SWillem de Bruijn 			vaddr = kmap_atomic(p);
16453ece7826SWillem de Bruijn 
16463ece7826SWillem de Bruijn 			while (done < p_len) {
16473ece7826SWillem de Bruijn 				if (d_off == PAGE_SIZE) {
16483ece7826SWillem de Bruijn 					d_off = 0;
16493ece7826SWillem de Bruijn 					page = (struct page *)page_private(page);
16503ece7826SWillem de Bruijn 				}
16513ece7826SWillem de Bruijn 				copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
16523ece7826SWillem de Bruijn 				memcpy(page_address(page) + d_off,
16533ece7826SWillem de Bruijn 				       vaddr + p_off + done, copy);
16543ece7826SWillem de Bruijn 				done += copy;
16553ece7826SWillem de Bruijn 				d_off += copy;
16563ece7826SWillem de Bruijn 			}
165751c56b00SEric Dumazet 			kunmap_atomic(vaddr);
1658c613c209SWillem de Bruijn 		}
1659a6686f2fSShirley Ma 	}
1660a6686f2fSShirley Ma 
1661a6686f2fSShirley Ma 	/* skb frags release userspace buffers */
166202756ed4SKrishna Kumar 	for (i = 0; i < num_frags; i++)
1663a8605c60SIan Campbell 		skb_frag_unref(skb, i);
1664a6686f2fSShirley Ma 
1665a6686f2fSShirley Ma 	/* skb frags point to kernel buffers */
16663ece7826SWillem de Bruijn 	for (i = 0; i < new_frags - 1; i++) {
16673ece7826SWillem de Bruijn 		__skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
166840dadff2SSunghan Suh 		head = (struct page *)page_private(head);
1669a6686f2fSShirley Ma 	}
16703ece7826SWillem de Bruijn 	__skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
16713ece7826SWillem de Bruijn 	skb_shinfo(skb)->nr_frags = new_frags;
167248c83012SMichael S. Tsirkin 
1673b90ddd56SWillem de Bruijn release:
16741f8b977aSWillem de Bruijn 	skb_zcopy_clear(skb, false);
1675a6686f2fSShirley Ma 	return 0;
1676a6686f2fSShirley Ma }
1677dcc0fb78SMichael S. Tsirkin EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1678a6686f2fSShirley Ma 
1679e0053ec0SHerbert Xu /**
1680e0053ec0SHerbert Xu  *	skb_clone	-	duplicate an sk_buff
1681e0053ec0SHerbert Xu  *	@skb: buffer to clone
1682e0053ec0SHerbert Xu  *	@gfp_mask: allocation priority
1683e0053ec0SHerbert Xu  *
1684e0053ec0SHerbert Xu  *	Duplicate an &sk_buff. The new one is not owned by a socket. Both
1685e0053ec0SHerbert Xu  *	copies share the same packet data but not structure. The new
1686e0053ec0SHerbert Xu  *	buffer has a reference count of 1. If the allocation fails the
1687e0053ec0SHerbert Xu  *	function returns %NULL otherwise the new buffer is returned.
1688e0053ec0SHerbert Xu  *
1689e0053ec0SHerbert Xu  *	If this function is called from an interrupt gfp_mask() must be
1690e0053ec0SHerbert Xu  *	%GFP_ATOMIC.
1691e0053ec0SHerbert Xu  */
1692e0053ec0SHerbert Xu 
1693e0053ec0SHerbert Xu struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1694e0053ec0SHerbert Xu {
1695d0bf4a9eSEric Dumazet 	struct sk_buff_fclones *fclones = container_of(skb,
1696d0bf4a9eSEric Dumazet 						       struct sk_buff_fclones,
1697d0bf4a9eSEric Dumazet 						       skb1);
16986ffe75ebSEric Dumazet 	struct sk_buff *n;
1699e0053ec0SHerbert Xu 
170070008aa5SMichael S. Tsirkin 	if (skb_orphan_frags(skb, gfp_mask))
1701a6686f2fSShirley Ma 		return NULL;
1702a6686f2fSShirley Ma 
1703e0053ec0SHerbert Xu 	if (skb->fclone == SKB_FCLONE_ORIG &&
17042638595aSReshetova, Elena 	    refcount_read(&fclones->fclone_ref) == 1) {
17056ffe75ebSEric Dumazet 		n = &fclones->skb2;
17062638595aSReshetova, Elena 		refcount_set(&fclones->fclone_ref, 2);
1707c2dd4059SEric Dumazet 		n->fclone = SKB_FCLONE_CLONE;
1708e0053ec0SHerbert Xu 	} else {
1709c93bdd0eSMel Gorman 		if (skb_pfmemalloc(skb))
1710c93bdd0eSMel Gorman 			gfp_mask |= __GFP_MEMALLOC;
1711c93bdd0eSMel Gorman 
1712e0053ec0SHerbert Xu 		n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1713e0053ec0SHerbert Xu 		if (!n)
1714e0053ec0SHerbert Xu 			return NULL;
1715fe55f6d5SVegard Nossum 
1716e0053ec0SHerbert Xu 		n->fclone = SKB_FCLONE_UNAVAILABLE;
1717e0053ec0SHerbert Xu 	}
1718e0053ec0SHerbert Xu 
1719e0053ec0SHerbert Xu 	return __skb_clone(n, skb);
17201da177e4SLinus Torvalds }
1721b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_clone);
17221da177e4SLinus Torvalds 
1723b0768a86SToshiaki Makita void skb_headers_offset_update(struct sk_buff *skb, int off)
1724f5b17294SPravin B Shelar {
1725030737bcSEric Dumazet 	/* Only adjust this if it actually is csum_start rather than csum */
1726030737bcSEric Dumazet 	if (skb->ip_summed == CHECKSUM_PARTIAL)
1727030737bcSEric Dumazet 		skb->csum_start += off;
1728f5b17294SPravin B Shelar 	/* {transport,network,mac}_header and tail are relative to skb->head */
1729f5b17294SPravin B Shelar 	skb->transport_header += off;
1730f5b17294SPravin B Shelar 	skb->network_header   += off;
1731f5b17294SPravin B Shelar 	if (skb_mac_header_was_set(skb))
1732f5b17294SPravin B Shelar 		skb->mac_header += off;
1733f5b17294SPravin B Shelar 	skb->inner_transport_header += off;
1734f5b17294SPravin B Shelar 	skb->inner_network_header += off;
1735aefbd2b3SPravin B Shelar 	skb->inner_mac_header += off;
1736f5b17294SPravin B Shelar }
1737b0768a86SToshiaki Makita EXPORT_SYMBOL(skb_headers_offset_update);
1738f5b17294SPravin B Shelar 
173908303c18SIlya Lesokhin void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
17401da177e4SLinus Torvalds {
1741dec18810SHerbert Xu 	__copy_skb_header(new, old);
1742dec18810SHerbert Xu 
17437967168cSHerbert Xu 	skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
17447967168cSHerbert Xu 	skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
17457967168cSHerbert Xu 	skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
17461da177e4SLinus Torvalds }
174708303c18SIlya Lesokhin EXPORT_SYMBOL(skb_copy_header);
17481da177e4SLinus Torvalds 
1749c93bdd0eSMel Gorman static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1750c93bdd0eSMel Gorman {
1751c93bdd0eSMel Gorman 	if (skb_pfmemalloc(skb))
1752c93bdd0eSMel Gorman 		return SKB_ALLOC_RX;
1753c93bdd0eSMel Gorman 	return 0;
1754c93bdd0eSMel Gorman }
1755c93bdd0eSMel Gorman 
17561da177e4SLinus Torvalds /**
17571da177e4SLinus Torvalds  *	skb_copy	-	create private copy of an sk_buff
17581da177e4SLinus Torvalds  *	@skb: buffer to copy
17591da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
17601da177e4SLinus Torvalds  *
17611da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and its data. This is used when the
17621da177e4SLinus Torvalds  *	caller wishes to modify the data and needs a private copy of the
17631da177e4SLinus Torvalds  *	data to alter. Returns %NULL on failure or the pointer to the buffer
17641da177e4SLinus Torvalds  *	on success. The returned buffer has a reference count of 1.
17651da177e4SLinus Torvalds  *
17661da177e4SLinus Torvalds  *	As by-product this function converts non-linear &sk_buff to linear
17671da177e4SLinus Torvalds  *	one, so that &sk_buff becomes completely private and caller is allowed
17681da177e4SLinus Torvalds  *	to modify all the data of returned buffer. This means that this
17691da177e4SLinus Torvalds  *	function is not recommended for use in circumstances when only
17701da177e4SLinus Torvalds  *	header is going to be modified. Use pskb_copy() instead.
17711da177e4SLinus Torvalds  */
17721da177e4SLinus Torvalds 
1773dd0fc66fSAl Viro struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
17741da177e4SLinus Torvalds {
17756602cebbSEric Dumazet 	int headerlen = skb_headroom(skb);
1776ec47ea82SAlexander Duyck 	unsigned int size = skb_end_offset(skb) + skb->data_len;
1777c93bdd0eSMel Gorman 	struct sk_buff *n = __alloc_skb(size, gfp_mask,
1778c93bdd0eSMel Gorman 					skb_alloc_rx_flag(skb), NUMA_NO_NODE);
17796602cebbSEric Dumazet 
17801da177e4SLinus Torvalds 	if (!n)
17811da177e4SLinus Torvalds 		return NULL;
17821da177e4SLinus Torvalds 
17831da177e4SLinus Torvalds 	/* Set the data pointer */
17841da177e4SLinus Torvalds 	skb_reserve(n, headerlen);
17851da177e4SLinus Torvalds 	/* Set the tail pointer and length */
17861da177e4SLinus Torvalds 	skb_put(n, skb->len);
17871da177e4SLinus Torvalds 
17889f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
17891da177e4SLinus Torvalds 
179008303c18SIlya Lesokhin 	skb_copy_header(n, skb);
17911da177e4SLinus Torvalds 	return n;
17921da177e4SLinus Torvalds }
1793b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy);
17941da177e4SLinus Torvalds 
17951da177e4SLinus Torvalds /**
1796bad93e9dSOctavian Purdila  *	__pskb_copy_fclone	-  create copy of an sk_buff with private head.
17971da177e4SLinus Torvalds  *	@skb: buffer to copy
1798117632e6SEric Dumazet  *	@headroom: headroom of new skb
17991da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
1800bad93e9dSOctavian Purdila  *	@fclone: if true allocate the copy of the skb from the fclone
1801bad93e9dSOctavian Purdila  *	cache instead of the head cache; it is recommended to set this
1802bad93e9dSOctavian Purdila  *	to true for the cases where the copy will likely be cloned
18031da177e4SLinus Torvalds  *
18041da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and part of its data, located
18051da177e4SLinus Torvalds  *	in header. Fragmented data remain shared. This is used when
18061da177e4SLinus Torvalds  *	the caller wishes to modify only header of &sk_buff and needs
18071da177e4SLinus Torvalds  *	private copy of the header to alter. Returns %NULL on failure
18081da177e4SLinus Torvalds  *	or the pointer to the buffer on success.
18091da177e4SLinus Torvalds  *	The returned buffer has a reference count of 1.
18101da177e4SLinus Torvalds  */
18111da177e4SLinus Torvalds 
1812bad93e9dSOctavian Purdila struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1813bad93e9dSOctavian Purdila 				   gfp_t gfp_mask, bool fclone)
18141da177e4SLinus Torvalds {
1815117632e6SEric Dumazet 	unsigned int size = skb_headlen(skb) + headroom;
1816bad93e9dSOctavian Purdila 	int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1817bad93e9dSOctavian Purdila 	struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
18186602cebbSEric Dumazet 
18191da177e4SLinus Torvalds 	if (!n)
18201da177e4SLinus Torvalds 		goto out;
18211da177e4SLinus Torvalds 
18221da177e4SLinus Torvalds 	/* Set the data pointer */
1823117632e6SEric Dumazet 	skb_reserve(n, headroom);
18241da177e4SLinus Torvalds 	/* Set the tail pointer and length */
18251da177e4SLinus Torvalds 	skb_put(n, skb_headlen(skb));
18261da177e4SLinus Torvalds 	/* Copy the bytes */
1827d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data(skb, n->data, n->len);
18281da177e4SLinus Torvalds 
182925f484a6SHerbert Xu 	n->truesize += skb->data_len;
18301da177e4SLinus Torvalds 	n->data_len  = skb->data_len;
18311da177e4SLinus Torvalds 	n->len	     = skb->len;
18321da177e4SLinus Torvalds 
18331da177e4SLinus Torvalds 	if (skb_shinfo(skb)->nr_frags) {
18341da177e4SLinus Torvalds 		int i;
18351da177e4SLinus Torvalds 
18361f8b977aSWillem de Bruijn 		if (skb_orphan_frags(skb, gfp_mask) ||
18371f8b977aSWillem de Bruijn 		    skb_zerocopy_clone(n, skb, gfp_mask)) {
18381511022cSDan Carpenter 			kfree_skb(n);
18391511022cSDan Carpenter 			n = NULL;
1840a6686f2fSShirley Ma 			goto out;
1841a6686f2fSShirley Ma 		}
18421da177e4SLinus Torvalds 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
18431da177e4SLinus Torvalds 			skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1844ea2ab693SIan Campbell 			skb_frag_ref(skb, i);
18451da177e4SLinus Torvalds 		}
18461da177e4SLinus Torvalds 		skb_shinfo(n)->nr_frags = i;
18471da177e4SLinus Torvalds 	}
18481da177e4SLinus Torvalds 
184921dc3301SDavid S. Miller 	if (skb_has_frag_list(skb)) {
18501da177e4SLinus Torvalds 		skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
18511da177e4SLinus Torvalds 		skb_clone_fraglist(n);
18521da177e4SLinus Torvalds 	}
18531da177e4SLinus Torvalds 
185408303c18SIlya Lesokhin 	skb_copy_header(n, skb);
18551da177e4SLinus Torvalds out:
18561da177e4SLinus Torvalds 	return n;
18571da177e4SLinus Torvalds }
1858bad93e9dSOctavian Purdila EXPORT_SYMBOL(__pskb_copy_fclone);
18591da177e4SLinus Torvalds 
18601da177e4SLinus Torvalds /**
18611da177e4SLinus Torvalds  *	pskb_expand_head - reallocate header of &sk_buff
18621da177e4SLinus Torvalds  *	@skb: buffer to reallocate
18631da177e4SLinus Torvalds  *	@nhead: room to add at head
18641da177e4SLinus Torvalds  *	@ntail: room to add at tail
18651da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
18661da177e4SLinus Torvalds  *
1867bc32383cSMathias Krause  *	Expands (or creates identical copy, if @nhead and @ntail are zero)
1868bc32383cSMathias Krause  *	header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
18691da177e4SLinus Torvalds  *	reference count of 1. Returns zero in the case of success or error,
18701da177e4SLinus Torvalds  *	if expansion failed. In the last case, &sk_buff is not changed.
18711da177e4SLinus Torvalds  *
18721da177e4SLinus Torvalds  *	All the pointers pointing into skb header may change and must be
18731da177e4SLinus Torvalds  *	reloaded after call to this function.
18741da177e4SLinus Torvalds  */
18751da177e4SLinus Torvalds 
187686a76cafSVictor Fusco int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1877dd0fc66fSAl Viro 		     gfp_t gfp_mask)
18781da177e4SLinus Torvalds {
187912d6c1d3SKees Cook 	unsigned int osize = skb_end_offset(skb);
188012d6c1d3SKees Cook 	unsigned int size = osize + nhead + ntail;
18811da177e4SLinus Torvalds 	long off;
1882158f323bSEric Dumazet 	u8 *data;
188312d6c1d3SKees Cook 	int i;
18841da177e4SLinus Torvalds 
18854edd87adSHerbert Xu 	BUG_ON(nhead < 0);
18864edd87adSHerbert Xu 
18879f77fad3STim Hansen 	BUG_ON(skb_shared(skb));
18881da177e4SLinus Torvalds 
1889753f1ca4SPavel Begunkov 	skb_zcopy_downgrade_managed(skb);
1890753f1ca4SPavel Begunkov 
1891c93bdd0eSMel Gorman 	if (skb_pfmemalloc(skb))
1892c93bdd0eSMel Gorman 		gfp_mask |= __GFP_MEMALLOC;
189312d6c1d3SKees Cook 
189412d6c1d3SKees Cook 	size = SKB_DATA_ALIGN(size);
189512d6c1d3SKees Cook 	size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
189612d6c1d3SKees Cook 	size = kmalloc_size_roundup(size);
189712d6c1d3SKees Cook 	data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
18981da177e4SLinus Torvalds 	if (!data)
18991da177e4SLinus Torvalds 		goto nodata;
190012d6c1d3SKees Cook 	size = SKB_WITH_OVERHEAD(size);
19011da177e4SLinus Torvalds 
19021da177e4SLinus Torvalds 	/* Copy only real data... and, alas, header. This should be
19036602cebbSEric Dumazet 	 * optimized for the cases when header is void.
19046602cebbSEric Dumazet 	 */
19056602cebbSEric Dumazet 	memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
19066602cebbSEric Dumazet 
19076602cebbSEric Dumazet 	memcpy((struct skb_shared_info *)(data + size),
19086602cebbSEric Dumazet 	       skb_shinfo(skb),
1909fed66381SEric Dumazet 	       offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
19101da177e4SLinus Torvalds 
19113e24591aSAlexander Duyck 	/*
19123e24591aSAlexander Duyck 	 * if shinfo is shared we must drop the old head gracefully, but if it
19133e24591aSAlexander Duyck 	 * is not we can just drop the old head and let the existing refcount
19143e24591aSAlexander Duyck 	 * be since all we did is relocate the values
19153e24591aSAlexander Duyck 	 */
19163e24591aSAlexander Duyck 	if (skb_cloned(skb)) {
191770008aa5SMichael S. Tsirkin 		if (skb_orphan_frags(skb, gfp_mask))
1918a6686f2fSShirley Ma 			goto nofrags;
19191f8b977aSWillem de Bruijn 		if (skb_zcopy(skb))
1920c1d1b437SEric Dumazet 			refcount_inc(&skb_uarg(skb)->refcnt);
19211da177e4SLinus Torvalds 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1922ea2ab693SIan Campbell 			skb_frag_ref(skb, i);
19231da177e4SLinus Torvalds 
192421dc3301SDavid S. Miller 		if (skb_has_frag_list(skb))
19251da177e4SLinus Torvalds 			skb_clone_fraglist(skb);
19261da177e4SLinus Torvalds 
1927511a3edaSEric Dumazet 		skb_release_data(skb, SKB_CONSUMED);
19283e24591aSAlexander Duyck 	} else {
19293e24591aSAlexander Duyck 		skb_free_head(skb);
19301fd63041SEric Dumazet 	}
19311da177e4SLinus Torvalds 	off = (data + nhead) - skb->head;
19321da177e4SLinus Torvalds 
19331da177e4SLinus Torvalds 	skb->head     = data;
1934d3836f21SEric Dumazet 	skb->head_frag = 0;
19351da177e4SLinus Torvalds 	skb->data    += off;
1936763087daSEric Dumazet 
1937763087daSEric Dumazet 	skb_set_end_offset(skb, size);
19384305b541SArnaldo Carvalho de Melo #ifdef NET_SKBUFF_DATA_USES_OFFSET
193956eb8882SPatrick McHardy 	off           = nhead;
194056eb8882SPatrick McHardy #endif
194127a884dcSArnaldo Carvalho de Melo 	skb->tail	      += off;
1942b41abb42SPeter Pan(潘卫平) 	skb_headers_offset_update(skb, nhead);
19431da177e4SLinus Torvalds 	skb->cloned   = 0;
1944334a8132SPatrick McHardy 	skb->hdr_len  = 0;
19451da177e4SLinus Torvalds 	skb->nohdr    = 0;
19461da177e4SLinus Torvalds 	atomic_set(&skb_shinfo(skb)->dataref, 1);
1947158f323bSEric Dumazet 
1948de8f3a83SDaniel Borkmann 	skb_metadata_clear(skb);
1949de8f3a83SDaniel Borkmann 
1950158f323bSEric Dumazet 	/* It is not generally safe to change skb->truesize.
1951158f323bSEric Dumazet 	 * For the moment, we really care of rx path, or
1952158f323bSEric Dumazet 	 * when skb is orphaned (not attached to a socket).
1953158f323bSEric Dumazet 	 */
1954158f323bSEric Dumazet 	if (!skb->sk || skb->destructor == sock_edemux)
1955158f323bSEric Dumazet 		skb->truesize += size - osize;
1956158f323bSEric Dumazet 
19571da177e4SLinus Torvalds 	return 0;
19581da177e4SLinus Torvalds 
1959a6686f2fSShirley Ma nofrags:
1960a6686f2fSShirley Ma 	kfree(data);
19611da177e4SLinus Torvalds nodata:
19621da177e4SLinus Torvalds 	return -ENOMEM;
19631da177e4SLinus Torvalds }
1964b4ac530fSDavid S. Miller EXPORT_SYMBOL(pskb_expand_head);
19651da177e4SLinus Torvalds 
19661da177e4SLinus Torvalds /* Make private copy of skb with writable head and some headroom */
19671da177e4SLinus Torvalds 
19681da177e4SLinus Torvalds struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
19691da177e4SLinus Torvalds {
19701da177e4SLinus Torvalds 	struct sk_buff *skb2;
19711da177e4SLinus Torvalds 	int delta = headroom - skb_headroom(skb);
19721da177e4SLinus Torvalds 
19731da177e4SLinus Torvalds 	if (delta <= 0)
19741da177e4SLinus Torvalds 		skb2 = pskb_copy(skb, GFP_ATOMIC);
19751da177e4SLinus Torvalds 	else {
19761da177e4SLinus Torvalds 		skb2 = skb_clone(skb, GFP_ATOMIC);
19771da177e4SLinus Torvalds 		if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
19781da177e4SLinus Torvalds 					     GFP_ATOMIC)) {
19791da177e4SLinus Torvalds 			kfree_skb(skb2);
19801da177e4SLinus Torvalds 			skb2 = NULL;
19811da177e4SLinus Torvalds 		}
19821da177e4SLinus Torvalds 	}
19831da177e4SLinus Torvalds 	return skb2;
19841da177e4SLinus Torvalds }
1985b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_realloc_headroom);
19861da177e4SLinus Torvalds 
19872b88cba5SEric Dumazet int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
19882b88cba5SEric Dumazet {
19892b88cba5SEric Dumazet 	unsigned int saved_end_offset, saved_truesize;
19902b88cba5SEric Dumazet 	struct skb_shared_info *shinfo;
19912b88cba5SEric Dumazet 	int res;
19922b88cba5SEric Dumazet 
19932b88cba5SEric Dumazet 	saved_end_offset = skb_end_offset(skb);
19942b88cba5SEric Dumazet 	saved_truesize = skb->truesize;
19952b88cba5SEric Dumazet 
19962b88cba5SEric Dumazet 	res = pskb_expand_head(skb, 0, 0, pri);
19972b88cba5SEric Dumazet 	if (res)
19982b88cba5SEric Dumazet 		return res;
19992b88cba5SEric Dumazet 
20002b88cba5SEric Dumazet 	skb->truesize = saved_truesize;
20012b88cba5SEric Dumazet 
20022b88cba5SEric Dumazet 	if (likely(skb_end_offset(skb) == saved_end_offset))
20032b88cba5SEric Dumazet 		return 0;
20042b88cba5SEric Dumazet 
20052b88cba5SEric Dumazet 	shinfo = skb_shinfo(skb);
20062b88cba5SEric Dumazet 
20072b88cba5SEric Dumazet 	/* We are about to change back skb->end,
20082b88cba5SEric Dumazet 	 * we need to move skb_shinfo() to its new location.
20092b88cba5SEric Dumazet 	 */
20102b88cba5SEric Dumazet 	memmove(skb->head + saved_end_offset,
20112b88cba5SEric Dumazet 		shinfo,
20122b88cba5SEric Dumazet 		offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
20132b88cba5SEric Dumazet 
20142b88cba5SEric Dumazet 	skb_set_end_offset(skb, saved_end_offset);
20152b88cba5SEric Dumazet 
20162b88cba5SEric Dumazet 	return 0;
20172b88cba5SEric Dumazet }
20182b88cba5SEric Dumazet 
20191da177e4SLinus Torvalds /**
2020f1260ff1SVasily Averin  *	skb_expand_head - reallocate header of &sk_buff
2021f1260ff1SVasily Averin  *	@skb: buffer to reallocate
2022f1260ff1SVasily Averin  *	@headroom: needed headroom
2023f1260ff1SVasily Averin  *
2024f1260ff1SVasily Averin  *	Unlike skb_realloc_headroom, this one does not allocate a new skb
2025f1260ff1SVasily Averin  *	if possible; copies skb->sk to new skb as needed
2026f1260ff1SVasily Averin  *	and frees original skb in case of failures.
2027f1260ff1SVasily Averin  *
2028f1260ff1SVasily Averin  *	It expect increased headroom and generates warning otherwise.
2029f1260ff1SVasily Averin  */
2030f1260ff1SVasily Averin 
2031f1260ff1SVasily Averin struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2032f1260ff1SVasily Averin {
2033f1260ff1SVasily Averin 	int delta = headroom - skb_headroom(skb);
20347f678defSVasily Averin 	int osize = skb_end_offset(skb);
20357f678defSVasily Averin 	struct sock *sk = skb->sk;
2036f1260ff1SVasily Averin 
2037f1260ff1SVasily Averin 	if (WARN_ONCE(delta <= 0,
2038f1260ff1SVasily Averin 		      "%s is expecting an increase in the headroom", __func__))
2039f1260ff1SVasily Averin 		return skb;
2040f1260ff1SVasily Averin 
20417f678defSVasily Averin 	delta = SKB_DATA_ALIGN(delta);
20427f678defSVasily Averin 	/* pskb_expand_head() might crash, if skb is shared. */
20437f678defSVasily Averin 	if (skb_shared(skb) || !is_skb_wmem(skb)) {
2044f1260ff1SVasily Averin 		struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2045f1260ff1SVasily Averin 
20467f678defSVasily Averin 		if (unlikely(!nskb))
20477f678defSVasily Averin 			goto fail;
20487f678defSVasily Averin 
20497f678defSVasily Averin 		if (sk)
20507f678defSVasily Averin 			skb_set_owner_w(nskb, sk);
2051f1260ff1SVasily Averin 		consume_skb(skb);
2052f1260ff1SVasily Averin 		skb = nskb;
2053f1260ff1SVasily Averin 	}
20547f678defSVasily Averin 	if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
20557f678defSVasily Averin 		goto fail;
20567f678defSVasily Averin 
20577f678defSVasily Averin 	if (sk && is_skb_wmem(skb)) {
20587f678defSVasily Averin 		delta = skb_end_offset(skb) - osize;
20597f678defSVasily Averin 		refcount_add(delta, &sk->sk_wmem_alloc);
20607f678defSVasily Averin 		skb->truesize += delta;
2061f1260ff1SVasily Averin 	}
2062f1260ff1SVasily Averin 	return skb;
20637f678defSVasily Averin 
20647f678defSVasily Averin fail:
20657f678defSVasily Averin 	kfree_skb(skb);
20667f678defSVasily Averin 	return NULL;
2067f1260ff1SVasily Averin }
2068f1260ff1SVasily Averin EXPORT_SYMBOL(skb_expand_head);
2069f1260ff1SVasily Averin 
2070f1260ff1SVasily Averin /**
20711da177e4SLinus Torvalds  *	skb_copy_expand	-	copy and expand sk_buff
20721da177e4SLinus Torvalds  *	@skb: buffer to copy
20731da177e4SLinus Torvalds  *	@newheadroom: new free bytes at head
20741da177e4SLinus Torvalds  *	@newtailroom: new free bytes at tail
20751da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
20761da177e4SLinus Torvalds  *
20771da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and its data and while doing so
20781da177e4SLinus Torvalds  *	allocate additional space.
20791da177e4SLinus Torvalds  *
20801da177e4SLinus Torvalds  *	This is used when the caller wishes to modify the data and needs a
20811da177e4SLinus Torvalds  *	private copy of the data to alter as well as more space for new fields.
20821da177e4SLinus Torvalds  *	Returns %NULL on failure or the pointer to the buffer
20831da177e4SLinus Torvalds  *	on success. The returned buffer has a reference count of 1.
20841da177e4SLinus Torvalds  *
20851da177e4SLinus Torvalds  *	You must pass %GFP_ATOMIC as the allocation priority if this function
20861da177e4SLinus Torvalds  *	is called from an interrupt.
20871da177e4SLinus Torvalds  */
20881da177e4SLinus Torvalds struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
208986a76cafSVictor Fusco 				int newheadroom, int newtailroom,
2090dd0fc66fSAl Viro 				gfp_t gfp_mask)
20911da177e4SLinus Torvalds {
20921da177e4SLinus Torvalds 	/*
20931da177e4SLinus Torvalds 	 *	Allocate the copy buffer
20941da177e4SLinus Torvalds 	 */
2095c93bdd0eSMel Gorman 	struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2096c93bdd0eSMel Gorman 					gfp_mask, skb_alloc_rx_flag(skb),
2097c93bdd0eSMel Gorman 					NUMA_NO_NODE);
2098efd1e8d5SPatrick McHardy 	int oldheadroom = skb_headroom(skb);
20991da177e4SLinus Torvalds 	int head_copy_len, head_copy_off;
21001da177e4SLinus Torvalds 
21011da177e4SLinus Torvalds 	if (!n)
21021da177e4SLinus Torvalds 		return NULL;
21031da177e4SLinus Torvalds 
21041da177e4SLinus Torvalds 	skb_reserve(n, newheadroom);
21051da177e4SLinus Torvalds 
21061da177e4SLinus Torvalds 	/* Set the tail pointer and length */
21071da177e4SLinus Torvalds 	skb_put(n, skb->len);
21081da177e4SLinus Torvalds 
2109efd1e8d5SPatrick McHardy 	head_copy_len = oldheadroom;
21101da177e4SLinus Torvalds 	head_copy_off = 0;
21111da177e4SLinus Torvalds 	if (newheadroom <= head_copy_len)
21121da177e4SLinus Torvalds 		head_copy_len = newheadroom;
21131da177e4SLinus Torvalds 	else
21141da177e4SLinus Torvalds 		head_copy_off = newheadroom - head_copy_len;
21151da177e4SLinus Torvalds 
21161da177e4SLinus Torvalds 	/* Copy the linear header and data. */
21179f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
21189f77fad3STim Hansen 			     skb->len + head_copy_len));
21191da177e4SLinus Torvalds 
212008303c18SIlya Lesokhin 	skb_copy_header(n, skb);
21211da177e4SLinus Torvalds 
2122030737bcSEric Dumazet 	skb_headers_offset_update(n, newheadroom - oldheadroom);
2123efd1e8d5SPatrick McHardy 
21241da177e4SLinus Torvalds 	return n;
21251da177e4SLinus Torvalds }
2126b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_expand);
21271da177e4SLinus Torvalds 
21281da177e4SLinus Torvalds /**
2129cd0a137aSFlorian Fainelli  *	__skb_pad		-	zero pad the tail of an skb
21301da177e4SLinus Torvalds  *	@skb: buffer to pad
21311da177e4SLinus Torvalds  *	@pad: space to pad
2132cd0a137aSFlorian Fainelli  *	@free_on_error: free buffer on error
21331da177e4SLinus Torvalds  *
21341da177e4SLinus Torvalds  *	Ensure that a buffer is followed by a padding area that is zero
21351da177e4SLinus Torvalds  *	filled. Used by network drivers which may DMA or transfer data
21361da177e4SLinus Torvalds  *	beyond the buffer end onto the wire.
21371da177e4SLinus Torvalds  *
2138cd0a137aSFlorian Fainelli  *	May return error in out of memory cases. The skb is freed on error
2139cd0a137aSFlorian Fainelli  *	if @free_on_error is true.
21401da177e4SLinus Torvalds  */
21411da177e4SLinus Torvalds 
2142cd0a137aSFlorian Fainelli int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
21431da177e4SLinus Torvalds {
21445b057c6bSHerbert Xu 	int err;
21455b057c6bSHerbert Xu 	int ntail;
21461da177e4SLinus Torvalds 
21471da177e4SLinus Torvalds 	/* If the skbuff is non linear tailroom is always zero.. */
21485b057c6bSHerbert Xu 	if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
21491da177e4SLinus Torvalds 		memset(skb->data+skb->len, 0, pad);
21505b057c6bSHerbert Xu 		return 0;
21511da177e4SLinus Torvalds 	}
21521da177e4SLinus Torvalds 
21534305b541SArnaldo Carvalho de Melo 	ntail = skb->data_len + pad - (skb->end - skb->tail);
21545b057c6bSHerbert Xu 	if (likely(skb_cloned(skb) || ntail > 0)) {
21555b057c6bSHerbert Xu 		err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
21565b057c6bSHerbert Xu 		if (unlikely(err))
21575b057c6bSHerbert Xu 			goto free_skb;
21585b057c6bSHerbert Xu 	}
21595b057c6bSHerbert Xu 
21605b057c6bSHerbert Xu 	/* FIXME: The use of this function with non-linear skb's really needs
21615b057c6bSHerbert Xu 	 * to be audited.
21625b057c6bSHerbert Xu 	 */
21635b057c6bSHerbert Xu 	err = skb_linearize(skb);
21645b057c6bSHerbert Xu 	if (unlikely(err))
21655b057c6bSHerbert Xu 		goto free_skb;
21665b057c6bSHerbert Xu 
21675b057c6bSHerbert Xu 	memset(skb->data + skb->len, 0, pad);
21685b057c6bSHerbert Xu 	return 0;
21695b057c6bSHerbert Xu 
21705b057c6bSHerbert Xu free_skb:
2171cd0a137aSFlorian Fainelli 	if (free_on_error)
21721da177e4SLinus Torvalds 		kfree_skb(skb);
21735b057c6bSHerbert Xu 	return err;
21741da177e4SLinus Torvalds }
2175cd0a137aSFlorian Fainelli EXPORT_SYMBOL(__skb_pad);
21761da177e4SLinus Torvalds 
21770dde3e16SIlpo Järvinen /**
21780c7ddf36SMathias Krause  *	pskb_put - add data to the tail of a potentially fragmented buffer
21790c7ddf36SMathias Krause  *	@skb: start of the buffer to use
21800c7ddf36SMathias Krause  *	@tail: tail fragment of the buffer to use
21810c7ddf36SMathias Krause  *	@len: amount of data to add
21820c7ddf36SMathias Krause  *
21830c7ddf36SMathias Krause  *	This function extends the used data area of the potentially
21840c7ddf36SMathias Krause  *	fragmented buffer. @tail must be the last fragment of @skb -- or
21850c7ddf36SMathias Krause  *	@skb itself. If this would exceed the total buffer size the kernel
21860c7ddf36SMathias Krause  *	will panic. A pointer to the first byte of the extra data is
21870c7ddf36SMathias Krause  *	returned.
21880c7ddf36SMathias Krause  */
21890c7ddf36SMathias Krause 
21904df864c1SJohannes Berg void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
21910c7ddf36SMathias Krause {
21920c7ddf36SMathias Krause 	if (tail != skb) {
21930c7ddf36SMathias Krause 		skb->data_len += len;
21940c7ddf36SMathias Krause 		skb->len += len;
21950c7ddf36SMathias Krause 	}
21960c7ddf36SMathias Krause 	return skb_put(tail, len);
21970c7ddf36SMathias Krause }
21980c7ddf36SMathias Krause EXPORT_SYMBOL_GPL(pskb_put);
21990c7ddf36SMathias Krause 
22000c7ddf36SMathias Krause /**
22010dde3e16SIlpo Järvinen  *	skb_put - add data to a buffer
22020dde3e16SIlpo Järvinen  *	@skb: buffer to use
22030dde3e16SIlpo Järvinen  *	@len: amount of data to add
22040dde3e16SIlpo Järvinen  *
22050dde3e16SIlpo Järvinen  *	This function extends the used data area of the buffer. If this would
22060dde3e16SIlpo Järvinen  *	exceed the total buffer size the kernel will panic. A pointer to the
22070dde3e16SIlpo Järvinen  *	first byte of the extra data is returned.
22080dde3e16SIlpo Järvinen  */
22094df864c1SJohannes Berg void *skb_put(struct sk_buff *skb, unsigned int len)
22100dde3e16SIlpo Järvinen {
22114df864c1SJohannes Berg 	void *tmp = skb_tail_pointer(skb);
22120dde3e16SIlpo Järvinen 	SKB_LINEAR_ASSERT(skb);
22130dde3e16SIlpo Järvinen 	skb->tail += len;
22140dde3e16SIlpo Järvinen 	skb->len  += len;
22150dde3e16SIlpo Järvinen 	if (unlikely(skb->tail > skb->end))
22160dde3e16SIlpo Järvinen 		skb_over_panic(skb, len, __builtin_return_address(0));
22170dde3e16SIlpo Järvinen 	return tmp;
22180dde3e16SIlpo Järvinen }
22190dde3e16SIlpo Järvinen EXPORT_SYMBOL(skb_put);
22200dde3e16SIlpo Järvinen 
22216be8ac2fSIlpo Järvinen /**
2222c2aa270aSIlpo Järvinen  *	skb_push - add data to the start of a buffer
2223c2aa270aSIlpo Järvinen  *	@skb: buffer to use
2224c2aa270aSIlpo Järvinen  *	@len: amount of data to add
2225c2aa270aSIlpo Järvinen  *
2226c2aa270aSIlpo Järvinen  *	This function extends the used data area of the buffer at the buffer
2227c2aa270aSIlpo Järvinen  *	start. If this would exceed the total buffer headroom the kernel will
2228c2aa270aSIlpo Järvinen  *	panic. A pointer to the first byte of the extra data is returned.
2229c2aa270aSIlpo Järvinen  */
2230d58ff351SJohannes Berg void *skb_push(struct sk_buff *skb, unsigned int len)
2231c2aa270aSIlpo Järvinen {
2232c2aa270aSIlpo Järvinen 	skb->data -= len;
2233c2aa270aSIlpo Järvinen 	skb->len  += len;
2234c2aa270aSIlpo Järvinen 	if (unlikely(skb->data < skb->head))
2235c2aa270aSIlpo Järvinen 		skb_under_panic(skb, len, __builtin_return_address(0));
2236c2aa270aSIlpo Järvinen 	return skb->data;
2237c2aa270aSIlpo Järvinen }
2238c2aa270aSIlpo Järvinen EXPORT_SYMBOL(skb_push);
2239c2aa270aSIlpo Järvinen 
2240c2aa270aSIlpo Järvinen /**
22416be8ac2fSIlpo Järvinen  *	skb_pull - remove data from the start of a buffer
22426be8ac2fSIlpo Järvinen  *	@skb: buffer to use
22436be8ac2fSIlpo Järvinen  *	@len: amount of data to remove
22446be8ac2fSIlpo Järvinen  *
22456be8ac2fSIlpo Järvinen  *	This function removes data from the start of a buffer, returning
22466be8ac2fSIlpo Järvinen  *	the memory to the headroom. A pointer to the next data in the buffer
22476be8ac2fSIlpo Järvinen  *	is returned. Once the data has been pulled future pushes will overwrite
22486be8ac2fSIlpo Järvinen  *	the old data.
22496be8ac2fSIlpo Järvinen  */
2250af72868bSJohannes Berg void *skb_pull(struct sk_buff *skb, unsigned int len)
22516be8ac2fSIlpo Järvinen {
225247d29646SDavid S. Miller 	return skb_pull_inline(skb, len);
22536be8ac2fSIlpo Järvinen }
22546be8ac2fSIlpo Järvinen EXPORT_SYMBOL(skb_pull);
22556be8ac2fSIlpo Järvinen 
2256419ae74eSIlpo Järvinen /**
225713244cccSLuiz Augusto von Dentz  *	skb_pull_data - remove data from the start of a buffer returning its
225813244cccSLuiz Augusto von Dentz  *	original position.
225913244cccSLuiz Augusto von Dentz  *	@skb: buffer to use
226013244cccSLuiz Augusto von Dentz  *	@len: amount of data to remove
226113244cccSLuiz Augusto von Dentz  *
226213244cccSLuiz Augusto von Dentz  *	This function removes data from the start of a buffer, returning
226313244cccSLuiz Augusto von Dentz  *	the memory to the headroom. A pointer to the original data in the buffer
226413244cccSLuiz Augusto von Dentz  *	is returned after checking if there is enough data to pull. Once the
226513244cccSLuiz Augusto von Dentz  *	data has been pulled future pushes will overwrite the old data.
226613244cccSLuiz Augusto von Dentz  */
226713244cccSLuiz Augusto von Dentz void *skb_pull_data(struct sk_buff *skb, size_t len)
226813244cccSLuiz Augusto von Dentz {
226913244cccSLuiz Augusto von Dentz 	void *data = skb->data;
227013244cccSLuiz Augusto von Dentz 
227113244cccSLuiz Augusto von Dentz 	if (skb->len < len)
227213244cccSLuiz Augusto von Dentz 		return NULL;
227313244cccSLuiz Augusto von Dentz 
227413244cccSLuiz Augusto von Dentz 	skb_pull(skb, len);
227513244cccSLuiz Augusto von Dentz 
227613244cccSLuiz Augusto von Dentz 	return data;
227713244cccSLuiz Augusto von Dentz }
227813244cccSLuiz Augusto von Dentz EXPORT_SYMBOL(skb_pull_data);
227913244cccSLuiz Augusto von Dentz 
228013244cccSLuiz Augusto von Dentz /**
2281419ae74eSIlpo Järvinen  *	skb_trim - remove end from a buffer
2282419ae74eSIlpo Järvinen  *	@skb: buffer to alter
2283419ae74eSIlpo Järvinen  *	@len: new length
2284419ae74eSIlpo Järvinen  *
2285419ae74eSIlpo Järvinen  *	Cut the length of a buffer down by removing data from the tail. If
2286419ae74eSIlpo Järvinen  *	the buffer is already under the length specified it is not modified.
2287419ae74eSIlpo Järvinen  *	The skb must be linear.
2288419ae74eSIlpo Järvinen  */
2289419ae74eSIlpo Järvinen void skb_trim(struct sk_buff *skb, unsigned int len)
2290419ae74eSIlpo Järvinen {
2291419ae74eSIlpo Järvinen 	if (skb->len > len)
2292419ae74eSIlpo Järvinen 		__skb_trim(skb, len);
2293419ae74eSIlpo Järvinen }
2294419ae74eSIlpo Järvinen EXPORT_SYMBOL(skb_trim);
2295419ae74eSIlpo Järvinen 
22963cc0e873SHerbert Xu /* Trims skb to length len. It can change skb pointers.
22971da177e4SLinus Torvalds  */
22981da177e4SLinus Torvalds 
22993cc0e873SHerbert Xu int ___pskb_trim(struct sk_buff *skb, unsigned int len)
23001da177e4SLinus Torvalds {
230127b437c8SHerbert Xu 	struct sk_buff **fragp;
230227b437c8SHerbert Xu 	struct sk_buff *frag;
23031da177e4SLinus Torvalds 	int offset = skb_headlen(skb);
23041da177e4SLinus Torvalds 	int nfrags = skb_shinfo(skb)->nr_frags;
23051da177e4SLinus Torvalds 	int i;
230627b437c8SHerbert Xu 	int err;
230727b437c8SHerbert Xu 
230827b437c8SHerbert Xu 	if (skb_cloned(skb) &&
230927b437c8SHerbert Xu 	    unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
231027b437c8SHerbert Xu 		return err;
23111da177e4SLinus Torvalds 
2312f4d26fb3SHerbert Xu 	i = 0;
2313f4d26fb3SHerbert Xu 	if (offset >= len)
2314f4d26fb3SHerbert Xu 		goto drop_pages;
2315f4d26fb3SHerbert Xu 
2316f4d26fb3SHerbert Xu 	for (; i < nfrags; i++) {
23179e903e08SEric Dumazet 		int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
231827b437c8SHerbert Xu 
231927b437c8SHerbert Xu 		if (end < len) {
23201da177e4SLinus Torvalds 			offset = end;
232127b437c8SHerbert Xu 			continue;
23221da177e4SLinus Torvalds 		}
23231da177e4SLinus Torvalds 
23249e903e08SEric Dumazet 		skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
232527b437c8SHerbert Xu 
2326f4d26fb3SHerbert Xu drop_pages:
232727b437c8SHerbert Xu 		skb_shinfo(skb)->nr_frags = i;
232827b437c8SHerbert Xu 
232927b437c8SHerbert Xu 		for (; i < nfrags; i++)
2330ea2ab693SIan Campbell 			skb_frag_unref(skb, i);
233127b437c8SHerbert Xu 
233221dc3301SDavid S. Miller 		if (skb_has_frag_list(skb))
233327b437c8SHerbert Xu 			skb_drop_fraglist(skb);
2334f4d26fb3SHerbert Xu 		goto done;
233527b437c8SHerbert Xu 	}
233627b437c8SHerbert Xu 
233727b437c8SHerbert Xu 	for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
233827b437c8SHerbert Xu 	     fragp = &frag->next) {
233927b437c8SHerbert Xu 		int end = offset + frag->len;
234027b437c8SHerbert Xu 
234127b437c8SHerbert Xu 		if (skb_shared(frag)) {
234227b437c8SHerbert Xu 			struct sk_buff *nfrag;
234327b437c8SHerbert Xu 
234427b437c8SHerbert Xu 			nfrag = skb_clone(frag, GFP_ATOMIC);
234527b437c8SHerbert Xu 			if (unlikely(!nfrag))
234627b437c8SHerbert Xu 				return -ENOMEM;
234727b437c8SHerbert Xu 
234827b437c8SHerbert Xu 			nfrag->next = frag->next;
234985bb2a60SEric Dumazet 			consume_skb(frag);
235027b437c8SHerbert Xu 			frag = nfrag;
235127b437c8SHerbert Xu 			*fragp = frag;
235227b437c8SHerbert Xu 		}
235327b437c8SHerbert Xu 
235427b437c8SHerbert Xu 		if (end < len) {
235527b437c8SHerbert Xu 			offset = end;
235627b437c8SHerbert Xu 			continue;
235727b437c8SHerbert Xu 		}
235827b437c8SHerbert Xu 
235927b437c8SHerbert Xu 		if (end > len &&
236027b437c8SHerbert Xu 		    unlikely((err = pskb_trim(frag, len - offset))))
236127b437c8SHerbert Xu 			return err;
236227b437c8SHerbert Xu 
236327b437c8SHerbert Xu 		if (frag->next)
236427b437c8SHerbert Xu 			skb_drop_list(&frag->next);
236527b437c8SHerbert Xu 		break;
236627b437c8SHerbert Xu 	}
236727b437c8SHerbert Xu 
2368f4d26fb3SHerbert Xu done:
236927b437c8SHerbert Xu 	if (len > skb_headlen(skb)) {
23701da177e4SLinus Torvalds 		skb->data_len -= skb->len - len;
23711da177e4SLinus Torvalds 		skb->len       = len;
23721da177e4SLinus Torvalds 	} else {
23731da177e4SLinus Torvalds 		skb->len       = len;
23741da177e4SLinus Torvalds 		skb->data_len  = 0;
237527a884dcSArnaldo Carvalho de Melo 		skb_set_tail_pointer(skb, len);
23761da177e4SLinus Torvalds 	}
23771da177e4SLinus Torvalds 
2378c21b48ccSEric Dumazet 	if (!skb->sk || skb->destructor == sock_edemux)
2379c21b48ccSEric Dumazet 		skb_condense(skb);
23801da177e4SLinus Torvalds 	return 0;
23811da177e4SLinus Torvalds }
2382b4ac530fSDavid S. Miller EXPORT_SYMBOL(___pskb_trim);
23831da177e4SLinus Torvalds 
238488078d98SEric Dumazet /* Note : use pskb_trim_rcsum() instead of calling this directly
238588078d98SEric Dumazet  */
238688078d98SEric Dumazet int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
238788078d98SEric Dumazet {
238888078d98SEric Dumazet 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
238988078d98SEric Dumazet 		int delta = skb->len - len;
239088078d98SEric Dumazet 
2391d55bef50SDimitris Michailidis 		skb->csum = csum_block_sub(skb->csum,
2392d55bef50SDimitris Michailidis 					   skb_checksum(skb, len, delta, 0),
2393d55bef50SDimitris Michailidis 					   len);
239454970a2fSVasily Averin 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
239554970a2fSVasily Averin 		int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
239654970a2fSVasily Averin 		int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
239754970a2fSVasily Averin 
239854970a2fSVasily Averin 		if (offset + sizeof(__sum16) > hdlen)
239954970a2fSVasily Averin 			return -EINVAL;
240088078d98SEric Dumazet 	}
240188078d98SEric Dumazet 	return __pskb_trim(skb, len);
240288078d98SEric Dumazet }
240388078d98SEric Dumazet EXPORT_SYMBOL(pskb_trim_rcsum_slow);
240488078d98SEric Dumazet 
24051da177e4SLinus Torvalds /**
24061da177e4SLinus Torvalds  *	__pskb_pull_tail - advance tail of skb header
24071da177e4SLinus Torvalds  *	@skb: buffer to reallocate
24081da177e4SLinus Torvalds  *	@delta: number of bytes to advance tail
24091da177e4SLinus Torvalds  *
24101da177e4SLinus Torvalds  *	The function makes a sense only on a fragmented &sk_buff,
24111da177e4SLinus Torvalds  *	it expands header moving its tail forward and copying necessary
24121da177e4SLinus Torvalds  *	data from fragmented part.
24131da177e4SLinus Torvalds  *
24141da177e4SLinus Torvalds  *	&sk_buff MUST have reference count of 1.
24151da177e4SLinus Torvalds  *
24161da177e4SLinus Torvalds  *	Returns %NULL (and &sk_buff does not change) if pull failed
24171da177e4SLinus Torvalds  *	or value of new tail of skb in the case of success.
24181da177e4SLinus Torvalds  *
24191da177e4SLinus Torvalds  *	All the pointers pointing into skb header may change and must be
24201da177e4SLinus Torvalds  *	reloaded after call to this function.
24211da177e4SLinus Torvalds  */
24221da177e4SLinus Torvalds 
24231da177e4SLinus Torvalds /* Moves tail of skb head forward, copying data from fragmented part,
24241da177e4SLinus Torvalds  * when it is necessary.
24251da177e4SLinus Torvalds  * 1. It may fail due to malloc failure.
24261da177e4SLinus Torvalds  * 2. It may change skb pointers.
24271da177e4SLinus Torvalds  *
24281da177e4SLinus Torvalds  * It is pretty complicated. Luckily, it is called only in exceptional cases.
24291da177e4SLinus Torvalds  */
2430af72868bSJohannes Berg void *__pskb_pull_tail(struct sk_buff *skb, int delta)
24311da177e4SLinus Torvalds {
24321da177e4SLinus Torvalds 	/* If skb has not enough free space at tail, get new one
24331da177e4SLinus Torvalds 	 * plus 128 bytes for future expansions. If we have enough
24341da177e4SLinus Torvalds 	 * room at tail, reallocate without expansion only if skb is cloned.
24351da177e4SLinus Torvalds 	 */
24364305b541SArnaldo Carvalho de Melo 	int i, k, eat = (skb->tail + delta) - skb->end;
24371da177e4SLinus Torvalds 
24381da177e4SLinus Torvalds 	if (eat > 0 || skb_cloned(skb)) {
24391da177e4SLinus Torvalds 		if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
24401da177e4SLinus Torvalds 				     GFP_ATOMIC))
24411da177e4SLinus Torvalds 			return NULL;
24421da177e4SLinus Torvalds 	}
24431da177e4SLinus Torvalds 
24449f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
24459f77fad3STim Hansen 			     skb_tail_pointer(skb), delta));
24461da177e4SLinus Torvalds 
24471da177e4SLinus Torvalds 	/* Optimization: no fragments, no reasons to preestimate
24481da177e4SLinus Torvalds 	 * size of pulled pages. Superb.
24491da177e4SLinus Torvalds 	 */
245021dc3301SDavid S. Miller 	if (!skb_has_frag_list(skb))
24511da177e4SLinus Torvalds 		goto pull_pages;
24521da177e4SLinus Torvalds 
24531da177e4SLinus Torvalds 	/* Estimate size of pulled pages. */
24541da177e4SLinus Torvalds 	eat = delta;
24551da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
24569e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
24579e903e08SEric Dumazet 
24589e903e08SEric Dumazet 		if (size >= eat)
24591da177e4SLinus Torvalds 			goto pull_pages;
24609e903e08SEric Dumazet 		eat -= size;
24611da177e4SLinus Torvalds 	}
24621da177e4SLinus Torvalds 
24631da177e4SLinus Torvalds 	/* If we need update frag list, we are in troubles.
246409001b03SWenhua Shi 	 * Certainly, it is possible to add an offset to skb data,
24651da177e4SLinus Torvalds 	 * but taking into account that pulling is expected to
24661da177e4SLinus Torvalds 	 * be very rare operation, it is worth to fight against
24671da177e4SLinus Torvalds 	 * further bloating skb head and crucify ourselves here instead.
24681da177e4SLinus Torvalds 	 * Pure masohism, indeed. 8)8)
24691da177e4SLinus Torvalds 	 */
24701da177e4SLinus Torvalds 	if (eat) {
24711da177e4SLinus Torvalds 		struct sk_buff *list = skb_shinfo(skb)->frag_list;
24721da177e4SLinus Torvalds 		struct sk_buff *clone = NULL;
24731da177e4SLinus Torvalds 		struct sk_buff *insp = NULL;
24741da177e4SLinus Torvalds 
24751da177e4SLinus Torvalds 		do {
24761da177e4SLinus Torvalds 			if (list->len <= eat) {
24771da177e4SLinus Torvalds 				/* Eaten as whole. */
24781da177e4SLinus Torvalds 				eat -= list->len;
24791da177e4SLinus Torvalds 				list = list->next;
24801da177e4SLinus Torvalds 				insp = list;
24811da177e4SLinus Torvalds 			} else {
24821da177e4SLinus Torvalds 				/* Eaten partially. */
24832d7afdcbSSubash Abhinov Kasiviswanathan 				if (skb_is_gso(skb) && !list->head_frag &&
24842d7afdcbSSubash Abhinov Kasiviswanathan 				    skb_headlen(list))
24852d7afdcbSSubash Abhinov Kasiviswanathan 					skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
24861da177e4SLinus Torvalds 
24871da177e4SLinus Torvalds 				if (skb_shared(list)) {
24881da177e4SLinus Torvalds 					/* Sucks! We need to fork list. :-( */
24891da177e4SLinus Torvalds 					clone = skb_clone(list, GFP_ATOMIC);
24901da177e4SLinus Torvalds 					if (!clone)
24911da177e4SLinus Torvalds 						return NULL;
24921da177e4SLinus Torvalds 					insp = list->next;
24931da177e4SLinus Torvalds 					list = clone;
24941da177e4SLinus Torvalds 				} else {
24951da177e4SLinus Torvalds 					/* This may be pulled without
24961da177e4SLinus Torvalds 					 * problems. */
24971da177e4SLinus Torvalds 					insp = list;
24981da177e4SLinus Torvalds 				}
24991da177e4SLinus Torvalds 				if (!pskb_pull(list, eat)) {
25001da177e4SLinus Torvalds 					kfree_skb(clone);
25011da177e4SLinus Torvalds 					return NULL;
25021da177e4SLinus Torvalds 				}
25031da177e4SLinus Torvalds 				break;
25041da177e4SLinus Torvalds 			}
25051da177e4SLinus Torvalds 		} while (eat);
25061da177e4SLinus Torvalds 
25071da177e4SLinus Torvalds 		/* Free pulled out fragments. */
25081da177e4SLinus Torvalds 		while ((list = skb_shinfo(skb)->frag_list) != insp) {
25091da177e4SLinus Torvalds 			skb_shinfo(skb)->frag_list = list->next;
2510ef527f96SEric Dumazet 			consume_skb(list);
25111da177e4SLinus Torvalds 		}
25121da177e4SLinus Torvalds 		/* And insert new clone at head. */
25131da177e4SLinus Torvalds 		if (clone) {
25141da177e4SLinus Torvalds 			clone->next = list;
25151da177e4SLinus Torvalds 			skb_shinfo(skb)->frag_list = clone;
25161da177e4SLinus Torvalds 		}
25171da177e4SLinus Torvalds 	}
25181da177e4SLinus Torvalds 	/* Success! Now we may commit changes to skb data. */
25191da177e4SLinus Torvalds 
25201da177e4SLinus Torvalds pull_pages:
25211da177e4SLinus Torvalds 	eat = delta;
25221da177e4SLinus Torvalds 	k = 0;
25231da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
25249e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
25259e903e08SEric Dumazet 
25269e903e08SEric Dumazet 		if (size <= eat) {
2527ea2ab693SIan Campbell 			skb_frag_unref(skb, i);
25289e903e08SEric Dumazet 			eat -= size;
25291da177e4SLinus Torvalds 		} else {
2530b54c9d5bSJonathan Lemon 			skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2531b54c9d5bSJonathan Lemon 
2532b54c9d5bSJonathan Lemon 			*frag = skb_shinfo(skb)->frags[i];
25331da177e4SLinus Torvalds 			if (eat) {
2534b54c9d5bSJonathan Lemon 				skb_frag_off_add(frag, eat);
2535b54c9d5bSJonathan Lemon 				skb_frag_size_sub(frag, eat);
25363ccc6c6fSlinzhang 				if (!i)
25373ccc6c6fSlinzhang 					goto end;
25381da177e4SLinus Torvalds 				eat = 0;
25391da177e4SLinus Torvalds 			}
25401da177e4SLinus Torvalds 			k++;
25411da177e4SLinus Torvalds 		}
25421da177e4SLinus Torvalds 	}
25431da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags = k;
25441da177e4SLinus Torvalds 
25453ccc6c6fSlinzhang end:
25461da177e4SLinus Torvalds 	skb->tail     += delta;
25471da177e4SLinus Torvalds 	skb->data_len -= delta;
25481da177e4SLinus Torvalds 
25491f8b977aSWillem de Bruijn 	if (!skb->data_len)
25501f8b977aSWillem de Bruijn 		skb_zcopy_clear(skb, false);
25511f8b977aSWillem de Bruijn 
255227a884dcSArnaldo Carvalho de Melo 	return skb_tail_pointer(skb);
25531da177e4SLinus Torvalds }
2554b4ac530fSDavid S. Miller EXPORT_SYMBOL(__pskb_pull_tail);
25551da177e4SLinus Torvalds 
255622019b17SEric Dumazet /**
255722019b17SEric Dumazet  *	skb_copy_bits - copy bits from skb to kernel buffer
255822019b17SEric Dumazet  *	@skb: source skb
255922019b17SEric Dumazet  *	@offset: offset in source
256022019b17SEric Dumazet  *	@to: destination buffer
256122019b17SEric Dumazet  *	@len: number of bytes to copy
256222019b17SEric Dumazet  *
256322019b17SEric Dumazet  *	Copy the specified number of bytes from the source skb to the
256422019b17SEric Dumazet  *	destination buffer.
256522019b17SEric Dumazet  *
256622019b17SEric Dumazet  *	CAUTION ! :
256722019b17SEric Dumazet  *		If its prototype is ever changed,
256822019b17SEric Dumazet  *		check arch/{*}/net/{*}.S files,
256922019b17SEric Dumazet  *		since it is called from BPF assembly code.
257022019b17SEric Dumazet  */
25711da177e4SLinus Torvalds int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
25721da177e4SLinus Torvalds {
25731a028e50SDavid S. Miller 	int start = skb_headlen(skb);
2574fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
2575fbb398a8SDavid S. Miller 	int i, copy;
25761da177e4SLinus Torvalds 
25771da177e4SLinus Torvalds 	if (offset > (int)skb->len - len)
25781da177e4SLinus Torvalds 		goto fault;
25791da177e4SLinus Torvalds 
25801da177e4SLinus Torvalds 	/* Copy header. */
25811a028e50SDavid S. Miller 	if ((copy = start - offset) > 0) {
25821da177e4SLinus Torvalds 		if (copy > len)
25831da177e4SLinus Torvalds 			copy = len;
2584d626f62bSArnaldo Carvalho de Melo 		skb_copy_from_linear_data_offset(skb, offset, to, copy);
25851da177e4SLinus Torvalds 		if ((len -= copy) == 0)
25861da177e4SLinus Torvalds 			return 0;
25871da177e4SLinus Torvalds 		offset += copy;
25881da177e4SLinus Torvalds 		to     += copy;
25891da177e4SLinus Torvalds 	}
25901da177e4SLinus Torvalds 
25911da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
25921a028e50SDavid S. Miller 		int end;
259351c56b00SEric Dumazet 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
25941da177e4SLinus Torvalds 
2595547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
25961a028e50SDavid S. Miller 
259751c56b00SEric Dumazet 		end = start + skb_frag_size(f);
25981da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
2599c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2600c613c209SWillem de Bruijn 			struct page *p;
26011da177e4SLinus Torvalds 			u8 *vaddr;
26021da177e4SLinus Torvalds 
26031da177e4SLinus Torvalds 			if (copy > len)
26041da177e4SLinus Torvalds 				copy = len;
26051da177e4SLinus Torvalds 
2606c613c209SWillem de Bruijn 			skb_frag_foreach_page(f,
2607b54c9d5bSJonathan Lemon 					      skb_frag_off(f) + offset - start,
2608c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2609c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
2610c613c209SWillem de Bruijn 				memcpy(to + copied, vaddr + p_off, p_len);
261151c56b00SEric Dumazet 				kunmap_atomic(vaddr);
2612c613c209SWillem de Bruijn 			}
26131da177e4SLinus Torvalds 
26141da177e4SLinus Torvalds 			if ((len -= copy) == 0)
26151da177e4SLinus Torvalds 				return 0;
26161da177e4SLinus Torvalds 			offset += copy;
26171da177e4SLinus Torvalds 			to     += copy;
26181da177e4SLinus Torvalds 		}
26191a028e50SDavid S. Miller 		start = end;
26201da177e4SLinus Torvalds 	}
26211da177e4SLinus Torvalds 
2622fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
26231a028e50SDavid S. Miller 		int end;
26241da177e4SLinus Torvalds 
2625547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
26261a028e50SDavid S. Miller 
2627fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
26281da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
26291da177e4SLinus Torvalds 			if (copy > len)
26301da177e4SLinus Torvalds 				copy = len;
2631fbb398a8SDavid S. Miller 			if (skb_copy_bits(frag_iter, offset - start, to, copy))
26321da177e4SLinus Torvalds 				goto fault;
26331da177e4SLinus Torvalds 			if ((len -= copy) == 0)
26341da177e4SLinus Torvalds 				return 0;
26351da177e4SLinus Torvalds 			offset += copy;
26361da177e4SLinus Torvalds 			to     += copy;
26371da177e4SLinus Torvalds 		}
26381a028e50SDavid S. Miller 		start = end;
26391da177e4SLinus Torvalds 	}
2640a6686f2fSShirley Ma 
26411da177e4SLinus Torvalds 	if (!len)
26421da177e4SLinus Torvalds 		return 0;
26431da177e4SLinus Torvalds 
26441da177e4SLinus Torvalds fault:
26451da177e4SLinus Torvalds 	return -EFAULT;
26461da177e4SLinus Torvalds }
2647b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_bits);
26481da177e4SLinus Torvalds 
26499c55e01cSJens Axboe /*
26509c55e01cSJens Axboe  * Callback from splice_to_pipe(), if we need to release some pages
26519c55e01cSJens Axboe  * at the end of the spd in case we error'ed out in filling the pipe.
26529c55e01cSJens Axboe  */
26539c55e01cSJens Axboe static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
26549c55e01cSJens Axboe {
26558b9d3728SJarek Poplawski 	put_page(spd->pages[i]);
26568b9d3728SJarek Poplawski }
26579c55e01cSJens Axboe 
2658a108d5f3SDavid S. Miller static struct page *linear_to_page(struct page *page, unsigned int *len,
26594fb66994SJarek Poplawski 				   unsigned int *offset,
266018aafc62SEric Dumazet 				   struct sock *sk)
26618b9d3728SJarek Poplawski {
26625640f768SEric Dumazet 	struct page_frag *pfrag = sk_page_frag(sk);
26638b9d3728SJarek Poplawski 
26645640f768SEric Dumazet 	if (!sk_page_frag_refill(sk, pfrag))
26658b9d3728SJarek Poplawski 		return NULL;
26664fb66994SJarek Poplawski 
26675640f768SEric Dumazet 	*len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
26684fb66994SJarek Poplawski 
26695640f768SEric Dumazet 	memcpy(page_address(pfrag->page) + pfrag->offset,
26705640f768SEric Dumazet 	       page_address(page) + *offset, *len);
26715640f768SEric Dumazet 	*offset = pfrag->offset;
26725640f768SEric Dumazet 	pfrag->offset += *len;
26734fb66994SJarek Poplawski 
26745640f768SEric Dumazet 	return pfrag->page;
26759c55e01cSJens Axboe }
26769c55e01cSJens Axboe 
267741c73a0dSEric Dumazet static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
267841c73a0dSEric Dumazet 			     struct page *page,
267941c73a0dSEric Dumazet 			     unsigned int offset)
268041c73a0dSEric Dumazet {
268141c73a0dSEric Dumazet 	return	spd->nr_pages &&
268241c73a0dSEric Dumazet 		spd->pages[spd->nr_pages - 1] == page &&
268341c73a0dSEric Dumazet 		(spd->partial[spd->nr_pages - 1].offset +
268441c73a0dSEric Dumazet 		 spd->partial[spd->nr_pages - 1].len == offset);
268541c73a0dSEric Dumazet }
268641c73a0dSEric Dumazet 
26879c55e01cSJens Axboe /*
26889c55e01cSJens Axboe  * Fill page/offset/length into spd, if it can hold more pages.
26899c55e01cSJens Axboe  */
2690a108d5f3SDavid S. Miller static bool spd_fill_page(struct splice_pipe_desc *spd,
269135f3d14dSJens Axboe 			  struct pipe_inode_info *pipe, struct page *page,
26924fb66994SJarek Poplawski 			  unsigned int *len, unsigned int offset,
269318aafc62SEric Dumazet 			  bool linear,
26947a67e56fSJarek Poplawski 			  struct sock *sk)
26959c55e01cSJens Axboe {
269641c73a0dSEric Dumazet 	if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2697a108d5f3SDavid S. Miller 		return true;
26989c55e01cSJens Axboe 
26998b9d3728SJarek Poplawski 	if (linear) {
270018aafc62SEric Dumazet 		page = linear_to_page(page, len, &offset, sk);
27018b9d3728SJarek Poplawski 		if (!page)
2702a108d5f3SDavid S. Miller 			return true;
270341c73a0dSEric Dumazet 	}
270441c73a0dSEric Dumazet 	if (spd_can_coalesce(spd, page, offset)) {
270541c73a0dSEric Dumazet 		spd->partial[spd->nr_pages - 1].len += *len;
2706a108d5f3SDavid S. Miller 		return false;
270741c73a0dSEric Dumazet 	}
27088b9d3728SJarek Poplawski 	get_page(page);
27099c55e01cSJens Axboe 	spd->pages[spd->nr_pages] = page;
27104fb66994SJarek Poplawski 	spd->partial[spd->nr_pages].len = *len;
27119c55e01cSJens Axboe 	spd->partial[spd->nr_pages].offset = offset;
27129c55e01cSJens Axboe 	spd->nr_pages++;
27138b9d3728SJarek Poplawski 
2714a108d5f3SDavid S. Miller 	return false;
27159c55e01cSJens Axboe }
27169c55e01cSJens Axboe 
2717a108d5f3SDavid S. Miller static bool __splice_segment(struct page *page, unsigned int poff,
27182870c43dSOctavian Purdila 			     unsigned int plen, unsigned int *off,
271918aafc62SEric Dumazet 			     unsigned int *len,
2720d7ccf7c0SEric Dumazet 			     struct splice_pipe_desc *spd, bool linear,
272135f3d14dSJens Axboe 			     struct sock *sk,
272235f3d14dSJens Axboe 			     struct pipe_inode_info *pipe)
27239c55e01cSJens Axboe {
27242870c43dSOctavian Purdila 	if (!*len)
2725a108d5f3SDavid S. Miller 		return true;
27269c55e01cSJens Axboe 
27272870c43dSOctavian Purdila 	/* skip this segment if already processed */
27282870c43dSOctavian Purdila 	if (*off >= plen) {
27292870c43dSOctavian Purdila 		*off -= plen;
2730a108d5f3SDavid S. Miller 		return false;
27312870c43dSOctavian Purdila 	}
27322870c43dSOctavian Purdila 
27332870c43dSOctavian Purdila 	/* ignore any bits we already processed */
27349ca1b22dSEric Dumazet 	poff += *off;
27359ca1b22dSEric Dumazet 	plen -= *off;
27362870c43dSOctavian Purdila 	*off = 0;
27372870c43dSOctavian Purdila 
273818aafc62SEric Dumazet 	do {
273918aafc62SEric Dumazet 		unsigned int flen = min(*len, plen);
27402870c43dSOctavian Purdila 
274118aafc62SEric Dumazet 		if (spd_fill_page(spd, pipe, page, &flen, poff,
274218aafc62SEric Dumazet 				  linear, sk))
2743a108d5f3SDavid S. Miller 			return true;
274418aafc62SEric Dumazet 		poff += flen;
274518aafc62SEric Dumazet 		plen -= flen;
27462870c43dSOctavian Purdila 		*len -= flen;
274718aafc62SEric Dumazet 	} while (*len && plen);
27482870c43dSOctavian Purdila 
2749a108d5f3SDavid S. Miller 	return false;
2750db43a282SOctavian Purdila }
27519c55e01cSJens Axboe 
27529c55e01cSJens Axboe /*
2753a108d5f3SDavid S. Miller  * Map linear and fragment data from the skb to spd. It reports true if the
27542870c43dSOctavian Purdila  * pipe is full or if we already spliced the requested length.
27559c55e01cSJens Axboe  */
2756a108d5f3SDavid S. Miller static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
275735f3d14dSJens Axboe 			      unsigned int *offset, unsigned int *len,
275835f3d14dSJens Axboe 			      struct splice_pipe_desc *spd, struct sock *sk)
27592870c43dSOctavian Purdila {
27602870c43dSOctavian Purdila 	int seg;
2761fa9835e5STom Herbert 	struct sk_buff *iter;
27629c55e01cSJens Axboe 
27631d0c0b32SEric Dumazet 	/* map the linear part :
27642996d31fSAlexander Duyck 	 * If skb->head_frag is set, this 'linear' part is backed by a
27652996d31fSAlexander Duyck 	 * fragment, and if the head is not shared with any clones then
27662996d31fSAlexander Duyck 	 * we can avoid a copy since we own the head portion of this page.
27679c55e01cSJens Axboe 	 */
27682870c43dSOctavian Purdila 	if (__splice_segment(virt_to_page(skb->data),
27692870c43dSOctavian Purdila 			     (unsigned long) skb->data & (PAGE_SIZE - 1),
27702870c43dSOctavian Purdila 			     skb_headlen(skb),
277118aafc62SEric Dumazet 			     offset, len, spd,
27723a7c1ee4SAlexander Duyck 			     skb_head_is_locked(skb),
27731d0c0b32SEric Dumazet 			     sk, pipe))
2774a108d5f3SDavid S. Miller 		return true;
27759c55e01cSJens Axboe 
27769c55e01cSJens Axboe 	/*
27779c55e01cSJens Axboe 	 * then map the fragments
27789c55e01cSJens Axboe 	 */
27799c55e01cSJens Axboe 	for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
27809c55e01cSJens Axboe 		const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
27819c55e01cSJens Axboe 
2782ea2ab693SIan Campbell 		if (__splice_segment(skb_frag_page(f),
2783b54c9d5bSJonathan Lemon 				     skb_frag_off(f), skb_frag_size(f),
278418aafc62SEric Dumazet 				     offset, len, spd, false, sk, pipe))
2785a108d5f3SDavid S. Miller 			return true;
27869c55e01cSJens Axboe 	}
27879c55e01cSJens Axboe 
2788fa9835e5STom Herbert 	skb_walk_frags(skb, iter) {
2789fa9835e5STom Herbert 		if (*offset >= iter->len) {
2790fa9835e5STom Herbert 			*offset -= iter->len;
2791fa9835e5STom Herbert 			continue;
2792fa9835e5STom Herbert 		}
2793fa9835e5STom Herbert 		/* __skb_splice_bits() only fails if the output has no room
2794fa9835e5STom Herbert 		 * left, so no point in going over the frag_list for the error
2795fa9835e5STom Herbert 		 * case.
2796fa9835e5STom Herbert 		 */
2797fa9835e5STom Herbert 		if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2798fa9835e5STom Herbert 			return true;
2799fa9835e5STom Herbert 	}
2800fa9835e5STom Herbert 
2801a108d5f3SDavid S. Miller 	return false;
28029c55e01cSJens Axboe }
28039c55e01cSJens Axboe 
28049c55e01cSJens Axboe /*
28059c55e01cSJens Axboe  * Map data from the skb to a pipe. Should handle both the linear part,
2806fa9835e5STom Herbert  * the fragments, and the frag list.
28079c55e01cSJens Axboe  */
2808a60e3cc7SHannes Frederic Sowa int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
28099c55e01cSJens Axboe 		    struct pipe_inode_info *pipe, unsigned int tlen,
281025869262SAl Viro 		    unsigned int flags)
28119c55e01cSJens Axboe {
281241c73a0dSEric Dumazet 	struct partial_page partial[MAX_SKB_FRAGS];
281341c73a0dSEric Dumazet 	struct page *pages[MAX_SKB_FRAGS];
28149c55e01cSJens Axboe 	struct splice_pipe_desc spd = {
28159c55e01cSJens Axboe 		.pages = pages,
28169c55e01cSJens Axboe 		.partial = partial,
2817047fe360SEric Dumazet 		.nr_pages_max = MAX_SKB_FRAGS,
281828a625cbSMiklos Szeredi 		.ops = &nosteal_pipe_buf_ops,
28199c55e01cSJens Axboe 		.spd_release = sock_spd_release,
28209c55e01cSJens Axboe 	};
282135f3d14dSJens Axboe 	int ret = 0;
282235f3d14dSJens Axboe 
2823fa9835e5STom Herbert 	__skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
28249c55e01cSJens Axboe 
2825a60e3cc7SHannes Frederic Sowa 	if (spd.nr_pages)
282625869262SAl Viro 		ret = splice_to_pipe(pipe, &spd);
28279c55e01cSJens Axboe 
282835f3d14dSJens Axboe 	return ret;
28299c55e01cSJens Axboe }
28302b514574SHannes Frederic Sowa EXPORT_SYMBOL_GPL(skb_splice_bits);
28319c55e01cSJens Axboe 
28320739cd28SCong Wang static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
28330739cd28SCong Wang 			    struct kvec *vec, size_t num, size_t size)
28340739cd28SCong Wang {
28350739cd28SCong Wang 	struct socket *sock = sk->sk_socket;
28360739cd28SCong Wang 
28370739cd28SCong Wang 	if (!sock)
28380739cd28SCong Wang 		return -EINVAL;
28390739cd28SCong Wang 	return kernel_sendmsg(sock, msg, vec, num, size);
28400739cd28SCong Wang }
28410739cd28SCong Wang 
28420739cd28SCong Wang static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
28430739cd28SCong Wang 			     size_t size, int flags)
28440739cd28SCong Wang {
28450739cd28SCong Wang 	struct socket *sock = sk->sk_socket;
28460739cd28SCong Wang 
28470739cd28SCong Wang 	if (!sock)
28480739cd28SCong Wang 		return -EINVAL;
28490739cd28SCong Wang 	return kernel_sendpage(sock, page, offset, size, flags);
28500739cd28SCong Wang }
28510739cd28SCong Wang 
28520739cd28SCong Wang typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
28530739cd28SCong Wang 			    struct kvec *vec, size_t num, size_t size);
28540739cd28SCong Wang typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
28550739cd28SCong Wang 			     size_t size, int flags);
28560739cd28SCong Wang static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
28570739cd28SCong Wang 			   int len, sendmsg_func sendmsg, sendpage_func sendpage)
285820bf50deSTom Herbert {
285920bf50deSTom Herbert 	unsigned int orig_len = len;
286020bf50deSTom Herbert 	struct sk_buff *head = skb;
286120bf50deSTom Herbert 	unsigned short fragidx;
286220bf50deSTom Herbert 	int slen, ret;
286320bf50deSTom Herbert 
286420bf50deSTom Herbert do_frag_list:
286520bf50deSTom Herbert 
286620bf50deSTom Herbert 	/* Deal with head data */
286720bf50deSTom Herbert 	while (offset < skb_headlen(skb) && len) {
286820bf50deSTom Herbert 		struct kvec kv;
286920bf50deSTom Herbert 		struct msghdr msg;
287020bf50deSTom Herbert 
287120bf50deSTom Herbert 		slen = min_t(int, len, skb_headlen(skb) - offset);
287220bf50deSTom Herbert 		kv.iov_base = skb->data + offset;
2873db5980d8SJohn Fastabend 		kv.iov_len = slen;
287420bf50deSTom Herbert 		memset(&msg, 0, sizeof(msg));
2875bd95e678SJohn Fastabend 		msg.msg_flags = MSG_DONTWAIT;
287620bf50deSTom Herbert 
28770739cd28SCong Wang 		ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
28780739cd28SCong Wang 				      sendmsg_unlocked, sk, &msg, &kv, 1, slen);
287920bf50deSTom Herbert 		if (ret <= 0)
288020bf50deSTom Herbert 			goto error;
288120bf50deSTom Herbert 
288220bf50deSTom Herbert 		offset += ret;
288320bf50deSTom Herbert 		len -= ret;
288420bf50deSTom Herbert 	}
288520bf50deSTom Herbert 
288620bf50deSTom Herbert 	/* All the data was skb head? */
288720bf50deSTom Herbert 	if (!len)
288820bf50deSTom Herbert 		goto out;
288920bf50deSTom Herbert 
289020bf50deSTom Herbert 	/* Make offset relative to start of frags */
289120bf50deSTom Herbert 	offset -= skb_headlen(skb);
289220bf50deSTom Herbert 
289320bf50deSTom Herbert 	/* Find where we are in frag list */
289420bf50deSTom Herbert 	for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
289520bf50deSTom Herbert 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
289620bf50deSTom Herbert 
2897d8e18a51SMatthew Wilcox (Oracle) 		if (offset < skb_frag_size(frag))
289820bf50deSTom Herbert 			break;
289920bf50deSTom Herbert 
2900d8e18a51SMatthew Wilcox (Oracle) 		offset -= skb_frag_size(frag);
290120bf50deSTom Herbert 	}
290220bf50deSTom Herbert 
290320bf50deSTom Herbert 	for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
290420bf50deSTom Herbert 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
290520bf50deSTom Herbert 
2906d8e18a51SMatthew Wilcox (Oracle) 		slen = min_t(size_t, len, skb_frag_size(frag) - offset);
290720bf50deSTom Herbert 
290820bf50deSTom Herbert 		while (slen) {
29090739cd28SCong Wang 			ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
29100739cd28SCong Wang 					      sendpage_unlocked, sk,
29110739cd28SCong Wang 					      skb_frag_page(frag),
2912b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset,
291320bf50deSTom Herbert 					      slen, MSG_DONTWAIT);
291420bf50deSTom Herbert 			if (ret <= 0)
291520bf50deSTom Herbert 				goto error;
291620bf50deSTom Herbert 
291720bf50deSTom Herbert 			len -= ret;
291820bf50deSTom Herbert 			offset += ret;
291920bf50deSTom Herbert 			slen -= ret;
292020bf50deSTom Herbert 		}
292120bf50deSTom Herbert 
292220bf50deSTom Herbert 		offset = 0;
292320bf50deSTom Herbert 	}
292420bf50deSTom Herbert 
292520bf50deSTom Herbert 	if (len) {
292620bf50deSTom Herbert 		/* Process any frag lists */
292720bf50deSTom Herbert 
292820bf50deSTom Herbert 		if (skb == head) {
292920bf50deSTom Herbert 			if (skb_has_frag_list(skb)) {
293020bf50deSTom Herbert 				skb = skb_shinfo(skb)->frag_list;
293120bf50deSTom Herbert 				goto do_frag_list;
293220bf50deSTom Herbert 			}
293320bf50deSTom Herbert 		} else if (skb->next) {
293420bf50deSTom Herbert 			skb = skb->next;
293520bf50deSTom Herbert 			goto do_frag_list;
293620bf50deSTom Herbert 		}
293720bf50deSTom Herbert 	}
293820bf50deSTom Herbert 
293920bf50deSTom Herbert out:
294020bf50deSTom Herbert 	return orig_len - len;
294120bf50deSTom Herbert 
294220bf50deSTom Herbert error:
294320bf50deSTom Herbert 	return orig_len == len ? ret : orig_len - len;
294420bf50deSTom Herbert }
29450739cd28SCong Wang 
29460739cd28SCong Wang /* Send skb data on a socket. Socket must be locked. */
29470739cd28SCong Wang int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
29480739cd28SCong Wang 			 int len)
29490739cd28SCong Wang {
29500739cd28SCong Wang 	return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
29510739cd28SCong Wang 			       kernel_sendpage_locked);
29520739cd28SCong Wang }
295320bf50deSTom Herbert EXPORT_SYMBOL_GPL(skb_send_sock_locked);
295420bf50deSTom Herbert 
29550739cd28SCong Wang /* Send skb data on a socket. Socket must be unlocked. */
29560739cd28SCong Wang int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
29570739cd28SCong Wang {
29580739cd28SCong Wang 	return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
29590739cd28SCong Wang 			       sendpage_unlocked);
29600739cd28SCong Wang }
29610739cd28SCong Wang 
2962357b40a1SHerbert Xu /**
2963357b40a1SHerbert Xu  *	skb_store_bits - store bits from kernel buffer to skb
2964357b40a1SHerbert Xu  *	@skb: destination buffer
2965357b40a1SHerbert Xu  *	@offset: offset in destination
2966357b40a1SHerbert Xu  *	@from: source buffer
2967357b40a1SHerbert Xu  *	@len: number of bytes to copy
2968357b40a1SHerbert Xu  *
2969357b40a1SHerbert Xu  *	Copy the specified number of bytes from the source buffer to the
2970357b40a1SHerbert Xu  *	destination skb.  This function handles all the messy bits of
2971357b40a1SHerbert Xu  *	traversing fragment lists and such.
2972357b40a1SHerbert Xu  */
2973357b40a1SHerbert Xu 
29740c6fcc8aSStephen Hemminger int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2975357b40a1SHerbert Xu {
29761a028e50SDavid S. Miller 	int start = skb_headlen(skb);
2977fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
2978fbb398a8SDavid S. Miller 	int i, copy;
2979357b40a1SHerbert Xu 
2980357b40a1SHerbert Xu 	if (offset > (int)skb->len - len)
2981357b40a1SHerbert Xu 		goto fault;
2982357b40a1SHerbert Xu 
29831a028e50SDavid S. Miller 	if ((copy = start - offset) > 0) {
2984357b40a1SHerbert Xu 		if (copy > len)
2985357b40a1SHerbert Xu 			copy = len;
298627d7ff46SArnaldo Carvalho de Melo 		skb_copy_to_linear_data_offset(skb, offset, from, copy);
2987357b40a1SHerbert Xu 		if ((len -= copy) == 0)
2988357b40a1SHerbert Xu 			return 0;
2989357b40a1SHerbert Xu 		offset += copy;
2990357b40a1SHerbert Xu 		from += copy;
2991357b40a1SHerbert Xu 	}
2992357b40a1SHerbert Xu 
2993357b40a1SHerbert Xu 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2994357b40a1SHerbert Xu 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
29951a028e50SDavid S. Miller 		int end;
2996357b40a1SHerbert Xu 
2997547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
29981a028e50SDavid S. Miller 
29999e903e08SEric Dumazet 		end = start + skb_frag_size(frag);
3000357b40a1SHerbert Xu 		if ((copy = end - offset) > 0) {
3001c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
3002c613c209SWillem de Bruijn 			struct page *p;
3003357b40a1SHerbert Xu 			u8 *vaddr;
3004357b40a1SHerbert Xu 
3005357b40a1SHerbert Xu 			if (copy > len)
3006357b40a1SHerbert Xu 				copy = len;
3007357b40a1SHerbert Xu 
3008c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
3009b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
3010c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
3011c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
3012c613c209SWillem de Bruijn 				memcpy(vaddr + p_off, from + copied, p_len);
301351c56b00SEric Dumazet 				kunmap_atomic(vaddr);
3014c613c209SWillem de Bruijn 			}
3015357b40a1SHerbert Xu 
3016357b40a1SHerbert Xu 			if ((len -= copy) == 0)
3017357b40a1SHerbert Xu 				return 0;
3018357b40a1SHerbert Xu 			offset += copy;
3019357b40a1SHerbert Xu 			from += copy;
3020357b40a1SHerbert Xu 		}
30211a028e50SDavid S. Miller 		start = end;
3022357b40a1SHerbert Xu 	}
3023357b40a1SHerbert Xu 
3024fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
30251a028e50SDavid S. Miller 		int end;
3026357b40a1SHerbert Xu 
3027547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
30281a028e50SDavid S. Miller 
3029fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
3030357b40a1SHerbert Xu 		if ((copy = end - offset) > 0) {
3031357b40a1SHerbert Xu 			if (copy > len)
3032357b40a1SHerbert Xu 				copy = len;
3033fbb398a8SDavid S. Miller 			if (skb_store_bits(frag_iter, offset - start,
30341a028e50SDavid S. Miller 					   from, copy))
3035357b40a1SHerbert Xu 				goto fault;
3036357b40a1SHerbert Xu 			if ((len -= copy) == 0)
3037357b40a1SHerbert Xu 				return 0;
3038357b40a1SHerbert Xu 			offset += copy;
3039357b40a1SHerbert Xu 			from += copy;
3040357b40a1SHerbert Xu 		}
30411a028e50SDavid S. Miller 		start = end;
3042357b40a1SHerbert Xu 	}
3043357b40a1SHerbert Xu 	if (!len)
3044357b40a1SHerbert Xu 		return 0;
3045357b40a1SHerbert Xu 
3046357b40a1SHerbert Xu fault:
3047357b40a1SHerbert Xu 	return -EFAULT;
3048357b40a1SHerbert Xu }
3049357b40a1SHerbert Xu EXPORT_SYMBOL(skb_store_bits);
3050357b40a1SHerbert Xu 
30511da177e4SLinus Torvalds /* Checksum skb data. */
30522817a336SDaniel Borkmann __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
30532817a336SDaniel Borkmann 		      __wsum csum, const struct skb_checksum_ops *ops)
30541da177e4SLinus Torvalds {
30551a028e50SDavid S. Miller 	int start = skb_headlen(skb);
30561a028e50SDavid S. Miller 	int i, copy = start - offset;
3057fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
30581da177e4SLinus Torvalds 	int pos = 0;
30591da177e4SLinus Torvalds 
30601da177e4SLinus Torvalds 	/* Checksum header. */
30611da177e4SLinus Torvalds 	if (copy > 0) {
30621da177e4SLinus Torvalds 		if (copy > len)
30631da177e4SLinus Torvalds 			copy = len;
30642544af03SMatteo Croce 		csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
30652544af03SMatteo Croce 				       skb->data + offset, copy, csum);
30661da177e4SLinus Torvalds 		if ((len -= copy) == 0)
30671da177e4SLinus Torvalds 			return csum;
30681da177e4SLinus Torvalds 		offset += copy;
30691da177e4SLinus Torvalds 		pos	= copy;
30701da177e4SLinus Torvalds 	}
30711da177e4SLinus Torvalds 
30721da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
30731a028e50SDavid S. Miller 		int end;
307451c56b00SEric Dumazet 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
30751da177e4SLinus Torvalds 
3076547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
30771a028e50SDavid S. Miller 
307851c56b00SEric Dumazet 		end = start + skb_frag_size(frag);
30791da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
3080c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
3081c613c209SWillem de Bruijn 			struct page *p;
308244bb9363SAl Viro 			__wsum csum2;
30831da177e4SLinus Torvalds 			u8 *vaddr;
30841da177e4SLinus Torvalds 
30851da177e4SLinus Torvalds 			if (copy > len)
30861da177e4SLinus Torvalds 				copy = len;
3087c613c209SWillem de Bruijn 
3088c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
3089b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
3090c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
3091c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
30922544af03SMatteo Croce 				csum2 = INDIRECT_CALL_1(ops->update,
30932544af03SMatteo Croce 							csum_partial_ext,
30942544af03SMatteo Croce 							vaddr + p_off, p_len, 0);
309551c56b00SEric Dumazet 				kunmap_atomic(vaddr);
30962544af03SMatteo Croce 				csum = INDIRECT_CALL_1(ops->combine,
30972544af03SMatteo Croce 						       csum_block_add_ext, csum,
30982544af03SMatteo Croce 						       csum2, pos, p_len);
3099c613c209SWillem de Bruijn 				pos += p_len;
3100c613c209SWillem de Bruijn 			}
3101c613c209SWillem de Bruijn 
31021da177e4SLinus Torvalds 			if (!(len -= copy))
31031da177e4SLinus Torvalds 				return csum;
31041da177e4SLinus Torvalds 			offset += copy;
31051da177e4SLinus Torvalds 		}
31061a028e50SDavid S. Miller 		start = end;
31071da177e4SLinus Torvalds 	}
31081da177e4SLinus Torvalds 
3109fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
31101a028e50SDavid S. Miller 		int end;
31111da177e4SLinus Torvalds 
3112547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
31131a028e50SDavid S. Miller 
3114fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
31151da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
31165f92a738SAl Viro 			__wsum csum2;
31171da177e4SLinus Torvalds 			if (copy > len)
31181da177e4SLinus Torvalds 				copy = len;
31192817a336SDaniel Borkmann 			csum2 = __skb_checksum(frag_iter, offset - start,
31202817a336SDaniel Borkmann 					       copy, 0, ops);
31212544af03SMatteo Croce 			csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
31222544af03SMatteo Croce 					       csum, csum2, pos, copy);
31231da177e4SLinus Torvalds 			if ((len -= copy) == 0)
31241da177e4SLinus Torvalds 				return csum;
31251da177e4SLinus Torvalds 			offset += copy;
31261da177e4SLinus Torvalds 			pos    += copy;
31271da177e4SLinus Torvalds 		}
31281a028e50SDavid S. Miller 		start = end;
31291da177e4SLinus Torvalds 	}
313009a62660SKris Katterjohn 	BUG_ON(len);
31311da177e4SLinus Torvalds 
31321da177e4SLinus Torvalds 	return csum;
31331da177e4SLinus Torvalds }
31342817a336SDaniel Borkmann EXPORT_SYMBOL(__skb_checksum);
31352817a336SDaniel Borkmann 
31362817a336SDaniel Borkmann __wsum skb_checksum(const struct sk_buff *skb, int offset,
31372817a336SDaniel Borkmann 		    int len, __wsum csum)
31382817a336SDaniel Borkmann {
31392817a336SDaniel Borkmann 	const struct skb_checksum_ops ops = {
3140cea80ea8SDaniel Borkmann 		.update  = csum_partial_ext,
31412817a336SDaniel Borkmann 		.combine = csum_block_add_ext,
31422817a336SDaniel Borkmann 	};
31432817a336SDaniel Borkmann 
31442817a336SDaniel Borkmann 	return __skb_checksum(skb, offset, len, csum, &ops);
31452817a336SDaniel Borkmann }
3146b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_checksum);
31471da177e4SLinus Torvalds 
31481da177e4SLinus Torvalds /* Both of above in one bottle. */
31491da177e4SLinus Torvalds 
315081d77662SAl Viro __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
31518d5930dfSAl Viro 				    u8 *to, int len)
31521da177e4SLinus Torvalds {
31531a028e50SDavid S. Miller 	int start = skb_headlen(skb);
31541a028e50SDavid S. Miller 	int i, copy = start - offset;
3155fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
31561da177e4SLinus Torvalds 	int pos = 0;
31578d5930dfSAl Viro 	__wsum csum = 0;
31581da177e4SLinus Torvalds 
31591da177e4SLinus Torvalds 	/* Copy header. */
31601da177e4SLinus Torvalds 	if (copy > 0) {
31611da177e4SLinus Torvalds 		if (copy > len)
31621da177e4SLinus Torvalds 			copy = len;
31631da177e4SLinus Torvalds 		csum = csum_partial_copy_nocheck(skb->data + offset, to,
3164cc44c17bSAl Viro 						 copy);
31651da177e4SLinus Torvalds 		if ((len -= copy) == 0)
31661da177e4SLinus Torvalds 			return csum;
31671da177e4SLinus Torvalds 		offset += copy;
31681da177e4SLinus Torvalds 		to     += copy;
31691da177e4SLinus Torvalds 		pos	= copy;
31701da177e4SLinus Torvalds 	}
31711da177e4SLinus Torvalds 
31721da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
31731a028e50SDavid S. Miller 		int end;
31741da177e4SLinus Torvalds 
3175547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
31761a028e50SDavid S. Miller 
31779e903e08SEric Dumazet 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
31781da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
3179c613c209SWillem de Bruijn 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3180c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
3181c613c209SWillem de Bruijn 			struct page *p;
31825084205fSAl Viro 			__wsum csum2;
31831da177e4SLinus Torvalds 			u8 *vaddr;
31841da177e4SLinus Torvalds 
31851da177e4SLinus Torvalds 			if (copy > len)
31861da177e4SLinus Torvalds 				copy = len;
3187c613c209SWillem de Bruijn 
3188c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
3189b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
3190c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
3191c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
3192c613c209SWillem de Bruijn 				csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3193c613c209SWillem de Bruijn 								  to + copied,
3194cc44c17bSAl Viro 								  p_len);
319551c56b00SEric Dumazet 				kunmap_atomic(vaddr);
31961da177e4SLinus Torvalds 				csum = csum_block_add(csum, csum2, pos);
3197c613c209SWillem de Bruijn 				pos += p_len;
3198c613c209SWillem de Bruijn 			}
3199c613c209SWillem de Bruijn 
32001da177e4SLinus Torvalds 			if (!(len -= copy))
32011da177e4SLinus Torvalds 				return csum;
32021da177e4SLinus Torvalds 			offset += copy;
32031da177e4SLinus Torvalds 			to     += copy;
32041da177e4SLinus Torvalds 		}
32051a028e50SDavid S. Miller 		start = end;
32061da177e4SLinus Torvalds 	}
32071da177e4SLinus Torvalds 
3208fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
320981d77662SAl Viro 		__wsum csum2;
32101a028e50SDavid S. Miller 		int end;
32111da177e4SLinus Torvalds 
3212547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
32131a028e50SDavid S. Miller 
3214fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
32151da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
32161da177e4SLinus Torvalds 			if (copy > len)
32171da177e4SLinus Torvalds 				copy = len;
3218fbb398a8SDavid S. Miller 			csum2 = skb_copy_and_csum_bits(frag_iter,
32191a028e50SDavid S. Miller 						       offset - start,
32208d5930dfSAl Viro 						       to, copy);
32211da177e4SLinus Torvalds 			csum = csum_block_add(csum, csum2, pos);
32221da177e4SLinus Torvalds 			if ((len -= copy) == 0)
32231da177e4SLinus Torvalds 				return csum;
32241da177e4SLinus Torvalds 			offset += copy;
32251da177e4SLinus Torvalds 			to     += copy;
32261da177e4SLinus Torvalds 			pos    += copy;
32271da177e4SLinus Torvalds 		}
32281a028e50SDavid S. Miller 		start = end;
32291da177e4SLinus Torvalds 	}
323009a62660SKris Katterjohn 	BUG_ON(len);
32311da177e4SLinus Torvalds 	return csum;
32321da177e4SLinus Torvalds }
3233b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_and_csum_bits);
32341da177e4SLinus Torvalds 
323549f8e832SCong Wang __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
323649f8e832SCong Wang {
323749f8e832SCong Wang 	__sum16 sum;
323849f8e832SCong Wang 
323949f8e832SCong Wang 	sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
324014641931SCong Wang 	/* See comments in __skb_checksum_complete(). */
324149f8e832SCong Wang 	if (likely(!sum)) {
324249f8e832SCong Wang 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
324349f8e832SCong Wang 		    !skb->csum_complete_sw)
32447fe50ac8SCong Wang 			netdev_rx_csum_fault(skb->dev, skb);
324549f8e832SCong Wang 	}
324649f8e832SCong Wang 	if (!skb_shared(skb))
324749f8e832SCong Wang 		skb->csum_valid = !sum;
324849f8e832SCong Wang 	return sum;
324949f8e832SCong Wang }
325049f8e832SCong Wang EXPORT_SYMBOL(__skb_checksum_complete_head);
325149f8e832SCong Wang 
325214641931SCong Wang /* This function assumes skb->csum already holds pseudo header's checksum,
325314641931SCong Wang  * which has been changed from the hardware checksum, for example, by
325414641931SCong Wang  * __skb_checksum_validate_complete(). And, the original skb->csum must
325514641931SCong Wang  * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
325614641931SCong Wang  *
325714641931SCong Wang  * It returns non-zero if the recomputed checksum is still invalid, otherwise
325814641931SCong Wang  * zero. The new checksum is stored back into skb->csum unless the skb is
325914641931SCong Wang  * shared.
326014641931SCong Wang  */
326149f8e832SCong Wang __sum16 __skb_checksum_complete(struct sk_buff *skb)
326249f8e832SCong Wang {
326349f8e832SCong Wang 	__wsum csum;
326449f8e832SCong Wang 	__sum16 sum;
326549f8e832SCong Wang 
326649f8e832SCong Wang 	csum = skb_checksum(skb, 0, skb->len, 0);
326749f8e832SCong Wang 
326849f8e832SCong Wang 	sum = csum_fold(csum_add(skb->csum, csum));
326914641931SCong Wang 	/* This check is inverted, because we already knew the hardware
327014641931SCong Wang 	 * checksum is invalid before calling this function. So, if the
327114641931SCong Wang 	 * re-computed checksum is valid instead, then we have a mismatch
327214641931SCong Wang 	 * between the original skb->csum and skb_checksum(). This means either
327314641931SCong Wang 	 * the original hardware checksum is incorrect or we screw up skb->csum
327414641931SCong Wang 	 * when moving skb->data around.
327514641931SCong Wang 	 */
327649f8e832SCong Wang 	if (likely(!sum)) {
327749f8e832SCong Wang 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
327849f8e832SCong Wang 		    !skb->csum_complete_sw)
32797fe50ac8SCong Wang 			netdev_rx_csum_fault(skb->dev, skb);
328049f8e832SCong Wang 	}
328149f8e832SCong Wang 
328249f8e832SCong Wang 	if (!skb_shared(skb)) {
328349f8e832SCong Wang 		/* Save full packet checksum */
328449f8e832SCong Wang 		skb->csum = csum;
328549f8e832SCong Wang 		skb->ip_summed = CHECKSUM_COMPLETE;
328649f8e832SCong Wang 		skb->csum_complete_sw = 1;
328749f8e832SCong Wang 		skb->csum_valid = !sum;
328849f8e832SCong Wang 	}
328949f8e832SCong Wang 
329049f8e832SCong Wang 	return sum;
329149f8e832SCong Wang }
329249f8e832SCong Wang EXPORT_SYMBOL(__skb_checksum_complete);
329349f8e832SCong Wang 
32949617813dSDavide Caratti static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
32959617813dSDavide Caratti {
32969617813dSDavide Caratti 	net_warn_ratelimited(
32979617813dSDavide Caratti 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
32989617813dSDavide Caratti 		__func__);
32999617813dSDavide Caratti 	return 0;
33009617813dSDavide Caratti }
33019617813dSDavide Caratti 
33029617813dSDavide Caratti static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
33039617813dSDavide Caratti 				       int offset, int len)
33049617813dSDavide Caratti {
33059617813dSDavide Caratti 	net_warn_ratelimited(
33069617813dSDavide Caratti 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
33079617813dSDavide Caratti 		__func__);
33089617813dSDavide Caratti 	return 0;
33099617813dSDavide Caratti }
33109617813dSDavide Caratti 
33119617813dSDavide Caratti static const struct skb_checksum_ops default_crc32c_ops = {
33129617813dSDavide Caratti 	.update  = warn_crc32c_csum_update,
33139617813dSDavide Caratti 	.combine = warn_crc32c_csum_combine,
33149617813dSDavide Caratti };
33159617813dSDavide Caratti 
33169617813dSDavide Caratti const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
33179617813dSDavide Caratti 	&default_crc32c_ops;
33189617813dSDavide Caratti EXPORT_SYMBOL(crc32c_csum_stub);
33199617813dSDavide Caratti 
3320af2806f8SThomas Graf  /**
3321af2806f8SThomas Graf  *	skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3322af2806f8SThomas Graf  *	@from: source buffer
3323af2806f8SThomas Graf  *
3324af2806f8SThomas Graf  *	Calculates the amount of linear headroom needed in the 'to' skb passed
3325af2806f8SThomas Graf  *	into skb_zerocopy().
3326af2806f8SThomas Graf  */
3327af2806f8SThomas Graf unsigned int
3328af2806f8SThomas Graf skb_zerocopy_headlen(const struct sk_buff *from)
3329af2806f8SThomas Graf {
3330af2806f8SThomas Graf 	unsigned int hlen = 0;
3331af2806f8SThomas Graf 
3332af2806f8SThomas Graf 	if (!from->head_frag ||
3333af2806f8SThomas Graf 	    skb_headlen(from) < L1_CACHE_BYTES ||
3334a17ad096SPravin B Shelar 	    skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3335af2806f8SThomas Graf 		hlen = skb_headlen(from);
3336a17ad096SPravin B Shelar 		if (!hlen)
3337a17ad096SPravin B Shelar 			hlen = from->len;
3338a17ad096SPravin B Shelar 	}
3339af2806f8SThomas Graf 
3340af2806f8SThomas Graf 	if (skb_has_frag_list(from))
3341af2806f8SThomas Graf 		hlen = from->len;
3342af2806f8SThomas Graf 
3343af2806f8SThomas Graf 	return hlen;
3344af2806f8SThomas Graf }
3345af2806f8SThomas Graf EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3346af2806f8SThomas Graf 
3347af2806f8SThomas Graf /**
3348af2806f8SThomas Graf  *	skb_zerocopy - Zero copy skb to skb
3349af2806f8SThomas Graf  *	@to: destination buffer
33507fceb4deSMasanari Iida  *	@from: source buffer
3351af2806f8SThomas Graf  *	@len: number of bytes to copy from source buffer
3352af2806f8SThomas Graf  *	@hlen: size of linear headroom in destination buffer
3353af2806f8SThomas Graf  *
3354af2806f8SThomas Graf  *	Copies up to `len` bytes from `from` to `to` by creating references
3355af2806f8SThomas Graf  *	to the frags in the source buffer.
3356af2806f8SThomas Graf  *
3357af2806f8SThomas Graf  *	The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3358af2806f8SThomas Graf  *	headroom in the `to` buffer.
335936d5fe6aSZoltan Kiss  *
336036d5fe6aSZoltan Kiss  *	Return value:
336136d5fe6aSZoltan Kiss  *	0: everything is OK
336236d5fe6aSZoltan Kiss  *	-ENOMEM: couldn't orphan frags of @from due to lack of memory
336336d5fe6aSZoltan Kiss  *	-EFAULT: skb_copy_bits() found some problem with skb geometry
3364af2806f8SThomas Graf  */
336536d5fe6aSZoltan Kiss int
336636d5fe6aSZoltan Kiss skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3367af2806f8SThomas Graf {
3368af2806f8SThomas Graf 	int i, j = 0;
3369af2806f8SThomas Graf 	int plen = 0; /* length of skb->head fragment */
337036d5fe6aSZoltan Kiss 	int ret;
3371af2806f8SThomas Graf 	struct page *page;
3372af2806f8SThomas Graf 	unsigned int offset;
3373af2806f8SThomas Graf 
3374af2806f8SThomas Graf 	BUG_ON(!from->head_frag && !hlen);
3375af2806f8SThomas Graf 
3376af2806f8SThomas Graf 	/* dont bother with small payloads */
337736d5fe6aSZoltan Kiss 	if (len <= skb_tailroom(to))
337836d5fe6aSZoltan Kiss 		return skb_copy_bits(from, 0, skb_put(to, len), len);
3379af2806f8SThomas Graf 
3380af2806f8SThomas Graf 	if (hlen) {
338136d5fe6aSZoltan Kiss 		ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
338236d5fe6aSZoltan Kiss 		if (unlikely(ret))
338336d5fe6aSZoltan Kiss 			return ret;
3384af2806f8SThomas Graf 		len -= hlen;
3385af2806f8SThomas Graf 	} else {
3386af2806f8SThomas Graf 		plen = min_t(int, skb_headlen(from), len);
3387af2806f8SThomas Graf 		if (plen) {
3388af2806f8SThomas Graf 			page = virt_to_head_page(from->head);
3389af2806f8SThomas Graf 			offset = from->data - (unsigned char *)page_address(page);
3390af2806f8SThomas Graf 			__skb_fill_page_desc(to, 0, page, offset, plen);
3391af2806f8SThomas Graf 			get_page(page);
3392af2806f8SThomas Graf 			j = 1;
3393af2806f8SThomas Graf 			len -= plen;
3394af2806f8SThomas Graf 		}
3395af2806f8SThomas Graf 	}
3396af2806f8SThomas Graf 
3397ede57d58SRichard Gobert 	skb_len_add(to, len + plen);
3398af2806f8SThomas Graf 
339936d5fe6aSZoltan Kiss 	if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
340036d5fe6aSZoltan Kiss 		skb_tx_error(from);
340136d5fe6aSZoltan Kiss 		return -ENOMEM;
340236d5fe6aSZoltan Kiss 	}
34031f8b977aSWillem de Bruijn 	skb_zerocopy_clone(to, from, GFP_ATOMIC);
340436d5fe6aSZoltan Kiss 
3405af2806f8SThomas Graf 	for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3406d8e18a51SMatthew Wilcox (Oracle) 		int size;
3407d8e18a51SMatthew Wilcox (Oracle) 
3408af2806f8SThomas Graf 		if (!len)
3409af2806f8SThomas Graf 			break;
3410af2806f8SThomas Graf 		skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3411d8e18a51SMatthew Wilcox (Oracle) 		size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3412d8e18a51SMatthew Wilcox (Oracle) 					len);
3413d8e18a51SMatthew Wilcox (Oracle) 		skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3414d8e18a51SMatthew Wilcox (Oracle) 		len -= size;
3415af2806f8SThomas Graf 		skb_frag_ref(to, j);
3416af2806f8SThomas Graf 		j++;
3417af2806f8SThomas Graf 	}
3418af2806f8SThomas Graf 	skb_shinfo(to)->nr_frags = j;
341936d5fe6aSZoltan Kiss 
342036d5fe6aSZoltan Kiss 	return 0;
3421af2806f8SThomas Graf }
3422af2806f8SThomas Graf EXPORT_SYMBOL_GPL(skb_zerocopy);
3423af2806f8SThomas Graf 
34241da177e4SLinus Torvalds void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
34251da177e4SLinus Torvalds {
3426d3bc23e7SAl Viro 	__wsum csum;
34271da177e4SLinus Torvalds 	long csstart;
34281da177e4SLinus Torvalds 
342984fa7933SPatrick McHardy 	if (skb->ip_summed == CHECKSUM_PARTIAL)
343055508d60SMichał Mirosław 		csstart = skb_checksum_start_offset(skb);
34311da177e4SLinus Torvalds 	else
34321da177e4SLinus Torvalds 		csstart = skb_headlen(skb);
34331da177e4SLinus Torvalds 
343409a62660SKris Katterjohn 	BUG_ON(csstart > skb_headlen(skb));
34351da177e4SLinus Torvalds 
3436d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data(skb, to, csstart);
34371da177e4SLinus Torvalds 
34381da177e4SLinus Torvalds 	csum = 0;
34391da177e4SLinus Torvalds 	if (csstart != skb->len)
34401da177e4SLinus Torvalds 		csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
34418d5930dfSAl Viro 					      skb->len - csstart);
34421da177e4SLinus Torvalds 
344384fa7933SPatrick McHardy 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
3444ff1dcadbSAl Viro 		long csstuff = csstart + skb->csum_offset;
34451da177e4SLinus Torvalds 
3446d3bc23e7SAl Viro 		*((__sum16 *)(to + csstuff)) = csum_fold(csum);
34471da177e4SLinus Torvalds 	}
34481da177e4SLinus Torvalds }
3449b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_and_csum_dev);
34501da177e4SLinus Torvalds 
34511da177e4SLinus Torvalds /**
34521da177e4SLinus Torvalds  *	skb_dequeue - remove from the head of the queue
34531da177e4SLinus Torvalds  *	@list: list to dequeue from
34541da177e4SLinus Torvalds  *
34551da177e4SLinus Torvalds  *	Remove the head of the list. The list lock is taken so the function
34561da177e4SLinus Torvalds  *	may be used safely with other locking list functions. The head item is
34571da177e4SLinus Torvalds  *	returned or %NULL if the list is empty.
34581da177e4SLinus Torvalds  */
34591da177e4SLinus Torvalds 
34601da177e4SLinus Torvalds struct sk_buff *skb_dequeue(struct sk_buff_head *list)
34611da177e4SLinus Torvalds {
34621da177e4SLinus Torvalds 	unsigned long flags;
34631da177e4SLinus Torvalds 	struct sk_buff *result;
34641da177e4SLinus Torvalds 
34651da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
34661da177e4SLinus Torvalds 	result = __skb_dequeue(list);
34671da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
34681da177e4SLinus Torvalds 	return result;
34691da177e4SLinus Torvalds }
3470b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_dequeue);
34711da177e4SLinus Torvalds 
34721da177e4SLinus Torvalds /**
34731da177e4SLinus Torvalds  *	skb_dequeue_tail - remove from the tail of the queue
34741da177e4SLinus Torvalds  *	@list: list to dequeue from
34751da177e4SLinus Torvalds  *
34761da177e4SLinus Torvalds  *	Remove the tail of the list. The list lock is taken so the function
34771da177e4SLinus Torvalds  *	may be used safely with other locking list functions. The tail item is
34781da177e4SLinus Torvalds  *	returned or %NULL if the list is empty.
34791da177e4SLinus Torvalds  */
34801da177e4SLinus Torvalds struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
34811da177e4SLinus Torvalds {
34821da177e4SLinus Torvalds 	unsigned long flags;
34831da177e4SLinus Torvalds 	struct sk_buff *result;
34841da177e4SLinus Torvalds 
34851da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
34861da177e4SLinus Torvalds 	result = __skb_dequeue_tail(list);
34871da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
34881da177e4SLinus Torvalds 	return result;
34891da177e4SLinus Torvalds }
3490b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_dequeue_tail);
34911da177e4SLinus Torvalds 
34921da177e4SLinus Torvalds /**
34931da177e4SLinus Torvalds  *	skb_queue_purge - empty a list
34941da177e4SLinus Torvalds  *	@list: list to empty
34951da177e4SLinus Torvalds  *
34961da177e4SLinus Torvalds  *	Delete all buffers on an &sk_buff list. Each buffer is removed from
34971da177e4SLinus Torvalds  *	the list and one reference dropped. This function takes the list
34981da177e4SLinus Torvalds  *	lock and is atomic with respect to other list locking functions.
34991da177e4SLinus Torvalds  */
35001da177e4SLinus Torvalds void skb_queue_purge(struct sk_buff_head *list)
35011da177e4SLinus Torvalds {
35021da177e4SLinus Torvalds 	struct sk_buff *skb;
35031da177e4SLinus Torvalds 	while ((skb = skb_dequeue(list)) != NULL)
35041da177e4SLinus Torvalds 		kfree_skb(skb);
35051da177e4SLinus Torvalds }
3506b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_purge);
35071da177e4SLinus Torvalds 
35081da177e4SLinus Torvalds /**
35099f5afeaeSYaogong Wang  *	skb_rbtree_purge - empty a skb rbtree
35109f5afeaeSYaogong Wang  *	@root: root of the rbtree to empty
3511385114deSPeter Oskolkov  *	Return value: the sum of truesizes of all purged skbs.
35129f5afeaeSYaogong Wang  *
35139f5afeaeSYaogong Wang  *	Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
35149f5afeaeSYaogong Wang  *	the list and one reference dropped. This function does not take
35159f5afeaeSYaogong Wang  *	any lock. Synchronization should be handled by the caller (e.g., TCP
35169f5afeaeSYaogong Wang  *	out-of-order queue is protected by the socket lock).
35179f5afeaeSYaogong Wang  */
3518385114deSPeter Oskolkov unsigned int skb_rbtree_purge(struct rb_root *root)
35199f5afeaeSYaogong Wang {
35207c90584cSEric Dumazet 	struct rb_node *p = rb_first(root);
3521385114deSPeter Oskolkov 	unsigned int sum = 0;
35229f5afeaeSYaogong Wang 
35237c90584cSEric Dumazet 	while (p) {
35247c90584cSEric Dumazet 		struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
35257c90584cSEric Dumazet 
35267c90584cSEric Dumazet 		p = rb_next(p);
35277c90584cSEric Dumazet 		rb_erase(&skb->rbnode, root);
3528385114deSPeter Oskolkov 		sum += skb->truesize;
35299f5afeaeSYaogong Wang 		kfree_skb(skb);
35307c90584cSEric Dumazet 	}
3531385114deSPeter Oskolkov 	return sum;
35329f5afeaeSYaogong Wang }
35339f5afeaeSYaogong Wang 
35349f5afeaeSYaogong Wang /**
35351da177e4SLinus Torvalds  *	skb_queue_head - queue a buffer at the list head
35361da177e4SLinus Torvalds  *	@list: list to use
35371da177e4SLinus Torvalds  *	@newsk: buffer to queue
35381da177e4SLinus Torvalds  *
35391da177e4SLinus Torvalds  *	Queue a buffer at the start of the list. This function takes the
35401da177e4SLinus Torvalds  *	list lock and can be used safely with other locking &sk_buff functions
35411da177e4SLinus Torvalds  *	safely.
35421da177e4SLinus Torvalds  *
35431da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
35441da177e4SLinus Torvalds  */
35451da177e4SLinus Torvalds void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
35461da177e4SLinus Torvalds {
35471da177e4SLinus Torvalds 	unsigned long flags;
35481da177e4SLinus Torvalds 
35491da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
35501da177e4SLinus Torvalds 	__skb_queue_head(list, newsk);
35511da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
35521da177e4SLinus Torvalds }
3553b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_head);
35541da177e4SLinus Torvalds 
35551da177e4SLinus Torvalds /**
35561da177e4SLinus Torvalds  *	skb_queue_tail - queue a buffer at the list tail
35571da177e4SLinus Torvalds  *	@list: list to use
35581da177e4SLinus Torvalds  *	@newsk: buffer to queue
35591da177e4SLinus Torvalds  *
35601da177e4SLinus Torvalds  *	Queue a buffer at the tail of the list. This function takes the
35611da177e4SLinus Torvalds  *	list lock and can be used safely with other locking &sk_buff functions
35621da177e4SLinus Torvalds  *	safely.
35631da177e4SLinus Torvalds  *
35641da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
35651da177e4SLinus Torvalds  */
35661da177e4SLinus Torvalds void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
35671da177e4SLinus Torvalds {
35681da177e4SLinus Torvalds 	unsigned long flags;
35691da177e4SLinus Torvalds 
35701da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
35711da177e4SLinus Torvalds 	__skb_queue_tail(list, newsk);
35721da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
35731da177e4SLinus Torvalds }
3574b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_tail);
35758728b834SDavid S. Miller 
35761da177e4SLinus Torvalds /**
35771da177e4SLinus Torvalds  *	skb_unlink	-	remove a buffer from a list
35781da177e4SLinus Torvalds  *	@skb: buffer to remove
35798728b834SDavid S. Miller  *	@list: list to use
35801da177e4SLinus Torvalds  *
35818728b834SDavid S. Miller  *	Remove a packet from a list. The list locks are taken and this
35828728b834SDavid S. Miller  *	function is atomic with respect to other list locked calls
35831da177e4SLinus Torvalds  *
35848728b834SDavid S. Miller  *	You must know what list the SKB is on.
35851da177e4SLinus Torvalds  */
35868728b834SDavid S. Miller void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
35871da177e4SLinus Torvalds {
35881da177e4SLinus Torvalds 	unsigned long flags;
35891da177e4SLinus Torvalds 
35901da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
35918728b834SDavid S. Miller 	__skb_unlink(skb, list);
35921da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
35931da177e4SLinus Torvalds }
3594b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_unlink);
35951da177e4SLinus Torvalds 
35961da177e4SLinus Torvalds /**
35971da177e4SLinus Torvalds  *	skb_append	-	append a buffer
35981da177e4SLinus Torvalds  *	@old: buffer to insert after
35991da177e4SLinus Torvalds  *	@newsk: buffer to insert
36008728b834SDavid S. Miller  *	@list: list to use
36011da177e4SLinus Torvalds  *
36021da177e4SLinus Torvalds  *	Place a packet after a given packet in a list. The list locks are taken
36031da177e4SLinus Torvalds  *	and this function is atomic with respect to other list locked calls.
36041da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
36051da177e4SLinus Torvalds  */
36068728b834SDavid S. Miller void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
36071da177e4SLinus Torvalds {
36081da177e4SLinus Torvalds 	unsigned long flags;
36091da177e4SLinus Torvalds 
36108728b834SDavid S. Miller 	spin_lock_irqsave(&list->lock, flags);
36117de6c033SGerrit Renker 	__skb_queue_after(list, old, newsk);
36128728b834SDavid S. Miller 	spin_unlock_irqrestore(&list->lock, flags);
36131da177e4SLinus Torvalds }
3614b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_append);
36151da177e4SLinus Torvalds 
36161da177e4SLinus Torvalds static inline void skb_split_inside_header(struct sk_buff *skb,
36171da177e4SLinus Torvalds 					   struct sk_buff* skb1,
36181da177e4SLinus Torvalds 					   const u32 len, const int pos)
36191da177e4SLinus Torvalds {
36201da177e4SLinus Torvalds 	int i;
36211da177e4SLinus Torvalds 
3622d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3623d626f62bSArnaldo Carvalho de Melo 					 pos - len);
36241da177e4SLinus Torvalds 	/* And move data appendix as is. */
36251da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
36261da177e4SLinus Torvalds 		skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
36271da177e4SLinus Torvalds 
36281da177e4SLinus Torvalds 	skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
36291da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags  = 0;
36301da177e4SLinus Torvalds 	skb1->data_len		   = skb->data_len;
36311da177e4SLinus Torvalds 	skb1->len		   += skb1->data_len;
36321da177e4SLinus Torvalds 	skb->data_len		   = 0;
36331da177e4SLinus Torvalds 	skb->len		   = len;
363427a884dcSArnaldo Carvalho de Melo 	skb_set_tail_pointer(skb, len);
36351da177e4SLinus Torvalds }
36361da177e4SLinus Torvalds 
36371da177e4SLinus Torvalds static inline void skb_split_no_header(struct sk_buff *skb,
36381da177e4SLinus Torvalds 				       struct sk_buff* skb1,
36391da177e4SLinus Torvalds 				       const u32 len, int pos)
36401da177e4SLinus Torvalds {
36411da177e4SLinus Torvalds 	int i, k = 0;
36421da177e4SLinus Torvalds 	const int nfrags = skb_shinfo(skb)->nr_frags;
36431da177e4SLinus Torvalds 
36441da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags = 0;
36451da177e4SLinus Torvalds 	skb1->len		  = skb1->data_len = skb->len - len;
36461da177e4SLinus Torvalds 	skb->len		  = len;
36471da177e4SLinus Torvalds 	skb->data_len		  = len - pos;
36481da177e4SLinus Torvalds 
36491da177e4SLinus Torvalds 	for (i = 0; i < nfrags; i++) {
36509e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
36511da177e4SLinus Torvalds 
36521da177e4SLinus Torvalds 		if (pos + size > len) {
36531da177e4SLinus Torvalds 			skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
36541da177e4SLinus Torvalds 
36551da177e4SLinus Torvalds 			if (pos < len) {
36561da177e4SLinus Torvalds 				/* Split frag.
36571da177e4SLinus Torvalds 				 * We have two variants in this case:
36581da177e4SLinus Torvalds 				 * 1. Move all the frag to the second
36591da177e4SLinus Torvalds 				 *    part, if it is possible. F.e.
36601da177e4SLinus Torvalds 				 *    this approach is mandatory for TUX,
36611da177e4SLinus Torvalds 				 *    where splitting is expensive.
36621da177e4SLinus Torvalds 				 * 2. Split is accurately. We make this.
36631da177e4SLinus Torvalds 				 */
3664ea2ab693SIan Campbell 				skb_frag_ref(skb, i);
3665b54c9d5bSJonathan Lemon 				skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
36669e903e08SEric Dumazet 				skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
36679e903e08SEric Dumazet 				skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
36681da177e4SLinus Torvalds 				skb_shinfo(skb)->nr_frags++;
36691da177e4SLinus Torvalds 			}
36701da177e4SLinus Torvalds 			k++;
36711da177e4SLinus Torvalds 		} else
36721da177e4SLinus Torvalds 			skb_shinfo(skb)->nr_frags++;
36731da177e4SLinus Torvalds 		pos += size;
36741da177e4SLinus Torvalds 	}
36751da177e4SLinus Torvalds 	skb_shinfo(skb1)->nr_frags = k;
36761da177e4SLinus Torvalds }
36771da177e4SLinus Torvalds 
36781da177e4SLinus Torvalds /**
36791da177e4SLinus Torvalds  * skb_split - Split fragmented skb to two parts at length len.
36801da177e4SLinus Torvalds  * @skb: the buffer to split
36811da177e4SLinus Torvalds  * @skb1: the buffer to receive the second part
36821da177e4SLinus Torvalds  * @len: new length for skb
36831da177e4SLinus Torvalds  */
36841da177e4SLinus Torvalds void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
36851da177e4SLinus Torvalds {
36861da177e4SLinus Torvalds 	int pos = skb_headlen(skb);
36879b65b17dSTalal Ahmad 	const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
36881da177e4SLinus Torvalds 
3689753f1ca4SPavel Begunkov 	skb_zcopy_downgrade_managed(skb);
3690753f1ca4SPavel Begunkov 
36919b65b17dSTalal Ahmad 	skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
36921f8b977aSWillem de Bruijn 	skb_zerocopy_clone(skb1, skb, 0);
36931da177e4SLinus Torvalds 	if (len < pos)	/* Split line is inside header. */
36941da177e4SLinus Torvalds 		skb_split_inside_header(skb, skb1, len, pos);
36951da177e4SLinus Torvalds 	else		/* Second chunk has no header, nothing to copy. */
36961da177e4SLinus Torvalds 		skb_split_no_header(skb, skb1, len, pos);
36971da177e4SLinus Torvalds }
3698b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_split);
36991da177e4SLinus Torvalds 
37009f782db3SIlpo Järvinen /* Shifting from/to a cloned skb is a no-go.
37019f782db3SIlpo Järvinen  *
37029f782db3SIlpo Järvinen  * Caller cannot keep skb_shinfo related pointers past calling here!
37039f782db3SIlpo Järvinen  */
3704832d11c5SIlpo Järvinen static int skb_prepare_for_shift(struct sk_buff *skb)
3705832d11c5SIlpo Järvinen {
3706c4777efaSEric Dumazet 	return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3707832d11c5SIlpo Järvinen }
3708832d11c5SIlpo Järvinen 
3709832d11c5SIlpo Järvinen /**
3710832d11c5SIlpo Järvinen  * skb_shift - Shifts paged data partially from skb to another
3711832d11c5SIlpo Järvinen  * @tgt: buffer into which tail data gets added
3712832d11c5SIlpo Järvinen  * @skb: buffer from which the paged data comes from
3713832d11c5SIlpo Järvinen  * @shiftlen: shift up to this many bytes
3714832d11c5SIlpo Järvinen  *
3715832d11c5SIlpo Järvinen  * Attempts to shift up to shiftlen worth of bytes, which may be less than
371620e994a0SFeng King  * the length of the skb, from skb to tgt. Returns number bytes shifted.
3717832d11c5SIlpo Järvinen  * It's up to caller to free skb if everything was shifted.
3718832d11c5SIlpo Järvinen  *
3719832d11c5SIlpo Järvinen  * If @tgt runs out of frags, the whole operation is aborted.
3720832d11c5SIlpo Järvinen  *
3721832d11c5SIlpo Järvinen  * Skb cannot include anything else but paged data while tgt is allowed
3722832d11c5SIlpo Järvinen  * to have non-paged data as well.
3723832d11c5SIlpo Järvinen  *
3724832d11c5SIlpo Järvinen  * TODO: full sized shift could be optimized but that would need
3725832d11c5SIlpo Järvinen  * specialized skb free'er to handle frags without up-to-date nr_frags.
3726832d11c5SIlpo Järvinen  */
3727832d11c5SIlpo Järvinen int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3728832d11c5SIlpo Järvinen {
3729832d11c5SIlpo Järvinen 	int from, to, merge, todo;
3730d8e18a51SMatthew Wilcox (Oracle) 	skb_frag_t *fragfrom, *fragto;
3731832d11c5SIlpo Järvinen 
3732832d11c5SIlpo Järvinen 	BUG_ON(shiftlen > skb->len);
3733f8071cdeSEric Dumazet 
3734f8071cdeSEric Dumazet 	if (skb_headlen(skb))
3735f8071cdeSEric Dumazet 		return 0;
37361f8b977aSWillem de Bruijn 	if (skb_zcopy(tgt) || skb_zcopy(skb))
37371f8b977aSWillem de Bruijn 		return 0;
3738832d11c5SIlpo Järvinen 
3739832d11c5SIlpo Järvinen 	todo = shiftlen;
3740832d11c5SIlpo Järvinen 	from = 0;
3741832d11c5SIlpo Järvinen 	to = skb_shinfo(tgt)->nr_frags;
3742832d11c5SIlpo Järvinen 	fragfrom = &skb_shinfo(skb)->frags[from];
3743832d11c5SIlpo Järvinen 
3744832d11c5SIlpo Järvinen 	/* Actual merge is delayed until the point when we know we can
3745832d11c5SIlpo Järvinen 	 * commit all, so that we don't have to undo partial changes
3746832d11c5SIlpo Järvinen 	 */
3747832d11c5SIlpo Järvinen 	if (!to ||
3748ea2ab693SIan Campbell 	    !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3749b54c9d5bSJonathan Lemon 			      skb_frag_off(fragfrom))) {
3750832d11c5SIlpo Järvinen 		merge = -1;
3751832d11c5SIlpo Järvinen 	} else {
3752832d11c5SIlpo Järvinen 		merge = to - 1;
3753832d11c5SIlpo Järvinen 
37549e903e08SEric Dumazet 		todo -= skb_frag_size(fragfrom);
3755832d11c5SIlpo Järvinen 		if (todo < 0) {
3756832d11c5SIlpo Järvinen 			if (skb_prepare_for_shift(skb) ||
3757832d11c5SIlpo Järvinen 			    skb_prepare_for_shift(tgt))
3758832d11c5SIlpo Järvinen 				return 0;
3759832d11c5SIlpo Järvinen 
37609f782db3SIlpo Järvinen 			/* All previous frag pointers might be stale! */
37619f782db3SIlpo Järvinen 			fragfrom = &skb_shinfo(skb)->frags[from];
3762832d11c5SIlpo Järvinen 			fragto = &skb_shinfo(tgt)->frags[merge];
3763832d11c5SIlpo Järvinen 
37649e903e08SEric Dumazet 			skb_frag_size_add(fragto, shiftlen);
37659e903e08SEric Dumazet 			skb_frag_size_sub(fragfrom, shiftlen);
3766b54c9d5bSJonathan Lemon 			skb_frag_off_add(fragfrom, shiftlen);
3767832d11c5SIlpo Järvinen 
3768832d11c5SIlpo Järvinen 			goto onlymerged;
3769832d11c5SIlpo Järvinen 		}
3770832d11c5SIlpo Järvinen 
3771832d11c5SIlpo Järvinen 		from++;
3772832d11c5SIlpo Järvinen 	}
3773832d11c5SIlpo Järvinen 
3774832d11c5SIlpo Järvinen 	/* Skip full, not-fitting skb to avoid expensive operations */
3775832d11c5SIlpo Järvinen 	if ((shiftlen == skb->len) &&
3776832d11c5SIlpo Järvinen 	    (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3777832d11c5SIlpo Järvinen 		return 0;
3778832d11c5SIlpo Järvinen 
3779832d11c5SIlpo Järvinen 	if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3780832d11c5SIlpo Järvinen 		return 0;
3781832d11c5SIlpo Järvinen 
3782832d11c5SIlpo Järvinen 	while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3783832d11c5SIlpo Järvinen 		if (to == MAX_SKB_FRAGS)
3784832d11c5SIlpo Järvinen 			return 0;
3785832d11c5SIlpo Järvinen 
3786832d11c5SIlpo Järvinen 		fragfrom = &skb_shinfo(skb)->frags[from];
3787832d11c5SIlpo Järvinen 		fragto = &skb_shinfo(tgt)->frags[to];
3788832d11c5SIlpo Järvinen 
37899e903e08SEric Dumazet 		if (todo >= skb_frag_size(fragfrom)) {
3790832d11c5SIlpo Järvinen 			*fragto = *fragfrom;
37919e903e08SEric Dumazet 			todo -= skb_frag_size(fragfrom);
3792832d11c5SIlpo Järvinen 			from++;
3793832d11c5SIlpo Järvinen 			to++;
3794832d11c5SIlpo Järvinen 
3795832d11c5SIlpo Järvinen 		} else {
3796ea2ab693SIan Campbell 			__skb_frag_ref(fragfrom);
3797b54c9d5bSJonathan Lemon 			skb_frag_page_copy(fragto, fragfrom);
3798b54c9d5bSJonathan Lemon 			skb_frag_off_copy(fragto, fragfrom);
37999e903e08SEric Dumazet 			skb_frag_size_set(fragto, todo);
3800832d11c5SIlpo Järvinen 
3801b54c9d5bSJonathan Lemon 			skb_frag_off_add(fragfrom, todo);
38029e903e08SEric Dumazet 			skb_frag_size_sub(fragfrom, todo);
3803832d11c5SIlpo Järvinen 			todo = 0;
3804832d11c5SIlpo Järvinen 
3805832d11c5SIlpo Järvinen 			to++;
3806832d11c5SIlpo Järvinen 			break;
3807832d11c5SIlpo Järvinen 		}
3808832d11c5SIlpo Järvinen 	}
3809832d11c5SIlpo Järvinen 
3810832d11c5SIlpo Järvinen 	/* Ready to "commit" this state change to tgt */
3811832d11c5SIlpo Järvinen 	skb_shinfo(tgt)->nr_frags = to;
3812832d11c5SIlpo Järvinen 
3813832d11c5SIlpo Järvinen 	if (merge >= 0) {
3814832d11c5SIlpo Järvinen 		fragfrom = &skb_shinfo(skb)->frags[0];
3815832d11c5SIlpo Järvinen 		fragto = &skb_shinfo(tgt)->frags[merge];
3816832d11c5SIlpo Järvinen 
38179e903e08SEric Dumazet 		skb_frag_size_add(fragto, skb_frag_size(fragfrom));
38186a5bcd84SIlias Apalodimas 		__skb_frag_unref(fragfrom, skb->pp_recycle);
3819832d11c5SIlpo Järvinen 	}
3820832d11c5SIlpo Järvinen 
3821832d11c5SIlpo Järvinen 	/* Reposition in the original skb */
3822832d11c5SIlpo Järvinen 	to = 0;
3823832d11c5SIlpo Järvinen 	while (from < skb_shinfo(skb)->nr_frags)
3824832d11c5SIlpo Järvinen 		skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3825832d11c5SIlpo Järvinen 	skb_shinfo(skb)->nr_frags = to;
3826832d11c5SIlpo Järvinen 
3827832d11c5SIlpo Järvinen 	BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3828832d11c5SIlpo Järvinen 
3829832d11c5SIlpo Järvinen onlymerged:
3830832d11c5SIlpo Järvinen 	/* Most likely the tgt won't ever need its checksum anymore, skb on
3831832d11c5SIlpo Järvinen 	 * the other hand might need it if it needs to be resent
3832832d11c5SIlpo Järvinen 	 */
3833832d11c5SIlpo Järvinen 	tgt->ip_summed = CHECKSUM_PARTIAL;
3834832d11c5SIlpo Järvinen 	skb->ip_summed = CHECKSUM_PARTIAL;
3835832d11c5SIlpo Järvinen 
3836ede57d58SRichard Gobert 	skb_len_add(skb, -shiftlen);
3837ede57d58SRichard Gobert 	skb_len_add(tgt, shiftlen);
3838832d11c5SIlpo Järvinen 
3839832d11c5SIlpo Järvinen 	return shiftlen;
3840832d11c5SIlpo Järvinen }
3841832d11c5SIlpo Järvinen 
3842677e90edSThomas Graf /**
3843677e90edSThomas Graf  * skb_prepare_seq_read - Prepare a sequential read of skb data
3844677e90edSThomas Graf  * @skb: the buffer to read
3845677e90edSThomas Graf  * @from: lower offset of data to be read
3846677e90edSThomas Graf  * @to: upper offset of data to be read
3847677e90edSThomas Graf  * @st: state variable
3848677e90edSThomas Graf  *
3849677e90edSThomas Graf  * Initializes the specified state variable. Must be called before
3850677e90edSThomas Graf  * invoking skb_seq_read() for the first time.
3851677e90edSThomas Graf  */
3852677e90edSThomas Graf void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3853677e90edSThomas Graf 			  unsigned int to, struct skb_seq_state *st)
3854677e90edSThomas Graf {
3855677e90edSThomas Graf 	st->lower_offset = from;
3856677e90edSThomas Graf 	st->upper_offset = to;
3857677e90edSThomas Graf 	st->root_skb = st->cur_skb = skb;
3858677e90edSThomas Graf 	st->frag_idx = st->stepped_offset = 0;
3859677e90edSThomas Graf 	st->frag_data = NULL;
386097550f6fSWillem de Bruijn 	st->frag_off = 0;
3861677e90edSThomas Graf }
3862b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_prepare_seq_read);
3863677e90edSThomas Graf 
3864677e90edSThomas Graf /**
3865677e90edSThomas Graf  * skb_seq_read - Sequentially read skb data
3866677e90edSThomas Graf  * @consumed: number of bytes consumed by the caller so far
3867677e90edSThomas Graf  * @data: destination pointer for data to be returned
3868677e90edSThomas Graf  * @st: state variable
3869677e90edSThomas Graf  *
3870bc32383cSMathias Krause  * Reads a block of skb data at @consumed relative to the
3871677e90edSThomas Graf  * lower offset specified to skb_prepare_seq_read(). Assigns
3872bc32383cSMathias Krause  * the head of the data block to @data and returns the length
3873677e90edSThomas Graf  * of the block or 0 if the end of the skb data or the upper
3874677e90edSThomas Graf  * offset has been reached.
3875677e90edSThomas Graf  *
3876677e90edSThomas Graf  * The caller is not required to consume all of the data
3877bc32383cSMathias Krause  * returned, i.e. @consumed is typically set to the number
3878677e90edSThomas Graf  * of bytes already consumed and the next call to
3879677e90edSThomas Graf  * skb_seq_read() will return the remaining part of the block.
3880677e90edSThomas Graf  *
388125985edcSLucas De Marchi  * Note 1: The size of each block of data returned can be arbitrary,
3882e793c0f7SMasanari Iida  *       this limitation is the cost for zerocopy sequential
3883677e90edSThomas Graf  *       reads of potentially non linear data.
3884677e90edSThomas Graf  *
3885bc2cda1eSRandy Dunlap  * Note 2: Fragment lists within fragments are not implemented
3886677e90edSThomas Graf  *       at the moment, state->root_skb could be replaced with
3887677e90edSThomas Graf  *       a stack for this purpose.
3888677e90edSThomas Graf  */
3889677e90edSThomas Graf unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3890677e90edSThomas Graf 			  struct skb_seq_state *st)
3891677e90edSThomas Graf {
3892677e90edSThomas Graf 	unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3893677e90edSThomas Graf 	skb_frag_t *frag;
3894677e90edSThomas Graf 
3895aeb193eaSWedson Almeida Filho 	if (unlikely(abs_offset >= st->upper_offset)) {
3896aeb193eaSWedson Almeida Filho 		if (st->frag_data) {
3897aeb193eaSWedson Almeida Filho 			kunmap_atomic(st->frag_data);
3898aeb193eaSWedson Almeida Filho 			st->frag_data = NULL;
3899aeb193eaSWedson Almeida Filho 		}
3900677e90edSThomas Graf 		return 0;
3901aeb193eaSWedson Almeida Filho 	}
3902677e90edSThomas Graf 
3903677e90edSThomas Graf next_skb:
390495e3b24cSHerbert Xu 	block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3905677e90edSThomas Graf 
3906995b3379SThomas Chenault 	if (abs_offset < block_limit && !st->frag_data) {
390795e3b24cSHerbert Xu 		*data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3908677e90edSThomas Graf 		return block_limit - abs_offset;
3909677e90edSThomas Graf 	}
3910677e90edSThomas Graf 
3911677e90edSThomas Graf 	if (st->frag_idx == 0 && !st->frag_data)
3912677e90edSThomas Graf 		st->stepped_offset += skb_headlen(st->cur_skb);
3913677e90edSThomas Graf 
3914677e90edSThomas Graf 	while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
391597550f6fSWillem de Bruijn 		unsigned int pg_idx, pg_off, pg_sz;
3916677e90edSThomas Graf 
391797550f6fSWillem de Bruijn 		frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
391897550f6fSWillem de Bruijn 
391997550f6fSWillem de Bruijn 		pg_idx = 0;
392097550f6fSWillem de Bruijn 		pg_off = skb_frag_off(frag);
392197550f6fSWillem de Bruijn 		pg_sz = skb_frag_size(frag);
392297550f6fSWillem de Bruijn 
392397550f6fSWillem de Bruijn 		if (skb_frag_must_loop(skb_frag_page(frag))) {
392497550f6fSWillem de Bruijn 			pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
392597550f6fSWillem de Bruijn 			pg_off = offset_in_page(pg_off + st->frag_off);
392697550f6fSWillem de Bruijn 			pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
392797550f6fSWillem de Bruijn 						    PAGE_SIZE - pg_off);
392897550f6fSWillem de Bruijn 		}
392997550f6fSWillem de Bruijn 
393097550f6fSWillem de Bruijn 		block_limit = pg_sz + st->stepped_offset;
3931677e90edSThomas Graf 		if (abs_offset < block_limit) {
3932677e90edSThomas Graf 			if (!st->frag_data)
393397550f6fSWillem de Bruijn 				st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3934677e90edSThomas Graf 
393597550f6fSWillem de Bruijn 			*data = (u8 *)st->frag_data + pg_off +
3936677e90edSThomas Graf 				(abs_offset - st->stepped_offset);
3937677e90edSThomas Graf 
3938677e90edSThomas Graf 			return block_limit - abs_offset;
3939677e90edSThomas Graf 		}
3940677e90edSThomas Graf 
3941677e90edSThomas Graf 		if (st->frag_data) {
394251c56b00SEric Dumazet 			kunmap_atomic(st->frag_data);
3943677e90edSThomas Graf 			st->frag_data = NULL;
3944677e90edSThomas Graf 		}
3945677e90edSThomas Graf 
394697550f6fSWillem de Bruijn 		st->stepped_offset += pg_sz;
394797550f6fSWillem de Bruijn 		st->frag_off += pg_sz;
394897550f6fSWillem de Bruijn 		if (st->frag_off == skb_frag_size(frag)) {
394997550f6fSWillem de Bruijn 			st->frag_off = 0;
3950677e90edSThomas Graf 			st->frag_idx++;
395197550f6fSWillem de Bruijn 		}
3952677e90edSThomas Graf 	}
3953677e90edSThomas Graf 
39545b5a60daSOlaf Kirch 	if (st->frag_data) {
395551c56b00SEric Dumazet 		kunmap_atomic(st->frag_data);
39565b5a60daSOlaf Kirch 		st->frag_data = NULL;
39575b5a60daSOlaf Kirch 	}
39585b5a60daSOlaf Kirch 
395921dc3301SDavid S. Miller 	if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3960677e90edSThomas Graf 		st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
396195e3b24cSHerbert Xu 		st->frag_idx = 0;
3962677e90edSThomas Graf 		goto next_skb;
396371b3346dSShyam Iyer 	} else if (st->cur_skb->next) {
396471b3346dSShyam Iyer 		st->cur_skb = st->cur_skb->next;
396571b3346dSShyam Iyer 		st->frag_idx = 0;
3966677e90edSThomas Graf 		goto next_skb;
3967677e90edSThomas Graf 	}
3968677e90edSThomas Graf 
3969677e90edSThomas Graf 	return 0;
3970677e90edSThomas Graf }
3971b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_seq_read);
3972677e90edSThomas Graf 
3973677e90edSThomas Graf /**
3974677e90edSThomas Graf  * skb_abort_seq_read - Abort a sequential read of skb data
3975677e90edSThomas Graf  * @st: state variable
3976677e90edSThomas Graf  *
3977677e90edSThomas Graf  * Must be called if skb_seq_read() was not called until it
3978677e90edSThomas Graf  * returned 0.
3979677e90edSThomas Graf  */
3980677e90edSThomas Graf void skb_abort_seq_read(struct skb_seq_state *st)
3981677e90edSThomas Graf {
3982677e90edSThomas Graf 	if (st->frag_data)
398351c56b00SEric Dumazet 		kunmap_atomic(st->frag_data);
3984677e90edSThomas Graf }
3985b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_abort_seq_read);
3986677e90edSThomas Graf 
39873fc7e8a6SThomas Graf #define TS_SKB_CB(state)	((struct skb_seq_state *) &((state)->cb))
39883fc7e8a6SThomas Graf 
39893fc7e8a6SThomas Graf static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
39903fc7e8a6SThomas Graf 					  struct ts_config *conf,
39913fc7e8a6SThomas Graf 					  struct ts_state *state)
39923fc7e8a6SThomas Graf {
39933fc7e8a6SThomas Graf 	return skb_seq_read(offset, text, TS_SKB_CB(state));
39943fc7e8a6SThomas Graf }
39953fc7e8a6SThomas Graf 
39963fc7e8a6SThomas Graf static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
39973fc7e8a6SThomas Graf {
39983fc7e8a6SThomas Graf 	skb_abort_seq_read(TS_SKB_CB(state));
39993fc7e8a6SThomas Graf }
40003fc7e8a6SThomas Graf 
40013fc7e8a6SThomas Graf /**
40023fc7e8a6SThomas Graf  * skb_find_text - Find a text pattern in skb data
40033fc7e8a6SThomas Graf  * @skb: the buffer to look in
40043fc7e8a6SThomas Graf  * @from: search offset
40053fc7e8a6SThomas Graf  * @to: search limit
40063fc7e8a6SThomas Graf  * @config: textsearch configuration
40073fc7e8a6SThomas Graf  *
40083fc7e8a6SThomas Graf  * Finds a pattern in the skb data according to the specified
40093fc7e8a6SThomas Graf  * textsearch configuration. Use textsearch_next() to retrieve
40103fc7e8a6SThomas Graf  * subsequent occurrences of the pattern. Returns the offset
40113fc7e8a6SThomas Graf  * to the first occurrence or UINT_MAX if no match was found.
40123fc7e8a6SThomas Graf  */
40133fc7e8a6SThomas Graf unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4014059a2440SBojan Prtvar 			   unsigned int to, struct ts_config *config)
40153fc7e8a6SThomas Graf {
4016059a2440SBojan Prtvar 	struct ts_state state;
4017f72b948dSPhil Oester 	unsigned int ret;
4018f72b948dSPhil Oester 
4019b228c9b0SWillem de Bruijn 	BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4020b228c9b0SWillem de Bruijn 
40213fc7e8a6SThomas Graf 	config->get_next_block = skb_ts_get_next_block;
40223fc7e8a6SThomas Graf 	config->finish = skb_ts_finish;
40233fc7e8a6SThomas Graf 
4024059a2440SBojan Prtvar 	skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
40253fc7e8a6SThomas Graf 
4026059a2440SBojan Prtvar 	ret = textsearch_find(config, &state);
4027f72b948dSPhil Oester 	return (ret <= to - from ? ret : UINT_MAX);
40283fc7e8a6SThomas Graf }
4029b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_find_text);
40303fc7e8a6SThomas Graf 
4031be12a1feSHannes Frederic Sowa int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4032be12a1feSHannes Frederic Sowa 			 int offset, size_t size)
4033be12a1feSHannes Frederic Sowa {
4034be12a1feSHannes Frederic Sowa 	int i = skb_shinfo(skb)->nr_frags;
4035be12a1feSHannes Frederic Sowa 
4036be12a1feSHannes Frederic Sowa 	if (skb_can_coalesce(skb, i, page, offset)) {
4037be12a1feSHannes Frederic Sowa 		skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4038be12a1feSHannes Frederic Sowa 	} else if (i < MAX_SKB_FRAGS) {
4039753f1ca4SPavel Begunkov 		skb_zcopy_downgrade_managed(skb);
4040be12a1feSHannes Frederic Sowa 		get_page(page);
4041228ebc41SEric Dumazet 		skb_fill_page_desc_noacc(skb, i, page, offset, size);
4042be12a1feSHannes Frederic Sowa 	} else {
4043be12a1feSHannes Frederic Sowa 		return -EMSGSIZE;
4044be12a1feSHannes Frederic Sowa 	}
4045be12a1feSHannes Frederic Sowa 
4046be12a1feSHannes Frederic Sowa 	return 0;
4047be12a1feSHannes Frederic Sowa }
4048be12a1feSHannes Frederic Sowa EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4049be12a1feSHannes Frederic Sowa 
4050cbb042f9SHerbert Xu /**
4051cbb042f9SHerbert Xu  *	skb_pull_rcsum - pull skb and update receive checksum
4052cbb042f9SHerbert Xu  *	@skb: buffer to update
4053cbb042f9SHerbert Xu  *	@len: length of data pulled
4054cbb042f9SHerbert Xu  *
4055cbb042f9SHerbert Xu  *	This function performs an skb_pull on the packet and updates
4056fee54fa5SUrs Thuermann  *	the CHECKSUM_COMPLETE checksum.  It should be used on
405784fa7933SPatrick McHardy  *	receive path processing instead of skb_pull unless you know
405884fa7933SPatrick McHardy  *	that the checksum difference is zero (e.g., a valid IP header)
405984fa7933SPatrick McHardy  *	or you are setting ip_summed to CHECKSUM_NONE.
4060cbb042f9SHerbert Xu  */
4061af72868bSJohannes Berg void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4062cbb042f9SHerbert Xu {
406331b33dfbSPravin B Shelar 	unsigned char *data = skb->data;
406431b33dfbSPravin B Shelar 
4065cbb042f9SHerbert Xu 	BUG_ON(len > skb->len);
406631b33dfbSPravin B Shelar 	__skb_pull(skb, len);
406731b33dfbSPravin B Shelar 	skb_postpull_rcsum(skb, data, len);
406831b33dfbSPravin B Shelar 	return skb->data;
4069cbb042f9SHerbert Xu }
4070f94691acSArnaldo Carvalho de Melo EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4071f94691acSArnaldo Carvalho de Melo 
407213acc94eSYonghong Song static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
407313acc94eSYonghong Song {
407413acc94eSYonghong Song 	skb_frag_t head_frag;
407513acc94eSYonghong Song 	struct page *page;
407613acc94eSYonghong Song 
407713acc94eSYonghong Song 	page = virt_to_head_page(frag_skb->head);
4078d8e18a51SMatthew Wilcox (Oracle) 	__skb_frag_set_page(&head_frag, page);
4079b54c9d5bSJonathan Lemon 	skb_frag_off_set(&head_frag, frag_skb->data -
4080b54c9d5bSJonathan Lemon 			 (unsigned char *)page_address(page));
4081d8e18a51SMatthew Wilcox (Oracle) 	skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
408213acc94eSYonghong Song 	return head_frag;
408313acc94eSYonghong Song }
408413acc94eSYonghong Song 
40853a1296a3SSteffen Klassert struct sk_buff *skb_segment_list(struct sk_buff *skb,
40863a1296a3SSteffen Klassert 				 netdev_features_t features,
40873a1296a3SSteffen Klassert 				 unsigned int offset)
40883a1296a3SSteffen Klassert {
40893a1296a3SSteffen Klassert 	struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
40903a1296a3SSteffen Klassert 	unsigned int tnl_hlen = skb_tnl_header_len(skb);
40913a1296a3SSteffen Klassert 	unsigned int delta_truesize = 0;
40923a1296a3SSteffen Klassert 	unsigned int delta_len = 0;
40933a1296a3SSteffen Klassert 	struct sk_buff *tail = NULL;
409453475c5dSDongseok Yi 	struct sk_buff *nskb, *tmp;
4095cf3ab8d4SLina Wang 	int len_diff, err;
40963a1296a3SSteffen Klassert 
40973a1296a3SSteffen Klassert 	skb_push(skb, -skb_network_offset(skb) + offset);
40983a1296a3SSteffen Klassert 
40993a1296a3SSteffen Klassert 	skb_shinfo(skb)->frag_list = NULL;
41003a1296a3SSteffen Klassert 
41013a1296a3SSteffen Klassert 	do {
41023a1296a3SSteffen Klassert 		nskb = list_skb;
41033a1296a3SSteffen Klassert 		list_skb = list_skb->next;
41043a1296a3SSteffen Klassert 
410553475c5dSDongseok Yi 		err = 0;
4106224102deSlena wang 		delta_truesize += nskb->truesize;
410753475c5dSDongseok Yi 		if (skb_shared(nskb)) {
410853475c5dSDongseok Yi 			tmp = skb_clone(nskb, GFP_ATOMIC);
410953475c5dSDongseok Yi 			if (tmp) {
411053475c5dSDongseok Yi 				consume_skb(nskb);
411153475c5dSDongseok Yi 				nskb = tmp;
411253475c5dSDongseok Yi 				err = skb_unclone(nskb, GFP_ATOMIC);
411353475c5dSDongseok Yi 			} else {
411453475c5dSDongseok Yi 				err = -ENOMEM;
411553475c5dSDongseok Yi 			}
411653475c5dSDongseok Yi 		}
411753475c5dSDongseok Yi 
41183a1296a3SSteffen Klassert 		if (!tail)
41193a1296a3SSteffen Klassert 			skb->next = nskb;
41203a1296a3SSteffen Klassert 		else
41213a1296a3SSteffen Klassert 			tail->next = nskb;
41223a1296a3SSteffen Klassert 
412353475c5dSDongseok Yi 		if (unlikely(err)) {
412453475c5dSDongseok Yi 			nskb->next = list_skb;
412553475c5dSDongseok Yi 			goto err_linearize;
412653475c5dSDongseok Yi 		}
412753475c5dSDongseok Yi 
41283a1296a3SSteffen Klassert 		tail = nskb;
41293a1296a3SSteffen Klassert 
41303a1296a3SSteffen Klassert 		delta_len += nskb->len;
41313a1296a3SSteffen Klassert 
41323a1296a3SSteffen Klassert 		skb_push(nskb, -skb_network_offset(nskb) + offset);
41333a1296a3SSteffen Klassert 
4134cf673ed0SFlorian Westphal 		skb_release_head_state(nskb);
4135cf3ab8d4SLina Wang 		len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
41363a1296a3SSteffen Klassert 		__copy_skb_header(nskb, skb);
41373a1296a3SSteffen Klassert 
41383a1296a3SSteffen Klassert 		skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4139cf3ab8d4SLina Wang 		nskb->transport_header += len_diff;
41403a1296a3SSteffen Klassert 		skb_copy_from_linear_data_offset(skb, -tnl_hlen,
41413a1296a3SSteffen Klassert 						 nskb->data - tnl_hlen,
41423a1296a3SSteffen Klassert 						 offset + tnl_hlen);
41433a1296a3SSteffen Klassert 
41443a1296a3SSteffen Klassert 		if (skb_needs_linearize(nskb, features) &&
41453a1296a3SSteffen Klassert 		    __skb_linearize(nskb))
41463a1296a3SSteffen Klassert 			goto err_linearize;
41473a1296a3SSteffen Klassert 
41483a1296a3SSteffen Klassert 	} while (list_skb);
41493a1296a3SSteffen Klassert 
41503a1296a3SSteffen Klassert 	skb->truesize = skb->truesize - delta_truesize;
41513a1296a3SSteffen Klassert 	skb->data_len = skb->data_len - delta_len;
41523a1296a3SSteffen Klassert 	skb->len = skb->len - delta_len;
41533a1296a3SSteffen Klassert 
41543a1296a3SSteffen Klassert 	skb_gso_reset(skb);
41553a1296a3SSteffen Klassert 
41563a1296a3SSteffen Klassert 	skb->prev = tail;
41573a1296a3SSteffen Klassert 
41583a1296a3SSteffen Klassert 	if (skb_needs_linearize(skb, features) &&
41593a1296a3SSteffen Klassert 	    __skb_linearize(skb))
41603a1296a3SSteffen Klassert 		goto err_linearize;
41613a1296a3SSteffen Klassert 
41623a1296a3SSteffen Klassert 	skb_get(skb);
41633a1296a3SSteffen Klassert 
41643a1296a3SSteffen Klassert 	return skb;
41653a1296a3SSteffen Klassert 
41663a1296a3SSteffen Klassert err_linearize:
41673a1296a3SSteffen Klassert 	kfree_skb_list(skb->next);
41683a1296a3SSteffen Klassert 	skb->next = NULL;
41693a1296a3SSteffen Klassert 	return ERR_PTR(-ENOMEM);
41703a1296a3SSteffen Klassert }
41713a1296a3SSteffen Klassert EXPORT_SYMBOL_GPL(skb_segment_list);
41723a1296a3SSteffen Klassert 
4173f4c50d99SHerbert Xu /**
4174f4c50d99SHerbert Xu  *	skb_segment - Perform protocol segmentation on skb.
4175df5771ffSMichael S. Tsirkin  *	@head_skb: buffer to segment
4176576a30ebSHerbert Xu  *	@features: features for the output path (see dev->features)
4177f4c50d99SHerbert Xu  *
4178f4c50d99SHerbert Xu  *	This function performs segmentation on the given skb.  It returns
41794c821d75SBen Hutchings  *	a pointer to the first in a list of new skbs for the segments.
41804c821d75SBen Hutchings  *	In case of error it returns ERR_PTR(err).
4181f4c50d99SHerbert Xu  */
4182df5771ffSMichael S. Tsirkin struct sk_buff *skb_segment(struct sk_buff *head_skb,
4183df5771ffSMichael S. Tsirkin 			    netdev_features_t features)
4184f4c50d99SHerbert Xu {
4185f4c50d99SHerbert Xu 	struct sk_buff *segs = NULL;
4186f4c50d99SHerbert Xu 	struct sk_buff *tail = NULL;
41871a4cedafSMichael S. Tsirkin 	struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4188df5771ffSMichael S. Tsirkin 	skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4189df5771ffSMichael S. Tsirkin 	unsigned int mss = skb_shinfo(head_skb)->gso_size;
4190df5771ffSMichael S. Tsirkin 	unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
41911fd819ecSMichael S. Tsirkin 	struct sk_buff *frag_skb = head_skb;
4192f4c50d99SHerbert Xu 	unsigned int offset = doffset;
4193df5771ffSMichael S. Tsirkin 	unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4194802ab55aSAlexander Duyck 	unsigned int partial_segs = 0;
4195f4c50d99SHerbert Xu 	unsigned int headroom;
4196802ab55aSAlexander Duyck 	unsigned int len = head_skb->len;
4197ec5f0615SPravin B Shelar 	__be16 proto;
419836c98382SAlexander Duyck 	bool csum, sg;
4199df5771ffSMichael S. Tsirkin 	int nfrags = skb_shinfo(head_skb)->nr_frags;
4200f4c50d99SHerbert Xu 	int err = -ENOMEM;
4201f4c50d99SHerbert Xu 	int i = 0;
4202f4c50d99SHerbert Xu 	int pos;
4203f4c50d99SHerbert Xu 
42049e4b7a99SJiri Benc 	if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
42059e4b7a99SJiri Benc 	    mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
42069e4b7a99SJiri Benc 		struct sk_buff *check_skb;
42079e4b7a99SJiri Benc 
42089e4b7a99SJiri Benc 		for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
42099e4b7a99SJiri Benc 			if (skb_headlen(check_skb) && !check_skb->head_frag) {
42109e4b7a99SJiri Benc 				/* gso_size is untrusted, and we have a frag_list with
42119e4b7a99SJiri Benc 				 * a linear non head_frag item.
42123dcbdb13SShmulik Ladkani 				 *
42139e4b7a99SJiri Benc 				 * If head_skb's headlen does not fit requested gso_size,
42149e4b7a99SJiri Benc 				 * it means that the frag_list members do NOT terminate
42159e4b7a99SJiri Benc 				 * on exact gso_size boundaries. Hence we cannot perform
42169e4b7a99SJiri Benc 				 * skb_frag_t page sharing. Therefore we must fallback to
42179e4b7a99SJiri Benc 				 * copying the frag_list skbs; we do so by disabling SG.
42183dcbdb13SShmulik Ladkani 				 */
42193dcbdb13SShmulik Ladkani 				features &= ~NETIF_F_SG;
42209e4b7a99SJiri Benc 				break;
42219e4b7a99SJiri Benc 			}
42229e4b7a99SJiri Benc 		}
42233dcbdb13SShmulik Ladkani 	}
42243dcbdb13SShmulik Ladkani 
42255882a07cSWei-Chun Chao 	__skb_push(head_skb, doffset);
42262f631133SMiaohe Lin 	proto = skb_network_protocol(head_skb, NULL);
4227ec5f0615SPravin B Shelar 	if (unlikely(!proto))
4228ec5f0615SPravin B Shelar 		return ERR_PTR(-EINVAL);
4229ec5f0615SPravin B Shelar 
423036c98382SAlexander Duyck 	sg = !!(features & NETIF_F_SG);
4231f245d079SAlexander Duyck 	csum = !!can_checksum_protocol(features, proto);
42327e2b10c1STom Herbert 
423307b26c94SSteffen Klassert 	if (sg && csum && (mss != GSO_BY_FRAGS))  {
423407b26c94SSteffen Klassert 		if (!(features & NETIF_F_GSO_PARTIAL)) {
423507b26c94SSteffen Klassert 			struct sk_buff *iter;
423643170c4eSIlan Tayari 			unsigned int frag_len;
423707b26c94SSteffen Klassert 
423807b26c94SSteffen Klassert 			if (!list_skb ||
423907b26c94SSteffen Klassert 			    !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
424007b26c94SSteffen Klassert 				goto normal;
424107b26c94SSteffen Klassert 
424243170c4eSIlan Tayari 			/* If we get here then all the required
424343170c4eSIlan Tayari 			 * GSO features except frag_list are supported.
424443170c4eSIlan Tayari 			 * Try to split the SKB to multiple GSO SKBs
424543170c4eSIlan Tayari 			 * with no frag_list.
424643170c4eSIlan Tayari 			 * Currently we can do that only when the buffers don't
424743170c4eSIlan Tayari 			 * have a linear part and all the buffers except
424843170c4eSIlan Tayari 			 * the last are of the same length.
424907b26c94SSteffen Klassert 			 */
425043170c4eSIlan Tayari 			frag_len = list_skb->len;
425107b26c94SSteffen Klassert 			skb_walk_frags(head_skb, iter) {
425243170c4eSIlan Tayari 				if (frag_len != iter->len && iter->next)
425343170c4eSIlan Tayari 					goto normal;
4254eaffadbbSIlan Tayari 				if (skb_headlen(iter) && !iter->head_frag)
425507b26c94SSteffen Klassert 					goto normal;
425607b26c94SSteffen Klassert 
425707b26c94SSteffen Klassert 				len -= iter->len;
425807b26c94SSteffen Klassert 			}
425943170c4eSIlan Tayari 
426043170c4eSIlan Tayari 			if (len != frag_len)
426143170c4eSIlan Tayari 				goto normal;
426207b26c94SSteffen Klassert 		}
426307b26c94SSteffen Klassert 
4264802ab55aSAlexander Duyck 		/* GSO partial only requires that we trim off any excess that
4265802ab55aSAlexander Duyck 		 * doesn't fit into an MSS sized block, so take care of that
4266802ab55aSAlexander Duyck 		 * now.
4267802ab55aSAlexander Duyck 		 */
4268802ab55aSAlexander Duyck 		partial_segs = len / mss;
4269d7fb5a80SAlexander Duyck 		if (partial_segs > 1)
4270802ab55aSAlexander Duyck 			mss *= partial_segs;
4271d7fb5a80SAlexander Duyck 		else
4272d7fb5a80SAlexander Duyck 			partial_segs = 0;
4273802ab55aSAlexander Duyck 	}
4274802ab55aSAlexander Duyck 
427507b26c94SSteffen Klassert normal:
4276df5771ffSMichael S. Tsirkin 	headroom = skb_headroom(head_skb);
4277df5771ffSMichael S. Tsirkin 	pos = skb_headlen(head_skb);
4278f4c50d99SHerbert Xu 
4279f4c50d99SHerbert Xu 	do {
4280f4c50d99SHerbert Xu 		struct sk_buff *nskb;
42818cb19905SMichael S. Tsirkin 		skb_frag_t *nskb_frag;
4282c8884eddSHerbert Xu 		int hsize;
4283f4c50d99SHerbert Xu 		int size;
4284f4c50d99SHerbert Xu 
42853953c46cSMarcelo Ricardo Leitner 		if (unlikely(mss == GSO_BY_FRAGS)) {
42863953c46cSMarcelo Ricardo Leitner 			len = list_skb->len;
42873953c46cSMarcelo Ricardo Leitner 		} else {
4288df5771ffSMichael S. Tsirkin 			len = head_skb->len - offset;
4289f4c50d99SHerbert Xu 			if (len > mss)
4290f4c50d99SHerbert Xu 				len = mss;
42913953c46cSMarcelo Ricardo Leitner 		}
4292f4c50d99SHerbert Xu 
4293df5771ffSMichael S. Tsirkin 		hsize = skb_headlen(head_skb) - offset;
4294f4c50d99SHerbert Xu 
4295dbd50f23SXin Long 		if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
42961a4cedafSMichael S. Tsirkin 		    (skb_headlen(list_skb) == len || sg)) {
42971a4cedafSMichael S. Tsirkin 			BUG_ON(skb_headlen(list_skb) > len);
429889319d38SHerbert Xu 
42999d8506ccSHerbert Xu 			i = 0;
43001a4cedafSMichael S. Tsirkin 			nfrags = skb_shinfo(list_skb)->nr_frags;
43011a4cedafSMichael S. Tsirkin 			frag = skb_shinfo(list_skb)->frags;
43021fd819ecSMichael S. Tsirkin 			frag_skb = list_skb;
43031a4cedafSMichael S. Tsirkin 			pos += skb_headlen(list_skb);
43049d8506ccSHerbert Xu 
43059d8506ccSHerbert Xu 			while (pos < offset + len) {
43069d8506ccSHerbert Xu 				BUG_ON(i >= nfrags);
43079d8506ccSHerbert Xu 
43084e1beba1SMichael S. Tsirkin 				size = skb_frag_size(frag);
43099d8506ccSHerbert Xu 				if (pos + size > offset + len)
43109d8506ccSHerbert Xu 					break;
43119d8506ccSHerbert Xu 
43129d8506ccSHerbert Xu 				i++;
43139d8506ccSHerbert Xu 				pos += size;
43144e1beba1SMichael S. Tsirkin 				frag++;
43159d8506ccSHerbert Xu 			}
43169d8506ccSHerbert Xu 
43171a4cedafSMichael S. Tsirkin 			nskb = skb_clone(list_skb, GFP_ATOMIC);
43181a4cedafSMichael S. Tsirkin 			list_skb = list_skb->next;
431989319d38SHerbert Xu 
4320f4c50d99SHerbert Xu 			if (unlikely(!nskb))
4321f4c50d99SHerbert Xu 				goto err;
4322f4c50d99SHerbert Xu 
43239d8506ccSHerbert Xu 			if (unlikely(pskb_trim(nskb, len))) {
43249d8506ccSHerbert Xu 				kfree_skb(nskb);
43259d8506ccSHerbert Xu 				goto err;
43269d8506ccSHerbert Xu 			}
43279d8506ccSHerbert Xu 
4328ec47ea82SAlexander Duyck 			hsize = skb_end_offset(nskb);
432989319d38SHerbert Xu 			if (skb_cow_head(nskb, doffset + headroom)) {
433089319d38SHerbert Xu 				kfree_skb(nskb);
433189319d38SHerbert Xu 				goto err;
433289319d38SHerbert Xu 			}
433389319d38SHerbert Xu 
4334ec47ea82SAlexander Duyck 			nskb->truesize += skb_end_offset(nskb) - hsize;
433589319d38SHerbert Xu 			skb_release_head_state(nskb);
433689319d38SHerbert Xu 			__skb_push(nskb, doffset);
433789319d38SHerbert Xu 		} else {
433800b229f7SPaolo Abeni 			if (hsize < 0)
433900b229f7SPaolo Abeni 				hsize = 0;
4340dbd50f23SXin Long 			if (hsize > len || !sg)
4341dbd50f23SXin Long 				hsize = len;
4342dbd50f23SXin Long 
4343c93bdd0eSMel Gorman 			nskb = __alloc_skb(hsize + doffset + headroom,
4344df5771ffSMichael S. Tsirkin 					   GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4345c93bdd0eSMel Gorman 					   NUMA_NO_NODE);
434689319d38SHerbert Xu 
434789319d38SHerbert Xu 			if (unlikely(!nskb))
434889319d38SHerbert Xu 				goto err;
434989319d38SHerbert Xu 
435089319d38SHerbert Xu 			skb_reserve(nskb, headroom);
435189319d38SHerbert Xu 			__skb_put(nskb, doffset);
435289319d38SHerbert Xu 		}
435389319d38SHerbert Xu 
4354f4c50d99SHerbert Xu 		if (segs)
4355f4c50d99SHerbert Xu 			tail->next = nskb;
4356f4c50d99SHerbert Xu 		else
4357f4c50d99SHerbert Xu 			segs = nskb;
4358f4c50d99SHerbert Xu 		tail = nskb;
4359f4c50d99SHerbert Xu 
4360df5771ffSMichael S. Tsirkin 		__copy_skb_header(nskb, head_skb);
4361f4c50d99SHerbert Xu 
4362030737bcSEric Dumazet 		skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4363fcdfe3a7SVlad Yasevich 		skb_reset_mac_len(nskb);
436468c33163SPravin B Shelar 
4365df5771ffSMichael S. Tsirkin 		skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
436668c33163SPravin B Shelar 						 nskb->data - tnl_hlen,
436768c33163SPravin B Shelar 						 doffset + tnl_hlen);
436889319d38SHerbert Xu 
43699d8506ccSHerbert Xu 		if (nskb->len == len + doffset)
43701cdbcb79SSimon Horman 			goto perform_csum_check;
437189319d38SHerbert Xu 
43727fbeffedSAlexander Duyck 		if (!sg) {
43731454c9faSYadu Kishore 			if (!csum) {
43747fbeffedSAlexander Duyck 				if (!nskb->remcsum_offload)
43756f85a124SHerbert Xu 					nskb->ip_summed = CHECKSUM_NONE;
437676443456SAlexander Duyck 				SKB_GSO_CB(nskb)->csum =
437776443456SAlexander Duyck 					skb_copy_and_csum_bits(head_skb, offset,
43781454c9faSYadu Kishore 							       skb_put(nskb,
43791454c9faSYadu Kishore 								       len),
43808d5930dfSAl Viro 							       len);
43817e2b10c1STom Herbert 				SKB_GSO_CB(nskb)->csum_start =
4382de843723STom Herbert 					skb_headroom(nskb) + doffset;
43831454c9faSYadu Kishore 			} else {
4384c624c58eSlily 				if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4385c624c58eSlily 					goto err;
43861454c9faSYadu Kishore 			}
4387f4c50d99SHerbert Xu 			continue;
4388f4c50d99SHerbert Xu 		}
4389f4c50d99SHerbert Xu 
43908cb19905SMichael S. Tsirkin 		nskb_frag = skb_shinfo(nskb)->frags;
4391f4c50d99SHerbert Xu 
4392df5771ffSMichael S. Tsirkin 		skb_copy_from_linear_data_offset(head_skb, offset,
4393d626f62bSArnaldo Carvalho de Melo 						 skb_put(nskb, hsize), hsize);
4394f4c50d99SHerbert Xu 
439506b4feb3SJonathan Lemon 		skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
439606b4feb3SJonathan Lemon 					   SKBFL_SHARED_FRAG;
4397cef401deSEric Dumazet 
4398bf5c25d6SWillem de Bruijn 		if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4399bf5c25d6SWillem de Bruijn 		    skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4400bf5c25d6SWillem de Bruijn 			goto err;
4401bf5c25d6SWillem de Bruijn 
44029d8506ccSHerbert Xu 		while (pos < offset + len) {
44039d8506ccSHerbert Xu 			if (i >= nfrags) {
44049d8506ccSHerbert Xu 				i = 0;
44051a4cedafSMichael S. Tsirkin 				nfrags = skb_shinfo(list_skb)->nr_frags;
44061a4cedafSMichael S. Tsirkin 				frag = skb_shinfo(list_skb)->frags;
44071fd819ecSMichael S. Tsirkin 				frag_skb = list_skb;
440813acc94eSYonghong Song 				if (!skb_headlen(list_skb)) {
44099d8506ccSHerbert Xu 					BUG_ON(!nfrags);
441013acc94eSYonghong Song 				} else {
441113acc94eSYonghong Song 					BUG_ON(!list_skb->head_frag);
44129d8506ccSHerbert Xu 
441313acc94eSYonghong Song 					/* to make room for head_frag. */
441413acc94eSYonghong Song 					i--;
441513acc94eSYonghong Song 					frag--;
441613acc94eSYonghong Song 				}
4417bf5c25d6SWillem de Bruijn 				if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4418bf5c25d6SWillem de Bruijn 				    skb_zerocopy_clone(nskb, frag_skb,
4419bf5c25d6SWillem de Bruijn 						       GFP_ATOMIC))
4420bf5c25d6SWillem de Bruijn 					goto err;
4421bf5c25d6SWillem de Bruijn 
44221a4cedafSMichael S. Tsirkin 				list_skb = list_skb->next;
44239d8506ccSHerbert Xu 			}
44249d8506ccSHerbert Xu 
44259d8506ccSHerbert Xu 			if (unlikely(skb_shinfo(nskb)->nr_frags >=
44269d8506ccSHerbert Xu 				     MAX_SKB_FRAGS)) {
44279d8506ccSHerbert Xu 				net_warn_ratelimited(
44289d8506ccSHerbert Xu 					"skb_segment: too many frags: %u %u\n",
44299d8506ccSHerbert Xu 					pos, mss);
4430ff907a11SEric Dumazet 				err = -EINVAL;
44319d8506ccSHerbert Xu 				goto err;
44329d8506ccSHerbert Xu 			}
44339d8506ccSHerbert Xu 
443413acc94eSYonghong Song 			*nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
44358cb19905SMichael S. Tsirkin 			__skb_frag_ref(nskb_frag);
44368cb19905SMichael S. Tsirkin 			size = skb_frag_size(nskb_frag);
4437f4c50d99SHerbert Xu 
4438f4c50d99SHerbert Xu 			if (pos < offset) {
4439b54c9d5bSJonathan Lemon 				skb_frag_off_add(nskb_frag, offset - pos);
44408cb19905SMichael S. Tsirkin 				skb_frag_size_sub(nskb_frag, offset - pos);
4441f4c50d99SHerbert Xu 			}
4442f4c50d99SHerbert Xu 
444389319d38SHerbert Xu 			skb_shinfo(nskb)->nr_frags++;
4444f4c50d99SHerbert Xu 
4445f4c50d99SHerbert Xu 			if (pos + size <= offset + len) {
4446f4c50d99SHerbert Xu 				i++;
44474e1beba1SMichael S. Tsirkin 				frag++;
4448f4c50d99SHerbert Xu 				pos += size;
4449f4c50d99SHerbert Xu 			} else {
44508cb19905SMichael S. Tsirkin 				skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
445189319d38SHerbert Xu 				goto skip_fraglist;
4452f4c50d99SHerbert Xu 			}
4453f4c50d99SHerbert Xu 
44548cb19905SMichael S. Tsirkin 			nskb_frag++;
4455f4c50d99SHerbert Xu 		}
4456f4c50d99SHerbert Xu 
445789319d38SHerbert Xu skip_fraglist:
4458f4c50d99SHerbert Xu 		nskb->data_len = len - hsize;
4459f4c50d99SHerbert Xu 		nskb->len += nskb->data_len;
4460f4c50d99SHerbert Xu 		nskb->truesize += nskb->data_len;
4461ec5f0615SPravin B Shelar 
44621cdbcb79SSimon Horman perform_csum_check:
44637fbeffedSAlexander Duyck 		if (!csum) {
4464ff907a11SEric Dumazet 			if (skb_has_shared_frag(nskb) &&
4465ff907a11SEric Dumazet 			    __skb_linearize(nskb))
4466ddff00d4SAlexander Duyck 				goto err;
4467ff907a11SEric Dumazet 
44687fbeffedSAlexander Duyck 			if (!nskb->remcsum_offload)
4469ec5f0615SPravin B Shelar 				nskb->ip_summed = CHECKSUM_NONE;
447076443456SAlexander Duyck 			SKB_GSO_CB(nskb)->csum =
447176443456SAlexander Duyck 				skb_checksum(nskb, doffset,
447276443456SAlexander Duyck 					     nskb->len - doffset, 0);
44737e2b10c1STom Herbert 			SKB_GSO_CB(nskb)->csum_start =
44747e2b10c1STom Herbert 				skb_headroom(nskb) + doffset;
4475ec5f0615SPravin B Shelar 		}
4476df5771ffSMichael S. Tsirkin 	} while ((offset += len) < head_skb->len);
4477f4c50d99SHerbert Xu 
4478bec3cfdcSEric Dumazet 	/* Some callers want to get the end of the list.
4479bec3cfdcSEric Dumazet 	 * Put it in segs->prev to avoid walking the list.
4480bec3cfdcSEric Dumazet 	 * (see validate_xmit_skb_list() for example)
4481bec3cfdcSEric Dumazet 	 */
4482bec3cfdcSEric Dumazet 	segs->prev = tail;
4483432c856fSToshiaki Makita 
4484802ab55aSAlexander Duyck 	if (partial_segs) {
448507b26c94SSteffen Klassert 		struct sk_buff *iter;
4486802ab55aSAlexander Duyck 		int type = skb_shinfo(head_skb)->gso_type;
448707b26c94SSteffen Klassert 		unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4488802ab55aSAlexander Duyck 
4489802ab55aSAlexander Duyck 		/* Update type to add partial and then remove dodgy if set */
449007b26c94SSteffen Klassert 		type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4491802ab55aSAlexander Duyck 		type &= ~SKB_GSO_DODGY;
4492802ab55aSAlexander Duyck 
4493802ab55aSAlexander Duyck 		/* Update GSO info and prepare to start updating headers on
4494802ab55aSAlexander Duyck 		 * our way back down the stack of protocols.
4495802ab55aSAlexander Duyck 		 */
449607b26c94SSteffen Klassert 		for (iter = segs; iter; iter = iter->next) {
449707b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_size = gso_size;
449807b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_segs = partial_segs;
449907b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_type = type;
450007b26c94SSteffen Klassert 			SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
450107b26c94SSteffen Klassert 		}
450207b26c94SSteffen Klassert 
450307b26c94SSteffen Klassert 		if (tail->len - doffset <= gso_size)
450407b26c94SSteffen Klassert 			skb_shinfo(tail)->gso_size = 0;
450507b26c94SSteffen Klassert 		else if (tail != segs)
450607b26c94SSteffen Klassert 			skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4507802ab55aSAlexander Duyck 	}
4508802ab55aSAlexander Duyck 
4509432c856fSToshiaki Makita 	/* Following permits correct backpressure, for protocols
4510432c856fSToshiaki Makita 	 * using skb_set_owner_w().
4511432c856fSToshiaki Makita 	 * Idea is to tranfert ownership from head_skb to last segment.
4512432c856fSToshiaki Makita 	 */
4513432c856fSToshiaki Makita 	if (head_skb->destructor == sock_wfree) {
4514432c856fSToshiaki Makita 		swap(tail->truesize, head_skb->truesize);
4515432c856fSToshiaki Makita 		swap(tail->destructor, head_skb->destructor);
4516432c856fSToshiaki Makita 		swap(tail->sk, head_skb->sk);
4517432c856fSToshiaki Makita 	}
4518f4c50d99SHerbert Xu 	return segs;
4519f4c50d99SHerbert Xu 
4520f4c50d99SHerbert Xu err:
4521289dccbeSEric Dumazet 	kfree_skb_list(segs);
4522f4c50d99SHerbert Xu 	return ERR_PTR(err);
4523f4c50d99SHerbert Xu }
4524f4c50d99SHerbert Xu EXPORT_SYMBOL_GPL(skb_segment);
4525f4c50d99SHerbert Xu 
4526df5042f4SFlorian Westphal #ifdef CONFIG_SKB_EXTENSIONS
4527df5042f4SFlorian Westphal #define SKB_EXT_ALIGN_VALUE	8
4528df5042f4SFlorian Westphal #define SKB_EXT_CHUNKSIZEOF(x)	(ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4529df5042f4SFlorian Westphal 
4530df5042f4SFlorian Westphal static const u8 skb_ext_type_len[] = {
4531df5042f4SFlorian Westphal #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4532df5042f4SFlorian Westphal 	[SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4533df5042f4SFlorian Westphal #endif
45344165079bSFlorian Westphal #ifdef CONFIG_XFRM
45354165079bSFlorian Westphal 	[SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
45364165079bSFlorian Westphal #endif
453795a7233cSPaul Blakey #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
453895a7233cSPaul Blakey 	[TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
453995a7233cSPaul Blakey #endif
45403ee17bc7SMat Martineau #if IS_ENABLED(CONFIG_MPTCP)
45413ee17bc7SMat Martineau 	[SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
45423ee17bc7SMat Martineau #endif
454378476d31SJeremy Kerr #if IS_ENABLED(CONFIG_MCTP_FLOWS)
454478476d31SJeremy Kerr 	[SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
454578476d31SJeremy Kerr #endif
4546df5042f4SFlorian Westphal };
4547df5042f4SFlorian Westphal 
4548df5042f4SFlorian Westphal static __always_inline unsigned int skb_ext_total_length(void)
4549df5042f4SFlorian Westphal {
4550df5042f4SFlorian Westphal 	return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4551df5042f4SFlorian Westphal #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4552df5042f4SFlorian Westphal 		skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4553df5042f4SFlorian Westphal #endif
45544165079bSFlorian Westphal #ifdef CONFIG_XFRM
45554165079bSFlorian Westphal 		skb_ext_type_len[SKB_EXT_SEC_PATH] +
45564165079bSFlorian Westphal #endif
455795a7233cSPaul Blakey #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
455895a7233cSPaul Blakey 		skb_ext_type_len[TC_SKB_EXT] +
455995a7233cSPaul Blakey #endif
45603ee17bc7SMat Martineau #if IS_ENABLED(CONFIG_MPTCP)
45613ee17bc7SMat Martineau 		skb_ext_type_len[SKB_EXT_MPTCP] +
45623ee17bc7SMat Martineau #endif
456378476d31SJeremy Kerr #if IS_ENABLED(CONFIG_MCTP_FLOWS)
456478476d31SJeremy Kerr 		skb_ext_type_len[SKB_EXT_MCTP] +
456578476d31SJeremy Kerr #endif
4566df5042f4SFlorian Westphal 		0;
4567df5042f4SFlorian Westphal }
4568df5042f4SFlorian Westphal 
4569df5042f4SFlorian Westphal static void skb_extensions_init(void)
4570df5042f4SFlorian Westphal {
4571df5042f4SFlorian Westphal 	BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4572df5042f4SFlorian Westphal 	BUILD_BUG_ON(skb_ext_total_length() > 255);
4573df5042f4SFlorian Westphal 
4574df5042f4SFlorian Westphal 	skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4575df5042f4SFlorian Westphal 					     SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4576df5042f4SFlorian Westphal 					     0,
4577df5042f4SFlorian Westphal 					     SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4578df5042f4SFlorian Westphal 					     NULL);
4579df5042f4SFlorian Westphal }
4580df5042f4SFlorian Westphal #else
4581df5042f4SFlorian Westphal static void skb_extensions_init(void) {}
4582df5042f4SFlorian Westphal #endif
4583df5042f4SFlorian Westphal 
45841da177e4SLinus Torvalds void __init skb_init(void)
45851da177e4SLinus Torvalds {
458679a8a642SKees Cook 	skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
45871da177e4SLinus Torvalds 					      sizeof(struct sk_buff),
45881da177e4SLinus Torvalds 					      0,
4589e5d679f3SAlexey Dobriyan 					      SLAB_HWCACHE_ALIGN|SLAB_PANIC,
459079a8a642SKees Cook 					      offsetof(struct sk_buff, cb),
459179a8a642SKees Cook 					      sizeof_field(struct sk_buff, cb),
459220c2df83SPaul Mundt 					      NULL);
4593d179cd12SDavid S. Miller 	skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4594d0bf4a9eSEric Dumazet 						sizeof(struct sk_buff_fclones),
4595d179cd12SDavid S. Miller 						0,
4596e5d679f3SAlexey Dobriyan 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
459720c2df83SPaul Mundt 						NULL);
4598df5042f4SFlorian Westphal 	skb_extensions_init();
45991da177e4SLinus Torvalds }
46001da177e4SLinus Torvalds 
460151c739d1SDavid S. Miller static int
460248a1df65SJason A. Donenfeld __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
460348a1df65SJason A. Donenfeld 	       unsigned int recursion_level)
4604716ea3a7SDavid Howells {
46051a028e50SDavid S. Miller 	int start = skb_headlen(skb);
46061a028e50SDavid S. Miller 	int i, copy = start - offset;
4607fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
4608716ea3a7SDavid Howells 	int elt = 0;
4609716ea3a7SDavid Howells 
461048a1df65SJason A. Donenfeld 	if (unlikely(recursion_level >= 24))
461148a1df65SJason A. Donenfeld 		return -EMSGSIZE;
461248a1df65SJason A. Donenfeld 
4613716ea3a7SDavid Howells 	if (copy > 0) {
4614716ea3a7SDavid Howells 		if (copy > len)
4615716ea3a7SDavid Howells 			copy = len;
4616642f1490SJens Axboe 		sg_set_buf(sg, skb->data + offset, copy);
4617716ea3a7SDavid Howells 		elt++;
4618716ea3a7SDavid Howells 		if ((len -= copy) == 0)
4619716ea3a7SDavid Howells 			return elt;
4620716ea3a7SDavid Howells 		offset += copy;
4621716ea3a7SDavid Howells 	}
4622716ea3a7SDavid Howells 
4623716ea3a7SDavid Howells 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
46241a028e50SDavid S. Miller 		int end;
4625716ea3a7SDavid Howells 
4626547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
46271a028e50SDavid S. Miller 
46289e903e08SEric Dumazet 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4629716ea3a7SDavid Howells 		if ((copy = end - offset) > 0) {
4630716ea3a7SDavid Howells 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
463148a1df65SJason A. Donenfeld 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
463248a1df65SJason A. Donenfeld 				return -EMSGSIZE;
4633716ea3a7SDavid Howells 
4634716ea3a7SDavid Howells 			if (copy > len)
4635716ea3a7SDavid Howells 				copy = len;
4636ea2ab693SIan Campbell 			sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4637b54c9d5bSJonathan Lemon 				    skb_frag_off(frag) + offset - start);
4638716ea3a7SDavid Howells 			elt++;
4639716ea3a7SDavid Howells 			if (!(len -= copy))
4640716ea3a7SDavid Howells 				return elt;
4641716ea3a7SDavid Howells 			offset += copy;
4642716ea3a7SDavid Howells 		}
46431a028e50SDavid S. Miller 		start = end;
4644716ea3a7SDavid Howells 	}
4645716ea3a7SDavid Howells 
4646fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
464748a1df65SJason A. Donenfeld 		int end, ret;
4648716ea3a7SDavid Howells 
4649547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
46501a028e50SDavid S. Miller 
4651fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
4652716ea3a7SDavid Howells 		if ((copy = end - offset) > 0) {
465348a1df65SJason A. Donenfeld 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
465448a1df65SJason A. Donenfeld 				return -EMSGSIZE;
465548a1df65SJason A. Donenfeld 
4656716ea3a7SDavid Howells 			if (copy > len)
4657716ea3a7SDavid Howells 				copy = len;
465848a1df65SJason A. Donenfeld 			ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
465948a1df65SJason A. Donenfeld 					      copy, recursion_level + 1);
466048a1df65SJason A. Donenfeld 			if (unlikely(ret < 0))
466148a1df65SJason A. Donenfeld 				return ret;
466248a1df65SJason A. Donenfeld 			elt += ret;
4663716ea3a7SDavid Howells 			if ((len -= copy) == 0)
4664716ea3a7SDavid Howells 				return elt;
4665716ea3a7SDavid Howells 			offset += copy;
4666716ea3a7SDavid Howells 		}
46671a028e50SDavid S. Miller 		start = end;
4668716ea3a7SDavid Howells 	}
4669716ea3a7SDavid Howells 	BUG_ON(len);
4670716ea3a7SDavid Howells 	return elt;
4671716ea3a7SDavid Howells }
4672716ea3a7SDavid Howells 
467348a1df65SJason A. Donenfeld /**
467448a1df65SJason A. Donenfeld  *	skb_to_sgvec - Fill a scatter-gather list from a socket buffer
467548a1df65SJason A. Donenfeld  *	@skb: Socket buffer containing the buffers to be mapped
467648a1df65SJason A. Donenfeld  *	@sg: The scatter-gather list to map into
467748a1df65SJason A. Donenfeld  *	@offset: The offset into the buffer's contents to start mapping
467848a1df65SJason A. Donenfeld  *	@len: Length of buffer space to be mapped
467948a1df65SJason A. Donenfeld  *
468048a1df65SJason A. Donenfeld  *	Fill the specified scatter-gather list with mappings/pointers into a
468148a1df65SJason A. Donenfeld  *	region of the buffer space attached to a socket buffer. Returns either
468248a1df65SJason A. Donenfeld  *	the number of scatterlist items used, or -EMSGSIZE if the contents
468348a1df65SJason A. Donenfeld  *	could not fit.
468448a1df65SJason A. Donenfeld  */
468548a1df65SJason A. Donenfeld int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
468648a1df65SJason A. Donenfeld {
468748a1df65SJason A. Donenfeld 	int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
468848a1df65SJason A. Donenfeld 
468948a1df65SJason A. Donenfeld 	if (nsg <= 0)
469048a1df65SJason A. Donenfeld 		return nsg;
469148a1df65SJason A. Donenfeld 
469248a1df65SJason A. Donenfeld 	sg_mark_end(&sg[nsg - 1]);
469348a1df65SJason A. Donenfeld 
469448a1df65SJason A. Donenfeld 	return nsg;
469548a1df65SJason A. Donenfeld }
469648a1df65SJason A. Donenfeld EXPORT_SYMBOL_GPL(skb_to_sgvec);
469748a1df65SJason A. Donenfeld 
469825a91d8dSFan Du /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
469925a91d8dSFan Du  * sglist without mark the sg which contain last skb data as the end.
470025a91d8dSFan Du  * So the caller can mannipulate sg list as will when padding new data after
470125a91d8dSFan Du  * the first call without calling sg_unmark_end to expend sg list.
470225a91d8dSFan Du  *
470325a91d8dSFan Du  * Scenario to use skb_to_sgvec_nomark:
470425a91d8dSFan Du  * 1. sg_init_table
470525a91d8dSFan Du  * 2. skb_to_sgvec_nomark(payload1)
470625a91d8dSFan Du  * 3. skb_to_sgvec_nomark(payload2)
470725a91d8dSFan Du  *
470825a91d8dSFan Du  * This is equivalent to:
470925a91d8dSFan Du  * 1. sg_init_table
471025a91d8dSFan Du  * 2. skb_to_sgvec(payload1)
471125a91d8dSFan Du  * 3. sg_unmark_end
471225a91d8dSFan Du  * 4. skb_to_sgvec(payload2)
471325a91d8dSFan Du  *
471425a91d8dSFan Du  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
471525a91d8dSFan Du  * is more preferable.
471625a91d8dSFan Du  */
471725a91d8dSFan Du int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
471825a91d8dSFan Du 			int offset, int len)
471925a91d8dSFan Du {
472048a1df65SJason A. Donenfeld 	return __skb_to_sgvec(skb, sg, offset, len, 0);
472125a91d8dSFan Du }
472225a91d8dSFan Du EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
472325a91d8dSFan Du 
472451c739d1SDavid S. Miller 
472551c739d1SDavid S. Miller 
4726716ea3a7SDavid Howells /**
4727716ea3a7SDavid Howells  *	skb_cow_data - Check that a socket buffer's data buffers are writable
4728716ea3a7SDavid Howells  *	@skb: The socket buffer to check.
4729716ea3a7SDavid Howells  *	@tailbits: Amount of trailing space to be added
4730716ea3a7SDavid Howells  *	@trailer: Returned pointer to the skb where the @tailbits space begins
4731716ea3a7SDavid Howells  *
4732716ea3a7SDavid Howells  *	Make sure that the data buffers attached to a socket buffer are
4733716ea3a7SDavid Howells  *	writable. If they are not, private copies are made of the data buffers
4734716ea3a7SDavid Howells  *	and the socket buffer is set to use these instead.
4735716ea3a7SDavid Howells  *
4736716ea3a7SDavid Howells  *	If @tailbits is given, make sure that there is space to write @tailbits
4737716ea3a7SDavid Howells  *	bytes of data beyond current end of socket buffer.  @trailer will be
4738716ea3a7SDavid Howells  *	set to point to the skb in which this space begins.
4739716ea3a7SDavid Howells  *
4740716ea3a7SDavid Howells  *	The number of scatterlist elements required to completely map the
4741716ea3a7SDavid Howells  *	COW'd and extended socket buffer will be returned.
4742716ea3a7SDavid Howells  */
4743716ea3a7SDavid Howells int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4744716ea3a7SDavid Howells {
4745716ea3a7SDavid Howells 	int copyflag;
4746716ea3a7SDavid Howells 	int elt;
4747716ea3a7SDavid Howells 	struct sk_buff *skb1, **skb_p;
4748716ea3a7SDavid Howells 
4749716ea3a7SDavid Howells 	/* If skb is cloned or its head is paged, reallocate
4750716ea3a7SDavid Howells 	 * head pulling out all the pages (pages are considered not writable
4751716ea3a7SDavid Howells 	 * at the moment even if they are anonymous).
4752716ea3a7SDavid Howells 	 */
4753716ea3a7SDavid Howells 	if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4754c15fc199SMiaohe Lin 	    !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4755716ea3a7SDavid Howells 		return -ENOMEM;
4756716ea3a7SDavid Howells 
4757716ea3a7SDavid Howells 	/* Easy case. Most of packets will go this way. */
475821dc3301SDavid S. Miller 	if (!skb_has_frag_list(skb)) {
4759716ea3a7SDavid Howells 		/* A little of trouble, not enough of space for trailer.
4760716ea3a7SDavid Howells 		 * This should not happen, when stack is tuned to generate
4761716ea3a7SDavid Howells 		 * good frames. OK, on miss we reallocate and reserve even more
4762716ea3a7SDavid Howells 		 * space, 128 bytes is fair. */
4763716ea3a7SDavid Howells 
4764716ea3a7SDavid Howells 		if (skb_tailroom(skb) < tailbits &&
4765716ea3a7SDavid Howells 		    pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4766716ea3a7SDavid Howells 			return -ENOMEM;
4767716ea3a7SDavid Howells 
4768716ea3a7SDavid Howells 		/* Voila! */
4769716ea3a7SDavid Howells 		*trailer = skb;
4770716ea3a7SDavid Howells 		return 1;
4771716ea3a7SDavid Howells 	}
4772716ea3a7SDavid Howells 
4773716ea3a7SDavid Howells 	/* Misery. We are in troubles, going to mincer fragments... */
4774716ea3a7SDavid Howells 
4775716ea3a7SDavid Howells 	elt = 1;
4776716ea3a7SDavid Howells 	skb_p = &skb_shinfo(skb)->frag_list;
4777716ea3a7SDavid Howells 	copyflag = 0;
4778716ea3a7SDavid Howells 
4779716ea3a7SDavid Howells 	while ((skb1 = *skb_p) != NULL) {
4780716ea3a7SDavid Howells 		int ntail = 0;
4781716ea3a7SDavid Howells 
4782716ea3a7SDavid Howells 		/* The fragment is partially pulled by someone,
4783716ea3a7SDavid Howells 		 * this can happen on input. Copy it and everything
4784716ea3a7SDavid Howells 		 * after it. */
4785716ea3a7SDavid Howells 
4786716ea3a7SDavid Howells 		if (skb_shared(skb1))
4787716ea3a7SDavid Howells 			copyflag = 1;
4788716ea3a7SDavid Howells 
4789716ea3a7SDavid Howells 		/* If the skb is the last, worry about trailer. */
4790716ea3a7SDavid Howells 
4791716ea3a7SDavid Howells 		if (skb1->next == NULL && tailbits) {
4792716ea3a7SDavid Howells 			if (skb_shinfo(skb1)->nr_frags ||
479321dc3301SDavid S. Miller 			    skb_has_frag_list(skb1) ||
4794716ea3a7SDavid Howells 			    skb_tailroom(skb1) < tailbits)
4795716ea3a7SDavid Howells 				ntail = tailbits + 128;
4796716ea3a7SDavid Howells 		}
4797716ea3a7SDavid Howells 
4798716ea3a7SDavid Howells 		if (copyflag ||
4799716ea3a7SDavid Howells 		    skb_cloned(skb1) ||
4800716ea3a7SDavid Howells 		    ntail ||
4801716ea3a7SDavid Howells 		    skb_shinfo(skb1)->nr_frags ||
480221dc3301SDavid S. Miller 		    skb_has_frag_list(skb1)) {
4803716ea3a7SDavid Howells 			struct sk_buff *skb2;
4804716ea3a7SDavid Howells 
4805716ea3a7SDavid Howells 			/* Fuck, we are miserable poor guys... */
4806716ea3a7SDavid Howells 			if (ntail == 0)
4807716ea3a7SDavid Howells 				skb2 = skb_copy(skb1, GFP_ATOMIC);
4808716ea3a7SDavid Howells 			else
4809716ea3a7SDavid Howells 				skb2 = skb_copy_expand(skb1,
4810716ea3a7SDavid Howells 						       skb_headroom(skb1),
4811716ea3a7SDavid Howells 						       ntail,
4812716ea3a7SDavid Howells 						       GFP_ATOMIC);
4813716ea3a7SDavid Howells 			if (unlikely(skb2 == NULL))
4814716ea3a7SDavid Howells 				return -ENOMEM;
4815716ea3a7SDavid Howells 
4816716ea3a7SDavid Howells 			if (skb1->sk)
4817716ea3a7SDavid Howells 				skb_set_owner_w(skb2, skb1->sk);
4818716ea3a7SDavid Howells 
4819716ea3a7SDavid Howells 			/* Looking around. Are we still alive?
4820716ea3a7SDavid Howells 			 * OK, link new skb, drop old one */
4821716ea3a7SDavid Howells 
4822716ea3a7SDavid Howells 			skb2->next = skb1->next;
4823716ea3a7SDavid Howells 			*skb_p = skb2;
4824716ea3a7SDavid Howells 			kfree_skb(skb1);
4825716ea3a7SDavid Howells 			skb1 = skb2;
4826716ea3a7SDavid Howells 		}
4827716ea3a7SDavid Howells 		elt++;
4828716ea3a7SDavid Howells 		*trailer = skb1;
4829716ea3a7SDavid Howells 		skb_p = &skb1->next;
4830716ea3a7SDavid Howells 	}
4831716ea3a7SDavid Howells 
4832716ea3a7SDavid Howells 	return elt;
4833716ea3a7SDavid Howells }
4834b4ac530fSDavid S. Miller EXPORT_SYMBOL_GPL(skb_cow_data);
4835716ea3a7SDavid Howells 
4836b1faf566SEric Dumazet static void sock_rmem_free(struct sk_buff *skb)
4837b1faf566SEric Dumazet {
4838b1faf566SEric Dumazet 	struct sock *sk = skb->sk;
4839b1faf566SEric Dumazet 
4840b1faf566SEric Dumazet 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4841b1faf566SEric Dumazet }
4842b1faf566SEric Dumazet 
48438605330aSSoheil Hassas Yeganeh static void skb_set_err_queue(struct sk_buff *skb)
48448605330aSSoheil Hassas Yeganeh {
48458605330aSSoheil Hassas Yeganeh 	/* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
48468605330aSSoheil Hassas Yeganeh 	 * So, it is safe to (mis)use it to mark skbs on the error queue.
48478605330aSSoheil Hassas Yeganeh 	 */
48488605330aSSoheil Hassas Yeganeh 	skb->pkt_type = PACKET_OUTGOING;
48498605330aSSoheil Hassas Yeganeh 	BUILD_BUG_ON(PACKET_OUTGOING == 0);
48508605330aSSoheil Hassas Yeganeh }
48518605330aSSoheil Hassas Yeganeh 
4852b1faf566SEric Dumazet /*
4853b1faf566SEric Dumazet  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4854b1faf566SEric Dumazet  */
4855b1faf566SEric Dumazet int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4856b1faf566SEric Dumazet {
4857b1faf566SEric Dumazet 	if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4858ebb3b78dSEric Dumazet 	    (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4859b1faf566SEric Dumazet 		return -ENOMEM;
4860b1faf566SEric Dumazet 
4861b1faf566SEric Dumazet 	skb_orphan(skb);
4862b1faf566SEric Dumazet 	skb->sk = sk;
4863b1faf566SEric Dumazet 	skb->destructor = sock_rmem_free;
4864b1faf566SEric Dumazet 	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
48658605330aSSoheil Hassas Yeganeh 	skb_set_err_queue(skb);
4866b1faf566SEric Dumazet 
4867abb57ea4SEric Dumazet 	/* before exiting rcu section, make sure dst is refcounted */
4868abb57ea4SEric Dumazet 	skb_dst_force(skb);
4869abb57ea4SEric Dumazet 
4870b1faf566SEric Dumazet 	skb_queue_tail(&sk->sk_error_queue, skb);
4871b1faf566SEric Dumazet 	if (!sock_flag(sk, SOCK_DEAD))
4872e3ae2365SAlexander Aring 		sk_error_report(sk);
4873b1faf566SEric Dumazet 	return 0;
4874b1faf566SEric Dumazet }
4875b1faf566SEric Dumazet EXPORT_SYMBOL(sock_queue_err_skb);
4876b1faf566SEric Dumazet 
487783a1a1a7SSoheil Hassas Yeganeh static bool is_icmp_err_skb(const struct sk_buff *skb)
487883a1a1a7SSoheil Hassas Yeganeh {
487983a1a1a7SSoheil Hassas Yeganeh 	return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
488083a1a1a7SSoheil Hassas Yeganeh 		       SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
488183a1a1a7SSoheil Hassas Yeganeh }
488283a1a1a7SSoheil Hassas Yeganeh 
4883364a9e93SWillem de Bruijn struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4884364a9e93SWillem de Bruijn {
4885364a9e93SWillem de Bruijn 	struct sk_buff_head *q = &sk->sk_error_queue;
488683a1a1a7SSoheil Hassas Yeganeh 	struct sk_buff *skb, *skb_next = NULL;
488783a1a1a7SSoheil Hassas Yeganeh 	bool icmp_next = false;
4888997d5c3fSEric Dumazet 	unsigned long flags;
4889364a9e93SWillem de Bruijn 
4890997d5c3fSEric Dumazet 	spin_lock_irqsave(&q->lock, flags);
4891364a9e93SWillem de Bruijn 	skb = __skb_dequeue(q);
489238b25793SSoheil Hassas Yeganeh 	if (skb && (skb_next = skb_peek(q))) {
489383a1a1a7SSoheil Hassas Yeganeh 		icmp_next = is_icmp_err_skb(skb_next);
489438b25793SSoheil Hassas Yeganeh 		if (icmp_next)
4895985f7337SWillem de Bruijn 			sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
489638b25793SSoheil Hassas Yeganeh 	}
4897997d5c3fSEric Dumazet 	spin_unlock_irqrestore(&q->lock, flags);
4898364a9e93SWillem de Bruijn 
489983a1a1a7SSoheil Hassas Yeganeh 	if (is_icmp_err_skb(skb) && !icmp_next)
490083a1a1a7SSoheil Hassas Yeganeh 		sk->sk_err = 0;
490183a1a1a7SSoheil Hassas Yeganeh 
490283a1a1a7SSoheil Hassas Yeganeh 	if (skb_next)
4903e3ae2365SAlexander Aring 		sk_error_report(sk);
4904364a9e93SWillem de Bruijn 
4905364a9e93SWillem de Bruijn 	return skb;
4906364a9e93SWillem de Bruijn }
4907364a9e93SWillem de Bruijn EXPORT_SYMBOL(sock_dequeue_err_skb);
4908364a9e93SWillem de Bruijn 
4909cab41c47SAlexander Duyck /**
4910cab41c47SAlexander Duyck  * skb_clone_sk - create clone of skb, and take reference to socket
4911cab41c47SAlexander Duyck  * @skb: the skb to clone
4912cab41c47SAlexander Duyck  *
4913cab41c47SAlexander Duyck  * This function creates a clone of a buffer that holds a reference on
4914cab41c47SAlexander Duyck  * sk_refcnt.  Buffers created via this function are meant to be
4915cab41c47SAlexander Duyck  * returned using sock_queue_err_skb, or free via kfree_skb.
4916cab41c47SAlexander Duyck  *
4917cab41c47SAlexander Duyck  * When passing buffers allocated with this function to sock_queue_err_skb
4918cab41c47SAlexander Duyck  * it is necessary to wrap the call with sock_hold/sock_put in order to
4919cab41c47SAlexander Duyck  * prevent the socket from being released prior to being enqueued on
4920cab41c47SAlexander Duyck  * the sk_error_queue.
4921cab41c47SAlexander Duyck  */
492262bccb8cSAlexander Duyck struct sk_buff *skb_clone_sk(struct sk_buff *skb)
492362bccb8cSAlexander Duyck {
492462bccb8cSAlexander Duyck 	struct sock *sk = skb->sk;
492562bccb8cSAlexander Duyck 	struct sk_buff *clone;
492662bccb8cSAlexander Duyck 
492741c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
492862bccb8cSAlexander Duyck 		return NULL;
492962bccb8cSAlexander Duyck 
493062bccb8cSAlexander Duyck 	clone = skb_clone(skb, GFP_ATOMIC);
493162bccb8cSAlexander Duyck 	if (!clone) {
493262bccb8cSAlexander Duyck 		sock_put(sk);
493362bccb8cSAlexander Duyck 		return NULL;
493462bccb8cSAlexander Duyck 	}
493562bccb8cSAlexander Duyck 
493662bccb8cSAlexander Duyck 	clone->sk = sk;
493762bccb8cSAlexander Duyck 	clone->destructor = sock_efree;
493862bccb8cSAlexander Duyck 
493962bccb8cSAlexander Duyck 	return clone;
494062bccb8cSAlexander Duyck }
494162bccb8cSAlexander Duyck EXPORT_SYMBOL(skb_clone_sk);
494262bccb8cSAlexander Duyck 
494337846ef0SAlexander Duyck static void __skb_complete_tx_timestamp(struct sk_buff *skb,
494437846ef0SAlexander Duyck 					struct sock *sk,
49454ef1b286SSoheil Hassas Yeganeh 					int tstype,
49464ef1b286SSoheil Hassas Yeganeh 					bool opt_stats)
4947ac45f602SPatrick Ohly {
4948ac45f602SPatrick Ohly 	struct sock_exterr_skb *serr;
4949ac45f602SPatrick Ohly 	int err;
4950ac45f602SPatrick Ohly 
49514ef1b286SSoheil Hassas Yeganeh 	BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
49524ef1b286SSoheil Hassas Yeganeh 
4953ac45f602SPatrick Ohly 	serr = SKB_EXT_ERR(skb);
4954ac45f602SPatrick Ohly 	memset(serr, 0, sizeof(*serr));
4955ac45f602SPatrick Ohly 	serr->ee.ee_errno = ENOMSG;
4956ac45f602SPatrick Ohly 	serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4957e7fd2885SWillem de Bruijn 	serr->ee.ee_info = tstype;
49584ef1b286SSoheil Hassas Yeganeh 	serr->opt_stats = opt_stats;
49591862d620SWillem de Bruijn 	serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
49604ed2d765SWillem de Bruijn 	if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
496109c2d251SWillem de Bruijn 		serr->ee.ee_data = skb_shinfo(skb)->tskey;
496242f67eeaSEric Dumazet 		if (sk_is_tcp(sk))
4963a1cdec57SEric Dumazet 			serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
49644ed2d765SWillem de Bruijn 	}
496529030374SEric Dumazet 
4966ac45f602SPatrick Ohly 	err = sock_queue_err_skb(sk, skb);
496729030374SEric Dumazet 
4968ac45f602SPatrick Ohly 	if (err)
4969ac45f602SPatrick Ohly 		kfree_skb(skb);
4970ac45f602SPatrick Ohly }
497137846ef0SAlexander Duyck 
4972b245be1fSWillem de Bruijn static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4973b245be1fSWillem de Bruijn {
4974b245be1fSWillem de Bruijn 	bool ret;
4975b245be1fSWillem de Bruijn 
4976d2154b0aSKuniyuki Iwashima 	if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
4977b245be1fSWillem de Bruijn 		return true;
4978b245be1fSWillem de Bruijn 
4979b245be1fSWillem de Bruijn 	read_lock_bh(&sk->sk_callback_lock);
4980b245be1fSWillem de Bruijn 	ret = sk->sk_socket && sk->sk_socket->file &&
4981b245be1fSWillem de Bruijn 	      file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4982b245be1fSWillem de Bruijn 	read_unlock_bh(&sk->sk_callback_lock);
4983b245be1fSWillem de Bruijn 	return ret;
4984b245be1fSWillem de Bruijn }
4985b245be1fSWillem de Bruijn 
498637846ef0SAlexander Duyck void skb_complete_tx_timestamp(struct sk_buff *skb,
498737846ef0SAlexander Duyck 			       struct skb_shared_hwtstamps *hwtstamps)
498837846ef0SAlexander Duyck {
498937846ef0SAlexander Duyck 	struct sock *sk = skb->sk;
499037846ef0SAlexander Duyck 
4991b245be1fSWillem de Bruijn 	if (!skb_may_tx_timestamp(sk, false))
499235b99dffSWillem de Bruijn 		goto err;
4993b245be1fSWillem de Bruijn 
49949ac25fc0SEric Dumazet 	/* Take a reference to prevent skb_orphan() from freeing the socket,
49959ac25fc0SEric Dumazet 	 * but only if the socket refcount is not zero.
49969ac25fc0SEric Dumazet 	 */
499741c6d650SReshetova, Elena 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
499837846ef0SAlexander Duyck 		*skb_hwtstamps(skb) = *hwtstamps;
49994ef1b286SSoheil Hassas Yeganeh 		__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
500037846ef0SAlexander Duyck 		sock_put(sk);
500135b99dffSWillem de Bruijn 		return;
500237846ef0SAlexander Duyck 	}
500335b99dffSWillem de Bruijn 
500435b99dffSWillem de Bruijn err:
500535b99dffSWillem de Bruijn 	kfree_skb(skb);
50069ac25fc0SEric Dumazet }
500737846ef0SAlexander Duyck EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
500837846ef0SAlexander Duyck 
500937846ef0SAlexander Duyck void __skb_tstamp_tx(struct sk_buff *orig_skb,
5010e7ed11eeSYousuk Seung 		     const struct sk_buff *ack_skb,
501137846ef0SAlexander Duyck 		     struct skb_shared_hwtstamps *hwtstamps,
501237846ef0SAlexander Duyck 		     struct sock *sk, int tstype)
501337846ef0SAlexander Duyck {
501437846ef0SAlexander Duyck 	struct sk_buff *skb;
50154ef1b286SSoheil Hassas Yeganeh 	bool tsonly, opt_stats = false;
501637846ef0SAlexander Duyck 
50173a8dd971SWillem de Bruijn 	if (!sk)
50183a8dd971SWillem de Bruijn 		return;
50193a8dd971SWillem de Bruijn 
5020b50a5c70SMiroslav Lichvar 	if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5021b50a5c70SMiroslav Lichvar 	    skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5022b50a5c70SMiroslav Lichvar 		return;
5023b50a5c70SMiroslav Lichvar 
50243a8dd971SWillem de Bruijn 	tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
50253a8dd971SWillem de Bruijn 	if (!skb_may_tx_timestamp(sk, tsonly))
502637846ef0SAlexander Duyck 		return;
502737846ef0SAlexander Duyck 
50281c885808SFrancis Yan 	if (tsonly) {
50291c885808SFrancis Yan #ifdef CONFIG_INET
50301c885808SFrancis Yan 		if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
503142f67eeaSEric Dumazet 		    sk_is_tcp(sk)) {
5032e7ed11eeSYousuk Seung 			skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5033e7ed11eeSYousuk Seung 							     ack_skb);
50344ef1b286SSoheil Hassas Yeganeh 			opt_stats = true;
50354ef1b286SSoheil Hassas Yeganeh 		} else
50361c885808SFrancis Yan #endif
50371c885808SFrancis Yan 			skb = alloc_skb(0, GFP_ATOMIC);
50381c885808SFrancis Yan 	} else {
503937846ef0SAlexander Duyck 		skb = skb_clone(orig_skb, GFP_ATOMIC);
50401c885808SFrancis Yan 	}
504137846ef0SAlexander Duyck 	if (!skb)
504237846ef0SAlexander Duyck 		return;
504337846ef0SAlexander Duyck 
504449ca0d8bSWillem de Bruijn 	if (tsonly) {
5045fff88030SWillem de Bruijn 		skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5046fff88030SWillem de Bruijn 					     SKBTX_ANY_TSTAMP;
504749ca0d8bSWillem de Bruijn 		skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
504849ca0d8bSWillem de Bruijn 	}
504949ca0d8bSWillem de Bruijn 
505049ca0d8bSWillem de Bruijn 	if (hwtstamps)
505149ca0d8bSWillem de Bruijn 		*skb_hwtstamps(skb) = *hwtstamps;
505249ca0d8bSWillem de Bruijn 	else
5053d93376f5SMartin KaFai Lau 		__net_timestamp(skb);
505449ca0d8bSWillem de Bruijn 
50554ef1b286SSoheil Hassas Yeganeh 	__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
505637846ef0SAlexander Duyck }
5057e7fd2885SWillem de Bruijn EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5058e7fd2885SWillem de Bruijn 
5059e7fd2885SWillem de Bruijn void skb_tstamp_tx(struct sk_buff *orig_skb,
5060e7fd2885SWillem de Bruijn 		   struct skb_shared_hwtstamps *hwtstamps)
5061e7fd2885SWillem de Bruijn {
5062e7ed11eeSYousuk Seung 	return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5063e7fd2885SWillem de Bruijn 			       SCM_TSTAMP_SND);
5064e7fd2885SWillem de Bruijn }
5065ac45f602SPatrick Ohly EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5066ac45f602SPatrick Ohly 
50676e3e939fSJohannes Berg void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
50686e3e939fSJohannes Berg {
50696e3e939fSJohannes Berg 	struct sock *sk = skb->sk;
50706e3e939fSJohannes Berg 	struct sock_exterr_skb *serr;
5071dd4f1072SEric Dumazet 	int err = 1;
50726e3e939fSJohannes Berg 
50736e3e939fSJohannes Berg 	skb->wifi_acked_valid = 1;
50746e3e939fSJohannes Berg 	skb->wifi_acked = acked;
50756e3e939fSJohannes Berg 
50766e3e939fSJohannes Berg 	serr = SKB_EXT_ERR(skb);
50776e3e939fSJohannes Berg 	memset(serr, 0, sizeof(*serr));
50786e3e939fSJohannes Berg 	serr->ee.ee_errno = ENOMSG;
50796e3e939fSJohannes Berg 	serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
50806e3e939fSJohannes Berg 
5081dd4f1072SEric Dumazet 	/* Take a reference to prevent skb_orphan() from freeing the socket,
5082dd4f1072SEric Dumazet 	 * but only if the socket refcount is not zero.
5083dd4f1072SEric Dumazet 	 */
508441c6d650SReshetova, Elena 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
50856e3e939fSJohannes Berg 		err = sock_queue_err_skb(sk, skb);
5086dd4f1072SEric Dumazet 		sock_put(sk);
5087dd4f1072SEric Dumazet 	}
50886e3e939fSJohannes Berg 	if (err)
50896e3e939fSJohannes Berg 		kfree_skb(skb);
50906e3e939fSJohannes Berg }
50916e3e939fSJohannes Berg EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
50926e3e939fSJohannes Berg 
5093f35d9d8aSRusty Russell /**
5094f35d9d8aSRusty Russell  * skb_partial_csum_set - set up and verify partial csum values for packet
5095f35d9d8aSRusty Russell  * @skb: the skb to set
5096f35d9d8aSRusty Russell  * @start: the number of bytes after skb->data to start checksumming.
5097f35d9d8aSRusty Russell  * @off: the offset from start to place the checksum.
5098f35d9d8aSRusty Russell  *
5099f35d9d8aSRusty Russell  * For untrusted partially-checksummed packets, we need to make sure the values
5100f35d9d8aSRusty Russell  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5101f35d9d8aSRusty Russell  *
5102f35d9d8aSRusty Russell  * This function checks and sets those values and skb->ip_summed: if this
5103f35d9d8aSRusty Russell  * returns false you should drop the packet.
5104f35d9d8aSRusty Russell  */
5105f35d9d8aSRusty Russell bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5106f35d9d8aSRusty Russell {
510752b5d6f5SEric Dumazet 	u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
510852b5d6f5SEric Dumazet 	u32 csum_start = skb_headroom(skb) + (u32)start;
510952b5d6f5SEric Dumazet 
511052b5d6f5SEric Dumazet 	if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
511152b5d6f5SEric Dumazet 		net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
511252b5d6f5SEric Dumazet 				     start, off, skb_headroom(skb), skb_headlen(skb));
5113f35d9d8aSRusty Russell 		return false;
5114f35d9d8aSRusty Russell 	}
5115f35d9d8aSRusty Russell 	skb->ip_summed = CHECKSUM_PARTIAL;
511652b5d6f5SEric Dumazet 	skb->csum_start = csum_start;
5117f35d9d8aSRusty Russell 	skb->csum_offset = off;
5118e5d5decaSJason Wang 	skb_set_transport_header(skb, start);
5119f35d9d8aSRusty Russell 	return true;
5120f35d9d8aSRusty Russell }
5121b4ac530fSDavid S. Miller EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5122f35d9d8aSRusty Russell 
5123ed1f50c3SPaul Durrant static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5124ed1f50c3SPaul Durrant 			       unsigned int max)
5125ed1f50c3SPaul Durrant {
5126ed1f50c3SPaul Durrant 	if (skb_headlen(skb) >= len)
5127ed1f50c3SPaul Durrant 		return 0;
5128ed1f50c3SPaul Durrant 
5129ed1f50c3SPaul Durrant 	/* If we need to pullup then pullup to the max, so we
5130ed1f50c3SPaul Durrant 	 * won't need to do it again.
5131ed1f50c3SPaul Durrant 	 */
5132ed1f50c3SPaul Durrant 	if (max > skb->len)
5133ed1f50c3SPaul Durrant 		max = skb->len;
5134ed1f50c3SPaul Durrant 
5135ed1f50c3SPaul Durrant 	if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5136ed1f50c3SPaul Durrant 		return -ENOMEM;
5137ed1f50c3SPaul Durrant 
5138ed1f50c3SPaul Durrant 	if (skb_headlen(skb) < len)
5139ed1f50c3SPaul Durrant 		return -EPROTO;
5140ed1f50c3SPaul Durrant 
5141ed1f50c3SPaul Durrant 	return 0;
5142ed1f50c3SPaul Durrant }
5143ed1f50c3SPaul Durrant 
5144f9708b43SJan Beulich #define MAX_TCP_HDR_LEN (15 * 4)
5145f9708b43SJan Beulich 
5146f9708b43SJan Beulich static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5147f9708b43SJan Beulich 				      typeof(IPPROTO_IP) proto,
5148f9708b43SJan Beulich 				      unsigned int off)
5149f9708b43SJan Beulich {
5150f9708b43SJan Beulich 	int err;
5151f9708b43SJan Beulich 
5152161d1792SKees Cook 	switch (proto) {
5153f9708b43SJan Beulich 	case IPPROTO_TCP:
5154f9708b43SJan Beulich 		err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5155f9708b43SJan Beulich 					  off + MAX_TCP_HDR_LEN);
5156f9708b43SJan Beulich 		if (!err && !skb_partial_csum_set(skb, off,
5157f9708b43SJan Beulich 						  offsetof(struct tcphdr,
5158f9708b43SJan Beulich 							   check)))
5159f9708b43SJan Beulich 			err = -EPROTO;
5160f9708b43SJan Beulich 		return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5161f9708b43SJan Beulich 
5162f9708b43SJan Beulich 	case IPPROTO_UDP:
5163f9708b43SJan Beulich 		err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5164f9708b43SJan Beulich 					  off + sizeof(struct udphdr));
5165f9708b43SJan Beulich 		if (!err && !skb_partial_csum_set(skb, off,
5166f9708b43SJan Beulich 						  offsetof(struct udphdr,
5167f9708b43SJan Beulich 							   check)))
5168f9708b43SJan Beulich 			err = -EPROTO;
5169f9708b43SJan Beulich 		return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5170f9708b43SJan Beulich 	}
5171f9708b43SJan Beulich 
5172f9708b43SJan Beulich 	return ERR_PTR(-EPROTO);
5173f9708b43SJan Beulich }
5174f9708b43SJan Beulich 
5175ed1f50c3SPaul Durrant /* This value should be large enough to cover a tagged ethernet header plus
5176ed1f50c3SPaul Durrant  * maximally sized IP and TCP or UDP headers.
5177ed1f50c3SPaul Durrant  */
5178ed1f50c3SPaul Durrant #define MAX_IP_HDR_LEN 128
5179ed1f50c3SPaul Durrant 
5180f9708b43SJan Beulich static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5181ed1f50c3SPaul Durrant {
5182ed1f50c3SPaul Durrant 	unsigned int off;
5183ed1f50c3SPaul Durrant 	bool fragment;
5184f9708b43SJan Beulich 	__sum16 *csum;
5185ed1f50c3SPaul Durrant 	int err;
5186ed1f50c3SPaul Durrant 
5187ed1f50c3SPaul Durrant 	fragment = false;
5188ed1f50c3SPaul Durrant 
5189ed1f50c3SPaul Durrant 	err = skb_maybe_pull_tail(skb,
5190ed1f50c3SPaul Durrant 				  sizeof(struct iphdr),
5191ed1f50c3SPaul Durrant 				  MAX_IP_HDR_LEN);
5192ed1f50c3SPaul Durrant 	if (err < 0)
5193ed1f50c3SPaul Durrant 		goto out;
5194ed1f50c3SPaul Durrant 
519511f920d2SMiaohe Lin 	if (ip_is_fragment(ip_hdr(skb)))
5196ed1f50c3SPaul Durrant 		fragment = true;
5197ed1f50c3SPaul Durrant 
5198ed1f50c3SPaul Durrant 	off = ip_hdrlen(skb);
5199ed1f50c3SPaul Durrant 
5200ed1f50c3SPaul Durrant 	err = -EPROTO;
5201ed1f50c3SPaul Durrant 
5202ed1f50c3SPaul Durrant 	if (fragment)
5203ed1f50c3SPaul Durrant 		goto out;
5204ed1f50c3SPaul Durrant 
5205f9708b43SJan Beulich 	csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5206f9708b43SJan Beulich 	if (IS_ERR(csum))
5207f9708b43SJan Beulich 		return PTR_ERR(csum);
5208ed1f50c3SPaul Durrant 
5209ed1f50c3SPaul Durrant 	if (recalculate)
5210f9708b43SJan Beulich 		*csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5211ed1f50c3SPaul Durrant 					   ip_hdr(skb)->daddr,
5212ed1f50c3SPaul Durrant 					   skb->len - off,
5213f9708b43SJan Beulich 					   ip_hdr(skb)->protocol, 0);
5214ed1f50c3SPaul Durrant 	err = 0;
5215ed1f50c3SPaul Durrant 
5216ed1f50c3SPaul Durrant out:
5217ed1f50c3SPaul Durrant 	return err;
5218ed1f50c3SPaul Durrant }
5219ed1f50c3SPaul Durrant 
5220ed1f50c3SPaul Durrant /* This value should be large enough to cover a tagged ethernet header plus
5221ed1f50c3SPaul Durrant  * an IPv6 header, all options, and a maximal TCP or UDP header.
5222ed1f50c3SPaul Durrant  */
5223ed1f50c3SPaul Durrant #define MAX_IPV6_HDR_LEN 256
5224ed1f50c3SPaul Durrant 
5225ed1f50c3SPaul Durrant #define OPT_HDR(type, skb, off) \
5226ed1f50c3SPaul Durrant 	(type *)(skb_network_header(skb) + (off))
5227ed1f50c3SPaul Durrant 
5228ed1f50c3SPaul Durrant static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5229ed1f50c3SPaul Durrant {
5230ed1f50c3SPaul Durrant 	int err;
5231ed1f50c3SPaul Durrant 	u8 nexthdr;
5232ed1f50c3SPaul Durrant 	unsigned int off;
5233ed1f50c3SPaul Durrant 	unsigned int len;
5234ed1f50c3SPaul Durrant 	bool fragment;
5235ed1f50c3SPaul Durrant 	bool done;
5236f9708b43SJan Beulich 	__sum16 *csum;
5237ed1f50c3SPaul Durrant 
5238ed1f50c3SPaul Durrant 	fragment = false;
5239ed1f50c3SPaul Durrant 	done = false;
5240ed1f50c3SPaul Durrant 
5241ed1f50c3SPaul Durrant 	off = sizeof(struct ipv6hdr);
5242ed1f50c3SPaul Durrant 
5243ed1f50c3SPaul Durrant 	err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5244ed1f50c3SPaul Durrant 	if (err < 0)
5245ed1f50c3SPaul Durrant 		goto out;
5246ed1f50c3SPaul Durrant 
5247ed1f50c3SPaul Durrant 	nexthdr = ipv6_hdr(skb)->nexthdr;
5248ed1f50c3SPaul Durrant 
5249ed1f50c3SPaul Durrant 	len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5250ed1f50c3SPaul Durrant 	while (off <= len && !done) {
5251ed1f50c3SPaul Durrant 		switch (nexthdr) {
5252ed1f50c3SPaul Durrant 		case IPPROTO_DSTOPTS:
5253ed1f50c3SPaul Durrant 		case IPPROTO_HOPOPTS:
5254ed1f50c3SPaul Durrant 		case IPPROTO_ROUTING: {
5255ed1f50c3SPaul Durrant 			struct ipv6_opt_hdr *hp;
5256ed1f50c3SPaul Durrant 
5257ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5258ed1f50c3SPaul Durrant 						  off +
5259ed1f50c3SPaul Durrant 						  sizeof(struct ipv6_opt_hdr),
5260ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5261ed1f50c3SPaul Durrant 			if (err < 0)
5262ed1f50c3SPaul Durrant 				goto out;
5263ed1f50c3SPaul Durrant 
5264ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5265ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5266ed1f50c3SPaul Durrant 			off += ipv6_optlen(hp);
5267ed1f50c3SPaul Durrant 			break;
5268ed1f50c3SPaul Durrant 		}
5269ed1f50c3SPaul Durrant 		case IPPROTO_AH: {
5270ed1f50c3SPaul Durrant 			struct ip_auth_hdr *hp;
5271ed1f50c3SPaul Durrant 
5272ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5273ed1f50c3SPaul Durrant 						  off +
5274ed1f50c3SPaul Durrant 						  sizeof(struct ip_auth_hdr),
5275ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5276ed1f50c3SPaul Durrant 			if (err < 0)
5277ed1f50c3SPaul Durrant 				goto out;
5278ed1f50c3SPaul Durrant 
5279ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5280ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5281ed1f50c3SPaul Durrant 			off += ipv6_authlen(hp);
5282ed1f50c3SPaul Durrant 			break;
5283ed1f50c3SPaul Durrant 		}
5284ed1f50c3SPaul Durrant 		case IPPROTO_FRAGMENT: {
5285ed1f50c3SPaul Durrant 			struct frag_hdr *hp;
5286ed1f50c3SPaul Durrant 
5287ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5288ed1f50c3SPaul Durrant 						  off +
5289ed1f50c3SPaul Durrant 						  sizeof(struct frag_hdr),
5290ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5291ed1f50c3SPaul Durrant 			if (err < 0)
5292ed1f50c3SPaul Durrant 				goto out;
5293ed1f50c3SPaul Durrant 
5294ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct frag_hdr, skb, off);
5295ed1f50c3SPaul Durrant 
5296ed1f50c3SPaul Durrant 			if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5297ed1f50c3SPaul Durrant 				fragment = true;
5298ed1f50c3SPaul Durrant 
5299ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5300ed1f50c3SPaul Durrant 			off += sizeof(struct frag_hdr);
5301ed1f50c3SPaul Durrant 			break;
5302ed1f50c3SPaul Durrant 		}
5303ed1f50c3SPaul Durrant 		default:
5304ed1f50c3SPaul Durrant 			done = true;
5305ed1f50c3SPaul Durrant 			break;
5306ed1f50c3SPaul Durrant 		}
5307ed1f50c3SPaul Durrant 	}
5308ed1f50c3SPaul Durrant 
5309ed1f50c3SPaul Durrant 	err = -EPROTO;
5310ed1f50c3SPaul Durrant 
5311ed1f50c3SPaul Durrant 	if (!done || fragment)
5312ed1f50c3SPaul Durrant 		goto out;
5313ed1f50c3SPaul Durrant 
5314f9708b43SJan Beulich 	csum = skb_checksum_setup_ip(skb, nexthdr, off);
5315f9708b43SJan Beulich 	if (IS_ERR(csum))
5316f9708b43SJan Beulich 		return PTR_ERR(csum);
5317ed1f50c3SPaul Durrant 
5318ed1f50c3SPaul Durrant 	if (recalculate)
5319f9708b43SJan Beulich 		*csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5320ed1f50c3SPaul Durrant 					 &ipv6_hdr(skb)->daddr,
5321f9708b43SJan Beulich 					 skb->len - off, nexthdr, 0);
5322ed1f50c3SPaul Durrant 	err = 0;
5323ed1f50c3SPaul Durrant 
5324ed1f50c3SPaul Durrant out:
5325ed1f50c3SPaul Durrant 	return err;
5326ed1f50c3SPaul Durrant }
5327ed1f50c3SPaul Durrant 
5328ed1f50c3SPaul Durrant /**
5329ed1f50c3SPaul Durrant  * skb_checksum_setup - set up partial checksum offset
5330ed1f50c3SPaul Durrant  * @skb: the skb to set up
5331ed1f50c3SPaul Durrant  * @recalculate: if true the pseudo-header checksum will be recalculated
5332ed1f50c3SPaul Durrant  */
5333ed1f50c3SPaul Durrant int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5334ed1f50c3SPaul Durrant {
5335ed1f50c3SPaul Durrant 	int err;
5336ed1f50c3SPaul Durrant 
5337ed1f50c3SPaul Durrant 	switch (skb->protocol) {
5338ed1f50c3SPaul Durrant 	case htons(ETH_P_IP):
5339f9708b43SJan Beulich 		err = skb_checksum_setup_ipv4(skb, recalculate);
5340ed1f50c3SPaul Durrant 		break;
5341ed1f50c3SPaul Durrant 
5342ed1f50c3SPaul Durrant 	case htons(ETH_P_IPV6):
5343ed1f50c3SPaul Durrant 		err = skb_checksum_setup_ipv6(skb, recalculate);
5344ed1f50c3SPaul Durrant 		break;
5345ed1f50c3SPaul Durrant 
5346ed1f50c3SPaul Durrant 	default:
5347ed1f50c3SPaul Durrant 		err = -EPROTO;
5348ed1f50c3SPaul Durrant 		break;
5349ed1f50c3SPaul Durrant 	}
5350ed1f50c3SPaul Durrant 
5351ed1f50c3SPaul Durrant 	return err;
5352ed1f50c3SPaul Durrant }
5353ed1f50c3SPaul Durrant EXPORT_SYMBOL(skb_checksum_setup);
5354ed1f50c3SPaul Durrant 
53559afd85c9SLinus Lüssing /**
53569afd85c9SLinus Lüssing  * skb_checksum_maybe_trim - maybe trims the given skb
53579afd85c9SLinus Lüssing  * @skb: the skb to check
53589afd85c9SLinus Lüssing  * @transport_len: the data length beyond the network header
53599afd85c9SLinus Lüssing  *
53609afd85c9SLinus Lüssing  * Checks whether the given skb has data beyond the given transport length.
53619afd85c9SLinus Lüssing  * If so, returns a cloned skb trimmed to this transport length.
53629afd85c9SLinus Lüssing  * Otherwise returns the provided skb. Returns NULL in error cases
53639afd85c9SLinus Lüssing  * (e.g. transport_len exceeds skb length or out-of-memory).
53649afd85c9SLinus Lüssing  *
5365a516993fSLinus Lüssing  * Caller needs to set the skb transport header and free any returned skb if it
5366a516993fSLinus Lüssing  * differs from the provided skb.
53679afd85c9SLinus Lüssing  */
53689afd85c9SLinus Lüssing static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
53699afd85c9SLinus Lüssing 					       unsigned int transport_len)
53709afd85c9SLinus Lüssing {
53719afd85c9SLinus Lüssing 	struct sk_buff *skb_chk;
53729afd85c9SLinus Lüssing 	unsigned int len = skb_transport_offset(skb) + transport_len;
53739afd85c9SLinus Lüssing 	int ret;
53749afd85c9SLinus Lüssing 
5375a516993fSLinus Lüssing 	if (skb->len < len)
53769afd85c9SLinus Lüssing 		return NULL;
5377a516993fSLinus Lüssing 	else if (skb->len == len)
53789afd85c9SLinus Lüssing 		return skb;
53799afd85c9SLinus Lüssing 
53809afd85c9SLinus Lüssing 	skb_chk = skb_clone(skb, GFP_ATOMIC);
53819afd85c9SLinus Lüssing 	if (!skb_chk)
53829afd85c9SLinus Lüssing 		return NULL;
53839afd85c9SLinus Lüssing 
53849afd85c9SLinus Lüssing 	ret = pskb_trim_rcsum(skb_chk, len);
53859afd85c9SLinus Lüssing 	if (ret) {
53869afd85c9SLinus Lüssing 		kfree_skb(skb_chk);
53879afd85c9SLinus Lüssing 		return NULL;
53889afd85c9SLinus Lüssing 	}
53899afd85c9SLinus Lüssing 
53909afd85c9SLinus Lüssing 	return skb_chk;
53919afd85c9SLinus Lüssing }
53929afd85c9SLinus Lüssing 
53939afd85c9SLinus Lüssing /**
53949afd85c9SLinus Lüssing  * skb_checksum_trimmed - validate checksum of an skb
53959afd85c9SLinus Lüssing  * @skb: the skb to check
53969afd85c9SLinus Lüssing  * @transport_len: the data length beyond the network header
53979afd85c9SLinus Lüssing  * @skb_chkf: checksum function to use
53989afd85c9SLinus Lüssing  *
53999afd85c9SLinus Lüssing  * Applies the given checksum function skb_chkf to the provided skb.
54009afd85c9SLinus Lüssing  * Returns a checked and maybe trimmed skb. Returns NULL on error.
54019afd85c9SLinus Lüssing  *
54029afd85c9SLinus Lüssing  * If the skb has data beyond the given transport length, then a
54039afd85c9SLinus Lüssing  * trimmed & cloned skb is checked and returned.
54049afd85c9SLinus Lüssing  *
5405a516993fSLinus Lüssing  * Caller needs to set the skb transport header and free any returned skb if it
5406a516993fSLinus Lüssing  * differs from the provided skb.
54079afd85c9SLinus Lüssing  */
54089afd85c9SLinus Lüssing struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
54099afd85c9SLinus Lüssing 				     unsigned int transport_len,
54109afd85c9SLinus Lüssing 				     __sum16(*skb_chkf)(struct sk_buff *skb))
54119afd85c9SLinus Lüssing {
54129afd85c9SLinus Lüssing 	struct sk_buff *skb_chk;
54139afd85c9SLinus Lüssing 	unsigned int offset = skb_transport_offset(skb);
5414fcba67c9SLinus Lüssing 	__sum16 ret;
54159afd85c9SLinus Lüssing 
54169afd85c9SLinus Lüssing 	skb_chk = skb_checksum_maybe_trim(skb, transport_len);
54179afd85c9SLinus Lüssing 	if (!skb_chk)
5418a516993fSLinus Lüssing 		goto err;
54199afd85c9SLinus Lüssing 
5420a516993fSLinus Lüssing 	if (!pskb_may_pull(skb_chk, offset))
5421a516993fSLinus Lüssing 		goto err;
54229afd85c9SLinus Lüssing 
54239b368814SLinus Lüssing 	skb_pull_rcsum(skb_chk, offset);
54249afd85c9SLinus Lüssing 	ret = skb_chkf(skb_chk);
54259b368814SLinus Lüssing 	skb_push_rcsum(skb_chk, offset);
54269afd85c9SLinus Lüssing 
5427a516993fSLinus Lüssing 	if (ret)
5428a516993fSLinus Lüssing 		goto err;
54299afd85c9SLinus Lüssing 
54309afd85c9SLinus Lüssing 	return skb_chk;
5431a516993fSLinus Lüssing 
5432a516993fSLinus Lüssing err:
5433a516993fSLinus Lüssing 	if (skb_chk && skb_chk != skb)
5434a516993fSLinus Lüssing 		kfree_skb(skb_chk);
5435a516993fSLinus Lüssing 
5436a516993fSLinus Lüssing 	return NULL;
5437a516993fSLinus Lüssing 
54389afd85c9SLinus Lüssing }
54399afd85c9SLinus Lüssing EXPORT_SYMBOL(skb_checksum_trimmed);
54409afd85c9SLinus Lüssing 
54414497b076SBen Hutchings void __skb_warn_lro_forwarding(const struct sk_buff *skb)
54424497b076SBen Hutchings {
5443e87cc472SJoe Perches 	net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5444e87cc472SJoe Perches 			     skb->dev->name);
54454497b076SBen Hutchings }
54464497b076SBen Hutchings EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5447bad43ca8SEric Dumazet 
5448bad43ca8SEric Dumazet void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5449bad43ca8SEric Dumazet {
54503d861f66SEric Dumazet 	if (head_stolen) {
54513d861f66SEric Dumazet 		skb_release_head_state(skb);
5452bad43ca8SEric Dumazet 		kmem_cache_free(skbuff_head_cache, skb);
54533d861f66SEric Dumazet 	} else {
5454bad43ca8SEric Dumazet 		__kfree_skb(skb);
5455bad43ca8SEric Dumazet 	}
54563d861f66SEric Dumazet }
5457bad43ca8SEric Dumazet EXPORT_SYMBOL(kfree_skb_partial);
5458bad43ca8SEric Dumazet 
5459bad43ca8SEric Dumazet /**
5460bad43ca8SEric Dumazet  * skb_try_coalesce - try to merge skb to prior one
5461bad43ca8SEric Dumazet  * @to: prior buffer
5462bad43ca8SEric Dumazet  * @from: buffer to add
5463bad43ca8SEric Dumazet  * @fragstolen: pointer to boolean
5464c6c4b97cSRandy Dunlap  * @delta_truesize: how much more was allocated than was requested
5465bad43ca8SEric Dumazet  */
5466bad43ca8SEric Dumazet bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5467bad43ca8SEric Dumazet 		      bool *fragstolen, int *delta_truesize)
5468bad43ca8SEric Dumazet {
5469c818fa9eSEric Dumazet 	struct skb_shared_info *to_shinfo, *from_shinfo;
5470bad43ca8SEric Dumazet 	int i, delta, len = from->len;
5471bad43ca8SEric Dumazet 
5472bad43ca8SEric Dumazet 	*fragstolen = false;
5473bad43ca8SEric Dumazet 
5474bad43ca8SEric Dumazet 	if (skb_cloned(to))
5475bad43ca8SEric Dumazet 		return false;
5476bad43ca8SEric Dumazet 
54771effe8caSJean-Philippe Brucker 	/* In general, avoid mixing slab allocated and page_pool allocated
54781effe8caSJean-Philippe Brucker 	 * pages within the same SKB. However when @to is not pp_recycle and
54791effe8caSJean-Philippe Brucker 	 * @from is cloned, we can transition frag pages from page_pool to
54801effe8caSJean-Philippe Brucker 	 * reference counted.
54811effe8caSJean-Philippe Brucker 	 *
54821effe8caSJean-Philippe Brucker 	 * On the other hand, don't allow coalescing two pp_recycle SKBs if
54831effe8caSJean-Philippe Brucker 	 * @from is cloned, in case the SKB is using page_pool fragment
54841effe8caSJean-Philippe Brucker 	 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
54851effe8caSJean-Philippe Brucker 	 * references for cloned SKBs at the moment that would result in
54861effe8caSJean-Philippe Brucker 	 * inconsistent reference counts.
54876a5bcd84SIlias Apalodimas 	 */
54881effe8caSJean-Philippe Brucker 	if (to->pp_recycle != (from->pp_recycle && !skb_cloned(from)))
54896a5bcd84SIlias Apalodimas 		return false;
54906a5bcd84SIlias Apalodimas 
5491bad43ca8SEric Dumazet 	if (len <= skb_tailroom(to)) {
5492e93a0435SEric Dumazet 		if (len)
5493bad43ca8SEric Dumazet 			BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5494bad43ca8SEric Dumazet 		*delta_truesize = 0;
5495bad43ca8SEric Dumazet 		return true;
5496bad43ca8SEric Dumazet 	}
5497bad43ca8SEric Dumazet 
5498c818fa9eSEric Dumazet 	to_shinfo = skb_shinfo(to);
5499c818fa9eSEric Dumazet 	from_shinfo = skb_shinfo(from);
5500c818fa9eSEric Dumazet 	if (to_shinfo->frag_list || from_shinfo->frag_list)
5501bad43ca8SEric Dumazet 		return false;
55021f8b977aSWillem de Bruijn 	if (skb_zcopy(to) || skb_zcopy(from))
55031f8b977aSWillem de Bruijn 		return false;
5504bad43ca8SEric Dumazet 
5505bad43ca8SEric Dumazet 	if (skb_headlen(from) != 0) {
5506bad43ca8SEric Dumazet 		struct page *page;
5507bad43ca8SEric Dumazet 		unsigned int offset;
5508bad43ca8SEric Dumazet 
5509c818fa9eSEric Dumazet 		if (to_shinfo->nr_frags +
5510c818fa9eSEric Dumazet 		    from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5511bad43ca8SEric Dumazet 			return false;
5512bad43ca8SEric Dumazet 
5513bad43ca8SEric Dumazet 		if (skb_head_is_locked(from))
5514bad43ca8SEric Dumazet 			return false;
5515bad43ca8SEric Dumazet 
5516bad43ca8SEric Dumazet 		delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5517bad43ca8SEric Dumazet 
5518bad43ca8SEric Dumazet 		page = virt_to_head_page(from->head);
5519bad43ca8SEric Dumazet 		offset = from->data - (unsigned char *)page_address(page);
5520bad43ca8SEric Dumazet 
5521c818fa9eSEric Dumazet 		skb_fill_page_desc(to, to_shinfo->nr_frags,
5522bad43ca8SEric Dumazet 				   page, offset, skb_headlen(from));
5523bad43ca8SEric Dumazet 		*fragstolen = true;
5524bad43ca8SEric Dumazet 	} else {
5525c818fa9eSEric Dumazet 		if (to_shinfo->nr_frags +
5526c818fa9eSEric Dumazet 		    from_shinfo->nr_frags > MAX_SKB_FRAGS)
5527bad43ca8SEric Dumazet 			return false;
5528bad43ca8SEric Dumazet 
5529f4b549a5SWeiping Pan 		delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5530bad43ca8SEric Dumazet 	}
5531bad43ca8SEric Dumazet 
5532bad43ca8SEric Dumazet 	WARN_ON_ONCE(delta < len);
5533bad43ca8SEric Dumazet 
5534c818fa9eSEric Dumazet 	memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5535c818fa9eSEric Dumazet 	       from_shinfo->frags,
5536c818fa9eSEric Dumazet 	       from_shinfo->nr_frags * sizeof(skb_frag_t));
5537c818fa9eSEric Dumazet 	to_shinfo->nr_frags += from_shinfo->nr_frags;
5538bad43ca8SEric Dumazet 
5539bad43ca8SEric Dumazet 	if (!skb_cloned(from))
5540c818fa9eSEric Dumazet 		from_shinfo->nr_frags = 0;
5541bad43ca8SEric Dumazet 
55428ea853fdSLi RongQing 	/* if the skb is not cloned this does nothing
55438ea853fdSLi RongQing 	 * since we set nr_frags to 0.
55448ea853fdSLi RongQing 	 */
5545c818fa9eSEric Dumazet 	for (i = 0; i < from_shinfo->nr_frags; i++)
5546c818fa9eSEric Dumazet 		__skb_frag_ref(&from_shinfo->frags[i]);
5547bad43ca8SEric Dumazet 
5548bad43ca8SEric Dumazet 	to->truesize += delta;
5549bad43ca8SEric Dumazet 	to->len += len;
5550bad43ca8SEric Dumazet 	to->data_len += len;
5551bad43ca8SEric Dumazet 
5552bad43ca8SEric Dumazet 	*delta_truesize = delta;
5553bad43ca8SEric Dumazet 	return true;
5554bad43ca8SEric Dumazet }
5555bad43ca8SEric Dumazet EXPORT_SYMBOL(skb_try_coalesce);
5556621e84d6SNicolas Dichtel 
5557621e84d6SNicolas Dichtel /**
55588b27f277SNicolas Dichtel  * skb_scrub_packet - scrub an skb
5559621e84d6SNicolas Dichtel  *
5560621e84d6SNicolas Dichtel  * @skb: buffer to clean
55618b27f277SNicolas Dichtel  * @xnet: packet is crossing netns
5562621e84d6SNicolas Dichtel  *
55638b27f277SNicolas Dichtel  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
55648b27f277SNicolas Dichtel  * into/from a tunnel. Some information have to be cleared during these
55658b27f277SNicolas Dichtel  * operations.
55668b27f277SNicolas Dichtel  * skb_scrub_packet can also be used to clean a skb before injecting it in
55678b27f277SNicolas Dichtel  * another namespace (@xnet == true). We have to clear all information in the
55688b27f277SNicolas Dichtel  * skb that could impact namespace isolation.
5569621e84d6SNicolas Dichtel  */
55708b27f277SNicolas Dichtel void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5571621e84d6SNicolas Dichtel {
5572621e84d6SNicolas Dichtel 	skb->pkt_type = PACKET_HOST;
5573621e84d6SNicolas Dichtel 	skb->skb_iif = 0;
557460ff7467SWANG Cong 	skb->ignore_df = 0;
5575621e84d6SNicolas Dichtel 	skb_dst_drop(skb);
5576174e2381SFlorian Westphal 	skb_ext_reset(skb);
5577895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
5578621e84d6SNicolas Dichtel 	nf_reset_trace(skb);
5579213dd74aSHerbert Xu 
55806f9a5069SPetr Machata #ifdef CONFIG_NET_SWITCHDEV
55816f9a5069SPetr Machata 	skb->offload_fwd_mark = 0;
5582875e8939SIdo Schimmel 	skb->offload_l3_fwd_mark = 0;
55836f9a5069SPetr Machata #endif
55846f9a5069SPetr Machata 
5585213dd74aSHerbert Xu 	if (!xnet)
5586213dd74aSHerbert Xu 		return;
5587213dd74aSHerbert Xu 
55882b5ec1a5SYe Yin 	ipvs_reset(skb);
5589213dd74aSHerbert Xu 	skb->mark = 0;
5590de799101SMartin KaFai Lau 	skb_clear_tstamp(skb);
5591621e84d6SNicolas Dichtel }
5592621e84d6SNicolas Dichtel EXPORT_SYMBOL_GPL(skb_scrub_packet);
5593de960aa9SFlorian Westphal 
5594de960aa9SFlorian Westphal /**
5595de960aa9SFlorian Westphal  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5596de960aa9SFlorian Westphal  *
5597de960aa9SFlorian Westphal  * @skb: GSO skb
5598de960aa9SFlorian Westphal  *
5599de960aa9SFlorian Westphal  * skb_gso_transport_seglen is used to determine the real size of the
5600de960aa9SFlorian Westphal  * individual segments, including Layer4 headers (TCP/UDP).
5601de960aa9SFlorian Westphal  *
5602de960aa9SFlorian Westphal  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5603de960aa9SFlorian Westphal  */
5604a4a77718SDaniel Axtens static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5605de960aa9SFlorian Westphal {
5606de960aa9SFlorian Westphal 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
5607f993bc25SFlorian Westphal 	unsigned int thlen = 0;
5608f993bc25SFlorian Westphal 
5609f993bc25SFlorian Westphal 	if (skb->encapsulation) {
5610f993bc25SFlorian Westphal 		thlen = skb_inner_transport_header(skb) -
5611f993bc25SFlorian Westphal 			skb_transport_header(skb);
5612de960aa9SFlorian Westphal 
5613de960aa9SFlorian Westphal 		if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5614f993bc25SFlorian Westphal 			thlen += inner_tcp_hdrlen(skb);
5615f993bc25SFlorian Westphal 	} else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5616f993bc25SFlorian Westphal 		thlen = tcp_hdrlen(skb);
56171dd27cdeSDaniel Axtens 	} else if (unlikely(skb_is_gso_sctp(skb))) {
561890017accSMarcelo Ricardo Leitner 		thlen = sizeof(struct sctphdr);
5619ee80d1ebSWillem de Bruijn 	} else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5620ee80d1ebSWillem de Bruijn 		thlen = sizeof(struct udphdr);
5621f993bc25SFlorian Westphal 	}
56226d39d589SFlorian Westphal 	/* UFO sets gso_size to the size of the fragmentation
56236d39d589SFlorian Westphal 	 * payload, i.e. the size of the L4 (UDP) header is already
56246d39d589SFlorian Westphal 	 * accounted for.
56256d39d589SFlorian Westphal 	 */
5626f993bc25SFlorian Westphal 	return thlen + shinfo->gso_size;
5627de960aa9SFlorian Westphal }
5628a4a77718SDaniel Axtens 
5629a4a77718SDaniel Axtens /**
5630a4a77718SDaniel Axtens  * skb_gso_network_seglen - Return length of individual segments of a gso packet
5631a4a77718SDaniel Axtens  *
5632a4a77718SDaniel Axtens  * @skb: GSO skb
5633a4a77718SDaniel Axtens  *
5634a4a77718SDaniel Axtens  * skb_gso_network_seglen is used to determine the real size of the
5635a4a77718SDaniel Axtens  * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5636a4a77718SDaniel Axtens  *
5637a4a77718SDaniel Axtens  * The MAC/L2 header is not accounted for.
5638a4a77718SDaniel Axtens  */
5639a4a77718SDaniel Axtens static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5640a4a77718SDaniel Axtens {
5641a4a77718SDaniel Axtens 	unsigned int hdr_len = skb_transport_header(skb) -
5642a4a77718SDaniel Axtens 			       skb_network_header(skb);
5643a4a77718SDaniel Axtens 
5644a4a77718SDaniel Axtens 	return hdr_len + skb_gso_transport_seglen(skb);
5645a4a77718SDaniel Axtens }
5646a4a77718SDaniel Axtens 
5647a4a77718SDaniel Axtens /**
5648a4a77718SDaniel Axtens  * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5649a4a77718SDaniel Axtens  *
5650a4a77718SDaniel Axtens  * @skb: GSO skb
5651a4a77718SDaniel Axtens  *
5652a4a77718SDaniel Axtens  * skb_gso_mac_seglen is used to determine the real size of the
5653a4a77718SDaniel Axtens  * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5654a4a77718SDaniel Axtens  * headers (TCP/UDP).
5655a4a77718SDaniel Axtens  */
5656a4a77718SDaniel Axtens static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5657a4a77718SDaniel Axtens {
5658a4a77718SDaniel Axtens 	unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5659a4a77718SDaniel Axtens 
5660a4a77718SDaniel Axtens 	return hdr_len + skb_gso_transport_seglen(skb);
5661a4a77718SDaniel Axtens }
56620d5501c1SVlad Yasevich 
5663ae7ef81eSMarcelo Ricardo Leitner /**
56642b16f048SDaniel Axtens  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
56652b16f048SDaniel Axtens  *
56662b16f048SDaniel Axtens  * There are a couple of instances where we have a GSO skb, and we
56672b16f048SDaniel Axtens  * want to determine what size it would be after it is segmented.
56682b16f048SDaniel Axtens  *
56692b16f048SDaniel Axtens  * We might want to check:
56702b16f048SDaniel Axtens  * -    L3+L4+payload size (e.g. IP forwarding)
56712b16f048SDaniel Axtens  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
56722b16f048SDaniel Axtens  *
56732b16f048SDaniel Axtens  * This is a helper to do that correctly considering GSO_BY_FRAGS.
56742b16f048SDaniel Axtens  *
567549682bfaSMathieu Malaterre  * @skb: GSO skb
567649682bfaSMathieu Malaterre  *
56772b16f048SDaniel Axtens  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
56782b16f048SDaniel Axtens  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
56792b16f048SDaniel Axtens  *
56802b16f048SDaniel Axtens  * @max_len: The maximum permissible length.
56812b16f048SDaniel Axtens  *
56822b16f048SDaniel Axtens  * Returns true if the segmented length <= max length.
56832b16f048SDaniel Axtens  */
56842b16f048SDaniel Axtens static inline bool skb_gso_size_check(const struct sk_buff *skb,
56852b16f048SDaniel Axtens 				      unsigned int seg_len,
56862b16f048SDaniel Axtens 				      unsigned int max_len) {
56872b16f048SDaniel Axtens 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
56882b16f048SDaniel Axtens 	const struct sk_buff *iter;
56892b16f048SDaniel Axtens 
56902b16f048SDaniel Axtens 	if (shinfo->gso_size != GSO_BY_FRAGS)
56912b16f048SDaniel Axtens 		return seg_len <= max_len;
56922b16f048SDaniel Axtens 
56932b16f048SDaniel Axtens 	/* Undo this so we can re-use header sizes */
56942b16f048SDaniel Axtens 	seg_len -= GSO_BY_FRAGS;
56952b16f048SDaniel Axtens 
56962b16f048SDaniel Axtens 	skb_walk_frags(skb, iter) {
56972b16f048SDaniel Axtens 		if (seg_len + skb_headlen(iter) > max_len)
56982b16f048SDaniel Axtens 			return false;
56992b16f048SDaniel Axtens 	}
57002b16f048SDaniel Axtens 
57012b16f048SDaniel Axtens 	return true;
57022b16f048SDaniel Axtens }
57032b16f048SDaniel Axtens 
57042b16f048SDaniel Axtens /**
5705779b7931SDaniel Axtens  * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5706ae7ef81eSMarcelo Ricardo Leitner  *
5707ae7ef81eSMarcelo Ricardo Leitner  * @skb: GSO skb
570876f21b99SDavid S. Miller  * @mtu: MTU to validate against
5709ae7ef81eSMarcelo Ricardo Leitner  *
5710779b7931SDaniel Axtens  * skb_gso_validate_network_len validates if a given skb will fit a
5711779b7931SDaniel Axtens  * wanted MTU once split. It considers L3 headers, L4 headers, and the
5712779b7931SDaniel Axtens  * payload.
5713ae7ef81eSMarcelo Ricardo Leitner  */
5714779b7931SDaniel Axtens bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5715ae7ef81eSMarcelo Ricardo Leitner {
57162b16f048SDaniel Axtens 	return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5717ae7ef81eSMarcelo Ricardo Leitner }
5718779b7931SDaniel Axtens EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5719ae7ef81eSMarcelo Ricardo Leitner 
57202b16f048SDaniel Axtens /**
57212b16f048SDaniel Axtens  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
57222b16f048SDaniel Axtens  *
57232b16f048SDaniel Axtens  * @skb: GSO skb
57242b16f048SDaniel Axtens  * @len: length to validate against
57252b16f048SDaniel Axtens  *
57262b16f048SDaniel Axtens  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
57272b16f048SDaniel Axtens  * length once split, including L2, L3 and L4 headers and the payload.
57282b16f048SDaniel Axtens  */
57292b16f048SDaniel Axtens bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
57302b16f048SDaniel Axtens {
57312b16f048SDaniel Axtens 	return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
57322b16f048SDaniel Axtens }
57332b16f048SDaniel Axtens EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
57342b16f048SDaniel Axtens 
57350d5501c1SVlad Yasevich static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
57360d5501c1SVlad Yasevich {
5737d85e8be2SYuya Kusakabe 	int mac_len, meta_len;
5738d85e8be2SYuya Kusakabe 	void *meta;
57394bbb3e0eSToshiaki Makita 
57400d5501c1SVlad Yasevich 	if (skb_cow(skb, skb_headroom(skb)) < 0) {
57410d5501c1SVlad Yasevich 		kfree_skb(skb);
57420d5501c1SVlad Yasevich 		return NULL;
57430d5501c1SVlad Yasevich 	}
57440d5501c1SVlad Yasevich 
57454bbb3e0eSToshiaki Makita 	mac_len = skb->data - skb_mac_header(skb);
5746ae474573SToshiaki Makita 	if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
57474bbb3e0eSToshiaki Makita 		memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
57484bbb3e0eSToshiaki Makita 			mac_len - VLAN_HLEN - ETH_TLEN);
5749ae474573SToshiaki Makita 	}
5750d85e8be2SYuya Kusakabe 
5751d85e8be2SYuya Kusakabe 	meta_len = skb_metadata_len(skb);
5752d85e8be2SYuya Kusakabe 	if (meta_len) {
5753d85e8be2SYuya Kusakabe 		meta = skb_metadata_end(skb) - meta_len;
5754d85e8be2SYuya Kusakabe 		memmove(meta + VLAN_HLEN, meta, meta_len);
5755d85e8be2SYuya Kusakabe 	}
5756d85e8be2SYuya Kusakabe 
57570d5501c1SVlad Yasevich 	skb->mac_header += VLAN_HLEN;
57580d5501c1SVlad Yasevich 	return skb;
57590d5501c1SVlad Yasevich }
57600d5501c1SVlad Yasevich 
57610d5501c1SVlad Yasevich struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
57620d5501c1SVlad Yasevich {
57630d5501c1SVlad Yasevich 	struct vlan_hdr *vhdr;
57640d5501c1SVlad Yasevich 	u16 vlan_tci;
57650d5501c1SVlad Yasevich 
5766df8a39deSJiri Pirko 	if (unlikely(skb_vlan_tag_present(skb))) {
57670d5501c1SVlad Yasevich 		/* vlan_tci is already set-up so leave this for another time */
57680d5501c1SVlad Yasevich 		return skb;
57690d5501c1SVlad Yasevich 	}
57700d5501c1SVlad Yasevich 
57710d5501c1SVlad Yasevich 	skb = skb_share_check(skb, GFP_ATOMIC);
57720d5501c1SVlad Yasevich 	if (unlikely(!skb))
57730d5501c1SVlad Yasevich 		goto err_free;
577455eff0ebSMiaohe Lin 	/* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
577555eff0ebSMiaohe Lin 	if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
57760d5501c1SVlad Yasevich 		goto err_free;
57770d5501c1SVlad Yasevich 
57780d5501c1SVlad Yasevich 	vhdr = (struct vlan_hdr *)skb->data;
57790d5501c1SVlad Yasevich 	vlan_tci = ntohs(vhdr->h_vlan_TCI);
57800d5501c1SVlad Yasevich 	__vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
57810d5501c1SVlad Yasevich 
57820d5501c1SVlad Yasevich 	skb_pull_rcsum(skb, VLAN_HLEN);
57830d5501c1SVlad Yasevich 	vlan_set_encap_proto(skb, vhdr);
57840d5501c1SVlad Yasevich 
57850d5501c1SVlad Yasevich 	skb = skb_reorder_vlan_header(skb);
57860d5501c1SVlad Yasevich 	if (unlikely(!skb))
57870d5501c1SVlad Yasevich 		goto err_free;
57880d5501c1SVlad Yasevich 
57890d5501c1SVlad Yasevich 	skb_reset_network_header(skb);
57908be33ecfSAlexander Lobakin 	if (!skb_transport_header_was_set(skb))
57910d5501c1SVlad Yasevich 		skb_reset_transport_header(skb);
57920d5501c1SVlad Yasevich 	skb_reset_mac_len(skb);
57930d5501c1SVlad Yasevich 
57940d5501c1SVlad Yasevich 	return skb;
57950d5501c1SVlad Yasevich 
57960d5501c1SVlad Yasevich err_free:
57970d5501c1SVlad Yasevich 	kfree_skb(skb);
57980d5501c1SVlad Yasevich 	return NULL;
57990d5501c1SVlad Yasevich }
58000d5501c1SVlad Yasevich EXPORT_SYMBOL(skb_vlan_untag);
58012e4e4410SEric Dumazet 
580292ece280SLiu Jian int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5803e2195121SJiri Pirko {
5804e2195121SJiri Pirko 	if (!pskb_may_pull(skb, write_len))
5805e2195121SJiri Pirko 		return -ENOMEM;
5806e2195121SJiri Pirko 
5807e2195121SJiri Pirko 	if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5808e2195121SJiri Pirko 		return 0;
5809e2195121SJiri Pirko 
5810e2195121SJiri Pirko 	return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5811e2195121SJiri Pirko }
5812e2195121SJiri Pirko EXPORT_SYMBOL(skb_ensure_writable);
5813e2195121SJiri Pirko 
5814bfca4c52SShmulik Ladkani /* remove VLAN header from packet and update csum accordingly.
5815bfca4c52SShmulik Ladkani  * expects a non skb_vlan_tag_present skb with a vlan tag payload
5816bfca4c52SShmulik Ladkani  */
5817bfca4c52SShmulik Ladkani int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
581893515d53SJiri Pirko {
581993515d53SJiri Pirko 	struct vlan_hdr *vhdr;
5820b6a79208SShmulik Ladkani 	int offset = skb->data - skb_mac_header(skb);
582193515d53SJiri Pirko 	int err;
582293515d53SJiri Pirko 
5823b6a79208SShmulik Ladkani 	if (WARN_ONCE(offset,
5824b6a79208SShmulik Ladkani 		      "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5825b6a79208SShmulik Ladkani 		      offset)) {
5826b6a79208SShmulik Ladkani 		return -EINVAL;
5827b6a79208SShmulik Ladkani 	}
5828b6a79208SShmulik Ladkani 
582993515d53SJiri Pirko 	err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
583093515d53SJiri Pirko 	if (unlikely(err))
5831b6a79208SShmulik Ladkani 		return err;
583293515d53SJiri Pirko 
583393515d53SJiri Pirko 	skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
583493515d53SJiri Pirko 
583593515d53SJiri Pirko 	vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
583693515d53SJiri Pirko 	*vlan_tci = ntohs(vhdr->h_vlan_TCI);
583793515d53SJiri Pirko 
583893515d53SJiri Pirko 	memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
583993515d53SJiri Pirko 	__skb_pull(skb, VLAN_HLEN);
584093515d53SJiri Pirko 
584193515d53SJiri Pirko 	vlan_set_encap_proto(skb, vhdr);
584293515d53SJiri Pirko 	skb->mac_header += VLAN_HLEN;
584393515d53SJiri Pirko 
584493515d53SJiri Pirko 	if (skb_network_offset(skb) < ETH_HLEN)
584593515d53SJiri Pirko 		skb_set_network_header(skb, ETH_HLEN);
584693515d53SJiri Pirko 
584793515d53SJiri Pirko 	skb_reset_mac_len(skb);
584893515d53SJiri Pirko 
584993515d53SJiri Pirko 	return err;
585093515d53SJiri Pirko }
5851bfca4c52SShmulik Ladkani EXPORT_SYMBOL(__skb_vlan_pop);
585293515d53SJiri Pirko 
5853b6a79208SShmulik Ladkani /* Pop a vlan tag either from hwaccel or from payload.
5854b6a79208SShmulik Ladkani  * Expects skb->data at mac header.
5855b6a79208SShmulik Ladkani  */
585693515d53SJiri Pirko int skb_vlan_pop(struct sk_buff *skb)
585793515d53SJiri Pirko {
585893515d53SJiri Pirko 	u16 vlan_tci;
585993515d53SJiri Pirko 	__be16 vlan_proto;
586093515d53SJiri Pirko 	int err;
586193515d53SJiri Pirko 
5862df8a39deSJiri Pirko 	if (likely(skb_vlan_tag_present(skb))) {
5863b1817524SMichał Mirosław 		__vlan_hwaccel_clear_tag(skb);
586493515d53SJiri Pirko 	} else {
5865ecf4ee41SShmulik Ladkani 		if (unlikely(!eth_type_vlan(skb->protocol)))
586693515d53SJiri Pirko 			return 0;
586793515d53SJiri Pirko 
586893515d53SJiri Pirko 		err = __skb_vlan_pop(skb, &vlan_tci);
586993515d53SJiri Pirko 		if (err)
587093515d53SJiri Pirko 			return err;
587193515d53SJiri Pirko 	}
587293515d53SJiri Pirko 	/* move next vlan tag to hw accel tag */
5873ecf4ee41SShmulik Ladkani 	if (likely(!eth_type_vlan(skb->protocol)))
587493515d53SJiri Pirko 		return 0;
587593515d53SJiri Pirko 
587693515d53SJiri Pirko 	vlan_proto = skb->protocol;
587793515d53SJiri Pirko 	err = __skb_vlan_pop(skb, &vlan_tci);
587893515d53SJiri Pirko 	if (unlikely(err))
587993515d53SJiri Pirko 		return err;
588093515d53SJiri Pirko 
588193515d53SJiri Pirko 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
588293515d53SJiri Pirko 	return 0;
588393515d53SJiri Pirko }
588493515d53SJiri Pirko EXPORT_SYMBOL(skb_vlan_pop);
588593515d53SJiri Pirko 
5886b6a79208SShmulik Ladkani /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5887b6a79208SShmulik Ladkani  * Expects skb->data at mac header.
5888b6a79208SShmulik Ladkani  */
588993515d53SJiri Pirko int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
589093515d53SJiri Pirko {
5891df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb)) {
5892b6a79208SShmulik Ladkani 		int offset = skb->data - skb_mac_header(skb);
589393515d53SJiri Pirko 		int err;
589493515d53SJiri Pirko 
5895b6a79208SShmulik Ladkani 		if (WARN_ONCE(offset,
5896b6a79208SShmulik Ladkani 			      "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5897b6a79208SShmulik Ladkani 			      offset)) {
5898b6a79208SShmulik Ladkani 			return -EINVAL;
5899b6a79208SShmulik Ladkani 		}
5900b6a79208SShmulik Ladkani 
590193515d53SJiri Pirko 		err = __vlan_insert_tag(skb, skb->vlan_proto,
5902df8a39deSJiri Pirko 					skb_vlan_tag_get(skb));
5903b6a79208SShmulik Ladkani 		if (err)
590493515d53SJiri Pirko 			return err;
59059241e2dfSDaniel Borkmann 
590693515d53SJiri Pirko 		skb->protocol = skb->vlan_proto;
590793515d53SJiri Pirko 		skb->mac_len += VLAN_HLEN;
590893515d53SJiri Pirko 
59096b83d28aSDaniel Borkmann 		skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
591093515d53SJiri Pirko 	}
591193515d53SJiri Pirko 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
591293515d53SJiri Pirko 	return 0;
591393515d53SJiri Pirko }
591493515d53SJiri Pirko EXPORT_SYMBOL(skb_vlan_push);
591593515d53SJiri Pirko 
591619fbcb36SGuillaume Nault /**
591719fbcb36SGuillaume Nault  * skb_eth_pop() - Drop the Ethernet header at the head of a packet
591819fbcb36SGuillaume Nault  *
591919fbcb36SGuillaume Nault  * @skb: Socket buffer to modify
592019fbcb36SGuillaume Nault  *
592119fbcb36SGuillaume Nault  * Drop the Ethernet header of @skb.
592219fbcb36SGuillaume Nault  *
592319fbcb36SGuillaume Nault  * Expects that skb->data points to the mac header and that no VLAN tags are
592419fbcb36SGuillaume Nault  * present.
592519fbcb36SGuillaume Nault  *
592619fbcb36SGuillaume Nault  * Returns 0 on success, -errno otherwise.
592719fbcb36SGuillaume Nault  */
592819fbcb36SGuillaume Nault int skb_eth_pop(struct sk_buff *skb)
592919fbcb36SGuillaume Nault {
593019fbcb36SGuillaume Nault 	if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
593119fbcb36SGuillaume Nault 	    skb_network_offset(skb) < ETH_HLEN)
593219fbcb36SGuillaume Nault 		return -EPROTO;
593319fbcb36SGuillaume Nault 
593419fbcb36SGuillaume Nault 	skb_pull_rcsum(skb, ETH_HLEN);
593519fbcb36SGuillaume Nault 	skb_reset_mac_header(skb);
593619fbcb36SGuillaume Nault 	skb_reset_mac_len(skb);
593719fbcb36SGuillaume Nault 
593819fbcb36SGuillaume Nault 	return 0;
593919fbcb36SGuillaume Nault }
594019fbcb36SGuillaume Nault EXPORT_SYMBOL(skb_eth_pop);
594119fbcb36SGuillaume Nault 
594219fbcb36SGuillaume Nault /**
594319fbcb36SGuillaume Nault  * skb_eth_push() - Add a new Ethernet header at the head of a packet
594419fbcb36SGuillaume Nault  *
594519fbcb36SGuillaume Nault  * @skb: Socket buffer to modify
594619fbcb36SGuillaume Nault  * @dst: Destination MAC address of the new header
594719fbcb36SGuillaume Nault  * @src: Source MAC address of the new header
594819fbcb36SGuillaume Nault  *
594919fbcb36SGuillaume Nault  * Prepend @skb with a new Ethernet header.
595019fbcb36SGuillaume Nault  *
595119fbcb36SGuillaume Nault  * Expects that skb->data points to the mac header, which must be empty.
595219fbcb36SGuillaume Nault  *
595319fbcb36SGuillaume Nault  * Returns 0 on success, -errno otherwise.
595419fbcb36SGuillaume Nault  */
595519fbcb36SGuillaume Nault int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
595619fbcb36SGuillaume Nault 		 const unsigned char *src)
595719fbcb36SGuillaume Nault {
595819fbcb36SGuillaume Nault 	struct ethhdr *eth;
595919fbcb36SGuillaume Nault 	int err;
596019fbcb36SGuillaume Nault 
596119fbcb36SGuillaume Nault 	if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
596219fbcb36SGuillaume Nault 		return -EPROTO;
596319fbcb36SGuillaume Nault 
596419fbcb36SGuillaume Nault 	err = skb_cow_head(skb, sizeof(*eth));
596519fbcb36SGuillaume Nault 	if (err < 0)
596619fbcb36SGuillaume Nault 		return err;
596719fbcb36SGuillaume Nault 
596819fbcb36SGuillaume Nault 	skb_push(skb, sizeof(*eth));
596919fbcb36SGuillaume Nault 	skb_reset_mac_header(skb);
597019fbcb36SGuillaume Nault 	skb_reset_mac_len(skb);
597119fbcb36SGuillaume Nault 
597219fbcb36SGuillaume Nault 	eth = eth_hdr(skb);
597319fbcb36SGuillaume Nault 	ether_addr_copy(eth->h_dest, dst);
597419fbcb36SGuillaume Nault 	ether_addr_copy(eth->h_source, src);
597519fbcb36SGuillaume Nault 	eth->h_proto = skb->protocol;
597619fbcb36SGuillaume Nault 
597719fbcb36SGuillaume Nault 	skb_postpush_rcsum(skb, eth, sizeof(*eth));
597819fbcb36SGuillaume Nault 
597919fbcb36SGuillaume Nault 	return 0;
598019fbcb36SGuillaume Nault }
598119fbcb36SGuillaume Nault EXPORT_SYMBOL(skb_eth_push);
598219fbcb36SGuillaume Nault 
59838822e270SJohn Hurley /* Update the ethertype of hdr and the skb csum value if required. */
59848822e270SJohn Hurley static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
59858822e270SJohn Hurley 			     __be16 ethertype)
59868822e270SJohn Hurley {
59878822e270SJohn Hurley 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
59888822e270SJohn Hurley 		__be16 diff[] = { ~hdr->h_proto, ethertype };
59898822e270SJohn Hurley 
59908822e270SJohn Hurley 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
59918822e270SJohn Hurley 	}
59928822e270SJohn Hurley 
59938822e270SJohn Hurley 	hdr->h_proto = ethertype;
59948822e270SJohn Hurley }
59958822e270SJohn Hurley 
59968822e270SJohn Hurley /**
5997e7dbfed1SMartin Varghese  * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5998e7dbfed1SMartin Varghese  *                   the packet
59998822e270SJohn Hurley  *
60008822e270SJohn Hurley  * @skb: buffer
60018822e270SJohn Hurley  * @mpls_lse: MPLS label stack entry to push
60028822e270SJohn Hurley  * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6003fa4e0f88SDavide Caratti  * @mac_len: length of the MAC header
6004e7dbfed1SMartin Varghese  * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6005e7dbfed1SMartin Varghese  *            ethernet
60068822e270SJohn Hurley  *
60078822e270SJohn Hurley  * Expects skb->data at mac header.
60088822e270SJohn Hurley  *
60098822e270SJohn Hurley  * Returns 0 on success, -errno otherwise.
60108822e270SJohn Hurley  */
6011fa4e0f88SDavide Caratti int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6012d04ac224SMartin Varghese 		  int mac_len, bool ethernet)
60138822e270SJohn Hurley {
60148822e270SJohn Hurley 	struct mpls_shim_hdr *lse;
60158822e270SJohn Hurley 	int err;
60168822e270SJohn Hurley 
60178822e270SJohn Hurley 	if (unlikely(!eth_p_mpls(mpls_proto)))
60188822e270SJohn Hurley 		return -EINVAL;
60198822e270SJohn Hurley 
60208822e270SJohn Hurley 	/* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
60218822e270SJohn Hurley 	if (skb->encapsulation)
60228822e270SJohn Hurley 		return -EINVAL;
60238822e270SJohn Hurley 
60248822e270SJohn Hurley 	err = skb_cow_head(skb, MPLS_HLEN);
60258822e270SJohn Hurley 	if (unlikely(err))
60268822e270SJohn Hurley 		return err;
60278822e270SJohn Hurley 
60288822e270SJohn Hurley 	if (!skb->inner_protocol) {
6029e7dbfed1SMartin Varghese 		skb_set_inner_network_header(skb, skb_network_offset(skb));
60308822e270SJohn Hurley 		skb_set_inner_protocol(skb, skb->protocol);
60318822e270SJohn Hurley 	}
60328822e270SJohn Hurley 
60338822e270SJohn Hurley 	skb_push(skb, MPLS_HLEN);
60348822e270SJohn Hurley 	memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6035fa4e0f88SDavide Caratti 		mac_len);
60368822e270SJohn Hurley 	skb_reset_mac_header(skb);
6037fa4e0f88SDavide Caratti 	skb_set_network_header(skb, mac_len);
6038e7dbfed1SMartin Varghese 	skb_reset_mac_len(skb);
60398822e270SJohn Hurley 
60408822e270SJohn Hurley 	lse = mpls_hdr(skb);
60418822e270SJohn Hurley 	lse->label_stack_entry = mpls_lse;
60428822e270SJohn Hurley 	skb_postpush_rcsum(skb, lse, MPLS_HLEN);
60438822e270SJohn Hurley 
60444296adc3SGuillaume Nault 	if (ethernet && mac_len >= ETH_HLEN)
60458822e270SJohn Hurley 		skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
60468822e270SJohn Hurley 	skb->protocol = mpls_proto;
60478822e270SJohn Hurley 
60488822e270SJohn Hurley 	return 0;
60498822e270SJohn Hurley }
60508822e270SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_push);
60518822e270SJohn Hurley 
60522e4e4410SEric Dumazet /**
6053ed246ceeSJohn Hurley  * skb_mpls_pop() - pop the outermost MPLS header
6054ed246ceeSJohn Hurley  *
6055ed246ceeSJohn Hurley  * @skb: buffer
6056ed246ceeSJohn Hurley  * @next_proto: ethertype of header after popped MPLS header
6057fa4e0f88SDavide Caratti  * @mac_len: length of the MAC header
605876f99f98SMartin Varghese  * @ethernet: flag to indicate if the packet is ethernet
6059ed246ceeSJohn Hurley  *
6060ed246ceeSJohn Hurley  * Expects skb->data at mac header.
6061ed246ceeSJohn Hurley  *
6062ed246ceeSJohn Hurley  * Returns 0 on success, -errno otherwise.
6063ed246ceeSJohn Hurley  */
6064040b5cfbSMartin Varghese int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6065040b5cfbSMartin Varghese 		 bool ethernet)
6066ed246ceeSJohn Hurley {
6067ed246ceeSJohn Hurley 	int err;
6068ed246ceeSJohn Hurley 
6069ed246ceeSJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
6070dedc5a08SDavide Caratti 		return 0;
6071ed246ceeSJohn Hurley 
6072fa4e0f88SDavide Caratti 	err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6073ed246ceeSJohn Hurley 	if (unlikely(err))
6074ed246ceeSJohn Hurley 		return err;
6075ed246ceeSJohn Hurley 
6076ed246ceeSJohn Hurley 	skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6077ed246ceeSJohn Hurley 	memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6078fa4e0f88SDavide Caratti 		mac_len);
6079ed246ceeSJohn Hurley 
6080ed246ceeSJohn Hurley 	__skb_pull(skb, MPLS_HLEN);
6081ed246ceeSJohn Hurley 	skb_reset_mac_header(skb);
6082fa4e0f88SDavide Caratti 	skb_set_network_header(skb, mac_len);
6083ed246ceeSJohn Hurley 
60844296adc3SGuillaume Nault 	if (ethernet && mac_len >= ETH_HLEN) {
6085ed246ceeSJohn Hurley 		struct ethhdr *hdr;
6086ed246ceeSJohn Hurley 
6087ed246ceeSJohn Hurley 		/* use mpls_hdr() to get ethertype to account for VLANs. */
6088ed246ceeSJohn Hurley 		hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6089ed246ceeSJohn Hurley 		skb_mod_eth_type(skb, hdr, next_proto);
6090ed246ceeSJohn Hurley 	}
6091ed246ceeSJohn Hurley 	skb->protocol = next_proto;
6092ed246ceeSJohn Hurley 
6093ed246ceeSJohn Hurley 	return 0;
6094ed246ceeSJohn Hurley }
6095ed246ceeSJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_pop);
6096ed246ceeSJohn Hurley 
6097ed246ceeSJohn Hurley /**
6098d27cf5c5SJohn Hurley  * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6099d27cf5c5SJohn Hurley  *
6100d27cf5c5SJohn Hurley  * @skb: buffer
6101d27cf5c5SJohn Hurley  * @mpls_lse: new MPLS label stack entry to update to
6102d27cf5c5SJohn Hurley  *
6103d27cf5c5SJohn Hurley  * Expects skb->data at mac header.
6104d27cf5c5SJohn Hurley  *
6105d27cf5c5SJohn Hurley  * Returns 0 on success, -errno otherwise.
6106d27cf5c5SJohn Hurley  */
6107d27cf5c5SJohn Hurley int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6108d27cf5c5SJohn Hurley {
6109d27cf5c5SJohn Hurley 	int err;
6110d27cf5c5SJohn Hurley 
6111d27cf5c5SJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
6112d27cf5c5SJohn Hurley 		return -EINVAL;
6113d27cf5c5SJohn Hurley 
6114d27cf5c5SJohn Hurley 	err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6115d27cf5c5SJohn Hurley 	if (unlikely(err))
6116d27cf5c5SJohn Hurley 		return err;
6117d27cf5c5SJohn Hurley 
6118d27cf5c5SJohn Hurley 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
6119d27cf5c5SJohn Hurley 		__be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6120d27cf5c5SJohn Hurley 
6121d27cf5c5SJohn Hurley 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6122d27cf5c5SJohn Hurley 	}
6123d27cf5c5SJohn Hurley 
6124d27cf5c5SJohn Hurley 	mpls_hdr(skb)->label_stack_entry = mpls_lse;
6125d27cf5c5SJohn Hurley 
6126d27cf5c5SJohn Hurley 	return 0;
6127d27cf5c5SJohn Hurley }
6128d27cf5c5SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6129d27cf5c5SJohn Hurley 
6130d27cf5c5SJohn Hurley /**
61312a2ea508SJohn Hurley  * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
61322a2ea508SJohn Hurley  *
61332a2ea508SJohn Hurley  * @skb: buffer
61342a2ea508SJohn Hurley  *
61352a2ea508SJohn Hurley  * Expects skb->data at mac header.
61362a2ea508SJohn Hurley  *
61372a2ea508SJohn Hurley  * Returns 0 on success, -errno otherwise.
61382a2ea508SJohn Hurley  */
61392a2ea508SJohn Hurley int skb_mpls_dec_ttl(struct sk_buff *skb)
61402a2ea508SJohn Hurley {
61412a2ea508SJohn Hurley 	u32 lse;
61422a2ea508SJohn Hurley 	u8 ttl;
61432a2ea508SJohn Hurley 
61442a2ea508SJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
61452a2ea508SJohn Hurley 		return -EINVAL;
61462a2ea508SJohn Hurley 
614713de4ed9SDavide Caratti 	if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
614813de4ed9SDavide Caratti 		return -ENOMEM;
614913de4ed9SDavide Caratti 
61502a2ea508SJohn Hurley 	lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
61512a2ea508SJohn Hurley 	ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
61522a2ea508SJohn Hurley 	if (!--ttl)
61532a2ea508SJohn Hurley 		return -EINVAL;
61542a2ea508SJohn Hurley 
61552a2ea508SJohn Hurley 	lse &= ~MPLS_LS_TTL_MASK;
61562a2ea508SJohn Hurley 	lse |= ttl << MPLS_LS_TTL_SHIFT;
61572a2ea508SJohn Hurley 
61582a2ea508SJohn Hurley 	return skb_mpls_update_lse(skb, cpu_to_be32(lse));
61592a2ea508SJohn Hurley }
61602a2ea508SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
61612a2ea508SJohn Hurley 
61622a2ea508SJohn Hurley /**
61632e4e4410SEric Dumazet  * alloc_skb_with_frags - allocate skb with page frags
61642e4e4410SEric Dumazet  *
6165de3f0d0eSMasanari Iida  * @header_len: size of linear part
6166de3f0d0eSMasanari Iida  * @data_len: needed length in frags
6167de3f0d0eSMasanari Iida  * @max_page_order: max page order desired.
6168de3f0d0eSMasanari Iida  * @errcode: pointer to error code if any
6169de3f0d0eSMasanari Iida  * @gfp_mask: allocation mask
61702e4e4410SEric Dumazet  *
61712e4e4410SEric Dumazet  * This can be used to allocate a paged skb, given a maximal order for frags.
61722e4e4410SEric Dumazet  */
61732e4e4410SEric Dumazet struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
61742e4e4410SEric Dumazet 				     unsigned long data_len,
61752e4e4410SEric Dumazet 				     int max_page_order,
61762e4e4410SEric Dumazet 				     int *errcode,
61772e4e4410SEric Dumazet 				     gfp_t gfp_mask)
61782e4e4410SEric Dumazet {
61792e4e4410SEric Dumazet 	int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
61802e4e4410SEric Dumazet 	unsigned long chunk;
61812e4e4410SEric Dumazet 	struct sk_buff *skb;
61822e4e4410SEric Dumazet 	struct page *page;
61832e4e4410SEric Dumazet 	int i;
61842e4e4410SEric Dumazet 
61852e4e4410SEric Dumazet 	*errcode = -EMSGSIZE;
61862e4e4410SEric Dumazet 	/* Note this test could be relaxed, if we succeed to allocate
61872e4e4410SEric Dumazet 	 * high order pages...
61882e4e4410SEric Dumazet 	 */
61892e4e4410SEric Dumazet 	if (npages > MAX_SKB_FRAGS)
61902e4e4410SEric Dumazet 		return NULL;
61912e4e4410SEric Dumazet 
61922e4e4410SEric Dumazet 	*errcode = -ENOBUFS;
6193f8c468e8SDavid Rientjes 	skb = alloc_skb(header_len, gfp_mask);
61942e4e4410SEric Dumazet 	if (!skb)
61952e4e4410SEric Dumazet 		return NULL;
61962e4e4410SEric Dumazet 
61972e4e4410SEric Dumazet 	skb->truesize += npages << PAGE_SHIFT;
61982e4e4410SEric Dumazet 
61992e4e4410SEric Dumazet 	for (i = 0; npages > 0; i++) {
62002e4e4410SEric Dumazet 		int order = max_page_order;
62012e4e4410SEric Dumazet 
62022e4e4410SEric Dumazet 		while (order) {
62032e4e4410SEric Dumazet 			if (npages >= 1 << order) {
6204d0164adcSMel Gorman 				page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
62052e4e4410SEric Dumazet 						   __GFP_COMP |
6206d14b56f5SMichal Hocko 						   __GFP_NOWARN,
62072e4e4410SEric Dumazet 						   order);
62082e4e4410SEric Dumazet 				if (page)
62092e4e4410SEric Dumazet 					goto fill_page;
62102e4e4410SEric Dumazet 				/* Do not retry other high order allocations */
62112e4e4410SEric Dumazet 				order = 1;
62122e4e4410SEric Dumazet 				max_page_order = 0;
62132e4e4410SEric Dumazet 			}
62142e4e4410SEric Dumazet 			order--;
62152e4e4410SEric Dumazet 		}
62162e4e4410SEric Dumazet 		page = alloc_page(gfp_mask);
62172e4e4410SEric Dumazet 		if (!page)
62182e4e4410SEric Dumazet 			goto failure;
62192e4e4410SEric Dumazet fill_page:
62202e4e4410SEric Dumazet 		chunk = min_t(unsigned long, data_len,
62212e4e4410SEric Dumazet 			      PAGE_SIZE << order);
62222e4e4410SEric Dumazet 		skb_fill_page_desc(skb, i, page, 0, chunk);
62232e4e4410SEric Dumazet 		data_len -= chunk;
62242e4e4410SEric Dumazet 		npages -= 1 << order;
62252e4e4410SEric Dumazet 	}
62262e4e4410SEric Dumazet 	return skb;
62272e4e4410SEric Dumazet 
62282e4e4410SEric Dumazet failure:
62292e4e4410SEric Dumazet 	kfree_skb(skb);
62302e4e4410SEric Dumazet 	return NULL;
62312e4e4410SEric Dumazet }
62322e4e4410SEric Dumazet EXPORT_SYMBOL(alloc_skb_with_frags);
62336fa01ccdSSowmini Varadhan 
62346fa01ccdSSowmini Varadhan /* carve out the first off bytes from skb when off < headlen */
62356fa01ccdSSowmini Varadhan static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
62366fa01ccdSSowmini Varadhan 				    const int headlen, gfp_t gfp_mask)
62376fa01ccdSSowmini Varadhan {
62386fa01ccdSSowmini Varadhan 	int i;
623912d6c1d3SKees Cook 	unsigned int size = skb_end_offset(skb);
62406fa01ccdSSowmini Varadhan 	int new_hlen = headlen - off;
62416fa01ccdSSowmini Varadhan 	u8 *data;
62426fa01ccdSSowmini Varadhan 
62436fa01ccdSSowmini Varadhan 	if (skb_pfmemalloc(skb))
62446fa01ccdSSowmini Varadhan 		gfp_mask |= __GFP_MEMALLOC;
624512d6c1d3SKees Cook 
624612d6c1d3SKees Cook 	size = SKB_DATA_ALIGN(size);
624712d6c1d3SKees Cook 	size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
624812d6c1d3SKees Cook 	size = kmalloc_size_roundup(size);
624912d6c1d3SKees Cook 	data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
62506fa01ccdSSowmini Varadhan 	if (!data)
62516fa01ccdSSowmini Varadhan 		return -ENOMEM;
625212d6c1d3SKees Cook 	size = SKB_WITH_OVERHEAD(size);
62536fa01ccdSSowmini Varadhan 
62546fa01ccdSSowmini Varadhan 	/* Copy real data, and all frags */
62556fa01ccdSSowmini Varadhan 	skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
62566fa01ccdSSowmini Varadhan 	skb->len -= off;
62576fa01ccdSSowmini Varadhan 
62586fa01ccdSSowmini Varadhan 	memcpy((struct skb_shared_info *)(data + size),
62596fa01ccdSSowmini Varadhan 	       skb_shinfo(skb),
62606fa01ccdSSowmini Varadhan 	       offsetof(struct skb_shared_info,
62616fa01ccdSSowmini Varadhan 			frags[skb_shinfo(skb)->nr_frags]));
62626fa01ccdSSowmini Varadhan 	if (skb_cloned(skb)) {
62636fa01ccdSSowmini Varadhan 		/* drop the old head gracefully */
62646fa01ccdSSowmini Varadhan 		if (skb_orphan_frags(skb, gfp_mask)) {
62656fa01ccdSSowmini Varadhan 			kfree(data);
62666fa01ccdSSowmini Varadhan 			return -ENOMEM;
62676fa01ccdSSowmini Varadhan 		}
62686fa01ccdSSowmini Varadhan 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
62696fa01ccdSSowmini Varadhan 			skb_frag_ref(skb, i);
62706fa01ccdSSowmini Varadhan 		if (skb_has_frag_list(skb))
62716fa01ccdSSowmini Varadhan 			skb_clone_fraglist(skb);
6272511a3edaSEric Dumazet 		skb_release_data(skb, SKB_CONSUMED);
62736fa01ccdSSowmini Varadhan 	} else {
62746fa01ccdSSowmini Varadhan 		/* we can reuse existing recount- all we did was
62756fa01ccdSSowmini Varadhan 		 * relocate values
62766fa01ccdSSowmini Varadhan 		 */
62776fa01ccdSSowmini Varadhan 		skb_free_head(skb);
62786fa01ccdSSowmini Varadhan 	}
62796fa01ccdSSowmini Varadhan 
62806fa01ccdSSowmini Varadhan 	skb->head = data;
62816fa01ccdSSowmini Varadhan 	skb->data = data;
62826fa01ccdSSowmini Varadhan 	skb->head_frag = 0;
6283763087daSEric Dumazet 	skb_set_end_offset(skb, size);
62846fa01ccdSSowmini Varadhan 	skb_set_tail_pointer(skb, skb_headlen(skb));
62856fa01ccdSSowmini Varadhan 	skb_headers_offset_update(skb, 0);
62866fa01ccdSSowmini Varadhan 	skb->cloned = 0;
62876fa01ccdSSowmini Varadhan 	skb->hdr_len = 0;
62886fa01ccdSSowmini Varadhan 	skb->nohdr = 0;
62896fa01ccdSSowmini Varadhan 	atomic_set(&skb_shinfo(skb)->dataref, 1);
62906fa01ccdSSowmini Varadhan 
62916fa01ccdSSowmini Varadhan 	return 0;
62926fa01ccdSSowmini Varadhan }
62936fa01ccdSSowmini Varadhan 
62946fa01ccdSSowmini Varadhan static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
62956fa01ccdSSowmini Varadhan 
62966fa01ccdSSowmini Varadhan /* carve out the first eat bytes from skb's frag_list. May recurse into
62976fa01ccdSSowmini Varadhan  * pskb_carve()
62986fa01ccdSSowmini Varadhan  */
62996fa01ccdSSowmini Varadhan static int pskb_carve_frag_list(struct sk_buff *skb,
63006fa01ccdSSowmini Varadhan 				struct skb_shared_info *shinfo, int eat,
63016fa01ccdSSowmini Varadhan 				gfp_t gfp_mask)
63026fa01ccdSSowmini Varadhan {
63036fa01ccdSSowmini Varadhan 	struct sk_buff *list = shinfo->frag_list;
63046fa01ccdSSowmini Varadhan 	struct sk_buff *clone = NULL;
63056fa01ccdSSowmini Varadhan 	struct sk_buff *insp = NULL;
63066fa01ccdSSowmini Varadhan 
63076fa01ccdSSowmini Varadhan 	do {
63086fa01ccdSSowmini Varadhan 		if (!list) {
63096fa01ccdSSowmini Varadhan 			pr_err("Not enough bytes to eat. Want %d\n", eat);
63106fa01ccdSSowmini Varadhan 			return -EFAULT;
63116fa01ccdSSowmini Varadhan 		}
63126fa01ccdSSowmini Varadhan 		if (list->len <= eat) {
63136fa01ccdSSowmini Varadhan 			/* Eaten as whole. */
63146fa01ccdSSowmini Varadhan 			eat -= list->len;
63156fa01ccdSSowmini Varadhan 			list = list->next;
63166fa01ccdSSowmini Varadhan 			insp = list;
63176fa01ccdSSowmini Varadhan 		} else {
63186fa01ccdSSowmini Varadhan 			/* Eaten partially. */
63196fa01ccdSSowmini Varadhan 			if (skb_shared(list)) {
63206fa01ccdSSowmini Varadhan 				clone = skb_clone(list, gfp_mask);
63216fa01ccdSSowmini Varadhan 				if (!clone)
63226fa01ccdSSowmini Varadhan 					return -ENOMEM;
63236fa01ccdSSowmini Varadhan 				insp = list->next;
63246fa01ccdSSowmini Varadhan 				list = clone;
63256fa01ccdSSowmini Varadhan 			} else {
63266fa01ccdSSowmini Varadhan 				/* This may be pulled without problems. */
63276fa01ccdSSowmini Varadhan 				insp = list;
63286fa01ccdSSowmini Varadhan 			}
63296fa01ccdSSowmini Varadhan 			if (pskb_carve(list, eat, gfp_mask) < 0) {
63306fa01ccdSSowmini Varadhan 				kfree_skb(clone);
63316fa01ccdSSowmini Varadhan 				return -ENOMEM;
63326fa01ccdSSowmini Varadhan 			}
63336fa01ccdSSowmini Varadhan 			break;
63346fa01ccdSSowmini Varadhan 		}
63356fa01ccdSSowmini Varadhan 	} while (eat);
63366fa01ccdSSowmini Varadhan 
63376fa01ccdSSowmini Varadhan 	/* Free pulled out fragments. */
63386fa01ccdSSowmini Varadhan 	while ((list = shinfo->frag_list) != insp) {
63396fa01ccdSSowmini Varadhan 		shinfo->frag_list = list->next;
6340ef527f96SEric Dumazet 		consume_skb(list);
63416fa01ccdSSowmini Varadhan 	}
63426fa01ccdSSowmini Varadhan 	/* And insert new clone at head. */
63436fa01ccdSSowmini Varadhan 	if (clone) {
63446fa01ccdSSowmini Varadhan 		clone->next = list;
63456fa01ccdSSowmini Varadhan 		shinfo->frag_list = clone;
63466fa01ccdSSowmini Varadhan 	}
63476fa01ccdSSowmini Varadhan 	return 0;
63486fa01ccdSSowmini Varadhan }
63496fa01ccdSSowmini Varadhan 
63506fa01ccdSSowmini Varadhan /* carve off first len bytes from skb. Split line (off) is in the
63516fa01ccdSSowmini Varadhan  * non-linear part of skb
63526fa01ccdSSowmini Varadhan  */
63536fa01ccdSSowmini Varadhan static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
63546fa01ccdSSowmini Varadhan 				       int pos, gfp_t gfp_mask)
63556fa01ccdSSowmini Varadhan {
63566fa01ccdSSowmini Varadhan 	int i, k = 0;
635712d6c1d3SKees Cook 	unsigned int size = skb_end_offset(skb);
63586fa01ccdSSowmini Varadhan 	u8 *data;
63596fa01ccdSSowmini Varadhan 	const int nfrags = skb_shinfo(skb)->nr_frags;
63606fa01ccdSSowmini Varadhan 	struct skb_shared_info *shinfo;
63616fa01ccdSSowmini Varadhan 
63626fa01ccdSSowmini Varadhan 	if (skb_pfmemalloc(skb))
63636fa01ccdSSowmini Varadhan 		gfp_mask |= __GFP_MEMALLOC;
636412d6c1d3SKees Cook 
636512d6c1d3SKees Cook 	size = SKB_DATA_ALIGN(size);
636612d6c1d3SKees Cook 	size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
636712d6c1d3SKees Cook 	size = kmalloc_size_roundup(size);
636812d6c1d3SKees Cook 	data = kmalloc_reserve(size, gfp_mask, NUMA_NO_NODE, NULL);
63696fa01ccdSSowmini Varadhan 	if (!data)
63706fa01ccdSSowmini Varadhan 		return -ENOMEM;
637112d6c1d3SKees Cook 	size = SKB_WITH_OVERHEAD(size);
63726fa01ccdSSowmini Varadhan 
63736fa01ccdSSowmini Varadhan 	memcpy((struct skb_shared_info *)(data + size),
6374e3ec1e8cSMiaohe Lin 	       skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
63756fa01ccdSSowmini Varadhan 	if (skb_orphan_frags(skb, gfp_mask)) {
63766fa01ccdSSowmini Varadhan 		kfree(data);
63776fa01ccdSSowmini Varadhan 		return -ENOMEM;
63786fa01ccdSSowmini Varadhan 	}
63796fa01ccdSSowmini Varadhan 	shinfo = (struct skb_shared_info *)(data + size);
63806fa01ccdSSowmini Varadhan 	for (i = 0; i < nfrags; i++) {
63816fa01ccdSSowmini Varadhan 		int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
63826fa01ccdSSowmini Varadhan 
63836fa01ccdSSowmini Varadhan 		if (pos + fsize > off) {
63846fa01ccdSSowmini Varadhan 			shinfo->frags[k] = skb_shinfo(skb)->frags[i];
63856fa01ccdSSowmini Varadhan 
63866fa01ccdSSowmini Varadhan 			if (pos < off) {
63876fa01ccdSSowmini Varadhan 				/* Split frag.
63886fa01ccdSSowmini Varadhan 				 * We have two variants in this case:
63896fa01ccdSSowmini Varadhan 				 * 1. Move all the frag to the second
63906fa01ccdSSowmini Varadhan 				 *    part, if it is possible. F.e.
63916fa01ccdSSowmini Varadhan 				 *    this approach is mandatory for TUX,
63926fa01ccdSSowmini Varadhan 				 *    where splitting is expensive.
63936fa01ccdSSowmini Varadhan 				 * 2. Split is accurately. We make this.
63946fa01ccdSSowmini Varadhan 				 */
6395b54c9d5bSJonathan Lemon 				skb_frag_off_add(&shinfo->frags[0], off - pos);
63966fa01ccdSSowmini Varadhan 				skb_frag_size_sub(&shinfo->frags[0], off - pos);
63976fa01ccdSSowmini Varadhan 			}
63986fa01ccdSSowmini Varadhan 			skb_frag_ref(skb, i);
63996fa01ccdSSowmini Varadhan 			k++;
64006fa01ccdSSowmini Varadhan 		}
64016fa01ccdSSowmini Varadhan 		pos += fsize;
64026fa01ccdSSowmini Varadhan 	}
64036fa01ccdSSowmini Varadhan 	shinfo->nr_frags = k;
64046fa01ccdSSowmini Varadhan 	if (skb_has_frag_list(skb))
64056fa01ccdSSowmini Varadhan 		skb_clone_fraglist(skb);
64066fa01ccdSSowmini Varadhan 
64076fa01ccdSSowmini Varadhan 	/* split line is in frag list */
6408eabe8618SMiaohe Lin 	if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6409eabe8618SMiaohe Lin 		/* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6410eabe8618SMiaohe Lin 		if (skb_has_frag_list(skb))
6411eabe8618SMiaohe Lin 			kfree_skb_list(skb_shinfo(skb)->frag_list);
6412eabe8618SMiaohe Lin 		kfree(data);
6413eabe8618SMiaohe Lin 		return -ENOMEM;
64146fa01ccdSSowmini Varadhan 	}
6415511a3edaSEric Dumazet 	skb_release_data(skb, SKB_CONSUMED);
64166fa01ccdSSowmini Varadhan 
64176fa01ccdSSowmini Varadhan 	skb->head = data;
64186fa01ccdSSowmini Varadhan 	skb->head_frag = 0;
64196fa01ccdSSowmini Varadhan 	skb->data = data;
6420763087daSEric Dumazet 	skb_set_end_offset(skb, size);
64216fa01ccdSSowmini Varadhan 	skb_reset_tail_pointer(skb);
64226fa01ccdSSowmini Varadhan 	skb_headers_offset_update(skb, 0);
64236fa01ccdSSowmini Varadhan 	skb->cloned   = 0;
64246fa01ccdSSowmini Varadhan 	skb->hdr_len  = 0;
64256fa01ccdSSowmini Varadhan 	skb->nohdr    = 0;
64266fa01ccdSSowmini Varadhan 	skb->len -= off;
64276fa01ccdSSowmini Varadhan 	skb->data_len = skb->len;
64286fa01ccdSSowmini Varadhan 	atomic_set(&skb_shinfo(skb)->dataref, 1);
64296fa01ccdSSowmini Varadhan 	return 0;
64306fa01ccdSSowmini Varadhan }
64316fa01ccdSSowmini Varadhan 
64326fa01ccdSSowmini Varadhan /* remove len bytes from the beginning of the skb */
64336fa01ccdSSowmini Varadhan static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
64346fa01ccdSSowmini Varadhan {
64356fa01ccdSSowmini Varadhan 	int headlen = skb_headlen(skb);
64366fa01ccdSSowmini Varadhan 
64376fa01ccdSSowmini Varadhan 	if (len < headlen)
64386fa01ccdSSowmini Varadhan 		return pskb_carve_inside_header(skb, len, headlen, gfp);
64396fa01ccdSSowmini Varadhan 	else
64406fa01ccdSSowmini Varadhan 		return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
64416fa01ccdSSowmini Varadhan }
64426fa01ccdSSowmini Varadhan 
64436fa01ccdSSowmini Varadhan /* Extract to_copy bytes starting at off from skb, and return this in
64446fa01ccdSSowmini Varadhan  * a new skb
64456fa01ccdSSowmini Varadhan  */
64466fa01ccdSSowmini Varadhan struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
64476fa01ccdSSowmini Varadhan 			     int to_copy, gfp_t gfp)
64486fa01ccdSSowmini Varadhan {
64496fa01ccdSSowmini Varadhan 	struct sk_buff  *clone = skb_clone(skb, gfp);
64506fa01ccdSSowmini Varadhan 
64516fa01ccdSSowmini Varadhan 	if (!clone)
64526fa01ccdSSowmini Varadhan 		return NULL;
64536fa01ccdSSowmini Varadhan 
64546fa01ccdSSowmini Varadhan 	if (pskb_carve(clone, off, gfp) < 0 ||
64556fa01ccdSSowmini Varadhan 	    pskb_trim(clone, to_copy)) {
64566fa01ccdSSowmini Varadhan 		kfree_skb(clone);
64576fa01ccdSSowmini Varadhan 		return NULL;
64586fa01ccdSSowmini Varadhan 	}
64596fa01ccdSSowmini Varadhan 	return clone;
64606fa01ccdSSowmini Varadhan }
64616fa01ccdSSowmini Varadhan EXPORT_SYMBOL(pskb_extract);
6462c8c8b127SEric Dumazet 
6463c8c8b127SEric Dumazet /**
6464c8c8b127SEric Dumazet  * skb_condense - try to get rid of fragments/frag_list if possible
6465c8c8b127SEric Dumazet  * @skb: buffer
6466c8c8b127SEric Dumazet  *
6467c8c8b127SEric Dumazet  * Can be used to save memory before skb is added to a busy queue.
6468c8c8b127SEric Dumazet  * If packet has bytes in frags and enough tail room in skb->head,
6469c8c8b127SEric Dumazet  * pull all of them, so that we can free the frags right now and adjust
6470c8c8b127SEric Dumazet  * truesize.
6471c8c8b127SEric Dumazet  * Notes:
6472c8c8b127SEric Dumazet  *	We do not reallocate skb->head thus can not fail.
6473c8c8b127SEric Dumazet  *	Caller must re-evaluate skb->truesize if needed.
6474c8c8b127SEric Dumazet  */
6475c8c8b127SEric Dumazet void skb_condense(struct sk_buff *skb)
6476c8c8b127SEric Dumazet {
64773174fed9SEric Dumazet 	if (skb->data_len) {
64783174fed9SEric Dumazet 		if (skb->data_len > skb->end - skb->tail ||
6479c8c8b127SEric Dumazet 		    skb_cloned(skb))
6480c8c8b127SEric Dumazet 			return;
6481c8c8b127SEric Dumazet 
6482c8c8b127SEric Dumazet 		/* Nice, we can free page frag(s) right now */
6483c8c8b127SEric Dumazet 		__pskb_pull_tail(skb, skb->data_len);
64843174fed9SEric Dumazet 	}
64853174fed9SEric Dumazet 	/* At this point, skb->truesize might be over estimated,
64863174fed9SEric Dumazet 	 * because skb had a fragment, and fragments do not tell
64873174fed9SEric Dumazet 	 * their truesize.
64883174fed9SEric Dumazet 	 * When we pulled its content into skb->head, fragment
64893174fed9SEric Dumazet 	 * was freed, but __pskb_pull_tail() could not possibly
64903174fed9SEric Dumazet 	 * adjust skb->truesize, not knowing the frag truesize.
6491c8c8b127SEric Dumazet 	 */
6492c8c8b127SEric Dumazet 	skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6493c8c8b127SEric Dumazet }
6494d57a3a15SDavid Howells EXPORT_SYMBOL(skb_condense);
6495df5042f4SFlorian Westphal 
6496df5042f4SFlorian Westphal #ifdef CONFIG_SKB_EXTENSIONS
6497df5042f4SFlorian Westphal static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6498df5042f4SFlorian Westphal {
6499df5042f4SFlorian Westphal 	return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6500df5042f4SFlorian Westphal }
6501df5042f4SFlorian Westphal 
65028b69a803SPaolo Abeni /**
65038b69a803SPaolo Abeni  * __skb_ext_alloc - allocate a new skb extensions storage
65048b69a803SPaolo Abeni  *
65054930f483SFlorian Westphal  * @flags: See kmalloc().
65064930f483SFlorian Westphal  *
65078b69a803SPaolo Abeni  * Returns the newly allocated pointer. The pointer can later attached to a
65088b69a803SPaolo Abeni  * skb via __skb_ext_set().
65098b69a803SPaolo Abeni  * Note: caller must handle the skb_ext as an opaque data.
65108b69a803SPaolo Abeni  */
65114930f483SFlorian Westphal struct skb_ext *__skb_ext_alloc(gfp_t flags)
6512df5042f4SFlorian Westphal {
65134930f483SFlorian Westphal 	struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6514df5042f4SFlorian Westphal 
6515df5042f4SFlorian Westphal 	if (new) {
6516df5042f4SFlorian Westphal 		memset(new->offset, 0, sizeof(new->offset));
6517df5042f4SFlorian Westphal 		refcount_set(&new->refcnt, 1);
6518df5042f4SFlorian Westphal 	}
6519df5042f4SFlorian Westphal 
6520df5042f4SFlorian Westphal 	return new;
6521df5042f4SFlorian Westphal }
6522df5042f4SFlorian Westphal 
65234165079bSFlorian Westphal static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
65244165079bSFlorian Westphal 					 unsigned int old_active)
6525df5042f4SFlorian Westphal {
6526df5042f4SFlorian Westphal 	struct skb_ext *new;
6527df5042f4SFlorian Westphal 
6528df5042f4SFlorian Westphal 	if (refcount_read(&old->refcnt) == 1)
6529df5042f4SFlorian Westphal 		return old;
6530df5042f4SFlorian Westphal 
6531df5042f4SFlorian Westphal 	new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6532df5042f4SFlorian Westphal 	if (!new)
6533df5042f4SFlorian Westphal 		return NULL;
6534df5042f4SFlorian Westphal 
6535df5042f4SFlorian Westphal 	memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6536df5042f4SFlorian Westphal 	refcount_set(&new->refcnt, 1);
6537df5042f4SFlorian Westphal 
65384165079bSFlorian Westphal #ifdef CONFIG_XFRM
65394165079bSFlorian Westphal 	if (old_active & (1 << SKB_EXT_SEC_PATH)) {
65404165079bSFlorian Westphal 		struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
65414165079bSFlorian Westphal 		unsigned int i;
65424165079bSFlorian Westphal 
65434165079bSFlorian Westphal 		for (i = 0; i < sp->len; i++)
65444165079bSFlorian Westphal 			xfrm_state_hold(sp->xvec[i]);
65454165079bSFlorian Westphal 	}
65464165079bSFlorian Westphal #endif
6547df5042f4SFlorian Westphal 	__skb_ext_put(old);
6548df5042f4SFlorian Westphal 	return new;
6549df5042f4SFlorian Westphal }
6550df5042f4SFlorian Westphal 
6551df5042f4SFlorian Westphal /**
65528b69a803SPaolo Abeni  * __skb_ext_set - attach the specified extension storage to this skb
65538b69a803SPaolo Abeni  * @skb: buffer
65548b69a803SPaolo Abeni  * @id: extension id
65558b69a803SPaolo Abeni  * @ext: extension storage previously allocated via __skb_ext_alloc()
65568b69a803SPaolo Abeni  *
65578b69a803SPaolo Abeni  * Existing extensions, if any, are cleared.
65588b69a803SPaolo Abeni  *
65598b69a803SPaolo Abeni  * Returns the pointer to the extension.
65608b69a803SPaolo Abeni  */
65618b69a803SPaolo Abeni void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
65628b69a803SPaolo Abeni 		    struct skb_ext *ext)
65638b69a803SPaolo Abeni {
65648b69a803SPaolo Abeni 	unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
65658b69a803SPaolo Abeni 
65668b69a803SPaolo Abeni 	skb_ext_put(skb);
65678b69a803SPaolo Abeni 	newlen = newoff + skb_ext_type_len[id];
65688b69a803SPaolo Abeni 	ext->chunks = newlen;
65698b69a803SPaolo Abeni 	ext->offset[id] = newoff;
65708b69a803SPaolo Abeni 	skb->extensions = ext;
65718b69a803SPaolo Abeni 	skb->active_extensions = 1 << id;
65728b69a803SPaolo Abeni 	return skb_ext_get_ptr(ext, id);
65738b69a803SPaolo Abeni }
65748b69a803SPaolo Abeni 
65758b69a803SPaolo Abeni /**
6576df5042f4SFlorian Westphal  * skb_ext_add - allocate space for given extension, COW if needed
6577df5042f4SFlorian Westphal  * @skb: buffer
6578df5042f4SFlorian Westphal  * @id: extension to allocate space for
6579df5042f4SFlorian Westphal  *
6580df5042f4SFlorian Westphal  * Allocates enough space for the given extension.
6581df5042f4SFlorian Westphal  * If the extension is already present, a pointer to that extension
6582df5042f4SFlorian Westphal  * is returned.
6583df5042f4SFlorian Westphal  *
6584df5042f4SFlorian Westphal  * If the skb was cloned, COW applies and the returned memory can be
6585df5042f4SFlorian Westphal  * modified without changing the extension space of clones buffers.
6586df5042f4SFlorian Westphal  *
6587df5042f4SFlorian Westphal  * Returns pointer to the extension or NULL on allocation failure.
6588df5042f4SFlorian Westphal  */
6589df5042f4SFlorian Westphal void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6590df5042f4SFlorian Westphal {
6591df5042f4SFlorian Westphal 	struct skb_ext *new, *old = NULL;
6592df5042f4SFlorian Westphal 	unsigned int newlen, newoff;
6593df5042f4SFlorian Westphal 
6594df5042f4SFlorian Westphal 	if (skb->active_extensions) {
6595df5042f4SFlorian Westphal 		old = skb->extensions;
6596df5042f4SFlorian Westphal 
65974165079bSFlorian Westphal 		new = skb_ext_maybe_cow(old, skb->active_extensions);
6598df5042f4SFlorian Westphal 		if (!new)
6599df5042f4SFlorian Westphal 			return NULL;
6600df5042f4SFlorian Westphal 
6601682ec859SPaolo Abeni 		if (__skb_ext_exist(new, id))
6602df5042f4SFlorian Westphal 			goto set_active;
6603df5042f4SFlorian Westphal 
6604e94e50bdSPaolo Abeni 		newoff = new->chunks;
6605df5042f4SFlorian Westphal 	} else {
6606df5042f4SFlorian Westphal 		newoff = SKB_EXT_CHUNKSIZEOF(*new);
6607df5042f4SFlorian Westphal 
66084930f483SFlorian Westphal 		new = __skb_ext_alloc(GFP_ATOMIC);
6609df5042f4SFlorian Westphal 		if (!new)
6610df5042f4SFlorian Westphal 			return NULL;
6611df5042f4SFlorian Westphal 	}
6612df5042f4SFlorian Westphal 
6613df5042f4SFlorian Westphal 	newlen = newoff + skb_ext_type_len[id];
6614df5042f4SFlorian Westphal 	new->chunks = newlen;
6615df5042f4SFlorian Westphal 	new->offset[id] = newoff;
6616df5042f4SFlorian Westphal set_active:
6617b0999f38SPaolo Abeni 	skb->slow_gro = 1;
6618682ec859SPaolo Abeni 	skb->extensions = new;
6619df5042f4SFlorian Westphal 	skb->active_extensions |= 1 << id;
6620df5042f4SFlorian Westphal 	return skb_ext_get_ptr(new, id);
6621df5042f4SFlorian Westphal }
6622df5042f4SFlorian Westphal EXPORT_SYMBOL(skb_ext_add);
6623df5042f4SFlorian Westphal 
66244165079bSFlorian Westphal #ifdef CONFIG_XFRM
66254165079bSFlorian Westphal static void skb_ext_put_sp(struct sec_path *sp)
66264165079bSFlorian Westphal {
66274165079bSFlorian Westphal 	unsigned int i;
66284165079bSFlorian Westphal 
66294165079bSFlorian Westphal 	for (i = 0; i < sp->len; i++)
66304165079bSFlorian Westphal 		xfrm_state_put(sp->xvec[i]);
66314165079bSFlorian Westphal }
66324165079bSFlorian Westphal #endif
66334165079bSFlorian Westphal 
663478476d31SJeremy Kerr #ifdef CONFIG_MCTP_FLOWS
663578476d31SJeremy Kerr static void skb_ext_put_mctp(struct mctp_flow *flow)
663678476d31SJeremy Kerr {
663778476d31SJeremy Kerr 	if (flow->key)
663878476d31SJeremy Kerr 		mctp_key_unref(flow->key);
663978476d31SJeremy Kerr }
664078476d31SJeremy Kerr #endif
664178476d31SJeremy Kerr 
6642df5042f4SFlorian Westphal void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6643df5042f4SFlorian Westphal {
6644df5042f4SFlorian Westphal 	struct skb_ext *ext = skb->extensions;
6645df5042f4SFlorian Westphal 
6646df5042f4SFlorian Westphal 	skb->active_extensions &= ~(1 << id);
6647df5042f4SFlorian Westphal 	if (skb->active_extensions == 0) {
6648df5042f4SFlorian Westphal 		skb->extensions = NULL;
6649df5042f4SFlorian Westphal 		__skb_ext_put(ext);
66504165079bSFlorian Westphal #ifdef CONFIG_XFRM
66514165079bSFlorian Westphal 	} else if (id == SKB_EXT_SEC_PATH &&
66524165079bSFlorian Westphal 		   refcount_read(&ext->refcnt) == 1) {
66534165079bSFlorian Westphal 		struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
66544165079bSFlorian Westphal 
66554165079bSFlorian Westphal 		skb_ext_put_sp(sp);
66564165079bSFlorian Westphal 		sp->len = 0;
66574165079bSFlorian Westphal #endif
6658df5042f4SFlorian Westphal 	}
6659df5042f4SFlorian Westphal }
6660df5042f4SFlorian Westphal EXPORT_SYMBOL(__skb_ext_del);
6661df5042f4SFlorian Westphal 
6662df5042f4SFlorian Westphal void __skb_ext_put(struct skb_ext *ext)
6663df5042f4SFlorian Westphal {
6664df5042f4SFlorian Westphal 	/* If this is last clone, nothing can increment
6665df5042f4SFlorian Westphal 	 * it after check passes.  Avoids one atomic op.
6666df5042f4SFlorian Westphal 	 */
6667df5042f4SFlorian Westphal 	if (refcount_read(&ext->refcnt) == 1)
6668df5042f4SFlorian Westphal 		goto free_now;
6669df5042f4SFlorian Westphal 
6670df5042f4SFlorian Westphal 	if (!refcount_dec_and_test(&ext->refcnt))
6671df5042f4SFlorian Westphal 		return;
6672df5042f4SFlorian Westphal free_now:
66734165079bSFlorian Westphal #ifdef CONFIG_XFRM
66744165079bSFlorian Westphal 	if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
66754165079bSFlorian Westphal 		skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
66764165079bSFlorian Westphal #endif
667778476d31SJeremy Kerr #ifdef CONFIG_MCTP_FLOWS
667878476d31SJeremy Kerr 	if (__skb_ext_exist(ext, SKB_EXT_MCTP))
667978476d31SJeremy Kerr 		skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
668078476d31SJeremy Kerr #endif
66814165079bSFlorian Westphal 
6682df5042f4SFlorian Westphal 	kmem_cache_free(skbuff_ext_cache, ext);
6683df5042f4SFlorian Westphal }
6684df5042f4SFlorian Westphal EXPORT_SYMBOL(__skb_ext_put);
6685df5042f4SFlorian Westphal #endif /* CONFIG_SKB_EXTENSIONS */
668668822bdfSEric Dumazet 
668768822bdfSEric Dumazet /**
668868822bdfSEric Dumazet  * skb_attempt_defer_free - queue skb for remote freeing
668968822bdfSEric Dumazet  * @skb: buffer
669068822bdfSEric Dumazet  *
669168822bdfSEric Dumazet  * Put @skb in a per-cpu list, using the cpu which
669268822bdfSEric Dumazet  * allocated the skb/pages to reduce false sharing
669368822bdfSEric Dumazet  * and memory zone spinlock contention.
669468822bdfSEric Dumazet  */
669568822bdfSEric Dumazet void skb_attempt_defer_free(struct sk_buff *skb)
669668822bdfSEric Dumazet {
669768822bdfSEric Dumazet 	int cpu = skb->alloc_cpu;
669868822bdfSEric Dumazet 	struct softnet_data *sd;
669968822bdfSEric Dumazet 	unsigned long flags;
670039564c3fSEric Dumazet 	unsigned int defer_max;
670168822bdfSEric Dumazet 	bool kick;
670268822bdfSEric Dumazet 
670368822bdfSEric Dumazet 	if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
670468822bdfSEric Dumazet 	    !cpu_online(cpu) ||
670568822bdfSEric Dumazet 	    cpu == raw_smp_processor_id()) {
670639564c3fSEric Dumazet nodefer:	__kfree_skb(skb);
670768822bdfSEric Dumazet 		return;
670868822bdfSEric Dumazet 	}
670968822bdfSEric Dumazet 
671068822bdfSEric Dumazet 	sd = &per_cpu(softnet_data, cpu);
671139564c3fSEric Dumazet 	defer_max = READ_ONCE(sysctl_skb_defer_max);
671239564c3fSEric Dumazet 	if (READ_ONCE(sd->defer_count) >= defer_max)
671339564c3fSEric Dumazet 		goto nodefer;
671439564c3fSEric Dumazet 
671568822bdfSEric Dumazet 	spin_lock_irqsave(&sd->defer_lock, flags);
6716c09b0cd2SJakub Kicinski 	/* Send an IPI every time queue reaches half capacity. */
6717c09b0cd2SJakub Kicinski 	kick = sd->defer_count == (defer_max >> 1);
6718c09b0cd2SJakub Kicinski 	/* Paired with the READ_ONCE() few lines above */
6719c09b0cd2SJakub Kicinski 	WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6720c09b0cd2SJakub Kicinski 
672168822bdfSEric Dumazet 	skb->next = sd->defer_list;
672268822bdfSEric Dumazet 	/* Paired with READ_ONCE() in skb_defer_free_flush() */
672368822bdfSEric Dumazet 	WRITE_ONCE(sd->defer_list, skb);
672468822bdfSEric Dumazet 	spin_unlock_irqrestore(&sd->defer_lock, flags);
672568822bdfSEric Dumazet 
672668822bdfSEric Dumazet 	/* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
672768822bdfSEric Dumazet 	 * if we are unlucky enough (this seems very unlikely).
672868822bdfSEric Dumazet 	 */
672997e719a8SEric Dumazet 	if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
673068822bdfSEric Dumazet 		smp_call_function_single_async(cpu, &sd->defer_csd);
673168822bdfSEric Dumazet }
6732