xref: /openbmc/linux/net/core/skbuff.c (revision e7d2b510)
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[] = {
979cb252c4SMenglong Dong 	DEFINE_DROP_REASON(FN, FN)
989cb252c4SMenglong Dong };
99ec43908dSMenglong Dong EXPORT_SYMBOL(drop_reasons);
100ec43908dSMenglong Dong 
1011da177e4SLinus Torvalds /**
102f05de73bSJean Sacren  *	skb_panic - private function for out-of-line support
1031da177e4SLinus Torvalds  *	@skb:	buffer
1041da177e4SLinus Torvalds  *	@sz:	size
105f05de73bSJean Sacren  *	@addr:	address
10699d5851eSJames Hogan  *	@msg:	skb_over_panic or skb_under_panic
1071da177e4SLinus Torvalds  *
108f05de73bSJean Sacren  *	Out-of-line support for skb_put() and skb_push().
109f05de73bSJean Sacren  *	Called via the wrapper skb_over_panic() or skb_under_panic().
110f05de73bSJean Sacren  *	Keep out of line to prevent kernel bloat.
111f05de73bSJean Sacren  *	__builtin_return_address is not used because it is not always reliable.
1121da177e4SLinus Torvalds  */
113f05de73bSJean Sacren static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
11499d5851eSJames Hogan 		      const char msg[])
1151da177e4SLinus Torvalds {
11641a46913SJesper Dangaard Brouer 	pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
11799d5851eSJames Hogan 		 msg, addr, skb->len, sz, skb->head, skb->data,
1184305b541SArnaldo Carvalho de Melo 		 (unsigned long)skb->tail, (unsigned long)skb->end,
11926095455SPatrick McHardy 		 skb->dev ? skb->dev->name : "<NULL>");
1201da177e4SLinus Torvalds 	BUG();
1211da177e4SLinus Torvalds }
1221da177e4SLinus Torvalds 
123f05de73bSJean Sacren static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
1241da177e4SLinus Torvalds {
125f05de73bSJean Sacren 	skb_panic(skb, sz, addr, __func__);
1261da177e4SLinus Torvalds }
1271da177e4SLinus Torvalds 
128f05de73bSJean Sacren static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
129f05de73bSJean Sacren {
130f05de73bSJean Sacren 	skb_panic(skb, sz, addr, __func__);
131f05de73bSJean Sacren }
132c93bdd0eSMel Gorman 
13350fad4b5SAlexander Lobakin #define NAPI_SKB_CACHE_SIZE	64
134f450d539SAlexander Lobakin #define NAPI_SKB_CACHE_BULK	16
135f450d539SAlexander Lobakin #define NAPI_SKB_CACHE_HALF	(NAPI_SKB_CACHE_SIZE / 2)
13650fad4b5SAlexander Lobakin 
13750fad4b5SAlexander Lobakin struct napi_alloc_cache {
13850fad4b5SAlexander Lobakin 	struct page_frag_cache page;
13950fad4b5SAlexander Lobakin 	unsigned int skb_count;
14050fad4b5SAlexander Lobakin 	void *skb_cache[NAPI_SKB_CACHE_SIZE];
14150fad4b5SAlexander Lobakin };
14250fad4b5SAlexander Lobakin 
14350fad4b5SAlexander Lobakin static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
14450fad4b5SAlexander Lobakin static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
14550fad4b5SAlexander Lobakin 
14632e3573fSYajun Deng void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
14750fad4b5SAlexander Lobakin {
14850fad4b5SAlexander Lobakin 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
14950fad4b5SAlexander Lobakin 
15050fad4b5SAlexander Lobakin 	fragsz = SKB_DATA_ALIGN(fragsz);
15150fad4b5SAlexander Lobakin 
15232e3573fSYajun Deng 	return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
15350fad4b5SAlexander Lobakin }
15450fad4b5SAlexander Lobakin EXPORT_SYMBOL(__napi_alloc_frag_align);
15550fad4b5SAlexander Lobakin 
15650fad4b5SAlexander Lobakin void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
15750fad4b5SAlexander Lobakin {
15850fad4b5SAlexander Lobakin 	void *data;
15950fad4b5SAlexander Lobakin 
16050fad4b5SAlexander Lobakin 	fragsz = SKB_DATA_ALIGN(fragsz);
161afa79d08SChangbin Du 	if (in_hardirq() || irqs_disabled()) {
16232e3573fSYajun Deng 		struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
16332e3573fSYajun Deng 
16450fad4b5SAlexander Lobakin 		data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
16550fad4b5SAlexander Lobakin 	} else {
16632e3573fSYajun Deng 		struct napi_alloc_cache *nc;
16732e3573fSYajun Deng 
16850fad4b5SAlexander Lobakin 		local_bh_disable();
16932e3573fSYajun Deng 		nc = this_cpu_ptr(&napi_alloc_cache);
17032e3573fSYajun Deng 		data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
17150fad4b5SAlexander Lobakin 		local_bh_enable();
17250fad4b5SAlexander Lobakin 	}
17350fad4b5SAlexander Lobakin 	return data;
17450fad4b5SAlexander Lobakin }
17550fad4b5SAlexander Lobakin EXPORT_SYMBOL(__netdev_alloc_frag_align);
17650fad4b5SAlexander Lobakin 
177f450d539SAlexander Lobakin static struct sk_buff *napi_skb_cache_get(void)
178f450d539SAlexander Lobakin {
179f450d539SAlexander Lobakin 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
180f450d539SAlexander Lobakin 	struct sk_buff *skb;
181f450d539SAlexander Lobakin 
18249ae83fcSSieng Piaw Liew 	if (unlikely(!nc->skb_count)) {
183f450d539SAlexander Lobakin 		nc->skb_count = kmem_cache_alloc_bulk(skbuff_head_cache,
184f450d539SAlexander Lobakin 						      GFP_ATOMIC,
185f450d539SAlexander Lobakin 						      NAPI_SKB_CACHE_BULK,
186f450d539SAlexander Lobakin 						      nc->skb_cache);
187f450d539SAlexander Lobakin 		if (unlikely(!nc->skb_count))
188f450d539SAlexander Lobakin 			return NULL;
18949ae83fcSSieng Piaw Liew 	}
190f450d539SAlexander Lobakin 
191f450d539SAlexander Lobakin 	skb = nc->skb_cache[--nc->skb_count];
192f450d539SAlexander Lobakin 	kasan_unpoison_object_data(skbuff_head_cache, skb);
193f450d539SAlexander Lobakin 
194f450d539SAlexander Lobakin 	return skb;
195f450d539SAlexander Lobakin }
196f450d539SAlexander Lobakin 
197ba0509b6SJesper Dangaard Brouer /* Caller must provide SKB that is memset cleared */
198483126b3SAlexander Lobakin static void __build_skb_around(struct sk_buff *skb, void *data,
199483126b3SAlexander Lobakin 			       unsigned int frag_size)
200ba0509b6SJesper Dangaard Brouer {
201ba0509b6SJesper Dangaard Brouer 	struct skb_shared_info *shinfo;
202ba0509b6SJesper Dangaard Brouer 	unsigned int size = frag_size ? : ksize(data);
203ba0509b6SJesper Dangaard Brouer 
204ba0509b6SJesper Dangaard Brouer 	size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
205ba0509b6SJesper Dangaard Brouer 
206ba0509b6SJesper Dangaard Brouer 	/* Assumes caller memset cleared SKB */
207ba0509b6SJesper Dangaard Brouer 	skb->truesize = SKB_TRUESIZE(size);
208ba0509b6SJesper Dangaard Brouer 	refcount_set(&skb->users, 1);
209ba0509b6SJesper Dangaard Brouer 	skb->head = data;
210ba0509b6SJesper Dangaard Brouer 	skb->data = data;
211ba0509b6SJesper Dangaard Brouer 	skb_reset_tail_pointer(skb);
212763087daSEric Dumazet 	skb_set_end_offset(skb, size);
213ba0509b6SJesper Dangaard Brouer 	skb->mac_header = (typeof(skb->mac_header))~0U;
214ba0509b6SJesper Dangaard Brouer 	skb->transport_header = (typeof(skb->transport_header))~0U;
21568822bdfSEric Dumazet 	skb->alloc_cpu = raw_smp_processor_id();
216ba0509b6SJesper Dangaard Brouer 	/* make sure we initialize shinfo sequentially */
217ba0509b6SJesper Dangaard Brouer 	shinfo = skb_shinfo(skb);
218ba0509b6SJesper Dangaard Brouer 	memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
219ba0509b6SJesper Dangaard Brouer 	atomic_set(&shinfo->dataref, 1);
220ba0509b6SJesper Dangaard Brouer 
2216370cc3bSAleksandr Nogikh 	skb_set_kcov_handle(skb, kcov_common_handle());
222ba0509b6SJesper Dangaard Brouer }
223ba0509b6SJesper Dangaard Brouer 
2241da177e4SLinus Torvalds /**
2252ea2f62cSEric Dumazet  * __build_skb - build a network buffer
226b2b5ce9dSEric Dumazet  * @data: data buffer provided by caller
2272ea2f62cSEric Dumazet  * @frag_size: size of data, or 0 if head was kmalloced
228b2b5ce9dSEric Dumazet  *
229b2b5ce9dSEric Dumazet  * Allocate a new &sk_buff. Caller provides space holding head and
230deceb4c0SFlorian Fainelli  * skb_shared_info. @data must have been allocated by kmalloc() only if
2312ea2f62cSEric Dumazet  * @frag_size is 0, otherwise data should come from the page allocator
2322ea2f62cSEric Dumazet  *  or vmalloc()
233b2b5ce9dSEric Dumazet  * The return is the new skb buffer.
234b2b5ce9dSEric Dumazet  * On a failure the return is %NULL, and @data is not freed.
235b2b5ce9dSEric Dumazet  * Notes :
236b2b5ce9dSEric Dumazet  *  Before IO, driver allocates only data buffer where NIC put incoming frame
237b2b5ce9dSEric Dumazet  *  Driver should add room at head (NET_SKB_PAD) and
238b2b5ce9dSEric Dumazet  *  MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
239b2b5ce9dSEric Dumazet  *  After IO, driver calls build_skb(), to allocate sk_buff and populate it
240b2b5ce9dSEric Dumazet  *  before giving packet to stack.
241b2b5ce9dSEric Dumazet  *  RX rings only contains data buffers, not full skbs.
242b2b5ce9dSEric Dumazet  */
2432ea2f62cSEric Dumazet struct sk_buff *__build_skb(void *data, unsigned int frag_size)
244b2b5ce9dSEric Dumazet {
245b2b5ce9dSEric Dumazet 	struct sk_buff *skb;
246b2b5ce9dSEric Dumazet 
247b2b5ce9dSEric Dumazet 	skb = kmem_cache_alloc(skbuff_head_cache, GFP_ATOMIC);
248ba0509b6SJesper Dangaard Brouer 	if (unlikely(!skb))
249b2b5ce9dSEric Dumazet 		return NULL;
250b2b5ce9dSEric Dumazet 
251b2b5ce9dSEric Dumazet 	memset(skb, 0, offsetof(struct sk_buff, tail));
252483126b3SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
253b2b5ce9dSEric Dumazet 
254483126b3SAlexander Lobakin 	return skb;
255b2b5ce9dSEric Dumazet }
2562ea2f62cSEric Dumazet 
2572ea2f62cSEric Dumazet /* build_skb() is wrapper over __build_skb(), that specifically
2582ea2f62cSEric Dumazet  * takes care of skb->head and skb->pfmemalloc
2592ea2f62cSEric Dumazet  * This means that if @frag_size is not zero, then @data must be backed
2602ea2f62cSEric Dumazet  * by a page fragment, not kmalloc() or vmalloc()
2612ea2f62cSEric Dumazet  */
2622ea2f62cSEric Dumazet struct sk_buff *build_skb(void *data, unsigned int frag_size)
2632ea2f62cSEric Dumazet {
2642ea2f62cSEric Dumazet 	struct sk_buff *skb = __build_skb(data, frag_size);
2652ea2f62cSEric Dumazet 
2662ea2f62cSEric Dumazet 	if (skb && frag_size) {
2672ea2f62cSEric Dumazet 		skb->head_frag = 1;
2682f064f34SMichal Hocko 		if (page_is_pfmemalloc(virt_to_head_page(data)))
2692ea2f62cSEric Dumazet 			skb->pfmemalloc = 1;
2702ea2f62cSEric Dumazet 	}
2712ea2f62cSEric Dumazet 	return skb;
2722ea2f62cSEric Dumazet }
273b2b5ce9dSEric Dumazet EXPORT_SYMBOL(build_skb);
274b2b5ce9dSEric Dumazet 
275ba0509b6SJesper Dangaard Brouer /**
276ba0509b6SJesper Dangaard Brouer  * build_skb_around - build a network buffer around provided skb
277ba0509b6SJesper Dangaard Brouer  * @skb: sk_buff provide by caller, must be memset cleared
278ba0509b6SJesper Dangaard Brouer  * @data: data buffer provided by caller
279ba0509b6SJesper Dangaard Brouer  * @frag_size: size of data, or 0 if head was kmalloced
280ba0509b6SJesper Dangaard Brouer  */
281ba0509b6SJesper Dangaard Brouer struct sk_buff *build_skb_around(struct sk_buff *skb,
282ba0509b6SJesper Dangaard Brouer 				 void *data, unsigned int frag_size)
283ba0509b6SJesper Dangaard Brouer {
284ba0509b6SJesper Dangaard Brouer 	if (unlikely(!skb))
285ba0509b6SJesper Dangaard Brouer 		return NULL;
286ba0509b6SJesper Dangaard Brouer 
287483126b3SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
288ba0509b6SJesper Dangaard Brouer 
289483126b3SAlexander Lobakin 	if (frag_size) {
290ba0509b6SJesper Dangaard Brouer 		skb->head_frag = 1;
291ba0509b6SJesper Dangaard Brouer 		if (page_is_pfmemalloc(virt_to_head_page(data)))
292ba0509b6SJesper Dangaard Brouer 			skb->pfmemalloc = 1;
293ba0509b6SJesper Dangaard Brouer 	}
294ba0509b6SJesper Dangaard Brouer 	return skb;
295ba0509b6SJesper Dangaard Brouer }
296ba0509b6SJesper Dangaard Brouer EXPORT_SYMBOL(build_skb_around);
297ba0509b6SJesper Dangaard Brouer 
298f450d539SAlexander Lobakin /**
299f450d539SAlexander Lobakin  * __napi_build_skb - build a network buffer
300f450d539SAlexander Lobakin  * @data: data buffer provided by caller
301f450d539SAlexander Lobakin  * @frag_size: size of data, or 0 if head was kmalloced
302f450d539SAlexander Lobakin  *
303f450d539SAlexander Lobakin  * Version of __build_skb() that uses NAPI percpu caches to obtain
304f450d539SAlexander Lobakin  * skbuff_head instead of inplace allocation.
305f450d539SAlexander Lobakin  *
306f450d539SAlexander Lobakin  * Returns a new &sk_buff on success, %NULL on allocation failure.
307f450d539SAlexander Lobakin  */
308f450d539SAlexander Lobakin static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
309f450d539SAlexander Lobakin {
310f450d539SAlexander Lobakin 	struct sk_buff *skb;
311f450d539SAlexander Lobakin 
312f450d539SAlexander Lobakin 	skb = napi_skb_cache_get();
313f450d539SAlexander Lobakin 	if (unlikely(!skb))
314f450d539SAlexander Lobakin 		return NULL;
315f450d539SAlexander Lobakin 
316f450d539SAlexander Lobakin 	memset(skb, 0, offsetof(struct sk_buff, tail));
317f450d539SAlexander Lobakin 	__build_skb_around(skb, data, frag_size);
318f450d539SAlexander Lobakin 
319f450d539SAlexander Lobakin 	return skb;
320f450d539SAlexander Lobakin }
321f450d539SAlexander Lobakin 
322f450d539SAlexander Lobakin /**
323f450d539SAlexander Lobakin  * napi_build_skb - build a network buffer
324f450d539SAlexander Lobakin  * @data: data buffer provided by caller
325f450d539SAlexander Lobakin  * @frag_size: size of data, or 0 if head was kmalloced
326f450d539SAlexander Lobakin  *
327f450d539SAlexander Lobakin  * Version of __napi_build_skb() that takes care of skb->head_frag
328f450d539SAlexander Lobakin  * and skb->pfmemalloc when the data is a page or page fragment.
329f450d539SAlexander Lobakin  *
330f450d539SAlexander Lobakin  * Returns a new &sk_buff on success, %NULL on allocation failure.
331f450d539SAlexander Lobakin  */
332f450d539SAlexander Lobakin struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
333f450d539SAlexander Lobakin {
334f450d539SAlexander Lobakin 	struct sk_buff *skb = __napi_build_skb(data, frag_size);
335f450d539SAlexander Lobakin 
336f450d539SAlexander Lobakin 	if (likely(skb) && frag_size) {
337f450d539SAlexander Lobakin 		skb->head_frag = 1;
338f450d539SAlexander Lobakin 		skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
339f450d539SAlexander Lobakin 	}
340f450d539SAlexander Lobakin 
341f450d539SAlexander Lobakin 	return skb;
342f450d539SAlexander Lobakin }
343f450d539SAlexander Lobakin EXPORT_SYMBOL(napi_build_skb);
344f450d539SAlexander Lobakin 
3455381b23dSAlexander Lobakin /*
3465381b23dSAlexander Lobakin  * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
3475381b23dSAlexander Lobakin  * the caller if emergency pfmemalloc reserves are being used. If it is and
3485381b23dSAlexander Lobakin  * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
3495381b23dSAlexander Lobakin  * may be used. Otherwise, the packet data may be discarded until enough
3505381b23dSAlexander Lobakin  * memory is free
3515381b23dSAlexander Lobakin  */
352ef28095fSAlexander Lobakin static void *kmalloc_reserve(size_t size, gfp_t flags, int node,
353ef28095fSAlexander Lobakin 			     bool *pfmemalloc)
3545381b23dSAlexander Lobakin {
3555381b23dSAlexander Lobakin 	void *obj;
3565381b23dSAlexander Lobakin 	bool ret_pfmemalloc = false;
3575381b23dSAlexander Lobakin 
3585381b23dSAlexander Lobakin 	/*
3595381b23dSAlexander Lobakin 	 * Try a regular allocation, when that fails and we're not entitled
3605381b23dSAlexander Lobakin 	 * to the reserves, fail.
3615381b23dSAlexander Lobakin 	 */
3625381b23dSAlexander Lobakin 	obj = kmalloc_node_track_caller(size,
3635381b23dSAlexander Lobakin 					flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
3645381b23dSAlexander Lobakin 					node);
3655381b23dSAlexander Lobakin 	if (obj || !(gfp_pfmemalloc_allowed(flags)))
3665381b23dSAlexander Lobakin 		goto out;
3675381b23dSAlexander Lobakin 
3685381b23dSAlexander Lobakin 	/* Try again but now we are using pfmemalloc reserves */
3695381b23dSAlexander Lobakin 	ret_pfmemalloc = true;
3705381b23dSAlexander Lobakin 	obj = kmalloc_node_track_caller(size, flags, node);
3715381b23dSAlexander Lobakin 
3725381b23dSAlexander Lobakin out:
3735381b23dSAlexander Lobakin 	if (pfmemalloc)
3745381b23dSAlexander Lobakin 		*pfmemalloc = ret_pfmemalloc;
3755381b23dSAlexander Lobakin 
3765381b23dSAlexander Lobakin 	return obj;
3775381b23dSAlexander Lobakin }
3785381b23dSAlexander Lobakin 
3795381b23dSAlexander Lobakin /* 	Allocate a new skbuff. We do this ourselves so we can fill in a few
3805381b23dSAlexander Lobakin  *	'private' fields and also do memory statistics to find all the
3815381b23dSAlexander Lobakin  *	[BEEP] leaks.
3825381b23dSAlexander Lobakin  *
3835381b23dSAlexander Lobakin  */
3845381b23dSAlexander Lobakin 
3855381b23dSAlexander Lobakin /**
3865381b23dSAlexander Lobakin  *	__alloc_skb	-	allocate a network buffer
3875381b23dSAlexander Lobakin  *	@size: size to allocate
3885381b23dSAlexander Lobakin  *	@gfp_mask: allocation mask
3895381b23dSAlexander Lobakin  *	@flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
3905381b23dSAlexander Lobakin  *		instead of head cache and allocate a cloned (child) skb.
3915381b23dSAlexander Lobakin  *		If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
3925381b23dSAlexander Lobakin  *		allocations in case the data is required for writeback
3935381b23dSAlexander Lobakin  *	@node: numa node to allocate memory on
3945381b23dSAlexander Lobakin  *
3955381b23dSAlexander Lobakin  *	Allocate a new &sk_buff. The returned buffer has no headroom and a
3965381b23dSAlexander Lobakin  *	tail room of at least size bytes. The object has a reference count
3975381b23dSAlexander Lobakin  *	of one. The return is the buffer. On a failure the return is %NULL.
3985381b23dSAlexander Lobakin  *
3995381b23dSAlexander Lobakin  *	Buffers may only be allocated from interrupts using a @gfp_mask of
4005381b23dSAlexander Lobakin  *	%GFP_ATOMIC.
4015381b23dSAlexander Lobakin  */
4025381b23dSAlexander Lobakin struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
4035381b23dSAlexander Lobakin 			    int flags, int node)
4045381b23dSAlexander Lobakin {
4055381b23dSAlexander Lobakin 	struct kmem_cache *cache;
4065381b23dSAlexander Lobakin 	struct sk_buff *skb;
407a5df6333SLi RongQing 	unsigned int osize;
4085381b23dSAlexander Lobakin 	bool pfmemalloc;
409a5df6333SLi RongQing 	u8 *data;
4105381b23dSAlexander Lobakin 
4115381b23dSAlexander Lobakin 	cache = (flags & SKB_ALLOC_FCLONE)
4125381b23dSAlexander Lobakin 		? skbuff_fclone_cache : skbuff_head_cache;
4135381b23dSAlexander Lobakin 
4145381b23dSAlexander Lobakin 	if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
4155381b23dSAlexander Lobakin 		gfp_mask |= __GFP_MEMALLOC;
4165381b23dSAlexander Lobakin 
4175381b23dSAlexander Lobakin 	/* Get the HEAD */
418d13612b5SAlexander Lobakin 	if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
419d13612b5SAlexander Lobakin 	    likely(node == NUMA_NO_NODE || node == numa_mem_id()))
420d13612b5SAlexander Lobakin 		skb = napi_skb_cache_get();
421d13612b5SAlexander Lobakin 	else
422d13612b5SAlexander Lobakin 		skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
423df1ae022SAlexander Lobakin 	if (unlikely(!skb))
424df1ae022SAlexander Lobakin 		return NULL;
4255381b23dSAlexander Lobakin 	prefetchw(skb);
4265381b23dSAlexander Lobakin 
4275381b23dSAlexander Lobakin 	/* We do our best to align skb_shared_info on a separate cache
4285381b23dSAlexander Lobakin 	 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
4295381b23dSAlexander Lobakin 	 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
4305381b23dSAlexander Lobakin 	 * Both skb->head and skb_shared_info are cache line aligned.
4315381b23dSAlexander Lobakin 	 */
4325381b23dSAlexander Lobakin 	size = SKB_DATA_ALIGN(size);
4335381b23dSAlexander Lobakin 	size += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
4345381b23dSAlexander Lobakin 	data = kmalloc_reserve(size, gfp_mask, node, &pfmemalloc);
435df1ae022SAlexander Lobakin 	if (unlikely(!data))
4365381b23dSAlexander Lobakin 		goto nodata;
4375381b23dSAlexander Lobakin 	/* kmalloc(size) might give us more room than requested.
4385381b23dSAlexander Lobakin 	 * Put skb_shared_info exactly at the end of allocated zone,
4395381b23dSAlexander Lobakin 	 * to allow max possible filling before reallocation.
4405381b23dSAlexander Lobakin 	 */
441a5df6333SLi RongQing 	osize = ksize(data);
442a5df6333SLi RongQing 	size = SKB_WITH_OVERHEAD(osize);
4435381b23dSAlexander Lobakin 	prefetchw(data + size);
4445381b23dSAlexander Lobakin 
4455381b23dSAlexander Lobakin 	/*
4465381b23dSAlexander Lobakin 	 * Only clear those fields we need to clear, not those that we will
4475381b23dSAlexander Lobakin 	 * actually initialise below. Hence, don't put any more fields after
4485381b23dSAlexander Lobakin 	 * the tail pointer in struct sk_buff!
4495381b23dSAlexander Lobakin 	 */
4505381b23dSAlexander Lobakin 	memset(skb, 0, offsetof(struct sk_buff, tail));
451a5df6333SLi RongQing 	__build_skb_around(skb, data, osize);
4525381b23dSAlexander Lobakin 	skb->pfmemalloc = pfmemalloc;
4535381b23dSAlexander Lobakin 
4545381b23dSAlexander Lobakin 	if (flags & SKB_ALLOC_FCLONE) {
4555381b23dSAlexander Lobakin 		struct sk_buff_fclones *fclones;
4565381b23dSAlexander Lobakin 
4575381b23dSAlexander Lobakin 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
4585381b23dSAlexander Lobakin 
4595381b23dSAlexander Lobakin 		skb->fclone = SKB_FCLONE_ORIG;
4605381b23dSAlexander Lobakin 		refcount_set(&fclones->fclone_ref, 1);
4615381b23dSAlexander Lobakin 	}
4625381b23dSAlexander Lobakin 
4635381b23dSAlexander Lobakin 	return skb;
464df1ae022SAlexander Lobakin 
4655381b23dSAlexander Lobakin nodata:
4665381b23dSAlexander Lobakin 	kmem_cache_free(cache, skb);
467df1ae022SAlexander Lobakin 	return NULL;
4685381b23dSAlexander Lobakin }
4695381b23dSAlexander Lobakin EXPORT_SYMBOL(__alloc_skb);
4705381b23dSAlexander Lobakin 
4717ba7aeabSSebastian Andrzej Siewior /**
472fd11a83dSAlexander Duyck  *	__netdev_alloc_skb - allocate an skbuff for rx on a specific device
473fd11a83dSAlexander Duyck  *	@dev: network device to receive on
474d7499160SMasanari Iida  *	@len: length to allocate
475fd11a83dSAlexander Duyck  *	@gfp_mask: get_free_pages mask, passed to alloc_skb
476fd11a83dSAlexander Duyck  *
477fd11a83dSAlexander Duyck  *	Allocate a new &sk_buff and assign it a usage count of one. The
478fd11a83dSAlexander Duyck  *	buffer has NET_SKB_PAD headroom built in. Users should allocate
479fd11a83dSAlexander Duyck  *	the headroom they think they need without accounting for the
480fd11a83dSAlexander Duyck  *	built in space. The built in space is used for optimisations.
481fd11a83dSAlexander Duyck  *
482fd11a83dSAlexander Duyck  *	%NULL is returned if there is no free memory.
483fd11a83dSAlexander Duyck  */
4849451980aSAlexander Duyck struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
4859451980aSAlexander Duyck 				   gfp_t gfp_mask)
486fd11a83dSAlexander Duyck {
487b63ae8caSAlexander Duyck 	struct page_frag_cache *nc;
488fd11a83dSAlexander Duyck 	struct sk_buff *skb;
4899451980aSAlexander Duyck 	bool pfmemalloc;
4909451980aSAlexander Duyck 	void *data;
491fd11a83dSAlexander Duyck 
4929451980aSAlexander Duyck 	len += NET_SKB_PAD;
493fd11a83dSAlexander Duyck 
49466c55602SAlexander Lobakin 	/* If requested length is either too small or too big,
49566c55602SAlexander Lobakin 	 * we use kmalloc() for skb->head allocation.
49666c55602SAlexander Lobakin 	 */
49766c55602SAlexander Lobakin 	if (len <= SKB_WITH_OVERHEAD(1024) ||
49866c55602SAlexander Lobakin 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
499d0164adcSMel Gorman 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
500a080e7bdSAlexander Duyck 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
501a080e7bdSAlexander Duyck 		if (!skb)
502a080e7bdSAlexander Duyck 			goto skb_fail;
503a080e7bdSAlexander Duyck 		goto skb_success;
504a080e7bdSAlexander Duyck 	}
5059451980aSAlexander Duyck 
5069451980aSAlexander Duyck 	len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
5079451980aSAlexander Duyck 	len = SKB_DATA_ALIGN(len);
5089451980aSAlexander Duyck 
5099451980aSAlexander Duyck 	if (sk_memalloc_socks())
5109451980aSAlexander Duyck 		gfp_mask |= __GFP_MEMALLOC;
5119451980aSAlexander Duyck 
512afa79d08SChangbin Du 	if (in_hardirq() || irqs_disabled()) {
5139451980aSAlexander Duyck 		nc = this_cpu_ptr(&netdev_alloc_cache);
5148c2dd3e4SAlexander Duyck 		data = page_frag_alloc(nc, len, gfp_mask);
5159451980aSAlexander Duyck 		pfmemalloc = nc->pfmemalloc;
51692dcabd7SSebastian Andrzej Siewior 	} else {
51792dcabd7SSebastian Andrzej Siewior 		local_bh_disable();
51892dcabd7SSebastian Andrzej Siewior 		nc = this_cpu_ptr(&napi_alloc_cache.page);
51992dcabd7SSebastian Andrzej Siewior 		data = page_frag_alloc(nc, len, gfp_mask);
52092dcabd7SSebastian Andrzej Siewior 		pfmemalloc = nc->pfmemalloc;
52192dcabd7SSebastian Andrzej Siewior 		local_bh_enable();
52292dcabd7SSebastian Andrzej Siewior 	}
5239451980aSAlexander Duyck 
5249451980aSAlexander Duyck 	if (unlikely(!data))
5259451980aSAlexander Duyck 		return NULL;
5269451980aSAlexander Duyck 
5279451980aSAlexander Duyck 	skb = __build_skb(data, len);
5289451980aSAlexander Duyck 	if (unlikely(!skb)) {
529181edb2bSAlexander Duyck 		skb_free_frag(data);
5309451980aSAlexander Duyck 		return NULL;
5319451980aSAlexander Duyck 	}
5329451980aSAlexander Duyck 
5339451980aSAlexander Duyck 	if (pfmemalloc)
5349451980aSAlexander Duyck 		skb->pfmemalloc = 1;
5359451980aSAlexander Duyck 	skb->head_frag = 1;
5369451980aSAlexander Duyck 
537a080e7bdSAlexander Duyck skb_success:
5388af27456SChristoph Hellwig 	skb_reserve(skb, NET_SKB_PAD);
5397b2e497aSChristoph Hellwig 	skb->dev = dev;
540fd11a83dSAlexander Duyck 
541a080e7bdSAlexander Duyck skb_fail:
5428af27456SChristoph Hellwig 	return skb;
5438af27456SChristoph Hellwig }
544b4ac530fSDavid S. Miller EXPORT_SYMBOL(__netdev_alloc_skb);
5451da177e4SLinus Torvalds 
546fd11a83dSAlexander Duyck /**
547fd11a83dSAlexander Duyck  *	__napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
548fd11a83dSAlexander Duyck  *	@napi: napi instance this buffer was allocated for
549d7499160SMasanari Iida  *	@len: length to allocate
550fd11a83dSAlexander Duyck  *	@gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
551fd11a83dSAlexander Duyck  *
552fd11a83dSAlexander Duyck  *	Allocate a new sk_buff for use in NAPI receive.  This buffer will
553fd11a83dSAlexander Duyck  *	attempt to allocate the head from a special reserved region used
554fd11a83dSAlexander Duyck  *	only for NAPI Rx allocation.  By doing this we can save several
555fd11a83dSAlexander Duyck  *	CPU cycles by avoiding having to disable and re-enable IRQs.
556fd11a83dSAlexander Duyck  *
557fd11a83dSAlexander Duyck  *	%NULL is returned if there is no free memory.
558fd11a83dSAlexander Duyck  */
5599451980aSAlexander Duyck struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
5609451980aSAlexander Duyck 				 gfp_t gfp_mask)
561fd11a83dSAlexander Duyck {
5623226b158SEric Dumazet 	struct napi_alloc_cache *nc;
563fd11a83dSAlexander Duyck 	struct sk_buff *skb;
5649451980aSAlexander Duyck 	void *data;
565fd11a83dSAlexander Duyck 
566ee2640dfSEric Dumazet 	DEBUG_NET_WARN_ON_ONCE(!in_softirq());
5679451980aSAlexander Duyck 	len += NET_SKB_PAD + NET_IP_ALIGN;
568fd11a83dSAlexander Duyck 
5693226b158SEric Dumazet 	/* If requested length is either too small or too big,
5703226b158SEric Dumazet 	 * we use kmalloc() for skb->head allocation.
5713226b158SEric Dumazet 	 */
5723226b158SEric Dumazet 	if (len <= SKB_WITH_OVERHEAD(1024) ||
5733226b158SEric Dumazet 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
574d0164adcSMel Gorman 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
575cfb8ec65SAlexander Lobakin 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
576cfb8ec65SAlexander Lobakin 				  NUMA_NO_NODE);
577a080e7bdSAlexander Duyck 		if (!skb)
578a080e7bdSAlexander Duyck 			goto skb_fail;
579a080e7bdSAlexander Duyck 		goto skb_success;
580a080e7bdSAlexander Duyck 	}
5819451980aSAlexander Duyck 
5823226b158SEric Dumazet 	nc = this_cpu_ptr(&napi_alloc_cache);
5839451980aSAlexander Duyck 	len += SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
5849451980aSAlexander Duyck 	len = SKB_DATA_ALIGN(len);
5859451980aSAlexander Duyck 
5869451980aSAlexander Duyck 	if (sk_memalloc_socks())
5879451980aSAlexander Duyck 		gfp_mask |= __GFP_MEMALLOC;
5889451980aSAlexander Duyck 
5898c2dd3e4SAlexander Duyck 	data = page_frag_alloc(&nc->page, len, gfp_mask);
5909451980aSAlexander Duyck 	if (unlikely(!data))
5919451980aSAlexander Duyck 		return NULL;
5929451980aSAlexander Duyck 
593cfb8ec65SAlexander Lobakin 	skb = __napi_build_skb(data, len);
5949451980aSAlexander Duyck 	if (unlikely(!skb)) {
595181edb2bSAlexander Duyck 		skb_free_frag(data);
5969451980aSAlexander Duyck 		return NULL;
5979451980aSAlexander Duyck 	}
5989451980aSAlexander Duyck 
599795bb1c0SJesper Dangaard Brouer 	if (nc->page.pfmemalloc)
6009451980aSAlexander Duyck 		skb->pfmemalloc = 1;
6019451980aSAlexander Duyck 	skb->head_frag = 1;
6029451980aSAlexander Duyck 
603a080e7bdSAlexander Duyck skb_success:
604fd11a83dSAlexander Duyck 	skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
605fd11a83dSAlexander Duyck 	skb->dev = napi->dev;
606fd11a83dSAlexander Duyck 
607a080e7bdSAlexander Duyck skb_fail:
608fd11a83dSAlexander Duyck 	return skb;
609fd11a83dSAlexander Duyck }
610fd11a83dSAlexander Duyck EXPORT_SYMBOL(__napi_alloc_skb);
611fd11a83dSAlexander Duyck 
612654bed16SPeter Zijlstra void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
61350269e19SEric Dumazet 		     int size, unsigned int truesize)
614654bed16SPeter Zijlstra {
615654bed16SPeter Zijlstra 	skb_fill_page_desc(skb, i, page, off, size);
616654bed16SPeter Zijlstra 	skb->len += size;
617654bed16SPeter Zijlstra 	skb->data_len += size;
61850269e19SEric Dumazet 	skb->truesize += truesize;
619654bed16SPeter Zijlstra }
620654bed16SPeter Zijlstra EXPORT_SYMBOL(skb_add_rx_frag);
621654bed16SPeter Zijlstra 
622f8e617e1SJason Wang void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
623f8e617e1SJason Wang 			  unsigned int truesize)
624f8e617e1SJason Wang {
625f8e617e1SJason Wang 	skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
626f8e617e1SJason Wang 
627f8e617e1SJason Wang 	skb_frag_size_add(frag, size);
628f8e617e1SJason Wang 	skb->len += size;
629f8e617e1SJason Wang 	skb->data_len += size;
630f8e617e1SJason Wang 	skb->truesize += truesize;
631f8e617e1SJason Wang }
632f8e617e1SJason Wang EXPORT_SYMBOL(skb_coalesce_rx_frag);
633f8e617e1SJason Wang 
63427b437c8SHerbert Xu static void skb_drop_list(struct sk_buff **listp)
6351da177e4SLinus Torvalds {
636bd8a7036SEric Dumazet 	kfree_skb_list(*listp);
63727b437c8SHerbert Xu 	*listp = NULL;
6381da177e4SLinus Torvalds }
6391da177e4SLinus Torvalds 
64027b437c8SHerbert Xu static inline void skb_drop_fraglist(struct sk_buff *skb)
64127b437c8SHerbert Xu {
64227b437c8SHerbert Xu 	skb_drop_list(&skb_shinfo(skb)->frag_list);
64327b437c8SHerbert Xu }
64427b437c8SHerbert Xu 
6451da177e4SLinus Torvalds static void skb_clone_fraglist(struct sk_buff *skb)
6461da177e4SLinus Torvalds {
6471da177e4SLinus Torvalds 	struct sk_buff *list;
6481da177e4SLinus Torvalds 
649fbb398a8SDavid S. Miller 	skb_walk_frags(skb, list)
6501da177e4SLinus Torvalds 		skb_get(list);
6511da177e4SLinus Torvalds }
6521da177e4SLinus Torvalds 
653d3836f21SEric Dumazet static void skb_free_head(struct sk_buff *skb)
654d3836f21SEric Dumazet {
655181edb2bSAlexander Duyck 	unsigned char *head = skb->head;
656181edb2bSAlexander Duyck 
6576a5bcd84SIlias Apalodimas 	if (skb->head_frag) {
6586a5bcd84SIlias Apalodimas 		if (skb_pp_recycle(skb, head))
6596a5bcd84SIlias Apalodimas 			return;
660181edb2bSAlexander Duyck 		skb_free_frag(head);
6616a5bcd84SIlias Apalodimas 	} else {
662181edb2bSAlexander Duyck 		kfree(head);
663d3836f21SEric Dumazet 	}
6646a5bcd84SIlias Apalodimas }
665d3836f21SEric Dumazet 
6665bba1712SAdrian Bunk static void skb_release_data(struct sk_buff *skb)
6671da177e4SLinus Torvalds {
668ff04a771SEric Dumazet 	struct skb_shared_info *shinfo = skb_shinfo(skb);
6691da177e4SLinus Torvalds 	int i;
670ff04a771SEric Dumazet 
671ff04a771SEric Dumazet 	if (skb->cloned &&
672ff04a771SEric Dumazet 	    atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
673ff04a771SEric Dumazet 			      &shinfo->dataref))
6742cc3aeb5SIlias Apalodimas 		goto exit;
675ff04a771SEric Dumazet 
676753f1ca4SPavel Begunkov 	if (skb_zcopy(skb)) {
677753f1ca4SPavel Begunkov 		bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
678753f1ca4SPavel Begunkov 
67970c43167SJonathan Lemon 		skb_zcopy_clear(skb, true);
680753f1ca4SPavel Begunkov 		if (skip_unref)
681753f1ca4SPavel Begunkov 			goto free_head;
682753f1ca4SPavel Begunkov 	}
68370c43167SJonathan Lemon 
684ff04a771SEric Dumazet 	for (i = 0; i < shinfo->nr_frags; i++)
6856a5bcd84SIlias Apalodimas 		__skb_frag_unref(&shinfo->frags[i], skb->pp_recycle);
6861da177e4SLinus Torvalds 
687753f1ca4SPavel Begunkov free_head:
688ff04a771SEric Dumazet 	if (shinfo->frag_list)
689ff04a771SEric Dumazet 		kfree_skb_list(shinfo->frag_list);
6901da177e4SLinus Torvalds 
691d3836f21SEric Dumazet 	skb_free_head(skb);
6922cc3aeb5SIlias Apalodimas exit:
6932cc3aeb5SIlias Apalodimas 	/* When we clone an SKB we copy the reycling bit. The pp_recycle
6942cc3aeb5SIlias Apalodimas 	 * bit is only set on the head though, so in order to avoid races
6952cc3aeb5SIlias Apalodimas 	 * while trying to recycle fragments on __skb_frag_unref() we need
6962cc3aeb5SIlias Apalodimas 	 * to make one SKB responsible for triggering the recycle path.
6972cc3aeb5SIlias Apalodimas 	 * So disable the recycling bit if an SKB is cloned and we have
69858e61e41STom Rix 	 * additional references to the fragmented part of the SKB.
6992cc3aeb5SIlias Apalodimas 	 * Eventually the last SKB will have the recycling bit set and it's
7002cc3aeb5SIlias Apalodimas 	 * dataref set to 0, which will trigger the recycling
7012cc3aeb5SIlias Apalodimas 	 */
7022cc3aeb5SIlias Apalodimas 	skb->pp_recycle = 0;
7031da177e4SLinus Torvalds }
7041da177e4SLinus Torvalds 
7051da177e4SLinus Torvalds /*
7061da177e4SLinus Torvalds  *	Free an skbuff by memory without cleaning the state.
7071da177e4SLinus Torvalds  */
7082d4baff8SHerbert Xu static void kfree_skbmem(struct sk_buff *skb)
7091da177e4SLinus Torvalds {
710d0bf4a9eSEric Dumazet 	struct sk_buff_fclones *fclones;
711d179cd12SDavid S. Miller 
712d179cd12SDavid S. Miller 	switch (skb->fclone) {
713d179cd12SDavid S. Miller 	case SKB_FCLONE_UNAVAILABLE:
7141da177e4SLinus Torvalds 		kmem_cache_free(skbuff_head_cache, skb);
7156ffe75ebSEric Dumazet 		return;
716d179cd12SDavid S. Miller 
717d179cd12SDavid S. Miller 	case SKB_FCLONE_ORIG:
718d0bf4a9eSEric Dumazet 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
7196ffe75ebSEric Dumazet 
7206ffe75ebSEric Dumazet 		/* We usually free the clone (TX completion) before original skb
7216ffe75ebSEric Dumazet 		 * This test would have no chance to be true for the clone,
7226ffe75ebSEric Dumazet 		 * while here, branch prediction will be good.
7236ffe75ebSEric Dumazet 		 */
7242638595aSReshetova, Elena 		if (refcount_read(&fclones->fclone_ref) == 1)
7256ffe75ebSEric Dumazet 			goto fastpath;
726d179cd12SDavid S. Miller 		break;
727d179cd12SDavid S. Miller 
7286ffe75ebSEric Dumazet 	default: /* SKB_FCLONE_CLONE */
729d0bf4a9eSEric Dumazet 		fclones = container_of(skb, struct sk_buff_fclones, skb2);
730d179cd12SDavid S. Miller 		break;
7313ff50b79SStephen Hemminger 	}
7322638595aSReshetova, Elena 	if (!refcount_dec_and_test(&fclones->fclone_ref))
7336ffe75ebSEric Dumazet 		return;
7346ffe75ebSEric Dumazet fastpath:
7356ffe75ebSEric Dumazet 	kmem_cache_free(skbuff_fclone_cache, fclones);
7361da177e4SLinus Torvalds }
7371da177e4SLinus Torvalds 
7380a463c78SPaolo Abeni void skb_release_head_state(struct sk_buff *skb)
7391da177e4SLinus Torvalds {
740adf30907SEric Dumazet 	skb_dst_drop(skb);
7411da177e4SLinus Torvalds 	if (skb->destructor) {
7427890e2f0SEric Dumazet 		DEBUG_NET_WARN_ON_ONCE(in_hardirq());
7431da177e4SLinus Torvalds 		skb->destructor(skb);
7441da177e4SLinus Torvalds 	}
745a3bf7ae9SIgor Maravić #if IS_ENABLED(CONFIG_NF_CONNTRACK)
746cb9c6836SFlorian Westphal 	nf_conntrack_put(skb_nfct(skb));
7472fc72c7bSKOVACS Krisztian #endif
748df5042f4SFlorian Westphal 	skb_ext_put(skb);
74904a4bb55SLennert Buytenhek }
75004a4bb55SLennert Buytenhek 
75104a4bb55SLennert Buytenhek /* Free everything but the sk_buff shell. */
75204a4bb55SLennert Buytenhek static void skb_release_all(struct sk_buff *skb)
75304a4bb55SLennert Buytenhek {
75404a4bb55SLennert Buytenhek 	skb_release_head_state(skb);
755a28b1b90SFlorian Westphal 	if (likely(skb->head))
7562d4baff8SHerbert Xu 		skb_release_data(skb);
7572d4baff8SHerbert Xu }
7581da177e4SLinus Torvalds 
7592d4baff8SHerbert Xu /**
7602d4baff8SHerbert Xu  *	__kfree_skb - private function
7612d4baff8SHerbert Xu  *	@skb: buffer
7622d4baff8SHerbert Xu  *
7632d4baff8SHerbert Xu  *	Free an sk_buff. Release anything attached to the buffer.
7642d4baff8SHerbert Xu  *	Clean the state. This is an internal helper function. Users should
7652d4baff8SHerbert Xu  *	always call kfree_skb
7662d4baff8SHerbert Xu  */
7672d4baff8SHerbert Xu 
7682d4baff8SHerbert Xu void __kfree_skb(struct sk_buff *skb)
7692d4baff8SHerbert Xu {
7702d4baff8SHerbert Xu 	skb_release_all(skb);
7711da177e4SLinus Torvalds 	kfree_skbmem(skb);
7721da177e4SLinus Torvalds }
773b4ac530fSDavid S. Miller EXPORT_SYMBOL(__kfree_skb);
7741da177e4SLinus Torvalds 
7751da177e4SLinus Torvalds /**
776c504e5c2SMenglong Dong  *	kfree_skb_reason - free an sk_buff with special reason
777231d06aeSJörn Engel  *	@skb: buffer to free
778c504e5c2SMenglong Dong  *	@reason: reason why this skb is dropped
779231d06aeSJörn Engel  *
780231d06aeSJörn Engel  *	Drop a reference to the buffer and free it if the usage count has
781c504e5c2SMenglong Dong  *	hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
782c504e5c2SMenglong Dong  *	tracepoint.
783231d06aeSJörn Engel  */
784c205cc75SMenglong Dong void __fix_address
785c205cc75SMenglong Dong kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
786231d06aeSJörn Engel {
787c205cc75SMenglong Dong 	if (unlikely(!skb_unref(skb)))
788231d06aeSJörn Engel 		return;
7893889a803SPaolo Abeni 
79020bbcd0aSMenglong Dong 	DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
79120bbcd0aSMenglong Dong 
792c504e5c2SMenglong Dong 	trace_kfree_skb(skb, __builtin_return_address(0), reason);
793231d06aeSJörn Engel 	__kfree_skb(skb);
794231d06aeSJörn Engel }
795c504e5c2SMenglong Dong EXPORT_SYMBOL(kfree_skb_reason);
796231d06aeSJörn Engel 
797215b0f19SMenglong Dong void kfree_skb_list_reason(struct sk_buff *segs,
798215b0f19SMenglong Dong 			   enum skb_drop_reason reason)
799bd8a7036SEric Dumazet {
800bd8a7036SEric Dumazet 	while (segs) {
801bd8a7036SEric Dumazet 		struct sk_buff *next = segs->next;
802bd8a7036SEric Dumazet 
803215b0f19SMenglong Dong 		kfree_skb_reason(segs, reason);
804bd8a7036SEric Dumazet 		segs = next;
805bd8a7036SEric Dumazet 	}
806bd8a7036SEric Dumazet }
807215b0f19SMenglong Dong EXPORT_SYMBOL(kfree_skb_list_reason);
808bd8a7036SEric Dumazet 
8096413139dSWillem de Bruijn /* Dump skb information and contents.
8106413139dSWillem de Bruijn  *
8116413139dSWillem de Bruijn  * Must only be called from net_ratelimit()-ed paths.
8126413139dSWillem de Bruijn  *
813302af7c6SVladimir Oltean  * Dumps whole packets if full_pkt, only headers otherwise.
8146413139dSWillem de Bruijn  */
8156413139dSWillem de Bruijn void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
8166413139dSWillem de Bruijn {
8176413139dSWillem de Bruijn 	struct skb_shared_info *sh = skb_shinfo(skb);
8186413139dSWillem de Bruijn 	struct net_device *dev = skb->dev;
8196413139dSWillem de Bruijn 	struct sock *sk = skb->sk;
8206413139dSWillem de Bruijn 	struct sk_buff *list_skb;
8216413139dSWillem de Bruijn 	bool has_mac, has_trans;
8226413139dSWillem de Bruijn 	int headroom, tailroom;
8236413139dSWillem de Bruijn 	int i, len, seg_len;
8246413139dSWillem de Bruijn 
8256413139dSWillem de Bruijn 	if (full_pkt)
8266413139dSWillem de Bruijn 		len = skb->len;
8276413139dSWillem de Bruijn 	else
8286413139dSWillem de Bruijn 		len = min_t(int, skb->len, MAX_HEADER + 128);
8296413139dSWillem de Bruijn 
8306413139dSWillem de Bruijn 	headroom = skb_headroom(skb);
8316413139dSWillem de Bruijn 	tailroom = skb_tailroom(skb);
8326413139dSWillem de Bruijn 
8336413139dSWillem de Bruijn 	has_mac = skb_mac_header_was_set(skb);
8346413139dSWillem de Bruijn 	has_trans = skb_transport_header_was_set(skb);
8356413139dSWillem de Bruijn 
8366413139dSWillem de Bruijn 	printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
8376413139dSWillem de Bruijn 	       "mac=(%d,%d) net=(%d,%d) trans=%d\n"
8386413139dSWillem de Bruijn 	       "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
8396413139dSWillem de Bruijn 	       "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
8406413139dSWillem de Bruijn 	       "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
8416413139dSWillem de Bruijn 	       level, skb->len, headroom, skb_headlen(skb), tailroom,
8426413139dSWillem de Bruijn 	       has_mac ? skb->mac_header : -1,
8436413139dSWillem de Bruijn 	       has_mac ? skb_mac_header_len(skb) : -1,
8446413139dSWillem de Bruijn 	       skb->network_header,
8456413139dSWillem de Bruijn 	       has_trans ? skb_network_header_len(skb) : -1,
8466413139dSWillem de Bruijn 	       has_trans ? skb->transport_header : -1,
8476413139dSWillem de Bruijn 	       sh->tx_flags, sh->nr_frags,
8486413139dSWillem de Bruijn 	       sh->gso_size, sh->gso_type, sh->gso_segs,
8496413139dSWillem de Bruijn 	       skb->csum, skb->ip_summed, skb->csum_complete_sw,
8506413139dSWillem de Bruijn 	       skb->csum_valid, skb->csum_level,
8516413139dSWillem de Bruijn 	       skb->hash, skb->sw_hash, skb->l4_hash,
8526413139dSWillem de Bruijn 	       ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
8536413139dSWillem de Bruijn 
8546413139dSWillem de Bruijn 	if (dev)
8558a03ef67SGal Pressman 		printk("%sdev name=%s feat=%pNF\n",
8566413139dSWillem de Bruijn 		       level, dev->name, &dev->features);
8576413139dSWillem de Bruijn 	if (sk)
858db8051f3SQian Cai 		printk("%ssk family=%hu type=%u proto=%u\n",
8596413139dSWillem de Bruijn 		       level, sk->sk_family, sk->sk_type, sk->sk_protocol);
8606413139dSWillem de Bruijn 
8616413139dSWillem de Bruijn 	if (full_pkt && headroom)
8626413139dSWillem de Bruijn 		print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
8636413139dSWillem de Bruijn 			       16, 1, skb->head, headroom, false);
8646413139dSWillem de Bruijn 
8656413139dSWillem de Bruijn 	seg_len = min_t(int, skb_headlen(skb), len);
8666413139dSWillem de Bruijn 	if (seg_len)
8676413139dSWillem de Bruijn 		print_hex_dump(level, "skb linear:   ", DUMP_PREFIX_OFFSET,
8686413139dSWillem de Bruijn 			       16, 1, skb->data, seg_len, false);
8696413139dSWillem de Bruijn 	len -= seg_len;
8706413139dSWillem de Bruijn 
8716413139dSWillem de Bruijn 	if (full_pkt && tailroom)
8726413139dSWillem de Bruijn 		print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
8736413139dSWillem de Bruijn 			       16, 1, skb_tail_pointer(skb), tailroom, false);
8746413139dSWillem de Bruijn 
8756413139dSWillem de Bruijn 	for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
8766413139dSWillem de Bruijn 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
8776413139dSWillem de Bruijn 		u32 p_off, p_len, copied;
8786413139dSWillem de Bruijn 		struct page *p;
8796413139dSWillem de Bruijn 		u8 *vaddr;
8806413139dSWillem de Bruijn 
881b54c9d5bSJonathan Lemon 		skb_frag_foreach_page(frag, skb_frag_off(frag),
8826413139dSWillem de Bruijn 				      skb_frag_size(frag), p, p_off, p_len,
8836413139dSWillem de Bruijn 				      copied) {
8846413139dSWillem de Bruijn 			seg_len = min_t(int, p_len, len);
8856413139dSWillem de Bruijn 			vaddr = kmap_atomic(p);
8866413139dSWillem de Bruijn 			print_hex_dump(level, "skb frag:     ",
8876413139dSWillem de Bruijn 				       DUMP_PREFIX_OFFSET,
8886413139dSWillem de Bruijn 				       16, 1, vaddr + p_off, seg_len, false);
8896413139dSWillem de Bruijn 			kunmap_atomic(vaddr);
8906413139dSWillem de Bruijn 			len -= seg_len;
8916413139dSWillem de Bruijn 			if (!len)
8926413139dSWillem de Bruijn 				break;
8936413139dSWillem de Bruijn 		}
8946413139dSWillem de Bruijn 	}
8956413139dSWillem de Bruijn 
8966413139dSWillem de Bruijn 	if (full_pkt && skb_has_frag_list(skb)) {
8976413139dSWillem de Bruijn 		printk("skb fraglist:\n");
8986413139dSWillem de Bruijn 		skb_walk_frags(skb, list_skb)
8996413139dSWillem de Bruijn 			skb_dump(level, list_skb, true);
9006413139dSWillem de Bruijn 	}
9016413139dSWillem de Bruijn }
9026413139dSWillem de Bruijn EXPORT_SYMBOL(skb_dump);
9036413139dSWillem de Bruijn 
904d1a203eaSStephen Hemminger /**
90525121173SMichael S. Tsirkin  *	skb_tx_error - report an sk_buff xmit error
90625121173SMichael S. Tsirkin  *	@skb: buffer that triggered an error
90725121173SMichael S. Tsirkin  *
90825121173SMichael S. Tsirkin  *	Report xmit error if a device callback is tracking this skb.
90925121173SMichael S. Tsirkin  *	skb must be freed afterwards.
91025121173SMichael S. Tsirkin  */
91125121173SMichael S. Tsirkin void skb_tx_error(struct sk_buff *skb)
91225121173SMichael S. Tsirkin {
913753f1ca4SPavel Begunkov 	if (skb) {
914753f1ca4SPavel Begunkov 		skb_zcopy_downgrade_managed(skb);
9151f8b977aSWillem de Bruijn 		skb_zcopy_clear(skb, true);
91625121173SMichael S. Tsirkin 	}
917753f1ca4SPavel Begunkov }
91825121173SMichael S. Tsirkin EXPORT_SYMBOL(skb_tx_error);
91925121173SMichael S. Tsirkin 
920be769db2SHerbert Xu #ifdef CONFIG_TRACEPOINTS
92125121173SMichael S. Tsirkin /**
922ead2ceb0SNeil Horman  *	consume_skb - free an skbuff
923ead2ceb0SNeil Horman  *	@skb: buffer to free
924ead2ceb0SNeil Horman  *
925ead2ceb0SNeil Horman  *	Drop a ref to the buffer and free it if the usage count has hit zero
926ead2ceb0SNeil Horman  *	Functions identically to kfree_skb, but kfree_skb assumes that the frame
927ead2ceb0SNeil Horman  *	is being dropped after a failure and notes that
928ead2ceb0SNeil Horman  */
929ead2ceb0SNeil Horman void consume_skb(struct sk_buff *skb)
930ead2ceb0SNeil Horman {
9313889a803SPaolo Abeni 	if (!skb_unref(skb))
932ead2ceb0SNeil Horman 		return;
9333889a803SPaolo Abeni 
93407dc22e7SKoki Sanagi 	trace_consume_skb(skb);
935ead2ceb0SNeil Horman 	__kfree_skb(skb);
936ead2ceb0SNeil Horman }
937ead2ceb0SNeil Horman EXPORT_SYMBOL(consume_skb);
938be769db2SHerbert Xu #endif
939ead2ceb0SNeil Horman 
9400a463c78SPaolo Abeni /**
941c1639be9SMauro Carvalho Chehab  *	__consume_stateless_skb - free an skbuff, assuming it is stateless
9420a463c78SPaolo Abeni  *	@skb: buffer to free
9430a463c78SPaolo Abeni  *
944ca2c1418SPaolo Abeni  *	Alike consume_skb(), but this variant assumes that this is the last
945ca2c1418SPaolo Abeni  *	skb reference and all the head states have been already dropped
9460a463c78SPaolo Abeni  */
947ca2c1418SPaolo Abeni void __consume_stateless_skb(struct sk_buff *skb)
9480a463c78SPaolo Abeni {
9490a463c78SPaolo Abeni 	trace_consume_skb(skb);
9500a463c78SPaolo Abeni 	skb_release_data(skb);
9510a463c78SPaolo Abeni 	kfree_skbmem(skb);
9520a463c78SPaolo Abeni }
9530a463c78SPaolo Abeni 
954f450d539SAlexander Lobakin static void napi_skb_cache_put(struct sk_buff *skb)
955795bb1c0SJesper Dangaard Brouer {
956795bb1c0SJesper Dangaard Brouer 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
957f450d539SAlexander Lobakin 	u32 i;
958795bb1c0SJesper Dangaard Brouer 
959f450d539SAlexander Lobakin 	kasan_poison_object_data(skbuff_head_cache, skb);
960795bb1c0SJesper Dangaard Brouer 	nc->skb_cache[nc->skb_count++] = skb;
961795bb1c0SJesper Dangaard Brouer 
962795bb1c0SJesper Dangaard Brouer 	if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
963f450d539SAlexander Lobakin 		for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
964f450d539SAlexander Lobakin 			kasan_unpoison_object_data(skbuff_head_cache,
965f450d539SAlexander Lobakin 						   nc->skb_cache[i]);
966f450d539SAlexander Lobakin 
967f450d539SAlexander Lobakin 		kmem_cache_free_bulk(skbuff_head_cache, NAPI_SKB_CACHE_HALF,
968f450d539SAlexander Lobakin 				     nc->skb_cache + NAPI_SKB_CACHE_HALF);
969f450d539SAlexander Lobakin 		nc->skb_count = NAPI_SKB_CACHE_HALF;
970795bb1c0SJesper Dangaard Brouer 	}
971795bb1c0SJesper Dangaard Brouer }
972f450d539SAlexander Lobakin 
97315fad714SJesper Dangaard Brouer void __kfree_skb_defer(struct sk_buff *skb)
97415fad714SJesper Dangaard Brouer {
9759243adfcSAlexander Lobakin 	skb_release_all(skb);
9769243adfcSAlexander Lobakin 	napi_skb_cache_put(skb);
9779243adfcSAlexander Lobakin }
9789243adfcSAlexander Lobakin 
9799243adfcSAlexander Lobakin void napi_skb_free_stolen_head(struct sk_buff *skb)
9809243adfcSAlexander Lobakin {
9819efb4b5bSPaolo Abeni 	if (unlikely(skb->slow_gro)) {
9828550ff8dSPaul Blakey 		nf_reset_ct(skb);
9839243adfcSAlexander Lobakin 		skb_dst_drop(skb);
9849243adfcSAlexander Lobakin 		skb_ext_put(skb);
9855e10da53SPaolo Abeni 		skb_orphan(skb);
9869efb4b5bSPaolo Abeni 		skb->slow_gro = 0;
9879efb4b5bSPaolo Abeni 	}
988f450d539SAlexander Lobakin 	napi_skb_cache_put(skb);
98915fad714SJesper Dangaard Brouer }
990795bb1c0SJesper Dangaard Brouer 
991795bb1c0SJesper Dangaard Brouer void napi_consume_skb(struct sk_buff *skb, int budget)
992795bb1c0SJesper Dangaard Brouer {
993885eb0a5SJesper Dangaard Brouer 	/* Zero budget indicate non-NAPI context called us, like netpoll */
994795bb1c0SJesper Dangaard Brouer 	if (unlikely(!budget)) {
995885eb0a5SJesper Dangaard Brouer 		dev_consume_skb_any(skb);
996795bb1c0SJesper Dangaard Brouer 		return;
997795bb1c0SJesper Dangaard Brouer 	}
998795bb1c0SJesper Dangaard Brouer 
999ee2640dfSEric Dumazet 	DEBUG_NET_WARN_ON_ONCE(!in_softirq());
10006454eca8SYunsheng Lin 
10017608894eSPaolo Abeni 	if (!skb_unref(skb))
1002795bb1c0SJesper Dangaard Brouer 		return;
10037608894eSPaolo Abeni 
1004795bb1c0SJesper Dangaard Brouer 	/* if reaching here SKB is ready to free */
1005795bb1c0SJesper Dangaard Brouer 	trace_consume_skb(skb);
1006795bb1c0SJesper Dangaard Brouer 
1007795bb1c0SJesper Dangaard Brouer 	/* if SKB is a clone, don't handle this case */
1008abbdb5a7SEric Dumazet 	if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1009795bb1c0SJesper Dangaard Brouer 		__kfree_skb(skb);
1010795bb1c0SJesper Dangaard Brouer 		return;
1011795bb1c0SJesper Dangaard Brouer 	}
1012795bb1c0SJesper Dangaard Brouer 
10139243adfcSAlexander Lobakin 	skb_release_all(skb);
1014f450d539SAlexander Lobakin 	napi_skb_cache_put(skb);
1015795bb1c0SJesper Dangaard Brouer }
1016795bb1c0SJesper Dangaard Brouer EXPORT_SYMBOL(napi_consume_skb);
1017795bb1c0SJesper Dangaard Brouer 
101803f61041SKees Cook /* Make sure a field is contained by headers group */
1019b1937227SEric Dumazet #define CHECK_SKB_FIELD(field) \
102003f61041SKees Cook 	BUILD_BUG_ON(offsetof(struct sk_buff, field) !=		\
102103f61041SKees Cook 		     offsetof(struct sk_buff, headers.field));	\
1022b1937227SEric Dumazet 
1023dec18810SHerbert Xu static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1024dec18810SHerbert Xu {
1025dec18810SHerbert Xu 	new->tstamp		= old->tstamp;
1026b1937227SEric Dumazet 	/* We do not copy old->sk */
1027dec18810SHerbert Xu 	new->dev		= old->dev;
1028b1937227SEric Dumazet 	memcpy(new->cb, old->cb, sizeof(old->cb));
10297fee226aSEric Dumazet 	skb_dst_copy(new, old);
1030df5042f4SFlorian Westphal 	__skb_ext_copy(new, old);
1031b1937227SEric Dumazet 	__nf_copy(new, old, false);
10326aa895b0SPatrick McHardy 
103303f61041SKees Cook 	/* Note : this field could be in the headers group.
1034b1937227SEric Dumazet 	 * It is not yet because we do not want to have a 16 bit hole
1035b1937227SEric Dumazet 	 */
1036b1937227SEric Dumazet 	new->queue_mapping = old->queue_mapping;
103706021292SEliezer Tamir 
103803f61041SKees Cook 	memcpy(&new->headers, &old->headers, sizeof(new->headers));
1039b1937227SEric Dumazet 	CHECK_SKB_FIELD(protocol);
1040b1937227SEric Dumazet 	CHECK_SKB_FIELD(csum);
1041b1937227SEric Dumazet 	CHECK_SKB_FIELD(hash);
1042b1937227SEric Dumazet 	CHECK_SKB_FIELD(priority);
1043b1937227SEric Dumazet 	CHECK_SKB_FIELD(skb_iif);
1044b1937227SEric Dumazet 	CHECK_SKB_FIELD(vlan_proto);
1045b1937227SEric Dumazet 	CHECK_SKB_FIELD(vlan_tci);
1046b1937227SEric Dumazet 	CHECK_SKB_FIELD(transport_header);
1047b1937227SEric Dumazet 	CHECK_SKB_FIELD(network_header);
1048b1937227SEric Dumazet 	CHECK_SKB_FIELD(mac_header);
1049b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_protocol);
1050b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_transport_header);
1051b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_network_header);
1052b1937227SEric Dumazet 	CHECK_SKB_FIELD(inner_mac_header);
1053b1937227SEric Dumazet 	CHECK_SKB_FIELD(mark);
1054b1937227SEric Dumazet #ifdef CONFIG_NETWORK_SECMARK
1055b1937227SEric Dumazet 	CHECK_SKB_FIELD(secmark);
1056b1937227SEric Dumazet #endif
1057e0d1095aSCong Wang #ifdef CONFIG_NET_RX_BUSY_POLL
1058b1937227SEric Dumazet 	CHECK_SKB_FIELD(napi_id);
105906021292SEliezer Tamir #endif
106068822bdfSEric Dumazet 	CHECK_SKB_FIELD(alloc_cpu);
10612bd82484SEric Dumazet #ifdef CONFIG_XPS
10622bd82484SEric Dumazet 	CHECK_SKB_FIELD(sender_cpu);
10632bd82484SEric Dumazet #endif
1064b1937227SEric Dumazet #ifdef CONFIG_NET_SCHED
1065b1937227SEric Dumazet 	CHECK_SKB_FIELD(tc_index);
1066b1937227SEric Dumazet #endif
1067b1937227SEric Dumazet 
1068dec18810SHerbert Xu }
1069dec18810SHerbert Xu 
107082c49a35SHerbert Xu /*
107182c49a35SHerbert Xu  * You should not add any new code to this function.  Add it to
107282c49a35SHerbert Xu  * __copy_skb_header above instead.
107382c49a35SHerbert Xu  */
1074e0053ec0SHerbert Xu static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
10751da177e4SLinus Torvalds {
10761da177e4SLinus Torvalds #define C(x) n->x = skb->x
10771da177e4SLinus Torvalds 
10781da177e4SLinus Torvalds 	n->next = n->prev = NULL;
10791da177e4SLinus Torvalds 	n->sk = NULL;
1080dec18810SHerbert Xu 	__copy_skb_header(n, skb);
1081dec18810SHerbert Xu 
10821da177e4SLinus Torvalds 	C(len);
10831da177e4SLinus Torvalds 	C(data_len);
10843e6b3b2eSAlexey Dobriyan 	C(mac_len);
1085334a8132SPatrick McHardy 	n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
108602f1c89dSPaul Moore 	n->cloned = 1;
10871da177e4SLinus Torvalds 	n->nohdr = 0;
1088b13dda9fSEric Dumazet 	n->peeked = 0;
1089e78bfb07SStefano Brivio 	C(pfmemalloc);
10906a5bcd84SIlias Apalodimas 	C(pp_recycle);
10911da177e4SLinus Torvalds 	n->destructor = NULL;
10921da177e4SLinus Torvalds 	C(tail);
10931da177e4SLinus Torvalds 	C(end);
109402f1c89dSPaul Moore 	C(head);
1095d3836f21SEric Dumazet 	C(head_frag);
109602f1c89dSPaul Moore 	C(data);
109702f1c89dSPaul Moore 	C(truesize);
109863354797SReshetova, Elena 	refcount_set(&n->users, 1);
10991da177e4SLinus Torvalds 
11001da177e4SLinus Torvalds 	atomic_inc(&(skb_shinfo(skb)->dataref));
11011da177e4SLinus Torvalds 	skb->cloned = 1;
11021da177e4SLinus Torvalds 
11031da177e4SLinus Torvalds 	return n;
1104e0053ec0SHerbert Xu #undef C
1105e0053ec0SHerbert Xu }
1106e0053ec0SHerbert Xu 
1107e0053ec0SHerbert Xu /**
1108da29e4b4SJakub Kicinski  * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1109da29e4b4SJakub Kicinski  * @first: first sk_buff of the msg
1110da29e4b4SJakub Kicinski  */
1111da29e4b4SJakub Kicinski struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1112da29e4b4SJakub Kicinski {
1113da29e4b4SJakub Kicinski 	struct sk_buff *n;
1114da29e4b4SJakub Kicinski 
1115da29e4b4SJakub Kicinski 	n = alloc_skb(0, GFP_ATOMIC);
1116da29e4b4SJakub Kicinski 	if (!n)
1117da29e4b4SJakub Kicinski 		return NULL;
1118da29e4b4SJakub Kicinski 
1119da29e4b4SJakub Kicinski 	n->len = first->len;
1120da29e4b4SJakub Kicinski 	n->data_len = first->len;
1121da29e4b4SJakub Kicinski 	n->truesize = first->truesize;
1122da29e4b4SJakub Kicinski 
1123da29e4b4SJakub Kicinski 	skb_shinfo(n)->frag_list = first;
1124da29e4b4SJakub Kicinski 
1125da29e4b4SJakub Kicinski 	__copy_skb_header(n, first);
1126da29e4b4SJakub Kicinski 	n->destructor = NULL;
1127da29e4b4SJakub Kicinski 
1128da29e4b4SJakub Kicinski 	return n;
1129da29e4b4SJakub Kicinski }
1130da29e4b4SJakub Kicinski EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1131da29e4b4SJakub Kicinski 
1132da29e4b4SJakub Kicinski /**
1133e0053ec0SHerbert Xu  *	skb_morph	-	morph one skb into another
1134e0053ec0SHerbert Xu  *	@dst: the skb to receive the contents
1135e0053ec0SHerbert Xu  *	@src: the skb to supply the contents
1136e0053ec0SHerbert Xu  *
1137e0053ec0SHerbert Xu  *	This is identical to skb_clone except that the target skb is
1138e0053ec0SHerbert Xu  *	supplied by the user.
1139e0053ec0SHerbert Xu  *
1140e0053ec0SHerbert Xu  *	The target skb is returned upon exit.
1141e0053ec0SHerbert Xu  */
1142e0053ec0SHerbert Xu struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1143e0053ec0SHerbert Xu {
11442d4baff8SHerbert Xu 	skb_release_all(dst);
1145e0053ec0SHerbert Xu 	return __skb_clone(dst, src);
1146e0053ec0SHerbert Xu }
1147e0053ec0SHerbert Xu EXPORT_SYMBOL_GPL(skb_morph);
1148e0053ec0SHerbert Xu 
11496f89dbceSSowmini Varadhan int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1150a91dbff5SWillem de Bruijn {
1151a91dbff5SWillem de Bruijn 	unsigned long max_pg, num_pg, new_pg, old_pg;
1152a91dbff5SWillem de Bruijn 	struct user_struct *user;
1153a91dbff5SWillem de Bruijn 
1154a91dbff5SWillem de Bruijn 	if (capable(CAP_IPC_LOCK) || !size)
1155a91dbff5SWillem de Bruijn 		return 0;
1156a91dbff5SWillem de Bruijn 
1157a91dbff5SWillem de Bruijn 	num_pg = (size >> PAGE_SHIFT) + 2;	/* worst case */
1158a91dbff5SWillem de Bruijn 	max_pg = rlimit(RLIMIT_MEMLOCK) >> PAGE_SHIFT;
1159a91dbff5SWillem de Bruijn 	user = mmp->user ? : current_user();
1160a91dbff5SWillem de Bruijn 
1161a91dbff5SWillem de Bruijn 	do {
1162a91dbff5SWillem de Bruijn 		old_pg = atomic_long_read(&user->locked_vm);
1163a91dbff5SWillem de Bruijn 		new_pg = old_pg + num_pg;
1164a91dbff5SWillem de Bruijn 		if (new_pg > max_pg)
1165a91dbff5SWillem de Bruijn 			return -ENOBUFS;
1166a91dbff5SWillem de Bruijn 	} while (atomic_long_cmpxchg(&user->locked_vm, old_pg, new_pg) !=
1167a91dbff5SWillem de Bruijn 		 old_pg);
1168a91dbff5SWillem de Bruijn 
1169a91dbff5SWillem de Bruijn 	if (!mmp->user) {
1170a91dbff5SWillem de Bruijn 		mmp->user = get_uid(user);
1171a91dbff5SWillem de Bruijn 		mmp->num_pg = num_pg;
1172a91dbff5SWillem de Bruijn 	} else {
1173a91dbff5SWillem de Bruijn 		mmp->num_pg += num_pg;
1174a91dbff5SWillem de Bruijn 	}
1175a91dbff5SWillem de Bruijn 
1176a91dbff5SWillem de Bruijn 	return 0;
1177a91dbff5SWillem de Bruijn }
11786f89dbceSSowmini Varadhan EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1179a91dbff5SWillem de Bruijn 
11806f89dbceSSowmini Varadhan void mm_unaccount_pinned_pages(struct mmpin *mmp)
1181a91dbff5SWillem de Bruijn {
1182a91dbff5SWillem de Bruijn 	if (mmp->user) {
1183a91dbff5SWillem de Bruijn 		atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1184a91dbff5SWillem de Bruijn 		free_uid(mmp->user);
1185a91dbff5SWillem de Bruijn 	}
1186a91dbff5SWillem de Bruijn }
11876f89dbceSSowmini Varadhan EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1188a91dbff5SWillem de Bruijn 
1189c67b627eSDavid Ahern static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
119052267790SWillem de Bruijn {
1191*e7d2b510SPavel Begunkov 	struct ubuf_info_msgzc *uarg;
119252267790SWillem de Bruijn 	struct sk_buff *skb;
119352267790SWillem de Bruijn 
119452267790SWillem de Bruijn 	WARN_ON_ONCE(!in_task());
119552267790SWillem de Bruijn 
119652267790SWillem de Bruijn 	skb = sock_omalloc(sk, 0, GFP_KERNEL);
119752267790SWillem de Bruijn 	if (!skb)
119852267790SWillem de Bruijn 		return NULL;
119952267790SWillem de Bruijn 
120052267790SWillem de Bruijn 	BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
120152267790SWillem de Bruijn 	uarg = (void *)skb->cb;
1202a91dbff5SWillem de Bruijn 	uarg->mmp.user = NULL;
1203a91dbff5SWillem de Bruijn 
1204a91dbff5SWillem de Bruijn 	if (mm_account_pinned_pages(&uarg->mmp, size)) {
1205a91dbff5SWillem de Bruijn 		kfree_skb(skb);
1206a91dbff5SWillem de Bruijn 		return NULL;
1207a91dbff5SWillem de Bruijn 	}
120852267790SWillem de Bruijn 
1209*e7d2b510SPavel Begunkov 	uarg->ubuf.callback = msg_zerocopy_callback;
12104ab6c99dSWillem de Bruijn 	uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
12114ab6c99dSWillem de Bruijn 	uarg->len = 1;
12124ab6c99dSWillem de Bruijn 	uarg->bytelen = size;
121352267790SWillem de Bruijn 	uarg->zerocopy = 1;
1214*e7d2b510SPavel Begunkov 	uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1215*e7d2b510SPavel Begunkov 	refcount_set(&uarg->ubuf.refcnt, 1);
121652267790SWillem de Bruijn 	sock_hold(sk);
121752267790SWillem de Bruijn 
1218*e7d2b510SPavel Begunkov 	return &uarg->ubuf;
121952267790SWillem de Bruijn }
122052267790SWillem de Bruijn 
1221*e7d2b510SPavel Begunkov static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
122252267790SWillem de Bruijn {
122352267790SWillem de Bruijn 	return container_of((void *)uarg, struct sk_buff, cb);
122452267790SWillem de Bruijn }
122552267790SWillem de Bruijn 
12268c793822SJonathan Lemon struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
12274ab6c99dSWillem de Bruijn 				       struct ubuf_info *uarg)
12284ab6c99dSWillem de Bruijn {
12294ab6c99dSWillem de Bruijn 	if (uarg) {
1230*e7d2b510SPavel Begunkov 		struct ubuf_info_msgzc *uarg_zc;
12314ab6c99dSWillem de Bruijn 		const u32 byte_limit = 1 << 19;		/* limit to a few TSO */
12324ab6c99dSWillem de Bruijn 		u32 bytelen, next;
12334ab6c99dSWillem de Bruijn 
12341b4b2b09SPavel Begunkov 		/* there might be non MSG_ZEROCOPY users */
12351b4b2b09SPavel Begunkov 		if (uarg->callback != msg_zerocopy_callback)
12361b4b2b09SPavel Begunkov 			return NULL;
12371b4b2b09SPavel Begunkov 
12384ab6c99dSWillem de Bruijn 		/* realloc only when socket is locked (TCP, UDP cork),
12394ab6c99dSWillem de Bruijn 		 * so uarg->len and sk_zckey access is serialized
12404ab6c99dSWillem de Bruijn 		 */
12414ab6c99dSWillem de Bruijn 		if (!sock_owned_by_user(sk)) {
12424ab6c99dSWillem de Bruijn 			WARN_ON_ONCE(1);
12434ab6c99dSWillem de Bruijn 			return NULL;
12444ab6c99dSWillem de Bruijn 		}
12454ab6c99dSWillem de Bruijn 
1246*e7d2b510SPavel Begunkov 		uarg_zc = uarg_to_msgzc(uarg);
1247*e7d2b510SPavel Begunkov 		bytelen = uarg_zc->bytelen + size;
1248*e7d2b510SPavel Begunkov 		if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
12494ab6c99dSWillem de Bruijn 			/* TCP can create new skb to attach new uarg */
12504ab6c99dSWillem de Bruijn 			if (sk->sk_type == SOCK_STREAM)
12514ab6c99dSWillem de Bruijn 				goto new_alloc;
12524ab6c99dSWillem de Bruijn 			return NULL;
12534ab6c99dSWillem de Bruijn 		}
12544ab6c99dSWillem de Bruijn 
12554ab6c99dSWillem de Bruijn 		next = (u32)atomic_read(&sk->sk_zckey);
1256*e7d2b510SPavel Begunkov 		if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1257*e7d2b510SPavel Begunkov 			if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1258a91dbff5SWillem de Bruijn 				return NULL;
1259*e7d2b510SPavel Begunkov 			uarg_zc->len++;
1260*e7d2b510SPavel Begunkov 			uarg_zc->bytelen = bytelen;
12614ab6c99dSWillem de Bruijn 			atomic_set(&sk->sk_zckey, ++next);
1262100f6d8eSWillem de Bruijn 
1263100f6d8eSWillem de Bruijn 			/* no extra ref when appending to datagram (MSG_MORE) */
1264100f6d8eSWillem de Bruijn 			if (sk->sk_type == SOCK_STREAM)
12658e044917SJonathan Lemon 				net_zcopy_get(uarg);
1266100f6d8eSWillem de Bruijn 
12674ab6c99dSWillem de Bruijn 			return uarg;
12684ab6c99dSWillem de Bruijn 		}
12694ab6c99dSWillem de Bruijn 	}
12704ab6c99dSWillem de Bruijn 
12714ab6c99dSWillem de Bruijn new_alloc:
12728c793822SJonathan Lemon 	return msg_zerocopy_alloc(sk, size);
12734ab6c99dSWillem de Bruijn }
12748c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
12754ab6c99dSWillem de Bruijn 
12764ab6c99dSWillem de Bruijn static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
12774ab6c99dSWillem de Bruijn {
12784ab6c99dSWillem de Bruijn 	struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
12794ab6c99dSWillem de Bruijn 	u32 old_lo, old_hi;
12804ab6c99dSWillem de Bruijn 	u64 sum_len;
12814ab6c99dSWillem de Bruijn 
12824ab6c99dSWillem de Bruijn 	old_lo = serr->ee.ee_info;
12834ab6c99dSWillem de Bruijn 	old_hi = serr->ee.ee_data;
12844ab6c99dSWillem de Bruijn 	sum_len = old_hi - old_lo + 1ULL + len;
12854ab6c99dSWillem de Bruijn 
12864ab6c99dSWillem de Bruijn 	if (sum_len >= (1ULL << 32))
12874ab6c99dSWillem de Bruijn 		return false;
12884ab6c99dSWillem de Bruijn 
12894ab6c99dSWillem de Bruijn 	if (lo != old_hi + 1)
12904ab6c99dSWillem de Bruijn 		return false;
12914ab6c99dSWillem de Bruijn 
12924ab6c99dSWillem de Bruijn 	serr->ee.ee_data += len;
12934ab6c99dSWillem de Bruijn 	return true;
12944ab6c99dSWillem de Bruijn }
12954ab6c99dSWillem de Bruijn 
1296*e7d2b510SPavel Begunkov static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
129752267790SWillem de Bruijn {
12984ab6c99dSWillem de Bruijn 	struct sk_buff *tail, *skb = skb_from_uarg(uarg);
129952267790SWillem de Bruijn 	struct sock_exterr_skb *serr;
130052267790SWillem de Bruijn 	struct sock *sk = skb->sk;
13014ab6c99dSWillem de Bruijn 	struct sk_buff_head *q;
13024ab6c99dSWillem de Bruijn 	unsigned long flags;
13033bdd5ee0SWillem de Bruijn 	bool is_zerocopy;
13044ab6c99dSWillem de Bruijn 	u32 lo, hi;
13054ab6c99dSWillem de Bruijn 	u16 len;
130652267790SWillem de Bruijn 
1307ccaffff1SWillem de Bruijn 	mm_unaccount_pinned_pages(&uarg->mmp);
1308ccaffff1SWillem de Bruijn 
13094ab6c99dSWillem de Bruijn 	/* if !len, there was only 1 call, and it was aborted
13104ab6c99dSWillem de Bruijn 	 * so do not queue a completion notification
13114ab6c99dSWillem de Bruijn 	 */
13124ab6c99dSWillem de Bruijn 	if (!uarg->len || sock_flag(sk, SOCK_DEAD))
131352267790SWillem de Bruijn 		goto release;
131452267790SWillem de Bruijn 
13154ab6c99dSWillem de Bruijn 	len = uarg->len;
13164ab6c99dSWillem de Bruijn 	lo = uarg->id;
13174ab6c99dSWillem de Bruijn 	hi = uarg->id + len - 1;
13183bdd5ee0SWillem de Bruijn 	is_zerocopy = uarg->zerocopy;
13194ab6c99dSWillem de Bruijn 
132052267790SWillem de Bruijn 	serr = SKB_EXT_ERR(skb);
132152267790SWillem de Bruijn 	memset(serr, 0, sizeof(*serr));
132252267790SWillem de Bruijn 	serr->ee.ee_errno = 0;
132352267790SWillem de Bruijn 	serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
13244ab6c99dSWillem de Bruijn 	serr->ee.ee_data = hi;
13254ab6c99dSWillem de Bruijn 	serr->ee.ee_info = lo;
13263bdd5ee0SWillem de Bruijn 	if (!is_zerocopy)
132752267790SWillem de Bruijn 		serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
132852267790SWillem de Bruijn 
13294ab6c99dSWillem de Bruijn 	q = &sk->sk_error_queue;
13304ab6c99dSWillem de Bruijn 	spin_lock_irqsave(&q->lock, flags);
13314ab6c99dSWillem de Bruijn 	tail = skb_peek_tail(q);
13324ab6c99dSWillem de Bruijn 	if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
13334ab6c99dSWillem de Bruijn 	    !skb_zerocopy_notify_extend(tail, lo, len)) {
13344ab6c99dSWillem de Bruijn 		__skb_queue_tail(q, skb);
133552267790SWillem de Bruijn 		skb = NULL;
13364ab6c99dSWillem de Bruijn 	}
13374ab6c99dSWillem de Bruijn 	spin_unlock_irqrestore(&q->lock, flags);
133852267790SWillem de Bruijn 
1339e3ae2365SAlexander Aring 	sk_error_report(sk);
134052267790SWillem de Bruijn 
134152267790SWillem de Bruijn release:
134252267790SWillem de Bruijn 	consume_skb(skb);
134352267790SWillem de Bruijn 	sock_put(sk);
134452267790SWillem de Bruijn }
134575518851SJonathan Lemon 
13468c793822SJonathan Lemon void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
134736177832SJonathan Lemon 			   bool success)
134875518851SJonathan Lemon {
1349*e7d2b510SPavel Begunkov 	struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1350*e7d2b510SPavel Begunkov 
1351*e7d2b510SPavel Begunkov 	uarg_zc->zerocopy = uarg_zc->zerocopy & success;
135275518851SJonathan Lemon 
135375518851SJonathan Lemon 	if (refcount_dec_and_test(&uarg->refcnt))
1354*e7d2b510SPavel Begunkov 		__msg_zerocopy_callback(uarg_zc);
135575518851SJonathan Lemon }
13568c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
135752267790SWillem de Bruijn 
13588c793822SJonathan Lemon void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
135952267790SWillem de Bruijn {
1360*e7d2b510SPavel Begunkov 	struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
136152267790SWillem de Bruijn 
136252267790SWillem de Bruijn 	atomic_dec(&sk->sk_zckey);
1363*e7d2b510SPavel Begunkov 	uarg_to_msgzc(uarg)->len--;
136452267790SWillem de Bruijn 
136552900d22SWillem de Bruijn 	if (have_uref)
13668c793822SJonathan Lemon 		msg_zerocopy_callback(NULL, uarg, true);
136752267790SWillem de Bruijn }
13688c793822SJonathan Lemon EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
136952267790SWillem de Bruijn 
137052267790SWillem de Bruijn int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
137152267790SWillem de Bruijn 			     struct msghdr *msg, int len,
137252267790SWillem de Bruijn 			     struct ubuf_info *uarg)
137352267790SWillem de Bruijn {
13744ab6c99dSWillem de Bruijn 	struct ubuf_info *orig_uarg = skb_zcopy(skb);
137552267790SWillem de Bruijn 	int err, orig_len = skb->len;
137652267790SWillem de Bruijn 
13774ab6c99dSWillem de Bruijn 	/* An skb can only point to one uarg. This edge case happens when
13784ab6c99dSWillem de Bruijn 	 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
13794ab6c99dSWillem de Bruijn 	 */
13804ab6c99dSWillem de Bruijn 	if (orig_uarg && uarg != orig_uarg)
13814ab6c99dSWillem de Bruijn 		return -EEXIST;
13824ab6c99dSWillem de Bruijn 
1383ebe73a28SDavid Ahern 	err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
138452267790SWillem de Bruijn 	if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
138554d43117SWillem de Bruijn 		struct sock *save_sk = skb->sk;
138654d43117SWillem de Bruijn 
138752267790SWillem de Bruijn 		/* Streams do not free skb on error. Reset to prev state. */
1388829b7bddSPavel Begunkov 		iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
138954d43117SWillem de Bruijn 		skb->sk = sk;
139052267790SWillem de Bruijn 		___pskb_trim(skb, orig_len);
139154d43117SWillem de Bruijn 		skb->sk = save_sk;
139252267790SWillem de Bruijn 		return err;
139352267790SWillem de Bruijn 	}
139452267790SWillem de Bruijn 
139552900d22SWillem de Bruijn 	skb_zcopy_set(skb, uarg, NULL);
139652267790SWillem de Bruijn 	return skb->len - orig_len;
139752267790SWillem de Bruijn }
139852267790SWillem de Bruijn EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
139952267790SWillem de Bruijn 
1400753f1ca4SPavel Begunkov void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1401753f1ca4SPavel Begunkov {
1402753f1ca4SPavel Begunkov 	int i;
1403753f1ca4SPavel Begunkov 
1404753f1ca4SPavel Begunkov 	skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1405753f1ca4SPavel Begunkov 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1406753f1ca4SPavel Begunkov 		skb_frag_ref(skb, i);
1407753f1ca4SPavel Begunkov }
1408753f1ca4SPavel Begunkov EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1409753f1ca4SPavel Begunkov 
14101f8b977aSWillem de Bruijn static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
141152267790SWillem de Bruijn 			      gfp_t gfp_mask)
141252267790SWillem de Bruijn {
141352267790SWillem de Bruijn 	if (skb_zcopy(orig)) {
141452267790SWillem de Bruijn 		if (skb_zcopy(nskb)) {
141552267790SWillem de Bruijn 			/* !gfp_mask callers are verified to !skb_zcopy(nskb) */
141652267790SWillem de Bruijn 			if (!gfp_mask) {
141752267790SWillem de Bruijn 				WARN_ON_ONCE(1);
141852267790SWillem de Bruijn 				return -ENOMEM;
141952267790SWillem de Bruijn 			}
142052267790SWillem de Bruijn 			if (skb_uarg(nskb) == skb_uarg(orig))
142152267790SWillem de Bruijn 				return 0;
142252267790SWillem de Bruijn 			if (skb_copy_ubufs(nskb, GFP_ATOMIC))
142352267790SWillem de Bruijn 				return -EIO;
142452267790SWillem de Bruijn 		}
142552900d22SWillem de Bruijn 		skb_zcopy_set(nskb, skb_uarg(orig), NULL);
142652267790SWillem de Bruijn 	}
142752267790SWillem de Bruijn 	return 0;
142852267790SWillem de Bruijn }
142952267790SWillem de Bruijn 
14302c53040fSBen Hutchings /**
14312c53040fSBen Hutchings  *	skb_copy_ubufs	-	copy userspace skb frags buffers to kernel
143248c83012SMichael S. Tsirkin  *	@skb: the skb to modify
143348c83012SMichael S. Tsirkin  *	@gfp_mask: allocation priority
143448c83012SMichael S. Tsirkin  *
143506b4feb3SJonathan Lemon  *	This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
143648c83012SMichael S. Tsirkin  *	It will copy all frags into kernel and drop the reference
143748c83012SMichael S. Tsirkin  *	to userspace pages.
143848c83012SMichael S. Tsirkin  *
143948c83012SMichael S. Tsirkin  *	If this function is called from an interrupt gfp_mask() must be
144048c83012SMichael S. Tsirkin  *	%GFP_ATOMIC.
144148c83012SMichael S. Tsirkin  *
144248c83012SMichael S. Tsirkin  *	Returns 0 on success or a negative error code on failure
144348c83012SMichael S. Tsirkin  *	to allocate kernel memory to copy to.
144448c83012SMichael S. Tsirkin  */
144548c83012SMichael S. Tsirkin int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1446a6686f2fSShirley Ma {
1447a6686f2fSShirley Ma 	int num_frags = skb_shinfo(skb)->nr_frags;
1448a6686f2fSShirley Ma 	struct page *page, *head = NULL;
14493ece7826SWillem de Bruijn 	int i, new_frags;
14503ece7826SWillem de Bruijn 	u32 d_off;
1451a6686f2fSShirley Ma 
14523ece7826SWillem de Bruijn 	if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
14533ece7826SWillem de Bruijn 		return -EINVAL;
14543ece7826SWillem de Bruijn 
1455f72c4ac6SWillem de Bruijn 	if (!num_frags)
1456f72c4ac6SWillem de Bruijn 		goto release;
1457f72c4ac6SWillem de Bruijn 
14583ece7826SWillem de Bruijn 	new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
14593ece7826SWillem de Bruijn 	for (i = 0; i < new_frags; i++) {
146002756ed4SKrishna Kumar 		page = alloc_page(gfp_mask);
1461a6686f2fSShirley Ma 		if (!page) {
1462a6686f2fSShirley Ma 			while (head) {
146340dadff2SSunghan Suh 				struct page *next = (struct page *)page_private(head);
1464a6686f2fSShirley Ma 				put_page(head);
1465a6686f2fSShirley Ma 				head = next;
1466a6686f2fSShirley Ma 			}
1467a6686f2fSShirley Ma 			return -ENOMEM;
1468a6686f2fSShirley Ma 		}
14693ece7826SWillem de Bruijn 		set_page_private(page, (unsigned long)head);
14703ece7826SWillem de Bruijn 		head = page;
14713ece7826SWillem de Bruijn 	}
14723ece7826SWillem de Bruijn 
14733ece7826SWillem de Bruijn 	page = head;
14743ece7826SWillem de Bruijn 	d_off = 0;
14753ece7826SWillem de Bruijn 	for (i = 0; i < num_frags; i++) {
14763ece7826SWillem de Bruijn 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
14773ece7826SWillem de Bruijn 		u32 p_off, p_len, copied;
14783ece7826SWillem de Bruijn 		struct page *p;
14793ece7826SWillem de Bruijn 		u8 *vaddr;
1480c613c209SWillem de Bruijn 
1481b54c9d5bSJonathan Lemon 		skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1482c613c209SWillem de Bruijn 				      p, p_off, p_len, copied) {
14833ece7826SWillem de Bruijn 			u32 copy, done = 0;
1484c613c209SWillem de Bruijn 			vaddr = kmap_atomic(p);
14853ece7826SWillem de Bruijn 
14863ece7826SWillem de Bruijn 			while (done < p_len) {
14873ece7826SWillem de Bruijn 				if (d_off == PAGE_SIZE) {
14883ece7826SWillem de Bruijn 					d_off = 0;
14893ece7826SWillem de Bruijn 					page = (struct page *)page_private(page);
14903ece7826SWillem de Bruijn 				}
14913ece7826SWillem de Bruijn 				copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
14923ece7826SWillem de Bruijn 				memcpy(page_address(page) + d_off,
14933ece7826SWillem de Bruijn 				       vaddr + p_off + done, copy);
14943ece7826SWillem de Bruijn 				done += copy;
14953ece7826SWillem de Bruijn 				d_off += copy;
14963ece7826SWillem de Bruijn 			}
149751c56b00SEric Dumazet 			kunmap_atomic(vaddr);
1498c613c209SWillem de Bruijn 		}
1499a6686f2fSShirley Ma 	}
1500a6686f2fSShirley Ma 
1501a6686f2fSShirley Ma 	/* skb frags release userspace buffers */
150202756ed4SKrishna Kumar 	for (i = 0; i < num_frags; i++)
1503a8605c60SIan Campbell 		skb_frag_unref(skb, i);
1504a6686f2fSShirley Ma 
1505a6686f2fSShirley Ma 	/* skb frags point to kernel buffers */
15063ece7826SWillem de Bruijn 	for (i = 0; i < new_frags - 1; i++) {
15073ece7826SWillem de Bruijn 		__skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
150840dadff2SSunghan Suh 		head = (struct page *)page_private(head);
1509a6686f2fSShirley Ma 	}
15103ece7826SWillem de Bruijn 	__skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
15113ece7826SWillem de Bruijn 	skb_shinfo(skb)->nr_frags = new_frags;
151248c83012SMichael S. Tsirkin 
1513b90ddd56SWillem de Bruijn release:
15141f8b977aSWillem de Bruijn 	skb_zcopy_clear(skb, false);
1515a6686f2fSShirley Ma 	return 0;
1516a6686f2fSShirley Ma }
1517dcc0fb78SMichael S. Tsirkin EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1518a6686f2fSShirley Ma 
1519e0053ec0SHerbert Xu /**
1520e0053ec0SHerbert Xu  *	skb_clone	-	duplicate an sk_buff
1521e0053ec0SHerbert Xu  *	@skb: buffer to clone
1522e0053ec0SHerbert Xu  *	@gfp_mask: allocation priority
1523e0053ec0SHerbert Xu  *
1524e0053ec0SHerbert Xu  *	Duplicate an &sk_buff. The new one is not owned by a socket. Both
1525e0053ec0SHerbert Xu  *	copies share the same packet data but not structure. The new
1526e0053ec0SHerbert Xu  *	buffer has a reference count of 1. If the allocation fails the
1527e0053ec0SHerbert Xu  *	function returns %NULL otherwise the new buffer is returned.
1528e0053ec0SHerbert Xu  *
1529e0053ec0SHerbert Xu  *	If this function is called from an interrupt gfp_mask() must be
1530e0053ec0SHerbert Xu  *	%GFP_ATOMIC.
1531e0053ec0SHerbert Xu  */
1532e0053ec0SHerbert Xu 
1533e0053ec0SHerbert Xu struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1534e0053ec0SHerbert Xu {
1535d0bf4a9eSEric Dumazet 	struct sk_buff_fclones *fclones = container_of(skb,
1536d0bf4a9eSEric Dumazet 						       struct sk_buff_fclones,
1537d0bf4a9eSEric Dumazet 						       skb1);
15386ffe75ebSEric Dumazet 	struct sk_buff *n;
1539e0053ec0SHerbert Xu 
154070008aa5SMichael S. Tsirkin 	if (skb_orphan_frags(skb, gfp_mask))
1541a6686f2fSShirley Ma 		return NULL;
1542a6686f2fSShirley Ma 
1543e0053ec0SHerbert Xu 	if (skb->fclone == SKB_FCLONE_ORIG &&
15442638595aSReshetova, Elena 	    refcount_read(&fclones->fclone_ref) == 1) {
15456ffe75ebSEric Dumazet 		n = &fclones->skb2;
15462638595aSReshetova, Elena 		refcount_set(&fclones->fclone_ref, 2);
1547c2dd4059SEric Dumazet 		n->fclone = SKB_FCLONE_CLONE;
1548e0053ec0SHerbert Xu 	} else {
1549c93bdd0eSMel Gorman 		if (skb_pfmemalloc(skb))
1550c93bdd0eSMel Gorman 			gfp_mask |= __GFP_MEMALLOC;
1551c93bdd0eSMel Gorman 
1552e0053ec0SHerbert Xu 		n = kmem_cache_alloc(skbuff_head_cache, gfp_mask);
1553e0053ec0SHerbert Xu 		if (!n)
1554e0053ec0SHerbert Xu 			return NULL;
1555fe55f6d5SVegard Nossum 
1556e0053ec0SHerbert Xu 		n->fclone = SKB_FCLONE_UNAVAILABLE;
1557e0053ec0SHerbert Xu 	}
1558e0053ec0SHerbert Xu 
1559e0053ec0SHerbert Xu 	return __skb_clone(n, skb);
15601da177e4SLinus Torvalds }
1561b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_clone);
15621da177e4SLinus Torvalds 
1563b0768a86SToshiaki Makita void skb_headers_offset_update(struct sk_buff *skb, int off)
1564f5b17294SPravin B Shelar {
1565030737bcSEric Dumazet 	/* Only adjust this if it actually is csum_start rather than csum */
1566030737bcSEric Dumazet 	if (skb->ip_summed == CHECKSUM_PARTIAL)
1567030737bcSEric Dumazet 		skb->csum_start += off;
1568f5b17294SPravin B Shelar 	/* {transport,network,mac}_header and tail are relative to skb->head */
1569f5b17294SPravin B Shelar 	skb->transport_header += off;
1570f5b17294SPravin B Shelar 	skb->network_header   += off;
1571f5b17294SPravin B Shelar 	if (skb_mac_header_was_set(skb))
1572f5b17294SPravin B Shelar 		skb->mac_header += off;
1573f5b17294SPravin B Shelar 	skb->inner_transport_header += off;
1574f5b17294SPravin B Shelar 	skb->inner_network_header += off;
1575aefbd2b3SPravin B Shelar 	skb->inner_mac_header += off;
1576f5b17294SPravin B Shelar }
1577b0768a86SToshiaki Makita EXPORT_SYMBOL(skb_headers_offset_update);
1578f5b17294SPravin B Shelar 
157908303c18SIlya Lesokhin void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
15801da177e4SLinus Torvalds {
1581dec18810SHerbert Xu 	__copy_skb_header(new, old);
1582dec18810SHerbert Xu 
15837967168cSHerbert Xu 	skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
15847967168cSHerbert Xu 	skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
15857967168cSHerbert Xu 	skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
15861da177e4SLinus Torvalds }
158708303c18SIlya Lesokhin EXPORT_SYMBOL(skb_copy_header);
15881da177e4SLinus Torvalds 
1589c93bdd0eSMel Gorman static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1590c93bdd0eSMel Gorman {
1591c93bdd0eSMel Gorman 	if (skb_pfmemalloc(skb))
1592c93bdd0eSMel Gorman 		return SKB_ALLOC_RX;
1593c93bdd0eSMel Gorman 	return 0;
1594c93bdd0eSMel Gorman }
1595c93bdd0eSMel Gorman 
15961da177e4SLinus Torvalds /**
15971da177e4SLinus Torvalds  *	skb_copy	-	create private copy of an sk_buff
15981da177e4SLinus Torvalds  *	@skb: buffer to copy
15991da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
16001da177e4SLinus Torvalds  *
16011da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and its data. This is used when the
16021da177e4SLinus Torvalds  *	caller wishes to modify the data and needs a private copy of the
16031da177e4SLinus Torvalds  *	data to alter. Returns %NULL on failure or the pointer to the buffer
16041da177e4SLinus Torvalds  *	on success. The returned buffer has a reference count of 1.
16051da177e4SLinus Torvalds  *
16061da177e4SLinus Torvalds  *	As by-product this function converts non-linear &sk_buff to linear
16071da177e4SLinus Torvalds  *	one, so that &sk_buff becomes completely private and caller is allowed
16081da177e4SLinus Torvalds  *	to modify all the data of returned buffer. This means that this
16091da177e4SLinus Torvalds  *	function is not recommended for use in circumstances when only
16101da177e4SLinus Torvalds  *	header is going to be modified. Use pskb_copy() instead.
16111da177e4SLinus Torvalds  */
16121da177e4SLinus Torvalds 
1613dd0fc66fSAl Viro struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
16141da177e4SLinus Torvalds {
16156602cebbSEric Dumazet 	int headerlen = skb_headroom(skb);
1616ec47ea82SAlexander Duyck 	unsigned int size = skb_end_offset(skb) + skb->data_len;
1617c93bdd0eSMel Gorman 	struct sk_buff *n = __alloc_skb(size, gfp_mask,
1618c93bdd0eSMel Gorman 					skb_alloc_rx_flag(skb), NUMA_NO_NODE);
16196602cebbSEric Dumazet 
16201da177e4SLinus Torvalds 	if (!n)
16211da177e4SLinus Torvalds 		return NULL;
16221da177e4SLinus Torvalds 
16231da177e4SLinus Torvalds 	/* Set the data pointer */
16241da177e4SLinus Torvalds 	skb_reserve(n, headerlen);
16251da177e4SLinus Torvalds 	/* Set the tail pointer and length */
16261da177e4SLinus Torvalds 	skb_put(n, skb->len);
16271da177e4SLinus Torvalds 
16289f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
16291da177e4SLinus Torvalds 
163008303c18SIlya Lesokhin 	skb_copy_header(n, skb);
16311da177e4SLinus Torvalds 	return n;
16321da177e4SLinus Torvalds }
1633b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy);
16341da177e4SLinus Torvalds 
16351da177e4SLinus Torvalds /**
1636bad93e9dSOctavian Purdila  *	__pskb_copy_fclone	-  create copy of an sk_buff with private head.
16371da177e4SLinus Torvalds  *	@skb: buffer to copy
1638117632e6SEric Dumazet  *	@headroom: headroom of new skb
16391da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
1640bad93e9dSOctavian Purdila  *	@fclone: if true allocate the copy of the skb from the fclone
1641bad93e9dSOctavian Purdila  *	cache instead of the head cache; it is recommended to set this
1642bad93e9dSOctavian Purdila  *	to true for the cases where the copy will likely be cloned
16431da177e4SLinus Torvalds  *
16441da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and part of its data, located
16451da177e4SLinus Torvalds  *	in header. Fragmented data remain shared. This is used when
16461da177e4SLinus Torvalds  *	the caller wishes to modify only header of &sk_buff and needs
16471da177e4SLinus Torvalds  *	private copy of the header to alter. Returns %NULL on failure
16481da177e4SLinus Torvalds  *	or the pointer to the buffer on success.
16491da177e4SLinus Torvalds  *	The returned buffer has a reference count of 1.
16501da177e4SLinus Torvalds  */
16511da177e4SLinus Torvalds 
1652bad93e9dSOctavian Purdila struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1653bad93e9dSOctavian Purdila 				   gfp_t gfp_mask, bool fclone)
16541da177e4SLinus Torvalds {
1655117632e6SEric Dumazet 	unsigned int size = skb_headlen(skb) + headroom;
1656bad93e9dSOctavian Purdila 	int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1657bad93e9dSOctavian Purdila 	struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
16586602cebbSEric Dumazet 
16591da177e4SLinus Torvalds 	if (!n)
16601da177e4SLinus Torvalds 		goto out;
16611da177e4SLinus Torvalds 
16621da177e4SLinus Torvalds 	/* Set the data pointer */
1663117632e6SEric Dumazet 	skb_reserve(n, headroom);
16641da177e4SLinus Torvalds 	/* Set the tail pointer and length */
16651da177e4SLinus Torvalds 	skb_put(n, skb_headlen(skb));
16661da177e4SLinus Torvalds 	/* Copy the bytes */
1667d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data(skb, n->data, n->len);
16681da177e4SLinus Torvalds 
166925f484a6SHerbert Xu 	n->truesize += skb->data_len;
16701da177e4SLinus Torvalds 	n->data_len  = skb->data_len;
16711da177e4SLinus Torvalds 	n->len	     = skb->len;
16721da177e4SLinus Torvalds 
16731da177e4SLinus Torvalds 	if (skb_shinfo(skb)->nr_frags) {
16741da177e4SLinus Torvalds 		int i;
16751da177e4SLinus Torvalds 
16761f8b977aSWillem de Bruijn 		if (skb_orphan_frags(skb, gfp_mask) ||
16771f8b977aSWillem de Bruijn 		    skb_zerocopy_clone(n, skb, gfp_mask)) {
16781511022cSDan Carpenter 			kfree_skb(n);
16791511022cSDan Carpenter 			n = NULL;
1680a6686f2fSShirley Ma 			goto out;
1681a6686f2fSShirley Ma 		}
16821da177e4SLinus Torvalds 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
16831da177e4SLinus Torvalds 			skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1684ea2ab693SIan Campbell 			skb_frag_ref(skb, i);
16851da177e4SLinus Torvalds 		}
16861da177e4SLinus Torvalds 		skb_shinfo(n)->nr_frags = i;
16871da177e4SLinus Torvalds 	}
16881da177e4SLinus Torvalds 
168921dc3301SDavid S. Miller 	if (skb_has_frag_list(skb)) {
16901da177e4SLinus Torvalds 		skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
16911da177e4SLinus Torvalds 		skb_clone_fraglist(n);
16921da177e4SLinus Torvalds 	}
16931da177e4SLinus Torvalds 
169408303c18SIlya Lesokhin 	skb_copy_header(n, skb);
16951da177e4SLinus Torvalds out:
16961da177e4SLinus Torvalds 	return n;
16971da177e4SLinus Torvalds }
1698bad93e9dSOctavian Purdila EXPORT_SYMBOL(__pskb_copy_fclone);
16991da177e4SLinus Torvalds 
17001da177e4SLinus Torvalds /**
17011da177e4SLinus Torvalds  *	pskb_expand_head - reallocate header of &sk_buff
17021da177e4SLinus Torvalds  *	@skb: buffer to reallocate
17031da177e4SLinus Torvalds  *	@nhead: room to add at head
17041da177e4SLinus Torvalds  *	@ntail: room to add at tail
17051da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
17061da177e4SLinus Torvalds  *
1707bc32383cSMathias Krause  *	Expands (or creates identical copy, if @nhead and @ntail are zero)
1708bc32383cSMathias Krause  *	header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
17091da177e4SLinus Torvalds  *	reference count of 1. Returns zero in the case of success or error,
17101da177e4SLinus Torvalds  *	if expansion failed. In the last case, &sk_buff is not changed.
17111da177e4SLinus Torvalds  *
17121da177e4SLinus Torvalds  *	All the pointers pointing into skb header may change and must be
17131da177e4SLinus Torvalds  *	reloaded after call to this function.
17141da177e4SLinus Torvalds  */
17151da177e4SLinus Torvalds 
171686a76cafSVictor Fusco int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1717dd0fc66fSAl Viro 		     gfp_t gfp_mask)
17181da177e4SLinus Torvalds {
1719158f323bSEric Dumazet 	int i, osize = skb_end_offset(skb);
1720158f323bSEric Dumazet 	int size = osize + nhead + ntail;
17211da177e4SLinus Torvalds 	long off;
1722158f323bSEric Dumazet 	u8 *data;
17231da177e4SLinus Torvalds 
17244edd87adSHerbert Xu 	BUG_ON(nhead < 0);
17254edd87adSHerbert Xu 
17269f77fad3STim Hansen 	BUG_ON(skb_shared(skb));
17271da177e4SLinus Torvalds 
1728753f1ca4SPavel Begunkov 	skb_zcopy_downgrade_managed(skb);
1729753f1ca4SPavel Begunkov 
17301da177e4SLinus Torvalds 	size = SKB_DATA_ALIGN(size);
17311da177e4SLinus Torvalds 
1732c93bdd0eSMel Gorman 	if (skb_pfmemalloc(skb))
1733c93bdd0eSMel Gorman 		gfp_mask |= __GFP_MEMALLOC;
1734c93bdd0eSMel Gorman 	data = kmalloc_reserve(size + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
1735c93bdd0eSMel Gorman 			       gfp_mask, NUMA_NO_NODE, NULL);
17361da177e4SLinus Torvalds 	if (!data)
17371da177e4SLinus Torvalds 		goto nodata;
173887151b86SEric Dumazet 	size = SKB_WITH_OVERHEAD(ksize(data));
17391da177e4SLinus Torvalds 
17401da177e4SLinus Torvalds 	/* Copy only real data... and, alas, header. This should be
17416602cebbSEric Dumazet 	 * optimized for the cases when header is void.
17426602cebbSEric Dumazet 	 */
17436602cebbSEric Dumazet 	memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
17446602cebbSEric Dumazet 
17456602cebbSEric Dumazet 	memcpy((struct skb_shared_info *)(data + size),
17466602cebbSEric Dumazet 	       skb_shinfo(skb),
1747fed66381SEric Dumazet 	       offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
17481da177e4SLinus Torvalds 
17493e24591aSAlexander Duyck 	/*
17503e24591aSAlexander Duyck 	 * if shinfo is shared we must drop the old head gracefully, but if it
17513e24591aSAlexander Duyck 	 * is not we can just drop the old head and let the existing refcount
17523e24591aSAlexander Duyck 	 * be since all we did is relocate the values
17533e24591aSAlexander Duyck 	 */
17543e24591aSAlexander Duyck 	if (skb_cloned(skb)) {
175570008aa5SMichael S. Tsirkin 		if (skb_orphan_frags(skb, gfp_mask))
1756a6686f2fSShirley Ma 			goto nofrags;
17571f8b977aSWillem de Bruijn 		if (skb_zcopy(skb))
1758c1d1b437SEric Dumazet 			refcount_inc(&skb_uarg(skb)->refcnt);
17591da177e4SLinus Torvalds 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1760ea2ab693SIan Campbell 			skb_frag_ref(skb, i);
17611da177e4SLinus Torvalds 
176221dc3301SDavid S. Miller 		if (skb_has_frag_list(skb))
17631da177e4SLinus Torvalds 			skb_clone_fraglist(skb);
17641da177e4SLinus Torvalds 
17651da177e4SLinus Torvalds 		skb_release_data(skb);
17663e24591aSAlexander Duyck 	} else {
17673e24591aSAlexander Duyck 		skb_free_head(skb);
17681fd63041SEric Dumazet 	}
17691da177e4SLinus Torvalds 	off = (data + nhead) - skb->head;
17701da177e4SLinus Torvalds 
17711da177e4SLinus Torvalds 	skb->head     = data;
1772d3836f21SEric Dumazet 	skb->head_frag = 0;
17731da177e4SLinus Torvalds 	skb->data    += off;
1774763087daSEric Dumazet 
1775763087daSEric Dumazet 	skb_set_end_offset(skb, size);
17764305b541SArnaldo Carvalho de Melo #ifdef NET_SKBUFF_DATA_USES_OFFSET
177756eb8882SPatrick McHardy 	off           = nhead;
177856eb8882SPatrick McHardy #endif
177927a884dcSArnaldo Carvalho de Melo 	skb->tail	      += off;
1780b41abb42SPeter Pan(潘卫平) 	skb_headers_offset_update(skb, nhead);
17811da177e4SLinus Torvalds 	skb->cloned   = 0;
1782334a8132SPatrick McHardy 	skb->hdr_len  = 0;
17831da177e4SLinus Torvalds 	skb->nohdr    = 0;
17841da177e4SLinus Torvalds 	atomic_set(&skb_shinfo(skb)->dataref, 1);
1785158f323bSEric Dumazet 
1786de8f3a83SDaniel Borkmann 	skb_metadata_clear(skb);
1787de8f3a83SDaniel Borkmann 
1788158f323bSEric Dumazet 	/* It is not generally safe to change skb->truesize.
1789158f323bSEric Dumazet 	 * For the moment, we really care of rx path, or
1790158f323bSEric Dumazet 	 * when skb is orphaned (not attached to a socket).
1791158f323bSEric Dumazet 	 */
1792158f323bSEric Dumazet 	if (!skb->sk || skb->destructor == sock_edemux)
1793158f323bSEric Dumazet 		skb->truesize += size - osize;
1794158f323bSEric Dumazet 
17951da177e4SLinus Torvalds 	return 0;
17961da177e4SLinus Torvalds 
1797a6686f2fSShirley Ma nofrags:
1798a6686f2fSShirley Ma 	kfree(data);
17991da177e4SLinus Torvalds nodata:
18001da177e4SLinus Torvalds 	return -ENOMEM;
18011da177e4SLinus Torvalds }
1802b4ac530fSDavid S. Miller EXPORT_SYMBOL(pskb_expand_head);
18031da177e4SLinus Torvalds 
18041da177e4SLinus Torvalds /* Make private copy of skb with writable head and some headroom */
18051da177e4SLinus Torvalds 
18061da177e4SLinus Torvalds struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
18071da177e4SLinus Torvalds {
18081da177e4SLinus Torvalds 	struct sk_buff *skb2;
18091da177e4SLinus Torvalds 	int delta = headroom - skb_headroom(skb);
18101da177e4SLinus Torvalds 
18111da177e4SLinus Torvalds 	if (delta <= 0)
18121da177e4SLinus Torvalds 		skb2 = pskb_copy(skb, GFP_ATOMIC);
18131da177e4SLinus Torvalds 	else {
18141da177e4SLinus Torvalds 		skb2 = skb_clone(skb, GFP_ATOMIC);
18151da177e4SLinus Torvalds 		if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
18161da177e4SLinus Torvalds 					     GFP_ATOMIC)) {
18171da177e4SLinus Torvalds 			kfree_skb(skb2);
18181da177e4SLinus Torvalds 			skb2 = NULL;
18191da177e4SLinus Torvalds 		}
18201da177e4SLinus Torvalds 	}
18211da177e4SLinus Torvalds 	return skb2;
18221da177e4SLinus Torvalds }
1823b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_realloc_headroom);
18241da177e4SLinus Torvalds 
18252b88cba5SEric Dumazet int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
18262b88cba5SEric Dumazet {
18272b88cba5SEric Dumazet 	unsigned int saved_end_offset, saved_truesize;
18282b88cba5SEric Dumazet 	struct skb_shared_info *shinfo;
18292b88cba5SEric Dumazet 	int res;
18302b88cba5SEric Dumazet 
18312b88cba5SEric Dumazet 	saved_end_offset = skb_end_offset(skb);
18322b88cba5SEric Dumazet 	saved_truesize = skb->truesize;
18332b88cba5SEric Dumazet 
18342b88cba5SEric Dumazet 	res = pskb_expand_head(skb, 0, 0, pri);
18352b88cba5SEric Dumazet 	if (res)
18362b88cba5SEric Dumazet 		return res;
18372b88cba5SEric Dumazet 
18382b88cba5SEric Dumazet 	skb->truesize = saved_truesize;
18392b88cba5SEric Dumazet 
18402b88cba5SEric Dumazet 	if (likely(skb_end_offset(skb) == saved_end_offset))
18412b88cba5SEric Dumazet 		return 0;
18422b88cba5SEric Dumazet 
18432b88cba5SEric Dumazet 	shinfo = skb_shinfo(skb);
18442b88cba5SEric Dumazet 
18452b88cba5SEric Dumazet 	/* We are about to change back skb->end,
18462b88cba5SEric Dumazet 	 * we need to move skb_shinfo() to its new location.
18472b88cba5SEric Dumazet 	 */
18482b88cba5SEric Dumazet 	memmove(skb->head + saved_end_offset,
18492b88cba5SEric Dumazet 		shinfo,
18502b88cba5SEric Dumazet 		offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
18512b88cba5SEric Dumazet 
18522b88cba5SEric Dumazet 	skb_set_end_offset(skb, saved_end_offset);
18532b88cba5SEric Dumazet 
18542b88cba5SEric Dumazet 	return 0;
18552b88cba5SEric Dumazet }
18562b88cba5SEric Dumazet 
18571da177e4SLinus Torvalds /**
1858f1260ff1SVasily Averin  *	skb_expand_head - reallocate header of &sk_buff
1859f1260ff1SVasily Averin  *	@skb: buffer to reallocate
1860f1260ff1SVasily Averin  *	@headroom: needed headroom
1861f1260ff1SVasily Averin  *
1862f1260ff1SVasily Averin  *	Unlike skb_realloc_headroom, this one does not allocate a new skb
1863f1260ff1SVasily Averin  *	if possible; copies skb->sk to new skb as needed
1864f1260ff1SVasily Averin  *	and frees original skb in case of failures.
1865f1260ff1SVasily Averin  *
1866f1260ff1SVasily Averin  *	It expect increased headroom and generates warning otherwise.
1867f1260ff1SVasily Averin  */
1868f1260ff1SVasily Averin 
1869f1260ff1SVasily Averin struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
1870f1260ff1SVasily Averin {
1871f1260ff1SVasily Averin 	int delta = headroom - skb_headroom(skb);
18727f678defSVasily Averin 	int osize = skb_end_offset(skb);
18737f678defSVasily Averin 	struct sock *sk = skb->sk;
1874f1260ff1SVasily Averin 
1875f1260ff1SVasily Averin 	if (WARN_ONCE(delta <= 0,
1876f1260ff1SVasily Averin 		      "%s is expecting an increase in the headroom", __func__))
1877f1260ff1SVasily Averin 		return skb;
1878f1260ff1SVasily Averin 
18797f678defSVasily Averin 	delta = SKB_DATA_ALIGN(delta);
18807f678defSVasily Averin 	/* pskb_expand_head() might crash, if skb is shared. */
18817f678defSVasily Averin 	if (skb_shared(skb) || !is_skb_wmem(skb)) {
1882f1260ff1SVasily Averin 		struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1883f1260ff1SVasily Averin 
18847f678defSVasily Averin 		if (unlikely(!nskb))
18857f678defSVasily Averin 			goto fail;
18867f678defSVasily Averin 
18877f678defSVasily Averin 		if (sk)
18887f678defSVasily Averin 			skb_set_owner_w(nskb, sk);
1889f1260ff1SVasily Averin 		consume_skb(skb);
1890f1260ff1SVasily Averin 		skb = nskb;
1891f1260ff1SVasily Averin 	}
18927f678defSVasily Averin 	if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
18937f678defSVasily Averin 		goto fail;
18947f678defSVasily Averin 
18957f678defSVasily Averin 	if (sk && is_skb_wmem(skb)) {
18967f678defSVasily Averin 		delta = skb_end_offset(skb) - osize;
18977f678defSVasily Averin 		refcount_add(delta, &sk->sk_wmem_alloc);
18987f678defSVasily Averin 		skb->truesize += delta;
1899f1260ff1SVasily Averin 	}
1900f1260ff1SVasily Averin 	return skb;
19017f678defSVasily Averin 
19027f678defSVasily Averin fail:
19037f678defSVasily Averin 	kfree_skb(skb);
19047f678defSVasily Averin 	return NULL;
1905f1260ff1SVasily Averin }
1906f1260ff1SVasily Averin EXPORT_SYMBOL(skb_expand_head);
1907f1260ff1SVasily Averin 
1908f1260ff1SVasily Averin /**
19091da177e4SLinus Torvalds  *	skb_copy_expand	-	copy and expand sk_buff
19101da177e4SLinus Torvalds  *	@skb: buffer to copy
19111da177e4SLinus Torvalds  *	@newheadroom: new free bytes at head
19121da177e4SLinus Torvalds  *	@newtailroom: new free bytes at tail
19131da177e4SLinus Torvalds  *	@gfp_mask: allocation priority
19141da177e4SLinus Torvalds  *
19151da177e4SLinus Torvalds  *	Make a copy of both an &sk_buff and its data and while doing so
19161da177e4SLinus Torvalds  *	allocate additional space.
19171da177e4SLinus Torvalds  *
19181da177e4SLinus Torvalds  *	This is used when the caller wishes to modify the data and needs a
19191da177e4SLinus Torvalds  *	private copy of the data to alter as well as more space for new fields.
19201da177e4SLinus Torvalds  *	Returns %NULL on failure or the pointer to the buffer
19211da177e4SLinus Torvalds  *	on success. The returned buffer has a reference count of 1.
19221da177e4SLinus Torvalds  *
19231da177e4SLinus Torvalds  *	You must pass %GFP_ATOMIC as the allocation priority if this function
19241da177e4SLinus Torvalds  *	is called from an interrupt.
19251da177e4SLinus Torvalds  */
19261da177e4SLinus Torvalds struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
192786a76cafSVictor Fusco 				int newheadroom, int newtailroom,
1928dd0fc66fSAl Viro 				gfp_t gfp_mask)
19291da177e4SLinus Torvalds {
19301da177e4SLinus Torvalds 	/*
19311da177e4SLinus Torvalds 	 *	Allocate the copy buffer
19321da177e4SLinus Torvalds 	 */
1933c93bdd0eSMel Gorman 	struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
1934c93bdd0eSMel Gorman 					gfp_mask, skb_alloc_rx_flag(skb),
1935c93bdd0eSMel Gorman 					NUMA_NO_NODE);
1936efd1e8d5SPatrick McHardy 	int oldheadroom = skb_headroom(skb);
19371da177e4SLinus Torvalds 	int head_copy_len, head_copy_off;
19381da177e4SLinus Torvalds 
19391da177e4SLinus Torvalds 	if (!n)
19401da177e4SLinus Torvalds 		return NULL;
19411da177e4SLinus Torvalds 
19421da177e4SLinus Torvalds 	skb_reserve(n, newheadroom);
19431da177e4SLinus Torvalds 
19441da177e4SLinus Torvalds 	/* Set the tail pointer and length */
19451da177e4SLinus Torvalds 	skb_put(n, skb->len);
19461da177e4SLinus Torvalds 
1947efd1e8d5SPatrick McHardy 	head_copy_len = oldheadroom;
19481da177e4SLinus Torvalds 	head_copy_off = 0;
19491da177e4SLinus Torvalds 	if (newheadroom <= head_copy_len)
19501da177e4SLinus Torvalds 		head_copy_len = newheadroom;
19511da177e4SLinus Torvalds 	else
19521da177e4SLinus Torvalds 		head_copy_off = newheadroom - head_copy_len;
19531da177e4SLinus Torvalds 
19541da177e4SLinus Torvalds 	/* Copy the linear header and data. */
19559f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
19569f77fad3STim Hansen 			     skb->len + head_copy_len));
19571da177e4SLinus Torvalds 
195808303c18SIlya Lesokhin 	skb_copy_header(n, skb);
19591da177e4SLinus Torvalds 
1960030737bcSEric Dumazet 	skb_headers_offset_update(n, newheadroom - oldheadroom);
1961efd1e8d5SPatrick McHardy 
19621da177e4SLinus Torvalds 	return n;
19631da177e4SLinus Torvalds }
1964b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_expand);
19651da177e4SLinus Torvalds 
19661da177e4SLinus Torvalds /**
1967cd0a137aSFlorian Fainelli  *	__skb_pad		-	zero pad the tail of an skb
19681da177e4SLinus Torvalds  *	@skb: buffer to pad
19691da177e4SLinus Torvalds  *	@pad: space to pad
1970cd0a137aSFlorian Fainelli  *	@free_on_error: free buffer on error
19711da177e4SLinus Torvalds  *
19721da177e4SLinus Torvalds  *	Ensure that a buffer is followed by a padding area that is zero
19731da177e4SLinus Torvalds  *	filled. Used by network drivers which may DMA or transfer data
19741da177e4SLinus Torvalds  *	beyond the buffer end onto the wire.
19751da177e4SLinus Torvalds  *
1976cd0a137aSFlorian Fainelli  *	May return error in out of memory cases. The skb is freed on error
1977cd0a137aSFlorian Fainelli  *	if @free_on_error is true.
19781da177e4SLinus Torvalds  */
19791da177e4SLinus Torvalds 
1980cd0a137aSFlorian Fainelli int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
19811da177e4SLinus Torvalds {
19825b057c6bSHerbert Xu 	int err;
19835b057c6bSHerbert Xu 	int ntail;
19841da177e4SLinus Torvalds 
19851da177e4SLinus Torvalds 	/* If the skbuff is non linear tailroom is always zero.. */
19865b057c6bSHerbert Xu 	if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
19871da177e4SLinus Torvalds 		memset(skb->data+skb->len, 0, pad);
19885b057c6bSHerbert Xu 		return 0;
19891da177e4SLinus Torvalds 	}
19901da177e4SLinus Torvalds 
19914305b541SArnaldo Carvalho de Melo 	ntail = skb->data_len + pad - (skb->end - skb->tail);
19925b057c6bSHerbert Xu 	if (likely(skb_cloned(skb) || ntail > 0)) {
19935b057c6bSHerbert Xu 		err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
19945b057c6bSHerbert Xu 		if (unlikely(err))
19955b057c6bSHerbert Xu 			goto free_skb;
19965b057c6bSHerbert Xu 	}
19975b057c6bSHerbert Xu 
19985b057c6bSHerbert Xu 	/* FIXME: The use of this function with non-linear skb's really needs
19995b057c6bSHerbert Xu 	 * to be audited.
20005b057c6bSHerbert Xu 	 */
20015b057c6bSHerbert Xu 	err = skb_linearize(skb);
20025b057c6bSHerbert Xu 	if (unlikely(err))
20035b057c6bSHerbert Xu 		goto free_skb;
20045b057c6bSHerbert Xu 
20055b057c6bSHerbert Xu 	memset(skb->data + skb->len, 0, pad);
20065b057c6bSHerbert Xu 	return 0;
20075b057c6bSHerbert Xu 
20085b057c6bSHerbert Xu free_skb:
2009cd0a137aSFlorian Fainelli 	if (free_on_error)
20101da177e4SLinus Torvalds 		kfree_skb(skb);
20115b057c6bSHerbert Xu 	return err;
20121da177e4SLinus Torvalds }
2013cd0a137aSFlorian Fainelli EXPORT_SYMBOL(__skb_pad);
20141da177e4SLinus Torvalds 
20150dde3e16SIlpo Järvinen /**
20160c7ddf36SMathias Krause  *	pskb_put - add data to the tail of a potentially fragmented buffer
20170c7ddf36SMathias Krause  *	@skb: start of the buffer to use
20180c7ddf36SMathias Krause  *	@tail: tail fragment of the buffer to use
20190c7ddf36SMathias Krause  *	@len: amount of data to add
20200c7ddf36SMathias Krause  *
20210c7ddf36SMathias Krause  *	This function extends the used data area of the potentially
20220c7ddf36SMathias Krause  *	fragmented buffer. @tail must be the last fragment of @skb -- or
20230c7ddf36SMathias Krause  *	@skb itself. If this would exceed the total buffer size the kernel
20240c7ddf36SMathias Krause  *	will panic. A pointer to the first byte of the extra data is
20250c7ddf36SMathias Krause  *	returned.
20260c7ddf36SMathias Krause  */
20270c7ddf36SMathias Krause 
20284df864c1SJohannes Berg void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
20290c7ddf36SMathias Krause {
20300c7ddf36SMathias Krause 	if (tail != skb) {
20310c7ddf36SMathias Krause 		skb->data_len += len;
20320c7ddf36SMathias Krause 		skb->len += len;
20330c7ddf36SMathias Krause 	}
20340c7ddf36SMathias Krause 	return skb_put(tail, len);
20350c7ddf36SMathias Krause }
20360c7ddf36SMathias Krause EXPORT_SYMBOL_GPL(pskb_put);
20370c7ddf36SMathias Krause 
20380c7ddf36SMathias Krause /**
20390dde3e16SIlpo Järvinen  *	skb_put - add data to a buffer
20400dde3e16SIlpo Järvinen  *	@skb: buffer to use
20410dde3e16SIlpo Järvinen  *	@len: amount of data to add
20420dde3e16SIlpo Järvinen  *
20430dde3e16SIlpo Järvinen  *	This function extends the used data area of the buffer. If this would
20440dde3e16SIlpo Järvinen  *	exceed the total buffer size the kernel will panic. A pointer to the
20450dde3e16SIlpo Järvinen  *	first byte of the extra data is returned.
20460dde3e16SIlpo Järvinen  */
20474df864c1SJohannes Berg void *skb_put(struct sk_buff *skb, unsigned int len)
20480dde3e16SIlpo Järvinen {
20494df864c1SJohannes Berg 	void *tmp = skb_tail_pointer(skb);
20500dde3e16SIlpo Järvinen 	SKB_LINEAR_ASSERT(skb);
20510dde3e16SIlpo Järvinen 	skb->tail += len;
20520dde3e16SIlpo Järvinen 	skb->len  += len;
20530dde3e16SIlpo Järvinen 	if (unlikely(skb->tail > skb->end))
20540dde3e16SIlpo Järvinen 		skb_over_panic(skb, len, __builtin_return_address(0));
20550dde3e16SIlpo Järvinen 	return tmp;
20560dde3e16SIlpo Järvinen }
20570dde3e16SIlpo Järvinen EXPORT_SYMBOL(skb_put);
20580dde3e16SIlpo Järvinen 
20596be8ac2fSIlpo Järvinen /**
2060c2aa270aSIlpo Järvinen  *	skb_push - add data to the start of a buffer
2061c2aa270aSIlpo Järvinen  *	@skb: buffer to use
2062c2aa270aSIlpo Järvinen  *	@len: amount of data to add
2063c2aa270aSIlpo Järvinen  *
2064c2aa270aSIlpo Järvinen  *	This function extends the used data area of the buffer at the buffer
2065c2aa270aSIlpo Järvinen  *	start. If this would exceed the total buffer headroom the kernel will
2066c2aa270aSIlpo Järvinen  *	panic. A pointer to the first byte of the extra data is returned.
2067c2aa270aSIlpo Järvinen  */
2068d58ff351SJohannes Berg void *skb_push(struct sk_buff *skb, unsigned int len)
2069c2aa270aSIlpo Järvinen {
2070c2aa270aSIlpo Järvinen 	skb->data -= len;
2071c2aa270aSIlpo Järvinen 	skb->len  += len;
2072c2aa270aSIlpo Järvinen 	if (unlikely(skb->data < skb->head))
2073c2aa270aSIlpo Järvinen 		skb_under_panic(skb, len, __builtin_return_address(0));
2074c2aa270aSIlpo Järvinen 	return skb->data;
2075c2aa270aSIlpo Järvinen }
2076c2aa270aSIlpo Järvinen EXPORT_SYMBOL(skb_push);
2077c2aa270aSIlpo Järvinen 
2078c2aa270aSIlpo Järvinen /**
20796be8ac2fSIlpo Järvinen  *	skb_pull - remove data from the start of a buffer
20806be8ac2fSIlpo Järvinen  *	@skb: buffer to use
20816be8ac2fSIlpo Järvinen  *	@len: amount of data to remove
20826be8ac2fSIlpo Järvinen  *
20836be8ac2fSIlpo Järvinen  *	This function removes data from the start of a buffer, returning
20846be8ac2fSIlpo Järvinen  *	the memory to the headroom. A pointer to the next data in the buffer
20856be8ac2fSIlpo Järvinen  *	is returned. Once the data has been pulled future pushes will overwrite
20866be8ac2fSIlpo Järvinen  *	the old data.
20876be8ac2fSIlpo Järvinen  */
2088af72868bSJohannes Berg void *skb_pull(struct sk_buff *skb, unsigned int len)
20896be8ac2fSIlpo Järvinen {
209047d29646SDavid S. Miller 	return skb_pull_inline(skb, len);
20916be8ac2fSIlpo Järvinen }
20926be8ac2fSIlpo Järvinen EXPORT_SYMBOL(skb_pull);
20936be8ac2fSIlpo Järvinen 
2094419ae74eSIlpo Järvinen /**
209513244cccSLuiz Augusto von Dentz  *	skb_pull_data - remove data from the start of a buffer returning its
209613244cccSLuiz Augusto von Dentz  *	original position.
209713244cccSLuiz Augusto von Dentz  *	@skb: buffer to use
209813244cccSLuiz Augusto von Dentz  *	@len: amount of data to remove
209913244cccSLuiz Augusto von Dentz  *
210013244cccSLuiz Augusto von Dentz  *	This function removes data from the start of a buffer, returning
210113244cccSLuiz Augusto von Dentz  *	the memory to the headroom. A pointer to the original data in the buffer
210213244cccSLuiz Augusto von Dentz  *	is returned after checking if there is enough data to pull. Once the
210313244cccSLuiz Augusto von Dentz  *	data has been pulled future pushes will overwrite the old data.
210413244cccSLuiz Augusto von Dentz  */
210513244cccSLuiz Augusto von Dentz void *skb_pull_data(struct sk_buff *skb, size_t len)
210613244cccSLuiz Augusto von Dentz {
210713244cccSLuiz Augusto von Dentz 	void *data = skb->data;
210813244cccSLuiz Augusto von Dentz 
210913244cccSLuiz Augusto von Dentz 	if (skb->len < len)
211013244cccSLuiz Augusto von Dentz 		return NULL;
211113244cccSLuiz Augusto von Dentz 
211213244cccSLuiz Augusto von Dentz 	skb_pull(skb, len);
211313244cccSLuiz Augusto von Dentz 
211413244cccSLuiz Augusto von Dentz 	return data;
211513244cccSLuiz Augusto von Dentz }
211613244cccSLuiz Augusto von Dentz EXPORT_SYMBOL(skb_pull_data);
211713244cccSLuiz Augusto von Dentz 
211813244cccSLuiz Augusto von Dentz /**
2119419ae74eSIlpo Järvinen  *	skb_trim - remove end from a buffer
2120419ae74eSIlpo Järvinen  *	@skb: buffer to alter
2121419ae74eSIlpo Järvinen  *	@len: new length
2122419ae74eSIlpo Järvinen  *
2123419ae74eSIlpo Järvinen  *	Cut the length of a buffer down by removing data from the tail. If
2124419ae74eSIlpo Järvinen  *	the buffer is already under the length specified it is not modified.
2125419ae74eSIlpo Järvinen  *	The skb must be linear.
2126419ae74eSIlpo Järvinen  */
2127419ae74eSIlpo Järvinen void skb_trim(struct sk_buff *skb, unsigned int len)
2128419ae74eSIlpo Järvinen {
2129419ae74eSIlpo Järvinen 	if (skb->len > len)
2130419ae74eSIlpo Järvinen 		__skb_trim(skb, len);
2131419ae74eSIlpo Järvinen }
2132419ae74eSIlpo Järvinen EXPORT_SYMBOL(skb_trim);
2133419ae74eSIlpo Järvinen 
21343cc0e873SHerbert Xu /* Trims skb to length len. It can change skb pointers.
21351da177e4SLinus Torvalds  */
21361da177e4SLinus Torvalds 
21373cc0e873SHerbert Xu int ___pskb_trim(struct sk_buff *skb, unsigned int len)
21381da177e4SLinus Torvalds {
213927b437c8SHerbert Xu 	struct sk_buff **fragp;
214027b437c8SHerbert Xu 	struct sk_buff *frag;
21411da177e4SLinus Torvalds 	int offset = skb_headlen(skb);
21421da177e4SLinus Torvalds 	int nfrags = skb_shinfo(skb)->nr_frags;
21431da177e4SLinus Torvalds 	int i;
214427b437c8SHerbert Xu 	int err;
214527b437c8SHerbert Xu 
214627b437c8SHerbert Xu 	if (skb_cloned(skb) &&
214727b437c8SHerbert Xu 	    unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
214827b437c8SHerbert Xu 		return err;
21491da177e4SLinus Torvalds 
2150f4d26fb3SHerbert Xu 	i = 0;
2151f4d26fb3SHerbert Xu 	if (offset >= len)
2152f4d26fb3SHerbert Xu 		goto drop_pages;
2153f4d26fb3SHerbert Xu 
2154f4d26fb3SHerbert Xu 	for (; i < nfrags; i++) {
21559e903e08SEric Dumazet 		int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
215627b437c8SHerbert Xu 
215727b437c8SHerbert Xu 		if (end < len) {
21581da177e4SLinus Torvalds 			offset = end;
215927b437c8SHerbert Xu 			continue;
21601da177e4SLinus Torvalds 		}
21611da177e4SLinus Torvalds 
21629e903e08SEric Dumazet 		skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
216327b437c8SHerbert Xu 
2164f4d26fb3SHerbert Xu drop_pages:
216527b437c8SHerbert Xu 		skb_shinfo(skb)->nr_frags = i;
216627b437c8SHerbert Xu 
216727b437c8SHerbert Xu 		for (; i < nfrags; i++)
2168ea2ab693SIan Campbell 			skb_frag_unref(skb, i);
216927b437c8SHerbert Xu 
217021dc3301SDavid S. Miller 		if (skb_has_frag_list(skb))
217127b437c8SHerbert Xu 			skb_drop_fraglist(skb);
2172f4d26fb3SHerbert Xu 		goto done;
217327b437c8SHerbert Xu 	}
217427b437c8SHerbert Xu 
217527b437c8SHerbert Xu 	for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
217627b437c8SHerbert Xu 	     fragp = &frag->next) {
217727b437c8SHerbert Xu 		int end = offset + frag->len;
217827b437c8SHerbert Xu 
217927b437c8SHerbert Xu 		if (skb_shared(frag)) {
218027b437c8SHerbert Xu 			struct sk_buff *nfrag;
218127b437c8SHerbert Xu 
218227b437c8SHerbert Xu 			nfrag = skb_clone(frag, GFP_ATOMIC);
218327b437c8SHerbert Xu 			if (unlikely(!nfrag))
218427b437c8SHerbert Xu 				return -ENOMEM;
218527b437c8SHerbert Xu 
218627b437c8SHerbert Xu 			nfrag->next = frag->next;
218785bb2a60SEric Dumazet 			consume_skb(frag);
218827b437c8SHerbert Xu 			frag = nfrag;
218927b437c8SHerbert Xu 			*fragp = frag;
219027b437c8SHerbert Xu 		}
219127b437c8SHerbert Xu 
219227b437c8SHerbert Xu 		if (end < len) {
219327b437c8SHerbert Xu 			offset = end;
219427b437c8SHerbert Xu 			continue;
219527b437c8SHerbert Xu 		}
219627b437c8SHerbert Xu 
219727b437c8SHerbert Xu 		if (end > len &&
219827b437c8SHerbert Xu 		    unlikely((err = pskb_trim(frag, len - offset))))
219927b437c8SHerbert Xu 			return err;
220027b437c8SHerbert Xu 
220127b437c8SHerbert Xu 		if (frag->next)
220227b437c8SHerbert Xu 			skb_drop_list(&frag->next);
220327b437c8SHerbert Xu 		break;
220427b437c8SHerbert Xu 	}
220527b437c8SHerbert Xu 
2206f4d26fb3SHerbert Xu done:
220727b437c8SHerbert Xu 	if (len > skb_headlen(skb)) {
22081da177e4SLinus Torvalds 		skb->data_len -= skb->len - len;
22091da177e4SLinus Torvalds 		skb->len       = len;
22101da177e4SLinus Torvalds 	} else {
22111da177e4SLinus Torvalds 		skb->len       = len;
22121da177e4SLinus Torvalds 		skb->data_len  = 0;
221327a884dcSArnaldo Carvalho de Melo 		skb_set_tail_pointer(skb, len);
22141da177e4SLinus Torvalds 	}
22151da177e4SLinus Torvalds 
2216c21b48ccSEric Dumazet 	if (!skb->sk || skb->destructor == sock_edemux)
2217c21b48ccSEric Dumazet 		skb_condense(skb);
22181da177e4SLinus Torvalds 	return 0;
22191da177e4SLinus Torvalds }
2220b4ac530fSDavid S. Miller EXPORT_SYMBOL(___pskb_trim);
22211da177e4SLinus Torvalds 
222288078d98SEric Dumazet /* Note : use pskb_trim_rcsum() instead of calling this directly
222388078d98SEric Dumazet  */
222488078d98SEric Dumazet int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
222588078d98SEric Dumazet {
222688078d98SEric Dumazet 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
222788078d98SEric Dumazet 		int delta = skb->len - len;
222888078d98SEric Dumazet 
2229d55bef50SDimitris Michailidis 		skb->csum = csum_block_sub(skb->csum,
2230d55bef50SDimitris Michailidis 					   skb_checksum(skb, len, delta, 0),
2231d55bef50SDimitris Michailidis 					   len);
223254970a2fSVasily Averin 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
223354970a2fSVasily Averin 		int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
223454970a2fSVasily Averin 		int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
223554970a2fSVasily Averin 
223654970a2fSVasily Averin 		if (offset + sizeof(__sum16) > hdlen)
223754970a2fSVasily Averin 			return -EINVAL;
223888078d98SEric Dumazet 	}
223988078d98SEric Dumazet 	return __pskb_trim(skb, len);
224088078d98SEric Dumazet }
224188078d98SEric Dumazet EXPORT_SYMBOL(pskb_trim_rcsum_slow);
224288078d98SEric Dumazet 
22431da177e4SLinus Torvalds /**
22441da177e4SLinus Torvalds  *	__pskb_pull_tail - advance tail of skb header
22451da177e4SLinus Torvalds  *	@skb: buffer to reallocate
22461da177e4SLinus Torvalds  *	@delta: number of bytes to advance tail
22471da177e4SLinus Torvalds  *
22481da177e4SLinus Torvalds  *	The function makes a sense only on a fragmented &sk_buff,
22491da177e4SLinus Torvalds  *	it expands header moving its tail forward and copying necessary
22501da177e4SLinus Torvalds  *	data from fragmented part.
22511da177e4SLinus Torvalds  *
22521da177e4SLinus Torvalds  *	&sk_buff MUST have reference count of 1.
22531da177e4SLinus Torvalds  *
22541da177e4SLinus Torvalds  *	Returns %NULL (and &sk_buff does not change) if pull failed
22551da177e4SLinus Torvalds  *	or value of new tail of skb in the case of success.
22561da177e4SLinus Torvalds  *
22571da177e4SLinus Torvalds  *	All the pointers pointing into skb header may change and must be
22581da177e4SLinus Torvalds  *	reloaded after call to this function.
22591da177e4SLinus Torvalds  */
22601da177e4SLinus Torvalds 
22611da177e4SLinus Torvalds /* Moves tail of skb head forward, copying data from fragmented part,
22621da177e4SLinus Torvalds  * when it is necessary.
22631da177e4SLinus Torvalds  * 1. It may fail due to malloc failure.
22641da177e4SLinus Torvalds  * 2. It may change skb pointers.
22651da177e4SLinus Torvalds  *
22661da177e4SLinus Torvalds  * It is pretty complicated. Luckily, it is called only in exceptional cases.
22671da177e4SLinus Torvalds  */
2268af72868bSJohannes Berg void *__pskb_pull_tail(struct sk_buff *skb, int delta)
22691da177e4SLinus Torvalds {
22701da177e4SLinus Torvalds 	/* If skb has not enough free space at tail, get new one
22711da177e4SLinus Torvalds 	 * plus 128 bytes for future expansions. If we have enough
22721da177e4SLinus Torvalds 	 * room at tail, reallocate without expansion only if skb is cloned.
22731da177e4SLinus Torvalds 	 */
22744305b541SArnaldo Carvalho de Melo 	int i, k, eat = (skb->tail + delta) - skb->end;
22751da177e4SLinus Torvalds 
22761da177e4SLinus Torvalds 	if (eat > 0 || skb_cloned(skb)) {
22771da177e4SLinus Torvalds 		if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
22781da177e4SLinus Torvalds 				     GFP_ATOMIC))
22791da177e4SLinus Torvalds 			return NULL;
22801da177e4SLinus Torvalds 	}
22811da177e4SLinus Torvalds 
22829f77fad3STim Hansen 	BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
22839f77fad3STim Hansen 			     skb_tail_pointer(skb), delta));
22841da177e4SLinus Torvalds 
22851da177e4SLinus Torvalds 	/* Optimization: no fragments, no reasons to preestimate
22861da177e4SLinus Torvalds 	 * size of pulled pages. Superb.
22871da177e4SLinus Torvalds 	 */
228821dc3301SDavid S. Miller 	if (!skb_has_frag_list(skb))
22891da177e4SLinus Torvalds 		goto pull_pages;
22901da177e4SLinus Torvalds 
22911da177e4SLinus Torvalds 	/* Estimate size of pulled pages. */
22921da177e4SLinus Torvalds 	eat = delta;
22931da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
22949e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
22959e903e08SEric Dumazet 
22969e903e08SEric Dumazet 		if (size >= eat)
22971da177e4SLinus Torvalds 			goto pull_pages;
22989e903e08SEric Dumazet 		eat -= size;
22991da177e4SLinus Torvalds 	}
23001da177e4SLinus Torvalds 
23011da177e4SLinus Torvalds 	/* If we need update frag list, we are in troubles.
230209001b03SWenhua Shi 	 * Certainly, it is possible to add an offset to skb data,
23031da177e4SLinus Torvalds 	 * but taking into account that pulling is expected to
23041da177e4SLinus Torvalds 	 * be very rare operation, it is worth to fight against
23051da177e4SLinus Torvalds 	 * further bloating skb head and crucify ourselves here instead.
23061da177e4SLinus Torvalds 	 * Pure masohism, indeed. 8)8)
23071da177e4SLinus Torvalds 	 */
23081da177e4SLinus Torvalds 	if (eat) {
23091da177e4SLinus Torvalds 		struct sk_buff *list = skb_shinfo(skb)->frag_list;
23101da177e4SLinus Torvalds 		struct sk_buff *clone = NULL;
23111da177e4SLinus Torvalds 		struct sk_buff *insp = NULL;
23121da177e4SLinus Torvalds 
23131da177e4SLinus Torvalds 		do {
23141da177e4SLinus Torvalds 			if (list->len <= eat) {
23151da177e4SLinus Torvalds 				/* Eaten as whole. */
23161da177e4SLinus Torvalds 				eat -= list->len;
23171da177e4SLinus Torvalds 				list = list->next;
23181da177e4SLinus Torvalds 				insp = list;
23191da177e4SLinus Torvalds 			} else {
23201da177e4SLinus Torvalds 				/* Eaten partially. */
23211da177e4SLinus Torvalds 
23221da177e4SLinus Torvalds 				if (skb_shared(list)) {
23231da177e4SLinus Torvalds 					/* Sucks! We need to fork list. :-( */
23241da177e4SLinus Torvalds 					clone = skb_clone(list, GFP_ATOMIC);
23251da177e4SLinus Torvalds 					if (!clone)
23261da177e4SLinus Torvalds 						return NULL;
23271da177e4SLinus Torvalds 					insp = list->next;
23281da177e4SLinus Torvalds 					list = clone;
23291da177e4SLinus Torvalds 				} else {
23301da177e4SLinus Torvalds 					/* This may be pulled without
23311da177e4SLinus Torvalds 					 * problems. */
23321da177e4SLinus Torvalds 					insp = list;
23331da177e4SLinus Torvalds 				}
23341da177e4SLinus Torvalds 				if (!pskb_pull(list, eat)) {
23351da177e4SLinus Torvalds 					kfree_skb(clone);
23361da177e4SLinus Torvalds 					return NULL;
23371da177e4SLinus Torvalds 				}
23381da177e4SLinus Torvalds 				break;
23391da177e4SLinus Torvalds 			}
23401da177e4SLinus Torvalds 		} while (eat);
23411da177e4SLinus Torvalds 
23421da177e4SLinus Torvalds 		/* Free pulled out fragments. */
23431da177e4SLinus Torvalds 		while ((list = skb_shinfo(skb)->frag_list) != insp) {
23441da177e4SLinus Torvalds 			skb_shinfo(skb)->frag_list = list->next;
2345ef527f96SEric Dumazet 			consume_skb(list);
23461da177e4SLinus Torvalds 		}
23471da177e4SLinus Torvalds 		/* And insert new clone at head. */
23481da177e4SLinus Torvalds 		if (clone) {
23491da177e4SLinus Torvalds 			clone->next = list;
23501da177e4SLinus Torvalds 			skb_shinfo(skb)->frag_list = clone;
23511da177e4SLinus Torvalds 		}
23521da177e4SLinus Torvalds 	}
23531da177e4SLinus Torvalds 	/* Success! Now we may commit changes to skb data. */
23541da177e4SLinus Torvalds 
23551da177e4SLinus Torvalds pull_pages:
23561da177e4SLinus Torvalds 	eat = delta;
23571da177e4SLinus Torvalds 	k = 0;
23581da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
23599e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
23609e903e08SEric Dumazet 
23619e903e08SEric Dumazet 		if (size <= eat) {
2362ea2ab693SIan Campbell 			skb_frag_unref(skb, i);
23639e903e08SEric Dumazet 			eat -= size;
23641da177e4SLinus Torvalds 		} else {
2365b54c9d5bSJonathan Lemon 			skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2366b54c9d5bSJonathan Lemon 
2367b54c9d5bSJonathan Lemon 			*frag = skb_shinfo(skb)->frags[i];
23681da177e4SLinus Torvalds 			if (eat) {
2369b54c9d5bSJonathan Lemon 				skb_frag_off_add(frag, eat);
2370b54c9d5bSJonathan Lemon 				skb_frag_size_sub(frag, eat);
23713ccc6c6fSlinzhang 				if (!i)
23723ccc6c6fSlinzhang 					goto end;
23731da177e4SLinus Torvalds 				eat = 0;
23741da177e4SLinus Torvalds 			}
23751da177e4SLinus Torvalds 			k++;
23761da177e4SLinus Torvalds 		}
23771da177e4SLinus Torvalds 	}
23781da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags = k;
23791da177e4SLinus Torvalds 
23803ccc6c6fSlinzhang end:
23811da177e4SLinus Torvalds 	skb->tail     += delta;
23821da177e4SLinus Torvalds 	skb->data_len -= delta;
23831da177e4SLinus Torvalds 
23841f8b977aSWillem de Bruijn 	if (!skb->data_len)
23851f8b977aSWillem de Bruijn 		skb_zcopy_clear(skb, false);
23861f8b977aSWillem de Bruijn 
238727a884dcSArnaldo Carvalho de Melo 	return skb_tail_pointer(skb);
23881da177e4SLinus Torvalds }
2389b4ac530fSDavid S. Miller EXPORT_SYMBOL(__pskb_pull_tail);
23901da177e4SLinus Torvalds 
239122019b17SEric Dumazet /**
239222019b17SEric Dumazet  *	skb_copy_bits - copy bits from skb to kernel buffer
239322019b17SEric Dumazet  *	@skb: source skb
239422019b17SEric Dumazet  *	@offset: offset in source
239522019b17SEric Dumazet  *	@to: destination buffer
239622019b17SEric Dumazet  *	@len: number of bytes to copy
239722019b17SEric Dumazet  *
239822019b17SEric Dumazet  *	Copy the specified number of bytes from the source skb to the
239922019b17SEric Dumazet  *	destination buffer.
240022019b17SEric Dumazet  *
240122019b17SEric Dumazet  *	CAUTION ! :
240222019b17SEric Dumazet  *		If its prototype is ever changed,
240322019b17SEric Dumazet  *		check arch/{*}/net/{*}.S files,
240422019b17SEric Dumazet  *		since it is called from BPF assembly code.
240522019b17SEric Dumazet  */
24061da177e4SLinus Torvalds int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
24071da177e4SLinus Torvalds {
24081a028e50SDavid S. Miller 	int start = skb_headlen(skb);
2409fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
2410fbb398a8SDavid S. Miller 	int i, copy;
24111da177e4SLinus Torvalds 
24121da177e4SLinus Torvalds 	if (offset > (int)skb->len - len)
24131da177e4SLinus Torvalds 		goto fault;
24141da177e4SLinus Torvalds 
24151da177e4SLinus Torvalds 	/* Copy header. */
24161a028e50SDavid S. Miller 	if ((copy = start - offset) > 0) {
24171da177e4SLinus Torvalds 		if (copy > len)
24181da177e4SLinus Torvalds 			copy = len;
2419d626f62bSArnaldo Carvalho de Melo 		skb_copy_from_linear_data_offset(skb, offset, to, copy);
24201da177e4SLinus Torvalds 		if ((len -= copy) == 0)
24211da177e4SLinus Torvalds 			return 0;
24221da177e4SLinus Torvalds 		offset += copy;
24231da177e4SLinus Torvalds 		to     += copy;
24241da177e4SLinus Torvalds 	}
24251da177e4SLinus Torvalds 
24261da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
24271a028e50SDavid S. Miller 		int end;
242851c56b00SEric Dumazet 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
24291da177e4SLinus Torvalds 
2430547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
24311a028e50SDavid S. Miller 
243251c56b00SEric Dumazet 		end = start + skb_frag_size(f);
24331da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
2434c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2435c613c209SWillem de Bruijn 			struct page *p;
24361da177e4SLinus Torvalds 			u8 *vaddr;
24371da177e4SLinus Torvalds 
24381da177e4SLinus Torvalds 			if (copy > len)
24391da177e4SLinus Torvalds 				copy = len;
24401da177e4SLinus Torvalds 
2441c613c209SWillem de Bruijn 			skb_frag_foreach_page(f,
2442b54c9d5bSJonathan Lemon 					      skb_frag_off(f) + offset - start,
2443c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2444c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
2445c613c209SWillem de Bruijn 				memcpy(to + copied, vaddr + p_off, p_len);
244651c56b00SEric Dumazet 				kunmap_atomic(vaddr);
2447c613c209SWillem de Bruijn 			}
24481da177e4SLinus Torvalds 
24491da177e4SLinus Torvalds 			if ((len -= copy) == 0)
24501da177e4SLinus Torvalds 				return 0;
24511da177e4SLinus Torvalds 			offset += copy;
24521da177e4SLinus Torvalds 			to     += copy;
24531da177e4SLinus Torvalds 		}
24541a028e50SDavid S. Miller 		start = end;
24551da177e4SLinus Torvalds 	}
24561da177e4SLinus Torvalds 
2457fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
24581a028e50SDavid S. Miller 		int end;
24591da177e4SLinus Torvalds 
2460547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
24611a028e50SDavid S. Miller 
2462fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
24631da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
24641da177e4SLinus Torvalds 			if (copy > len)
24651da177e4SLinus Torvalds 				copy = len;
2466fbb398a8SDavid S. Miller 			if (skb_copy_bits(frag_iter, offset - start, to, copy))
24671da177e4SLinus Torvalds 				goto fault;
24681da177e4SLinus Torvalds 			if ((len -= copy) == 0)
24691da177e4SLinus Torvalds 				return 0;
24701da177e4SLinus Torvalds 			offset += copy;
24711da177e4SLinus Torvalds 			to     += copy;
24721da177e4SLinus Torvalds 		}
24731a028e50SDavid S. Miller 		start = end;
24741da177e4SLinus Torvalds 	}
2475a6686f2fSShirley Ma 
24761da177e4SLinus Torvalds 	if (!len)
24771da177e4SLinus Torvalds 		return 0;
24781da177e4SLinus Torvalds 
24791da177e4SLinus Torvalds fault:
24801da177e4SLinus Torvalds 	return -EFAULT;
24811da177e4SLinus Torvalds }
2482b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_bits);
24831da177e4SLinus Torvalds 
24849c55e01cSJens Axboe /*
24859c55e01cSJens Axboe  * Callback from splice_to_pipe(), if we need to release some pages
24869c55e01cSJens Axboe  * at the end of the spd in case we error'ed out in filling the pipe.
24879c55e01cSJens Axboe  */
24889c55e01cSJens Axboe static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
24899c55e01cSJens Axboe {
24908b9d3728SJarek Poplawski 	put_page(spd->pages[i]);
24918b9d3728SJarek Poplawski }
24929c55e01cSJens Axboe 
2493a108d5f3SDavid S. Miller static struct page *linear_to_page(struct page *page, unsigned int *len,
24944fb66994SJarek Poplawski 				   unsigned int *offset,
249518aafc62SEric Dumazet 				   struct sock *sk)
24968b9d3728SJarek Poplawski {
24975640f768SEric Dumazet 	struct page_frag *pfrag = sk_page_frag(sk);
24988b9d3728SJarek Poplawski 
24995640f768SEric Dumazet 	if (!sk_page_frag_refill(sk, pfrag))
25008b9d3728SJarek Poplawski 		return NULL;
25014fb66994SJarek Poplawski 
25025640f768SEric Dumazet 	*len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
25034fb66994SJarek Poplawski 
25045640f768SEric Dumazet 	memcpy(page_address(pfrag->page) + pfrag->offset,
25055640f768SEric Dumazet 	       page_address(page) + *offset, *len);
25065640f768SEric Dumazet 	*offset = pfrag->offset;
25075640f768SEric Dumazet 	pfrag->offset += *len;
25084fb66994SJarek Poplawski 
25095640f768SEric Dumazet 	return pfrag->page;
25109c55e01cSJens Axboe }
25119c55e01cSJens Axboe 
251241c73a0dSEric Dumazet static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
251341c73a0dSEric Dumazet 			     struct page *page,
251441c73a0dSEric Dumazet 			     unsigned int offset)
251541c73a0dSEric Dumazet {
251641c73a0dSEric Dumazet 	return	spd->nr_pages &&
251741c73a0dSEric Dumazet 		spd->pages[spd->nr_pages - 1] == page &&
251841c73a0dSEric Dumazet 		(spd->partial[spd->nr_pages - 1].offset +
251941c73a0dSEric Dumazet 		 spd->partial[spd->nr_pages - 1].len == offset);
252041c73a0dSEric Dumazet }
252141c73a0dSEric Dumazet 
25229c55e01cSJens Axboe /*
25239c55e01cSJens Axboe  * Fill page/offset/length into spd, if it can hold more pages.
25249c55e01cSJens Axboe  */
2525a108d5f3SDavid S. Miller static bool spd_fill_page(struct splice_pipe_desc *spd,
252635f3d14dSJens Axboe 			  struct pipe_inode_info *pipe, struct page *page,
25274fb66994SJarek Poplawski 			  unsigned int *len, unsigned int offset,
252818aafc62SEric Dumazet 			  bool linear,
25297a67e56fSJarek Poplawski 			  struct sock *sk)
25309c55e01cSJens Axboe {
253141c73a0dSEric Dumazet 	if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2532a108d5f3SDavid S. Miller 		return true;
25339c55e01cSJens Axboe 
25348b9d3728SJarek Poplawski 	if (linear) {
253518aafc62SEric Dumazet 		page = linear_to_page(page, len, &offset, sk);
25368b9d3728SJarek Poplawski 		if (!page)
2537a108d5f3SDavid S. Miller 			return true;
253841c73a0dSEric Dumazet 	}
253941c73a0dSEric Dumazet 	if (spd_can_coalesce(spd, page, offset)) {
254041c73a0dSEric Dumazet 		spd->partial[spd->nr_pages - 1].len += *len;
2541a108d5f3SDavid S. Miller 		return false;
254241c73a0dSEric Dumazet 	}
25438b9d3728SJarek Poplawski 	get_page(page);
25449c55e01cSJens Axboe 	spd->pages[spd->nr_pages] = page;
25454fb66994SJarek Poplawski 	spd->partial[spd->nr_pages].len = *len;
25469c55e01cSJens Axboe 	spd->partial[spd->nr_pages].offset = offset;
25479c55e01cSJens Axboe 	spd->nr_pages++;
25488b9d3728SJarek Poplawski 
2549a108d5f3SDavid S. Miller 	return false;
25509c55e01cSJens Axboe }
25519c55e01cSJens Axboe 
2552a108d5f3SDavid S. Miller static bool __splice_segment(struct page *page, unsigned int poff,
25532870c43dSOctavian Purdila 			     unsigned int plen, unsigned int *off,
255418aafc62SEric Dumazet 			     unsigned int *len,
2555d7ccf7c0SEric Dumazet 			     struct splice_pipe_desc *spd, bool linear,
255635f3d14dSJens Axboe 			     struct sock *sk,
255735f3d14dSJens Axboe 			     struct pipe_inode_info *pipe)
25589c55e01cSJens Axboe {
25592870c43dSOctavian Purdila 	if (!*len)
2560a108d5f3SDavid S. Miller 		return true;
25619c55e01cSJens Axboe 
25622870c43dSOctavian Purdila 	/* skip this segment if already processed */
25632870c43dSOctavian Purdila 	if (*off >= plen) {
25642870c43dSOctavian Purdila 		*off -= plen;
2565a108d5f3SDavid S. Miller 		return false;
25662870c43dSOctavian Purdila 	}
25672870c43dSOctavian Purdila 
25682870c43dSOctavian Purdila 	/* ignore any bits we already processed */
25699ca1b22dSEric Dumazet 	poff += *off;
25709ca1b22dSEric Dumazet 	plen -= *off;
25712870c43dSOctavian Purdila 	*off = 0;
25722870c43dSOctavian Purdila 
257318aafc62SEric Dumazet 	do {
257418aafc62SEric Dumazet 		unsigned int flen = min(*len, plen);
25752870c43dSOctavian Purdila 
257618aafc62SEric Dumazet 		if (spd_fill_page(spd, pipe, page, &flen, poff,
257718aafc62SEric Dumazet 				  linear, sk))
2578a108d5f3SDavid S. Miller 			return true;
257918aafc62SEric Dumazet 		poff += flen;
258018aafc62SEric Dumazet 		plen -= flen;
25812870c43dSOctavian Purdila 		*len -= flen;
258218aafc62SEric Dumazet 	} while (*len && plen);
25832870c43dSOctavian Purdila 
2584a108d5f3SDavid S. Miller 	return false;
2585db43a282SOctavian Purdila }
25869c55e01cSJens Axboe 
25879c55e01cSJens Axboe /*
2588a108d5f3SDavid S. Miller  * Map linear and fragment data from the skb to spd. It reports true if the
25892870c43dSOctavian Purdila  * pipe is full or if we already spliced the requested length.
25909c55e01cSJens Axboe  */
2591a108d5f3SDavid S. Miller static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
259235f3d14dSJens Axboe 			      unsigned int *offset, unsigned int *len,
259335f3d14dSJens Axboe 			      struct splice_pipe_desc *spd, struct sock *sk)
25942870c43dSOctavian Purdila {
25952870c43dSOctavian Purdila 	int seg;
2596fa9835e5STom Herbert 	struct sk_buff *iter;
25979c55e01cSJens Axboe 
25981d0c0b32SEric Dumazet 	/* map the linear part :
25992996d31fSAlexander Duyck 	 * If skb->head_frag is set, this 'linear' part is backed by a
26002996d31fSAlexander Duyck 	 * fragment, and if the head is not shared with any clones then
26012996d31fSAlexander Duyck 	 * we can avoid a copy since we own the head portion of this page.
26029c55e01cSJens Axboe 	 */
26032870c43dSOctavian Purdila 	if (__splice_segment(virt_to_page(skb->data),
26042870c43dSOctavian Purdila 			     (unsigned long) skb->data & (PAGE_SIZE - 1),
26052870c43dSOctavian Purdila 			     skb_headlen(skb),
260618aafc62SEric Dumazet 			     offset, len, spd,
26073a7c1ee4SAlexander Duyck 			     skb_head_is_locked(skb),
26081d0c0b32SEric Dumazet 			     sk, pipe))
2609a108d5f3SDavid S. Miller 		return true;
26109c55e01cSJens Axboe 
26119c55e01cSJens Axboe 	/*
26129c55e01cSJens Axboe 	 * then map the fragments
26139c55e01cSJens Axboe 	 */
26149c55e01cSJens Axboe 	for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
26159c55e01cSJens Axboe 		const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
26169c55e01cSJens Axboe 
2617ea2ab693SIan Campbell 		if (__splice_segment(skb_frag_page(f),
2618b54c9d5bSJonathan Lemon 				     skb_frag_off(f), skb_frag_size(f),
261918aafc62SEric Dumazet 				     offset, len, spd, false, sk, pipe))
2620a108d5f3SDavid S. Miller 			return true;
26219c55e01cSJens Axboe 	}
26229c55e01cSJens Axboe 
2623fa9835e5STom Herbert 	skb_walk_frags(skb, iter) {
2624fa9835e5STom Herbert 		if (*offset >= iter->len) {
2625fa9835e5STom Herbert 			*offset -= iter->len;
2626fa9835e5STom Herbert 			continue;
2627fa9835e5STom Herbert 		}
2628fa9835e5STom Herbert 		/* __skb_splice_bits() only fails if the output has no room
2629fa9835e5STom Herbert 		 * left, so no point in going over the frag_list for the error
2630fa9835e5STom Herbert 		 * case.
2631fa9835e5STom Herbert 		 */
2632fa9835e5STom Herbert 		if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2633fa9835e5STom Herbert 			return true;
2634fa9835e5STom Herbert 	}
2635fa9835e5STom Herbert 
2636a108d5f3SDavid S. Miller 	return false;
26379c55e01cSJens Axboe }
26389c55e01cSJens Axboe 
26399c55e01cSJens Axboe /*
26409c55e01cSJens Axboe  * Map data from the skb to a pipe. Should handle both the linear part,
2641fa9835e5STom Herbert  * the fragments, and the frag list.
26429c55e01cSJens Axboe  */
2643a60e3cc7SHannes Frederic Sowa int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
26449c55e01cSJens Axboe 		    struct pipe_inode_info *pipe, unsigned int tlen,
264525869262SAl Viro 		    unsigned int flags)
26469c55e01cSJens Axboe {
264741c73a0dSEric Dumazet 	struct partial_page partial[MAX_SKB_FRAGS];
264841c73a0dSEric Dumazet 	struct page *pages[MAX_SKB_FRAGS];
26499c55e01cSJens Axboe 	struct splice_pipe_desc spd = {
26509c55e01cSJens Axboe 		.pages = pages,
26519c55e01cSJens Axboe 		.partial = partial,
2652047fe360SEric Dumazet 		.nr_pages_max = MAX_SKB_FRAGS,
265328a625cbSMiklos Szeredi 		.ops = &nosteal_pipe_buf_ops,
26549c55e01cSJens Axboe 		.spd_release = sock_spd_release,
26559c55e01cSJens Axboe 	};
265635f3d14dSJens Axboe 	int ret = 0;
265735f3d14dSJens Axboe 
2658fa9835e5STom Herbert 	__skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
26599c55e01cSJens Axboe 
2660a60e3cc7SHannes Frederic Sowa 	if (spd.nr_pages)
266125869262SAl Viro 		ret = splice_to_pipe(pipe, &spd);
26629c55e01cSJens Axboe 
266335f3d14dSJens Axboe 	return ret;
26649c55e01cSJens Axboe }
26652b514574SHannes Frederic Sowa EXPORT_SYMBOL_GPL(skb_splice_bits);
26669c55e01cSJens Axboe 
26670739cd28SCong Wang static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
26680739cd28SCong Wang 			    struct kvec *vec, size_t num, size_t size)
26690739cd28SCong Wang {
26700739cd28SCong Wang 	struct socket *sock = sk->sk_socket;
26710739cd28SCong Wang 
26720739cd28SCong Wang 	if (!sock)
26730739cd28SCong Wang 		return -EINVAL;
26740739cd28SCong Wang 	return kernel_sendmsg(sock, msg, vec, num, size);
26750739cd28SCong Wang }
26760739cd28SCong Wang 
26770739cd28SCong Wang static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
26780739cd28SCong Wang 			     size_t size, int flags)
26790739cd28SCong Wang {
26800739cd28SCong Wang 	struct socket *sock = sk->sk_socket;
26810739cd28SCong Wang 
26820739cd28SCong Wang 	if (!sock)
26830739cd28SCong Wang 		return -EINVAL;
26840739cd28SCong Wang 	return kernel_sendpage(sock, page, offset, size, flags);
26850739cd28SCong Wang }
26860739cd28SCong Wang 
26870739cd28SCong Wang typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
26880739cd28SCong Wang 			    struct kvec *vec, size_t num, size_t size);
26890739cd28SCong Wang typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
26900739cd28SCong Wang 			     size_t size, int flags);
26910739cd28SCong Wang static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
26920739cd28SCong Wang 			   int len, sendmsg_func sendmsg, sendpage_func sendpage)
269320bf50deSTom Herbert {
269420bf50deSTom Herbert 	unsigned int orig_len = len;
269520bf50deSTom Herbert 	struct sk_buff *head = skb;
269620bf50deSTom Herbert 	unsigned short fragidx;
269720bf50deSTom Herbert 	int slen, ret;
269820bf50deSTom Herbert 
269920bf50deSTom Herbert do_frag_list:
270020bf50deSTom Herbert 
270120bf50deSTom Herbert 	/* Deal with head data */
270220bf50deSTom Herbert 	while (offset < skb_headlen(skb) && len) {
270320bf50deSTom Herbert 		struct kvec kv;
270420bf50deSTom Herbert 		struct msghdr msg;
270520bf50deSTom Herbert 
270620bf50deSTom Herbert 		slen = min_t(int, len, skb_headlen(skb) - offset);
270720bf50deSTom Herbert 		kv.iov_base = skb->data + offset;
2708db5980d8SJohn Fastabend 		kv.iov_len = slen;
270920bf50deSTom Herbert 		memset(&msg, 0, sizeof(msg));
2710bd95e678SJohn Fastabend 		msg.msg_flags = MSG_DONTWAIT;
271120bf50deSTom Herbert 
27120739cd28SCong Wang 		ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
27130739cd28SCong Wang 				      sendmsg_unlocked, sk, &msg, &kv, 1, slen);
271420bf50deSTom Herbert 		if (ret <= 0)
271520bf50deSTom Herbert 			goto error;
271620bf50deSTom Herbert 
271720bf50deSTom Herbert 		offset += ret;
271820bf50deSTom Herbert 		len -= ret;
271920bf50deSTom Herbert 	}
272020bf50deSTom Herbert 
272120bf50deSTom Herbert 	/* All the data was skb head? */
272220bf50deSTom Herbert 	if (!len)
272320bf50deSTom Herbert 		goto out;
272420bf50deSTom Herbert 
272520bf50deSTom Herbert 	/* Make offset relative to start of frags */
272620bf50deSTom Herbert 	offset -= skb_headlen(skb);
272720bf50deSTom Herbert 
272820bf50deSTom Herbert 	/* Find where we are in frag list */
272920bf50deSTom Herbert 	for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
273020bf50deSTom Herbert 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
273120bf50deSTom Herbert 
2732d8e18a51SMatthew Wilcox (Oracle) 		if (offset < skb_frag_size(frag))
273320bf50deSTom Herbert 			break;
273420bf50deSTom Herbert 
2735d8e18a51SMatthew Wilcox (Oracle) 		offset -= skb_frag_size(frag);
273620bf50deSTom Herbert 	}
273720bf50deSTom Herbert 
273820bf50deSTom Herbert 	for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
273920bf50deSTom Herbert 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
274020bf50deSTom Herbert 
2741d8e18a51SMatthew Wilcox (Oracle) 		slen = min_t(size_t, len, skb_frag_size(frag) - offset);
274220bf50deSTom Herbert 
274320bf50deSTom Herbert 		while (slen) {
27440739cd28SCong Wang 			ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
27450739cd28SCong Wang 					      sendpage_unlocked, sk,
27460739cd28SCong Wang 					      skb_frag_page(frag),
2747b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset,
274820bf50deSTom Herbert 					      slen, MSG_DONTWAIT);
274920bf50deSTom Herbert 			if (ret <= 0)
275020bf50deSTom Herbert 				goto error;
275120bf50deSTom Herbert 
275220bf50deSTom Herbert 			len -= ret;
275320bf50deSTom Herbert 			offset += ret;
275420bf50deSTom Herbert 			slen -= ret;
275520bf50deSTom Herbert 		}
275620bf50deSTom Herbert 
275720bf50deSTom Herbert 		offset = 0;
275820bf50deSTom Herbert 	}
275920bf50deSTom Herbert 
276020bf50deSTom Herbert 	if (len) {
276120bf50deSTom Herbert 		/* Process any frag lists */
276220bf50deSTom Herbert 
276320bf50deSTom Herbert 		if (skb == head) {
276420bf50deSTom Herbert 			if (skb_has_frag_list(skb)) {
276520bf50deSTom Herbert 				skb = skb_shinfo(skb)->frag_list;
276620bf50deSTom Herbert 				goto do_frag_list;
276720bf50deSTom Herbert 			}
276820bf50deSTom Herbert 		} else if (skb->next) {
276920bf50deSTom Herbert 			skb = skb->next;
277020bf50deSTom Herbert 			goto do_frag_list;
277120bf50deSTom Herbert 		}
277220bf50deSTom Herbert 	}
277320bf50deSTom Herbert 
277420bf50deSTom Herbert out:
277520bf50deSTom Herbert 	return orig_len - len;
277620bf50deSTom Herbert 
277720bf50deSTom Herbert error:
277820bf50deSTom Herbert 	return orig_len == len ? ret : orig_len - len;
277920bf50deSTom Herbert }
27800739cd28SCong Wang 
27810739cd28SCong Wang /* Send skb data on a socket. Socket must be locked. */
27820739cd28SCong Wang int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
27830739cd28SCong Wang 			 int len)
27840739cd28SCong Wang {
27850739cd28SCong Wang 	return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
27860739cd28SCong Wang 			       kernel_sendpage_locked);
27870739cd28SCong Wang }
278820bf50deSTom Herbert EXPORT_SYMBOL_GPL(skb_send_sock_locked);
278920bf50deSTom Herbert 
27900739cd28SCong Wang /* Send skb data on a socket. Socket must be unlocked. */
27910739cd28SCong Wang int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
27920739cd28SCong Wang {
27930739cd28SCong Wang 	return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
27940739cd28SCong Wang 			       sendpage_unlocked);
27950739cd28SCong Wang }
27960739cd28SCong Wang 
2797357b40a1SHerbert Xu /**
2798357b40a1SHerbert Xu  *	skb_store_bits - store bits from kernel buffer to skb
2799357b40a1SHerbert Xu  *	@skb: destination buffer
2800357b40a1SHerbert Xu  *	@offset: offset in destination
2801357b40a1SHerbert Xu  *	@from: source buffer
2802357b40a1SHerbert Xu  *	@len: number of bytes to copy
2803357b40a1SHerbert Xu  *
2804357b40a1SHerbert Xu  *	Copy the specified number of bytes from the source buffer to the
2805357b40a1SHerbert Xu  *	destination skb.  This function handles all the messy bits of
2806357b40a1SHerbert Xu  *	traversing fragment lists and such.
2807357b40a1SHerbert Xu  */
2808357b40a1SHerbert Xu 
28090c6fcc8aSStephen Hemminger int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
2810357b40a1SHerbert Xu {
28111a028e50SDavid S. Miller 	int start = skb_headlen(skb);
2812fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
2813fbb398a8SDavid S. Miller 	int i, copy;
2814357b40a1SHerbert Xu 
2815357b40a1SHerbert Xu 	if (offset > (int)skb->len - len)
2816357b40a1SHerbert Xu 		goto fault;
2817357b40a1SHerbert Xu 
28181a028e50SDavid S. Miller 	if ((copy = start - offset) > 0) {
2819357b40a1SHerbert Xu 		if (copy > len)
2820357b40a1SHerbert Xu 			copy = len;
282127d7ff46SArnaldo Carvalho de Melo 		skb_copy_to_linear_data_offset(skb, offset, from, copy);
2822357b40a1SHerbert Xu 		if ((len -= copy) == 0)
2823357b40a1SHerbert Xu 			return 0;
2824357b40a1SHerbert Xu 		offset += copy;
2825357b40a1SHerbert Xu 		from += copy;
2826357b40a1SHerbert Xu 	}
2827357b40a1SHerbert Xu 
2828357b40a1SHerbert Xu 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2829357b40a1SHerbert Xu 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
28301a028e50SDavid S. Miller 		int end;
2831357b40a1SHerbert Xu 
2832547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
28331a028e50SDavid S. Miller 
28349e903e08SEric Dumazet 		end = start + skb_frag_size(frag);
2835357b40a1SHerbert Xu 		if ((copy = end - offset) > 0) {
2836c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2837c613c209SWillem de Bruijn 			struct page *p;
2838357b40a1SHerbert Xu 			u8 *vaddr;
2839357b40a1SHerbert Xu 
2840357b40a1SHerbert Xu 			if (copy > len)
2841357b40a1SHerbert Xu 				copy = len;
2842357b40a1SHerbert Xu 
2843c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
2844b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
2845c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2846c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
2847c613c209SWillem de Bruijn 				memcpy(vaddr + p_off, from + copied, p_len);
284851c56b00SEric Dumazet 				kunmap_atomic(vaddr);
2849c613c209SWillem de Bruijn 			}
2850357b40a1SHerbert Xu 
2851357b40a1SHerbert Xu 			if ((len -= copy) == 0)
2852357b40a1SHerbert Xu 				return 0;
2853357b40a1SHerbert Xu 			offset += copy;
2854357b40a1SHerbert Xu 			from += copy;
2855357b40a1SHerbert Xu 		}
28561a028e50SDavid S. Miller 		start = end;
2857357b40a1SHerbert Xu 	}
2858357b40a1SHerbert Xu 
2859fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
28601a028e50SDavid S. Miller 		int end;
2861357b40a1SHerbert Xu 
2862547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
28631a028e50SDavid S. Miller 
2864fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
2865357b40a1SHerbert Xu 		if ((copy = end - offset) > 0) {
2866357b40a1SHerbert Xu 			if (copy > len)
2867357b40a1SHerbert Xu 				copy = len;
2868fbb398a8SDavid S. Miller 			if (skb_store_bits(frag_iter, offset - start,
28691a028e50SDavid S. Miller 					   from, copy))
2870357b40a1SHerbert Xu 				goto fault;
2871357b40a1SHerbert Xu 			if ((len -= copy) == 0)
2872357b40a1SHerbert Xu 				return 0;
2873357b40a1SHerbert Xu 			offset += copy;
2874357b40a1SHerbert Xu 			from += copy;
2875357b40a1SHerbert Xu 		}
28761a028e50SDavid S. Miller 		start = end;
2877357b40a1SHerbert Xu 	}
2878357b40a1SHerbert Xu 	if (!len)
2879357b40a1SHerbert Xu 		return 0;
2880357b40a1SHerbert Xu 
2881357b40a1SHerbert Xu fault:
2882357b40a1SHerbert Xu 	return -EFAULT;
2883357b40a1SHerbert Xu }
2884357b40a1SHerbert Xu EXPORT_SYMBOL(skb_store_bits);
2885357b40a1SHerbert Xu 
28861da177e4SLinus Torvalds /* Checksum skb data. */
28872817a336SDaniel Borkmann __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
28882817a336SDaniel Borkmann 		      __wsum csum, const struct skb_checksum_ops *ops)
28891da177e4SLinus Torvalds {
28901a028e50SDavid S. Miller 	int start = skb_headlen(skb);
28911a028e50SDavid S. Miller 	int i, copy = start - offset;
2892fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
28931da177e4SLinus Torvalds 	int pos = 0;
28941da177e4SLinus Torvalds 
28951da177e4SLinus Torvalds 	/* Checksum header. */
28961da177e4SLinus Torvalds 	if (copy > 0) {
28971da177e4SLinus Torvalds 		if (copy > len)
28981da177e4SLinus Torvalds 			copy = len;
28992544af03SMatteo Croce 		csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
29002544af03SMatteo Croce 				       skb->data + offset, copy, csum);
29011da177e4SLinus Torvalds 		if ((len -= copy) == 0)
29021da177e4SLinus Torvalds 			return csum;
29031da177e4SLinus Torvalds 		offset += copy;
29041da177e4SLinus Torvalds 		pos	= copy;
29051da177e4SLinus Torvalds 	}
29061da177e4SLinus Torvalds 
29071da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
29081a028e50SDavid S. Miller 		int end;
290951c56b00SEric Dumazet 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
29101da177e4SLinus Torvalds 
2911547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
29121a028e50SDavid S. Miller 
291351c56b00SEric Dumazet 		end = start + skb_frag_size(frag);
29141da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
2915c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
2916c613c209SWillem de Bruijn 			struct page *p;
291744bb9363SAl Viro 			__wsum csum2;
29181da177e4SLinus Torvalds 			u8 *vaddr;
29191da177e4SLinus Torvalds 
29201da177e4SLinus Torvalds 			if (copy > len)
29211da177e4SLinus Torvalds 				copy = len;
2922c613c209SWillem de Bruijn 
2923c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
2924b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
2925c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
2926c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
29272544af03SMatteo Croce 				csum2 = INDIRECT_CALL_1(ops->update,
29282544af03SMatteo Croce 							csum_partial_ext,
29292544af03SMatteo Croce 							vaddr + p_off, p_len, 0);
293051c56b00SEric Dumazet 				kunmap_atomic(vaddr);
29312544af03SMatteo Croce 				csum = INDIRECT_CALL_1(ops->combine,
29322544af03SMatteo Croce 						       csum_block_add_ext, csum,
29332544af03SMatteo Croce 						       csum2, pos, p_len);
2934c613c209SWillem de Bruijn 				pos += p_len;
2935c613c209SWillem de Bruijn 			}
2936c613c209SWillem de Bruijn 
29371da177e4SLinus Torvalds 			if (!(len -= copy))
29381da177e4SLinus Torvalds 				return csum;
29391da177e4SLinus Torvalds 			offset += copy;
29401da177e4SLinus Torvalds 		}
29411a028e50SDavid S. Miller 		start = end;
29421da177e4SLinus Torvalds 	}
29431da177e4SLinus Torvalds 
2944fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
29451a028e50SDavid S. Miller 		int end;
29461da177e4SLinus Torvalds 
2947547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
29481a028e50SDavid S. Miller 
2949fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
29501da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
29515f92a738SAl Viro 			__wsum csum2;
29521da177e4SLinus Torvalds 			if (copy > len)
29531da177e4SLinus Torvalds 				copy = len;
29542817a336SDaniel Borkmann 			csum2 = __skb_checksum(frag_iter, offset - start,
29552817a336SDaniel Borkmann 					       copy, 0, ops);
29562544af03SMatteo Croce 			csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
29572544af03SMatteo Croce 					       csum, csum2, pos, copy);
29581da177e4SLinus Torvalds 			if ((len -= copy) == 0)
29591da177e4SLinus Torvalds 				return csum;
29601da177e4SLinus Torvalds 			offset += copy;
29611da177e4SLinus Torvalds 			pos    += copy;
29621da177e4SLinus Torvalds 		}
29631a028e50SDavid S. Miller 		start = end;
29641da177e4SLinus Torvalds 	}
296509a62660SKris Katterjohn 	BUG_ON(len);
29661da177e4SLinus Torvalds 
29671da177e4SLinus Torvalds 	return csum;
29681da177e4SLinus Torvalds }
29692817a336SDaniel Borkmann EXPORT_SYMBOL(__skb_checksum);
29702817a336SDaniel Borkmann 
29712817a336SDaniel Borkmann __wsum skb_checksum(const struct sk_buff *skb, int offset,
29722817a336SDaniel Borkmann 		    int len, __wsum csum)
29732817a336SDaniel Borkmann {
29742817a336SDaniel Borkmann 	const struct skb_checksum_ops ops = {
2975cea80ea8SDaniel Borkmann 		.update  = csum_partial_ext,
29762817a336SDaniel Borkmann 		.combine = csum_block_add_ext,
29772817a336SDaniel Borkmann 	};
29782817a336SDaniel Borkmann 
29792817a336SDaniel Borkmann 	return __skb_checksum(skb, offset, len, csum, &ops);
29802817a336SDaniel Borkmann }
2981b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_checksum);
29821da177e4SLinus Torvalds 
29831da177e4SLinus Torvalds /* Both of above in one bottle. */
29841da177e4SLinus Torvalds 
298581d77662SAl Viro __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
29868d5930dfSAl Viro 				    u8 *to, int len)
29871da177e4SLinus Torvalds {
29881a028e50SDavid S. Miller 	int start = skb_headlen(skb);
29891a028e50SDavid S. Miller 	int i, copy = start - offset;
2990fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
29911da177e4SLinus Torvalds 	int pos = 0;
29928d5930dfSAl Viro 	__wsum csum = 0;
29931da177e4SLinus Torvalds 
29941da177e4SLinus Torvalds 	/* Copy header. */
29951da177e4SLinus Torvalds 	if (copy > 0) {
29961da177e4SLinus Torvalds 		if (copy > len)
29971da177e4SLinus Torvalds 			copy = len;
29981da177e4SLinus Torvalds 		csum = csum_partial_copy_nocheck(skb->data + offset, to,
2999cc44c17bSAl Viro 						 copy);
30001da177e4SLinus Torvalds 		if ((len -= copy) == 0)
30011da177e4SLinus Torvalds 			return csum;
30021da177e4SLinus Torvalds 		offset += copy;
30031da177e4SLinus Torvalds 		to     += copy;
30041da177e4SLinus Torvalds 		pos	= copy;
30051da177e4SLinus Torvalds 	}
30061da177e4SLinus Torvalds 
30071da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
30081a028e50SDavid S. Miller 		int end;
30091da177e4SLinus Torvalds 
3010547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
30111a028e50SDavid S. Miller 
30129e903e08SEric Dumazet 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
30131da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
3014c613c209SWillem de Bruijn 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3015c613c209SWillem de Bruijn 			u32 p_off, p_len, copied;
3016c613c209SWillem de Bruijn 			struct page *p;
30175084205fSAl Viro 			__wsum csum2;
30181da177e4SLinus Torvalds 			u8 *vaddr;
30191da177e4SLinus Torvalds 
30201da177e4SLinus Torvalds 			if (copy > len)
30211da177e4SLinus Torvalds 				copy = len;
3022c613c209SWillem de Bruijn 
3023c613c209SWillem de Bruijn 			skb_frag_foreach_page(frag,
3024b54c9d5bSJonathan Lemon 					      skb_frag_off(frag) + offset - start,
3025c613c209SWillem de Bruijn 					      copy, p, p_off, p_len, copied) {
3026c613c209SWillem de Bruijn 				vaddr = kmap_atomic(p);
3027c613c209SWillem de Bruijn 				csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3028c613c209SWillem de Bruijn 								  to + copied,
3029cc44c17bSAl Viro 								  p_len);
303051c56b00SEric Dumazet 				kunmap_atomic(vaddr);
30311da177e4SLinus Torvalds 				csum = csum_block_add(csum, csum2, pos);
3032c613c209SWillem de Bruijn 				pos += p_len;
3033c613c209SWillem de Bruijn 			}
3034c613c209SWillem de Bruijn 
30351da177e4SLinus Torvalds 			if (!(len -= copy))
30361da177e4SLinus Torvalds 				return csum;
30371da177e4SLinus Torvalds 			offset += copy;
30381da177e4SLinus Torvalds 			to     += copy;
30391da177e4SLinus Torvalds 		}
30401a028e50SDavid S. Miller 		start = end;
30411da177e4SLinus Torvalds 	}
30421da177e4SLinus Torvalds 
3043fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
304481d77662SAl Viro 		__wsum csum2;
30451a028e50SDavid S. Miller 		int end;
30461da177e4SLinus Torvalds 
3047547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
30481a028e50SDavid S. Miller 
3049fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
30501da177e4SLinus Torvalds 		if ((copy = end - offset) > 0) {
30511da177e4SLinus Torvalds 			if (copy > len)
30521da177e4SLinus Torvalds 				copy = len;
3053fbb398a8SDavid S. Miller 			csum2 = skb_copy_and_csum_bits(frag_iter,
30541a028e50SDavid S. Miller 						       offset - start,
30558d5930dfSAl Viro 						       to, copy);
30561da177e4SLinus Torvalds 			csum = csum_block_add(csum, csum2, pos);
30571da177e4SLinus Torvalds 			if ((len -= copy) == 0)
30581da177e4SLinus Torvalds 				return csum;
30591da177e4SLinus Torvalds 			offset += copy;
30601da177e4SLinus Torvalds 			to     += copy;
30611da177e4SLinus Torvalds 			pos    += copy;
30621da177e4SLinus Torvalds 		}
30631a028e50SDavid S. Miller 		start = end;
30641da177e4SLinus Torvalds 	}
306509a62660SKris Katterjohn 	BUG_ON(len);
30661da177e4SLinus Torvalds 	return csum;
30671da177e4SLinus Torvalds }
3068b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_and_csum_bits);
30691da177e4SLinus Torvalds 
307049f8e832SCong Wang __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
307149f8e832SCong Wang {
307249f8e832SCong Wang 	__sum16 sum;
307349f8e832SCong Wang 
307449f8e832SCong Wang 	sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
307514641931SCong Wang 	/* See comments in __skb_checksum_complete(). */
307649f8e832SCong Wang 	if (likely(!sum)) {
307749f8e832SCong Wang 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
307849f8e832SCong Wang 		    !skb->csum_complete_sw)
30797fe50ac8SCong Wang 			netdev_rx_csum_fault(skb->dev, skb);
308049f8e832SCong Wang 	}
308149f8e832SCong Wang 	if (!skb_shared(skb))
308249f8e832SCong Wang 		skb->csum_valid = !sum;
308349f8e832SCong Wang 	return sum;
308449f8e832SCong Wang }
308549f8e832SCong Wang EXPORT_SYMBOL(__skb_checksum_complete_head);
308649f8e832SCong Wang 
308714641931SCong Wang /* This function assumes skb->csum already holds pseudo header's checksum,
308814641931SCong Wang  * which has been changed from the hardware checksum, for example, by
308914641931SCong Wang  * __skb_checksum_validate_complete(). And, the original skb->csum must
309014641931SCong Wang  * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
309114641931SCong Wang  *
309214641931SCong Wang  * It returns non-zero if the recomputed checksum is still invalid, otherwise
309314641931SCong Wang  * zero. The new checksum is stored back into skb->csum unless the skb is
309414641931SCong Wang  * shared.
309514641931SCong Wang  */
309649f8e832SCong Wang __sum16 __skb_checksum_complete(struct sk_buff *skb)
309749f8e832SCong Wang {
309849f8e832SCong Wang 	__wsum csum;
309949f8e832SCong Wang 	__sum16 sum;
310049f8e832SCong Wang 
310149f8e832SCong Wang 	csum = skb_checksum(skb, 0, skb->len, 0);
310249f8e832SCong Wang 
310349f8e832SCong Wang 	sum = csum_fold(csum_add(skb->csum, csum));
310414641931SCong Wang 	/* This check is inverted, because we already knew the hardware
310514641931SCong Wang 	 * checksum is invalid before calling this function. So, if the
310614641931SCong Wang 	 * re-computed checksum is valid instead, then we have a mismatch
310714641931SCong Wang 	 * between the original skb->csum and skb_checksum(). This means either
310814641931SCong Wang 	 * the original hardware checksum is incorrect or we screw up skb->csum
310914641931SCong Wang 	 * when moving skb->data around.
311014641931SCong Wang 	 */
311149f8e832SCong Wang 	if (likely(!sum)) {
311249f8e832SCong Wang 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
311349f8e832SCong Wang 		    !skb->csum_complete_sw)
31147fe50ac8SCong Wang 			netdev_rx_csum_fault(skb->dev, skb);
311549f8e832SCong Wang 	}
311649f8e832SCong Wang 
311749f8e832SCong Wang 	if (!skb_shared(skb)) {
311849f8e832SCong Wang 		/* Save full packet checksum */
311949f8e832SCong Wang 		skb->csum = csum;
312049f8e832SCong Wang 		skb->ip_summed = CHECKSUM_COMPLETE;
312149f8e832SCong Wang 		skb->csum_complete_sw = 1;
312249f8e832SCong Wang 		skb->csum_valid = !sum;
312349f8e832SCong Wang 	}
312449f8e832SCong Wang 
312549f8e832SCong Wang 	return sum;
312649f8e832SCong Wang }
312749f8e832SCong Wang EXPORT_SYMBOL(__skb_checksum_complete);
312849f8e832SCong Wang 
31299617813dSDavide Caratti static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
31309617813dSDavide Caratti {
31319617813dSDavide Caratti 	net_warn_ratelimited(
31329617813dSDavide Caratti 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
31339617813dSDavide Caratti 		__func__);
31349617813dSDavide Caratti 	return 0;
31359617813dSDavide Caratti }
31369617813dSDavide Caratti 
31379617813dSDavide Caratti static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
31389617813dSDavide Caratti 				       int offset, int len)
31399617813dSDavide Caratti {
31409617813dSDavide Caratti 	net_warn_ratelimited(
31419617813dSDavide Caratti 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
31429617813dSDavide Caratti 		__func__);
31439617813dSDavide Caratti 	return 0;
31449617813dSDavide Caratti }
31459617813dSDavide Caratti 
31469617813dSDavide Caratti static const struct skb_checksum_ops default_crc32c_ops = {
31479617813dSDavide Caratti 	.update  = warn_crc32c_csum_update,
31489617813dSDavide Caratti 	.combine = warn_crc32c_csum_combine,
31499617813dSDavide Caratti };
31509617813dSDavide Caratti 
31519617813dSDavide Caratti const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
31529617813dSDavide Caratti 	&default_crc32c_ops;
31539617813dSDavide Caratti EXPORT_SYMBOL(crc32c_csum_stub);
31549617813dSDavide Caratti 
3155af2806f8SThomas Graf  /**
3156af2806f8SThomas Graf  *	skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3157af2806f8SThomas Graf  *	@from: source buffer
3158af2806f8SThomas Graf  *
3159af2806f8SThomas Graf  *	Calculates the amount of linear headroom needed in the 'to' skb passed
3160af2806f8SThomas Graf  *	into skb_zerocopy().
3161af2806f8SThomas Graf  */
3162af2806f8SThomas Graf unsigned int
3163af2806f8SThomas Graf skb_zerocopy_headlen(const struct sk_buff *from)
3164af2806f8SThomas Graf {
3165af2806f8SThomas Graf 	unsigned int hlen = 0;
3166af2806f8SThomas Graf 
3167af2806f8SThomas Graf 	if (!from->head_frag ||
3168af2806f8SThomas Graf 	    skb_headlen(from) < L1_CACHE_BYTES ||
3169a17ad096SPravin B Shelar 	    skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3170af2806f8SThomas Graf 		hlen = skb_headlen(from);
3171a17ad096SPravin B Shelar 		if (!hlen)
3172a17ad096SPravin B Shelar 			hlen = from->len;
3173a17ad096SPravin B Shelar 	}
3174af2806f8SThomas Graf 
3175af2806f8SThomas Graf 	if (skb_has_frag_list(from))
3176af2806f8SThomas Graf 		hlen = from->len;
3177af2806f8SThomas Graf 
3178af2806f8SThomas Graf 	return hlen;
3179af2806f8SThomas Graf }
3180af2806f8SThomas Graf EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3181af2806f8SThomas Graf 
3182af2806f8SThomas Graf /**
3183af2806f8SThomas Graf  *	skb_zerocopy - Zero copy skb to skb
3184af2806f8SThomas Graf  *	@to: destination buffer
31857fceb4deSMasanari Iida  *	@from: source buffer
3186af2806f8SThomas Graf  *	@len: number of bytes to copy from source buffer
3187af2806f8SThomas Graf  *	@hlen: size of linear headroom in destination buffer
3188af2806f8SThomas Graf  *
3189af2806f8SThomas Graf  *	Copies up to `len` bytes from `from` to `to` by creating references
3190af2806f8SThomas Graf  *	to the frags in the source buffer.
3191af2806f8SThomas Graf  *
3192af2806f8SThomas Graf  *	The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3193af2806f8SThomas Graf  *	headroom in the `to` buffer.
319436d5fe6aSZoltan Kiss  *
319536d5fe6aSZoltan Kiss  *	Return value:
319636d5fe6aSZoltan Kiss  *	0: everything is OK
319736d5fe6aSZoltan Kiss  *	-ENOMEM: couldn't orphan frags of @from due to lack of memory
319836d5fe6aSZoltan Kiss  *	-EFAULT: skb_copy_bits() found some problem with skb geometry
3199af2806f8SThomas Graf  */
320036d5fe6aSZoltan Kiss int
320136d5fe6aSZoltan Kiss skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3202af2806f8SThomas Graf {
3203af2806f8SThomas Graf 	int i, j = 0;
3204af2806f8SThomas Graf 	int plen = 0; /* length of skb->head fragment */
320536d5fe6aSZoltan Kiss 	int ret;
3206af2806f8SThomas Graf 	struct page *page;
3207af2806f8SThomas Graf 	unsigned int offset;
3208af2806f8SThomas Graf 
3209af2806f8SThomas Graf 	BUG_ON(!from->head_frag && !hlen);
3210af2806f8SThomas Graf 
3211af2806f8SThomas Graf 	/* dont bother with small payloads */
321236d5fe6aSZoltan Kiss 	if (len <= skb_tailroom(to))
321336d5fe6aSZoltan Kiss 		return skb_copy_bits(from, 0, skb_put(to, len), len);
3214af2806f8SThomas Graf 
3215af2806f8SThomas Graf 	if (hlen) {
321636d5fe6aSZoltan Kiss 		ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
321736d5fe6aSZoltan Kiss 		if (unlikely(ret))
321836d5fe6aSZoltan Kiss 			return ret;
3219af2806f8SThomas Graf 		len -= hlen;
3220af2806f8SThomas Graf 	} else {
3221af2806f8SThomas Graf 		plen = min_t(int, skb_headlen(from), len);
3222af2806f8SThomas Graf 		if (plen) {
3223af2806f8SThomas Graf 			page = virt_to_head_page(from->head);
3224af2806f8SThomas Graf 			offset = from->data - (unsigned char *)page_address(page);
3225af2806f8SThomas Graf 			__skb_fill_page_desc(to, 0, page, offset, plen);
3226af2806f8SThomas Graf 			get_page(page);
3227af2806f8SThomas Graf 			j = 1;
3228af2806f8SThomas Graf 			len -= plen;
3229af2806f8SThomas Graf 		}
3230af2806f8SThomas Graf 	}
3231af2806f8SThomas Graf 
3232ede57d58SRichard Gobert 	skb_len_add(to, len + plen);
3233af2806f8SThomas Graf 
323436d5fe6aSZoltan Kiss 	if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
323536d5fe6aSZoltan Kiss 		skb_tx_error(from);
323636d5fe6aSZoltan Kiss 		return -ENOMEM;
323736d5fe6aSZoltan Kiss 	}
32381f8b977aSWillem de Bruijn 	skb_zerocopy_clone(to, from, GFP_ATOMIC);
323936d5fe6aSZoltan Kiss 
3240af2806f8SThomas Graf 	for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3241d8e18a51SMatthew Wilcox (Oracle) 		int size;
3242d8e18a51SMatthew Wilcox (Oracle) 
3243af2806f8SThomas Graf 		if (!len)
3244af2806f8SThomas Graf 			break;
3245af2806f8SThomas Graf 		skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3246d8e18a51SMatthew Wilcox (Oracle) 		size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3247d8e18a51SMatthew Wilcox (Oracle) 					len);
3248d8e18a51SMatthew Wilcox (Oracle) 		skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3249d8e18a51SMatthew Wilcox (Oracle) 		len -= size;
3250af2806f8SThomas Graf 		skb_frag_ref(to, j);
3251af2806f8SThomas Graf 		j++;
3252af2806f8SThomas Graf 	}
3253af2806f8SThomas Graf 	skb_shinfo(to)->nr_frags = j;
325436d5fe6aSZoltan Kiss 
325536d5fe6aSZoltan Kiss 	return 0;
3256af2806f8SThomas Graf }
3257af2806f8SThomas Graf EXPORT_SYMBOL_GPL(skb_zerocopy);
3258af2806f8SThomas Graf 
32591da177e4SLinus Torvalds void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
32601da177e4SLinus Torvalds {
3261d3bc23e7SAl Viro 	__wsum csum;
32621da177e4SLinus Torvalds 	long csstart;
32631da177e4SLinus Torvalds 
326484fa7933SPatrick McHardy 	if (skb->ip_summed == CHECKSUM_PARTIAL)
326555508d60SMichał Mirosław 		csstart = skb_checksum_start_offset(skb);
32661da177e4SLinus Torvalds 	else
32671da177e4SLinus Torvalds 		csstart = skb_headlen(skb);
32681da177e4SLinus Torvalds 
326909a62660SKris Katterjohn 	BUG_ON(csstart > skb_headlen(skb));
32701da177e4SLinus Torvalds 
3271d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data(skb, to, csstart);
32721da177e4SLinus Torvalds 
32731da177e4SLinus Torvalds 	csum = 0;
32741da177e4SLinus Torvalds 	if (csstart != skb->len)
32751da177e4SLinus Torvalds 		csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
32768d5930dfSAl Viro 					      skb->len - csstart);
32771da177e4SLinus Torvalds 
327884fa7933SPatrick McHardy 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
3279ff1dcadbSAl Viro 		long csstuff = csstart + skb->csum_offset;
32801da177e4SLinus Torvalds 
3281d3bc23e7SAl Viro 		*((__sum16 *)(to + csstuff)) = csum_fold(csum);
32821da177e4SLinus Torvalds 	}
32831da177e4SLinus Torvalds }
3284b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_copy_and_csum_dev);
32851da177e4SLinus Torvalds 
32861da177e4SLinus Torvalds /**
32871da177e4SLinus Torvalds  *	skb_dequeue - remove from the head of the queue
32881da177e4SLinus Torvalds  *	@list: list to dequeue from
32891da177e4SLinus Torvalds  *
32901da177e4SLinus Torvalds  *	Remove the head of the list. The list lock is taken so the function
32911da177e4SLinus Torvalds  *	may be used safely with other locking list functions. The head item is
32921da177e4SLinus Torvalds  *	returned or %NULL if the list is empty.
32931da177e4SLinus Torvalds  */
32941da177e4SLinus Torvalds 
32951da177e4SLinus Torvalds struct sk_buff *skb_dequeue(struct sk_buff_head *list)
32961da177e4SLinus Torvalds {
32971da177e4SLinus Torvalds 	unsigned long flags;
32981da177e4SLinus Torvalds 	struct sk_buff *result;
32991da177e4SLinus Torvalds 
33001da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
33011da177e4SLinus Torvalds 	result = __skb_dequeue(list);
33021da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
33031da177e4SLinus Torvalds 	return result;
33041da177e4SLinus Torvalds }
3305b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_dequeue);
33061da177e4SLinus Torvalds 
33071da177e4SLinus Torvalds /**
33081da177e4SLinus Torvalds  *	skb_dequeue_tail - remove from the tail of the queue
33091da177e4SLinus Torvalds  *	@list: list to dequeue from
33101da177e4SLinus Torvalds  *
33111da177e4SLinus Torvalds  *	Remove the tail of the list. The list lock is taken so the function
33121da177e4SLinus Torvalds  *	may be used safely with other locking list functions. The tail item is
33131da177e4SLinus Torvalds  *	returned or %NULL if the list is empty.
33141da177e4SLinus Torvalds  */
33151da177e4SLinus Torvalds struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
33161da177e4SLinus Torvalds {
33171da177e4SLinus Torvalds 	unsigned long flags;
33181da177e4SLinus Torvalds 	struct sk_buff *result;
33191da177e4SLinus Torvalds 
33201da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
33211da177e4SLinus Torvalds 	result = __skb_dequeue_tail(list);
33221da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
33231da177e4SLinus Torvalds 	return result;
33241da177e4SLinus Torvalds }
3325b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_dequeue_tail);
33261da177e4SLinus Torvalds 
33271da177e4SLinus Torvalds /**
33281da177e4SLinus Torvalds  *	skb_queue_purge - empty a list
33291da177e4SLinus Torvalds  *	@list: list to empty
33301da177e4SLinus Torvalds  *
33311da177e4SLinus Torvalds  *	Delete all buffers on an &sk_buff list. Each buffer is removed from
33321da177e4SLinus Torvalds  *	the list and one reference dropped. This function takes the list
33331da177e4SLinus Torvalds  *	lock and is atomic with respect to other list locking functions.
33341da177e4SLinus Torvalds  */
33351da177e4SLinus Torvalds void skb_queue_purge(struct sk_buff_head *list)
33361da177e4SLinus Torvalds {
33371da177e4SLinus Torvalds 	struct sk_buff *skb;
33381da177e4SLinus Torvalds 	while ((skb = skb_dequeue(list)) != NULL)
33391da177e4SLinus Torvalds 		kfree_skb(skb);
33401da177e4SLinus Torvalds }
3341b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_purge);
33421da177e4SLinus Torvalds 
33431da177e4SLinus Torvalds /**
33449f5afeaeSYaogong Wang  *	skb_rbtree_purge - empty a skb rbtree
33459f5afeaeSYaogong Wang  *	@root: root of the rbtree to empty
3346385114deSPeter Oskolkov  *	Return value: the sum of truesizes of all purged skbs.
33479f5afeaeSYaogong Wang  *
33489f5afeaeSYaogong Wang  *	Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
33499f5afeaeSYaogong Wang  *	the list and one reference dropped. This function does not take
33509f5afeaeSYaogong Wang  *	any lock. Synchronization should be handled by the caller (e.g., TCP
33519f5afeaeSYaogong Wang  *	out-of-order queue is protected by the socket lock).
33529f5afeaeSYaogong Wang  */
3353385114deSPeter Oskolkov unsigned int skb_rbtree_purge(struct rb_root *root)
33549f5afeaeSYaogong Wang {
33557c90584cSEric Dumazet 	struct rb_node *p = rb_first(root);
3356385114deSPeter Oskolkov 	unsigned int sum = 0;
33579f5afeaeSYaogong Wang 
33587c90584cSEric Dumazet 	while (p) {
33597c90584cSEric Dumazet 		struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
33607c90584cSEric Dumazet 
33617c90584cSEric Dumazet 		p = rb_next(p);
33627c90584cSEric Dumazet 		rb_erase(&skb->rbnode, root);
3363385114deSPeter Oskolkov 		sum += skb->truesize;
33649f5afeaeSYaogong Wang 		kfree_skb(skb);
33657c90584cSEric Dumazet 	}
3366385114deSPeter Oskolkov 	return sum;
33679f5afeaeSYaogong Wang }
33689f5afeaeSYaogong Wang 
33699f5afeaeSYaogong Wang /**
33701da177e4SLinus Torvalds  *	skb_queue_head - queue a buffer at the list head
33711da177e4SLinus Torvalds  *	@list: list to use
33721da177e4SLinus Torvalds  *	@newsk: buffer to queue
33731da177e4SLinus Torvalds  *
33741da177e4SLinus Torvalds  *	Queue a buffer at the start of the list. This function takes the
33751da177e4SLinus Torvalds  *	list lock and can be used safely with other locking &sk_buff functions
33761da177e4SLinus Torvalds  *	safely.
33771da177e4SLinus Torvalds  *
33781da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
33791da177e4SLinus Torvalds  */
33801da177e4SLinus Torvalds void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
33811da177e4SLinus Torvalds {
33821da177e4SLinus Torvalds 	unsigned long flags;
33831da177e4SLinus Torvalds 
33841da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
33851da177e4SLinus Torvalds 	__skb_queue_head(list, newsk);
33861da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
33871da177e4SLinus Torvalds }
3388b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_head);
33891da177e4SLinus Torvalds 
33901da177e4SLinus Torvalds /**
33911da177e4SLinus Torvalds  *	skb_queue_tail - queue a buffer at the list tail
33921da177e4SLinus Torvalds  *	@list: list to use
33931da177e4SLinus Torvalds  *	@newsk: buffer to queue
33941da177e4SLinus Torvalds  *
33951da177e4SLinus Torvalds  *	Queue a buffer at the tail of the list. This function takes the
33961da177e4SLinus Torvalds  *	list lock and can be used safely with other locking &sk_buff functions
33971da177e4SLinus Torvalds  *	safely.
33981da177e4SLinus Torvalds  *
33991da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
34001da177e4SLinus Torvalds  */
34011da177e4SLinus Torvalds void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
34021da177e4SLinus Torvalds {
34031da177e4SLinus Torvalds 	unsigned long flags;
34041da177e4SLinus Torvalds 
34051da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
34061da177e4SLinus Torvalds 	__skb_queue_tail(list, newsk);
34071da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
34081da177e4SLinus Torvalds }
3409b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_queue_tail);
34108728b834SDavid S. Miller 
34111da177e4SLinus Torvalds /**
34121da177e4SLinus Torvalds  *	skb_unlink	-	remove a buffer from a list
34131da177e4SLinus Torvalds  *	@skb: buffer to remove
34148728b834SDavid S. Miller  *	@list: list to use
34151da177e4SLinus Torvalds  *
34168728b834SDavid S. Miller  *	Remove a packet from a list. The list locks are taken and this
34178728b834SDavid S. Miller  *	function is atomic with respect to other list locked calls
34181da177e4SLinus Torvalds  *
34198728b834SDavid S. Miller  *	You must know what list the SKB is on.
34201da177e4SLinus Torvalds  */
34218728b834SDavid S. Miller void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
34221da177e4SLinus Torvalds {
34231da177e4SLinus Torvalds 	unsigned long flags;
34241da177e4SLinus Torvalds 
34251da177e4SLinus Torvalds 	spin_lock_irqsave(&list->lock, flags);
34268728b834SDavid S. Miller 	__skb_unlink(skb, list);
34271da177e4SLinus Torvalds 	spin_unlock_irqrestore(&list->lock, flags);
34281da177e4SLinus Torvalds }
3429b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_unlink);
34301da177e4SLinus Torvalds 
34311da177e4SLinus Torvalds /**
34321da177e4SLinus Torvalds  *	skb_append	-	append a buffer
34331da177e4SLinus Torvalds  *	@old: buffer to insert after
34341da177e4SLinus Torvalds  *	@newsk: buffer to insert
34358728b834SDavid S. Miller  *	@list: list to use
34361da177e4SLinus Torvalds  *
34371da177e4SLinus Torvalds  *	Place a packet after a given packet in a list. The list locks are taken
34381da177e4SLinus Torvalds  *	and this function is atomic with respect to other list locked calls.
34391da177e4SLinus Torvalds  *	A buffer cannot be placed on two lists at the same time.
34401da177e4SLinus Torvalds  */
34418728b834SDavid S. Miller void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
34421da177e4SLinus Torvalds {
34431da177e4SLinus Torvalds 	unsigned long flags;
34441da177e4SLinus Torvalds 
34458728b834SDavid S. Miller 	spin_lock_irqsave(&list->lock, flags);
34467de6c033SGerrit Renker 	__skb_queue_after(list, old, newsk);
34478728b834SDavid S. Miller 	spin_unlock_irqrestore(&list->lock, flags);
34481da177e4SLinus Torvalds }
3449b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_append);
34501da177e4SLinus Torvalds 
34511da177e4SLinus Torvalds static inline void skb_split_inside_header(struct sk_buff *skb,
34521da177e4SLinus Torvalds 					   struct sk_buff* skb1,
34531da177e4SLinus Torvalds 					   const u32 len, const int pos)
34541da177e4SLinus Torvalds {
34551da177e4SLinus Torvalds 	int i;
34561da177e4SLinus Torvalds 
3457d626f62bSArnaldo Carvalho de Melo 	skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3458d626f62bSArnaldo Carvalho de Melo 					 pos - len);
34591da177e4SLinus Torvalds 	/* And move data appendix as is. */
34601da177e4SLinus Torvalds 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
34611da177e4SLinus Torvalds 		skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
34621da177e4SLinus Torvalds 
34631da177e4SLinus Torvalds 	skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
34641da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags  = 0;
34651da177e4SLinus Torvalds 	skb1->data_len		   = skb->data_len;
34661da177e4SLinus Torvalds 	skb1->len		   += skb1->data_len;
34671da177e4SLinus Torvalds 	skb->data_len		   = 0;
34681da177e4SLinus Torvalds 	skb->len		   = len;
346927a884dcSArnaldo Carvalho de Melo 	skb_set_tail_pointer(skb, len);
34701da177e4SLinus Torvalds }
34711da177e4SLinus Torvalds 
34721da177e4SLinus Torvalds static inline void skb_split_no_header(struct sk_buff *skb,
34731da177e4SLinus Torvalds 				       struct sk_buff* skb1,
34741da177e4SLinus Torvalds 				       const u32 len, int pos)
34751da177e4SLinus Torvalds {
34761da177e4SLinus Torvalds 	int i, k = 0;
34771da177e4SLinus Torvalds 	const int nfrags = skb_shinfo(skb)->nr_frags;
34781da177e4SLinus Torvalds 
34791da177e4SLinus Torvalds 	skb_shinfo(skb)->nr_frags = 0;
34801da177e4SLinus Torvalds 	skb1->len		  = skb1->data_len = skb->len - len;
34811da177e4SLinus Torvalds 	skb->len		  = len;
34821da177e4SLinus Torvalds 	skb->data_len		  = len - pos;
34831da177e4SLinus Torvalds 
34841da177e4SLinus Torvalds 	for (i = 0; i < nfrags; i++) {
34859e903e08SEric Dumazet 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
34861da177e4SLinus Torvalds 
34871da177e4SLinus Torvalds 		if (pos + size > len) {
34881da177e4SLinus Torvalds 			skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
34891da177e4SLinus Torvalds 
34901da177e4SLinus Torvalds 			if (pos < len) {
34911da177e4SLinus Torvalds 				/* Split frag.
34921da177e4SLinus Torvalds 				 * We have two variants in this case:
34931da177e4SLinus Torvalds 				 * 1. Move all the frag to the second
34941da177e4SLinus Torvalds 				 *    part, if it is possible. F.e.
34951da177e4SLinus Torvalds 				 *    this approach is mandatory for TUX,
34961da177e4SLinus Torvalds 				 *    where splitting is expensive.
34971da177e4SLinus Torvalds 				 * 2. Split is accurately. We make this.
34981da177e4SLinus Torvalds 				 */
3499ea2ab693SIan Campbell 				skb_frag_ref(skb, i);
3500b54c9d5bSJonathan Lemon 				skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
35019e903e08SEric Dumazet 				skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
35029e903e08SEric Dumazet 				skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
35031da177e4SLinus Torvalds 				skb_shinfo(skb)->nr_frags++;
35041da177e4SLinus Torvalds 			}
35051da177e4SLinus Torvalds 			k++;
35061da177e4SLinus Torvalds 		} else
35071da177e4SLinus Torvalds 			skb_shinfo(skb)->nr_frags++;
35081da177e4SLinus Torvalds 		pos += size;
35091da177e4SLinus Torvalds 	}
35101da177e4SLinus Torvalds 	skb_shinfo(skb1)->nr_frags = k;
35111da177e4SLinus Torvalds }
35121da177e4SLinus Torvalds 
35131da177e4SLinus Torvalds /**
35141da177e4SLinus Torvalds  * skb_split - Split fragmented skb to two parts at length len.
35151da177e4SLinus Torvalds  * @skb: the buffer to split
35161da177e4SLinus Torvalds  * @skb1: the buffer to receive the second part
35171da177e4SLinus Torvalds  * @len: new length for skb
35181da177e4SLinus Torvalds  */
35191da177e4SLinus Torvalds void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
35201da177e4SLinus Torvalds {
35211da177e4SLinus Torvalds 	int pos = skb_headlen(skb);
35229b65b17dSTalal Ahmad 	const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
35231da177e4SLinus Torvalds 
3524753f1ca4SPavel Begunkov 	skb_zcopy_downgrade_managed(skb);
3525753f1ca4SPavel Begunkov 
35269b65b17dSTalal Ahmad 	skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
35271f8b977aSWillem de Bruijn 	skb_zerocopy_clone(skb1, skb, 0);
35281da177e4SLinus Torvalds 	if (len < pos)	/* Split line is inside header. */
35291da177e4SLinus Torvalds 		skb_split_inside_header(skb, skb1, len, pos);
35301da177e4SLinus Torvalds 	else		/* Second chunk has no header, nothing to copy. */
35311da177e4SLinus Torvalds 		skb_split_no_header(skb, skb1, len, pos);
35321da177e4SLinus Torvalds }
3533b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_split);
35341da177e4SLinus Torvalds 
35359f782db3SIlpo Järvinen /* Shifting from/to a cloned skb is a no-go.
35369f782db3SIlpo Järvinen  *
35379f782db3SIlpo Järvinen  * Caller cannot keep skb_shinfo related pointers past calling here!
35389f782db3SIlpo Järvinen  */
3539832d11c5SIlpo Järvinen static int skb_prepare_for_shift(struct sk_buff *skb)
3540832d11c5SIlpo Järvinen {
3541c4777efaSEric Dumazet 	return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3542832d11c5SIlpo Järvinen }
3543832d11c5SIlpo Järvinen 
3544832d11c5SIlpo Järvinen /**
3545832d11c5SIlpo Järvinen  * skb_shift - Shifts paged data partially from skb to another
3546832d11c5SIlpo Järvinen  * @tgt: buffer into which tail data gets added
3547832d11c5SIlpo Järvinen  * @skb: buffer from which the paged data comes from
3548832d11c5SIlpo Järvinen  * @shiftlen: shift up to this many bytes
3549832d11c5SIlpo Järvinen  *
3550832d11c5SIlpo Järvinen  * Attempts to shift up to shiftlen worth of bytes, which may be less than
355120e994a0SFeng King  * the length of the skb, from skb to tgt. Returns number bytes shifted.
3552832d11c5SIlpo Järvinen  * It's up to caller to free skb if everything was shifted.
3553832d11c5SIlpo Järvinen  *
3554832d11c5SIlpo Järvinen  * If @tgt runs out of frags, the whole operation is aborted.
3555832d11c5SIlpo Järvinen  *
3556832d11c5SIlpo Järvinen  * Skb cannot include anything else but paged data while tgt is allowed
3557832d11c5SIlpo Järvinen  * to have non-paged data as well.
3558832d11c5SIlpo Järvinen  *
3559832d11c5SIlpo Järvinen  * TODO: full sized shift could be optimized but that would need
3560832d11c5SIlpo Järvinen  * specialized skb free'er to handle frags without up-to-date nr_frags.
3561832d11c5SIlpo Järvinen  */
3562832d11c5SIlpo Järvinen int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3563832d11c5SIlpo Järvinen {
3564832d11c5SIlpo Järvinen 	int from, to, merge, todo;
3565d8e18a51SMatthew Wilcox (Oracle) 	skb_frag_t *fragfrom, *fragto;
3566832d11c5SIlpo Järvinen 
3567832d11c5SIlpo Järvinen 	BUG_ON(shiftlen > skb->len);
3568f8071cdeSEric Dumazet 
3569f8071cdeSEric Dumazet 	if (skb_headlen(skb))
3570f8071cdeSEric Dumazet 		return 0;
35711f8b977aSWillem de Bruijn 	if (skb_zcopy(tgt) || skb_zcopy(skb))
35721f8b977aSWillem de Bruijn 		return 0;
3573832d11c5SIlpo Järvinen 
3574832d11c5SIlpo Järvinen 	todo = shiftlen;
3575832d11c5SIlpo Järvinen 	from = 0;
3576832d11c5SIlpo Järvinen 	to = skb_shinfo(tgt)->nr_frags;
3577832d11c5SIlpo Järvinen 	fragfrom = &skb_shinfo(skb)->frags[from];
3578832d11c5SIlpo Järvinen 
3579832d11c5SIlpo Järvinen 	/* Actual merge is delayed until the point when we know we can
3580832d11c5SIlpo Järvinen 	 * commit all, so that we don't have to undo partial changes
3581832d11c5SIlpo Järvinen 	 */
3582832d11c5SIlpo Järvinen 	if (!to ||
3583ea2ab693SIan Campbell 	    !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3584b54c9d5bSJonathan Lemon 			      skb_frag_off(fragfrom))) {
3585832d11c5SIlpo Järvinen 		merge = -1;
3586832d11c5SIlpo Järvinen 	} else {
3587832d11c5SIlpo Järvinen 		merge = to - 1;
3588832d11c5SIlpo Järvinen 
35899e903e08SEric Dumazet 		todo -= skb_frag_size(fragfrom);
3590832d11c5SIlpo Järvinen 		if (todo < 0) {
3591832d11c5SIlpo Järvinen 			if (skb_prepare_for_shift(skb) ||
3592832d11c5SIlpo Järvinen 			    skb_prepare_for_shift(tgt))
3593832d11c5SIlpo Järvinen 				return 0;
3594832d11c5SIlpo Järvinen 
35959f782db3SIlpo Järvinen 			/* All previous frag pointers might be stale! */
35969f782db3SIlpo Järvinen 			fragfrom = &skb_shinfo(skb)->frags[from];
3597832d11c5SIlpo Järvinen 			fragto = &skb_shinfo(tgt)->frags[merge];
3598832d11c5SIlpo Järvinen 
35999e903e08SEric Dumazet 			skb_frag_size_add(fragto, shiftlen);
36009e903e08SEric Dumazet 			skb_frag_size_sub(fragfrom, shiftlen);
3601b54c9d5bSJonathan Lemon 			skb_frag_off_add(fragfrom, shiftlen);
3602832d11c5SIlpo Järvinen 
3603832d11c5SIlpo Järvinen 			goto onlymerged;
3604832d11c5SIlpo Järvinen 		}
3605832d11c5SIlpo Järvinen 
3606832d11c5SIlpo Järvinen 		from++;
3607832d11c5SIlpo Järvinen 	}
3608832d11c5SIlpo Järvinen 
3609832d11c5SIlpo Järvinen 	/* Skip full, not-fitting skb to avoid expensive operations */
3610832d11c5SIlpo Järvinen 	if ((shiftlen == skb->len) &&
3611832d11c5SIlpo Järvinen 	    (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3612832d11c5SIlpo Järvinen 		return 0;
3613832d11c5SIlpo Järvinen 
3614832d11c5SIlpo Järvinen 	if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3615832d11c5SIlpo Järvinen 		return 0;
3616832d11c5SIlpo Järvinen 
3617832d11c5SIlpo Järvinen 	while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3618832d11c5SIlpo Järvinen 		if (to == MAX_SKB_FRAGS)
3619832d11c5SIlpo Järvinen 			return 0;
3620832d11c5SIlpo Järvinen 
3621832d11c5SIlpo Järvinen 		fragfrom = &skb_shinfo(skb)->frags[from];
3622832d11c5SIlpo Järvinen 		fragto = &skb_shinfo(tgt)->frags[to];
3623832d11c5SIlpo Järvinen 
36249e903e08SEric Dumazet 		if (todo >= skb_frag_size(fragfrom)) {
3625832d11c5SIlpo Järvinen 			*fragto = *fragfrom;
36269e903e08SEric Dumazet 			todo -= skb_frag_size(fragfrom);
3627832d11c5SIlpo Järvinen 			from++;
3628832d11c5SIlpo Järvinen 			to++;
3629832d11c5SIlpo Järvinen 
3630832d11c5SIlpo Järvinen 		} else {
3631ea2ab693SIan Campbell 			__skb_frag_ref(fragfrom);
3632b54c9d5bSJonathan Lemon 			skb_frag_page_copy(fragto, fragfrom);
3633b54c9d5bSJonathan Lemon 			skb_frag_off_copy(fragto, fragfrom);
36349e903e08SEric Dumazet 			skb_frag_size_set(fragto, todo);
3635832d11c5SIlpo Järvinen 
3636b54c9d5bSJonathan Lemon 			skb_frag_off_add(fragfrom, todo);
36379e903e08SEric Dumazet 			skb_frag_size_sub(fragfrom, todo);
3638832d11c5SIlpo Järvinen 			todo = 0;
3639832d11c5SIlpo Järvinen 
3640832d11c5SIlpo Järvinen 			to++;
3641832d11c5SIlpo Järvinen 			break;
3642832d11c5SIlpo Järvinen 		}
3643832d11c5SIlpo Järvinen 	}
3644832d11c5SIlpo Järvinen 
3645832d11c5SIlpo Järvinen 	/* Ready to "commit" this state change to tgt */
3646832d11c5SIlpo Järvinen 	skb_shinfo(tgt)->nr_frags = to;
3647832d11c5SIlpo Järvinen 
3648832d11c5SIlpo Järvinen 	if (merge >= 0) {
3649832d11c5SIlpo Järvinen 		fragfrom = &skb_shinfo(skb)->frags[0];
3650832d11c5SIlpo Järvinen 		fragto = &skb_shinfo(tgt)->frags[merge];
3651832d11c5SIlpo Järvinen 
36529e903e08SEric Dumazet 		skb_frag_size_add(fragto, skb_frag_size(fragfrom));
36536a5bcd84SIlias Apalodimas 		__skb_frag_unref(fragfrom, skb->pp_recycle);
3654832d11c5SIlpo Järvinen 	}
3655832d11c5SIlpo Järvinen 
3656832d11c5SIlpo Järvinen 	/* Reposition in the original skb */
3657832d11c5SIlpo Järvinen 	to = 0;
3658832d11c5SIlpo Järvinen 	while (from < skb_shinfo(skb)->nr_frags)
3659832d11c5SIlpo Järvinen 		skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3660832d11c5SIlpo Järvinen 	skb_shinfo(skb)->nr_frags = to;
3661832d11c5SIlpo Järvinen 
3662832d11c5SIlpo Järvinen 	BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3663832d11c5SIlpo Järvinen 
3664832d11c5SIlpo Järvinen onlymerged:
3665832d11c5SIlpo Järvinen 	/* Most likely the tgt won't ever need its checksum anymore, skb on
3666832d11c5SIlpo Järvinen 	 * the other hand might need it if it needs to be resent
3667832d11c5SIlpo Järvinen 	 */
3668832d11c5SIlpo Järvinen 	tgt->ip_summed = CHECKSUM_PARTIAL;
3669832d11c5SIlpo Järvinen 	skb->ip_summed = CHECKSUM_PARTIAL;
3670832d11c5SIlpo Järvinen 
3671ede57d58SRichard Gobert 	skb_len_add(skb, -shiftlen);
3672ede57d58SRichard Gobert 	skb_len_add(tgt, shiftlen);
3673832d11c5SIlpo Järvinen 
3674832d11c5SIlpo Järvinen 	return shiftlen;
3675832d11c5SIlpo Järvinen }
3676832d11c5SIlpo Järvinen 
3677677e90edSThomas Graf /**
3678677e90edSThomas Graf  * skb_prepare_seq_read - Prepare a sequential read of skb data
3679677e90edSThomas Graf  * @skb: the buffer to read
3680677e90edSThomas Graf  * @from: lower offset of data to be read
3681677e90edSThomas Graf  * @to: upper offset of data to be read
3682677e90edSThomas Graf  * @st: state variable
3683677e90edSThomas Graf  *
3684677e90edSThomas Graf  * Initializes the specified state variable. Must be called before
3685677e90edSThomas Graf  * invoking skb_seq_read() for the first time.
3686677e90edSThomas Graf  */
3687677e90edSThomas Graf void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3688677e90edSThomas Graf 			  unsigned int to, struct skb_seq_state *st)
3689677e90edSThomas Graf {
3690677e90edSThomas Graf 	st->lower_offset = from;
3691677e90edSThomas Graf 	st->upper_offset = to;
3692677e90edSThomas Graf 	st->root_skb = st->cur_skb = skb;
3693677e90edSThomas Graf 	st->frag_idx = st->stepped_offset = 0;
3694677e90edSThomas Graf 	st->frag_data = NULL;
369597550f6fSWillem de Bruijn 	st->frag_off = 0;
3696677e90edSThomas Graf }
3697b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_prepare_seq_read);
3698677e90edSThomas Graf 
3699677e90edSThomas Graf /**
3700677e90edSThomas Graf  * skb_seq_read - Sequentially read skb data
3701677e90edSThomas Graf  * @consumed: number of bytes consumed by the caller so far
3702677e90edSThomas Graf  * @data: destination pointer for data to be returned
3703677e90edSThomas Graf  * @st: state variable
3704677e90edSThomas Graf  *
3705bc32383cSMathias Krause  * Reads a block of skb data at @consumed relative to the
3706677e90edSThomas Graf  * lower offset specified to skb_prepare_seq_read(). Assigns
3707bc32383cSMathias Krause  * the head of the data block to @data and returns the length
3708677e90edSThomas Graf  * of the block or 0 if the end of the skb data or the upper
3709677e90edSThomas Graf  * offset has been reached.
3710677e90edSThomas Graf  *
3711677e90edSThomas Graf  * The caller is not required to consume all of the data
3712bc32383cSMathias Krause  * returned, i.e. @consumed is typically set to the number
3713677e90edSThomas Graf  * of bytes already consumed and the next call to
3714677e90edSThomas Graf  * skb_seq_read() will return the remaining part of the block.
3715677e90edSThomas Graf  *
371625985edcSLucas De Marchi  * Note 1: The size of each block of data returned can be arbitrary,
3717e793c0f7SMasanari Iida  *       this limitation is the cost for zerocopy sequential
3718677e90edSThomas Graf  *       reads of potentially non linear data.
3719677e90edSThomas Graf  *
3720bc2cda1eSRandy Dunlap  * Note 2: Fragment lists within fragments are not implemented
3721677e90edSThomas Graf  *       at the moment, state->root_skb could be replaced with
3722677e90edSThomas Graf  *       a stack for this purpose.
3723677e90edSThomas Graf  */
3724677e90edSThomas Graf unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
3725677e90edSThomas Graf 			  struct skb_seq_state *st)
3726677e90edSThomas Graf {
3727677e90edSThomas Graf 	unsigned int block_limit, abs_offset = consumed + st->lower_offset;
3728677e90edSThomas Graf 	skb_frag_t *frag;
3729677e90edSThomas Graf 
3730aeb193eaSWedson Almeida Filho 	if (unlikely(abs_offset >= st->upper_offset)) {
3731aeb193eaSWedson Almeida Filho 		if (st->frag_data) {
3732aeb193eaSWedson Almeida Filho 			kunmap_atomic(st->frag_data);
3733aeb193eaSWedson Almeida Filho 			st->frag_data = NULL;
3734aeb193eaSWedson Almeida Filho 		}
3735677e90edSThomas Graf 		return 0;
3736aeb193eaSWedson Almeida Filho 	}
3737677e90edSThomas Graf 
3738677e90edSThomas Graf next_skb:
373995e3b24cSHerbert Xu 	block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
3740677e90edSThomas Graf 
3741995b3379SThomas Chenault 	if (abs_offset < block_limit && !st->frag_data) {
374295e3b24cSHerbert Xu 		*data = st->cur_skb->data + (abs_offset - st->stepped_offset);
3743677e90edSThomas Graf 		return block_limit - abs_offset;
3744677e90edSThomas Graf 	}
3745677e90edSThomas Graf 
3746677e90edSThomas Graf 	if (st->frag_idx == 0 && !st->frag_data)
3747677e90edSThomas Graf 		st->stepped_offset += skb_headlen(st->cur_skb);
3748677e90edSThomas Graf 
3749677e90edSThomas Graf 	while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
375097550f6fSWillem de Bruijn 		unsigned int pg_idx, pg_off, pg_sz;
3751677e90edSThomas Graf 
375297550f6fSWillem de Bruijn 		frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
375397550f6fSWillem de Bruijn 
375497550f6fSWillem de Bruijn 		pg_idx = 0;
375597550f6fSWillem de Bruijn 		pg_off = skb_frag_off(frag);
375697550f6fSWillem de Bruijn 		pg_sz = skb_frag_size(frag);
375797550f6fSWillem de Bruijn 
375897550f6fSWillem de Bruijn 		if (skb_frag_must_loop(skb_frag_page(frag))) {
375997550f6fSWillem de Bruijn 			pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
376097550f6fSWillem de Bruijn 			pg_off = offset_in_page(pg_off + st->frag_off);
376197550f6fSWillem de Bruijn 			pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
376297550f6fSWillem de Bruijn 						    PAGE_SIZE - pg_off);
376397550f6fSWillem de Bruijn 		}
376497550f6fSWillem de Bruijn 
376597550f6fSWillem de Bruijn 		block_limit = pg_sz + st->stepped_offset;
3766677e90edSThomas Graf 		if (abs_offset < block_limit) {
3767677e90edSThomas Graf 			if (!st->frag_data)
376897550f6fSWillem de Bruijn 				st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
3769677e90edSThomas Graf 
377097550f6fSWillem de Bruijn 			*data = (u8 *)st->frag_data + pg_off +
3771677e90edSThomas Graf 				(abs_offset - st->stepped_offset);
3772677e90edSThomas Graf 
3773677e90edSThomas Graf 			return block_limit - abs_offset;
3774677e90edSThomas Graf 		}
3775677e90edSThomas Graf 
3776677e90edSThomas Graf 		if (st->frag_data) {
377751c56b00SEric Dumazet 			kunmap_atomic(st->frag_data);
3778677e90edSThomas Graf 			st->frag_data = NULL;
3779677e90edSThomas Graf 		}
3780677e90edSThomas Graf 
378197550f6fSWillem de Bruijn 		st->stepped_offset += pg_sz;
378297550f6fSWillem de Bruijn 		st->frag_off += pg_sz;
378397550f6fSWillem de Bruijn 		if (st->frag_off == skb_frag_size(frag)) {
378497550f6fSWillem de Bruijn 			st->frag_off = 0;
3785677e90edSThomas Graf 			st->frag_idx++;
378697550f6fSWillem de Bruijn 		}
3787677e90edSThomas Graf 	}
3788677e90edSThomas Graf 
37895b5a60daSOlaf Kirch 	if (st->frag_data) {
379051c56b00SEric Dumazet 		kunmap_atomic(st->frag_data);
37915b5a60daSOlaf Kirch 		st->frag_data = NULL;
37925b5a60daSOlaf Kirch 	}
37935b5a60daSOlaf Kirch 
379421dc3301SDavid S. Miller 	if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
3795677e90edSThomas Graf 		st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
379695e3b24cSHerbert Xu 		st->frag_idx = 0;
3797677e90edSThomas Graf 		goto next_skb;
379871b3346dSShyam Iyer 	} else if (st->cur_skb->next) {
379971b3346dSShyam Iyer 		st->cur_skb = st->cur_skb->next;
380071b3346dSShyam Iyer 		st->frag_idx = 0;
3801677e90edSThomas Graf 		goto next_skb;
3802677e90edSThomas Graf 	}
3803677e90edSThomas Graf 
3804677e90edSThomas Graf 	return 0;
3805677e90edSThomas Graf }
3806b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_seq_read);
3807677e90edSThomas Graf 
3808677e90edSThomas Graf /**
3809677e90edSThomas Graf  * skb_abort_seq_read - Abort a sequential read of skb data
3810677e90edSThomas Graf  * @st: state variable
3811677e90edSThomas Graf  *
3812677e90edSThomas Graf  * Must be called if skb_seq_read() was not called until it
3813677e90edSThomas Graf  * returned 0.
3814677e90edSThomas Graf  */
3815677e90edSThomas Graf void skb_abort_seq_read(struct skb_seq_state *st)
3816677e90edSThomas Graf {
3817677e90edSThomas Graf 	if (st->frag_data)
381851c56b00SEric Dumazet 		kunmap_atomic(st->frag_data);
3819677e90edSThomas Graf }
3820b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_abort_seq_read);
3821677e90edSThomas Graf 
38223fc7e8a6SThomas Graf #define TS_SKB_CB(state)	((struct skb_seq_state *) &((state)->cb))
38233fc7e8a6SThomas Graf 
38243fc7e8a6SThomas Graf static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
38253fc7e8a6SThomas Graf 					  struct ts_config *conf,
38263fc7e8a6SThomas Graf 					  struct ts_state *state)
38273fc7e8a6SThomas Graf {
38283fc7e8a6SThomas Graf 	return skb_seq_read(offset, text, TS_SKB_CB(state));
38293fc7e8a6SThomas Graf }
38303fc7e8a6SThomas Graf 
38313fc7e8a6SThomas Graf static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
38323fc7e8a6SThomas Graf {
38333fc7e8a6SThomas Graf 	skb_abort_seq_read(TS_SKB_CB(state));
38343fc7e8a6SThomas Graf }
38353fc7e8a6SThomas Graf 
38363fc7e8a6SThomas Graf /**
38373fc7e8a6SThomas Graf  * skb_find_text - Find a text pattern in skb data
38383fc7e8a6SThomas Graf  * @skb: the buffer to look in
38393fc7e8a6SThomas Graf  * @from: search offset
38403fc7e8a6SThomas Graf  * @to: search limit
38413fc7e8a6SThomas Graf  * @config: textsearch configuration
38423fc7e8a6SThomas Graf  *
38433fc7e8a6SThomas Graf  * Finds a pattern in the skb data according to the specified
38443fc7e8a6SThomas Graf  * textsearch configuration. Use textsearch_next() to retrieve
38453fc7e8a6SThomas Graf  * subsequent occurrences of the pattern. Returns the offset
38463fc7e8a6SThomas Graf  * to the first occurrence or UINT_MAX if no match was found.
38473fc7e8a6SThomas Graf  */
38483fc7e8a6SThomas Graf unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
3849059a2440SBojan Prtvar 			   unsigned int to, struct ts_config *config)
38503fc7e8a6SThomas Graf {
3851059a2440SBojan Prtvar 	struct ts_state state;
3852f72b948dSPhil Oester 	unsigned int ret;
3853f72b948dSPhil Oester 
3854b228c9b0SWillem de Bruijn 	BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
3855b228c9b0SWillem de Bruijn 
38563fc7e8a6SThomas Graf 	config->get_next_block = skb_ts_get_next_block;
38573fc7e8a6SThomas Graf 	config->finish = skb_ts_finish;
38583fc7e8a6SThomas Graf 
3859059a2440SBojan Prtvar 	skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
38603fc7e8a6SThomas Graf 
3861059a2440SBojan Prtvar 	ret = textsearch_find(config, &state);
3862f72b948dSPhil Oester 	return (ret <= to - from ? ret : UINT_MAX);
38633fc7e8a6SThomas Graf }
3864b4ac530fSDavid S. Miller EXPORT_SYMBOL(skb_find_text);
38653fc7e8a6SThomas Graf 
3866be12a1feSHannes Frederic Sowa int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
3867be12a1feSHannes Frederic Sowa 			 int offset, size_t size)
3868be12a1feSHannes Frederic Sowa {
3869be12a1feSHannes Frederic Sowa 	int i = skb_shinfo(skb)->nr_frags;
3870be12a1feSHannes Frederic Sowa 
3871be12a1feSHannes Frederic Sowa 	if (skb_can_coalesce(skb, i, page, offset)) {
3872be12a1feSHannes Frederic Sowa 		skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
3873be12a1feSHannes Frederic Sowa 	} else if (i < MAX_SKB_FRAGS) {
3874753f1ca4SPavel Begunkov 		skb_zcopy_downgrade_managed(skb);
3875be12a1feSHannes Frederic Sowa 		get_page(page);
3876be12a1feSHannes Frederic Sowa 		skb_fill_page_desc(skb, i, page, offset, size);
3877be12a1feSHannes Frederic Sowa 	} else {
3878be12a1feSHannes Frederic Sowa 		return -EMSGSIZE;
3879be12a1feSHannes Frederic Sowa 	}
3880be12a1feSHannes Frederic Sowa 
3881be12a1feSHannes Frederic Sowa 	return 0;
3882be12a1feSHannes Frederic Sowa }
3883be12a1feSHannes Frederic Sowa EXPORT_SYMBOL_GPL(skb_append_pagefrags);
3884be12a1feSHannes Frederic Sowa 
3885cbb042f9SHerbert Xu /**
3886cbb042f9SHerbert Xu  *	skb_pull_rcsum - pull skb and update receive checksum
3887cbb042f9SHerbert Xu  *	@skb: buffer to update
3888cbb042f9SHerbert Xu  *	@len: length of data pulled
3889cbb042f9SHerbert Xu  *
3890cbb042f9SHerbert Xu  *	This function performs an skb_pull on the packet and updates
3891fee54fa5SUrs Thuermann  *	the CHECKSUM_COMPLETE checksum.  It should be used on
389284fa7933SPatrick McHardy  *	receive path processing instead of skb_pull unless you know
389384fa7933SPatrick McHardy  *	that the checksum difference is zero (e.g., a valid IP header)
389484fa7933SPatrick McHardy  *	or you are setting ip_summed to CHECKSUM_NONE.
3895cbb042f9SHerbert Xu  */
3896af72868bSJohannes Berg void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
3897cbb042f9SHerbert Xu {
389831b33dfbSPravin B Shelar 	unsigned char *data = skb->data;
389931b33dfbSPravin B Shelar 
3900cbb042f9SHerbert Xu 	BUG_ON(len > skb->len);
390131b33dfbSPravin B Shelar 	__skb_pull(skb, len);
390231b33dfbSPravin B Shelar 	skb_postpull_rcsum(skb, data, len);
390331b33dfbSPravin B Shelar 	return skb->data;
3904cbb042f9SHerbert Xu }
3905f94691acSArnaldo Carvalho de Melo EXPORT_SYMBOL_GPL(skb_pull_rcsum);
3906f94691acSArnaldo Carvalho de Melo 
390713acc94eSYonghong Song static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
390813acc94eSYonghong Song {
390913acc94eSYonghong Song 	skb_frag_t head_frag;
391013acc94eSYonghong Song 	struct page *page;
391113acc94eSYonghong Song 
391213acc94eSYonghong Song 	page = virt_to_head_page(frag_skb->head);
3913d8e18a51SMatthew Wilcox (Oracle) 	__skb_frag_set_page(&head_frag, page);
3914b54c9d5bSJonathan Lemon 	skb_frag_off_set(&head_frag, frag_skb->data -
3915b54c9d5bSJonathan Lemon 			 (unsigned char *)page_address(page));
3916d8e18a51SMatthew Wilcox (Oracle) 	skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
391713acc94eSYonghong Song 	return head_frag;
391813acc94eSYonghong Song }
391913acc94eSYonghong Song 
39203a1296a3SSteffen Klassert struct sk_buff *skb_segment_list(struct sk_buff *skb,
39213a1296a3SSteffen Klassert 				 netdev_features_t features,
39223a1296a3SSteffen Klassert 				 unsigned int offset)
39233a1296a3SSteffen Klassert {
39243a1296a3SSteffen Klassert 	struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
39253a1296a3SSteffen Klassert 	unsigned int tnl_hlen = skb_tnl_header_len(skb);
39263a1296a3SSteffen Klassert 	unsigned int delta_truesize = 0;
39273a1296a3SSteffen Klassert 	unsigned int delta_len = 0;
39283a1296a3SSteffen Klassert 	struct sk_buff *tail = NULL;
392953475c5dSDongseok Yi 	struct sk_buff *nskb, *tmp;
3930cf3ab8d4SLina Wang 	int len_diff, err;
39313a1296a3SSteffen Klassert 
39323a1296a3SSteffen Klassert 	skb_push(skb, -skb_network_offset(skb) + offset);
39333a1296a3SSteffen Klassert 
39343a1296a3SSteffen Klassert 	skb_shinfo(skb)->frag_list = NULL;
39353a1296a3SSteffen Klassert 
39363a1296a3SSteffen Klassert 	do {
39373a1296a3SSteffen Klassert 		nskb = list_skb;
39383a1296a3SSteffen Klassert 		list_skb = list_skb->next;
39393a1296a3SSteffen Klassert 
394053475c5dSDongseok Yi 		err = 0;
3941224102deSlena wang 		delta_truesize += nskb->truesize;
394253475c5dSDongseok Yi 		if (skb_shared(nskb)) {
394353475c5dSDongseok Yi 			tmp = skb_clone(nskb, GFP_ATOMIC);
394453475c5dSDongseok Yi 			if (tmp) {
394553475c5dSDongseok Yi 				consume_skb(nskb);
394653475c5dSDongseok Yi 				nskb = tmp;
394753475c5dSDongseok Yi 				err = skb_unclone(nskb, GFP_ATOMIC);
394853475c5dSDongseok Yi 			} else {
394953475c5dSDongseok Yi 				err = -ENOMEM;
395053475c5dSDongseok Yi 			}
395153475c5dSDongseok Yi 		}
395253475c5dSDongseok Yi 
39533a1296a3SSteffen Klassert 		if (!tail)
39543a1296a3SSteffen Klassert 			skb->next = nskb;
39553a1296a3SSteffen Klassert 		else
39563a1296a3SSteffen Klassert 			tail->next = nskb;
39573a1296a3SSteffen Klassert 
395853475c5dSDongseok Yi 		if (unlikely(err)) {
395953475c5dSDongseok Yi 			nskb->next = list_skb;
396053475c5dSDongseok Yi 			goto err_linearize;
396153475c5dSDongseok Yi 		}
396253475c5dSDongseok Yi 
39633a1296a3SSteffen Klassert 		tail = nskb;
39643a1296a3SSteffen Klassert 
39653a1296a3SSteffen Klassert 		delta_len += nskb->len;
39663a1296a3SSteffen Klassert 
39673a1296a3SSteffen Klassert 		skb_push(nskb, -skb_network_offset(nskb) + offset);
39683a1296a3SSteffen Klassert 
3969cf673ed0SFlorian Westphal 		skb_release_head_state(nskb);
3970cf3ab8d4SLina Wang 		len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
39713a1296a3SSteffen Klassert 		__copy_skb_header(nskb, skb);
39723a1296a3SSteffen Klassert 
39733a1296a3SSteffen Klassert 		skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
3974cf3ab8d4SLina Wang 		nskb->transport_header += len_diff;
39753a1296a3SSteffen Klassert 		skb_copy_from_linear_data_offset(skb, -tnl_hlen,
39763a1296a3SSteffen Klassert 						 nskb->data - tnl_hlen,
39773a1296a3SSteffen Klassert 						 offset + tnl_hlen);
39783a1296a3SSteffen Klassert 
39793a1296a3SSteffen Klassert 		if (skb_needs_linearize(nskb, features) &&
39803a1296a3SSteffen Klassert 		    __skb_linearize(nskb))
39813a1296a3SSteffen Klassert 			goto err_linearize;
39823a1296a3SSteffen Klassert 
39833a1296a3SSteffen Klassert 	} while (list_skb);
39843a1296a3SSteffen Klassert 
39853a1296a3SSteffen Klassert 	skb->truesize = skb->truesize - delta_truesize;
39863a1296a3SSteffen Klassert 	skb->data_len = skb->data_len - delta_len;
39873a1296a3SSteffen Klassert 	skb->len = skb->len - delta_len;
39883a1296a3SSteffen Klassert 
39893a1296a3SSteffen Klassert 	skb_gso_reset(skb);
39903a1296a3SSteffen Klassert 
39913a1296a3SSteffen Klassert 	skb->prev = tail;
39923a1296a3SSteffen Klassert 
39933a1296a3SSteffen Klassert 	if (skb_needs_linearize(skb, features) &&
39943a1296a3SSteffen Klassert 	    __skb_linearize(skb))
39953a1296a3SSteffen Klassert 		goto err_linearize;
39963a1296a3SSteffen Klassert 
39973a1296a3SSteffen Klassert 	skb_get(skb);
39983a1296a3SSteffen Klassert 
39993a1296a3SSteffen Klassert 	return skb;
40003a1296a3SSteffen Klassert 
40013a1296a3SSteffen Klassert err_linearize:
40023a1296a3SSteffen Klassert 	kfree_skb_list(skb->next);
40033a1296a3SSteffen Klassert 	skb->next = NULL;
40043a1296a3SSteffen Klassert 	return ERR_PTR(-ENOMEM);
40053a1296a3SSteffen Klassert }
40063a1296a3SSteffen Klassert EXPORT_SYMBOL_GPL(skb_segment_list);
40073a1296a3SSteffen Klassert 
4008f4c50d99SHerbert Xu /**
4009f4c50d99SHerbert Xu  *	skb_segment - Perform protocol segmentation on skb.
4010df5771ffSMichael S. Tsirkin  *	@head_skb: buffer to segment
4011576a30ebSHerbert Xu  *	@features: features for the output path (see dev->features)
4012f4c50d99SHerbert Xu  *
4013f4c50d99SHerbert Xu  *	This function performs segmentation on the given skb.  It returns
40144c821d75SBen Hutchings  *	a pointer to the first in a list of new skbs for the segments.
40154c821d75SBen Hutchings  *	In case of error it returns ERR_PTR(err).
4016f4c50d99SHerbert Xu  */
4017df5771ffSMichael S. Tsirkin struct sk_buff *skb_segment(struct sk_buff *head_skb,
4018df5771ffSMichael S. Tsirkin 			    netdev_features_t features)
4019f4c50d99SHerbert Xu {
4020f4c50d99SHerbert Xu 	struct sk_buff *segs = NULL;
4021f4c50d99SHerbert Xu 	struct sk_buff *tail = NULL;
40221a4cedafSMichael S. Tsirkin 	struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4023df5771ffSMichael S. Tsirkin 	skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4024df5771ffSMichael S. Tsirkin 	unsigned int mss = skb_shinfo(head_skb)->gso_size;
4025df5771ffSMichael S. Tsirkin 	unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
40261fd819ecSMichael S. Tsirkin 	struct sk_buff *frag_skb = head_skb;
4027f4c50d99SHerbert Xu 	unsigned int offset = doffset;
4028df5771ffSMichael S. Tsirkin 	unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4029802ab55aSAlexander Duyck 	unsigned int partial_segs = 0;
4030f4c50d99SHerbert Xu 	unsigned int headroom;
4031802ab55aSAlexander Duyck 	unsigned int len = head_skb->len;
4032ec5f0615SPravin B Shelar 	__be16 proto;
403336c98382SAlexander Duyck 	bool csum, sg;
4034df5771ffSMichael S. Tsirkin 	int nfrags = skb_shinfo(head_skb)->nr_frags;
4035f4c50d99SHerbert Xu 	int err = -ENOMEM;
4036f4c50d99SHerbert Xu 	int i = 0;
4037f4c50d99SHerbert Xu 	int pos;
4038f4c50d99SHerbert Xu 
40393dcbdb13SShmulik Ladkani 	if (list_skb && !list_skb->head_frag && skb_headlen(list_skb) &&
40403dcbdb13SShmulik Ladkani 	    (skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY)) {
40413dcbdb13SShmulik Ladkani 		/* gso_size is untrusted, and we have a frag_list with a linear
40423dcbdb13SShmulik Ladkani 		 * non head_frag head.
40433dcbdb13SShmulik Ladkani 		 *
40443dcbdb13SShmulik Ladkani 		 * (we assume checking the first list_skb member suffices;
40453dcbdb13SShmulik Ladkani 		 * i.e if either of the list_skb members have non head_frag
40463dcbdb13SShmulik Ladkani 		 * head, then the first one has too).
40473dcbdb13SShmulik Ladkani 		 *
40483dcbdb13SShmulik Ladkani 		 * If head_skb's headlen does not fit requested gso_size, it
40493dcbdb13SShmulik Ladkani 		 * means that the frag_list members do NOT terminate on exact
40503dcbdb13SShmulik Ladkani 		 * gso_size boundaries. Hence we cannot perform skb_frag_t page
40513dcbdb13SShmulik Ladkani 		 * sharing. Therefore we must fallback to copying the frag_list
40523dcbdb13SShmulik Ladkani 		 * skbs; we do so by disabling SG.
40533dcbdb13SShmulik Ladkani 		 */
40543dcbdb13SShmulik Ladkani 		if (mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb))
40553dcbdb13SShmulik Ladkani 			features &= ~NETIF_F_SG;
40563dcbdb13SShmulik Ladkani 	}
40573dcbdb13SShmulik Ladkani 
40585882a07cSWei-Chun Chao 	__skb_push(head_skb, doffset);
40592f631133SMiaohe Lin 	proto = skb_network_protocol(head_skb, NULL);
4060ec5f0615SPravin B Shelar 	if (unlikely(!proto))
4061ec5f0615SPravin B Shelar 		return ERR_PTR(-EINVAL);
4062ec5f0615SPravin B Shelar 
406336c98382SAlexander Duyck 	sg = !!(features & NETIF_F_SG);
4064f245d079SAlexander Duyck 	csum = !!can_checksum_protocol(features, proto);
40657e2b10c1STom Herbert 
406607b26c94SSteffen Klassert 	if (sg && csum && (mss != GSO_BY_FRAGS))  {
406707b26c94SSteffen Klassert 		if (!(features & NETIF_F_GSO_PARTIAL)) {
406807b26c94SSteffen Klassert 			struct sk_buff *iter;
406943170c4eSIlan Tayari 			unsigned int frag_len;
407007b26c94SSteffen Klassert 
407107b26c94SSteffen Klassert 			if (!list_skb ||
407207b26c94SSteffen Klassert 			    !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
407307b26c94SSteffen Klassert 				goto normal;
407407b26c94SSteffen Klassert 
407543170c4eSIlan Tayari 			/* If we get here then all the required
407643170c4eSIlan Tayari 			 * GSO features except frag_list are supported.
407743170c4eSIlan Tayari 			 * Try to split the SKB to multiple GSO SKBs
407843170c4eSIlan Tayari 			 * with no frag_list.
407943170c4eSIlan Tayari 			 * Currently we can do that only when the buffers don't
408043170c4eSIlan Tayari 			 * have a linear part and all the buffers except
408143170c4eSIlan Tayari 			 * the last are of the same length.
408207b26c94SSteffen Klassert 			 */
408343170c4eSIlan Tayari 			frag_len = list_skb->len;
408407b26c94SSteffen Klassert 			skb_walk_frags(head_skb, iter) {
408543170c4eSIlan Tayari 				if (frag_len != iter->len && iter->next)
408643170c4eSIlan Tayari 					goto normal;
4087eaffadbbSIlan Tayari 				if (skb_headlen(iter) && !iter->head_frag)
408807b26c94SSteffen Klassert 					goto normal;
408907b26c94SSteffen Klassert 
409007b26c94SSteffen Klassert 				len -= iter->len;
409107b26c94SSteffen Klassert 			}
409243170c4eSIlan Tayari 
409343170c4eSIlan Tayari 			if (len != frag_len)
409443170c4eSIlan Tayari 				goto normal;
409507b26c94SSteffen Klassert 		}
409607b26c94SSteffen Klassert 
4097802ab55aSAlexander Duyck 		/* GSO partial only requires that we trim off any excess that
4098802ab55aSAlexander Duyck 		 * doesn't fit into an MSS sized block, so take care of that
4099802ab55aSAlexander Duyck 		 * now.
4100802ab55aSAlexander Duyck 		 */
4101802ab55aSAlexander Duyck 		partial_segs = len / mss;
4102d7fb5a80SAlexander Duyck 		if (partial_segs > 1)
4103802ab55aSAlexander Duyck 			mss *= partial_segs;
4104d7fb5a80SAlexander Duyck 		else
4105d7fb5a80SAlexander Duyck 			partial_segs = 0;
4106802ab55aSAlexander Duyck 	}
4107802ab55aSAlexander Duyck 
410807b26c94SSteffen Klassert normal:
4109df5771ffSMichael S. Tsirkin 	headroom = skb_headroom(head_skb);
4110df5771ffSMichael S. Tsirkin 	pos = skb_headlen(head_skb);
4111f4c50d99SHerbert Xu 
4112f4c50d99SHerbert Xu 	do {
4113f4c50d99SHerbert Xu 		struct sk_buff *nskb;
41148cb19905SMichael S. Tsirkin 		skb_frag_t *nskb_frag;
4115c8884eddSHerbert Xu 		int hsize;
4116f4c50d99SHerbert Xu 		int size;
4117f4c50d99SHerbert Xu 
41183953c46cSMarcelo Ricardo Leitner 		if (unlikely(mss == GSO_BY_FRAGS)) {
41193953c46cSMarcelo Ricardo Leitner 			len = list_skb->len;
41203953c46cSMarcelo Ricardo Leitner 		} else {
4121df5771ffSMichael S. Tsirkin 			len = head_skb->len - offset;
4122f4c50d99SHerbert Xu 			if (len > mss)
4123f4c50d99SHerbert Xu 				len = mss;
41243953c46cSMarcelo Ricardo Leitner 		}
4125f4c50d99SHerbert Xu 
4126df5771ffSMichael S. Tsirkin 		hsize = skb_headlen(head_skb) - offset;
4127f4c50d99SHerbert Xu 
4128dbd50f23SXin Long 		if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
41291a4cedafSMichael S. Tsirkin 		    (skb_headlen(list_skb) == len || sg)) {
41301a4cedafSMichael S. Tsirkin 			BUG_ON(skb_headlen(list_skb) > len);
413189319d38SHerbert Xu 
41329d8506ccSHerbert Xu 			i = 0;
41331a4cedafSMichael S. Tsirkin 			nfrags = skb_shinfo(list_skb)->nr_frags;
41341a4cedafSMichael S. Tsirkin 			frag = skb_shinfo(list_skb)->frags;
41351fd819ecSMichael S. Tsirkin 			frag_skb = list_skb;
41361a4cedafSMichael S. Tsirkin 			pos += skb_headlen(list_skb);
41379d8506ccSHerbert Xu 
41389d8506ccSHerbert Xu 			while (pos < offset + len) {
41399d8506ccSHerbert Xu 				BUG_ON(i >= nfrags);
41409d8506ccSHerbert Xu 
41414e1beba1SMichael S. Tsirkin 				size = skb_frag_size(frag);
41429d8506ccSHerbert Xu 				if (pos + size > offset + len)
41439d8506ccSHerbert Xu 					break;
41449d8506ccSHerbert Xu 
41459d8506ccSHerbert Xu 				i++;
41469d8506ccSHerbert Xu 				pos += size;
41474e1beba1SMichael S. Tsirkin 				frag++;
41489d8506ccSHerbert Xu 			}
41499d8506ccSHerbert Xu 
41501a4cedafSMichael S. Tsirkin 			nskb = skb_clone(list_skb, GFP_ATOMIC);
41511a4cedafSMichael S. Tsirkin 			list_skb = list_skb->next;
415289319d38SHerbert Xu 
4153f4c50d99SHerbert Xu 			if (unlikely(!nskb))
4154f4c50d99SHerbert Xu 				goto err;
4155f4c50d99SHerbert Xu 
41569d8506ccSHerbert Xu 			if (unlikely(pskb_trim(nskb, len))) {
41579d8506ccSHerbert Xu 				kfree_skb(nskb);
41589d8506ccSHerbert Xu 				goto err;
41599d8506ccSHerbert Xu 			}
41609d8506ccSHerbert Xu 
4161ec47ea82SAlexander Duyck 			hsize = skb_end_offset(nskb);
416289319d38SHerbert Xu 			if (skb_cow_head(nskb, doffset + headroom)) {
416389319d38SHerbert Xu 				kfree_skb(nskb);
416489319d38SHerbert Xu 				goto err;
416589319d38SHerbert Xu 			}
416689319d38SHerbert Xu 
4167ec47ea82SAlexander Duyck 			nskb->truesize += skb_end_offset(nskb) - hsize;
416889319d38SHerbert Xu 			skb_release_head_state(nskb);
416989319d38SHerbert Xu 			__skb_push(nskb, doffset);
417089319d38SHerbert Xu 		} else {
417100b229f7SPaolo Abeni 			if (hsize < 0)
417200b229f7SPaolo Abeni 				hsize = 0;
4173dbd50f23SXin Long 			if (hsize > len || !sg)
4174dbd50f23SXin Long 				hsize = len;
4175dbd50f23SXin Long 
4176c93bdd0eSMel Gorman 			nskb = __alloc_skb(hsize + doffset + headroom,
4177df5771ffSMichael S. Tsirkin 					   GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4178c93bdd0eSMel Gorman 					   NUMA_NO_NODE);
417989319d38SHerbert Xu 
418089319d38SHerbert Xu 			if (unlikely(!nskb))
418189319d38SHerbert Xu 				goto err;
418289319d38SHerbert Xu 
418389319d38SHerbert Xu 			skb_reserve(nskb, headroom);
418489319d38SHerbert Xu 			__skb_put(nskb, doffset);
418589319d38SHerbert Xu 		}
418689319d38SHerbert Xu 
4187f4c50d99SHerbert Xu 		if (segs)
4188f4c50d99SHerbert Xu 			tail->next = nskb;
4189f4c50d99SHerbert Xu 		else
4190f4c50d99SHerbert Xu 			segs = nskb;
4191f4c50d99SHerbert Xu 		tail = nskb;
4192f4c50d99SHerbert Xu 
4193df5771ffSMichael S. Tsirkin 		__copy_skb_header(nskb, head_skb);
4194f4c50d99SHerbert Xu 
4195030737bcSEric Dumazet 		skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4196fcdfe3a7SVlad Yasevich 		skb_reset_mac_len(nskb);
419768c33163SPravin B Shelar 
4198df5771ffSMichael S. Tsirkin 		skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
419968c33163SPravin B Shelar 						 nskb->data - tnl_hlen,
420068c33163SPravin B Shelar 						 doffset + tnl_hlen);
420189319d38SHerbert Xu 
42029d8506ccSHerbert Xu 		if (nskb->len == len + doffset)
42031cdbcb79SSimon Horman 			goto perform_csum_check;
420489319d38SHerbert Xu 
42057fbeffedSAlexander Duyck 		if (!sg) {
42061454c9faSYadu Kishore 			if (!csum) {
42077fbeffedSAlexander Duyck 				if (!nskb->remcsum_offload)
42086f85a124SHerbert Xu 					nskb->ip_summed = CHECKSUM_NONE;
420976443456SAlexander Duyck 				SKB_GSO_CB(nskb)->csum =
421076443456SAlexander Duyck 					skb_copy_and_csum_bits(head_skb, offset,
42111454c9faSYadu Kishore 							       skb_put(nskb,
42121454c9faSYadu Kishore 								       len),
42138d5930dfSAl Viro 							       len);
42147e2b10c1STom Herbert 				SKB_GSO_CB(nskb)->csum_start =
4215de843723STom Herbert 					skb_headroom(nskb) + doffset;
42161454c9faSYadu Kishore 			} else {
4217c624c58eSlily 				if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4218c624c58eSlily 					goto err;
42191454c9faSYadu Kishore 			}
4220f4c50d99SHerbert Xu 			continue;
4221f4c50d99SHerbert Xu 		}
4222f4c50d99SHerbert Xu 
42238cb19905SMichael S. Tsirkin 		nskb_frag = skb_shinfo(nskb)->frags;
4224f4c50d99SHerbert Xu 
4225df5771ffSMichael S. Tsirkin 		skb_copy_from_linear_data_offset(head_skb, offset,
4226d626f62bSArnaldo Carvalho de Melo 						 skb_put(nskb, hsize), hsize);
4227f4c50d99SHerbert Xu 
422806b4feb3SJonathan Lemon 		skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
422906b4feb3SJonathan Lemon 					   SKBFL_SHARED_FRAG;
4230cef401deSEric Dumazet 
4231bf5c25d6SWillem de Bruijn 		if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4232bf5c25d6SWillem de Bruijn 		    skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4233bf5c25d6SWillem de Bruijn 			goto err;
4234bf5c25d6SWillem de Bruijn 
42359d8506ccSHerbert Xu 		while (pos < offset + len) {
42369d8506ccSHerbert Xu 			if (i >= nfrags) {
42379d8506ccSHerbert Xu 				i = 0;
42381a4cedafSMichael S. Tsirkin 				nfrags = skb_shinfo(list_skb)->nr_frags;
42391a4cedafSMichael S. Tsirkin 				frag = skb_shinfo(list_skb)->frags;
42401fd819ecSMichael S. Tsirkin 				frag_skb = list_skb;
424113acc94eSYonghong Song 				if (!skb_headlen(list_skb)) {
42429d8506ccSHerbert Xu 					BUG_ON(!nfrags);
424313acc94eSYonghong Song 				} else {
424413acc94eSYonghong Song 					BUG_ON(!list_skb->head_frag);
42459d8506ccSHerbert Xu 
424613acc94eSYonghong Song 					/* to make room for head_frag. */
424713acc94eSYonghong Song 					i--;
424813acc94eSYonghong Song 					frag--;
424913acc94eSYonghong Song 				}
4250bf5c25d6SWillem de Bruijn 				if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4251bf5c25d6SWillem de Bruijn 				    skb_zerocopy_clone(nskb, frag_skb,
4252bf5c25d6SWillem de Bruijn 						       GFP_ATOMIC))
4253bf5c25d6SWillem de Bruijn 					goto err;
4254bf5c25d6SWillem de Bruijn 
42551a4cedafSMichael S. Tsirkin 				list_skb = list_skb->next;
42569d8506ccSHerbert Xu 			}
42579d8506ccSHerbert Xu 
42589d8506ccSHerbert Xu 			if (unlikely(skb_shinfo(nskb)->nr_frags >=
42599d8506ccSHerbert Xu 				     MAX_SKB_FRAGS)) {
42609d8506ccSHerbert Xu 				net_warn_ratelimited(
42619d8506ccSHerbert Xu 					"skb_segment: too many frags: %u %u\n",
42629d8506ccSHerbert Xu 					pos, mss);
4263ff907a11SEric Dumazet 				err = -EINVAL;
42649d8506ccSHerbert Xu 				goto err;
42659d8506ccSHerbert Xu 			}
42669d8506ccSHerbert Xu 
426713acc94eSYonghong Song 			*nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
42688cb19905SMichael S. Tsirkin 			__skb_frag_ref(nskb_frag);
42698cb19905SMichael S. Tsirkin 			size = skb_frag_size(nskb_frag);
4270f4c50d99SHerbert Xu 
4271f4c50d99SHerbert Xu 			if (pos < offset) {
4272b54c9d5bSJonathan Lemon 				skb_frag_off_add(nskb_frag, offset - pos);
42738cb19905SMichael S. Tsirkin 				skb_frag_size_sub(nskb_frag, offset - pos);
4274f4c50d99SHerbert Xu 			}
4275f4c50d99SHerbert Xu 
427689319d38SHerbert Xu 			skb_shinfo(nskb)->nr_frags++;
4277f4c50d99SHerbert Xu 
4278f4c50d99SHerbert Xu 			if (pos + size <= offset + len) {
4279f4c50d99SHerbert Xu 				i++;
42804e1beba1SMichael S. Tsirkin 				frag++;
4281f4c50d99SHerbert Xu 				pos += size;
4282f4c50d99SHerbert Xu 			} else {
42838cb19905SMichael S. Tsirkin 				skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
428489319d38SHerbert Xu 				goto skip_fraglist;
4285f4c50d99SHerbert Xu 			}
4286f4c50d99SHerbert Xu 
42878cb19905SMichael S. Tsirkin 			nskb_frag++;
4288f4c50d99SHerbert Xu 		}
4289f4c50d99SHerbert Xu 
429089319d38SHerbert Xu skip_fraglist:
4291f4c50d99SHerbert Xu 		nskb->data_len = len - hsize;
4292f4c50d99SHerbert Xu 		nskb->len += nskb->data_len;
4293f4c50d99SHerbert Xu 		nskb->truesize += nskb->data_len;
4294ec5f0615SPravin B Shelar 
42951cdbcb79SSimon Horman perform_csum_check:
42967fbeffedSAlexander Duyck 		if (!csum) {
4297ff907a11SEric Dumazet 			if (skb_has_shared_frag(nskb) &&
4298ff907a11SEric Dumazet 			    __skb_linearize(nskb))
4299ddff00d4SAlexander Duyck 				goto err;
4300ff907a11SEric Dumazet 
43017fbeffedSAlexander Duyck 			if (!nskb->remcsum_offload)
4302ec5f0615SPravin B Shelar 				nskb->ip_summed = CHECKSUM_NONE;
430376443456SAlexander Duyck 			SKB_GSO_CB(nskb)->csum =
430476443456SAlexander Duyck 				skb_checksum(nskb, doffset,
430576443456SAlexander Duyck 					     nskb->len - doffset, 0);
43067e2b10c1STom Herbert 			SKB_GSO_CB(nskb)->csum_start =
43077e2b10c1STom Herbert 				skb_headroom(nskb) + doffset;
4308ec5f0615SPravin B Shelar 		}
4309df5771ffSMichael S. Tsirkin 	} while ((offset += len) < head_skb->len);
4310f4c50d99SHerbert Xu 
4311bec3cfdcSEric Dumazet 	/* Some callers want to get the end of the list.
4312bec3cfdcSEric Dumazet 	 * Put it in segs->prev to avoid walking the list.
4313bec3cfdcSEric Dumazet 	 * (see validate_xmit_skb_list() for example)
4314bec3cfdcSEric Dumazet 	 */
4315bec3cfdcSEric Dumazet 	segs->prev = tail;
4316432c856fSToshiaki Makita 
4317802ab55aSAlexander Duyck 	if (partial_segs) {
431807b26c94SSteffen Klassert 		struct sk_buff *iter;
4319802ab55aSAlexander Duyck 		int type = skb_shinfo(head_skb)->gso_type;
432007b26c94SSteffen Klassert 		unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4321802ab55aSAlexander Duyck 
4322802ab55aSAlexander Duyck 		/* Update type to add partial and then remove dodgy if set */
432307b26c94SSteffen Klassert 		type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4324802ab55aSAlexander Duyck 		type &= ~SKB_GSO_DODGY;
4325802ab55aSAlexander Duyck 
4326802ab55aSAlexander Duyck 		/* Update GSO info and prepare to start updating headers on
4327802ab55aSAlexander Duyck 		 * our way back down the stack of protocols.
4328802ab55aSAlexander Duyck 		 */
432907b26c94SSteffen Klassert 		for (iter = segs; iter; iter = iter->next) {
433007b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_size = gso_size;
433107b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_segs = partial_segs;
433207b26c94SSteffen Klassert 			skb_shinfo(iter)->gso_type = type;
433307b26c94SSteffen Klassert 			SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
433407b26c94SSteffen Klassert 		}
433507b26c94SSteffen Klassert 
433607b26c94SSteffen Klassert 		if (tail->len - doffset <= gso_size)
433707b26c94SSteffen Klassert 			skb_shinfo(tail)->gso_size = 0;
433807b26c94SSteffen Klassert 		else if (tail != segs)
433907b26c94SSteffen Klassert 			skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4340802ab55aSAlexander Duyck 	}
4341802ab55aSAlexander Duyck 
4342432c856fSToshiaki Makita 	/* Following permits correct backpressure, for protocols
4343432c856fSToshiaki Makita 	 * using skb_set_owner_w().
4344432c856fSToshiaki Makita 	 * Idea is to tranfert ownership from head_skb to last segment.
4345432c856fSToshiaki Makita 	 */
4346432c856fSToshiaki Makita 	if (head_skb->destructor == sock_wfree) {
4347432c856fSToshiaki Makita 		swap(tail->truesize, head_skb->truesize);
4348432c856fSToshiaki Makita 		swap(tail->destructor, head_skb->destructor);
4349432c856fSToshiaki Makita 		swap(tail->sk, head_skb->sk);
4350432c856fSToshiaki Makita 	}
4351f4c50d99SHerbert Xu 	return segs;
4352f4c50d99SHerbert Xu 
4353f4c50d99SHerbert Xu err:
4354289dccbeSEric Dumazet 	kfree_skb_list(segs);
4355f4c50d99SHerbert Xu 	return ERR_PTR(err);
4356f4c50d99SHerbert Xu }
4357f4c50d99SHerbert Xu EXPORT_SYMBOL_GPL(skb_segment);
4358f4c50d99SHerbert Xu 
4359df5042f4SFlorian Westphal #ifdef CONFIG_SKB_EXTENSIONS
4360df5042f4SFlorian Westphal #define SKB_EXT_ALIGN_VALUE	8
4361df5042f4SFlorian Westphal #define SKB_EXT_CHUNKSIZEOF(x)	(ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4362df5042f4SFlorian Westphal 
4363df5042f4SFlorian Westphal static const u8 skb_ext_type_len[] = {
4364df5042f4SFlorian Westphal #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4365df5042f4SFlorian Westphal 	[SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4366df5042f4SFlorian Westphal #endif
43674165079bSFlorian Westphal #ifdef CONFIG_XFRM
43684165079bSFlorian Westphal 	[SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
43694165079bSFlorian Westphal #endif
437095a7233cSPaul Blakey #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
437195a7233cSPaul Blakey 	[TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
437295a7233cSPaul Blakey #endif
43733ee17bc7SMat Martineau #if IS_ENABLED(CONFIG_MPTCP)
43743ee17bc7SMat Martineau 	[SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
43753ee17bc7SMat Martineau #endif
437678476d31SJeremy Kerr #if IS_ENABLED(CONFIG_MCTP_FLOWS)
437778476d31SJeremy Kerr 	[SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
437878476d31SJeremy Kerr #endif
4379df5042f4SFlorian Westphal };
4380df5042f4SFlorian Westphal 
4381df5042f4SFlorian Westphal static __always_inline unsigned int skb_ext_total_length(void)
4382df5042f4SFlorian Westphal {
4383df5042f4SFlorian Westphal 	return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4384df5042f4SFlorian Westphal #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4385df5042f4SFlorian Westphal 		skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4386df5042f4SFlorian Westphal #endif
43874165079bSFlorian Westphal #ifdef CONFIG_XFRM
43884165079bSFlorian Westphal 		skb_ext_type_len[SKB_EXT_SEC_PATH] +
43894165079bSFlorian Westphal #endif
439095a7233cSPaul Blakey #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
439195a7233cSPaul Blakey 		skb_ext_type_len[TC_SKB_EXT] +
439295a7233cSPaul Blakey #endif
43933ee17bc7SMat Martineau #if IS_ENABLED(CONFIG_MPTCP)
43943ee17bc7SMat Martineau 		skb_ext_type_len[SKB_EXT_MPTCP] +
43953ee17bc7SMat Martineau #endif
439678476d31SJeremy Kerr #if IS_ENABLED(CONFIG_MCTP_FLOWS)
439778476d31SJeremy Kerr 		skb_ext_type_len[SKB_EXT_MCTP] +
439878476d31SJeremy Kerr #endif
4399df5042f4SFlorian Westphal 		0;
4400df5042f4SFlorian Westphal }
4401df5042f4SFlorian Westphal 
4402df5042f4SFlorian Westphal static void skb_extensions_init(void)
4403df5042f4SFlorian Westphal {
4404df5042f4SFlorian Westphal 	BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4405df5042f4SFlorian Westphal 	BUILD_BUG_ON(skb_ext_total_length() > 255);
4406df5042f4SFlorian Westphal 
4407df5042f4SFlorian Westphal 	skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4408df5042f4SFlorian Westphal 					     SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4409df5042f4SFlorian Westphal 					     0,
4410df5042f4SFlorian Westphal 					     SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4411df5042f4SFlorian Westphal 					     NULL);
4412df5042f4SFlorian Westphal }
4413df5042f4SFlorian Westphal #else
4414df5042f4SFlorian Westphal static void skb_extensions_init(void) {}
4415df5042f4SFlorian Westphal #endif
4416df5042f4SFlorian Westphal 
44171da177e4SLinus Torvalds void __init skb_init(void)
44181da177e4SLinus Torvalds {
441979a8a642SKees Cook 	skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
44201da177e4SLinus Torvalds 					      sizeof(struct sk_buff),
44211da177e4SLinus Torvalds 					      0,
4422e5d679f3SAlexey Dobriyan 					      SLAB_HWCACHE_ALIGN|SLAB_PANIC,
442379a8a642SKees Cook 					      offsetof(struct sk_buff, cb),
442479a8a642SKees Cook 					      sizeof_field(struct sk_buff, cb),
442520c2df83SPaul Mundt 					      NULL);
4426d179cd12SDavid S. Miller 	skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4427d0bf4a9eSEric Dumazet 						sizeof(struct sk_buff_fclones),
4428d179cd12SDavid S. Miller 						0,
4429e5d679f3SAlexey Dobriyan 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
443020c2df83SPaul Mundt 						NULL);
4431df5042f4SFlorian Westphal 	skb_extensions_init();
44321da177e4SLinus Torvalds }
44331da177e4SLinus Torvalds 
443451c739d1SDavid S. Miller static int
443548a1df65SJason A. Donenfeld __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
443648a1df65SJason A. Donenfeld 	       unsigned int recursion_level)
4437716ea3a7SDavid Howells {
44381a028e50SDavid S. Miller 	int start = skb_headlen(skb);
44391a028e50SDavid S. Miller 	int i, copy = start - offset;
4440fbb398a8SDavid S. Miller 	struct sk_buff *frag_iter;
4441716ea3a7SDavid Howells 	int elt = 0;
4442716ea3a7SDavid Howells 
444348a1df65SJason A. Donenfeld 	if (unlikely(recursion_level >= 24))
444448a1df65SJason A. Donenfeld 		return -EMSGSIZE;
444548a1df65SJason A. Donenfeld 
4446716ea3a7SDavid Howells 	if (copy > 0) {
4447716ea3a7SDavid Howells 		if (copy > len)
4448716ea3a7SDavid Howells 			copy = len;
4449642f1490SJens Axboe 		sg_set_buf(sg, skb->data + offset, copy);
4450716ea3a7SDavid Howells 		elt++;
4451716ea3a7SDavid Howells 		if ((len -= copy) == 0)
4452716ea3a7SDavid Howells 			return elt;
4453716ea3a7SDavid Howells 		offset += copy;
4454716ea3a7SDavid Howells 	}
4455716ea3a7SDavid Howells 
4456716ea3a7SDavid Howells 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
44571a028e50SDavid S. Miller 		int end;
4458716ea3a7SDavid Howells 
4459547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
44601a028e50SDavid S. Miller 
44619e903e08SEric Dumazet 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4462716ea3a7SDavid Howells 		if ((copy = end - offset) > 0) {
4463716ea3a7SDavid Howells 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
446448a1df65SJason A. Donenfeld 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
446548a1df65SJason A. Donenfeld 				return -EMSGSIZE;
4466716ea3a7SDavid Howells 
4467716ea3a7SDavid Howells 			if (copy > len)
4468716ea3a7SDavid Howells 				copy = len;
4469ea2ab693SIan Campbell 			sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4470b54c9d5bSJonathan Lemon 				    skb_frag_off(frag) + offset - start);
4471716ea3a7SDavid Howells 			elt++;
4472716ea3a7SDavid Howells 			if (!(len -= copy))
4473716ea3a7SDavid Howells 				return elt;
4474716ea3a7SDavid Howells 			offset += copy;
4475716ea3a7SDavid Howells 		}
44761a028e50SDavid S. Miller 		start = end;
4477716ea3a7SDavid Howells 	}
4478716ea3a7SDavid Howells 
4479fbb398a8SDavid S. Miller 	skb_walk_frags(skb, frag_iter) {
448048a1df65SJason A. Donenfeld 		int end, ret;
4481716ea3a7SDavid Howells 
4482547b792cSIlpo Järvinen 		WARN_ON(start > offset + len);
44831a028e50SDavid S. Miller 
4484fbb398a8SDavid S. Miller 		end = start + frag_iter->len;
4485716ea3a7SDavid Howells 		if ((copy = end - offset) > 0) {
448648a1df65SJason A. Donenfeld 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
448748a1df65SJason A. Donenfeld 				return -EMSGSIZE;
448848a1df65SJason A. Donenfeld 
4489716ea3a7SDavid Howells 			if (copy > len)
4490716ea3a7SDavid Howells 				copy = len;
449148a1df65SJason A. Donenfeld 			ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
449248a1df65SJason A. Donenfeld 					      copy, recursion_level + 1);
449348a1df65SJason A. Donenfeld 			if (unlikely(ret < 0))
449448a1df65SJason A. Donenfeld 				return ret;
449548a1df65SJason A. Donenfeld 			elt += ret;
4496716ea3a7SDavid Howells 			if ((len -= copy) == 0)
4497716ea3a7SDavid Howells 				return elt;
4498716ea3a7SDavid Howells 			offset += copy;
4499716ea3a7SDavid Howells 		}
45001a028e50SDavid S. Miller 		start = end;
4501716ea3a7SDavid Howells 	}
4502716ea3a7SDavid Howells 	BUG_ON(len);
4503716ea3a7SDavid Howells 	return elt;
4504716ea3a7SDavid Howells }
4505716ea3a7SDavid Howells 
450648a1df65SJason A. Donenfeld /**
450748a1df65SJason A. Donenfeld  *	skb_to_sgvec - Fill a scatter-gather list from a socket buffer
450848a1df65SJason A. Donenfeld  *	@skb: Socket buffer containing the buffers to be mapped
450948a1df65SJason A. Donenfeld  *	@sg: The scatter-gather list to map into
451048a1df65SJason A. Donenfeld  *	@offset: The offset into the buffer's contents to start mapping
451148a1df65SJason A. Donenfeld  *	@len: Length of buffer space to be mapped
451248a1df65SJason A. Donenfeld  *
451348a1df65SJason A. Donenfeld  *	Fill the specified scatter-gather list with mappings/pointers into a
451448a1df65SJason A. Donenfeld  *	region of the buffer space attached to a socket buffer. Returns either
451548a1df65SJason A. Donenfeld  *	the number of scatterlist items used, or -EMSGSIZE if the contents
451648a1df65SJason A. Donenfeld  *	could not fit.
451748a1df65SJason A. Donenfeld  */
451848a1df65SJason A. Donenfeld int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
451948a1df65SJason A. Donenfeld {
452048a1df65SJason A. Donenfeld 	int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
452148a1df65SJason A. Donenfeld 
452248a1df65SJason A. Donenfeld 	if (nsg <= 0)
452348a1df65SJason A. Donenfeld 		return nsg;
452448a1df65SJason A. Donenfeld 
452548a1df65SJason A. Donenfeld 	sg_mark_end(&sg[nsg - 1]);
452648a1df65SJason A. Donenfeld 
452748a1df65SJason A. Donenfeld 	return nsg;
452848a1df65SJason A. Donenfeld }
452948a1df65SJason A. Donenfeld EXPORT_SYMBOL_GPL(skb_to_sgvec);
453048a1df65SJason A. Donenfeld 
453125a91d8dSFan Du /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
453225a91d8dSFan Du  * sglist without mark the sg which contain last skb data as the end.
453325a91d8dSFan Du  * So the caller can mannipulate sg list as will when padding new data after
453425a91d8dSFan Du  * the first call without calling sg_unmark_end to expend sg list.
453525a91d8dSFan Du  *
453625a91d8dSFan Du  * Scenario to use skb_to_sgvec_nomark:
453725a91d8dSFan Du  * 1. sg_init_table
453825a91d8dSFan Du  * 2. skb_to_sgvec_nomark(payload1)
453925a91d8dSFan Du  * 3. skb_to_sgvec_nomark(payload2)
454025a91d8dSFan Du  *
454125a91d8dSFan Du  * This is equivalent to:
454225a91d8dSFan Du  * 1. sg_init_table
454325a91d8dSFan Du  * 2. skb_to_sgvec(payload1)
454425a91d8dSFan Du  * 3. sg_unmark_end
454525a91d8dSFan Du  * 4. skb_to_sgvec(payload2)
454625a91d8dSFan Du  *
454725a91d8dSFan Du  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
454825a91d8dSFan Du  * is more preferable.
454925a91d8dSFan Du  */
455025a91d8dSFan Du int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
455125a91d8dSFan Du 			int offset, int len)
455225a91d8dSFan Du {
455348a1df65SJason A. Donenfeld 	return __skb_to_sgvec(skb, sg, offset, len, 0);
455425a91d8dSFan Du }
455525a91d8dSFan Du EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
455625a91d8dSFan Du 
455751c739d1SDavid S. Miller 
455851c739d1SDavid S. Miller 
4559716ea3a7SDavid Howells /**
4560716ea3a7SDavid Howells  *	skb_cow_data - Check that a socket buffer's data buffers are writable
4561716ea3a7SDavid Howells  *	@skb: The socket buffer to check.
4562716ea3a7SDavid Howells  *	@tailbits: Amount of trailing space to be added
4563716ea3a7SDavid Howells  *	@trailer: Returned pointer to the skb where the @tailbits space begins
4564716ea3a7SDavid Howells  *
4565716ea3a7SDavid Howells  *	Make sure that the data buffers attached to a socket buffer are
4566716ea3a7SDavid Howells  *	writable. If they are not, private copies are made of the data buffers
4567716ea3a7SDavid Howells  *	and the socket buffer is set to use these instead.
4568716ea3a7SDavid Howells  *
4569716ea3a7SDavid Howells  *	If @tailbits is given, make sure that there is space to write @tailbits
4570716ea3a7SDavid Howells  *	bytes of data beyond current end of socket buffer.  @trailer will be
4571716ea3a7SDavid Howells  *	set to point to the skb in which this space begins.
4572716ea3a7SDavid Howells  *
4573716ea3a7SDavid Howells  *	The number of scatterlist elements required to completely map the
4574716ea3a7SDavid Howells  *	COW'd and extended socket buffer will be returned.
4575716ea3a7SDavid Howells  */
4576716ea3a7SDavid Howells int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4577716ea3a7SDavid Howells {
4578716ea3a7SDavid Howells 	int copyflag;
4579716ea3a7SDavid Howells 	int elt;
4580716ea3a7SDavid Howells 	struct sk_buff *skb1, **skb_p;
4581716ea3a7SDavid Howells 
4582716ea3a7SDavid Howells 	/* If skb is cloned or its head is paged, reallocate
4583716ea3a7SDavid Howells 	 * head pulling out all the pages (pages are considered not writable
4584716ea3a7SDavid Howells 	 * at the moment even if they are anonymous).
4585716ea3a7SDavid Howells 	 */
4586716ea3a7SDavid Howells 	if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4587c15fc199SMiaohe Lin 	    !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4588716ea3a7SDavid Howells 		return -ENOMEM;
4589716ea3a7SDavid Howells 
4590716ea3a7SDavid Howells 	/* Easy case. Most of packets will go this way. */
459121dc3301SDavid S. Miller 	if (!skb_has_frag_list(skb)) {
4592716ea3a7SDavid Howells 		/* A little of trouble, not enough of space for trailer.
4593716ea3a7SDavid Howells 		 * This should not happen, when stack is tuned to generate
4594716ea3a7SDavid Howells 		 * good frames. OK, on miss we reallocate and reserve even more
4595716ea3a7SDavid Howells 		 * space, 128 bytes is fair. */
4596716ea3a7SDavid Howells 
4597716ea3a7SDavid Howells 		if (skb_tailroom(skb) < tailbits &&
4598716ea3a7SDavid Howells 		    pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4599716ea3a7SDavid Howells 			return -ENOMEM;
4600716ea3a7SDavid Howells 
4601716ea3a7SDavid Howells 		/* Voila! */
4602716ea3a7SDavid Howells 		*trailer = skb;
4603716ea3a7SDavid Howells 		return 1;
4604716ea3a7SDavid Howells 	}
4605716ea3a7SDavid Howells 
4606716ea3a7SDavid Howells 	/* Misery. We are in troubles, going to mincer fragments... */
4607716ea3a7SDavid Howells 
4608716ea3a7SDavid Howells 	elt = 1;
4609716ea3a7SDavid Howells 	skb_p = &skb_shinfo(skb)->frag_list;
4610716ea3a7SDavid Howells 	copyflag = 0;
4611716ea3a7SDavid Howells 
4612716ea3a7SDavid Howells 	while ((skb1 = *skb_p) != NULL) {
4613716ea3a7SDavid Howells 		int ntail = 0;
4614716ea3a7SDavid Howells 
4615716ea3a7SDavid Howells 		/* The fragment is partially pulled by someone,
4616716ea3a7SDavid Howells 		 * this can happen on input. Copy it and everything
4617716ea3a7SDavid Howells 		 * after it. */
4618716ea3a7SDavid Howells 
4619716ea3a7SDavid Howells 		if (skb_shared(skb1))
4620716ea3a7SDavid Howells 			copyflag = 1;
4621716ea3a7SDavid Howells 
4622716ea3a7SDavid Howells 		/* If the skb is the last, worry about trailer. */
4623716ea3a7SDavid Howells 
4624716ea3a7SDavid Howells 		if (skb1->next == NULL && tailbits) {
4625716ea3a7SDavid Howells 			if (skb_shinfo(skb1)->nr_frags ||
462621dc3301SDavid S. Miller 			    skb_has_frag_list(skb1) ||
4627716ea3a7SDavid Howells 			    skb_tailroom(skb1) < tailbits)
4628716ea3a7SDavid Howells 				ntail = tailbits + 128;
4629716ea3a7SDavid Howells 		}
4630716ea3a7SDavid Howells 
4631716ea3a7SDavid Howells 		if (copyflag ||
4632716ea3a7SDavid Howells 		    skb_cloned(skb1) ||
4633716ea3a7SDavid Howells 		    ntail ||
4634716ea3a7SDavid Howells 		    skb_shinfo(skb1)->nr_frags ||
463521dc3301SDavid S. Miller 		    skb_has_frag_list(skb1)) {
4636716ea3a7SDavid Howells 			struct sk_buff *skb2;
4637716ea3a7SDavid Howells 
4638716ea3a7SDavid Howells 			/* Fuck, we are miserable poor guys... */
4639716ea3a7SDavid Howells 			if (ntail == 0)
4640716ea3a7SDavid Howells 				skb2 = skb_copy(skb1, GFP_ATOMIC);
4641716ea3a7SDavid Howells 			else
4642716ea3a7SDavid Howells 				skb2 = skb_copy_expand(skb1,
4643716ea3a7SDavid Howells 						       skb_headroom(skb1),
4644716ea3a7SDavid Howells 						       ntail,
4645716ea3a7SDavid Howells 						       GFP_ATOMIC);
4646716ea3a7SDavid Howells 			if (unlikely(skb2 == NULL))
4647716ea3a7SDavid Howells 				return -ENOMEM;
4648716ea3a7SDavid Howells 
4649716ea3a7SDavid Howells 			if (skb1->sk)
4650716ea3a7SDavid Howells 				skb_set_owner_w(skb2, skb1->sk);
4651716ea3a7SDavid Howells 
4652716ea3a7SDavid Howells 			/* Looking around. Are we still alive?
4653716ea3a7SDavid Howells 			 * OK, link new skb, drop old one */
4654716ea3a7SDavid Howells 
4655716ea3a7SDavid Howells 			skb2->next = skb1->next;
4656716ea3a7SDavid Howells 			*skb_p = skb2;
4657716ea3a7SDavid Howells 			kfree_skb(skb1);
4658716ea3a7SDavid Howells 			skb1 = skb2;
4659716ea3a7SDavid Howells 		}
4660716ea3a7SDavid Howells 		elt++;
4661716ea3a7SDavid Howells 		*trailer = skb1;
4662716ea3a7SDavid Howells 		skb_p = &skb1->next;
4663716ea3a7SDavid Howells 	}
4664716ea3a7SDavid Howells 
4665716ea3a7SDavid Howells 	return elt;
4666716ea3a7SDavid Howells }
4667b4ac530fSDavid S. Miller EXPORT_SYMBOL_GPL(skb_cow_data);
4668716ea3a7SDavid Howells 
4669b1faf566SEric Dumazet static void sock_rmem_free(struct sk_buff *skb)
4670b1faf566SEric Dumazet {
4671b1faf566SEric Dumazet 	struct sock *sk = skb->sk;
4672b1faf566SEric Dumazet 
4673b1faf566SEric Dumazet 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4674b1faf566SEric Dumazet }
4675b1faf566SEric Dumazet 
46768605330aSSoheil Hassas Yeganeh static void skb_set_err_queue(struct sk_buff *skb)
46778605330aSSoheil Hassas Yeganeh {
46788605330aSSoheil Hassas Yeganeh 	/* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
46798605330aSSoheil Hassas Yeganeh 	 * So, it is safe to (mis)use it to mark skbs on the error queue.
46808605330aSSoheil Hassas Yeganeh 	 */
46818605330aSSoheil Hassas Yeganeh 	skb->pkt_type = PACKET_OUTGOING;
46828605330aSSoheil Hassas Yeganeh 	BUILD_BUG_ON(PACKET_OUTGOING == 0);
46838605330aSSoheil Hassas Yeganeh }
46848605330aSSoheil Hassas Yeganeh 
4685b1faf566SEric Dumazet /*
4686b1faf566SEric Dumazet  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4687b1faf566SEric Dumazet  */
4688b1faf566SEric Dumazet int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4689b1faf566SEric Dumazet {
4690b1faf566SEric Dumazet 	if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4691ebb3b78dSEric Dumazet 	    (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4692b1faf566SEric Dumazet 		return -ENOMEM;
4693b1faf566SEric Dumazet 
4694b1faf566SEric Dumazet 	skb_orphan(skb);
4695b1faf566SEric Dumazet 	skb->sk = sk;
4696b1faf566SEric Dumazet 	skb->destructor = sock_rmem_free;
4697b1faf566SEric Dumazet 	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
46988605330aSSoheil Hassas Yeganeh 	skb_set_err_queue(skb);
4699b1faf566SEric Dumazet 
4700abb57ea4SEric Dumazet 	/* before exiting rcu section, make sure dst is refcounted */
4701abb57ea4SEric Dumazet 	skb_dst_force(skb);
4702abb57ea4SEric Dumazet 
4703b1faf566SEric Dumazet 	skb_queue_tail(&sk->sk_error_queue, skb);
4704b1faf566SEric Dumazet 	if (!sock_flag(sk, SOCK_DEAD))
4705e3ae2365SAlexander Aring 		sk_error_report(sk);
4706b1faf566SEric Dumazet 	return 0;
4707b1faf566SEric Dumazet }
4708b1faf566SEric Dumazet EXPORT_SYMBOL(sock_queue_err_skb);
4709b1faf566SEric Dumazet 
471083a1a1a7SSoheil Hassas Yeganeh static bool is_icmp_err_skb(const struct sk_buff *skb)
471183a1a1a7SSoheil Hassas Yeganeh {
471283a1a1a7SSoheil Hassas Yeganeh 	return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
471383a1a1a7SSoheil Hassas Yeganeh 		       SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
471483a1a1a7SSoheil Hassas Yeganeh }
471583a1a1a7SSoheil Hassas Yeganeh 
4716364a9e93SWillem de Bruijn struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4717364a9e93SWillem de Bruijn {
4718364a9e93SWillem de Bruijn 	struct sk_buff_head *q = &sk->sk_error_queue;
471983a1a1a7SSoheil Hassas Yeganeh 	struct sk_buff *skb, *skb_next = NULL;
472083a1a1a7SSoheil Hassas Yeganeh 	bool icmp_next = false;
4721997d5c3fSEric Dumazet 	unsigned long flags;
4722364a9e93SWillem de Bruijn 
4723997d5c3fSEric Dumazet 	spin_lock_irqsave(&q->lock, flags);
4724364a9e93SWillem de Bruijn 	skb = __skb_dequeue(q);
472538b25793SSoheil Hassas Yeganeh 	if (skb && (skb_next = skb_peek(q))) {
472683a1a1a7SSoheil Hassas Yeganeh 		icmp_next = is_icmp_err_skb(skb_next);
472738b25793SSoheil Hassas Yeganeh 		if (icmp_next)
4728985f7337SWillem de Bruijn 			sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
472938b25793SSoheil Hassas Yeganeh 	}
4730997d5c3fSEric Dumazet 	spin_unlock_irqrestore(&q->lock, flags);
4731364a9e93SWillem de Bruijn 
473283a1a1a7SSoheil Hassas Yeganeh 	if (is_icmp_err_skb(skb) && !icmp_next)
473383a1a1a7SSoheil Hassas Yeganeh 		sk->sk_err = 0;
473483a1a1a7SSoheil Hassas Yeganeh 
473583a1a1a7SSoheil Hassas Yeganeh 	if (skb_next)
4736e3ae2365SAlexander Aring 		sk_error_report(sk);
4737364a9e93SWillem de Bruijn 
4738364a9e93SWillem de Bruijn 	return skb;
4739364a9e93SWillem de Bruijn }
4740364a9e93SWillem de Bruijn EXPORT_SYMBOL(sock_dequeue_err_skb);
4741364a9e93SWillem de Bruijn 
4742cab41c47SAlexander Duyck /**
4743cab41c47SAlexander Duyck  * skb_clone_sk - create clone of skb, and take reference to socket
4744cab41c47SAlexander Duyck  * @skb: the skb to clone
4745cab41c47SAlexander Duyck  *
4746cab41c47SAlexander Duyck  * This function creates a clone of a buffer that holds a reference on
4747cab41c47SAlexander Duyck  * sk_refcnt.  Buffers created via this function are meant to be
4748cab41c47SAlexander Duyck  * returned using sock_queue_err_skb, or free via kfree_skb.
4749cab41c47SAlexander Duyck  *
4750cab41c47SAlexander Duyck  * When passing buffers allocated with this function to sock_queue_err_skb
4751cab41c47SAlexander Duyck  * it is necessary to wrap the call with sock_hold/sock_put in order to
4752cab41c47SAlexander Duyck  * prevent the socket from being released prior to being enqueued on
4753cab41c47SAlexander Duyck  * the sk_error_queue.
4754cab41c47SAlexander Duyck  */
475562bccb8cSAlexander Duyck struct sk_buff *skb_clone_sk(struct sk_buff *skb)
475662bccb8cSAlexander Duyck {
475762bccb8cSAlexander Duyck 	struct sock *sk = skb->sk;
475862bccb8cSAlexander Duyck 	struct sk_buff *clone;
475962bccb8cSAlexander Duyck 
476041c6d650SReshetova, Elena 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
476162bccb8cSAlexander Duyck 		return NULL;
476262bccb8cSAlexander Duyck 
476362bccb8cSAlexander Duyck 	clone = skb_clone(skb, GFP_ATOMIC);
476462bccb8cSAlexander Duyck 	if (!clone) {
476562bccb8cSAlexander Duyck 		sock_put(sk);
476662bccb8cSAlexander Duyck 		return NULL;
476762bccb8cSAlexander Duyck 	}
476862bccb8cSAlexander Duyck 
476962bccb8cSAlexander Duyck 	clone->sk = sk;
477062bccb8cSAlexander Duyck 	clone->destructor = sock_efree;
477162bccb8cSAlexander Duyck 
477262bccb8cSAlexander Duyck 	return clone;
477362bccb8cSAlexander Duyck }
477462bccb8cSAlexander Duyck EXPORT_SYMBOL(skb_clone_sk);
477562bccb8cSAlexander Duyck 
477637846ef0SAlexander Duyck static void __skb_complete_tx_timestamp(struct sk_buff *skb,
477737846ef0SAlexander Duyck 					struct sock *sk,
47784ef1b286SSoheil Hassas Yeganeh 					int tstype,
47794ef1b286SSoheil Hassas Yeganeh 					bool opt_stats)
4780ac45f602SPatrick Ohly {
4781ac45f602SPatrick Ohly 	struct sock_exterr_skb *serr;
4782ac45f602SPatrick Ohly 	int err;
4783ac45f602SPatrick Ohly 
47844ef1b286SSoheil Hassas Yeganeh 	BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
47854ef1b286SSoheil Hassas Yeganeh 
4786ac45f602SPatrick Ohly 	serr = SKB_EXT_ERR(skb);
4787ac45f602SPatrick Ohly 	memset(serr, 0, sizeof(*serr));
4788ac45f602SPatrick Ohly 	serr->ee.ee_errno = ENOMSG;
4789ac45f602SPatrick Ohly 	serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4790e7fd2885SWillem de Bruijn 	serr->ee.ee_info = tstype;
47914ef1b286SSoheil Hassas Yeganeh 	serr->opt_stats = opt_stats;
47921862d620SWillem de Bruijn 	serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
47934ed2d765SWillem de Bruijn 	if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
479409c2d251SWillem de Bruijn 		serr->ee.ee_data = skb_shinfo(skb)->tskey;
479542f67eeaSEric Dumazet 		if (sk_is_tcp(sk))
4796a1cdec57SEric Dumazet 			serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
47974ed2d765SWillem de Bruijn 	}
479829030374SEric Dumazet 
4799ac45f602SPatrick Ohly 	err = sock_queue_err_skb(sk, skb);
480029030374SEric Dumazet 
4801ac45f602SPatrick Ohly 	if (err)
4802ac45f602SPatrick Ohly 		kfree_skb(skb);
4803ac45f602SPatrick Ohly }
480437846ef0SAlexander Duyck 
4805b245be1fSWillem de Bruijn static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4806b245be1fSWillem de Bruijn {
4807b245be1fSWillem de Bruijn 	bool ret;
4808b245be1fSWillem de Bruijn 
4809d2154b0aSKuniyuki Iwashima 	if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
4810b245be1fSWillem de Bruijn 		return true;
4811b245be1fSWillem de Bruijn 
4812b245be1fSWillem de Bruijn 	read_lock_bh(&sk->sk_callback_lock);
4813b245be1fSWillem de Bruijn 	ret = sk->sk_socket && sk->sk_socket->file &&
4814b245be1fSWillem de Bruijn 	      file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4815b245be1fSWillem de Bruijn 	read_unlock_bh(&sk->sk_callback_lock);
4816b245be1fSWillem de Bruijn 	return ret;
4817b245be1fSWillem de Bruijn }
4818b245be1fSWillem de Bruijn 
481937846ef0SAlexander Duyck void skb_complete_tx_timestamp(struct sk_buff *skb,
482037846ef0SAlexander Duyck 			       struct skb_shared_hwtstamps *hwtstamps)
482137846ef0SAlexander Duyck {
482237846ef0SAlexander Duyck 	struct sock *sk = skb->sk;
482337846ef0SAlexander Duyck 
4824b245be1fSWillem de Bruijn 	if (!skb_may_tx_timestamp(sk, false))
482535b99dffSWillem de Bruijn 		goto err;
4826b245be1fSWillem de Bruijn 
48279ac25fc0SEric Dumazet 	/* Take a reference to prevent skb_orphan() from freeing the socket,
48289ac25fc0SEric Dumazet 	 * but only if the socket refcount is not zero.
48299ac25fc0SEric Dumazet 	 */
483041c6d650SReshetova, Elena 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
483137846ef0SAlexander Duyck 		*skb_hwtstamps(skb) = *hwtstamps;
48324ef1b286SSoheil Hassas Yeganeh 		__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
483337846ef0SAlexander Duyck 		sock_put(sk);
483435b99dffSWillem de Bruijn 		return;
483537846ef0SAlexander Duyck 	}
483635b99dffSWillem de Bruijn 
483735b99dffSWillem de Bruijn err:
483835b99dffSWillem de Bruijn 	kfree_skb(skb);
48399ac25fc0SEric Dumazet }
484037846ef0SAlexander Duyck EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
484137846ef0SAlexander Duyck 
484237846ef0SAlexander Duyck void __skb_tstamp_tx(struct sk_buff *orig_skb,
4843e7ed11eeSYousuk Seung 		     const struct sk_buff *ack_skb,
484437846ef0SAlexander Duyck 		     struct skb_shared_hwtstamps *hwtstamps,
484537846ef0SAlexander Duyck 		     struct sock *sk, int tstype)
484637846ef0SAlexander Duyck {
484737846ef0SAlexander Duyck 	struct sk_buff *skb;
48484ef1b286SSoheil Hassas Yeganeh 	bool tsonly, opt_stats = false;
484937846ef0SAlexander Duyck 
48503a8dd971SWillem de Bruijn 	if (!sk)
48513a8dd971SWillem de Bruijn 		return;
48523a8dd971SWillem de Bruijn 
4853b50a5c70SMiroslav Lichvar 	if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4854b50a5c70SMiroslav Lichvar 	    skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4855b50a5c70SMiroslav Lichvar 		return;
4856b50a5c70SMiroslav Lichvar 
48573a8dd971SWillem de Bruijn 	tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
48583a8dd971SWillem de Bruijn 	if (!skb_may_tx_timestamp(sk, tsonly))
485937846ef0SAlexander Duyck 		return;
486037846ef0SAlexander Duyck 
48611c885808SFrancis Yan 	if (tsonly) {
48621c885808SFrancis Yan #ifdef CONFIG_INET
48631c885808SFrancis Yan 		if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
486442f67eeaSEric Dumazet 		    sk_is_tcp(sk)) {
4865e7ed11eeSYousuk Seung 			skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4866e7ed11eeSYousuk Seung 							     ack_skb);
48674ef1b286SSoheil Hassas Yeganeh 			opt_stats = true;
48684ef1b286SSoheil Hassas Yeganeh 		} else
48691c885808SFrancis Yan #endif
48701c885808SFrancis Yan 			skb = alloc_skb(0, GFP_ATOMIC);
48711c885808SFrancis Yan 	} else {
487237846ef0SAlexander Duyck 		skb = skb_clone(orig_skb, GFP_ATOMIC);
48731c885808SFrancis Yan 	}
487437846ef0SAlexander Duyck 	if (!skb)
487537846ef0SAlexander Duyck 		return;
487637846ef0SAlexander Duyck 
487749ca0d8bSWillem de Bruijn 	if (tsonly) {
4878fff88030SWillem de Bruijn 		skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4879fff88030SWillem de Bruijn 					     SKBTX_ANY_TSTAMP;
488049ca0d8bSWillem de Bruijn 		skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
488149ca0d8bSWillem de Bruijn 	}
488249ca0d8bSWillem de Bruijn 
488349ca0d8bSWillem de Bruijn 	if (hwtstamps)
488449ca0d8bSWillem de Bruijn 		*skb_hwtstamps(skb) = *hwtstamps;
488549ca0d8bSWillem de Bruijn 	else
4886d93376f5SMartin KaFai Lau 		__net_timestamp(skb);
488749ca0d8bSWillem de Bruijn 
48884ef1b286SSoheil Hassas Yeganeh 	__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
488937846ef0SAlexander Duyck }
4890e7fd2885SWillem de Bruijn EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4891e7fd2885SWillem de Bruijn 
4892e7fd2885SWillem de Bruijn void skb_tstamp_tx(struct sk_buff *orig_skb,
4893e7fd2885SWillem de Bruijn 		   struct skb_shared_hwtstamps *hwtstamps)
4894e7fd2885SWillem de Bruijn {
4895e7ed11eeSYousuk Seung 	return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4896e7fd2885SWillem de Bruijn 			       SCM_TSTAMP_SND);
4897e7fd2885SWillem de Bruijn }
4898ac45f602SPatrick Ohly EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4899ac45f602SPatrick Ohly 
49006e3e939fSJohannes Berg void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
49016e3e939fSJohannes Berg {
49026e3e939fSJohannes Berg 	struct sock *sk = skb->sk;
49036e3e939fSJohannes Berg 	struct sock_exterr_skb *serr;
4904dd4f1072SEric Dumazet 	int err = 1;
49056e3e939fSJohannes Berg 
49066e3e939fSJohannes Berg 	skb->wifi_acked_valid = 1;
49076e3e939fSJohannes Berg 	skb->wifi_acked = acked;
49086e3e939fSJohannes Berg 
49096e3e939fSJohannes Berg 	serr = SKB_EXT_ERR(skb);
49106e3e939fSJohannes Berg 	memset(serr, 0, sizeof(*serr));
49116e3e939fSJohannes Berg 	serr->ee.ee_errno = ENOMSG;
49126e3e939fSJohannes Berg 	serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
49136e3e939fSJohannes Berg 
4914dd4f1072SEric Dumazet 	/* Take a reference to prevent skb_orphan() from freeing the socket,
4915dd4f1072SEric Dumazet 	 * but only if the socket refcount is not zero.
4916dd4f1072SEric Dumazet 	 */
491741c6d650SReshetova, Elena 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
49186e3e939fSJohannes Berg 		err = sock_queue_err_skb(sk, skb);
4919dd4f1072SEric Dumazet 		sock_put(sk);
4920dd4f1072SEric Dumazet 	}
49216e3e939fSJohannes Berg 	if (err)
49226e3e939fSJohannes Berg 		kfree_skb(skb);
49236e3e939fSJohannes Berg }
49246e3e939fSJohannes Berg EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
49256e3e939fSJohannes Berg 
4926f35d9d8aSRusty Russell /**
4927f35d9d8aSRusty Russell  * skb_partial_csum_set - set up and verify partial csum values for packet
4928f35d9d8aSRusty Russell  * @skb: the skb to set
4929f35d9d8aSRusty Russell  * @start: the number of bytes after skb->data to start checksumming.
4930f35d9d8aSRusty Russell  * @off: the offset from start to place the checksum.
4931f35d9d8aSRusty Russell  *
4932f35d9d8aSRusty Russell  * For untrusted partially-checksummed packets, we need to make sure the values
4933f35d9d8aSRusty Russell  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4934f35d9d8aSRusty Russell  *
4935f35d9d8aSRusty Russell  * This function checks and sets those values and skb->ip_summed: if this
4936f35d9d8aSRusty Russell  * returns false you should drop the packet.
4937f35d9d8aSRusty Russell  */
4938f35d9d8aSRusty Russell bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4939f35d9d8aSRusty Russell {
494052b5d6f5SEric Dumazet 	u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
494152b5d6f5SEric Dumazet 	u32 csum_start = skb_headroom(skb) + (u32)start;
494252b5d6f5SEric Dumazet 
494352b5d6f5SEric Dumazet 	if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
494452b5d6f5SEric Dumazet 		net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
494552b5d6f5SEric Dumazet 				     start, off, skb_headroom(skb), skb_headlen(skb));
4946f35d9d8aSRusty Russell 		return false;
4947f35d9d8aSRusty Russell 	}
4948f35d9d8aSRusty Russell 	skb->ip_summed = CHECKSUM_PARTIAL;
494952b5d6f5SEric Dumazet 	skb->csum_start = csum_start;
4950f35d9d8aSRusty Russell 	skb->csum_offset = off;
4951e5d5decaSJason Wang 	skb_set_transport_header(skb, start);
4952f35d9d8aSRusty Russell 	return true;
4953f35d9d8aSRusty Russell }
4954b4ac530fSDavid S. Miller EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4955f35d9d8aSRusty Russell 
4956ed1f50c3SPaul Durrant static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4957ed1f50c3SPaul Durrant 			       unsigned int max)
4958ed1f50c3SPaul Durrant {
4959ed1f50c3SPaul Durrant 	if (skb_headlen(skb) >= len)
4960ed1f50c3SPaul Durrant 		return 0;
4961ed1f50c3SPaul Durrant 
4962ed1f50c3SPaul Durrant 	/* If we need to pullup then pullup to the max, so we
4963ed1f50c3SPaul Durrant 	 * won't need to do it again.
4964ed1f50c3SPaul Durrant 	 */
4965ed1f50c3SPaul Durrant 	if (max > skb->len)
4966ed1f50c3SPaul Durrant 		max = skb->len;
4967ed1f50c3SPaul Durrant 
4968ed1f50c3SPaul Durrant 	if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4969ed1f50c3SPaul Durrant 		return -ENOMEM;
4970ed1f50c3SPaul Durrant 
4971ed1f50c3SPaul Durrant 	if (skb_headlen(skb) < len)
4972ed1f50c3SPaul Durrant 		return -EPROTO;
4973ed1f50c3SPaul Durrant 
4974ed1f50c3SPaul Durrant 	return 0;
4975ed1f50c3SPaul Durrant }
4976ed1f50c3SPaul Durrant 
4977f9708b43SJan Beulich #define MAX_TCP_HDR_LEN (15 * 4)
4978f9708b43SJan Beulich 
4979f9708b43SJan Beulich static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4980f9708b43SJan Beulich 				      typeof(IPPROTO_IP) proto,
4981f9708b43SJan Beulich 				      unsigned int off)
4982f9708b43SJan Beulich {
4983f9708b43SJan Beulich 	int err;
4984f9708b43SJan Beulich 
4985161d1792SKees Cook 	switch (proto) {
4986f9708b43SJan Beulich 	case IPPROTO_TCP:
4987f9708b43SJan Beulich 		err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4988f9708b43SJan Beulich 					  off + MAX_TCP_HDR_LEN);
4989f9708b43SJan Beulich 		if (!err && !skb_partial_csum_set(skb, off,
4990f9708b43SJan Beulich 						  offsetof(struct tcphdr,
4991f9708b43SJan Beulich 							   check)))
4992f9708b43SJan Beulich 			err = -EPROTO;
4993f9708b43SJan Beulich 		return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4994f9708b43SJan Beulich 
4995f9708b43SJan Beulich 	case IPPROTO_UDP:
4996f9708b43SJan Beulich 		err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4997f9708b43SJan Beulich 					  off + sizeof(struct udphdr));
4998f9708b43SJan Beulich 		if (!err && !skb_partial_csum_set(skb, off,
4999f9708b43SJan Beulich 						  offsetof(struct udphdr,
5000f9708b43SJan Beulich 							   check)))
5001f9708b43SJan Beulich 			err = -EPROTO;
5002f9708b43SJan Beulich 		return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5003f9708b43SJan Beulich 	}
5004f9708b43SJan Beulich 
5005f9708b43SJan Beulich 	return ERR_PTR(-EPROTO);
5006f9708b43SJan Beulich }
5007f9708b43SJan Beulich 
5008ed1f50c3SPaul Durrant /* This value should be large enough to cover a tagged ethernet header plus
5009ed1f50c3SPaul Durrant  * maximally sized IP and TCP or UDP headers.
5010ed1f50c3SPaul Durrant  */
5011ed1f50c3SPaul Durrant #define MAX_IP_HDR_LEN 128
5012ed1f50c3SPaul Durrant 
5013f9708b43SJan Beulich static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5014ed1f50c3SPaul Durrant {
5015ed1f50c3SPaul Durrant 	unsigned int off;
5016ed1f50c3SPaul Durrant 	bool fragment;
5017f9708b43SJan Beulich 	__sum16 *csum;
5018ed1f50c3SPaul Durrant 	int err;
5019ed1f50c3SPaul Durrant 
5020ed1f50c3SPaul Durrant 	fragment = false;
5021ed1f50c3SPaul Durrant 
5022ed1f50c3SPaul Durrant 	err = skb_maybe_pull_tail(skb,
5023ed1f50c3SPaul Durrant 				  sizeof(struct iphdr),
5024ed1f50c3SPaul Durrant 				  MAX_IP_HDR_LEN);
5025ed1f50c3SPaul Durrant 	if (err < 0)
5026ed1f50c3SPaul Durrant 		goto out;
5027ed1f50c3SPaul Durrant 
502811f920d2SMiaohe Lin 	if (ip_is_fragment(ip_hdr(skb)))
5029ed1f50c3SPaul Durrant 		fragment = true;
5030ed1f50c3SPaul Durrant 
5031ed1f50c3SPaul Durrant 	off = ip_hdrlen(skb);
5032ed1f50c3SPaul Durrant 
5033ed1f50c3SPaul Durrant 	err = -EPROTO;
5034ed1f50c3SPaul Durrant 
5035ed1f50c3SPaul Durrant 	if (fragment)
5036ed1f50c3SPaul Durrant 		goto out;
5037ed1f50c3SPaul Durrant 
5038f9708b43SJan Beulich 	csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5039f9708b43SJan Beulich 	if (IS_ERR(csum))
5040f9708b43SJan Beulich 		return PTR_ERR(csum);
5041ed1f50c3SPaul Durrant 
5042ed1f50c3SPaul Durrant 	if (recalculate)
5043f9708b43SJan Beulich 		*csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5044ed1f50c3SPaul Durrant 					   ip_hdr(skb)->daddr,
5045ed1f50c3SPaul Durrant 					   skb->len - off,
5046f9708b43SJan Beulich 					   ip_hdr(skb)->protocol, 0);
5047ed1f50c3SPaul Durrant 	err = 0;
5048ed1f50c3SPaul Durrant 
5049ed1f50c3SPaul Durrant out:
5050ed1f50c3SPaul Durrant 	return err;
5051ed1f50c3SPaul Durrant }
5052ed1f50c3SPaul Durrant 
5053ed1f50c3SPaul Durrant /* This value should be large enough to cover a tagged ethernet header plus
5054ed1f50c3SPaul Durrant  * an IPv6 header, all options, and a maximal TCP or UDP header.
5055ed1f50c3SPaul Durrant  */
5056ed1f50c3SPaul Durrant #define MAX_IPV6_HDR_LEN 256
5057ed1f50c3SPaul Durrant 
5058ed1f50c3SPaul Durrant #define OPT_HDR(type, skb, off) \
5059ed1f50c3SPaul Durrant 	(type *)(skb_network_header(skb) + (off))
5060ed1f50c3SPaul Durrant 
5061ed1f50c3SPaul Durrant static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5062ed1f50c3SPaul Durrant {
5063ed1f50c3SPaul Durrant 	int err;
5064ed1f50c3SPaul Durrant 	u8 nexthdr;
5065ed1f50c3SPaul Durrant 	unsigned int off;
5066ed1f50c3SPaul Durrant 	unsigned int len;
5067ed1f50c3SPaul Durrant 	bool fragment;
5068ed1f50c3SPaul Durrant 	bool done;
5069f9708b43SJan Beulich 	__sum16 *csum;
5070ed1f50c3SPaul Durrant 
5071ed1f50c3SPaul Durrant 	fragment = false;
5072ed1f50c3SPaul Durrant 	done = false;
5073ed1f50c3SPaul Durrant 
5074ed1f50c3SPaul Durrant 	off = sizeof(struct ipv6hdr);
5075ed1f50c3SPaul Durrant 
5076ed1f50c3SPaul Durrant 	err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5077ed1f50c3SPaul Durrant 	if (err < 0)
5078ed1f50c3SPaul Durrant 		goto out;
5079ed1f50c3SPaul Durrant 
5080ed1f50c3SPaul Durrant 	nexthdr = ipv6_hdr(skb)->nexthdr;
5081ed1f50c3SPaul Durrant 
5082ed1f50c3SPaul Durrant 	len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5083ed1f50c3SPaul Durrant 	while (off <= len && !done) {
5084ed1f50c3SPaul Durrant 		switch (nexthdr) {
5085ed1f50c3SPaul Durrant 		case IPPROTO_DSTOPTS:
5086ed1f50c3SPaul Durrant 		case IPPROTO_HOPOPTS:
5087ed1f50c3SPaul Durrant 		case IPPROTO_ROUTING: {
5088ed1f50c3SPaul Durrant 			struct ipv6_opt_hdr *hp;
5089ed1f50c3SPaul Durrant 
5090ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5091ed1f50c3SPaul Durrant 						  off +
5092ed1f50c3SPaul Durrant 						  sizeof(struct ipv6_opt_hdr),
5093ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5094ed1f50c3SPaul Durrant 			if (err < 0)
5095ed1f50c3SPaul Durrant 				goto out;
5096ed1f50c3SPaul Durrant 
5097ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5098ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5099ed1f50c3SPaul Durrant 			off += ipv6_optlen(hp);
5100ed1f50c3SPaul Durrant 			break;
5101ed1f50c3SPaul Durrant 		}
5102ed1f50c3SPaul Durrant 		case IPPROTO_AH: {
5103ed1f50c3SPaul Durrant 			struct ip_auth_hdr *hp;
5104ed1f50c3SPaul Durrant 
5105ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5106ed1f50c3SPaul Durrant 						  off +
5107ed1f50c3SPaul Durrant 						  sizeof(struct ip_auth_hdr),
5108ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5109ed1f50c3SPaul Durrant 			if (err < 0)
5110ed1f50c3SPaul Durrant 				goto out;
5111ed1f50c3SPaul Durrant 
5112ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5113ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5114ed1f50c3SPaul Durrant 			off += ipv6_authlen(hp);
5115ed1f50c3SPaul Durrant 			break;
5116ed1f50c3SPaul Durrant 		}
5117ed1f50c3SPaul Durrant 		case IPPROTO_FRAGMENT: {
5118ed1f50c3SPaul Durrant 			struct frag_hdr *hp;
5119ed1f50c3SPaul Durrant 
5120ed1f50c3SPaul Durrant 			err = skb_maybe_pull_tail(skb,
5121ed1f50c3SPaul Durrant 						  off +
5122ed1f50c3SPaul Durrant 						  sizeof(struct frag_hdr),
5123ed1f50c3SPaul Durrant 						  MAX_IPV6_HDR_LEN);
5124ed1f50c3SPaul Durrant 			if (err < 0)
5125ed1f50c3SPaul Durrant 				goto out;
5126ed1f50c3SPaul Durrant 
5127ed1f50c3SPaul Durrant 			hp = OPT_HDR(struct frag_hdr, skb, off);
5128ed1f50c3SPaul Durrant 
5129ed1f50c3SPaul Durrant 			if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5130ed1f50c3SPaul Durrant 				fragment = true;
5131ed1f50c3SPaul Durrant 
5132ed1f50c3SPaul Durrant 			nexthdr = hp->nexthdr;
5133ed1f50c3SPaul Durrant 			off += sizeof(struct frag_hdr);
5134ed1f50c3SPaul Durrant 			break;
5135ed1f50c3SPaul Durrant 		}
5136ed1f50c3SPaul Durrant 		default:
5137ed1f50c3SPaul Durrant 			done = true;
5138ed1f50c3SPaul Durrant 			break;
5139ed1f50c3SPaul Durrant 		}
5140ed1f50c3SPaul Durrant 	}
5141ed1f50c3SPaul Durrant 
5142ed1f50c3SPaul Durrant 	err = -EPROTO;
5143ed1f50c3SPaul Durrant 
5144ed1f50c3SPaul Durrant 	if (!done || fragment)
5145ed1f50c3SPaul Durrant 		goto out;
5146ed1f50c3SPaul Durrant 
5147f9708b43SJan Beulich 	csum = skb_checksum_setup_ip(skb, nexthdr, off);
5148f9708b43SJan Beulich 	if (IS_ERR(csum))
5149f9708b43SJan Beulich 		return PTR_ERR(csum);
5150ed1f50c3SPaul Durrant 
5151ed1f50c3SPaul Durrant 	if (recalculate)
5152f9708b43SJan Beulich 		*csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5153ed1f50c3SPaul Durrant 					 &ipv6_hdr(skb)->daddr,
5154f9708b43SJan Beulich 					 skb->len - off, nexthdr, 0);
5155ed1f50c3SPaul Durrant 	err = 0;
5156ed1f50c3SPaul Durrant 
5157ed1f50c3SPaul Durrant out:
5158ed1f50c3SPaul Durrant 	return err;
5159ed1f50c3SPaul Durrant }
5160ed1f50c3SPaul Durrant 
5161ed1f50c3SPaul Durrant /**
5162ed1f50c3SPaul Durrant  * skb_checksum_setup - set up partial checksum offset
5163ed1f50c3SPaul Durrant  * @skb: the skb to set up
5164ed1f50c3SPaul Durrant  * @recalculate: if true the pseudo-header checksum will be recalculated
5165ed1f50c3SPaul Durrant  */
5166ed1f50c3SPaul Durrant int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5167ed1f50c3SPaul Durrant {
5168ed1f50c3SPaul Durrant 	int err;
5169ed1f50c3SPaul Durrant 
5170ed1f50c3SPaul Durrant 	switch (skb->protocol) {
5171ed1f50c3SPaul Durrant 	case htons(ETH_P_IP):
5172f9708b43SJan Beulich 		err = skb_checksum_setup_ipv4(skb, recalculate);
5173ed1f50c3SPaul Durrant 		break;
5174ed1f50c3SPaul Durrant 
5175ed1f50c3SPaul Durrant 	case htons(ETH_P_IPV6):
5176ed1f50c3SPaul Durrant 		err = skb_checksum_setup_ipv6(skb, recalculate);
5177ed1f50c3SPaul Durrant 		break;
5178ed1f50c3SPaul Durrant 
5179ed1f50c3SPaul Durrant 	default:
5180ed1f50c3SPaul Durrant 		err = -EPROTO;
5181ed1f50c3SPaul Durrant 		break;
5182ed1f50c3SPaul Durrant 	}
5183ed1f50c3SPaul Durrant 
5184ed1f50c3SPaul Durrant 	return err;
5185ed1f50c3SPaul Durrant }
5186ed1f50c3SPaul Durrant EXPORT_SYMBOL(skb_checksum_setup);
5187ed1f50c3SPaul Durrant 
51889afd85c9SLinus Lüssing /**
51899afd85c9SLinus Lüssing  * skb_checksum_maybe_trim - maybe trims the given skb
51909afd85c9SLinus Lüssing  * @skb: the skb to check
51919afd85c9SLinus Lüssing  * @transport_len: the data length beyond the network header
51929afd85c9SLinus Lüssing  *
51939afd85c9SLinus Lüssing  * Checks whether the given skb has data beyond the given transport length.
51949afd85c9SLinus Lüssing  * If so, returns a cloned skb trimmed to this transport length.
51959afd85c9SLinus Lüssing  * Otherwise returns the provided skb. Returns NULL in error cases
51969afd85c9SLinus Lüssing  * (e.g. transport_len exceeds skb length or out-of-memory).
51979afd85c9SLinus Lüssing  *
5198a516993fSLinus Lüssing  * Caller needs to set the skb transport header and free any returned skb if it
5199a516993fSLinus Lüssing  * differs from the provided skb.
52009afd85c9SLinus Lüssing  */
52019afd85c9SLinus Lüssing static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
52029afd85c9SLinus Lüssing 					       unsigned int transport_len)
52039afd85c9SLinus Lüssing {
52049afd85c9SLinus Lüssing 	struct sk_buff *skb_chk;
52059afd85c9SLinus Lüssing 	unsigned int len = skb_transport_offset(skb) + transport_len;
52069afd85c9SLinus Lüssing 	int ret;
52079afd85c9SLinus Lüssing 
5208a516993fSLinus Lüssing 	if (skb->len < len)
52099afd85c9SLinus Lüssing 		return NULL;
5210a516993fSLinus Lüssing 	else if (skb->len == len)
52119afd85c9SLinus Lüssing 		return skb;
52129afd85c9SLinus Lüssing 
52139afd85c9SLinus Lüssing 	skb_chk = skb_clone(skb, GFP_ATOMIC);
52149afd85c9SLinus Lüssing 	if (!skb_chk)
52159afd85c9SLinus Lüssing 		return NULL;
52169afd85c9SLinus Lüssing 
52179afd85c9SLinus Lüssing 	ret = pskb_trim_rcsum(skb_chk, len);
52189afd85c9SLinus Lüssing 	if (ret) {
52199afd85c9SLinus Lüssing 		kfree_skb(skb_chk);
52209afd85c9SLinus Lüssing 		return NULL;
52219afd85c9SLinus Lüssing 	}
52229afd85c9SLinus Lüssing 
52239afd85c9SLinus Lüssing 	return skb_chk;
52249afd85c9SLinus Lüssing }
52259afd85c9SLinus Lüssing 
52269afd85c9SLinus Lüssing /**
52279afd85c9SLinus Lüssing  * skb_checksum_trimmed - validate checksum of an skb
52289afd85c9SLinus Lüssing  * @skb: the skb to check
52299afd85c9SLinus Lüssing  * @transport_len: the data length beyond the network header
52309afd85c9SLinus Lüssing  * @skb_chkf: checksum function to use
52319afd85c9SLinus Lüssing  *
52329afd85c9SLinus Lüssing  * Applies the given checksum function skb_chkf to the provided skb.
52339afd85c9SLinus Lüssing  * Returns a checked and maybe trimmed skb. Returns NULL on error.
52349afd85c9SLinus Lüssing  *
52359afd85c9SLinus Lüssing  * If the skb has data beyond the given transport length, then a
52369afd85c9SLinus Lüssing  * trimmed & cloned skb is checked and returned.
52379afd85c9SLinus Lüssing  *
5238a516993fSLinus Lüssing  * Caller needs to set the skb transport header and free any returned skb if it
5239a516993fSLinus Lüssing  * differs from the provided skb.
52409afd85c9SLinus Lüssing  */
52419afd85c9SLinus Lüssing struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
52429afd85c9SLinus Lüssing 				     unsigned int transport_len,
52439afd85c9SLinus Lüssing 				     __sum16(*skb_chkf)(struct sk_buff *skb))
52449afd85c9SLinus Lüssing {
52459afd85c9SLinus Lüssing 	struct sk_buff *skb_chk;
52469afd85c9SLinus Lüssing 	unsigned int offset = skb_transport_offset(skb);
5247fcba67c9SLinus Lüssing 	__sum16 ret;
52489afd85c9SLinus Lüssing 
52499afd85c9SLinus Lüssing 	skb_chk = skb_checksum_maybe_trim(skb, transport_len);
52509afd85c9SLinus Lüssing 	if (!skb_chk)
5251a516993fSLinus Lüssing 		goto err;
52529afd85c9SLinus Lüssing 
5253a516993fSLinus Lüssing 	if (!pskb_may_pull(skb_chk, offset))
5254a516993fSLinus Lüssing 		goto err;
52559afd85c9SLinus Lüssing 
52569b368814SLinus Lüssing 	skb_pull_rcsum(skb_chk, offset);
52579afd85c9SLinus Lüssing 	ret = skb_chkf(skb_chk);
52589b368814SLinus Lüssing 	skb_push_rcsum(skb_chk, offset);
52599afd85c9SLinus Lüssing 
5260a516993fSLinus Lüssing 	if (ret)
5261a516993fSLinus Lüssing 		goto err;
52629afd85c9SLinus Lüssing 
52639afd85c9SLinus Lüssing 	return skb_chk;
5264a516993fSLinus Lüssing 
5265a516993fSLinus Lüssing err:
5266a516993fSLinus Lüssing 	if (skb_chk && skb_chk != skb)
5267a516993fSLinus Lüssing 		kfree_skb(skb_chk);
5268a516993fSLinus Lüssing 
5269a516993fSLinus Lüssing 	return NULL;
5270a516993fSLinus Lüssing 
52719afd85c9SLinus Lüssing }
52729afd85c9SLinus Lüssing EXPORT_SYMBOL(skb_checksum_trimmed);
52739afd85c9SLinus Lüssing 
52744497b076SBen Hutchings void __skb_warn_lro_forwarding(const struct sk_buff *skb)
52754497b076SBen Hutchings {
5276e87cc472SJoe Perches 	net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5277e87cc472SJoe Perches 			     skb->dev->name);
52784497b076SBen Hutchings }
52794497b076SBen Hutchings EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5280bad43ca8SEric Dumazet 
5281bad43ca8SEric Dumazet void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5282bad43ca8SEric Dumazet {
52833d861f66SEric Dumazet 	if (head_stolen) {
52843d861f66SEric Dumazet 		skb_release_head_state(skb);
5285bad43ca8SEric Dumazet 		kmem_cache_free(skbuff_head_cache, skb);
52863d861f66SEric Dumazet 	} else {
5287bad43ca8SEric Dumazet 		__kfree_skb(skb);
5288bad43ca8SEric Dumazet 	}
52893d861f66SEric Dumazet }
5290bad43ca8SEric Dumazet EXPORT_SYMBOL(kfree_skb_partial);
5291bad43ca8SEric Dumazet 
5292bad43ca8SEric Dumazet /**
5293bad43ca8SEric Dumazet  * skb_try_coalesce - try to merge skb to prior one
5294bad43ca8SEric Dumazet  * @to: prior buffer
5295bad43ca8SEric Dumazet  * @from: buffer to add
5296bad43ca8SEric Dumazet  * @fragstolen: pointer to boolean
5297c6c4b97cSRandy Dunlap  * @delta_truesize: how much more was allocated than was requested
5298bad43ca8SEric Dumazet  */
5299bad43ca8SEric Dumazet bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5300bad43ca8SEric Dumazet 		      bool *fragstolen, int *delta_truesize)
5301bad43ca8SEric Dumazet {
5302c818fa9eSEric Dumazet 	struct skb_shared_info *to_shinfo, *from_shinfo;
5303bad43ca8SEric Dumazet 	int i, delta, len = from->len;
5304bad43ca8SEric Dumazet 
5305bad43ca8SEric Dumazet 	*fragstolen = false;
5306bad43ca8SEric Dumazet 
5307bad43ca8SEric Dumazet 	if (skb_cloned(to))
5308bad43ca8SEric Dumazet 		return false;
5309bad43ca8SEric Dumazet 
53101effe8caSJean-Philippe Brucker 	/* In general, avoid mixing slab allocated and page_pool allocated
53111effe8caSJean-Philippe Brucker 	 * pages within the same SKB. However when @to is not pp_recycle and
53121effe8caSJean-Philippe Brucker 	 * @from is cloned, we can transition frag pages from page_pool to
53131effe8caSJean-Philippe Brucker 	 * reference counted.
53141effe8caSJean-Philippe Brucker 	 *
53151effe8caSJean-Philippe Brucker 	 * On the other hand, don't allow coalescing two pp_recycle SKBs if
53161effe8caSJean-Philippe Brucker 	 * @from is cloned, in case the SKB is using page_pool fragment
53171effe8caSJean-Philippe Brucker 	 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
53181effe8caSJean-Philippe Brucker 	 * references for cloned SKBs at the moment that would result in
53191effe8caSJean-Philippe Brucker 	 * inconsistent reference counts.
53206a5bcd84SIlias Apalodimas 	 */
53211effe8caSJean-Philippe Brucker 	if (to->pp_recycle != (from->pp_recycle && !skb_cloned(from)))
53226a5bcd84SIlias Apalodimas 		return false;
53236a5bcd84SIlias Apalodimas 
5324bad43ca8SEric Dumazet 	if (len <= skb_tailroom(to)) {
5325e93a0435SEric Dumazet 		if (len)
5326bad43ca8SEric Dumazet 			BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5327bad43ca8SEric Dumazet 		*delta_truesize = 0;
5328bad43ca8SEric Dumazet 		return true;
5329bad43ca8SEric Dumazet 	}
5330bad43ca8SEric Dumazet 
5331c818fa9eSEric Dumazet 	to_shinfo = skb_shinfo(to);
5332c818fa9eSEric Dumazet 	from_shinfo = skb_shinfo(from);
5333c818fa9eSEric Dumazet 	if (to_shinfo->frag_list || from_shinfo->frag_list)
5334bad43ca8SEric Dumazet 		return false;
53351f8b977aSWillem de Bruijn 	if (skb_zcopy(to) || skb_zcopy(from))
53361f8b977aSWillem de Bruijn 		return false;
5337bad43ca8SEric Dumazet 
5338bad43ca8SEric Dumazet 	if (skb_headlen(from) != 0) {
5339bad43ca8SEric Dumazet 		struct page *page;
5340bad43ca8SEric Dumazet 		unsigned int offset;
5341bad43ca8SEric Dumazet 
5342c818fa9eSEric Dumazet 		if (to_shinfo->nr_frags +
5343c818fa9eSEric Dumazet 		    from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5344bad43ca8SEric Dumazet 			return false;
5345bad43ca8SEric Dumazet 
5346bad43ca8SEric Dumazet 		if (skb_head_is_locked(from))
5347bad43ca8SEric Dumazet 			return false;
5348bad43ca8SEric Dumazet 
5349bad43ca8SEric Dumazet 		delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5350bad43ca8SEric Dumazet 
5351bad43ca8SEric Dumazet 		page = virt_to_head_page(from->head);
5352bad43ca8SEric Dumazet 		offset = from->data - (unsigned char *)page_address(page);
5353bad43ca8SEric Dumazet 
5354c818fa9eSEric Dumazet 		skb_fill_page_desc(to, to_shinfo->nr_frags,
5355bad43ca8SEric Dumazet 				   page, offset, skb_headlen(from));
5356bad43ca8SEric Dumazet 		*fragstolen = true;
5357bad43ca8SEric Dumazet 	} else {
5358c818fa9eSEric Dumazet 		if (to_shinfo->nr_frags +
5359c818fa9eSEric Dumazet 		    from_shinfo->nr_frags > MAX_SKB_FRAGS)
5360bad43ca8SEric Dumazet 			return false;
5361bad43ca8SEric Dumazet 
5362f4b549a5SWeiping Pan 		delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5363bad43ca8SEric Dumazet 	}
5364bad43ca8SEric Dumazet 
5365bad43ca8SEric Dumazet 	WARN_ON_ONCE(delta < len);
5366bad43ca8SEric Dumazet 
5367c818fa9eSEric Dumazet 	memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5368c818fa9eSEric Dumazet 	       from_shinfo->frags,
5369c818fa9eSEric Dumazet 	       from_shinfo->nr_frags * sizeof(skb_frag_t));
5370c818fa9eSEric Dumazet 	to_shinfo->nr_frags += from_shinfo->nr_frags;
5371bad43ca8SEric Dumazet 
5372bad43ca8SEric Dumazet 	if (!skb_cloned(from))
5373c818fa9eSEric Dumazet 		from_shinfo->nr_frags = 0;
5374bad43ca8SEric Dumazet 
53758ea853fdSLi RongQing 	/* if the skb is not cloned this does nothing
53768ea853fdSLi RongQing 	 * since we set nr_frags to 0.
53778ea853fdSLi RongQing 	 */
5378c818fa9eSEric Dumazet 	for (i = 0; i < from_shinfo->nr_frags; i++)
5379c818fa9eSEric Dumazet 		__skb_frag_ref(&from_shinfo->frags[i]);
5380bad43ca8SEric Dumazet 
5381bad43ca8SEric Dumazet 	to->truesize += delta;
5382bad43ca8SEric Dumazet 	to->len += len;
5383bad43ca8SEric Dumazet 	to->data_len += len;
5384bad43ca8SEric Dumazet 
5385bad43ca8SEric Dumazet 	*delta_truesize = delta;
5386bad43ca8SEric Dumazet 	return true;
5387bad43ca8SEric Dumazet }
5388bad43ca8SEric Dumazet EXPORT_SYMBOL(skb_try_coalesce);
5389621e84d6SNicolas Dichtel 
5390621e84d6SNicolas Dichtel /**
53918b27f277SNicolas Dichtel  * skb_scrub_packet - scrub an skb
5392621e84d6SNicolas Dichtel  *
5393621e84d6SNicolas Dichtel  * @skb: buffer to clean
53948b27f277SNicolas Dichtel  * @xnet: packet is crossing netns
5395621e84d6SNicolas Dichtel  *
53968b27f277SNicolas Dichtel  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
53978b27f277SNicolas Dichtel  * into/from a tunnel. Some information have to be cleared during these
53988b27f277SNicolas Dichtel  * operations.
53998b27f277SNicolas Dichtel  * skb_scrub_packet can also be used to clean a skb before injecting it in
54008b27f277SNicolas Dichtel  * another namespace (@xnet == true). We have to clear all information in the
54018b27f277SNicolas Dichtel  * skb that could impact namespace isolation.
5402621e84d6SNicolas Dichtel  */
54038b27f277SNicolas Dichtel void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5404621e84d6SNicolas Dichtel {
5405621e84d6SNicolas Dichtel 	skb->pkt_type = PACKET_HOST;
5406621e84d6SNicolas Dichtel 	skb->skb_iif = 0;
540760ff7467SWANG Cong 	skb->ignore_df = 0;
5408621e84d6SNicolas Dichtel 	skb_dst_drop(skb);
5409174e2381SFlorian Westphal 	skb_ext_reset(skb);
5410895b5c9fSFlorian Westphal 	nf_reset_ct(skb);
5411621e84d6SNicolas Dichtel 	nf_reset_trace(skb);
5412213dd74aSHerbert Xu 
54136f9a5069SPetr Machata #ifdef CONFIG_NET_SWITCHDEV
54146f9a5069SPetr Machata 	skb->offload_fwd_mark = 0;
5415875e8939SIdo Schimmel 	skb->offload_l3_fwd_mark = 0;
54166f9a5069SPetr Machata #endif
54176f9a5069SPetr Machata 
5418213dd74aSHerbert Xu 	if (!xnet)
5419213dd74aSHerbert Xu 		return;
5420213dd74aSHerbert Xu 
54212b5ec1a5SYe Yin 	ipvs_reset(skb);
5422213dd74aSHerbert Xu 	skb->mark = 0;
5423de799101SMartin KaFai Lau 	skb_clear_tstamp(skb);
5424621e84d6SNicolas Dichtel }
5425621e84d6SNicolas Dichtel EXPORT_SYMBOL_GPL(skb_scrub_packet);
5426de960aa9SFlorian Westphal 
5427de960aa9SFlorian Westphal /**
5428de960aa9SFlorian Westphal  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5429de960aa9SFlorian Westphal  *
5430de960aa9SFlorian Westphal  * @skb: GSO skb
5431de960aa9SFlorian Westphal  *
5432de960aa9SFlorian Westphal  * skb_gso_transport_seglen is used to determine the real size of the
5433de960aa9SFlorian Westphal  * individual segments, including Layer4 headers (TCP/UDP).
5434de960aa9SFlorian Westphal  *
5435de960aa9SFlorian Westphal  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5436de960aa9SFlorian Westphal  */
5437a4a77718SDaniel Axtens static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5438de960aa9SFlorian Westphal {
5439de960aa9SFlorian Westphal 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
5440f993bc25SFlorian Westphal 	unsigned int thlen = 0;
5441f993bc25SFlorian Westphal 
5442f993bc25SFlorian Westphal 	if (skb->encapsulation) {
5443f993bc25SFlorian Westphal 		thlen = skb_inner_transport_header(skb) -
5444f993bc25SFlorian Westphal 			skb_transport_header(skb);
5445de960aa9SFlorian Westphal 
5446de960aa9SFlorian Westphal 		if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5447f993bc25SFlorian Westphal 			thlen += inner_tcp_hdrlen(skb);
5448f993bc25SFlorian Westphal 	} else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5449f993bc25SFlorian Westphal 		thlen = tcp_hdrlen(skb);
54501dd27cdeSDaniel Axtens 	} else if (unlikely(skb_is_gso_sctp(skb))) {
545190017accSMarcelo Ricardo Leitner 		thlen = sizeof(struct sctphdr);
5452ee80d1ebSWillem de Bruijn 	} else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5453ee80d1ebSWillem de Bruijn 		thlen = sizeof(struct udphdr);
5454f993bc25SFlorian Westphal 	}
54556d39d589SFlorian Westphal 	/* UFO sets gso_size to the size of the fragmentation
54566d39d589SFlorian Westphal 	 * payload, i.e. the size of the L4 (UDP) header is already
54576d39d589SFlorian Westphal 	 * accounted for.
54586d39d589SFlorian Westphal 	 */
5459f993bc25SFlorian Westphal 	return thlen + shinfo->gso_size;
5460de960aa9SFlorian Westphal }
5461a4a77718SDaniel Axtens 
5462a4a77718SDaniel Axtens /**
5463a4a77718SDaniel Axtens  * skb_gso_network_seglen - Return length of individual segments of a gso packet
5464a4a77718SDaniel Axtens  *
5465a4a77718SDaniel Axtens  * @skb: GSO skb
5466a4a77718SDaniel Axtens  *
5467a4a77718SDaniel Axtens  * skb_gso_network_seglen is used to determine the real size of the
5468a4a77718SDaniel Axtens  * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5469a4a77718SDaniel Axtens  *
5470a4a77718SDaniel Axtens  * The MAC/L2 header is not accounted for.
5471a4a77718SDaniel Axtens  */
5472a4a77718SDaniel Axtens static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5473a4a77718SDaniel Axtens {
5474a4a77718SDaniel Axtens 	unsigned int hdr_len = skb_transport_header(skb) -
5475a4a77718SDaniel Axtens 			       skb_network_header(skb);
5476a4a77718SDaniel Axtens 
5477a4a77718SDaniel Axtens 	return hdr_len + skb_gso_transport_seglen(skb);
5478a4a77718SDaniel Axtens }
5479a4a77718SDaniel Axtens 
5480a4a77718SDaniel Axtens /**
5481a4a77718SDaniel Axtens  * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5482a4a77718SDaniel Axtens  *
5483a4a77718SDaniel Axtens  * @skb: GSO skb
5484a4a77718SDaniel Axtens  *
5485a4a77718SDaniel Axtens  * skb_gso_mac_seglen is used to determine the real size of the
5486a4a77718SDaniel Axtens  * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5487a4a77718SDaniel Axtens  * headers (TCP/UDP).
5488a4a77718SDaniel Axtens  */
5489a4a77718SDaniel Axtens static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5490a4a77718SDaniel Axtens {
5491a4a77718SDaniel Axtens 	unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5492a4a77718SDaniel Axtens 
5493a4a77718SDaniel Axtens 	return hdr_len + skb_gso_transport_seglen(skb);
5494a4a77718SDaniel Axtens }
54950d5501c1SVlad Yasevich 
5496ae7ef81eSMarcelo Ricardo Leitner /**
54972b16f048SDaniel Axtens  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
54982b16f048SDaniel Axtens  *
54992b16f048SDaniel Axtens  * There are a couple of instances where we have a GSO skb, and we
55002b16f048SDaniel Axtens  * want to determine what size it would be after it is segmented.
55012b16f048SDaniel Axtens  *
55022b16f048SDaniel Axtens  * We might want to check:
55032b16f048SDaniel Axtens  * -    L3+L4+payload size (e.g. IP forwarding)
55042b16f048SDaniel Axtens  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
55052b16f048SDaniel Axtens  *
55062b16f048SDaniel Axtens  * This is a helper to do that correctly considering GSO_BY_FRAGS.
55072b16f048SDaniel Axtens  *
550849682bfaSMathieu Malaterre  * @skb: GSO skb
550949682bfaSMathieu Malaterre  *
55102b16f048SDaniel Axtens  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
55112b16f048SDaniel Axtens  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
55122b16f048SDaniel Axtens  *
55132b16f048SDaniel Axtens  * @max_len: The maximum permissible length.
55142b16f048SDaniel Axtens  *
55152b16f048SDaniel Axtens  * Returns true if the segmented length <= max length.
55162b16f048SDaniel Axtens  */
55172b16f048SDaniel Axtens static inline bool skb_gso_size_check(const struct sk_buff *skb,
55182b16f048SDaniel Axtens 				      unsigned int seg_len,
55192b16f048SDaniel Axtens 				      unsigned int max_len) {
55202b16f048SDaniel Axtens 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
55212b16f048SDaniel Axtens 	const struct sk_buff *iter;
55222b16f048SDaniel Axtens 
55232b16f048SDaniel Axtens 	if (shinfo->gso_size != GSO_BY_FRAGS)
55242b16f048SDaniel Axtens 		return seg_len <= max_len;
55252b16f048SDaniel Axtens 
55262b16f048SDaniel Axtens 	/* Undo this so we can re-use header sizes */
55272b16f048SDaniel Axtens 	seg_len -= GSO_BY_FRAGS;
55282b16f048SDaniel Axtens 
55292b16f048SDaniel Axtens 	skb_walk_frags(skb, iter) {
55302b16f048SDaniel Axtens 		if (seg_len + skb_headlen(iter) > max_len)
55312b16f048SDaniel Axtens 			return false;
55322b16f048SDaniel Axtens 	}
55332b16f048SDaniel Axtens 
55342b16f048SDaniel Axtens 	return true;
55352b16f048SDaniel Axtens }
55362b16f048SDaniel Axtens 
55372b16f048SDaniel Axtens /**
5538779b7931SDaniel Axtens  * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5539ae7ef81eSMarcelo Ricardo Leitner  *
5540ae7ef81eSMarcelo Ricardo Leitner  * @skb: GSO skb
554176f21b99SDavid S. Miller  * @mtu: MTU to validate against
5542ae7ef81eSMarcelo Ricardo Leitner  *
5543779b7931SDaniel Axtens  * skb_gso_validate_network_len validates if a given skb will fit a
5544779b7931SDaniel Axtens  * wanted MTU once split. It considers L3 headers, L4 headers, and the
5545779b7931SDaniel Axtens  * payload.
5546ae7ef81eSMarcelo Ricardo Leitner  */
5547779b7931SDaniel Axtens bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5548ae7ef81eSMarcelo Ricardo Leitner {
55492b16f048SDaniel Axtens 	return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5550ae7ef81eSMarcelo Ricardo Leitner }
5551779b7931SDaniel Axtens EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5552ae7ef81eSMarcelo Ricardo Leitner 
55532b16f048SDaniel Axtens /**
55542b16f048SDaniel Axtens  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
55552b16f048SDaniel Axtens  *
55562b16f048SDaniel Axtens  * @skb: GSO skb
55572b16f048SDaniel Axtens  * @len: length to validate against
55582b16f048SDaniel Axtens  *
55592b16f048SDaniel Axtens  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
55602b16f048SDaniel Axtens  * length once split, including L2, L3 and L4 headers and the payload.
55612b16f048SDaniel Axtens  */
55622b16f048SDaniel Axtens bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
55632b16f048SDaniel Axtens {
55642b16f048SDaniel Axtens 	return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
55652b16f048SDaniel Axtens }
55662b16f048SDaniel Axtens EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
55672b16f048SDaniel Axtens 
55680d5501c1SVlad Yasevich static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
55690d5501c1SVlad Yasevich {
5570d85e8be2SYuya Kusakabe 	int mac_len, meta_len;
5571d85e8be2SYuya Kusakabe 	void *meta;
55724bbb3e0eSToshiaki Makita 
55730d5501c1SVlad Yasevich 	if (skb_cow(skb, skb_headroom(skb)) < 0) {
55740d5501c1SVlad Yasevich 		kfree_skb(skb);
55750d5501c1SVlad Yasevich 		return NULL;
55760d5501c1SVlad Yasevich 	}
55770d5501c1SVlad Yasevich 
55784bbb3e0eSToshiaki Makita 	mac_len = skb->data - skb_mac_header(skb);
5579ae474573SToshiaki Makita 	if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
55804bbb3e0eSToshiaki Makita 		memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
55814bbb3e0eSToshiaki Makita 			mac_len - VLAN_HLEN - ETH_TLEN);
5582ae474573SToshiaki Makita 	}
5583d85e8be2SYuya Kusakabe 
5584d85e8be2SYuya Kusakabe 	meta_len = skb_metadata_len(skb);
5585d85e8be2SYuya Kusakabe 	if (meta_len) {
5586d85e8be2SYuya Kusakabe 		meta = skb_metadata_end(skb) - meta_len;
5587d85e8be2SYuya Kusakabe 		memmove(meta + VLAN_HLEN, meta, meta_len);
5588d85e8be2SYuya Kusakabe 	}
5589d85e8be2SYuya Kusakabe 
55900d5501c1SVlad Yasevich 	skb->mac_header += VLAN_HLEN;
55910d5501c1SVlad Yasevich 	return skb;
55920d5501c1SVlad Yasevich }
55930d5501c1SVlad Yasevich 
55940d5501c1SVlad Yasevich struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
55950d5501c1SVlad Yasevich {
55960d5501c1SVlad Yasevich 	struct vlan_hdr *vhdr;
55970d5501c1SVlad Yasevich 	u16 vlan_tci;
55980d5501c1SVlad Yasevich 
5599df8a39deSJiri Pirko 	if (unlikely(skb_vlan_tag_present(skb))) {
56000d5501c1SVlad Yasevich 		/* vlan_tci is already set-up so leave this for another time */
56010d5501c1SVlad Yasevich 		return skb;
56020d5501c1SVlad Yasevich 	}
56030d5501c1SVlad Yasevich 
56040d5501c1SVlad Yasevich 	skb = skb_share_check(skb, GFP_ATOMIC);
56050d5501c1SVlad Yasevich 	if (unlikely(!skb))
56060d5501c1SVlad Yasevich 		goto err_free;
560755eff0ebSMiaohe Lin 	/* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
560855eff0ebSMiaohe Lin 	if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
56090d5501c1SVlad Yasevich 		goto err_free;
56100d5501c1SVlad Yasevich 
56110d5501c1SVlad Yasevich 	vhdr = (struct vlan_hdr *)skb->data;
56120d5501c1SVlad Yasevich 	vlan_tci = ntohs(vhdr->h_vlan_TCI);
56130d5501c1SVlad Yasevich 	__vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
56140d5501c1SVlad Yasevich 
56150d5501c1SVlad Yasevich 	skb_pull_rcsum(skb, VLAN_HLEN);
56160d5501c1SVlad Yasevich 	vlan_set_encap_proto(skb, vhdr);
56170d5501c1SVlad Yasevich 
56180d5501c1SVlad Yasevich 	skb = skb_reorder_vlan_header(skb);
56190d5501c1SVlad Yasevich 	if (unlikely(!skb))
56200d5501c1SVlad Yasevich 		goto err_free;
56210d5501c1SVlad Yasevich 
56220d5501c1SVlad Yasevich 	skb_reset_network_header(skb);
56238be33ecfSAlexander Lobakin 	if (!skb_transport_header_was_set(skb))
56240d5501c1SVlad Yasevich 		skb_reset_transport_header(skb);
56250d5501c1SVlad Yasevich 	skb_reset_mac_len(skb);
56260d5501c1SVlad Yasevich 
56270d5501c1SVlad Yasevich 	return skb;
56280d5501c1SVlad Yasevich 
56290d5501c1SVlad Yasevich err_free:
56300d5501c1SVlad Yasevich 	kfree_skb(skb);
56310d5501c1SVlad Yasevich 	return NULL;
56320d5501c1SVlad Yasevich }
56330d5501c1SVlad Yasevich EXPORT_SYMBOL(skb_vlan_untag);
56342e4e4410SEric Dumazet 
563592ece280SLiu Jian int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5636e2195121SJiri Pirko {
5637e2195121SJiri Pirko 	if (!pskb_may_pull(skb, write_len))
5638e2195121SJiri Pirko 		return -ENOMEM;
5639e2195121SJiri Pirko 
5640e2195121SJiri Pirko 	if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5641e2195121SJiri Pirko 		return 0;
5642e2195121SJiri Pirko 
5643e2195121SJiri Pirko 	return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5644e2195121SJiri Pirko }
5645e2195121SJiri Pirko EXPORT_SYMBOL(skb_ensure_writable);
5646e2195121SJiri Pirko 
5647bfca4c52SShmulik Ladkani /* remove VLAN header from packet and update csum accordingly.
5648bfca4c52SShmulik Ladkani  * expects a non skb_vlan_tag_present skb with a vlan tag payload
5649bfca4c52SShmulik Ladkani  */
5650bfca4c52SShmulik Ladkani int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
565193515d53SJiri Pirko {
565293515d53SJiri Pirko 	struct vlan_hdr *vhdr;
5653b6a79208SShmulik Ladkani 	int offset = skb->data - skb_mac_header(skb);
565493515d53SJiri Pirko 	int err;
565593515d53SJiri Pirko 
5656b6a79208SShmulik Ladkani 	if (WARN_ONCE(offset,
5657b6a79208SShmulik Ladkani 		      "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5658b6a79208SShmulik Ladkani 		      offset)) {
5659b6a79208SShmulik Ladkani 		return -EINVAL;
5660b6a79208SShmulik Ladkani 	}
5661b6a79208SShmulik Ladkani 
566293515d53SJiri Pirko 	err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
566393515d53SJiri Pirko 	if (unlikely(err))
5664b6a79208SShmulik Ladkani 		return err;
566593515d53SJiri Pirko 
566693515d53SJiri Pirko 	skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
566793515d53SJiri Pirko 
566893515d53SJiri Pirko 	vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
566993515d53SJiri Pirko 	*vlan_tci = ntohs(vhdr->h_vlan_TCI);
567093515d53SJiri Pirko 
567193515d53SJiri Pirko 	memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
567293515d53SJiri Pirko 	__skb_pull(skb, VLAN_HLEN);
567393515d53SJiri Pirko 
567493515d53SJiri Pirko 	vlan_set_encap_proto(skb, vhdr);
567593515d53SJiri Pirko 	skb->mac_header += VLAN_HLEN;
567693515d53SJiri Pirko 
567793515d53SJiri Pirko 	if (skb_network_offset(skb) < ETH_HLEN)
567893515d53SJiri Pirko 		skb_set_network_header(skb, ETH_HLEN);
567993515d53SJiri Pirko 
568093515d53SJiri Pirko 	skb_reset_mac_len(skb);
568193515d53SJiri Pirko 
568293515d53SJiri Pirko 	return err;
568393515d53SJiri Pirko }
5684bfca4c52SShmulik Ladkani EXPORT_SYMBOL(__skb_vlan_pop);
568593515d53SJiri Pirko 
5686b6a79208SShmulik Ladkani /* Pop a vlan tag either from hwaccel or from payload.
5687b6a79208SShmulik Ladkani  * Expects skb->data at mac header.
5688b6a79208SShmulik Ladkani  */
568993515d53SJiri Pirko int skb_vlan_pop(struct sk_buff *skb)
569093515d53SJiri Pirko {
569193515d53SJiri Pirko 	u16 vlan_tci;
569293515d53SJiri Pirko 	__be16 vlan_proto;
569393515d53SJiri Pirko 	int err;
569493515d53SJiri Pirko 
5695df8a39deSJiri Pirko 	if (likely(skb_vlan_tag_present(skb))) {
5696b1817524SMichał Mirosław 		__vlan_hwaccel_clear_tag(skb);
569793515d53SJiri Pirko 	} else {
5698ecf4ee41SShmulik Ladkani 		if (unlikely(!eth_type_vlan(skb->protocol)))
569993515d53SJiri Pirko 			return 0;
570093515d53SJiri Pirko 
570193515d53SJiri Pirko 		err = __skb_vlan_pop(skb, &vlan_tci);
570293515d53SJiri Pirko 		if (err)
570393515d53SJiri Pirko 			return err;
570493515d53SJiri Pirko 	}
570593515d53SJiri Pirko 	/* move next vlan tag to hw accel tag */
5706ecf4ee41SShmulik Ladkani 	if (likely(!eth_type_vlan(skb->protocol)))
570793515d53SJiri Pirko 		return 0;
570893515d53SJiri Pirko 
570993515d53SJiri Pirko 	vlan_proto = skb->protocol;
571093515d53SJiri Pirko 	err = __skb_vlan_pop(skb, &vlan_tci);
571193515d53SJiri Pirko 	if (unlikely(err))
571293515d53SJiri Pirko 		return err;
571393515d53SJiri Pirko 
571493515d53SJiri Pirko 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
571593515d53SJiri Pirko 	return 0;
571693515d53SJiri Pirko }
571793515d53SJiri Pirko EXPORT_SYMBOL(skb_vlan_pop);
571893515d53SJiri Pirko 
5719b6a79208SShmulik Ladkani /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5720b6a79208SShmulik Ladkani  * Expects skb->data at mac header.
5721b6a79208SShmulik Ladkani  */
572293515d53SJiri Pirko int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
572393515d53SJiri Pirko {
5724df8a39deSJiri Pirko 	if (skb_vlan_tag_present(skb)) {
5725b6a79208SShmulik Ladkani 		int offset = skb->data - skb_mac_header(skb);
572693515d53SJiri Pirko 		int err;
572793515d53SJiri Pirko 
5728b6a79208SShmulik Ladkani 		if (WARN_ONCE(offset,
5729b6a79208SShmulik Ladkani 			      "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5730b6a79208SShmulik Ladkani 			      offset)) {
5731b6a79208SShmulik Ladkani 			return -EINVAL;
5732b6a79208SShmulik Ladkani 		}
5733b6a79208SShmulik Ladkani 
573493515d53SJiri Pirko 		err = __vlan_insert_tag(skb, skb->vlan_proto,
5735df8a39deSJiri Pirko 					skb_vlan_tag_get(skb));
5736b6a79208SShmulik Ladkani 		if (err)
573793515d53SJiri Pirko 			return err;
57389241e2dfSDaniel Borkmann 
573993515d53SJiri Pirko 		skb->protocol = skb->vlan_proto;
574093515d53SJiri Pirko 		skb->mac_len += VLAN_HLEN;
574193515d53SJiri Pirko 
57426b83d28aSDaniel Borkmann 		skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
574393515d53SJiri Pirko 	}
574493515d53SJiri Pirko 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
574593515d53SJiri Pirko 	return 0;
574693515d53SJiri Pirko }
574793515d53SJiri Pirko EXPORT_SYMBOL(skb_vlan_push);
574893515d53SJiri Pirko 
574919fbcb36SGuillaume Nault /**
575019fbcb36SGuillaume Nault  * skb_eth_pop() - Drop the Ethernet header at the head of a packet
575119fbcb36SGuillaume Nault  *
575219fbcb36SGuillaume Nault  * @skb: Socket buffer to modify
575319fbcb36SGuillaume Nault  *
575419fbcb36SGuillaume Nault  * Drop the Ethernet header of @skb.
575519fbcb36SGuillaume Nault  *
575619fbcb36SGuillaume Nault  * Expects that skb->data points to the mac header and that no VLAN tags are
575719fbcb36SGuillaume Nault  * present.
575819fbcb36SGuillaume Nault  *
575919fbcb36SGuillaume Nault  * Returns 0 on success, -errno otherwise.
576019fbcb36SGuillaume Nault  */
576119fbcb36SGuillaume Nault int skb_eth_pop(struct sk_buff *skb)
576219fbcb36SGuillaume Nault {
576319fbcb36SGuillaume Nault 	if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
576419fbcb36SGuillaume Nault 	    skb_network_offset(skb) < ETH_HLEN)
576519fbcb36SGuillaume Nault 		return -EPROTO;
576619fbcb36SGuillaume Nault 
576719fbcb36SGuillaume Nault 	skb_pull_rcsum(skb, ETH_HLEN);
576819fbcb36SGuillaume Nault 	skb_reset_mac_header(skb);
576919fbcb36SGuillaume Nault 	skb_reset_mac_len(skb);
577019fbcb36SGuillaume Nault 
577119fbcb36SGuillaume Nault 	return 0;
577219fbcb36SGuillaume Nault }
577319fbcb36SGuillaume Nault EXPORT_SYMBOL(skb_eth_pop);
577419fbcb36SGuillaume Nault 
577519fbcb36SGuillaume Nault /**
577619fbcb36SGuillaume Nault  * skb_eth_push() - Add a new Ethernet header at the head of a packet
577719fbcb36SGuillaume Nault  *
577819fbcb36SGuillaume Nault  * @skb: Socket buffer to modify
577919fbcb36SGuillaume Nault  * @dst: Destination MAC address of the new header
578019fbcb36SGuillaume Nault  * @src: Source MAC address of the new header
578119fbcb36SGuillaume Nault  *
578219fbcb36SGuillaume Nault  * Prepend @skb with a new Ethernet header.
578319fbcb36SGuillaume Nault  *
578419fbcb36SGuillaume Nault  * Expects that skb->data points to the mac header, which must be empty.
578519fbcb36SGuillaume Nault  *
578619fbcb36SGuillaume Nault  * Returns 0 on success, -errno otherwise.
578719fbcb36SGuillaume Nault  */
578819fbcb36SGuillaume Nault int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
578919fbcb36SGuillaume Nault 		 const unsigned char *src)
579019fbcb36SGuillaume Nault {
579119fbcb36SGuillaume Nault 	struct ethhdr *eth;
579219fbcb36SGuillaume Nault 	int err;
579319fbcb36SGuillaume Nault 
579419fbcb36SGuillaume Nault 	if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
579519fbcb36SGuillaume Nault 		return -EPROTO;
579619fbcb36SGuillaume Nault 
579719fbcb36SGuillaume Nault 	err = skb_cow_head(skb, sizeof(*eth));
579819fbcb36SGuillaume Nault 	if (err < 0)
579919fbcb36SGuillaume Nault 		return err;
580019fbcb36SGuillaume Nault 
580119fbcb36SGuillaume Nault 	skb_push(skb, sizeof(*eth));
580219fbcb36SGuillaume Nault 	skb_reset_mac_header(skb);
580319fbcb36SGuillaume Nault 	skb_reset_mac_len(skb);
580419fbcb36SGuillaume Nault 
580519fbcb36SGuillaume Nault 	eth = eth_hdr(skb);
580619fbcb36SGuillaume Nault 	ether_addr_copy(eth->h_dest, dst);
580719fbcb36SGuillaume Nault 	ether_addr_copy(eth->h_source, src);
580819fbcb36SGuillaume Nault 	eth->h_proto = skb->protocol;
580919fbcb36SGuillaume Nault 
581019fbcb36SGuillaume Nault 	skb_postpush_rcsum(skb, eth, sizeof(*eth));
581119fbcb36SGuillaume Nault 
581219fbcb36SGuillaume Nault 	return 0;
581319fbcb36SGuillaume Nault }
581419fbcb36SGuillaume Nault EXPORT_SYMBOL(skb_eth_push);
581519fbcb36SGuillaume Nault 
58168822e270SJohn Hurley /* Update the ethertype of hdr and the skb csum value if required. */
58178822e270SJohn Hurley static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
58188822e270SJohn Hurley 			     __be16 ethertype)
58198822e270SJohn Hurley {
58208822e270SJohn Hurley 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
58218822e270SJohn Hurley 		__be16 diff[] = { ~hdr->h_proto, ethertype };
58228822e270SJohn Hurley 
58238822e270SJohn Hurley 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
58248822e270SJohn Hurley 	}
58258822e270SJohn Hurley 
58268822e270SJohn Hurley 	hdr->h_proto = ethertype;
58278822e270SJohn Hurley }
58288822e270SJohn Hurley 
58298822e270SJohn Hurley /**
5830e7dbfed1SMartin Varghese  * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5831e7dbfed1SMartin Varghese  *                   the packet
58328822e270SJohn Hurley  *
58338822e270SJohn Hurley  * @skb: buffer
58348822e270SJohn Hurley  * @mpls_lse: MPLS label stack entry to push
58358822e270SJohn Hurley  * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5836fa4e0f88SDavide Caratti  * @mac_len: length of the MAC header
5837e7dbfed1SMartin Varghese  * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5838e7dbfed1SMartin Varghese  *            ethernet
58398822e270SJohn Hurley  *
58408822e270SJohn Hurley  * Expects skb->data at mac header.
58418822e270SJohn Hurley  *
58428822e270SJohn Hurley  * Returns 0 on success, -errno otherwise.
58438822e270SJohn Hurley  */
5844fa4e0f88SDavide Caratti int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5845d04ac224SMartin Varghese 		  int mac_len, bool ethernet)
58468822e270SJohn Hurley {
58478822e270SJohn Hurley 	struct mpls_shim_hdr *lse;
58488822e270SJohn Hurley 	int err;
58498822e270SJohn Hurley 
58508822e270SJohn Hurley 	if (unlikely(!eth_p_mpls(mpls_proto)))
58518822e270SJohn Hurley 		return -EINVAL;
58528822e270SJohn Hurley 
58538822e270SJohn Hurley 	/* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
58548822e270SJohn Hurley 	if (skb->encapsulation)
58558822e270SJohn Hurley 		return -EINVAL;
58568822e270SJohn Hurley 
58578822e270SJohn Hurley 	err = skb_cow_head(skb, MPLS_HLEN);
58588822e270SJohn Hurley 	if (unlikely(err))
58598822e270SJohn Hurley 		return err;
58608822e270SJohn Hurley 
58618822e270SJohn Hurley 	if (!skb->inner_protocol) {
5862e7dbfed1SMartin Varghese 		skb_set_inner_network_header(skb, skb_network_offset(skb));
58638822e270SJohn Hurley 		skb_set_inner_protocol(skb, skb->protocol);
58648822e270SJohn Hurley 	}
58658822e270SJohn Hurley 
58668822e270SJohn Hurley 	skb_push(skb, MPLS_HLEN);
58678822e270SJohn Hurley 	memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5868fa4e0f88SDavide Caratti 		mac_len);
58698822e270SJohn Hurley 	skb_reset_mac_header(skb);
5870fa4e0f88SDavide Caratti 	skb_set_network_header(skb, mac_len);
5871e7dbfed1SMartin Varghese 	skb_reset_mac_len(skb);
58728822e270SJohn Hurley 
58738822e270SJohn Hurley 	lse = mpls_hdr(skb);
58748822e270SJohn Hurley 	lse->label_stack_entry = mpls_lse;
58758822e270SJohn Hurley 	skb_postpush_rcsum(skb, lse, MPLS_HLEN);
58768822e270SJohn Hurley 
58774296adc3SGuillaume Nault 	if (ethernet && mac_len >= ETH_HLEN)
58788822e270SJohn Hurley 		skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
58798822e270SJohn Hurley 	skb->protocol = mpls_proto;
58808822e270SJohn Hurley 
58818822e270SJohn Hurley 	return 0;
58828822e270SJohn Hurley }
58838822e270SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_push);
58848822e270SJohn Hurley 
58852e4e4410SEric Dumazet /**
5886ed246ceeSJohn Hurley  * skb_mpls_pop() - pop the outermost MPLS header
5887ed246ceeSJohn Hurley  *
5888ed246ceeSJohn Hurley  * @skb: buffer
5889ed246ceeSJohn Hurley  * @next_proto: ethertype of header after popped MPLS header
5890fa4e0f88SDavide Caratti  * @mac_len: length of the MAC header
589176f99f98SMartin Varghese  * @ethernet: flag to indicate if the packet is ethernet
5892ed246ceeSJohn Hurley  *
5893ed246ceeSJohn Hurley  * Expects skb->data at mac header.
5894ed246ceeSJohn Hurley  *
5895ed246ceeSJohn Hurley  * Returns 0 on success, -errno otherwise.
5896ed246ceeSJohn Hurley  */
5897040b5cfbSMartin Varghese int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5898040b5cfbSMartin Varghese 		 bool ethernet)
5899ed246ceeSJohn Hurley {
5900ed246ceeSJohn Hurley 	int err;
5901ed246ceeSJohn Hurley 
5902ed246ceeSJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
5903dedc5a08SDavide Caratti 		return 0;
5904ed246ceeSJohn Hurley 
5905fa4e0f88SDavide Caratti 	err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5906ed246ceeSJohn Hurley 	if (unlikely(err))
5907ed246ceeSJohn Hurley 		return err;
5908ed246ceeSJohn Hurley 
5909ed246ceeSJohn Hurley 	skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5910ed246ceeSJohn Hurley 	memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5911fa4e0f88SDavide Caratti 		mac_len);
5912ed246ceeSJohn Hurley 
5913ed246ceeSJohn Hurley 	__skb_pull(skb, MPLS_HLEN);
5914ed246ceeSJohn Hurley 	skb_reset_mac_header(skb);
5915fa4e0f88SDavide Caratti 	skb_set_network_header(skb, mac_len);
5916ed246ceeSJohn Hurley 
59174296adc3SGuillaume Nault 	if (ethernet && mac_len >= ETH_HLEN) {
5918ed246ceeSJohn Hurley 		struct ethhdr *hdr;
5919ed246ceeSJohn Hurley 
5920ed246ceeSJohn Hurley 		/* use mpls_hdr() to get ethertype to account for VLANs. */
5921ed246ceeSJohn Hurley 		hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5922ed246ceeSJohn Hurley 		skb_mod_eth_type(skb, hdr, next_proto);
5923ed246ceeSJohn Hurley 	}
5924ed246ceeSJohn Hurley 	skb->protocol = next_proto;
5925ed246ceeSJohn Hurley 
5926ed246ceeSJohn Hurley 	return 0;
5927ed246ceeSJohn Hurley }
5928ed246ceeSJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_pop);
5929ed246ceeSJohn Hurley 
5930ed246ceeSJohn Hurley /**
5931d27cf5c5SJohn Hurley  * skb_mpls_update_lse() - modify outermost MPLS header and update csum
5932d27cf5c5SJohn Hurley  *
5933d27cf5c5SJohn Hurley  * @skb: buffer
5934d27cf5c5SJohn Hurley  * @mpls_lse: new MPLS label stack entry to update to
5935d27cf5c5SJohn Hurley  *
5936d27cf5c5SJohn Hurley  * Expects skb->data at mac header.
5937d27cf5c5SJohn Hurley  *
5938d27cf5c5SJohn Hurley  * Returns 0 on success, -errno otherwise.
5939d27cf5c5SJohn Hurley  */
5940d27cf5c5SJohn Hurley int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
5941d27cf5c5SJohn Hurley {
5942d27cf5c5SJohn Hurley 	int err;
5943d27cf5c5SJohn Hurley 
5944d27cf5c5SJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
5945d27cf5c5SJohn Hurley 		return -EINVAL;
5946d27cf5c5SJohn Hurley 
5947d27cf5c5SJohn Hurley 	err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
5948d27cf5c5SJohn Hurley 	if (unlikely(err))
5949d27cf5c5SJohn Hurley 		return err;
5950d27cf5c5SJohn Hurley 
5951d27cf5c5SJohn Hurley 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
5952d27cf5c5SJohn Hurley 		__be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
5953d27cf5c5SJohn Hurley 
5954d27cf5c5SJohn Hurley 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5955d27cf5c5SJohn Hurley 	}
5956d27cf5c5SJohn Hurley 
5957d27cf5c5SJohn Hurley 	mpls_hdr(skb)->label_stack_entry = mpls_lse;
5958d27cf5c5SJohn Hurley 
5959d27cf5c5SJohn Hurley 	return 0;
5960d27cf5c5SJohn Hurley }
5961d27cf5c5SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
5962d27cf5c5SJohn Hurley 
5963d27cf5c5SJohn Hurley /**
59642a2ea508SJohn Hurley  * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
59652a2ea508SJohn Hurley  *
59662a2ea508SJohn Hurley  * @skb: buffer
59672a2ea508SJohn Hurley  *
59682a2ea508SJohn Hurley  * Expects skb->data at mac header.
59692a2ea508SJohn Hurley  *
59702a2ea508SJohn Hurley  * Returns 0 on success, -errno otherwise.
59712a2ea508SJohn Hurley  */
59722a2ea508SJohn Hurley int skb_mpls_dec_ttl(struct sk_buff *skb)
59732a2ea508SJohn Hurley {
59742a2ea508SJohn Hurley 	u32 lse;
59752a2ea508SJohn Hurley 	u8 ttl;
59762a2ea508SJohn Hurley 
59772a2ea508SJohn Hurley 	if (unlikely(!eth_p_mpls(skb->protocol)))
59782a2ea508SJohn Hurley 		return -EINVAL;
59792a2ea508SJohn Hurley 
598013de4ed9SDavide Caratti 	if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
598113de4ed9SDavide Caratti 		return -ENOMEM;
598213de4ed9SDavide Caratti 
59832a2ea508SJohn Hurley 	lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
59842a2ea508SJohn Hurley 	ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
59852a2ea508SJohn Hurley 	if (!--ttl)
59862a2ea508SJohn Hurley 		return -EINVAL;
59872a2ea508SJohn Hurley 
59882a2ea508SJohn Hurley 	lse &= ~MPLS_LS_TTL_MASK;
59892a2ea508SJohn Hurley 	lse |= ttl << MPLS_LS_TTL_SHIFT;
59902a2ea508SJohn Hurley 
59912a2ea508SJohn Hurley 	return skb_mpls_update_lse(skb, cpu_to_be32(lse));
59922a2ea508SJohn Hurley }
59932a2ea508SJohn Hurley EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
59942a2ea508SJohn Hurley 
59952a2ea508SJohn Hurley /**
59962e4e4410SEric Dumazet  * alloc_skb_with_frags - allocate skb with page frags
59972e4e4410SEric Dumazet  *
5998de3f0d0eSMasanari Iida  * @header_len: size of linear part
5999de3f0d0eSMasanari Iida  * @data_len: needed length in frags
6000de3f0d0eSMasanari Iida  * @max_page_order: max page order desired.
6001de3f0d0eSMasanari Iida  * @errcode: pointer to error code if any
6002de3f0d0eSMasanari Iida  * @gfp_mask: allocation mask
60032e4e4410SEric Dumazet  *
60042e4e4410SEric Dumazet  * This can be used to allocate a paged skb, given a maximal order for frags.
60052e4e4410SEric Dumazet  */
60062e4e4410SEric Dumazet struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
60072e4e4410SEric Dumazet 				     unsigned long data_len,
60082e4e4410SEric Dumazet 				     int max_page_order,
60092e4e4410SEric Dumazet 				     int *errcode,
60102e4e4410SEric Dumazet 				     gfp_t gfp_mask)
60112e4e4410SEric Dumazet {
60122e4e4410SEric Dumazet 	int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
60132e4e4410SEric Dumazet 	unsigned long chunk;
60142e4e4410SEric Dumazet 	struct sk_buff *skb;
60152e4e4410SEric Dumazet 	struct page *page;
60162e4e4410SEric Dumazet 	int i;
60172e4e4410SEric Dumazet 
60182e4e4410SEric Dumazet 	*errcode = -EMSGSIZE;
60192e4e4410SEric Dumazet 	/* Note this test could be relaxed, if we succeed to allocate
60202e4e4410SEric Dumazet 	 * high order pages...
60212e4e4410SEric Dumazet 	 */
60222e4e4410SEric Dumazet 	if (npages > MAX_SKB_FRAGS)
60232e4e4410SEric Dumazet 		return NULL;
60242e4e4410SEric Dumazet 
60252e4e4410SEric Dumazet 	*errcode = -ENOBUFS;
6026f8c468e8SDavid Rientjes 	skb = alloc_skb(header_len, gfp_mask);
60272e4e4410SEric Dumazet 	if (!skb)
60282e4e4410SEric Dumazet 		return NULL;
60292e4e4410SEric Dumazet 
60302e4e4410SEric Dumazet 	skb->truesize += npages << PAGE_SHIFT;
60312e4e4410SEric Dumazet 
60322e4e4410SEric Dumazet 	for (i = 0; npages > 0; i++) {
60332e4e4410SEric Dumazet 		int order = max_page_order;
60342e4e4410SEric Dumazet 
60352e4e4410SEric Dumazet 		while (order) {
60362e4e4410SEric Dumazet 			if (npages >= 1 << order) {
6037d0164adcSMel Gorman 				page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
60382e4e4410SEric Dumazet 						   __GFP_COMP |
6039d14b56f5SMichal Hocko 						   __GFP_NOWARN,
60402e4e4410SEric Dumazet 						   order);
60412e4e4410SEric Dumazet 				if (page)
60422e4e4410SEric Dumazet 					goto fill_page;
60432e4e4410SEric Dumazet 				/* Do not retry other high order allocations */
60442e4e4410SEric Dumazet 				order = 1;
60452e4e4410SEric Dumazet 				max_page_order = 0;
60462e4e4410SEric Dumazet 			}
60472e4e4410SEric Dumazet 			order--;
60482e4e4410SEric Dumazet 		}
60492e4e4410SEric Dumazet 		page = alloc_page(gfp_mask);
60502e4e4410SEric Dumazet 		if (!page)
60512e4e4410SEric Dumazet 			goto failure;
60522e4e4410SEric Dumazet fill_page:
60532e4e4410SEric Dumazet 		chunk = min_t(unsigned long, data_len,
60542e4e4410SEric Dumazet 			      PAGE_SIZE << order);
60552e4e4410SEric Dumazet 		skb_fill_page_desc(skb, i, page, 0, chunk);
60562e4e4410SEric Dumazet 		data_len -= chunk;
60572e4e4410SEric Dumazet 		npages -= 1 << order;
60582e4e4410SEric Dumazet 	}
60592e4e4410SEric Dumazet 	return skb;
60602e4e4410SEric Dumazet 
60612e4e4410SEric Dumazet failure:
60622e4e4410SEric Dumazet 	kfree_skb(skb);
60632e4e4410SEric Dumazet 	return NULL;
60642e4e4410SEric Dumazet }
60652e4e4410SEric Dumazet EXPORT_SYMBOL(alloc_skb_with_frags);
60666fa01ccdSSowmini Varadhan 
60676fa01ccdSSowmini Varadhan /* carve out the first off bytes from skb when off < headlen */
60686fa01ccdSSowmini Varadhan static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
60696fa01ccdSSowmini Varadhan 				    const int headlen, gfp_t gfp_mask)
60706fa01ccdSSowmini Varadhan {
60716fa01ccdSSowmini Varadhan 	int i;
60726fa01ccdSSowmini Varadhan 	int size = skb_end_offset(skb);
60736fa01ccdSSowmini Varadhan 	int new_hlen = headlen - off;
60746fa01ccdSSowmini Varadhan 	u8 *data;
60756fa01ccdSSowmini Varadhan 
60766fa01ccdSSowmini Varadhan 	size = SKB_DATA_ALIGN(size);
60776fa01ccdSSowmini Varadhan 
60786fa01ccdSSowmini Varadhan 	if (skb_pfmemalloc(skb))
60796fa01ccdSSowmini Varadhan 		gfp_mask |= __GFP_MEMALLOC;
60806fa01ccdSSowmini Varadhan 	data = kmalloc_reserve(size +
60816fa01ccdSSowmini Varadhan 			       SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
60826fa01ccdSSowmini Varadhan 			       gfp_mask, NUMA_NO_NODE, NULL);
60836fa01ccdSSowmini Varadhan 	if (!data)
60846fa01ccdSSowmini Varadhan 		return -ENOMEM;
60856fa01ccdSSowmini Varadhan 
60866fa01ccdSSowmini Varadhan 	size = SKB_WITH_OVERHEAD(ksize(data));
60876fa01ccdSSowmini Varadhan 
60886fa01ccdSSowmini Varadhan 	/* Copy real data, and all frags */
60896fa01ccdSSowmini Varadhan 	skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
60906fa01ccdSSowmini Varadhan 	skb->len -= off;
60916fa01ccdSSowmini Varadhan 
60926fa01ccdSSowmini Varadhan 	memcpy((struct skb_shared_info *)(data + size),
60936fa01ccdSSowmini Varadhan 	       skb_shinfo(skb),
60946fa01ccdSSowmini Varadhan 	       offsetof(struct skb_shared_info,
60956fa01ccdSSowmini Varadhan 			frags[skb_shinfo(skb)->nr_frags]));
60966fa01ccdSSowmini Varadhan 	if (skb_cloned(skb)) {
60976fa01ccdSSowmini Varadhan 		/* drop the old head gracefully */
60986fa01ccdSSowmini Varadhan 		if (skb_orphan_frags(skb, gfp_mask)) {
60996fa01ccdSSowmini Varadhan 			kfree(data);
61006fa01ccdSSowmini Varadhan 			return -ENOMEM;
61016fa01ccdSSowmini Varadhan 		}
61026fa01ccdSSowmini Varadhan 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
61036fa01ccdSSowmini Varadhan 			skb_frag_ref(skb, i);
61046fa01ccdSSowmini Varadhan 		if (skb_has_frag_list(skb))
61056fa01ccdSSowmini Varadhan 			skb_clone_fraglist(skb);
61066fa01ccdSSowmini Varadhan 		skb_release_data(skb);
61076fa01ccdSSowmini Varadhan 	} else {
61086fa01ccdSSowmini Varadhan 		/* we can reuse existing recount- all we did was
61096fa01ccdSSowmini Varadhan 		 * relocate values
61106fa01ccdSSowmini Varadhan 		 */
61116fa01ccdSSowmini Varadhan 		skb_free_head(skb);
61126fa01ccdSSowmini Varadhan 	}
61136fa01ccdSSowmini Varadhan 
61146fa01ccdSSowmini Varadhan 	skb->head = data;
61156fa01ccdSSowmini Varadhan 	skb->data = data;
61166fa01ccdSSowmini Varadhan 	skb->head_frag = 0;
6117763087daSEric Dumazet 	skb_set_end_offset(skb, size);
61186fa01ccdSSowmini Varadhan 	skb_set_tail_pointer(skb, skb_headlen(skb));
61196fa01ccdSSowmini Varadhan 	skb_headers_offset_update(skb, 0);
61206fa01ccdSSowmini Varadhan 	skb->cloned = 0;
61216fa01ccdSSowmini Varadhan 	skb->hdr_len = 0;
61226fa01ccdSSowmini Varadhan 	skb->nohdr = 0;
61236fa01ccdSSowmini Varadhan 	atomic_set(&skb_shinfo(skb)->dataref, 1);
61246fa01ccdSSowmini Varadhan 
61256fa01ccdSSowmini Varadhan 	return 0;
61266fa01ccdSSowmini Varadhan }
61276fa01ccdSSowmini Varadhan 
61286fa01ccdSSowmini Varadhan static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
61296fa01ccdSSowmini Varadhan 
61306fa01ccdSSowmini Varadhan /* carve out the first eat bytes from skb's frag_list. May recurse into
61316fa01ccdSSowmini Varadhan  * pskb_carve()
61326fa01ccdSSowmini Varadhan  */
61336fa01ccdSSowmini Varadhan static int pskb_carve_frag_list(struct sk_buff *skb,
61346fa01ccdSSowmini Varadhan 				struct skb_shared_info *shinfo, int eat,
61356fa01ccdSSowmini Varadhan 				gfp_t gfp_mask)
61366fa01ccdSSowmini Varadhan {
61376fa01ccdSSowmini Varadhan 	struct sk_buff *list = shinfo->frag_list;
61386fa01ccdSSowmini Varadhan 	struct sk_buff *clone = NULL;
61396fa01ccdSSowmini Varadhan 	struct sk_buff *insp = NULL;
61406fa01ccdSSowmini Varadhan 
61416fa01ccdSSowmini Varadhan 	do {
61426fa01ccdSSowmini Varadhan 		if (!list) {
61436fa01ccdSSowmini Varadhan 			pr_err("Not enough bytes to eat. Want %d\n", eat);
61446fa01ccdSSowmini Varadhan 			return -EFAULT;
61456fa01ccdSSowmini Varadhan 		}
61466fa01ccdSSowmini Varadhan 		if (list->len <= eat) {
61476fa01ccdSSowmini Varadhan 			/* Eaten as whole. */
61486fa01ccdSSowmini Varadhan 			eat -= list->len;
61496fa01ccdSSowmini Varadhan 			list = list->next;
61506fa01ccdSSowmini Varadhan 			insp = list;
61516fa01ccdSSowmini Varadhan 		} else {
61526fa01ccdSSowmini Varadhan 			/* Eaten partially. */
61536fa01ccdSSowmini Varadhan 			if (skb_shared(list)) {
61546fa01ccdSSowmini Varadhan 				clone = skb_clone(list, gfp_mask);
61556fa01ccdSSowmini Varadhan 				if (!clone)
61566fa01ccdSSowmini Varadhan 					return -ENOMEM;
61576fa01ccdSSowmini Varadhan 				insp = list->next;
61586fa01ccdSSowmini Varadhan 				list = clone;
61596fa01ccdSSowmini Varadhan 			} else {
61606fa01ccdSSowmini Varadhan 				/* This may be pulled without problems. */
61616fa01ccdSSowmini Varadhan 				insp = list;
61626fa01ccdSSowmini Varadhan 			}
61636fa01ccdSSowmini Varadhan 			if (pskb_carve(list, eat, gfp_mask) < 0) {
61646fa01ccdSSowmini Varadhan 				kfree_skb(clone);
61656fa01ccdSSowmini Varadhan 				return -ENOMEM;
61666fa01ccdSSowmini Varadhan 			}
61676fa01ccdSSowmini Varadhan 			break;
61686fa01ccdSSowmini Varadhan 		}
61696fa01ccdSSowmini Varadhan 	} while (eat);
61706fa01ccdSSowmini Varadhan 
61716fa01ccdSSowmini Varadhan 	/* Free pulled out fragments. */
61726fa01ccdSSowmini Varadhan 	while ((list = shinfo->frag_list) != insp) {
61736fa01ccdSSowmini Varadhan 		shinfo->frag_list = list->next;
6174ef527f96SEric Dumazet 		consume_skb(list);
61756fa01ccdSSowmini Varadhan 	}
61766fa01ccdSSowmini Varadhan 	/* And insert new clone at head. */
61776fa01ccdSSowmini Varadhan 	if (clone) {
61786fa01ccdSSowmini Varadhan 		clone->next = list;
61796fa01ccdSSowmini Varadhan 		shinfo->frag_list = clone;
61806fa01ccdSSowmini Varadhan 	}
61816fa01ccdSSowmini Varadhan 	return 0;
61826fa01ccdSSowmini Varadhan }
61836fa01ccdSSowmini Varadhan 
61846fa01ccdSSowmini Varadhan /* carve off first len bytes from skb. Split line (off) is in the
61856fa01ccdSSowmini Varadhan  * non-linear part of skb
61866fa01ccdSSowmini Varadhan  */
61876fa01ccdSSowmini Varadhan static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
61886fa01ccdSSowmini Varadhan 				       int pos, gfp_t gfp_mask)
61896fa01ccdSSowmini Varadhan {
61906fa01ccdSSowmini Varadhan 	int i, k = 0;
61916fa01ccdSSowmini Varadhan 	int size = skb_end_offset(skb);
61926fa01ccdSSowmini Varadhan 	u8 *data;
61936fa01ccdSSowmini Varadhan 	const int nfrags = skb_shinfo(skb)->nr_frags;
61946fa01ccdSSowmini Varadhan 	struct skb_shared_info *shinfo;
61956fa01ccdSSowmini Varadhan 
61966fa01ccdSSowmini Varadhan 	size = SKB_DATA_ALIGN(size);
61976fa01ccdSSowmini Varadhan 
61986fa01ccdSSowmini Varadhan 	if (skb_pfmemalloc(skb))
61996fa01ccdSSowmini Varadhan 		gfp_mask |= __GFP_MEMALLOC;
62006fa01ccdSSowmini Varadhan 	data = kmalloc_reserve(size +
62016fa01ccdSSowmini Varadhan 			       SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
62026fa01ccdSSowmini Varadhan 			       gfp_mask, NUMA_NO_NODE, NULL);
62036fa01ccdSSowmini Varadhan 	if (!data)
62046fa01ccdSSowmini Varadhan 		return -ENOMEM;
62056fa01ccdSSowmini Varadhan 
62066fa01ccdSSowmini Varadhan 	size = SKB_WITH_OVERHEAD(ksize(data));
62076fa01ccdSSowmini Varadhan 
62086fa01ccdSSowmini Varadhan 	memcpy((struct skb_shared_info *)(data + size),
6209e3ec1e8cSMiaohe Lin 	       skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
62106fa01ccdSSowmini Varadhan 	if (skb_orphan_frags(skb, gfp_mask)) {
62116fa01ccdSSowmini Varadhan 		kfree(data);
62126fa01ccdSSowmini Varadhan 		return -ENOMEM;
62136fa01ccdSSowmini Varadhan 	}
62146fa01ccdSSowmini Varadhan 	shinfo = (struct skb_shared_info *)(data + size);
62156fa01ccdSSowmini Varadhan 	for (i = 0; i < nfrags; i++) {
62166fa01ccdSSowmini Varadhan 		int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
62176fa01ccdSSowmini Varadhan 
62186fa01ccdSSowmini Varadhan 		if (pos + fsize > off) {
62196fa01ccdSSowmini Varadhan 			shinfo->frags[k] = skb_shinfo(skb)->frags[i];
62206fa01ccdSSowmini Varadhan 
62216fa01ccdSSowmini Varadhan 			if (pos < off) {
62226fa01ccdSSowmini Varadhan 				/* Split frag.
62236fa01ccdSSowmini Varadhan 				 * We have two variants in this case:
62246fa01ccdSSowmini Varadhan 				 * 1. Move all the frag to the second
62256fa01ccdSSowmini Varadhan 				 *    part, if it is possible. F.e.
62266fa01ccdSSowmini Varadhan 				 *    this approach is mandatory for TUX,
62276fa01ccdSSowmini Varadhan 				 *    where splitting is expensive.
62286fa01ccdSSowmini Varadhan 				 * 2. Split is accurately. We make this.
62296fa01ccdSSowmini Varadhan 				 */
6230b54c9d5bSJonathan Lemon 				skb_frag_off_add(&shinfo->frags[0], off - pos);
62316fa01ccdSSowmini Varadhan 				skb_frag_size_sub(&shinfo->frags[0], off - pos);
62326fa01ccdSSowmini Varadhan 			}
62336fa01ccdSSowmini Varadhan 			skb_frag_ref(skb, i);
62346fa01ccdSSowmini Varadhan 			k++;
62356fa01ccdSSowmini Varadhan 		}
62366fa01ccdSSowmini Varadhan 		pos += fsize;
62376fa01ccdSSowmini Varadhan 	}
62386fa01ccdSSowmini Varadhan 	shinfo->nr_frags = k;
62396fa01ccdSSowmini Varadhan 	if (skb_has_frag_list(skb))
62406fa01ccdSSowmini Varadhan 		skb_clone_fraglist(skb);
62416fa01ccdSSowmini Varadhan 
62426fa01ccdSSowmini Varadhan 	/* split line is in frag list */
6243eabe8618SMiaohe Lin 	if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6244eabe8618SMiaohe Lin 		/* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6245eabe8618SMiaohe Lin 		if (skb_has_frag_list(skb))
6246eabe8618SMiaohe Lin 			kfree_skb_list(skb_shinfo(skb)->frag_list);
6247eabe8618SMiaohe Lin 		kfree(data);
6248eabe8618SMiaohe Lin 		return -ENOMEM;
62496fa01ccdSSowmini Varadhan 	}
62506fa01ccdSSowmini Varadhan 	skb_release_data(skb);
62516fa01ccdSSowmini Varadhan 
62526fa01ccdSSowmini Varadhan 	skb->head = data;
62536fa01ccdSSowmini Varadhan 	skb->head_frag = 0;
62546fa01ccdSSowmini Varadhan 	skb->data = data;
6255763087daSEric Dumazet 	skb_set_end_offset(skb, size);
62566fa01ccdSSowmini Varadhan 	skb_reset_tail_pointer(skb);
62576fa01ccdSSowmini Varadhan 	skb_headers_offset_update(skb, 0);
62586fa01ccdSSowmini Varadhan 	skb->cloned   = 0;
62596fa01ccdSSowmini Varadhan 	skb->hdr_len  = 0;
62606fa01ccdSSowmini Varadhan 	skb->nohdr    = 0;
62616fa01ccdSSowmini Varadhan 	skb->len -= off;
62626fa01ccdSSowmini Varadhan 	skb->data_len = skb->len;
62636fa01ccdSSowmini Varadhan 	atomic_set(&skb_shinfo(skb)->dataref, 1);
62646fa01ccdSSowmini Varadhan 	return 0;
62656fa01ccdSSowmini Varadhan }
62666fa01ccdSSowmini Varadhan 
62676fa01ccdSSowmini Varadhan /* remove len bytes from the beginning of the skb */
62686fa01ccdSSowmini Varadhan static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
62696fa01ccdSSowmini Varadhan {
62706fa01ccdSSowmini Varadhan 	int headlen = skb_headlen(skb);
62716fa01ccdSSowmini Varadhan 
62726fa01ccdSSowmini Varadhan 	if (len < headlen)
62736fa01ccdSSowmini Varadhan 		return pskb_carve_inside_header(skb, len, headlen, gfp);
62746fa01ccdSSowmini Varadhan 	else
62756fa01ccdSSowmini Varadhan 		return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
62766fa01ccdSSowmini Varadhan }
62776fa01ccdSSowmini Varadhan 
62786fa01ccdSSowmini Varadhan /* Extract to_copy bytes starting at off from skb, and return this in
62796fa01ccdSSowmini Varadhan  * a new skb
62806fa01ccdSSowmini Varadhan  */
62816fa01ccdSSowmini Varadhan struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
62826fa01ccdSSowmini Varadhan 			     int to_copy, gfp_t gfp)
62836fa01ccdSSowmini Varadhan {
62846fa01ccdSSowmini Varadhan 	struct sk_buff  *clone = skb_clone(skb, gfp);
62856fa01ccdSSowmini Varadhan 
62866fa01ccdSSowmini Varadhan 	if (!clone)
62876fa01ccdSSowmini Varadhan 		return NULL;
62886fa01ccdSSowmini Varadhan 
62896fa01ccdSSowmini Varadhan 	if (pskb_carve(clone, off, gfp) < 0 ||
62906fa01ccdSSowmini Varadhan 	    pskb_trim(clone, to_copy)) {
62916fa01ccdSSowmini Varadhan 		kfree_skb(clone);
62926fa01ccdSSowmini Varadhan 		return NULL;
62936fa01ccdSSowmini Varadhan 	}
62946fa01ccdSSowmini Varadhan 	return clone;
62956fa01ccdSSowmini Varadhan }
62966fa01ccdSSowmini Varadhan EXPORT_SYMBOL(pskb_extract);
6297c8c8b127SEric Dumazet 
6298c8c8b127SEric Dumazet /**
6299c8c8b127SEric Dumazet  * skb_condense - try to get rid of fragments/frag_list if possible
6300c8c8b127SEric Dumazet  * @skb: buffer
6301c8c8b127SEric Dumazet  *
6302c8c8b127SEric Dumazet  * Can be used to save memory before skb is added to a busy queue.
6303c8c8b127SEric Dumazet  * If packet has bytes in frags and enough tail room in skb->head,
6304c8c8b127SEric Dumazet  * pull all of them, so that we can free the frags right now and adjust
6305c8c8b127SEric Dumazet  * truesize.
6306c8c8b127SEric Dumazet  * Notes:
6307c8c8b127SEric Dumazet  *	We do not reallocate skb->head thus can not fail.
6308c8c8b127SEric Dumazet  *	Caller must re-evaluate skb->truesize if needed.
6309c8c8b127SEric Dumazet  */
6310c8c8b127SEric Dumazet void skb_condense(struct sk_buff *skb)
6311c8c8b127SEric Dumazet {
63123174fed9SEric Dumazet 	if (skb->data_len) {
63133174fed9SEric Dumazet 		if (skb->data_len > skb->end - skb->tail ||
6314c8c8b127SEric Dumazet 		    skb_cloned(skb))
6315c8c8b127SEric Dumazet 			return;
6316c8c8b127SEric Dumazet 
6317c8c8b127SEric Dumazet 		/* Nice, we can free page frag(s) right now */
6318c8c8b127SEric Dumazet 		__pskb_pull_tail(skb, skb->data_len);
63193174fed9SEric Dumazet 	}
63203174fed9SEric Dumazet 	/* At this point, skb->truesize might be over estimated,
63213174fed9SEric Dumazet 	 * because skb had a fragment, and fragments do not tell
63223174fed9SEric Dumazet 	 * their truesize.
63233174fed9SEric Dumazet 	 * When we pulled its content into skb->head, fragment
63243174fed9SEric Dumazet 	 * was freed, but __pskb_pull_tail() could not possibly
63253174fed9SEric Dumazet 	 * adjust skb->truesize, not knowing the frag truesize.
6326c8c8b127SEric Dumazet 	 */
6327c8c8b127SEric Dumazet 	skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6328c8c8b127SEric Dumazet }
6329df5042f4SFlorian Westphal 
6330df5042f4SFlorian Westphal #ifdef CONFIG_SKB_EXTENSIONS
6331df5042f4SFlorian Westphal static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6332df5042f4SFlorian Westphal {
6333df5042f4SFlorian Westphal 	return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6334df5042f4SFlorian Westphal }
6335df5042f4SFlorian Westphal 
63368b69a803SPaolo Abeni /**
63378b69a803SPaolo Abeni  * __skb_ext_alloc - allocate a new skb extensions storage
63388b69a803SPaolo Abeni  *
63394930f483SFlorian Westphal  * @flags: See kmalloc().
63404930f483SFlorian Westphal  *
63418b69a803SPaolo Abeni  * Returns the newly allocated pointer. The pointer can later attached to a
63428b69a803SPaolo Abeni  * skb via __skb_ext_set().
63438b69a803SPaolo Abeni  * Note: caller must handle the skb_ext as an opaque data.
63448b69a803SPaolo Abeni  */
63454930f483SFlorian Westphal struct skb_ext *__skb_ext_alloc(gfp_t flags)
6346df5042f4SFlorian Westphal {
63474930f483SFlorian Westphal 	struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6348df5042f4SFlorian Westphal 
6349df5042f4SFlorian Westphal 	if (new) {
6350df5042f4SFlorian Westphal 		memset(new->offset, 0, sizeof(new->offset));
6351df5042f4SFlorian Westphal 		refcount_set(&new->refcnt, 1);
6352df5042f4SFlorian Westphal 	}
6353df5042f4SFlorian Westphal 
6354df5042f4SFlorian Westphal 	return new;
6355df5042f4SFlorian Westphal }
6356df5042f4SFlorian Westphal 
63574165079bSFlorian Westphal static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
63584165079bSFlorian Westphal 					 unsigned int old_active)
6359df5042f4SFlorian Westphal {
6360df5042f4SFlorian Westphal 	struct skb_ext *new;
6361df5042f4SFlorian Westphal 
6362df5042f4SFlorian Westphal 	if (refcount_read(&old->refcnt) == 1)
6363df5042f4SFlorian Westphal 		return old;
6364df5042f4SFlorian Westphal 
6365df5042f4SFlorian Westphal 	new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6366df5042f4SFlorian Westphal 	if (!new)
6367df5042f4SFlorian Westphal 		return NULL;
6368df5042f4SFlorian Westphal 
6369df5042f4SFlorian Westphal 	memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6370df5042f4SFlorian Westphal 	refcount_set(&new->refcnt, 1);
6371df5042f4SFlorian Westphal 
63724165079bSFlorian Westphal #ifdef CONFIG_XFRM
63734165079bSFlorian Westphal 	if (old_active & (1 << SKB_EXT_SEC_PATH)) {
63744165079bSFlorian Westphal 		struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
63754165079bSFlorian Westphal 		unsigned int i;
63764165079bSFlorian Westphal 
63774165079bSFlorian Westphal 		for (i = 0; i < sp->len; i++)
63784165079bSFlorian Westphal 			xfrm_state_hold(sp->xvec[i]);
63794165079bSFlorian Westphal 	}
63804165079bSFlorian Westphal #endif
6381df5042f4SFlorian Westphal 	__skb_ext_put(old);
6382df5042f4SFlorian Westphal 	return new;
6383df5042f4SFlorian Westphal }
6384df5042f4SFlorian Westphal 
6385df5042f4SFlorian Westphal /**
63868b69a803SPaolo Abeni  * __skb_ext_set - attach the specified extension storage to this skb
63878b69a803SPaolo Abeni  * @skb: buffer
63888b69a803SPaolo Abeni  * @id: extension id
63898b69a803SPaolo Abeni  * @ext: extension storage previously allocated via __skb_ext_alloc()
63908b69a803SPaolo Abeni  *
63918b69a803SPaolo Abeni  * Existing extensions, if any, are cleared.
63928b69a803SPaolo Abeni  *
63938b69a803SPaolo Abeni  * Returns the pointer to the extension.
63948b69a803SPaolo Abeni  */
63958b69a803SPaolo Abeni void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
63968b69a803SPaolo Abeni 		    struct skb_ext *ext)
63978b69a803SPaolo Abeni {
63988b69a803SPaolo Abeni 	unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
63998b69a803SPaolo Abeni 
64008b69a803SPaolo Abeni 	skb_ext_put(skb);
64018b69a803SPaolo Abeni 	newlen = newoff + skb_ext_type_len[id];
64028b69a803SPaolo Abeni 	ext->chunks = newlen;
64038b69a803SPaolo Abeni 	ext->offset[id] = newoff;
64048b69a803SPaolo Abeni 	skb->extensions = ext;
64058b69a803SPaolo Abeni 	skb->active_extensions = 1 << id;
64068b69a803SPaolo Abeni 	return skb_ext_get_ptr(ext, id);
64078b69a803SPaolo Abeni }
64088b69a803SPaolo Abeni 
64098b69a803SPaolo Abeni /**
6410df5042f4SFlorian Westphal  * skb_ext_add - allocate space for given extension, COW if needed
6411df5042f4SFlorian Westphal  * @skb: buffer
6412df5042f4SFlorian Westphal  * @id: extension to allocate space for
6413df5042f4SFlorian Westphal  *
6414df5042f4SFlorian Westphal  * Allocates enough space for the given extension.
6415df5042f4SFlorian Westphal  * If the extension is already present, a pointer to that extension
6416df5042f4SFlorian Westphal  * is returned.
6417df5042f4SFlorian Westphal  *
6418df5042f4SFlorian Westphal  * If the skb was cloned, COW applies and the returned memory can be
6419df5042f4SFlorian Westphal  * modified without changing the extension space of clones buffers.
6420df5042f4SFlorian Westphal  *
6421df5042f4SFlorian Westphal  * Returns pointer to the extension or NULL on allocation failure.
6422df5042f4SFlorian Westphal  */
6423df5042f4SFlorian Westphal void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6424df5042f4SFlorian Westphal {
6425df5042f4SFlorian Westphal 	struct skb_ext *new, *old = NULL;
6426df5042f4SFlorian Westphal 	unsigned int newlen, newoff;
6427df5042f4SFlorian Westphal 
6428df5042f4SFlorian Westphal 	if (skb->active_extensions) {
6429df5042f4SFlorian Westphal 		old = skb->extensions;
6430df5042f4SFlorian Westphal 
64314165079bSFlorian Westphal 		new = skb_ext_maybe_cow(old, skb->active_extensions);
6432df5042f4SFlorian Westphal 		if (!new)
6433df5042f4SFlorian Westphal 			return NULL;
6434df5042f4SFlorian Westphal 
6435682ec859SPaolo Abeni 		if (__skb_ext_exist(new, id))
6436df5042f4SFlorian Westphal 			goto set_active;
6437df5042f4SFlorian Westphal 
6438e94e50bdSPaolo Abeni 		newoff = new->chunks;
6439df5042f4SFlorian Westphal 	} else {
6440df5042f4SFlorian Westphal 		newoff = SKB_EXT_CHUNKSIZEOF(*new);
6441df5042f4SFlorian Westphal 
64424930f483SFlorian Westphal 		new = __skb_ext_alloc(GFP_ATOMIC);
6443df5042f4SFlorian Westphal 		if (!new)
6444df5042f4SFlorian Westphal 			return NULL;
6445df5042f4SFlorian Westphal 	}
6446df5042f4SFlorian Westphal 
6447df5042f4SFlorian Westphal 	newlen = newoff + skb_ext_type_len[id];
6448df5042f4SFlorian Westphal 	new->chunks = newlen;
6449df5042f4SFlorian Westphal 	new->offset[id] = newoff;
6450df5042f4SFlorian Westphal set_active:
6451b0999f38SPaolo Abeni 	skb->slow_gro = 1;
6452682ec859SPaolo Abeni 	skb->extensions = new;
6453df5042f4SFlorian Westphal 	skb->active_extensions |= 1 << id;
6454df5042f4SFlorian Westphal 	return skb_ext_get_ptr(new, id);
6455df5042f4SFlorian Westphal }
6456df5042f4SFlorian Westphal EXPORT_SYMBOL(skb_ext_add);
6457df5042f4SFlorian Westphal 
64584165079bSFlorian Westphal #ifdef CONFIG_XFRM
64594165079bSFlorian Westphal static void skb_ext_put_sp(struct sec_path *sp)
64604165079bSFlorian Westphal {
64614165079bSFlorian Westphal 	unsigned int i;
64624165079bSFlorian Westphal 
64634165079bSFlorian Westphal 	for (i = 0; i < sp->len; i++)
64644165079bSFlorian Westphal 		xfrm_state_put(sp->xvec[i]);
64654165079bSFlorian Westphal }
64664165079bSFlorian Westphal #endif
64674165079bSFlorian Westphal 
646878476d31SJeremy Kerr #ifdef CONFIG_MCTP_FLOWS
646978476d31SJeremy Kerr static void skb_ext_put_mctp(struct mctp_flow *flow)
647078476d31SJeremy Kerr {
647178476d31SJeremy Kerr 	if (flow->key)
647278476d31SJeremy Kerr 		mctp_key_unref(flow->key);
647378476d31SJeremy Kerr }
647478476d31SJeremy Kerr #endif
647578476d31SJeremy Kerr 
6476df5042f4SFlorian Westphal void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6477df5042f4SFlorian Westphal {
6478df5042f4SFlorian Westphal 	struct skb_ext *ext = skb->extensions;
6479df5042f4SFlorian Westphal 
6480df5042f4SFlorian Westphal 	skb->active_extensions &= ~(1 << id);
6481df5042f4SFlorian Westphal 	if (skb->active_extensions == 0) {
6482df5042f4SFlorian Westphal 		skb->extensions = NULL;
6483df5042f4SFlorian Westphal 		__skb_ext_put(ext);
64844165079bSFlorian Westphal #ifdef CONFIG_XFRM
64854165079bSFlorian Westphal 	} else if (id == SKB_EXT_SEC_PATH &&
64864165079bSFlorian Westphal 		   refcount_read(&ext->refcnt) == 1) {
64874165079bSFlorian Westphal 		struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
64884165079bSFlorian Westphal 
64894165079bSFlorian Westphal 		skb_ext_put_sp(sp);
64904165079bSFlorian Westphal 		sp->len = 0;
64914165079bSFlorian Westphal #endif
6492df5042f4SFlorian Westphal 	}
6493df5042f4SFlorian Westphal }
6494df5042f4SFlorian Westphal EXPORT_SYMBOL(__skb_ext_del);
6495df5042f4SFlorian Westphal 
6496df5042f4SFlorian Westphal void __skb_ext_put(struct skb_ext *ext)
6497df5042f4SFlorian Westphal {
6498df5042f4SFlorian Westphal 	/* If this is last clone, nothing can increment
6499df5042f4SFlorian Westphal 	 * it after check passes.  Avoids one atomic op.
6500df5042f4SFlorian Westphal 	 */
6501df5042f4SFlorian Westphal 	if (refcount_read(&ext->refcnt) == 1)
6502df5042f4SFlorian Westphal 		goto free_now;
6503df5042f4SFlorian Westphal 
6504df5042f4SFlorian Westphal 	if (!refcount_dec_and_test(&ext->refcnt))
6505df5042f4SFlorian Westphal 		return;
6506df5042f4SFlorian Westphal free_now:
65074165079bSFlorian Westphal #ifdef CONFIG_XFRM
65084165079bSFlorian Westphal 	if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
65094165079bSFlorian Westphal 		skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
65104165079bSFlorian Westphal #endif
651178476d31SJeremy Kerr #ifdef CONFIG_MCTP_FLOWS
651278476d31SJeremy Kerr 	if (__skb_ext_exist(ext, SKB_EXT_MCTP))
651378476d31SJeremy Kerr 		skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
651478476d31SJeremy Kerr #endif
65154165079bSFlorian Westphal 
6516df5042f4SFlorian Westphal 	kmem_cache_free(skbuff_ext_cache, ext);
6517df5042f4SFlorian Westphal }
6518df5042f4SFlorian Westphal EXPORT_SYMBOL(__skb_ext_put);
6519df5042f4SFlorian Westphal #endif /* CONFIG_SKB_EXTENSIONS */
652068822bdfSEric Dumazet 
652168822bdfSEric Dumazet /**
652268822bdfSEric Dumazet  * skb_attempt_defer_free - queue skb for remote freeing
652368822bdfSEric Dumazet  * @skb: buffer
652468822bdfSEric Dumazet  *
652568822bdfSEric Dumazet  * Put @skb in a per-cpu list, using the cpu which
652668822bdfSEric Dumazet  * allocated the skb/pages to reduce false sharing
652768822bdfSEric Dumazet  * and memory zone spinlock contention.
652868822bdfSEric Dumazet  */
652968822bdfSEric Dumazet void skb_attempt_defer_free(struct sk_buff *skb)
653068822bdfSEric Dumazet {
653168822bdfSEric Dumazet 	int cpu = skb->alloc_cpu;
653268822bdfSEric Dumazet 	struct softnet_data *sd;
653368822bdfSEric Dumazet 	unsigned long flags;
653439564c3fSEric Dumazet 	unsigned int defer_max;
653568822bdfSEric Dumazet 	bool kick;
653668822bdfSEric Dumazet 
653768822bdfSEric Dumazet 	if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
653868822bdfSEric Dumazet 	    !cpu_online(cpu) ||
653968822bdfSEric Dumazet 	    cpu == raw_smp_processor_id()) {
654039564c3fSEric Dumazet nodefer:	__kfree_skb(skb);
654168822bdfSEric Dumazet 		return;
654268822bdfSEric Dumazet 	}
654368822bdfSEric Dumazet 
654468822bdfSEric Dumazet 	sd = &per_cpu(softnet_data, cpu);
654539564c3fSEric Dumazet 	defer_max = READ_ONCE(sysctl_skb_defer_max);
654639564c3fSEric Dumazet 	if (READ_ONCE(sd->defer_count) >= defer_max)
654739564c3fSEric Dumazet 		goto nodefer;
654839564c3fSEric Dumazet 
654968822bdfSEric Dumazet 	spin_lock_irqsave(&sd->defer_lock, flags);
6550c09b0cd2SJakub Kicinski 	/* Send an IPI every time queue reaches half capacity. */
6551c09b0cd2SJakub Kicinski 	kick = sd->defer_count == (defer_max >> 1);
6552c09b0cd2SJakub Kicinski 	/* Paired with the READ_ONCE() few lines above */
6553c09b0cd2SJakub Kicinski 	WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6554c09b0cd2SJakub Kicinski 
655568822bdfSEric Dumazet 	skb->next = sd->defer_list;
655668822bdfSEric Dumazet 	/* Paired with READ_ONCE() in skb_defer_free_flush() */
655768822bdfSEric Dumazet 	WRITE_ONCE(sd->defer_list, skb);
655868822bdfSEric Dumazet 	spin_unlock_irqrestore(&sd->defer_lock, flags);
655968822bdfSEric Dumazet 
656068822bdfSEric Dumazet 	/* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
656168822bdfSEric Dumazet 	 * if we are unlucky enough (this seems very unlikely).
656268822bdfSEric Dumazet 	 */
656397e719a8SEric Dumazet 	if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
656468822bdfSEric Dumazet 		smp_call_function_single_async(cpu, &sd->defer_csd);
656568822bdfSEric Dumazet }
6566