xref: /openbmc/linux/net/core/skbuff.c (revision 35b288d6)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  *	Routines having to do with the 'struct sk_buff' memory handlers.
4  *
5  *	Authors:	Alan Cox <alan@lxorguk.ukuu.org.uk>
6  *			Florian La Roche <rzsfl@rz.uni-sb.de>
7  *
8  *	Fixes:
9  *		Alan Cox	:	Fixed the worst of the load
10  *					balancer bugs.
11  *		Dave Platt	:	Interrupt stacking fix.
12  *	Richard Kooijman	:	Timestamp fixes.
13  *		Alan Cox	:	Changed buffer format.
14  *		Alan Cox	:	destructor hook for AF_UNIX etc.
15  *		Linus Torvalds	:	Better skb_clone.
16  *		Alan Cox	:	Added skb_copy.
17  *		Alan Cox	:	Added all the changed routines Linus
18  *					only put in the headers
19  *		Ray VanTassle	:	Fixed --skb->lock in free
20  *		Alan Cox	:	skb_copy copy arp field
21  *		Andi Kleen	:	slabified it.
22  *		Robert Olsson	:	Removed skb_head_pool
23  *
24  *	NOTE:
25  *		The __skb_ routines should be called with interrupts
26  *	disabled, or you better be *real* sure that the operation is atomic
27  *	with respect to whatever list is being frobbed (e.g. via lock_sock()
28  *	or via disabling bottom half handlers, etc).
29  */
30 
31 /*
32  *	The functions in this file will not compile correctly with gcc 2.4.x
33  */
34 
35 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
36 
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/kernel.h>
40 #include <linux/mm.h>
41 #include <linux/interrupt.h>
42 #include <linux/in.h>
43 #include <linux/inet.h>
44 #include <linux/slab.h>
45 #include <linux/tcp.h>
46 #include <linux/udp.h>
47 #include <linux/sctp.h>
48 #include <linux/netdevice.h>
49 #ifdef CONFIG_NET_CLS_ACT
50 #include <net/pkt_sched.h>
51 #endif
52 #include <linux/string.h>
53 #include <linux/skbuff.h>
54 #include <linux/splice.h>
55 #include <linux/cache.h>
56 #include <linux/rtnetlink.h>
57 #include <linux/init.h>
58 #include <linux/scatterlist.h>
59 #include <linux/errqueue.h>
60 #include <linux/prefetch.h>
61 #include <linux/if_vlan.h>
62 #include <linux/mpls.h>
63 #include <linux/kcov.h>
64 
65 #include <net/protocol.h>
66 #include <net/dst.h>
67 #include <net/sock.h>
68 #include <net/checksum.h>
69 #include <net/ip6_checksum.h>
70 #include <net/xfrm.h>
71 #include <net/mpls.h>
72 #include <net/mptcp.h>
73 #include <net/mctp.h>
74 #include <net/page_pool.h>
75 
76 #include <linux/uaccess.h>
77 #include <trace/events/skb.h>
78 #include <linux/highmem.h>
79 #include <linux/capability.h>
80 #include <linux/user_namespace.h>
81 #include <linux/indirect_call_wrapper.h>
82 #include <linux/textsearch.h>
83 
84 #include "dev.h"
85 #include "sock_destructor.h"
86 
87 struct kmem_cache *skbuff_cache __ro_after_init;
88 static struct kmem_cache *skbuff_fclone_cache __ro_after_init;
89 #ifdef CONFIG_SKB_EXTENSIONS
90 static struct kmem_cache *skbuff_ext_cache __ro_after_init;
91 #endif
92 
93 /* skb_small_head_cache and related code is only supported
94  * for CONFIG_SLAB and CONFIG_SLUB.
95  * As soon as SLOB is removed from the kernel, we can clean up this.
96  */
97 #if !defined(CONFIG_SLOB)
98 # define HAVE_SKB_SMALL_HEAD_CACHE 1
99 #endif
100 
101 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
102 static struct kmem_cache *skb_small_head_cache __ro_after_init;
103 
104 #define SKB_SMALL_HEAD_SIZE SKB_HEAD_ALIGN(MAX_TCP_HEADER)
105 
106 /* We want SKB_SMALL_HEAD_CACHE_SIZE to not be a power of two.
107  * This should ensure that SKB_SMALL_HEAD_HEADROOM is a unique
108  * size, and we can differentiate heads from skb_small_head_cache
109  * vs system slabs by looking at their size (skb_end_offset()).
110  */
111 #define SKB_SMALL_HEAD_CACHE_SIZE					\
112 	(is_power_of_2(SKB_SMALL_HEAD_SIZE) ?			\
113 		(SKB_SMALL_HEAD_SIZE + L1_CACHE_BYTES) :	\
114 		SKB_SMALL_HEAD_SIZE)
115 
116 #define SKB_SMALL_HEAD_HEADROOM						\
117 	SKB_WITH_OVERHEAD(SKB_SMALL_HEAD_CACHE_SIZE)
118 #endif /* HAVE_SKB_SMALL_HEAD_CACHE */
119 
120 int sysctl_max_skb_frags __read_mostly = MAX_SKB_FRAGS;
121 EXPORT_SYMBOL(sysctl_max_skb_frags);
122 
123 #undef FN
124 #define FN(reason) [SKB_DROP_REASON_##reason] = #reason,
125 const char * const drop_reasons[] = {
126 	[SKB_CONSUMED] = "CONSUMED",
127 	DEFINE_DROP_REASON(FN, FN)
128 };
129 EXPORT_SYMBOL(drop_reasons);
130 
131 /**
132  *	skb_panic - private function for out-of-line support
133  *	@skb:	buffer
134  *	@sz:	size
135  *	@addr:	address
136  *	@msg:	skb_over_panic or skb_under_panic
137  *
138  *	Out-of-line support for skb_put() and skb_push().
139  *	Called via the wrapper skb_over_panic() or skb_under_panic().
140  *	Keep out of line to prevent kernel bloat.
141  *	__builtin_return_address is not used because it is not always reliable.
142  */
143 static void skb_panic(struct sk_buff *skb, unsigned int sz, void *addr,
144 		      const char msg[])
145 {
146 	pr_emerg("%s: text:%px len:%d put:%d head:%px data:%px tail:%#lx end:%#lx dev:%s\n",
147 		 msg, addr, skb->len, sz, skb->head, skb->data,
148 		 (unsigned long)skb->tail, (unsigned long)skb->end,
149 		 skb->dev ? skb->dev->name : "<NULL>");
150 	BUG();
151 }
152 
153 static void skb_over_panic(struct sk_buff *skb, unsigned int sz, void *addr)
154 {
155 	skb_panic(skb, sz, addr, __func__);
156 }
157 
158 static void skb_under_panic(struct sk_buff *skb, unsigned int sz, void *addr)
159 {
160 	skb_panic(skb, sz, addr, __func__);
161 }
162 
163 #define NAPI_SKB_CACHE_SIZE	64
164 #define NAPI_SKB_CACHE_BULK	16
165 #define NAPI_SKB_CACHE_HALF	(NAPI_SKB_CACHE_SIZE / 2)
166 
167 #if PAGE_SIZE == SZ_4K
168 
169 #define NAPI_HAS_SMALL_PAGE_FRAG	1
170 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc)	((nc).pfmemalloc)
171 
172 /* specialized page frag allocator using a single order 0 page
173  * and slicing it into 1K sized fragment. Constrained to systems
174  * with a very limited amount of 1K fragments fitting a single
175  * page - to avoid excessive truesize underestimation
176  */
177 
178 struct page_frag_1k {
179 	void *va;
180 	u16 offset;
181 	bool pfmemalloc;
182 };
183 
184 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp)
185 {
186 	struct page *page;
187 	int offset;
188 
189 	offset = nc->offset - SZ_1K;
190 	if (likely(offset >= 0))
191 		goto use_frag;
192 
193 	page = alloc_pages_node(NUMA_NO_NODE, gfp, 0);
194 	if (!page)
195 		return NULL;
196 
197 	nc->va = page_address(page);
198 	nc->pfmemalloc = page_is_pfmemalloc(page);
199 	offset = PAGE_SIZE - SZ_1K;
200 	page_ref_add(page, offset / SZ_1K);
201 
202 use_frag:
203 	nc->offset = offset;
204 	return nc->va + offset;
205 }
206 #else
207 
208 /* the small page is actually unused in this build; add dummy helpers
209  * to please the compiler and avoid later preprocessor's conditionals
210  */
211 #define NAPI_HAS_SMALL_PAGE_FRAG	0
212 #define NAPI_SMALL_PAGE_PFMEMALLOC(nc)	false
213 
214 struct page_frag_1k {
215 };
216 
217 static void *page_frag_alloc_1k(struct page_frag_1k *nc, gfp_t gfp_mask)
218 {
219 	return NULL;
220 }
221 
222 #endif
223 
224 struct napi_alloc_cache {
225 	struct page_frag_cache page;
226 	struct page_frag_1k page_small;
227 	unsigned int skb_count;
228 	void *skb_cache[NAPI_SKB_CACHE_SIZE];
229 };
230 
231 static DEFINE_PER_CPU(struct page_frag_cache, netdev_alloc_cache);
232 static DEFINE_PER_CPU(struct napi_alloc_cache, napi_alloc_cache);
233 
234 /* Double check that napi_get_frags() allocates skbs with
235  * skb->head being backed by slab, not a page fragment.
236  * This is to make sure bug fixed in 3226b158e67c
237  * ("net: avoid 32 x truesize under-estimation for tiny skbs")
238  * does not accidentally come back.
239  */
240 void napi_get_frags_check(struct napi_struct *napi)
241 {
242 	struct sk_buff *skb;
243 
244 	local_bh_disable();
245 	skb = napi_get_frags(napi);
246 	WARN_ON_ONCE(!NAPI_HAS_SMALL_PAGE_FRAG && skb && skb->head_frag);
247 	napi_free_frags(napi);
248 	local_bh_enable();
249 }
250 
251 void *__napi_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
252 {
253 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
254 
255 	fragsz = SKB_DATA_ALIGN(fragsz);
256 
257 	return page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
258 }
259 EXPORT_SYMBOL(__napi_alloc_frag_align);
260 
261 void *__netdev_alloc_frag_align(unsigned int fragsz, unsigned int align_mask)
262 {
263 	void *data;
264 
265 	fragsz = SKB_DATA_ALIGN(fragsz);
266 	if (in_hardirq() || irqs_disabled()) {
267 		struct page_frag_cache *nc = this_cpu_ptr(&netdev_alloc_cache);
268 
269 		data = page_frag_alloc_align(nc, fragsz, GFP_ATOMIC, align_mask);
270 	} else {
271 		struct napi_alloc_cache *nc;
272 
273 		local_bh_disable();
274 		nc = this_cpu_ptr(&napi_alloc_cache);
275 		data = page_frag_alloc_align(&nc->page, fragsz, GFP_ATOMIC, align_mask);
276 		local_bh_enable();
277 	}
278 	return data;
279 }
280 EXPORT_SYMBOL(__netdev_alloc_frag_align);
281 
282 static struct sk_buff *napi_skb_cache_get(void)
283 {
284 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
285 	struct sk_buff *skb;
286 
287 	if (unlikely(!nc->skb_count)) {
288 		nc->skb_count = kmem_cache_alloc_bulk(skbuff_cache,
289 						      GFP_ATOMIC,
290 						      NAPI_SKB_CACHE_BULK,
291 						      nc->skb_cache);
292 		if (unlikely(!nc->skb_count))
293 			return NULL;
294 	}
295 
296 	skb = nc->skb_cache[--nc->skb_count];
297 	kasan_unpoison_object_data(skbuff_cache, skb);
298 
299 	return skb;
300 }
301 
302 static inline void __finalize_skb_around(struct sk_buff *skb, void *data,
303 					 unsigned int size)
304 {
305 	struct skb_shared_info *shinfo;
306 
307 	size -= SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
308 
309 	/* Assumes caller memset cleared SKB */
310 	skb->truesize = SKB_TRUESIZE(size);
311 	refcount_set(&skb->users, 1);
312 	skb->head = data;
313 	skb->data = data;
314 	skb_reset_tail_pointer(skb);
315 	skb_set_end_offset(skb, size);
316 	skb->mac_header = (typeof(skb->mac_header))~0U;
317 	skb->transport_header = (typeof(skb->transport_header))~0U;
318 	skb->alloc_cpu = raw_smp_processor_id();
319 	/* make sure we initialize shinfo sequentially */
320 	shinfo = skb_shinfo(skb);
321 	memset(shinfo, 0, offsetof(struct skb_shared_info, dataref));
322 	atomic_set(&shinfo->dataref, 1);
323 
324 	skb_set_kcov_handle(skb, kcov_common_handle());
325 }
326 
327 static inline void *__slab_build_skb(struct sk_buff *skb, void *data,
328 				     unsigned int *size)
329 {
330 	void *resized;
331 
332 	/* Must find the allocation size (and grow it to match). */
333 	*size = ksize(data);
334 	/* krealloc() will immediately return "data" when
335 	 * "ksize(data)" is requested: it is the existing upper
336 	 * bounds. As a result, GFP_ATOMIC will be ignored. Note
337 	 * that this "new" pointer needs to be passed back to the
338 	 * caller for use so the __alloc_size hinting will be
339 	 * tracked correctly.
340 	 */
341 	resized = krealloc(data, *size, GFP_ATOMIC);
342 	WARN_ON_ONCE(resized != data);
343 	return resized;
344 }
345 
346 /* build_skb() variant which can operate on slab buffers.
347  * Note that this should be used sparingly as slab buffers
348  * cannot be combined efficiently by GRO!
349  */
350 struct sk_buff *slab_build_skb(void *data)
351 {
352 	struct sk_buff *skb;
353 	unsigned int size;
354 
355 	skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
356 	if (unlikely(!skb))
357 		return NULL;
358 
359 	memset(skb, 0, offsetof(struct sk_buff, tail));
360 	data = __slab_build_skb(skb, data, &size);
361 	__finalize_skb_around(skb, data, size);
362 
363 	return skb;
364 }
365 EXPORT_SYMBOL(slab_build_skb);
366 
367 /* Caller must provide SKB that is memset cleared */
368 static void __build_skb_around(struct sk_buff *skb, void *data,
369 			       unsigned int frag_size)
370 {
371 	unsigned int size = frag_size;
372 
373 	/* frag_size == 0 is considered deprecated now. Callers
374 	 * using slab buffer should use slab_build_skb() instead.
375 	 */
376 	if (WARN_ONCE(size == 0, "Use slab_build_skb() instead"))
377 		data = __slab_build_skb(skb, data, &size);
378 
379 	__finalize_skb_around(skb, data, size);
380 }
381 
382 /**
383  * __build_skb - build a network buffer
384  * @data: data buffer provided by caller
385  * @frag_size: size of data (must not be 0)
386  *
387  * Allocate a new &sk_buff. Caller provides space holding head and
388  * skb_shared_info. @data must have been allocated from the page
389  * allocator or vmalloc(). (A @frag_size of 0 to indicate a kmalloc()
390  * allocation is deprecated, and callers should use slab_build_skb()
391  * instead.)
392  * The return is the new skb buffer.
393  * On a failure the return is %NULL, and @data is not freed.
394  * Notes :
395  *  Before IO, driver allocates only data buffer where NIC put incoming frame
396  *  Driver should add room at head (NET_SKB_PAD) and
397  *  MUST add room at tail (SKB_DATA_ALIGN(skb_shared_info))
398  *  After IO, driver calls build_skb(), to allocate sk_buff and populate it
399  *  before giving packet to stack.
400  *  RX rings only contains data buffers, not full skbs.
401  */
402 struct sk_buff *__build_skb(void *data, unsigned int frag_size)
403 {
404 	struct sk_buff *skb;
405 
406 	skb = kmem_cache_alloc(skbuff_cache, GFP_ATOMIC);
407 	if (unlikely(!skb))
408 		return NULL;
409 
410 	memset(skb, 0, offsetof(struct sk_buff, tail));
411 	__build_skb_around(skb, data, frag_size);
412 
413 	return skb;
414 }
415 
416 /* build_skb() is wrapper over __build_skb(), that specifically
417  * takes care of skb->head and skb->pfmemalloc
418  */
419 struct sk_buff *build_skb(void *data, unsigned int frag_size)
420 {
421 	struct sk_buff *skb = __build_skb(data, frag_size);
422 
423 	if (likely(skb && frag_size)) {
424 		skb->head_frag = 1;
425 		skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
426 	}
427 	return skb;
428 }
429 EXPORT_SYMBOL(build_skb);
430 
431 /**
432  * build_skb_around - build a network buffer around provided skb
433  * @skb: sk_buff provide by caller, must be memset cleared
434  * @data: data buffer provided by caller
435  * @frag_size: size of data
436  */
437 struct sk_buff *build_skb_around(struct sk_buff *skb,
438 				 void *data, unsigned int frag_size)
439 {
440 	if (unlikely(!skb))
441 		return NULL;
442 
443 	__build_skb_around(skb, data, frag_size);
444 
445 	if (frag_size) {
446 		skb->head_frag = 1;
447 		skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
448 	}
449 	return skb;
450 }
451 EXPORT_SYMBOL(build_skb_around);
452 
453 /**
454  * __napi_build_skb - build a network buffer
455  * @data: data buffer provided by caller
456  * @frag_size: size of data
457  *
458  * Version of __build_skb() that uses NAPI percpu caches to obtain
459  * skbuff_head instead of inplace allocation.
460  *
461  * Returns a new &sk_buff on success, %NULL on allocation failure.
462  */
463 static struct sk_buff *__napi_build_skb(void *data, unsigned int frag_size)
464 {
465 	struct sk_buff *skb;
466 
467 	skb = napi_skb_cache_get();
468 	if (unlikely(!skb))
469 		return NULL;
470 
471 	memset(skb, 0, offsetof(struct sk_buff, tail));
472 	__build_skb_around(skb, data, frag_size);
473 
474 	return skb;
475 }
476 
477 /**
478  * napi_build_skb - build a network buffer
479  * @data: data buffer provided by caller
480  * @frag_size: size of data
481  *
482  * Version of __napi_build_skb() that takes care of skb->head_frag
483  * and skb->pfmemalloc when the data is a page or page fragment.
484  *
485  * Returns a new &sk_buff on success, %NULL on allocation failure.
486  */
487 struct sk_buff *napi_build_skb(void *data, unsigned int frag_size)
488 {
489 	struct sk_buff *skb = __napi_build_skb(data, frag_size);
490 
491 	if (likely(skb) && frag_size) {
492 		skb->head_frag = 1;
493 		skb_propagate_pfmemalloc(virt_to_head_page(data), skb);
494 	}
495 
496 	return skb;
497 }
498 EXPORT_SYMBOL(napi_build_skb);
499 
500 /*
501  * kmalloc_reserve is a wrapper around kmalloc_node_track_caller that tells
502  * the caller if emergency pfmemalloc reserves are being used. If it is and
503  * the socket is later found to be SOCK_MEMALLOC then PFMEMALLOC reserves
504  * may be used. Otherwise, the packet data may be discarded until enough
505  * memory is free
506  */
507 static void *kmalloc_reserve(unsigned int *size, gfp_t flags, int node,
508 			     bool *pfmemalloc)
509 {
510 	bool ret_pfmemalloc = false;
511 	unsigned int obj_size;
512 	void *obj;
513 
514 	obj_size = SKB_HEAD_ALIGN(*size);
515 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
516 	if (obj_size <= SKB_SMALL_HEAD_CACHE_SIZE &&
517 	    !(flags & KMALLOC_NOT_NORMAL_BITS)) {
518 		obj = kmem_cache_alloc_node(skb_small_head_cache,
519 				flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
520 				node);
521 		*size = SKB_SMALL_HEAD_CACHE_SIZE;
522 		if (obj || !(gfp_pfmemalloc_allowed(flags)))
523 			goto out;
524 		/* Try again but now we are using pfmemalloc reserves */
525 		ret_pfmemalloc = true;
526 		obj = kmem_cache_alloc_node(skb_small_head_cache, flags, node);
527 		goto out;
528 	}
529 #endif
530 	*size = obj_size = kmalloc_size_roundup(obj_size);
531 	/*
532 	 * Try a regular allocation, when that fails and we're not entitled
533 	 * to the reserves, fail.
534 	 */
535 	obj = kmalloc_node_track_caller(obj_size,
536 					flags | __GFP_NOMEMALLOC | __GFP_NOWARN,
537 					node);
538 	if (obj || !(gfp_pfmemalloc_allowed(flags)))
539 		goto out;
540 
541 	/* Try again but now we are using pfmemalloc reserves */
542 	ret_pfmemalloc = true;
543 	obj = kmalloc_node_track_caller(obj_size, flags, node);
544 
545 out:
546 	if (pfmemalloc)
547 		*pfmemalloc = ret_pfmemalloc;
548 
549 	return obj;
550 }
551 
552 /* 	Allocate a new skbuff. We do this ourselves so we can fill in a few
553  *	'private' fields and also do memory statistics to find all the
554  *	[BEEP] leaks.
555  *
556  */
557 
558 /**
559  *	__alloc_skb	-	allocate a network buffer
560  *	@size: size to allocate
561  *	@gfp_mask: allocation mask
562  *	@flags: If SKB_ALLOC_FCLONE is set, allocate from fclone cache
563  *		instead of head cache and allocate a cloned (child) skb.
564  *		If SKB_ALLOC_RX is set, __GFP_MEMALLOC will be used for
565  *		allocations in case the data is required for writeback
566  *	@node: numa node to allocate memory on
567  *
568  *	Allocate a new &sk_buff. The returned buffer has no headroom and a
569  *	tail room of at least size bytes. The object has a reference count
570  *	of one. The return is the buffer. On a failure the return is %NULL.
571  *
572  *	Buffers may only be allocated from interrupts using a @gfp_mask of
573  *	%GFP_ATOMIC.
574  */
575 struct sk_buff *__alloc_skb(unsigned int size, gfp_t gfp_mask,
576 			    int flags, int node)
577 {
578 	struct kmem_cache *cache;
579 	struct sk_buff *skb;
580 	bool pfmemalloc;
581 	u8 *data;
582 
583 	cache = (flags & SKB_ALLOC_FCLONE)
584 		? skbuff_fclone_cache : skbuff_cache;
585 
586 	if (sk_memalloc_socks() && (flags & SKB_ALLOC_RX))
587 		gfp_mask |= __GFP_MEMALLOC;
588 
589 	/* Get the HEAD */
590 	if ((flags & (SKB_ALLOC_FCLONE | SKB_ALLOC_NAPI)) == SKB_ALLOC_NAPI &&
591 	    likely(node == NUMA_NO_NODE || node == numa_mem_id()))
592 		skb = napi_skb_cache_get();
593 	else
594 		skb = kmem_cache_alloc_node(cache, gfp_mask & ~GFP_DMA, node);
595 	if (unlikely(!skb))
596 		return NULL;
597 	prefetchw(skb);
598 
599 	/* We do our best to align skb_shared_info on a separate cache
600 	 * line. It usually works because kmalloc(X > SMP_CACHE_BYTES) gives
601 	 * aligned memory blocks, unless SLUB/SLAB debug is enabled.
602 	 * Both skb->head and skb_shared_info are cache line aligned.
603 	 */
604 	data = kmalloc_reserve(&size, gfp_mask, node, &pfmemalloc);
605 	if (unlikely(!data))
606 		goto nodata;
607 	/* kmalloc_size_roundup() might give us more room than requested.
608 	 * Put skb_shared_info exactly at the end of allocated zone,
609 	 * to allow max possible filling before reallocation.
610 	 */
611 	prefetchw(data + SKB_WITH_OVERHEAD(size));
612 
613 	/*
614 	 * Only clear those fields we need to clear, not those that we will
615 	 * actually initialise below. Hence, don't put any more fields after
616 	 * the tail pointer in struct sk_buff!
617 	 */
618 	memset(skb, 0, offsetof(struct sk_buff, tail));
619 	__build_skb_around(skb, data, size);
620 	skb->pfmemalloc = pfmemalloc;
621 
622 	if (flags & SKB_ALLOC_FCLONE) {
623 		struct sk_buff_fclones *fclones;
624 
625 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
626 
627 		skb->fclone = SKB_FCLONE_ORIG;
628 		refcount_set(&fclones->fclone_ref, 1);
629 	}
630 
631 	return skb;
632 
633 nodata:
634 	kmem_cache_free(cache, skb);
635 	return NULL;
636 }
637 EXPORT_SYMBOL(__alloc_skb);
638 
639 /**
640  *	__netdev_alloc_skb - allocate an skbuff for rx on a specific device
641  *	@dev: network device to receive on
642  *	@len: length to allocate
643  *	@gfp_mask: get_free_pages mask, passed to alloc_skb
644  *
645  *	Allocate a new &sk_buff and assign it a usage count of one. The
646  *	buffer has NET_SKB_PAD headroom built in. Users should allocate
647  *	the headroom they think they need without accounting for the
648  *	built in space. The built in space is used for optimisations.
649  *
650  *	%NULL is returned if there is no free memory.
651  */
652 struct sk_buff *__netdev_alloc_skb(struct net_device *dev, unsigned int len,
653 				   gfp_t gfp_mask)
654 {
655 	struct page_frag_cache *nc;
656 	struct sk_buff *skb;
657 	bool pfmemalloc;
658 	void *data;
659 
660 	len += NET_SKB_PAD;
661 
662 	/* If requested length is either too small or too big,
663 	 * we use kmalloc() for skb->head allocation.
664 	 */
665 	if (len <= SKB_WITH_OVERHEAD(1024) ||
666 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
667 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
668 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX, NUMA_NO_NODE);
669 		if (!skb)
670 			goto skb_fail;
671 		goto skb_success;
672 	}
673 
674 	len = SKB_HEAD_ALIGN(len);
675 
676 	if (sk_memalloc_socks())
677 		gfp_mask |= __GFP_MEMALLOC;
678 
679 	if (in_hardirq() || irqs_disabled()) {
680 		nc = this_cpu_ptr(&netdev_alloc_cache);
681 		data = page_frag_alloc(nc, len, gfp_mask);
682 		pfmemalloc = nc->pfmemalloc;
683 	} else {
684 		local_bh_disable();
685 		nc = this_cpu_ptr(&napi_alloc_cache.page);
686 		data = page_frag_alloc(nc, len, gfp_mask);
687 		pfmemalloc = nc->pfmemalloc;
688 		local_bh_enable();
689 	}
690 
691 	if (unlikely(!data))
692 		return NULL;
693 
694 	skb = __build_skb(data, len);
695 	if (unlikely(!skb)) {
696 		skb_free_frag(data);
697 		return NULL;
698 	}
699 
700 	if (pfmemalloc)
701 		skb->pfmemalloc = 1;
702 	skb->head_frag = 1;
703 
704 skb_success:
705 	skb_reserve(skb, NET_SKB_PAD);
706 	skb->dev = dev;
707 
708 skb_fail:
709 	return skb;
710 }
711 EXPORT_SYMBOL(__netdev_alloc_skb);
712 
713 /**
714  *	__napi_alloc_skb - allocate skbuff for rx in a specific NAPI instance
715  *	@napi: napi instance this buffer was allocated for
716  *	@len: length to allocate
717  *	@gfp_mask: get_free_pages mask, passed to alloc_skb and alloc_pages
718  *
719  *	Allocate a new sk_buff for use in NAPI receive.  This buffer will
720  *	attempt to allocate the head from a special reserved region used
721  *	only for NAPI Rx allocation.  By doing this we can save several
722  *	CPU cycles by avoiding having to disable and re-enable IRQs.
723  *
724  *	%NULL is returned if there is no free memory.
725  */
726 struct sk_buff *__napi_alloc_skb(struct napi_struct *napi, unsigned int len,
727 				 gfp_t gfp_mask)
728 {
729 	struct napi_alloc_cache *nc;
730 	struct sk_buff *skb;
731 	bool pfmemalloc;
732 	void *data;
733 
734 	DEBUG_NET_WARN_ON_ONCE(!in_softirq());
735 	len += NET_SKB_PAD + NET_IP_ALIGN;
736 
737 	/* If requested length is either too small or too big,
738 	 * we use kmalloc() for skb->head allocation.
739 	 * When the small frag allocator is available, prefer it over kmalloc
740 	 * for small fragments
741 	 */
742 	if ((!NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) ||
743 	    len > SKB_WITH_OVERHEAD(PAGE_SIZE) ||
744 	    (gfp_mask & (__GFP_DIRECT_RECLAIM | GFP_DMA))) {
745 		skb = __alloc_skb(len, gfp_mask, SKB_ALLOC_RX | SKB_ALLOC_NAPI,
746 				  NUMA_NO_NODE);
747 		if (!skb)
748 			goto skb_fail;
749 		goto skb_success;
750 	}
751 
752 	nc = this_cpu_ptr(&napi_alloc_cache);
753 
754 	if (sk_memalloc_socks())
755 		gfp_mask |= __GFP_MEMALLOC;
756 
757 	if (NAPI_HAS_SMALL_PAGE_FRAG && len <= SKB_WITH_OVERHEAD(1024)) {
758 		/* we are artificially inflating the allocation size, but
759 		 * that is not as bad as it may look like, as:
760 		 * - 'len' less than GRO_MAX_HEAD makes little sense
761 		 * - On most systems, larger 'len' values lead to fragment
762 		 *   size above 512 bytes
763 		 * - kmalloc would use the kmalloc-1k slab for such values
764 		 * - Builds with smaller GRO_MAX_HEAD will very likely do
765 		 *   little networking, as that implies no WiFi and no
766 		 *   tunnels support, and 32 bits arches.
767 		 */
768 		len = SZ_1K;
769 
770 		data = page_frag_alloc_1k(&nc->page_small, gfp_mask);
771 		pfmemalloc = NAPI_SMALL_PAGE_PFMEMALLOC(nc->page_small);
772 	} else {
773 		len = SKB_HEAD_ALIGN(len);
774 
775 		data = page_frag_alloc(&nc->page, len, gfp_mask);
776 		pfmemalloc = nc->page.pfmemalloc;
777 	}
778 
779 	if (unlikely(!data))
780 		return NULL;
781 
782 	skb = __napi_build_skb(data, len);
783 	if (unlikely(!skb)) {
784 		skb_free_frag(data);
785 		return NULL;
786 	}
787 
788 	if (pfmemalloc)
789 		skb->pfmemalloc = 1;
790 	skb->head_frag = 1;
791 
792 skb_success:
793 	skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN);
794 	skb->dev = napi->dev;
795 
796 skb_fail:
797 	return skb;
798 }
799 EXPORT_SYMBOL(__napi_alloc_skb);
800 
801 void skb_add_rx_frag(struct sk_buff *skb, int i, struct page *page, int off,
802 		     int size, unsigned int truesize)
803 {
804 	skb_fill_page_desc(skb, i, page, off, size);
805 	skb->len += size;
806 	skb->data_len += size;
807 	skb->truesize += truesize;
808 }
809 EXPORT_SYMBOL(skb_add_rx_frag);
810 
811 void skb_coalesce_rx_frag(struct sk_buff *skb, int i, int size,
812 			  unsigned int truesize)
813 {
814 	skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
815 
816 	skb_frag_size_add(frag, size);
817 	skb->len += size;
818 	skb->data_len += size;
819 	skb->truesize += truesize;
820 }
821 EXPORT_SYMBOL(skb_coalesce_rx_frag);
822 
823 static void skb_drop_list(struct sk_buff **listp)
824 {
825 	kfree_skb_list(*listp);
826 	*listp = NULL;
827 }
828 
829 static inline void skb_drop_fraglist(struct sk_buff *skb)
830 {
831 	skb_drop_list(&skb_shinfo(skb)->frag_list);
832 }
833 
834 static void skb_clone_fraglist(struct sk_buff *skb)
835 {
836 	struct sk_buff *list;
837 
838 	skb_walk_frags(skb, list)
839 		skb_get(list);
840 }
841 
842 static bool skb_pp_recycle(struct sk_buff *skb, void *data, bool napi_safe)
843 {
844 	if (!IS_ENABLED(CONFIG_PAGE_POOL) || !skb->pp_recycle)
845 		return false;
846 	return page_pool_return_skb_page(virt_to_page(data), napi_safe);
847 }
848 
849 static void skb_kfree_head(void *head, unsigned int end_offset)
850 {
851 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
852 	if (end_offset == SKB_SMALL_HEAD_HEADROOM)
853 		kmem_cache_free(skb_small_head_cache, head);
854 	else
855 #endif
856 		kfree(head);
857 }
858 
859 static void skb_free_head(struct sk_buff *skb, bool napi_safe)
860 {
861 	unsigned char *head = skb->head;
862 
863 	if (skb->head_frag) {
864 		if (skb_pp_recycle(skb, head, napi_safe))
865 			return;
866 		skb_free_frag(head);
867 	} else {
868 		skb_kfree_head(head, skb_end_offset(skb));
869 	}
870 }
871 
872 static void skb_release_data(struct sk_buff *skb, enum skb_drop_reason reason,
873 			     bool napi_safe)
874 {
875 	struct skb_shared_info *shinfo = skb_shinfo(skb);
876 	int i;
877 
878 	if (skb->cloned &&
879 	    atomic_sub_return(skb->nohdr ? (1 << SKB_DATAREF_SHIFT) + 1 : 1,
880 			      &shinfo->dataref))
881 		goto exit;
882 
883 	if (skb_zcopy(skb)) {
884 		bool skip_unref = shinfo->flags & SKBFL_MANAGED_FRAG_REFS;
885 
886 		skb_zcopy_clear(skb, true);
887 		if (skip_unref)
888 			goto free_head;
889 	}
890 
891 	for (i = 0; i < shinfo->nr_frags; i++)
892 		napi_frag_unref(&shinfo->frags[i], skb->pp_recycle, napi_safe);
893 
894 free_head:
895 	if (shinfo->frag_list)
896 		kfree_skb_list_reason(shinfo->frag_list, reason);
897 
898 	skb_free_head(skb, napi_safe);
899 exit:
900 	/* When we clone an SKB we copy the reycling bit. The pp_recycle
901 	 * bit is only set on the head though, so in order to avoid races
902 	 * while trying to recycle fragments on __skb_frag_unref() we need
903 	 * to make one SKB responsible for triggering the recycle path.
904 	 * So disable the recycling bit if an SKB is cloned and we have
905 	 * additional references to the fragmented part of the SKB.
906 	 * Eventually the last SKB will have the recycling bit set and it's
907 	 * dataref set to 0, which will trigger the recycling
908 	 */
909 	skb->pp_recycle = 0;
910 }
911 
912 /*
913  *	Free an skbuff by memory without cleaning the state.
914  */
915 static void kfree_skbmem(struct sk_buff *skb)
916 {
917 	struct sk_buff_fclones *fclones;
918 
919 	switch (skb->fclone) {
920 	case SKB_FCLONE_UNAVAILABLE:
921 		kmem_cache_free(skbuff_cache, skb);
922 		return;
923 
924 	case SKB_FCLONE_ORIG:
925 		fclones = container_of(skb, struct sk_buff_fclones, skb1);
926 
927 		/* We usually free the clone (TX completion) before original skb
928 		 * This test would have no chance to be true for the clone,
929 		 * while here, branch prediction will be good.
930 		 */
931 		if (refcount_read(&fclones->fclone_ref) == 1)
932 			goto fastpath;
933 		break;
934 
935 	default: /* SKB_FCLONE_CLONE */
936 		fclones = container_of(skb, struct sk_buff_fclones, skb2);
937 		break;
938 	}
939 	if (!refcount_dec_and_test(&fclones->fclone_ref))
940 		return;
941 fastpath:
942 	kmem_cache_free(skbuff_fclone_cache, fclones);
943 }
944 
945 void skb_release_head_state(struct sk_buff *skb)
946 {
947 	skb_dst_drop(skb);
948 	if (skb->destructor) {
949 		DEBUG_NET_WARN_ON_ONCE(in_hardirq());
950 		skb->destructor(skb);
951 	}
952 #if IS_ENABLED(CONFIG_NF_CONNTRACK)
953 	nf_conntrack_put(skb_nfct(skb));
954 #endif
955 	skb_ext_put(skb);
956 }
957 
958 /* Free everything but the sk_buff shell. */
959 static void skb_release_all(struct sk_buff *skb, enum skb_drop_reason reason,
960 			    bool napi_safe)
961 {
962 	skb_release_head_state(skb);
963 	if (likely(skb->head))
964 		skb_release_data(skb, reason, napi_safe);
965 }
966 
967 /**
968  *	__kfree_skb - private function
969  *	@skb: buffer
970  *
971  *	Free an sk_buff. Release anything attached to the buffer.
972  *	Clean the state. This is an internal helper function. Users should
973  *	always call kfree_skb
974  */
975 
976 void __kfree_skb(struct sk_buff *skb)
977 {
978 	skb_release_all(skb, SKB_DROP_REASON_NOT_SPECIFIED, false);
979 	kfree_skbmem(skb);
980 }
981 EXPORT_SYMBOL(__kfree_skb);
982 
983 static __always_inline
984 bool __kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
985 {
986 	if (unlikely(!skb_unref(skb)))
987 		return false;
988 
989 	DEBUG_NET_WARN_ON_ONCE(reason <= 0 || reason >= SKB_DROP_REASON_MAX);
990 
991 	if (reason == SKB_CONSUMED)
992 		trace_consume_skb(skb, __builtin_return_address(0));
993 	else
994 		trace_kfree_skb(skb, __builtin_return_address(0), reason);
995 	return true;
996 }
997 
998 /**
999  *	kfree_skb_reason - free an sk_buff with special reason
1000  *	@skb: buffer to free
1001  *	@reason: reason why this skb is dropped
1002  *
1003  *	Drop a reference to the buffer and free it if the usage count has
1004  *	hit zero. Meanwhile, pass the drop reason to 'kfree_skb'
1005  *	tracepoint.
1006  */
1007 void __fix_address
1008 kfree_skb_reason(struct sk_buff *skb, enum skb_drop_reason reason)
1009 {
1010 	if (__kfree_skb_reason(skb, reason))
1011 		__kfree_skb(skb);
1012 }
1013 EXPORT_SYMBOL(kfree_skb_reason);
1014 
1015 #define KFREE_SKB_BULK_SIZE	16
1016 
1017 struct skb_free_array {
1018 	unsigned int skb_count;
1019 	void *skb_array[KFREE_SKB_BULK_SIZE];
1020 };
1021 
1022 static void kfree_skb_add_bulk(struct sk_buff *skb,
1023 			       struct skb_free_array *sa,
1024 			       enum skb_drop_reason reason)
1025 {
1026 	/* if SKB is a clone, don't handle this case */
1027 	if (unlikely(skb->fclone != SKB_FCLONE_UNAVAILABLE)) {
1028 		__kfree_skb(skb);
1029 		return;
1030 	}
1031 
1032 	skb_release_all(skb, reason, false);
1033 	sa->skb_array[sa->skb_count++] = skb;
1034 
1035 	if (unlikely(sa->skb_count == KFREE_SKB_BULK_SIZE)) {
1036 		kmem_cache_free_bulk(skbuff_cache, KFREE_SKB_BULK_SIZE,
1037 				     sa->skb_array);
1038 		sa->skb_count = 0;
1039 	}
1040 }
1041 
1042 void __fix_address
1043 kfree_skb_list_reason(struct sk_buff *segs, enum skb_drop_reason reason)
1044 {
1045 	struct skb_free_array sa;
1046 
1047 	sa.skb_count = 0;
1048 
1049 	while (segs) {
1050 		struct sk_buff *next = segs->next;
1051 
1052 		if (__kfree_skb_reason(segs, reason)) {
1053 			skb_poison_list(segs);
1054 			kfree_skb_add_bulk(segs, &sa, reason);
1055 		}
1056 
1057 		segs = next;
1058 	}
1059 
1060 	if (sa.skb_count)
1061 		kmem_cache_free_bulk(skbuff_cache, sa.skb_count, sa.skb_array);
1062 }
1063 EXPORT_SYMBOL(kfree_skb_list_reason);
1064 
1065 /* Dump skb information and contents.
1066  *
1067  * Must only be called from net_ratelimit()-ed paths.
1068  *
1069  * Dumps whole packets if full_pkt, only headers otherwise.
1070  */
1071 void skb_dump(const char *level, const struct sk_buff *skb, bool full_pkt)
1072 {
1073 	struct skb_shared_info *sh = skb_shinfo(skb);
1074 	struct net_device *dev = skb->dev;
1075 	struct sock *sk = skb->sk;
1076 	struct sk_buff *list_skb;
1077 	bool has_mac, has_trans;
1078 	int headroom, tailroom;
1079 	int i, len, seg_len;
1080 
1081 	if (full_pkt)
1082 		len = skb->len;
1083 	else
1084 		len = min_t(int, skb->len, MAX_HEADER + 128);
1085 
1086 	headroom = skb_headroom(skb);
1087 	tailroom = skb_tailroom(skb);
1088 
1089 	has_mac = skb_mac_header_was_set(skb);
1090 	has_trans = skb_transport_header_was_set(skb);
1091 
1092 	printk("%sskb len=%u headroom=%u headlen=%u tailroom=%u\n"
1093 	       "mac=(%d,%d) net=(%d,%d) trans=%d\n"
1094 	       "shinfo(txflags=%u nr_frags=%u gso(size=%hu type=%u segs=%hu))\n"
1095 	       "csum(0x%x ip_summed=%u complete_sw=%u valid=%u level=%u)\n"
1096 	       "hash(0x%x sw=%u l4=%u) proto=0x%04x pkttype=%u iif=%d\n",
1097 	       level, skb->len, headroom, skb_headlen(skb), tailroom,
1098 	       has_mac ? skb->mac_header : -1,
1099 	       has_mac ? skb_mac_header_len(skb) : -1,
1100 	       skb->network_header,
1101 	       has_trans ? skb_network_header_len(skb) : -1,
1102 	       has_trans ? skb->transport_header : -1,
1103 	       sh->tx_flags, sh->nr_frags,
1104 	       sh->gso_size, sh->gso_type, sh->gso_segs,
1105 	       skb->csum, skb->ip_summed, skb->csum_complete_sw,
1106 	       skb->csum_valid, skb->csum_level,
1107 	       skb->hash, skb->sw_hash, skb->l4_hash,
1108 	       ntohs(skb->protocol), skb->pkt_type, skb->skb_iif);
1109 
1110 	if (dev)
1111 		printk("%sdev name=%s feat=%pNF\n",
1112 		       level, dev->name, &dev->features);
1113 	if (sk)
1114 		printk("%ssk family=%hu type=%u proto=%u\n",
1115 		       level, sk->sk_family, sk->sk_type, sk->sk_protocol);
1116 
1117 	if (full_pkt && headroom)
1118 		print_hex_dump(level, "skb headroom: ", DUMP_PREFIX_OFFSET,
1119 			       16, 1, skb->head, headroom, false);
1120 
1121 	seg_len = min_t(int, skb_headlen(skb), len);
1122 	if (seg_len)
1123 		print_hex_dump(level, "skb linear:   ", DUMP_PREFIX_OFFSET,
1124 			       16, 1, skb->data, seg_len, false);
1125 	len -= seg_len;
1126 
1127 	if (full_pkt && tailroom)
1128 		print_hex_dump(level, "skb tailroom: ", DUMP_PREFIX_OFFSET,
1129 			       16, 1, skb_tail_pointer(skb), tailroom, false);
1130 
1131 	for (i = 0; len && i < skb_shinfo(skb)->nr_frags; i++) {
1132 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
1133 		u32 p_off, p_len, copied;
1134 		struct page *p;
1135 		u8 *vaddr;
1136 
1137 		skb_frag_foreach_page(frag, skb_frag_off(frag),
1138 				      skb_frag_size(frag), p, p_off, p_len,
1139 				      copied) {
1140 			seg_len = min_t(int, p_len, len);
1141 			vaddr = kmap_atomic(p);
1142 			print_hex_dump(level, "skb frag:     ",
1143 				       DUMP_PREFIX_OFFSET,
1144 				       16, 1, vaddr + p_off, seg_len, false);
1145 			kunmap_atomic(vaddr);
1146 			len -= seg_len;
1147 			if (!len)
1148 				break;
1149 		}
1150 	}
1151 
1152 	if (full_pkt && skb_has_frag_list(skb)) {
1153 		printk("skb fraglist:\n");
1154 		skb_walk_frags(skb, list_skb)
1155 			skb_dump(level, list_skb, true);
1156 	}
1157 }
1158 EXPORT_SYMBOL(skb_dump);
1159 
1160 /**
1161  *	skb_tx_error - report an sk_buff xmit error
1162  *	@skb: buffer that triggered an error
1163  *
1164  *	Report xmit error if a device callback is tracking this skb.
1165  *	skb must be freed afterwards.
1166  */
1167 void skb_tx_error(struct sk_buff *skb)
1168 {
1169 	if (skb) {
1170 		skb_zcopy_downgrade_managed(skb);
1171 		skb_zcopy_clear(skb, true);
1172 	}
1173 }
1174 EXPORT_SYMBOL(skb_tx_error);
1175 
1176 #ifdef CONFIG_TRACEPOINTS
1177 /**
1178  *	consume_skb - free an skbuff
1179  *	@skb: buffer to free
1180  *
1181  *	Drop a ref to the buffer and free it if the usage count has hit zero
1182  *	Functions identically to kfree_skb, but kfree_skb assumes that the frame
1183  *	is being dropped after a failure and notes that
1184  */
1185 void consume_skb(struct sk_buff *skb)
1186 {
1187 	if (!skb_unref(skb))
1188 		return;
1189 
1190 	trace_consume_skb(skb, __builtin_return_address(0));
1191 	__kfree_skb(skb);
1192 }
1193 EXPORT_SYMBOL(consume_skb);
1194 #endif
1195 
1196 /**
1197  *	__consume_stateless_skb - free an skbuff, assuming it is stateless
1198  *	@skb: buffer to free
1199  *
1200  *	Alike consume_skb(), but this variant assumes that this is the last
1201  *	skb reference and all the head states have been already dropped
1202  */
1203 void __consume_stateless_skb(struct sk_buff *skb)
1204 {
1205 	trace_consume_skb(skb, __builtin_return_address(0));
1206 	skb_release_data(skb, SKB_CONSUMED, false);
1207 	kfree_skbmem(skb);
1208 }
1209 
1210 static void napi_skb_cache_put(struct sk_buff *skb)
1211 {
1212 	struct napi_alloc_cache *nc = this_cpu_ptr(&napi_alloc_cache);
1213 	u32 i;
1214 
1215 	kasan_poison_object_data(skbuff_cache, skb);
1216 	nc->skb_cache[nc->skb_count++] = skb;
1217 
1218 	if (unlikely(nc->skb_count == NAPI_SKB_CACHE_SIZE)) {
1219 		for (i = NAPI_SKB_CACHE_HALF; i < NAPI_SKB_CACHE_SIZE; i++)
1220 			kasan_unpoison_object_data(skbuff_cache,
1221 						   nc->skb_cache[i]);
1222 
1223 		kmem_cache_free_bulk(skbuff_cache, NAPI_SKB_CACHE_HALF,
1224 				     nc->skb_cache + NAPI_SKB_CACHE_HALF);
1225 		nc->skb_count = NAPI_SKB_CACHE_HALF;
1226 	}
1227 }
1228 
1229 void __napi_kfree_skb(struct sk_buff *skb, enum skb_drop_reason reason)
1230 {
1231 	skb_release_all(skb, reason, true);
1232 	napi_skb_cache_put(skb);
1233 }
1234 
1235 void napi_skb_free_stolen_head(struct sk_buff *skb)
1236 {
1237 	if (unlikely(skb->slow_gro)) {
1238 		nf_reset_ct(skb);
1239 		skb_dst_drop(skb);
1240 		skb_ext_put(skb);
1241 		skb_orphan(skb);
1242 		skb->slow_gro = 0;
1243 	}
1244 	napi_skb_cache_put(skb);
1245 }
1246 
1247 void napi_consume_skb(struct sk_buff *skb, int budget)
1248 {
1249 	/* Zero budget indicate non-NAPI context called us, like netpoll */
1250 	if (unlikely(!budget)) {
1251 		dev_consume_skb_any(skb);
1252 		return;
1253 	}
1254 
1255 	DEBUG_NET_WARN_ON_ONCE(!in_softirq());
1256 
1257 	if (!skb_unref(skb))
1258 		return;
1259 
1260 	/* if reaching here SKB is ready to free */
1261 	trace_consume_skb(skb, __builtin_return_address(0));
1262 
1263 	/* if SKB is a clone, don't handle this case */
1264 	if (skb->fclone != SKB_FCLONE_UNAVAILABLE) {
1265 		__kfree_skb(skb);
1266 		return;
1267 	}
1268 
1269 	skb_release_all(skb, SKB_CONSUMED, !!budget);
1270 	napi_skb_cache_put(skb);
1271 }
1272 EXPORT_SYMBOL(napi_consume_skb);
1273 
1274 /* Make sure a field is contained by headers group */
1275 #define CHECK_SKB_FIELD(field) \
1276 	BUILD_BUG_ON(offsetof(struct sk_buff, field) !=		\
1277 		     offsetof(struct sk_buff, headers.field));	\
1278 
1279 static void __copy_skb_header(struct sk_buff *new, const struct sk_buff *old)
1280 {
1281 	new->tstamp		= old->tstamp;
1282 	/* We do not copy old->sk */
1283 	new->dev		= old->dev;
1284 	memcpy(new->cb, old->cb, sizeof(old->cb));
1285 	skb_dst_copy(new, old);
1286 	__skb_ext_copy(new, old);
1287 	__nf_copy(new, old, false);
1288 
1289 	/* Note : this field could be in the headers group.
1290 	 * It is not yet because we do not want to have a 16 bit hole
1291 	 */
1292 	new->queue_mapping = old->queue_mapping;
1293 
1294 	memcpy(&new->headers, &old->headers, sizeof(new->headers));
1295 	CHECK_SKB_FIELD(protocol);
1296 	CHECK_SKB_FIELD(csum);
1297 	CHECK_SKB_FIELD(hash);
1298 	CHECK_SKB_FIELD(priority);
1299 	CHECK_SKB_FIELD(skb_iif);
1300 	CHECK_SKB_FIELD(vlan_proto);
1301 	CHECK_SKB_FIELD(vlan_tci);
1302 	CHECK_SKB_FIELD(transport_header);
1303 	CHECK_SKB_FIELD(network_header);
1304 	CHECK_SKB_FIELD(mac_header);
1305 	CHECK_SKB_FIELD(inner_protocol);
1306 	CHECK_SKB_FIELD(inner_transport_header);
1307 	CHECK_SKB_FIELD(inner_network_header);
1308 	CHECK_SKB_FIELD(inner_mac_header);
1309 	CHECK_SKB_FIELD(mark);
1310 #ifdef CONFIG_NETWORK_SECMARK
1311 	CHECK_SKB_FIELD(secmark);
1312 #endif
1313 #ifdef CONFIG_NET_RX_BUSY_POLL
1314 	CHECK_SKB_FIELD(napi_id);
1315 #endif
1316 	CHECK_SKB_FIELD(alloc_cpu);
1317 #ifdef CONFIG_XPS
1318 	CHECK_SKB_FIELD(sender_cpu);
1319 #endif
1320 #ifdef CONFIG_NET_SCHED
1321 	CHECK_SKB_FIELD(tc_index);
1322 #endif
1323 
1324 }
1325 
1326 /*
1327  * You should not add any new code to this function.  Add it to
1328  * __copy_skb_header above instead.
1329  */
1330 static struct sk_buff *__skb_clone(struct sk_buff *n, struct sk_buff *skb)
1331 {
1332 #define C(x) n->x = skb->x
1333 
1334 	n->next = n->prev = NULL;
1335 	n->sk = NULL;
1336 	__copy_skb_header(n, skb);
1337 
1338 	C(len);
1339 	C(data_len);
1340 	C(mac_len);
1341 	n->hdr_len = skb->nohdr ? skb_headroom(skb) : skb->hdr_len;
1342 	n->cloned = 1;
1343 	n->nohdr = 0;
1344 	n->peeked = 0;
1345 	C(pfmemalloc);
1346 	C(pp_recycle);
1347 	n->destructor = NULL;
1348 	C(tail);
1349 	C(end);
1350 	C(head);
1351 	C(head_frag);
1352 	C(data);
1353 	C(truesize);
1354 	refcount_set(&n->users, 1);
1355 
1356 	atomic_inc(&(skb_shinfo(skb)->dataref));
1357 	skb->cloned = 1;
1358 
1359 	return n;
1360 #undef C
1361 }
1362 
1363 /**
1364  * alloc_skb_for_msg() - allocate sk_buff to wrap frag list forming a msg
1365  * @first: first sk_buff of the msg
1366  */
1367 struct sk_buff *alloc_skb_for_msg(struct sk_buff *first)
1368 {
1369 	struct sk_buff *n;
1370 
1371 	n = alloc_skb(0, GFP_ATOMIC);
1372 	if (!n)
1373 		return NULL;
1374 
1375 	n->len = first->len;
1376 	n->data_len = first->len;
1377 	n->truesize = first->truesize;
1378 
1379 	skb_shinfo(n)->frag_list = first;
1380 
1381 	__copy_skb_header(n, first);
1382 	n->destructor = NULL;
1383 
1384 	return n;
1385 }
1386 EXPORT_SYMBOL_GPL(alloc_skb_for_msg);
1387 
1388 /**
1389  *	skb_morph	-	morph one skb into another
1390  *	@dst: the skb to receive the contents
1391  *	@src: the skb to supply the contents
1392  *
1393  *	This is identical to skb_clone except that the target skb is
1394  *	supplied by the user.
1395  *
1396  *	The target skb is returned upon exit.
1397  */
1398 struct sk_buff *skb_morph(struct sk_buff *dst, struct sk_buff *src)
1399 {
1400 	skb_release_all(dst, SKB_CONSUMED, false);
1401 	return __skb_clone(dst, src);
1402 }
1403 EXPORT_SYMBOL_GPL(skb_morph);
1404 
1405 int mm_account_pinned_pages(struct mmpin *mmp, size_t size)
1406 {
1407 	unsigned long max_pg, num_pg, new_pg, old_pg, rlim;
1408 	struct user_struct *user;
1409 
1410 	if (capable(CAP_IPC_LOCK) || !size)
1411 		return 0;
1412 
1413 	rlim = rlimit(RLIMIT_MEMLOCK);
1414 	if (rlim == RLIM_INFINITY)
1415 		return 0;
1416 
1417 	num_pg = (size >> PAGE_SHIFT) + 2;	/* worst case */
1418 	max_pg = rlim >> PAGE_SHIFT;
1419 	user = mmp->user ? : current_user();
1420 
1421 	old_pg = atomic_long_read(&user->locked_vm);
1422 	do {
1423 		new_pg = old_pg + num_pg;
1424 		if (new_pg > max_pg)
1425 			return -ENOBUFS;
1426 	} while (!atomic_long_try_cmpxchg(&user->locked_vm, &old_pg, new_pg));
1427 
1428 	if (!mmp->user) {
1429 		mmp->user = get_uid(user);
1430 		mmp->num_pg = num_pg;
1431 	} else {
1432 		mmp->num_pg += num_pg;
1433 	}
1434 
1435 	return 0;
1436 }
1437 EXPORT_SYMBOL_GPL(mm_account_pinned_pages);
1438 
1439 void mm_unaccount_pinned_pages(struct mmpin *mmp)
1440 {
1441 	if (mmp->user) {
1442 		atomic_long_sub(mmp->num_pg, &mmp->user->locked_vm);
1443 		free_uid(mmp->user);
1444 	}
1445 }
1446 EXPORT_SYMBOL_GPL(mm_unaccount_pinned_pages);
1447 
1448 static struct ubuf_info *msg_zerocopy_alloc(struct sock *sk, size_t size)
1449 {
1450 	struct ubuf_info_msgzc *uarg;
1451 	struct sk_buff *skb;
1452 
1453 	WARN_ON_ONCE(!in_task());
1454 
1455 	skb = sock_omalloc(sk, 0, GFP_KERNEL);
1456 	if (!skb)
1457 		return NULL;
1458 
1459 	BUILD_BUG_ON(sizeof(*uarg) > sizeof(skb->cb));
1460 	uarg = (void *)skb->cb;
1461 	uarg->mmp.user = NULL;
1462 
1463 	if (mm_account_pinned_pages(&uarg->mmp, size)) {
1464 		kfree_skb(skb);
1465 		return NULL;
1466 	}
1467 
1468 	uarg->ubuf.callback = msg_zerocopy_callback;
1469 	uarg->id = ((u32)atomic_inc_return(&sk->sk_zckey)) - 1;
1470 	uarg->len = 1;
1471 	uarg->bytelen = size;
1472 	uarg->zerocopy = 1;
1473 	uarg->ubuf.flags = SKBFL_ZEROCOPY_FRAG | SKBFL_DONT_ORPHAN;
1474 	refcount_set(&uarg->ubuf.refcnt, 1);
1475 	sock_hold(sk);
1476 
1477 	return &uarg->ubuf;
1478 }
1479 
1480 static inline struct sk_buff *skb_from_uarg(struct ubuf_info_msgzc *uarg)
1481 {
1482 	return container_of((void *)uarg, struct sk_buff, cb);
1483 }
1484 
1485 struct ubuf_info *msg_zerocopy_realloc(struct sock *sk, size_t size,
1486 				       struct ubuf_info *uarg)
1487 {
1488 	if (uarg) {
1489 		struct ubuf_info_msgzc *uarg_zc;
1490 		const u32 byte_limit = 1 << 19;		/* limit to a few TSO */
1491 		u32 bytelen, next;
1492 
1493 		/* there might be non MSG_ZEROCOPY users */
1494 		if (uarg->callback != msg_zerocopy_callback)
1495 			return NULL;
1496 
1497 		/* realloc only when socket is locked (TCP, UDP cork),
1498 		 * so uarg->len and sk_zckey access is serialized
1499 		 */
1500 		if (!sock_owned_by_user(sk)) {
1501 			WARN_ON_ONCE(1);
1502 			return NULL;
1503 		}
1504 
1505 		uarg_zc = uarg_to_msgzc(uarg);
1506 		bytelen = uarg_zc->bytelen + size;
1507 		if (uarg_zc->len == USHRT_MAX - 1 || bytelen > byte_limit) {
1508 			/* TCP can create new skb to attach new uarg */
1509 			if (sk->sk_type == SOCK_STREAM)
1510 				goto new_alloc;
1511 			return NULL;
1512 		}
1513 
1514 		next = (u32)atomic_read(&sk->sk_zckey);
1515 		if ((u32)(uarg_zc->id + uarg_zc->len) == next) {
1516 			if (mm_account_pinned_pages(&uarg_zc->mmp, size))
1517 				return NULL;
1518 			uarg_zc->len++;
1519 			uarg_zc->bytelen = bytelen;
1520 			atomic_set(&sk->sk_zckey, ++next);
1521 
1522 			/* no extra ref when appending to datagram (MSG_MORE) */
1523 			if (sk->sk_type == SOCK_STREAM)
1524 				net_zcopy_get(uarg);
1525 
1526 			return uarg;
1527 		}
1528 	}
1529 
1530 new_alloc:
1531 	return msg_zerocopy_alloc(sk, size);
1532 }
1533 EXPORT_SYMBOL_GPL(msg_zerocopy_realloc);
1534 
1535 static bool skb_zerocopy_notify_extend(struct sk_buff *skb, u32 lo, u16 len)
1536 {
1537 	struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
1538 	u32 old_lo, old_hi;
1539 	u64 sum_len;
1540 
1541 	old_lo = serr->ee.ee_info;
1542 	old_hi = serr->ee.ee_data;
1543 	sum_len = old_hi - old_lo + 1ULL + len;
1544 
1545 	if (sum_len >= (1ULL << 32))
1546 		return false;
1547 
1548 	if (lo != old_hi + 1)
1549 		return false;
1550 
1551 	serr->ee.ee_data += len;
1552 	return true;
1553 }
1554 
1555 static void __msg_zerocopy_callback(struct ubuf_info_msgzc *uarg)
1556 {
1557 	struct sk_buff *tail, *skb = skb_from_uarg(uarg);
1558 	struct sock_exterr_skb *serr;
1559 	struct sock *sk = skb->sk;
1560 	struct sk_buff_head *q;
1561 	unsigned long flags;
1562 	bool is_zerocopy;
1563 	u32 lo, hi;
1564 	u16 len;
1565 
1566 	mm_unaccount_pinned_pages(&uarg->mmp);
1567 
1568 	/* if !len, there was only 1 call, and it was aborted
1569 	 * so do not queue a completion notification
1570 	 */
1571 	if (!uarg->len || sock_flag(sk, SOCK_DEAD))
1572 		goto release;
1573 
1574 	len = uarg->len;
1575 	lo = uarg->id;
1576 	hi = uarg->id + len - 1;
1577 	is_zerocopy = uarg->zerocopy;
1578 
1579 	serr = SKB_EXT_ERR(skb);
1580 	memset(serr, 0, sizeof(*serr));
1581 	serr->ee.ee_errno = 0;
1582 	serr->ee.ee_origin = SO_EE_ORIGIN_ZEROCOPY;
1583 	serr->ee.ee_data = hi;
1584 	serr->ee.ee_info = lo;
1585 	if (!is_zerocopy)
1586 		serr->ee.ee_code |= SO_EE_CODE_ZEROCOPY_COPIED;
1587 
1588 	q = &sk->sk_error_queue;
1589 	spin_lock_irqsave(&q->lock, flags);
1590 	tail = skb_peek_tail(q);
1591 	if (!tail || SKB_EXT_ERR(tail)->ee.ee_origin != SO_EE_ORIGIN_ZEROCOPY ||
1592 	    !skb_zerocopy_notify_extend(tail, lo, len)) {
1593 		__skb_queue_tail(q, skb);
1594 		skb = NULL;
1595 	}
1596 	spin_unlock_irqrestore(&q->lock, flags);
1597 
1598 	sk_error_report(sk);
1599 
1600 release:
1601 	consume_skb(skb);
1602 	sock_put(sk);
1603 }
1604 
1605 void msg_zerocopy_callback(struct sk_buff *skb, struct ubuf_info *uarg,
1606 			   bool success)
1607 {
1608 	struct ubuf_info_msgzc *uarg_zc = uarg_to_msgzc(uarg);
1609 
1610 	uarg_zc->zerocopy = uarg_zc->zerocopy & success;
1611 
1612 	if (refcount_dec_and_test(&uarg->refcnt))
1613 		__msg_zerocopy_callback(uarg_zc);
1614 }
1615 EXPORT_SYMBOL_GPL(msg_zerocopy_callback);
1616 
1617 void msg_zerocopy_put_abort(struct ubuf_info *uarg, bool have_uref)
1618 {
1619 	struct sock *sk = skb_from_uarg(uarg_to_msgzc(uarg))->sk;
1620 
1621 	atomic_dec(&sk->sk_zckey);
1622 	uarg_to_msgzc(uarg)->len--;
1623 
1624 	if (have_uref)
1625 		msg_zerocopy_callback(NULL, uarg, true);
1626 }
1627 EXPORT_SYMBOL_GPL(msg_zerocopy_put_abort);
1628 
1629 int skb_zerocopy_iter_stream(struct sock *sk, struct sk_buff *skb,
1630 			     struct msghdr *msg, int len,
1631 			     struct ubuf_info *uarg)
1632 {
1633 	struct ubuf_info *orig_uarg = skb_zcopy(skb);
1634 	int err, orig_len = skb->len;
1635 
1636 	/* An skb can only point to one uarg. This edge case happens when
1637 	 * TCP appends to an skb, but zerocopy_realloc triggered a new alloc.
1638 	 */
1639 	if (orig_uarg && uarg != orig_uarg)
1640 		return -EEXIST;
1641 
1642 	err = __zerocopy_sg_from_iter(msg, sk, skb, &msg->msg_iter, len);
1643 	if (err == -EFAULT || (err == -EMSGSIZE && skb->len == orig_len)) {
1644 		struct sock *save_sk = skb->sk;
1645 
1646 		/* Streams do not free skb on error. Reset to prev state. */
1647 		iov_iter_revert(&msg->msg_iter, skb->len - orig_len);
1648 		skb->sk = sk;
1649 		___pskb_trim(skb, orig_len);
1650 		skb->sk = save_sk;
1651 		return err;
1652 	}
1653 
1654 	skb_zcopy_set(skb, uarg, NULL);
1655 	return skb->len - orig_len;
1656 }
1657 EXPORT_SYMBOL_GPL(skb_zerocopy_iter_stream);
1658 
1659 void __skb_zcopy_downgrade_managed(struct sk_buff *skb)
1660 {
1661 	int i;
1662 
1663 	skb_shinfo(skb)->flags &= ~SKBFL_MANAGED_FRAG_REFS;
1664 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
1665 		skb_frag_ref(skb, i);
1666 }
1667 EXPORT_SYMBOL_GPL(__skb_zcopy_downgrade_managed);
1668 
1669 static int skb_zerocopy_clone(struct sk_buff *nskb, struct sk_buff *orig,
1670 			      gfp_t gfp_mask)
1671 {
1672 	if (skb_zcopy(orig)) {
1673 		if (skb_zcopy(nskb)) {
1674 			/* !gfp_mask callers are verified to !skb_zcopy(nskb) */
1675 			if (!gfp_mask) {
1676 				WARN_ON_ONCE(1);
1677 				return -ENOMEM;
1678 			}
1679 			if (skb_uarg(nskb) == skb_uarg(orig))
1680 				return 0;
1681 			if (skb_copy_ubufs(nskb, GFP_ATOMIC))
1682 				return -EIO;
1683 		}
1684 		skb_zcopy_set(nskb, skb_uarg(orig), NULL);
1685 	}
1686 	return 0;
1687 }
1688 
1689 /**
1690  *	skb_copy_ubufs	-	copy userspace skb frags buffers to kernel
1691  *	@skb: the skb to modify
1692  *	@gfp_mask: allocation priority
1693  *
1694  *	This must be called on skb with SKBFL_ZEROCOPY_ENABLE.
1695  *	It will copy all frags into kernel and drop the reference
1696  *	to userspace pages.
1697  *
1698  *	If this function is called from an interrupt gfp_mask() must be
1699  *	%GFP_ATOMIC.
1700  *
1701  *	Returns 0 on success or a negative error code on failure
1702  *	to allocate kernel memory to copy to.
1703  */
1704 int skb_copy_ubufs(struct sk_buff *skb, gfp_t gfp_mask)
1705 {
1706 	int num_frags = skb_shinfo(skb)->nr_frags;
1707 	struct page *page, *head = NULL;
1708 	int i, new_frags;
1709 	u32 d_off;
1710 
1711 	if (skb_shared(skb) || skb_unclone(skb, gfp_mask))
1712 		return -EINVAL;
1713 
1714 	if (!num_frags)
1715 		goto release;
1716 
1717 	new_frags = (__skb_pagelen(skb) + PAGE_SIZE - 1) >> PAGE_SHIFT;
1718 	for (i = 0; i < new_frags; i++) {
1719 		page = alloc_page(gfp_mask);
1720 		if (!page) {
1721 			while (head) {
1722 				struct page *next = (struct page *)page_private(head);
1723 				put_page(head);
1724 				head = next;
1725 			}
1726 			return -ENOMEM;
1727 		}
1728 		set_page_private(page, (unsigned long)head);
1729 		head = page;
1730 	}
1731 
1732 	page = head;
1733 	d_off = 0;
1734 	for (i = 0; i < num_frags; i++) {
1735 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
1736 		u32 p_off, p_len, copied;
1737 		struct page *p;
1738 		u8 *vaddr;
1739 
1740 		skb_frag_foreach_page(f, skb_frag_off(f), skb_frag_size(f),
1741 				      p, p_off, p_len, copied) {
1742 			u32 copy, done = 0;
1743 			vaddr = kmap_atomic(p);
1744 
1745 			while (done < p_len) {
1746 				if (d_off == PAGE_SIZE) {
1747 					d_off = 0;
1748 					page = (struct page *)page_private(page);
1749 				}
1750 				copy = min_t(u32, PAGE_SIZE - d_off, p_len - done);
1751 				memcpy(page_address(page) + d_off,
1752 				       vaddr + p_off + done, copy);
1753 				done += copy;
1754 				d_off += copy;
1755 			}
1756 			kunmap_atomic(vaddr);
1757 		}
1758 	}
1759 
1760 	/* skb frags release userspace buffers */
1761 	for (i = 0; i < num_frags; i++)
1762 		skb_frag_unref(skb, i);
1763 
1764 	/* skb frags point to kernel buffers */
1765 	for (i = 0; i < new_frags - 1; i++) {
1766 		__skb_fill_page_desc(skb, i, head, 0, PAGE_SIZE);
1767 		head = (struct page *)page_private(head);
1768 	}
1769 	__skb_fill_page_desc(skb, new_frags - 1, head, 0, d_off);
1770 	skb_shinfo(skb)->nr_frags = new_frags;
1771 
1772 release:
1773 	skb_zcopy_clear(skb, false);
1774 	return 0;
1775 }
1776 EXPORT_SYMBOL_GPL(skb_copy_ubufs);
1777 
1778 /**
1779  *	skb_clone	-	duplicate an sk_buff
1780  *	@skb: buffer to clone
1781  *	@gfp_mask: allocation priority
1782  *
1783  *	Duplicate an &sk_buff. The new one is not owned by a socket. Both
1784  *	copies share the same packet data but not structure. The new
1785  *	buffer has a reference count of 1. If the allocation fails the
1786  *	function returns %NULL otherwise the new buffer is returned.
1787  *
1788  *	If this function is called from an interrupt gfp_mask() must be
1789  *	%GFP_ATOMIC.
1790  */
1791 
1792 struct sk_buff *skb_clone(struct sk_buff *skb, gfp_t gfp_mask)
1793 {
1794 	struct sk_buff_fclones *fclones = container_of(skb,
1795 						       struct sk_buff_fclones,
1796 						       skb1);
1797 	struct sk_buff *n;
1798 
1799 	if (skb_orphan_frags(skb, gfp_mask))
1800 		return NULL;
1801 
1802 	if (skb->fclone == SKB_FCLONE_ORIG &&
1803 	    refcount_read(&fclones->fclone_ref) == 1) {
1804 		n = &fclones->skb2;
1805 		refcount_set(&fclones->fclone_ref, 2);
1806 		n->fclone = SKB_FCLONE_CLONE;
1807 	} else {
1808 		if (skb_pfmemalloc(skb))
1809 			gfp_mask |= __GFP_MEMALLOC;
1810 
1811 		n = kmem_cache_alloc(skbuff_cache, gfp_mask);
1812 		if (!n)
1813 			return NULL;
1814 
1815 		n->fclone = SKB_FCLONE_UNAVAILABLE;
1816 	}
1817 
1818 	return __skb_clone(n, skb);
1819 }
1820 EXPORT_SYMBOL(skb_clone);
1821 
1822 void skb_headers_offset_update(struct sk_buff *skb, int off)
1823 {
1824 	/* Only adjust this if it actually is csum_start rather than csum */
1825 	if (skb->ip_summed == CHECKSUM_PARTIAL)
1826 		skb->csum_start += off;
1827 	/* {transport,network,mac}_header and tail are relative to skb->head */
1828 	skb->transport_header += off;
1829 	skb->network_header   += off;
1830 	if (skb_mac_header_was_set(skb))
1831 		skb->mac_header += off;
1832 	skb->inner_transport_header += off;
1833 	skb->inner_network_header += off;
1834 	skb->inner_mac_header += off;
1835 }
1836 EXPORT_SYMBOL(skb_headers_offset_update);
1837 
1838 void skb_copy_header(struct sk_buff *new, const struct sk_buff *old)
1839 {
1840 	__copy_skb_header(new, old);
1841 
1842 	skb_shinfo(new)->gso_size = skb_shinfo(old)->gso_size;
1843 	skb_shinfo(new)->gso_segs = skb_shinfo(old)->gso_segs;
1844 	skb_shinfo(new)->gso_type = skb_shinfo(old)->gso_type;
1845 }
1846 EXPORT_SYMBOL(skb_copy_header);
1847 
1848 static inline int skb_alloc_rx_flag(const struct sk_buff *skb)
1849 {
1850 	if (skb_pfmemalloc(skb))
1851 		return SKB_ALLOC_RX;
1852 	return 0;
1853 }
1854 
1855 /**
1856  *	skb_copy	-	create private copy of an sk_buff
1857  *	@skb: buffer to copy
1858  *	@gfp_mask: allocation priority
1859  *
1860  *	Make a copy of both an &sk_buff and its data. This is used when the
1861  *	caller wishes to modify the data and needs a private copy of the
1862  *	data to alter. Returns %NULL on failure or the pointer to the buffer
1863  *	on success. The returned buffer has a reference count of 1.
1864  *
1865  *	As by-product this function converts non-linear &sk_buff to linear
1866  *	one, so that &sk_buff becomes completely private and caller is allowed
1867  *	to modify all the data of returned buffer. This means that this
1868  *	function is not recommended for use in circumstances when only
1869  *	header is going to be modified. Use pskb_copy() instead.
1870  */
1871 
1872 struct sk_buff *skb_copy(const struct sk_buff *skb, gfp_t gfp_mask)
1873 {
1874 	int headerlen = skb_headroom(skb);
1875 	unsigned int size = skb_end_offset(skb) + skb->data_len;
1876 	struct sk_buff *n = __alloc_skb(size, gfp_mask,
1877 					skb_alloc_rx_flag(skb), NUMA_NO_NODE);
1878 
1879 	if (!n)
1880 		return NULL;
1881 
1882 	/* Set the data pointer */
1883 	skb_reserve(n, headerlen);
1884 	/* Set the tail pointer and length */
1885 	skb_put(n, skb->len);
1886 
1887 	BUG_ON(skb_copy_bits(skb, -headerlen, n->head, headerlen + skb->len));
1888 
1889 	skb_copy_header(n, skb);
1890 	return n;
1891 }
1892 EXPORT_SYMBOL(skb_copy);
1893 
1894 /**
1895  *	__pskb_copy_fclone	-  create copy of an sk_buff with private head.
1896  *	@skb: buffer to copy
1897  *	@headroom: headroom of new skb
1898  *	@gfp_mask: allocation priority
1899  *	@fclone: if true allocate the copy of the skb from the fclone
1900  *	cache instead of the head cache; it is recommended to set this
1901  *	to true for the cases where the copy will likely be cloned
1902  *
1903  *	Make a copy of both an &sk_buff and part of its data, located
1904  *	in header. Fragmented data remain shared. This is used when
1905  *	the caller wishes to modify only header of &sk_buff and needs
1906  *	private copy of the header to alter. Returns %NULL on failure
1907  *	or the pointer to the buffer on success.
1908  *	The returned buffer has a reference count of 1.
1909  */
1910 
1911 struct sk_buff *__pskb_copy_fclone(struct sk_buff *skb, int headroom,
1912 				   gfp_t gfp_mask, bool fclone)
1913 {
1914 	unsigned int size = skb_headlen(skb) + headroom;
1915 	int flags = skb_alloc_rx_flag(skb) | (fclone ? SKB_ALLOC_FCLONE : 0);
1916 	struct sk_buff *n = __alloc_skb(size, gfp_mask, flags, NUMA_NO_NODE);
1917 
1918 	if (!n)
1919 		goto out;
1920 
1921 	/* Set the data pointer */
1922 	skb_reserve(n, headroom);
1923 	/* Set the tail pointer and length */
1924 	skb_put(n, skb_headlen(skb));
1925 	/* Copy the bytes */
1926 	skb_copy_from_linear_data(skb, n->data, n->len);
1927 
1928 	n->truesize += skb->data_len;
1929 	n->data_len  = skb->data_len;
1930 	n->len	     = skb->len;
1931 
1932 	if (skb_shinfo(skb)->nr_frags) {
1933 		int i;
1934 
1935 		if (skb_orphan_frags(skb, gfp_mask) ||
1936 		    skb_zerocopy_clone(n, skb, gfp_mask)) {
1937 			kfree_skb(n);
1938 			n = NULL;
1939 			goto out;
1940 		}
1941 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
1942 			skb_shinfo(n)->frags[i] = skb_shinfo(skb)->frags[i];
1943 			skb_frag_ref(skb, i);
1944 		}
1945 		skb_shinfo(n)->nr_frags = i;
1946 	}
1947 
1948 	if (skb_has_frag_list(skb)) {
1949 		skb_shinfo(n)->frag_list = skb_shinfo(skb)->frag_list;
1950 		skb_clone_fraglist(n);
1951 	}
1952 
1953 	skb_copy_header(n, skb);
1954 out:
1955 	return n;
1956 }
1957 EXPORT_SYMBOL(__pskb_copy_fclone);
1958 
1959 /**
1960  *	pskb_expand_head - reallocate header of &sk_buff
1961  *	@skb: buffer to reallocate
1962  *	@nhead: room to add at head
1963  *	@ntail: room to add at tail
1964  *	@gfp_mask: allocation priority
1965  *
1966  *	Expands (or creates identical copy, if @nhead and @ntail are zero)
1967  *	header of @skb. &sk_buff itself is not changed. &sk_buff MUST have
1968  *	reference count of 1. Returns zero in the case of success or error,
1969  *	if expansion failed. In the last case, &sk_buff is not changed.
1970  *
1971  *	All the pointers pointing into skb header may change and must be
1972  *	reloaded after call to this function.
1973  */
1974 
1975 int pskb_expand_head(struct sk_buff *skb, int nhead, int ntail,
1976 		     gfp_t gfp_mask)
1977 {
1978 	unsigned int osize = skb_end_offset(skb);
1979 	unsigned int size = osize + nhead + ntail;
1980 	long off;
1981 	u8 *data;
1982 	int i;
1983 
1984 	BUG_ON(nhead < 0);
1985 
1986 	BUG_ON(skb_shared(skb));
1987 
1988 	skb_zcopy_downgrade_managed(skb);
1989 
1990 	if (skb_pfmemalloc(skb))
1991 		gfp_mask |= __GFP_MEMALLOC;
1992 
1993 	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
1994 	if (!data)
1995 		goto nodata;
1996 	size = SKB_WITH_OVERHEAD(size);
1997 
1998 	/* Copy only real data... and, alas, header. This should be
1999 	 * optimized for the cases when header is void.
2000 	 */
2001 	memcpy(data + nhead, skb->head, skb_tail_pointer(skb) - skb->head);
2002 
2003 	memcpy((struct skb_shared_info *)(data + size),
2004 	       skb_shinfo(skb),
2005 	       offsetof(struct skb_shared_info, frags[skb_shinfo(skb)->nr_frags]));
2006 
2007 	/*
2008 	 * if shinfo is shared we must drop the old head gracefully, but if it
2009 	 * is not we can just drop the old head and let the existing refcount
2010 	 * be since all we did is relocate the values
2011 	 */
2012 	if (skb_cloned(skb)) {
2013 		if (skb_orphan_frags(skb, gfp_mask))
2014 			goto nofrags;
2015 		if (skb_zcopy(skb))
2016 			refcount_inc(&skb_uarg(skb)->refcnt);
2017 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
2018 			skb_frag_ref(skb, i);
2019 
2020 		if (skb_has_frag_list(skb))
2021 			skb_clone_fraglist(skb);
2022 
2023 		skb_release_data(skb, SKB_CONSUMED, false);
2024 	} else {
2025 		skb_free_head(skb, false);
2026 	}
2027 	off = (data + nhead) - skb->head;
2028 
2029 	skb->head     = data;
2030 	skb->head_frag = 0;
2031 	skb->data    += off;
2032 
2033 	skb_set_end_offset(skb, size);
2034 #ifdef NET_SKBUFF_DATA_USES_OFFSET
2035 	off           = nhead;
2036 #endif
2037 	skb->tail	      += off;
2038 	skb_headers_offset_update(skb, nhead);
2039 	skb->cloned   = 0;
2040 	skb->hdr_len  = 0;
2041 	skb->nohdr    = 0;
2042 	atomic_set(&skb_shinfo(skb)->dataref, 1);
2043 
2044 	skb_metadata_clear(skb);
2045 
2046 	/* It is not generally safe to change skb->truesize.
2047 	 * For the moment, we really care of rx path, or
2048 	 * when skb is orphaned (not attached to a socket).
2049 	 */
2050 	if (!skb->sk || skb->destructor == sock_edemux)
2051 		skb->truesize += size - osize;
2052 
2053 	return 0;
2054 
2055 nofrags:
2056 	skb_kfree_head(data, size);
2057 nodata:
2058 	return -ENOMEM;
2059 }
2060 EXPORT_SYMBOL(pskb_expand_head);
2061 
2062 /* Make private copy of skb with writable head and some headroom */
2063 
2064 struct sk_buff *skb_realloc_headroom(struct sk_buff *skb, unsigned int headroom)
2065 {
2066 	struct sk_buff *skb2;
2067 	int delta = headroom - skb_headroom(skb);
2068 
2069 	if (delta <= 0)
2070 		skb2 = pskb_copy(skb, GFP_ATOMIC);
2071 	else {
2072 		skb2 = skb_clone(skb, GFP_ATOMIC);
2073 		if (skb2 && pskb_expand_head(skb2, SKB_DATA_ALIGN(delta), 0,
2074 					     GFP_ATOMIC)) {
2075 			kfree_skb(skb2);
2076 			skb2 = NULL;
2077 		}
2078 	}
2079 	return skb2;
2080 }
2081 EXPORT_SYMBOL(skb_realloc_headroom);
2082 
2083 /* Note: We plan to rework this in linux-6.4 */
2084 int __skb_unclone_keeptruesize(struct sk_buff *skb, gfp_t pri)
2085 {
2086 	unsigned int saved_end_offset, saved_truesize;
2087 	struct skb_shared_info *shinfo;
2088 	int res;
2089 
2090 	saved_end_offset = skb_end_offset(skb);
2091 	saved_truesize = skb->truesize;
2092 
2093 	res = pskb_expand_head(skb, 0, 0, pri);
2094 	if (res)
2095 		return res;
2096 
2097 	skb->truesize = saved_truesize;
2098 
2099 	if (likely(skb_end_offset(skb) == saved_end_offset))
2100 		return 0;
2101 
2102 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
2103 	/* We can not change skb->end if the original or new value
2104 	 * is SKB_SMALL_HEAD_HEADROOM, as it might break skb_kfree_head().
2105 	 */
2106 	if (saved_end_offset == SKB_SMALL_HEAD_HEADROOM ||
2107 	    skb_end_offset(skb) == SKB_SMALL_HEAD_HEADROOM) {
2108 		/* We think this path should not be taken.
2109 		 * Add a temporary trace to warn us just in case.
2110 		 */
2111 		pr_err_once("__skb_unclone_keeptruesize() skb_end_offset() %u -> %u\n",
2112 			    saved_end_offset, skb_end_offset(skb));
2113 		WARN_ON_ONCE(1);
2114 		return 0;
2115 	}
2116 #endif
2117 
2118 	shinfo = skb_shinfo(skb);
2119 
2120 	/* We are about to change back skb->end,
2121 	 * we need to move skb_shinfo() to its new location.
2122 	 */
2123 	memmove(skb->head + saved_end_offset,
2124 		shinfo,
2125 		offsetof(struct skb_shared_info, frags[shinfo->nr_frags]));
2126 
2127 	skb_set_end_offset(skb, saved_end_offset);
2128 
2129 	return 0;
2130 }
2131 
2132 /**
2133  *	skb_expand_head - reallocate header of &sk_buff
2134  *	@skb: buffer to reallocate
2135  *	@headroom: needed headroom
2136  *
2137  *	Unlike skb_realloc_headroom, this one does not allocate a new skb
2138  *	if possible; copies skb->sk to new skb as needed
2139  *	and frees original skb in case of failures.
2140  *
2141  *	It expect increased headroom and generates warning otherwise.
2142  */
2143 
2144 struct sk_buff *skb_expand_head(struct sk_buff *skb, unsigned int headroom)
2145 {
2146 	int delta = headroom - skb_headroom(skb);
2147 	int osize = skb_end_offset(skb);
2148 	struct sock *sk = skb->sk;
2149 
2150 	if (WARN_ONCE(delta <= 0,
2151 		      "%s is expecting an increase in the headroom", __func__))
2152 		return skb;
2153 
2154 	delta = SKB_DATA_ALIGN(delta);
2155 	/* pskb_expand_head() might crash, if skb is shared. */
2156 	if (skb_shared(skb) || !is_skb_wmem(skb)) {
2157 		struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2158 
2159 		if (unlikely(!nskb))
2160 			goto fail;
2161 
2162 		if (sk)
2163 			skb_set_owner_w(nskb, sk);
2164 		consume_skb(skb);
2165 		skb = nskb;
2166 	}
2167 	if (pskb_expand_head(skb, delta, 0, GFP_ATOMIC))
2168 		goto fail;
2169 
2170 	if (sk && is_skb_wmem(skb)) {
2171 		delta = skb_end_offset(skb) - osize;
2172 		refcount_add(delta, &sk->sk_wmem_alloc);
2173 		skb->truesize += delta;
2174 	}
2175 	return skb;
2176 
2177 fail:
2178 	kfree_skb(skb);
2179 	return NULL;
2180 }
2181 EXPORT_SYMBOL(skb_expand_head);
2182 
2183 /**
2184  *	skb_copy_expand	-	copy and expand sk_buff
2185  *	@skb: buffer to copy
2186  *	@newheadroom: new free bytes at head
2187  *	@newtailroom: new free bytes at tail
2188  *	@gfp_mask: allocation priority
2189  *
2190  *	Make a copy of both an &sk_buff and its data and while doing so
2191  *	allocate additional space.
2192  *
2193  *	This is used when the caller wishes to modify the data and needs a
2194  *	private copy of the data to alter as well as more space for new fields.
2195  *	Returns %NULL on failure or the pointer to the buffer
2196  *	on success. The returned buffer has a reference count of 1.
2197  *
2198  *	You must pass %GFP_ATOMIC as the allocation priority if this function
2199  *	is called from an interrupt.
2200  */
2201 struct sk_buff *skb_copy_expand(const struct sk_buff *skb,
2202 				int newheadroom, int newtailroom,
2203 				gfp_t gfp_mask)
2204 {
2205 	/*
2206 	 *	Allocate the copy buffer
2207 	 */
2208 	struct sk_buff *n = __alloc_skb(newheadroom + skb->len + newtailroom,
2209 					gfp_mask, skb_alloc_rx_flag(skb),
2210 					NUMA_NO_NODE);
2211 	int oldheadroom = skb_headroom(skb);
2212 	int head_copy_len, head_copy_off;
2213 
2214 	if (!n)
2215 		return NULL;
2216 
2217 	skb_reserve(n, newheadroom);
2218 
2219 	/* Set the tail pointer and length */
2220 	skb_put(n, skb->len);
2221 
2222 	head_copy_len = oldheadroom;
2223 	head_copy_off = 0;
2224 	if (newheadroom <= head_copy_len)
2225 		head_copy_len = newheadroom;
2226 	else
2227 		head_copy_off = newheadroom - head_copy_len;
2228 
2229 	/* Copy the linear header and data. */
2230 	BUG_ON(skb_copy_bits(skb, -head_copy_len, n->head + head_copy_off,
2231 			     skb->len + head_copy_len));
2232 
2233 	skb_copy_header(n, skb);
2234 
2235 	skb_headers_offset_update(n, newheadroom - oldheadroom);
2236 
2237 	return n;
2238 }
2239 EXPORT_SYMBOL(skb_copy_expand);
2240 
2241 /**
2242  *	__skb_pad		-	zero pad the tail of an skb
2243  *	@skb: buffer to pad
2244  *	@pad: space to pad
2245  *	@free_on_error: free buffer on error
2246  *
2247  *	Ensure that a buffer is followed by a padding area that is zero
2248  *	filled. Used by network drivers which may DMA or transfer data
2249  *	beyond the buffer end onto the wire.
2250  *
2251  *	May return error in out of memory cases. The skb is freed on error
2252  *	if @free_on_error is true.
2253  */
2254 
2255 int __skb_pad(struct sk_buff *skb, int pad, bool free_on_error)
2256 {
2257 	int err;
2258 	int ntail;
2259 
2260 	/* If the skbuff is non linear tailroom is always zero.. */
2261 	if (!skb_cloned(skb) && skb_tailroom(skb) >= pad) {
2262 		memset(skb->data+skb->len, 0, pad);
2263 		return 0;
2264 	}
2265 
2266 	ntail = skb->data_len + pad - (skb->end - skb->tail);
2267 	if (likely(skb_cloned(skb) || ntail > 0)) {
2268 		err = pskb_expand_head(skb, 0, ntail, GFP_ATOMIC);
2269 		if (unlikely(err))
2270 			goto free_skb;
2271 	}
2272 
2273 	/* FIXME: The use of this function with non-linear skb's really needs
2274 	 * to be audited.
2275 	 */
2276 	err = skb_linearize(skb);
2277 	if (unlikely(err))
2278 		goto free_skb;
2279 
2280 	memset(skb->data + skb->len, 0, pad);
2281 	return 0;
2282 
2283 free_skb:
2284 	if (free_on_error)
2285 		kfree_skb(skb);
2286 	return err;
2287 }
2288 EXPORT_SYMBOL(__skb_pad);
2289 
2290 /**
2291  *	pskb_put - add data to the tail of a potentially fragmented buffer
2292  *	@skb: start of the buffer to use
2293  *	@tail: tail fragment of the buffer to use
2294  *	@len: amount of data to add
2295  *
2296  *	This function extends the used data area of the potentially
2297  *	fragmented buffer. @tail must be the last fragment of @skb -- or
2298  *	@skb itself. If this would exceed the total buffer size the kernel
2299  *	will panic. A pointer to the first byte of the extra data is
2300  *	returned.
2301  */
2302 
2303 void *pskb_put(struct sk_buff *skb, struct sk_buff *tail, int len)
2304 {
2305 	if (tail != skb) {
2306 		skb->data_len += len;
2307 		skb->len += len;
2308 	}
2309 	return skb_put(tail, len);
2310 }
2311 EXPORT_SYMBOL_GPL(pskb_put);
2312 
2313 /**
2314  *	skb_put - add data to a buffer
2315  *	@skb: buffer to use
2316  *	@len: amount of data to add
2317  *
2318  *	This function extends the used data area of the buffer. If this would
2319  *	exceed the total buffer size the kernel will panic. A pointer to the
2320  *	first byte of the extra data is returned.
2321  */
2322 void *skb_put(struct sk_buff *skb, unsigned int len)
2323 {
2324 	void *tmp = skb_tail_pointer(skb);
2325 	SKB_LINEAR_ASSERT(skb);
2326 	skb->tail += len;
2327 	skb->len  += len;
2328 	if (unlikely(skb->tail > skb->end))
2329 		skb_over_panic(skb, len, __builtin_return_address(0));
2330 	return tmp;
2331 }
2332 EXPORT_SYMBOL(skb_put);
2333 
2334 /**
2335  *	skb_push - add data to the start of a buffer
2336  *	@skb: buffer to use
2337  *	@len: amount of data to add
2338  *
2339  *	This function extends the used data area of the buffer at the buffer
2340  *	start. If this would exceed the total buffer headroom the kernel will
2341  *	panic. A pointer to the first byte of the extra data is returned.
2342  */
2343 void *skb_push(struct sk_buff *skb, unsigned int len)
2344 {
2345 	skb->data -= len;
2346 	skb->len  += len;
2347 	if (unlikely(skb->data < skb->head))
2348 		skb_under_panic(skb, len, __builtin_return_address(0));
2349 	return skb->data;
2350 }
2351 EXPORT_SYMBOL(skb_push);
2352 
2353 /**
2354  *	skb_pull - remove data from the start of a buffer
2355  *	@skb: buffer to use
2356  *	@len: amount of data to remove
2357  *
2358  *	This function removes data from the start of a buffer, returning
2359  *	the memory to the headroom. A pointer to the next data in the buffer
2360  *	is returned. Once the data has been pulled future pushes will overwrite
2361  *	the old data.
2362  */
2363 void *skb_pull(struct sk_buff *skb, unsigned int len)
2364 {
2365 	return skb_pull_inline(skb, len);
2366 }
2367 EXPORT_SYMBOL(skb_pull);
2368 
2369 /**
2370  *	skb_pull_data - remove data from the start of a buffer returning its
2371  *	original position.
2372  *	@skb: buffer to use
2373  *	@len: amount of data to remove
2374  *
2375  *	This function removes data from the start of a buffer, returning
2376  *	the memory to the headroom. A pointer to the original data in the buffer
2377  *	is returned after checking if there is enough data to pull. Once the
2378  *	data has been pulled future pushes will overwrite the old data.
2379  */
2380 void *skb_pull_data(struct sk_buff *skb, size_t len)
2381 {
2382 	void *data = skb->data;
2383 
2384 	if (skb->len < len)
2385 		return NULL;
2386 
2387 	skb_pull(skb, len);
2388 
2389 	return data;
2390 }
2391 EXPORT_SYMBOL(skb_pull_data);
2392 
2393 /**
2394  *	skb_trim - remove end from a buffer
2395  *	@skb: buffer to alter
2396  *	@len: new length
2397  *
2398  *	Cut the length of a buffer down by removing data from the tail. If
2399  *	the buffer is already under the length specified it is not modified.
2400  *	The skb must be linear.
2401  */
2402 void skb_trim(struct sk_buff *skb, unsigned int len)
2403 {
2404 	if (skb->len > len)
2405 		__skb_trim(skb, len);
2406 }
2407 EXPORT_SYMBOL(skb_trim);
2408 
2409 /* Trims skb to length len. It can change skb pointers.
2410  */
2411 
2412 int ___pskb_trim(struct sk_buff *skb, unsigned int len)
2413 {
2414 	struct sk_buff **fragp;
2415 	struct sk_buff *frag;
2416 	int offset = skb_headlen(skb);
2417 	int nfrags = skb_shinfo(skb)->nr_frags;
2418 	int i;
2419 	int err;
2420 
2421 	if (skb_cloned(skb) &&
2422 	    unlikely((err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC))))
2423 		return err;
2424 
2425 	i = 0;
2426 	if (offset >= len)
2427 		goto drop_pages;
2428 
2429 	for (; i < nfrags; i++) {
2430 		int end = offset + skb_frag_size(&skb_shinfo(skb)->frags[i]);
2431 
2432 		if (end < len) {
2433 			offset = end;
2434 			continue;
2435 		}
2436 
2437 		skb_frag_size_set(&skb_shinfo(skb)->frags[i++], len - offset);
2438 
2439 drop_pages:
2440 		skb_shinfo(skb)->nr_frags = i;
2441 
2442 		for (; i < nfrags; i++)
2443 			skb_frag_unref(skb, i);
2444 
2445 		if (skb_has_frag_list(skb))
2446 			skb_drop_fraglist(skb);
2447 		goto done;
2448 	}
2449 
2450 	for (fragp = &skb_shinfo(skb)->frag_list; (frag = *fragp);
2451 	     fragp = &frag->next) {
2452 		int end = offset + frag->len;
2453 
2454 		if (skb_shared(frag)) {
2455 			struct sk_buff *nfrag;
2456 
2457 			nfrag = skb_clone(frag, GFP_ATOMIC);
2458 			if (unlikely(!nfrag))
2459 				return -ENOMEM;
2460 
2461 			nfrag->next = frag->next;
2462 			consume_skb(frag);
2463 			frag = nfrag;
2464 			*fragp = frag;
2465 		}
2466 
2467 		if (end < len) {
2468 			offset = end;
2469 			continue;
2470 		}
2471 
2472 		if (end > len &&
2473 		    unlikely((err = pskb_trim(frag, len - offset))))
2474 			return err;
2475 
2476 		if (frag->next)
2477 			skb_drop_list(&frag->next);
2478 		break;
2479 	}
2480 
2481 done:
2482 	if (len > skb_headlen(skb)) {
2483 		skb->data_len -= skb->len - len;
2484 		skb->len       = len;
2485 	} else {
2486 		skb->len       = len;
2487 		skb->data_len  = 0;
2488 		skb_set_tail_pointer(skb, len);
2489 	}
2490 
2491 	if (!skb->sk || skb->destructor == sock_edemux)
2492 		skb_condense(skb);
2493 	return 0;
2494 }
2495 EXPORT_SYMBOL(___pskb_trim);
2496 
2497 /* Note : use pskb_trim_rcsum() instead of calling this directly
2498  */
2499 int pskb_trim_rcsum_slow(struct sk_buff *skb, unsigned int len)
2500 {
2501 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
2502 		int delta = skb->len - len;
2503 
2504 		skb->csum = csum_block_sub(skb->csum,
2505 					   skb_checksum(skb, len, delta, 0),
2506 					   len);
2507 	} else if (skb->ip_summed == CHECKSUM_PARTIAL) {
2508 		int hdlen = (len > skb_headlen(skb)) ? skb_headlen(skb) : len;
2509 		int offset = skb_checksum_start_offset(skb) + skb->csum_offset;
2510 
2511 		if (offset + sizeof(__sum16) > hdlen)
2512 			return -EINVAL;
2513 	}
2514 	return __pskb_trim(skb, len);
2515 }
2516 EXPORT_SYMBOL(pskb_trim_rcsum_slow);
2517 
2518 /**
2519  *	__pskb_pull_tail - advance tail of skb header
2520  *	@skb: buffer to reallocate
2521  *	@delta: number of bytes to advance tail
2522  *
2523  *	The function makes a sense only on a fragmented &sk_buff,
2524  *	it expands header moving its tail forward and copying necessary
2525  *	data from fragmented part.
2526  *
2527  *	&sk_buff MUST have reference count of 1.
2528  *
2529  *	Returns %NULL (and &sk_buff does not change) if pull failed
2530  *	or value of new tail of skb in the case of success.
2531  *
2532  *	All the pointers pointing into skb header may change and must be
2533  *	reloaded after call to this function.
2534  */
2535 
2536 /* Moves tail of skb head forward, copying data from fragmented part,
2537  * when it is necessary.
2538  * 1. It may fail due to malloc failure.
2539  * 2. It may change skb pointers.
2540  *
2541  * It is pretty complicated. Luckily, it is called only in exceptional cases.
2542  */
2543 void *__pskb_pull_tail(struct sk_buff *skb, int delta)
2544 {
2545 	/* If skb has not enough free space at tail, get new one
2546 	 * plus 128 bytes for future expansions. If we have enough
2547 	 * room at tail, reallocate without expansion only if skb is cloned.
2548 	 */
2549 	int i, k, eat = (skb->tail + delta) - skb->end;
2550 
2551 	if (eat > 0 || skb_cloned(skb)) {
2552 		if (pskb_expand_head(skb, 0, eat > 0 ? eat + 128 : 0,
2553 				     GFP_ATOMIC))
2554 			return NULL;
2555 	}
2556 
2557 	BUG_ON(skb_copy_bits(skb, skb_headlen(skb),
2558 			     skb_tail_pointer(skb), delta));
2559 
2560 	/* Optimization: no fragments, no reasons to preestimate
2561 	 * size of pulled pages. Superb.
2562 	 */
2563 	if (!skb_has_frag_list(skb))
2564 		goto pull_pages;
2565 
2566 	/* Estimate size of pulled pages. */
2567 	eat = delta;
2568 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2569 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2570 
2571 		if (size >= eat)
2572 			goto pull_pages;
2573 		eat -= size;
2574 	}
2575 
2576 	/* If we need update frag list, we are in troubles.
2577 	 * Certainly, it is possible to add an offset to skb data,
2578 	 * but taking into account that pulling is expected to
2579 	 * be very rare operation, it is worth to fight against
2580 	 * further bloating skb head and crucify ourselves here instead.
2581 	 * Pure masohism, indeed. 8)8)
2582 	 */
2583 	if (eat) {
2584 		struct sk_buff *list = skb_shinfo(skb)->frag_list;
2585 		struct sk_buff *clone = NULL;
2586 		struct sk_buff *insp = NULL;
2587 
2588 		do {
2589 			if (list->len <= eat) {
2590 				/* Eaten as whole. */
2591 				eat -= list->len;
2592 				list = list->next;
2593 				insp = list;
2594 			} else {
2595 				/* Eaten partially. */
2596 				if (skb_is_gso(skb) && !list->head_frag &&
2597 				    skb_headlen(list))
2598 					skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2599 
2600 				if (skb_shared(list)) {
2601 					/* Sucks! We need to fork list. :-( */
2602 					clone = skb_clone(list, GFP_ATOMIC);
2603 					if (!clone)
2604 						return NULL;
2605 					insp = list->next;
2606 					list = clone;
2607 				} else {
2608 					/* This may be pulled without
2609 					 * problems. */
2610 					insp = list;
2611 				}
2612 				if (!pskb_pull(list, eat)) {
2613 					kfree_skb(clone);
2614 					return NULL;
2615 				}
2616 				break;
2617 			}
2618 		} while (eat);
2619 
2620 		/* Free pulled out fragments. */
2621 		while ((list = skb_shinfo(skb)->frag_list) != insp) {
2622 			skb_shinfo(skb)->frag_list = list->next;
2623 			consume_skb(list);
2624 		}
2625 		/* And insert new clone at head. */
2626 		if (clone) {
2627 			clone->next = list;
2628 			skb_shinfo(skb)->frag_list = clone;
2629 		}
2630 	}
2631 	/* Success! Now we may commit changes to skb data. */
2632 
2633 pull_pages:
2634 	eat = delta;
2635 	k = 0;
2636 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2637 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
2638 
2639 		if (size <= eat) {
2640 			skb_frag_unref(skb, i);
2641 			eat -= size;
2642 		} else {
2643 			skb_frag_t *frag = &skb_shinfo(skb)->frags[k];
2644 
2645 			*frag = skb_shinfo(skb)->frags[i];
2646 			if (eat) {
2647 				skb_frag_off_add(frag, eat);
2648 				skb_frag_size_sub(frag, eat);
2649 				if (!i)
2650 					goto end;
2651 				eat = 0;
2652 			}
2653 			k++;
2654 		}
2655 	}
2656 	skb_shinfo(skb)->nr_frags = k;
2657 
2658 end:
2659 	skb->tail     += delta;
2660 	skb->data_len -= delta;
2661 
2662 	if (!skb->data_len)
2663 		skb_zcopy_clear(skb, false);
2664 
2665 	return skb_tail_pointer(skb);
2666 }
2667 EXPORT_SYMBOL(__pskb_pull_tail);
2668 
2669 /**
2670  *	skb_copy_bits - copy bits from skb to kernel buffer
2671  *	@skb: source skb
2672  *	@offset: offset in source
2673  *	@to: destination buffer
2674  *	@len: number of bytes to copy
2675  *
2676  *	Copy the specified number of bytes from the source skb to the
2677  *	destination buffer.
2678  *
2679  *	CAUTION ! :
2680  *		If its prototype is ever changed,
2681  *		check arch/{*}/net/{*}.S files,
2682  *		since it is called from BPF assembly code.
2683  */
2684 int skb_copy_bits(const struct sk_buff *skb, int offset, void *to, int len)
2685 {
2686 	int start = skb_headlen(skb);
2687 	struct sk_buff *frag_iter;
2688 	int i, copy;
2689 
2690 	if (offset > (int)skb->len - len)
2691 		goto fault;
2692 
2693 	/* Copy header. */
2694 	if ((copy = start - offset) > 0) {
2695 		if (copy > len)
2696 			copy = len;
2697 		skb_copy_from_linear_data_offset(skb, offset, to, copy);
2698 		if ((len -= copy) == 0)
2699 			return 0;
2700 		offset += copy;
2701 		to     += copy;
2702 	}
2703 
2704 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
2705 		int end;
2706 		skb_frag_t *f = &skb_shinfo(skb)->frags[i];
2707 
2708 		WARN_ON(start > offset + len);
2709 
2710 		end = start + skb_frag_size(f);
2711 		if ((copy = end - offset) > 0) {
2712 			u32 p_off, p_len, copied;
2713 			struct page *p;
2714 			u8 *vaddr;
2715 
2716 			if (copy > len)
2717 				copy = len;
2718 
2719 			skb_frag_foreach_page(f,
2720 					      skb_frag_off(f) + offset - start,
2721 					      copy, p, p_off, p_len, copied) {
2722 				vaddr = kmap_atomic(p);
2723 				memcpy(to + copied, vaddr + p_off, p_len);
2724 				kunmap_atomic(vaddr);
2725 			}
2726 
2727 			if ((len -= copy) == 0)
2728 				return 0;
2729 			offset += copy;
2730 			to     += copy;
2731 		}
2732 		start = end;
2733 	}
2734 
2735 	skb_walk_frags(skb, frag_iter) {
2736 		int end;
2737 
2738 		WARN_ON(start > offset + len);
2739 
2740 		end = start + frag_iter->len;
2741 		if ((copy = end - offset) > 0) {
2742 			if (copy > len)
2743 				copy = len;
2744 			if (skb_copy_bits(frag_iter, offset - start, to, copy))
2745 				goto fault;
2746 			if ((len -= copy) == 0)
2747 				return 0;
2748 			offset += copy;
2749 			to     += copy;
2750 		}
2751 		start = end;
2752 	}
2753 
2754 	if (!len)
2755 		return 0;
2756 
2757 fault:
2758 	return -EFAULT;
2759 }
2760 EXPORT_SYMBOL(skb_copy_bits);
2761 
2762 /*
2763  * Callback from splice_to_pipe(), if we need to release some pages
2764  * at the end of the spd in case we error'ed out in filling the pipe.
2765  */
2766 static void sock_spd_release(struct splice_pipe_desc *spd, unsigned int i)
2767 {
2768 	put_page(spd->pages[i]);
2769 }
2770 
2771 static struct page *linear_to_page(struct page *page, unsigned int *len,
2772 				   unsigned int *offset,
2773 				   struct sock *sk)
2774 {
2775 	struct page_frag *pfrag = sk_page_frag(sk);
2776 
2777 	if (!sk_page_frag_refill(sk, pfrag))
2778 		return NULL;
2779 
2780 	*len = min_t(unsigned int, *len, pfrag->size - pfrag->offset);
2781 
2782 	memcpy(page_address(pfrag->page) + pfrag->offset,
2783 	       page_address(page) + *offset, *len);
2784 	*offset = pfrag->offset;
2785 	pfrag->offset += *len;
2786 
2787 	return pfrag->page;
2788 }
2789 
2790 static bool spd_can_coalesce(const struct splice_pipe_desc *spd,
2791 			     struct page *page,
2792 			     unsigned int offset)
2793 {
2794 	return	spd->nr_pages &&
2795 		spd->pages[spd->nr_pages - 1] == page &&
2796 		(spd->partial[spd->nr_pages - 1].offset +
2797 		 spd->partial[spd->nr_pages - 1].len == offset);
2798 }
2799 
2800 /*
2801  * Fill page/offset/length into spd, if it can hold more pages.
2802  */
2803 static bool spd_fill_page(struct splice_pipe_desc *spd,
2804 			  struct pipe_inode_info *pipe, struct page *page,
2805 			  unsigned int *len, unsigned int offset,
2806 			  bool linear,
2807 			  struct sock *sk)
2808 {
2809 	if (unlikely(spd->nr_pages == MAX_SKB_FRAGS))
2810 		return true;
2811 
2812 	if (linear) {
2813 		page = linear_to_page(page, len, &offset, sk);
2814 		if (!page)
2815 			return true;
2816 	}
2817 	if (spd_can_coalesce(spd, page, offset)) {
2818 		spd->partial[spd->nr_pages - 1].len += *len;
2819 		return false;
2820 	}
2821 	get_page(page);
2822 	spd->pages[spd->nr_pages] = page;
2823 	spd->partial[spd->nr_pages].len = *len;
2824 	spd->partial[spd->nr_pages].offset = offset;
2825 	spd->nr_pages++;
2826 
2827 	return false;
2828 }
2829 
2830 static bool __splice_segment(struct page *page, unsigned int poff,
2831 			     unsigned int plen, unsigned int *off,
2832 			     unsigned int *len,
2833 			     struct splice_pipe_desc *spd, bool linear,
2834 			     struct sock *sk,
2835 			     struct pipe_inode_info *pipe)
2836 {
2837 	if (!*len)
2838 		return true;
2839 
2840 	/* skip this segment if already processed */
2841 	if (*off >= plen) {
2842 		*off -= plen;
2843 		return false;
2844 	}
2845 
2846 	/* ignore any bits we already processed */
2847 	poff += *off;
2848 	plen -= *off;
2849 	*off = 0;
2850 
2851 	do {
2852 		unsigned int flen = min(*len, plen);
2853 
2854 		if (spd_fill_page(spd, pipe, page, &flen, poff,
2855 				  linear, sk))
2856 			return true;
2857 		poff += flen;
2858 		plen -= flen;
2859 		*len -= flen;
2860 	} while (*len && plen);
2861 
2862 	return false;
2863 }
2864 
2865 /*
2866  * Map linear and fragment data from the skb to spd. It reports true if the
2867  * pipe is full or if we already spliced the requested length.
2868  */
2869 static bool __skb_splice_bits(struct sk_buff *skb, struct pipe_inode_info *pipe,
2870 			      unsigned int *offset, unsigned int *len,
2871 			      struct splice_pipe_desc *spd, struct sock *sk)
2872 {
2873 	int seg;
2874 	struct sk_buff *iter;
2875 
2876 	/* map the linear part :
2877 	 * If skb->head_frag is set, this 'linear' part is backed by a
2878 	 * fragment, and if the head is not shared with any clones then
2879 	 * we can avoid a copy since we own the head portion of this page.
2880 	 */
2881 	if (__splice_segment(virt_to_page(skb->data),
2882 			     (unsigned long) skb->data & (PAGE_SIZE - 1),
2883 			     skb_headlen(skb),
2884 			     offset, len, spd,
2885 			     skb_head_is_locked(skb),
2886 			     sk, pipe))
2887 		return true;
2888 
2889 	/*
2890 	 * then map the fragments
2891 	 */
2892 	for (seg = 0; seg < skb_shinfo(skb)->nr_frags; seg++) {
2893 		const skb_frag_t *f = &skb_shinfo(skb)->frags[seg];
2894 
2895 		if (__splice_segment(skb_frag_page(f),
2896 				     skb_frag_off(f), skb_frag_size(f),
2897 				     offset, len, spd, false, sk, pipe))
2898 			return true;
2899 	}
2900 
2901 	skb_walk_frags(skb, iter) {
2902 		if (*offset >= iter->len) {
2903 			*offset -= iter->len;
2904 			continue;
2905 		}
2906 		/* __skb_splice_bits() only fails if the output has no room
2907 		 * left, so no point in going over the frag_list for the error
2908 		 * case.
2909 		 */
2910 		if (__skb_splice_bits(iter, pipe, offset, len, spd, sk))
2911 			return true;
2912 	}
2913 
2914 	return false;
2915 }
2916 
2917 /*
2918  * Map data from the skb to a pipe. Should handle both the linear part,
2919  * the fragments, and the frag list.
2920  */
2921 int skb_splice_bits(struct sk_buff *skb, struct sock *sk, unsigned int offset,
2922 		    struct pipe_inode_info *pipe, unsigned int tlen,
2923 		    unsigned int flags)
2924 {
2925 	struct partial_page partial[MAX_SKB_FRAGS];
2926 	struct page *pages[MAX_SKB_FRAGS];
2927 	struct splice_pipe_desc spd = {
2928 		.pages = pages,
2929 		.partial = partial,
2930 		.nr_pages_max = MAX_SKB_FRAGS,
2931 		.ops = &nosteal_pipe_buf_ops,
2932 		.spd_release = sock_spd_release,
2933 	};
2934 	int ret = 0;
2935 
2936 	__skb_splice_bits(skb, pipe, &offset, &tlen, &spd, sk);
2937 
2938 	if (spd.nr_pages)
2939 		ret = splice_to_pipe(pipe, &spd);
2940 
2941 	return ret;
2942 }
2943 EXPORT_SYMBOL_GPL(skb_splice_bits);
2944 
2945 static int sendmsg_unlocked(struct sock *sk, struct msghdr *msg,
2946 			    struct kvec *vec, size_t num, size_t size)
2947 {
2948 	struct socket *sock = sk->sk_socket;
2949 
2950 	if (!sock)
2951 		return -EINVAL;
2952 	return kernel_sendmsg(sock, msg, vec, num, size);
2953 }
2954 
2955 static int sendpage_unlocked(struct sock *sk, struct page *page, int offset,
2956 			     size_t size, int flags)
2957 {
2958 	struct socket *sock = sk->sk_socket;
2959 
2960 	if (!sock)
2961 		return -EINVAL;
2962 	return kernel_sendpage(sock, page, offset, size, flags);
2963 }
2964 
2965 typedef int (*sendmsg_func)(struct sock *sk, struct msghdr *msg,
2966 			    struct kvec *vec, size_t num, size_t size);
2967 typedef int (*sendpage_func)(struct sock *sk, struct page *page, int offset,
2968 			     size_t size, int flags);
2969 static int __skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset,
2970 			   int len, sendmsg_func sendmsg, sendpage_func sendpage)
2971 {
2972 	unsigned int orig_len = len;
2973 	struct sk_buff *head = skb;
2974 	unsigned short fragidx;
2975 	int slen, ret;
2976 
2977 do_frag_list:
2978 
2979 	/* Deal with head data */
2980 	while (offset < skb_headlen(skb) && len) {
2981 		struct kvec kv;
2982 		struct msghdr msg;
2983 
2984 		slen = min_t(int, len, skb_headlen(skb) - offset);
2985 		kv.iov_base = skb->data + offset;
2986 		kv.iov_len = slen;
2987 		memset(&msg, 0, sizeof(msg));
2988 		msg.msg_flags = MSG_DONTWAIT;
2989 
2990 		ret = INDIRECT_CALL_2(sendmsg, kernel_sendmsg_locked,
2991 				      sendmsg_unlocked, sk, &msg, &kv, 1, slen);
2992 		if (ret <= 0)
2993 			goto error;
2994 
2995 		offset += ret;
2996 		len -= ret;
2997 	}
2998 
2999 	/* All the data was skb head? */
3000 	if (!len)
3001 		goto out;
3002 
3003 	/* Make offset relative to start of frags */
3004 	offset -= skb_headlen(skb);
3005 
3006 	/* Find where we are in frag list */
3007 	for (fragidx = 0; fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3008 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
3009 
3010 		if (offset < skb_frag_size(frag))
3011 			break;
3012 
3013 		offset -= skb_frag_size(frag);
3014 	}
3015 
3016 	for (; len && fragidx < skb_shinfo(skb)->nr_frags; fragidx++) {
3017 		skb_frag_t *frag  = &skb_shinfo(skb)->frags[fragidx];
3018 
3019 		slen = min_t(size_t, len, skb_frag_size(frag) - offset);
3020 
3021 		while (slen) {
3022 			ret = INDIRECT_CALL_2(sendpage, kernel_sendpage_locked,
3023 					      sendpage_unlocked, sk,
3024 					      skb_frag_page(frag),
3025 					      skb_frag_off(frag) + offset,
3026 					      slen, MSG_DONTWAIT);
3027 			if (ret <= 0)
3028 				goto error;
3029 
3030 			len -= ret;
3031 			offset += ret;
3032 			slen -= ret;
3033 		}
3034 
3035 		offset = 0;
3036 	}
3037 
3038 	if (len) {
3039 		/* Process any frag lists */
3040 
3041 		if (skb == head) {
3042 			if (skb_has_frag_list(skb)) {
3043 				skb = skb_shinfo(skb)->frag_list;
3044 				goto do_frag_list;
3045 			}
3046 		} else if (skb->next) {
3047 			skb = skb->next;
3048 			goto do_frag_list;
3049 		}
3050 	}
3051 
3052 out:
3053 	return orig_len - len;
3054 
3055 error:
3056 	return orig_len == len ? ret : orig_len - len;
3057 }
3058 
3059 /* Send skb data on a socket. Socket must be locked. */
3060 int skb_send_sock_locked(struct sock *sk, struct sk_buff *skb, int offset,
3061 			 int len)
3062 {
3063 	return __skb_send_sock(sk, skb, offset, len, kernel_sendmsg_locked,
3064 			       kernel_sendpage_locked);
3065 }
3066 EXPORT_SYMBOL_GPL(skb_send_sock_locked);
3067 
3068 /* Send skb data on a socket. Socket must be unlocked. */
3069 int skb_send_sock(struct sock *sk, struct sk_buff *skb, int offset, int len)
3070 {
3071 	return __skb_send_sock(sk, skb, offset, len, sendmsg_unlocked,
3072 			       sendpage_unlocked);
3073 }
3074 
3075 /**
3076  *	skb_store_bits - store bits from kernel buffer to skb
3077  *	@skb: destination buffer
3078  *	@offset: offset in destination
3079  *	@from: source buffer
3080  *	@len: number of bytes to copy
3081  *
3082  *	Copy the specified number of bytes from the source buffer to the
3083  *	destination skb.  This function handles all the messy bits of
3084  *	traversing fragment lists and such.
3085  */
3086 
3087 int skb_store_bits(struct sk_buff *skb, int offset, const void *from, int len)
3088 {
3089 	int start = skb_headlen(skb);
3090 	struct sk_buff *frag_iter;
3091 	int i, copy;
3092 
3093 	if (offset > (int)skb->len - len)
3094 		goto fault;
3095 
3096 	if ((copy = start - offset) > 0) {
3097 		if (copy > len)
3098 			copy = len;
3099 		skb_copy_to_linear_data_offset(skb, offset, from, copy);
3100 		if ((len -= copy) == 0)
3101 			return 0;
3102 		offset += copy;
3103 		from += copy;
3104 	}
3105 
3106 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3107 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3108 		int end;
3109 
3110 		WARN_ON(start > offset + len);
3111 
3112 		end = start + skb_frag_size(frag);
3113 		if ((copy = end - offset) > 0) {
3114 			u32 p_off, p_len, copied;
3115 			struct page *p;
3116 			u8 *vaddr;
3117 
3118 			if (copy > len)
3119 				copy = len;
3120 
3121 			skb_frag_foreach_page(frag,
3122 					      skb_frag_off(frag) + offset - start,
3123 					      copy, p, p_off, p_len, copied) {
3124 				vaddr = kmap_atomic(p);
3125 				memcpy(vaddr + p_off, from + copied, p_len);
3126 				kunmap_atomic(vaddr);
3127 			}
3128 
3129 			if ((len -= copy) == 0)
3130 				return 0;
3131 			offset += copy;
3132 			from += copy;
3133 		}
3134 		start = end;
3135 	}
3136 
3137 	skb_walk_frags(skb, frag_iter) {
3138 		int end;
3139 
3140 		WARN_ON(start > offset + len);
3141 
3142 		end = start + frag_iter->len;
3143 		if ((copy = end - offset) > 0) {
3144 			if (copy > len)
3145 				copy = len;
3146 			if (skb_store_bits(frag_iter, offset - start,
3147 					   from, copy))
3148 				goto fault;
3149 			if ((len -= copy) == 0)
3150 				return 0;
3151 			offset += copy;
3152 			from += copy;
3153 		}
3154 		start = end;
3155 	}
3156 	if (!len)
3157 		return 0;
3158 
3159 fault:
3160 	return -EFAULT;
3161 }
3162 EXPORT_SYMBOL(skb_store_bits);
3163 
3164 /* Checksum skb data. */
3165 __wsum __skb_checksum(const struct sk_buff *skb, int offset, int len,
3166 		      __wsum csum, const struct skb_checksum_ops *ops)
3167 {
3168 	int start = skb_headlen(skb);
3169 	int i, copy = start - offset;
3170 	struct sk_buff *frag_iter;
3171 	int pos = 0;
3172 
3173 	/* Checksum header. */
3174 	if (copy > 0) {
3175 		if (copy > len)
3176 			copy = len;
3177 		csum = INDIRECT_CALL_1(ops->update, csum_partial_ext,
3178 				       skb->data + offset, copy, csum);
3179 		if ((len -= copy) == 0)
3180 			return csum;
3181 		offset += copy;
3182 		pos	= copy;
3183 	}
3184 
3185 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3186 		int end;
3187 		skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3188 
3189 		WARN_ON(start > offset + len);
3190 
3191 		end = start + skb_frag_size(frag);
3192 		if ((copy = end - offset) > 0) {
3193 			u32 p_off, p_len, copied;
3194 			struct page *p;
3195 			__wsum csum2;
3196 			u8 *vaddr;
3197 
3198 			if (copy > len)
3199 				copy = len;
3200 
3201 			skb_frag_foreach_page(frag,
3202 					      skb_frag_off(frag) + offset - start,
3203 					      copy, p, p_off, p_len, copied) {
3204 				vaddr = kmap_atomic(p);
3205 				csum2 = INDIRECT_CALL_1(ops->update,
3206 							csum_partial_ext,
3207 							vaddr + p_off, p_len, 0);
3208 				kunmap_atomic(vaddr);
3209 				csum = INDIRECT_CALL_1(ops->combine,
3210 						       csum_block_add_ext, csum,
3211 						       csum2, pos, p_len);
3212 				pos += p_len;
3213 			}
3214 
3215 			if (!(len -= copy))
3216 				return csum;
3217 			offset += copy;
3218 		}
3219 		start = end;
3220 	}
3221 
3222 	skb_walk_frags(skb, frag_iter) {
3223 		int end;
3224 
3225 		WARN_ON(start > offset + len);
3226 
3227 		end = start + frag_iter->len;
3228 		if ((copy = end - offset) > 0) {
3229 			__wsum csum2;
3230 			if (copy > len)
3231 				copy = len;
3232 			csum2 = __skb_checksum(frag_iter, offset - start,
3233 					       copy, 0, ops);
3234 			csum = INDIRECT_CALL_1(ops->combine, csum_block_add_ext,
3235 					       csum, csum2, pos, copy);
3236 			if ((len -= copy) == 0)
3237 				return csum;
3238 			offset += copy;
3239 			pos    += copy;
3240 		}
3241 		start = end;
3242 	}
3243 	BUG_ON(len);
3244 
3245 	return csum;
3246 }
3247 EXPORT_SYMBOL(__skb_checksum);
3248 
3249 __wsum skb_checksum(const struct sk_buff *skb, int offset,
3250 		    int len, __wsum csum)
3251 {
3252 	const struct skb_checksum_ops ops = {
3253 		.update  = csum_partial_ext,
3254 		.combine = csum_block_add_ext,
3255 	};
3256 
3257 	return __skb_checksum(skb, offset, len, csum, &ops);
3258 }
3259 EXPORT_SYMBOL(skb_checksum);
3260 
3261 /* Both of above in one bottle. */
3262 
3263 __wsum skb_copy_and_csum_bits(const struct sk_buff *skb, int offset,
3264 				    u8 *to, int len)
3265 {
3266 	int start = skb_headlen(skb);
3267 	int i, copy = start - offset;
3268 	struct sk_buff *frag_iter;
3269 	int pos = 0;
3270 	__wsum csum = 0;
3271 
3272 	/* Copy header. */
3273 	if (copy > 0) {
3274 		if (copy > len)
3275 			copy = len;
3276 		csum = csum_partial_copy_nocheck(skb->data + offset, to,
3277 						 copy);
3278 		if ((len -= copy) == 0)
3279 			return csum;
3280 		offset += copy;
3281 		to     += copy;
3282 		pos	= copy;
3283 	}
3284 
3285 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
3286 		int end;
3287 
3288 		WARN_ON(start > offset + len);
3289 
3290 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
3291 		if ((copy = end - offset) > 0) {
3292 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
3293 			u32 p_off, p_len, copied;
3294 			struct page *p;
3295 			__wsum csum2;
3296 			u8 *vaddr;
3297 
3298 			if (copy > len)
3299 				copy = len;
3300 
3301 			skb_frag_foreach_page(frag,
3302 					      skb_frag_off(frag) + offset - start,
3303 					      copy, p, p_off, p_len, copied) {
3304 				vaddr = kmap_atomic(p);
3305 				csum2 = csum_partial_copy_nocheck(vaddr + p_off,
3306 								  to + copied,
3307 								  p_len);
3308 				kunmap_atomic(vaddr);
3309 				csum = csum_block_add(csum, csum2, pos);
3310 				pos += p_len;
3311 			}
3312 
3313 			if (!(len -= copy))
3314 				return csum;
3315 			offset += copy;
3316 			to     += copy;
3317 		}
3318 		start = end;
3319 	}
3320 
3321 	skb_walk_frags(skb, frag_iter) {
3322 		__wsum csum2;
3323 		int end;
3324 
3325 		WARN_ON(start > offset + len);
3326 
3327 		end = start + frag_iter->len;
3328 		if ((copy = end - offset) > 0) {
3329 			if (copy > len)
3330 				copy = len;
3331 			csum2 = skb_copy_and_csum_bits(frag_iter,
3332 						       offset - start,
3333 						       to, copy);
3334 			csum = csum_block_add(csum, csum2, pos);
3335 			if ((len -= copy) == 0)
3336 				return csum;
3337 			offset += copy;
3338 			to     += copy;
3339 			pos    += copy;
3340 		}
3341 		start = end;
3342 	}
3343 	BUG_ON(len);
3344 	return csum;
3345 }
3346 EXPORT_SYMBOL(skb_copy_and_csum_bits);
3347 
3348 __sum16 __skb_checksum_complete_head(struct sk_buff *skb, int len)
3349 {
3350 	__sum16 sum;
3351 
3352 	sum = csum_fold(skb_checksum(skb, 0, len, skb->csum));
3353 	/* See comments in __skb_checksum_complete(). */
3354 	if (likely(!sum)) {
3355 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3356 		    !skb->csum_complete_sw)
3357 			netdev_rx_csum_fault(skb->dev, skb);
3358 	}
3359 	if (!skb_shared(skb))
3360 		skb->csum_valid = !sum;
3361 	return sum;
3362 }
3363 EXPORT_SYMBOL(__skb_checksum_complete_head);
3364 
3365 /* This function assumes skb->csum already holds pseudo header's checksum,
3366  * which has been changed from the hardware checksum, for example, by
3367  * __skb_checksum_validate_complete(). And, the original skb->csum must
3368  * have been validated unsuccessfully for CHECKSUM_COMPLETE case.
3369  *
3370  * It returns non-zero if the recomputed checksum is still invalid, otherwise
3371  * zero. The new checksum is stored back into skb->csum unless the skb is
3372  * shared.
3373  */
3374 __sum16 __skb_checksum_complete(struct sk_buff *skb)
3375 {
3376 	__wsum csum;
3377 	__sum16 sum;
3378 
3379 	csum = skb_checksum(skb, 0, skb->len, 0);
3380 
3381 	sum = csum_fold(csum_add(skb->csum, csum));
3382 	/* This check is inverted, because we already knew the hardware
3383 	 * checksum is invalid before calling this function. So, if the
3384 	 * re-computed checksum is valid instead, then we have a mismatch
3385 	 * between the original skb->csum and skb_checksum(). This means either
3386 	 * the original hardware checksum is incorrect or we screw up skb->csum
3387 	 * when moving skb->data around.
3388 	 */
3389 	if (likely(!sum)) {
3390 		if (unlikely(skb->ip_summed == CHECKSUM_COMPLETE) &&
3391 		    !skb->csum_complete_sw)
3392 			netdev_rx_csum_fault(skb->dev, skb);
3393 	}
3394 
3395 	if (!skb_shared(skb)) {
3396 		/* Save full packet checksum */
3397 		skb->csum = csum;
3398 		skb->ip_summed = CHECKSUM_COMPLETE;
3399 		skb->csum_complete_sw = 1;
3400 		skb->csum_valid = !sum;
3401 	}
3402 
3403 	return sum;
3404 }
3405 EXPORT_SYMBOL(__skb_checksum_complete);
3406 
3407 static __wsum warn_crc32c_csum_update(const void *buff, int len, __wsum sum)
3408 {
3409 	net_warn_ratelimited(
3410 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
3411 		__func__);
3412 	return 0;
3413 }
3414 
3415 static __wsum warn_crc32c_csum_combine(__wsum csum, __wsum csum2,
3416 				       int offset, int len)
3417 {
3418 	net_warn_ratelimited(
3419 		"%s: attempt to compute crc32c without libcrc32c.ko\n",
3420 		__func__);
3421 	return 0;
3422 }
3423 
3424 static const struct skb_checksum_ops default_crc32c_ops = {
3425 	.update  = warn_crc32c_csum_update,
3426 	.combine = warn_crc32c_csum_combine,
3427 };
3428 
3429 const struct skb_checksum_ops *crc32c_csum_stub __read_mostly =
3430 	&default_crc32c_ops;
3431 EXPORT_SYMBOL(crc32c_csum_stub);
3432 
3433  /**
3434  *	skb_zerocopy_headlen - Calculate headroom needed for skb_zerocopy()
3435  *	@from: source buffer
3436  *
3437  *	Calculates the amount of linear headroom needed in the 'to' skb passed
3438  *	into skb_zerocopy().
3439  */
3440 unsigned int
3441 skb_zerocopy_headlen(const struct sk_buff *from)
3442 {
3443 	unsigned int hlen = 0;
3444 
3445 	if (!from->head_frag ||
3446 	    skb_headlen(from) < L1_CACHE_BYTES ||
3447 	    skb_shinfo(from)->nr_frags >= MAX_SKB_FRAGS) {
3448 		hlen = skb_headlen(from);
3449 		if (!hlen)
3450 			hlen = from->len;
3451 	}
3452 
3453 	if (skb_has_frag_list(from))
3454 		hlen = from->len;
3455 
3456 	return hlen;
3457 }
3458 EXPORT_SYMBOL_GPL(skb_zerocopy_headlen);
3459 
3460 /**
3461  *	skb_zerocopy - Zero copy skb to skb
3462  *	@to: destination buffer
3463  *	@from: source buffer
3464  *	@len: number of bytes to copy from source buffer
3465  *	@hlen: size of linear headroom in destination buffer
3466  *
3467  *	Copies up to `len` bytes from `from` to `to` by creating references
3468  *	to the frags in the source buffer.
3469  *
3470  *	The `hlen` as calculated by skb_zerocopy_headlen() specifies the
3471  *	headroom in the `to` buffer.
3472  *
3473  *	Return value:
3474  *	0: everything is OK
3475  *	-ENOMEM: couldn't orphan frags of @from due to lack of memory
3476  *	-EFAULT: skb_copy_bits() found some problem with skb geometry
3477  */
3478 int
3479 skb_zerocopy(struct sk_buff *to, struct sk_buff *from, int len, int hlen)
3480 {
3481 	int i, j = 0;
3482 	int plen = 0; /* length of skb->head fragment */
3483 	int ret;
3484 	struct page *page;
3485 	unsigned int offset;
3486 
3487 	BUG_ON(!from->head_frag && !hlen);
3488 
3489 	/* dont bother with small payloads */
3490 	if (len <= skb_tailroom(to))
3491 		return skb_copy_bits(from, 0, skb_put(to, len), len);
3492 
3493 	if (hlen) {
3494 		ret = skb_copy_bits(from, 0, skb_put(to, hlen), hlen);
3495 		if (unlikely(ret))
3496 			return ret;
3497 		len -= hlen;
3498 	} else {
3499 		plen = min_t(int, skb_headlen(from), len);
3500 		if (plen) {
3501 			page = virt_to_head_page(from->head);
3502 			offset = from->data - (unsigned char *)page_address(page);
3503 			__skb_fill_page_desc(to, 0, page, offset, plen);
3504 			get_page(page);
3505 			j = 1;
3506 			len -= plen;
3507 		}
3508 	}
3509 
3510 	skb_len_add(to, len + plen);
3511 
3512 	if (unlikely(skb_orphan_frags(from, GFP_ATOMIC))) {
3513 		skb_tx_error(from);
3514 		return -ENOMEM;
3515 	}
3516 	skb_zerocopy_clone(to, from, GFP_ATOMIC);
3517 
3518 	for (i = 0; i < skb_shinfo(from)->nr_frags; i++) {
3519 		int size;
3520 
3521 		if (!len)
3522 			break;
3523 		skb_shinfo(to)->frags[j] = skb_shinfo(from)->frags[i];
3524 		size = min_t(int, skb_frag_size(&skb_shinfo(to)->frags[j]),
3525 					len);
3526 		skb_frag_size_set(&skb_shinfo(to)->frags[j], size);
3527 		len -= size;
3528 		skb_frag_ref(to, j);
3529 		j++;
3530 	}
3531 	skb_shinfo(to)->nr_frags = j;
3532 
3533 	return 0;
3534 }
3535 EXPORT_SYMBOL_GPL(skb_zerocopy);
3536 
3537 void skb_copy_and_csum_dev(const struct sk_buff *skb, u8 *to)
3538 {
3539 	__wsum csum;
3540 	long csstart;
3541 
3542 	if (skb->ip_summed == CHECKSUM_PARTIAL)
3543 		csstart = skb_checksum_start_offset(skb);
3544 	else
3545 		csstart = skb_headlen(skb);
3546 
3547 	BUG_ON(csstart > skb_headlen(skb));
3548 
3549 	skb_copy_from_linear_data(skb, to, csstart);
3550 
3551 	csum = 0;
3552 	if (csstart != skb->len)
3553 		csum = skb_copy_and_csum_bits(skb, csstart, to + csstart,
3554 					      skb->len - csstart);
3555 
3556 	if (skb->ip_summed == CHECKSUM_PARTIAL) {
3557 		long csstuff = csstart + skb->csum_offset;
3558 
3559 		*((__sum16 *)(to + csstuff)) = csum_fold(csum);
3560 	}
3561 }
3562 EXPORT_SYMBOL(skb_copy_and_csum_dev);
3563 
3564 /**
3565  *	skb_dequeue - remove from the head of the queue
3566  *	@list: list to dequeue from
3567  *
3568  *	Remove the head of the list. The list lock is taken so the function
3569  *	may be used safely with other locking list functions. The head item is
3570  *	returned or %NULL if the list is empty.
3571  */
3572 
3573 struct sk_buff *skb_dequeue(struct sk_buff_head *list)
3574 {
3575 	unsigned long flags;
3576 	struct sk_buff *result;
3577 
3578 	spin_lock_irqsave(&list->lock, flags);
3579 	result = __skb_dequeue(list);
3580 	spin_unlock_irqrestore(&list->lock, flags);
3581 	return result;
3582 }
3583 EXPORT_SYMBOL(skb_dequeue);
3584 
3585 /**
3586  *	skb_dequeue_tail - remove from the tail of the queue
3587  *	@list: list to dequeue from
3588  *
3589  *	Remove the tail of the list. The list lock is taken so the function
3590  *	may be used safely with other locking list functions. The tail item is
3591  *	returned or %NULL if the list is empty.
3592  */
3593 struct sk_buff *skb_dequeue_tail(struct sk_buff_head *list)
3594 {
3595 	unsigned long flags;
3596 	struct sk_buff *result;
3597 
3598 	spin_lock_irqsave(&list->lock, flags);
3599 	result = __skb_dequeue_tail(list);
3600 	spin_unlock_irqrestore(&list->lock, flags);
3601 	return result;
3602 }
3603 EXPORT_SYMBOL(skb_dequeue_tail);
3604 
3605 /**
3606  *	skb_queue_purge - empty a list
3607  *	@list: list to empty
3608  *
3609  *	Delete all buffers on an &sk_buff list. Each buffer is removed from
3610  *	the list and one reference dropped. This function takes the list
3611  *	lock and is atomic with respect to other list locking functions.
3612  */
3613 void skb_queue_purge(struct sk_buff_head *list)
3614 {
3615 	struct sk_buff *skb;
3616 	while ((skb = skb_dequeue(list)) != NULL)
3617 		kfree_skb(skb);
3618 }
3619 EXPORT_SYMBOL(skb_queue_purge);
3620 
3621 /**
3622  *	skb_rbtree_purge - empty a skb rbtree
3623  *	@root: root of the rbtree to empty
3624  *	Return value: the sum of truesizes of all purged skbs.
3625  *
3626  *	Delete all buffers on an &sk_buff rbtree. Each buffer is removed from
3627  *	the list and one reference dropped. This function does not take
3628  *	any lock. Synchronization should be handled by the caller (e.g., TCP
3629  *	out-of-order queue is protected by the socket lock).
3630  */
3631 unsigned int skb_rbtree_purge(struct rb_root *root)
3632 {
3633 	struct rb_node *p = rb_first(root);
3634 	unsigned int sum = 0;
3635 
3636 	while (p) {
3637 		struct sk_buff *skb = rb_entry(p, struct sk_buff, rbnode);
3638 
3639 		p = rb_next(p);
3640 		rb_erase(&skb->rbnode, root);
3641 		sum += skb->truesize;
3642 		kfree_skb(skb);
3643 	}
3644 	return sum;
3645 }
3646 
3647 /**
3648  *	skb_queue_head - queue a buffer at the list head
3649  *	@list: list to use
3650  *	@newsk: buffer to queue
3651  *
3652  *	Queue a buffer at the start of the list. This function takes the
3653  *	list lock and can be used safely with other locking &sk_buff functions
3654  *	safely.
3655  *
3656  *	A buffer cannot be placed on two lists at the same time.
3657  */
3658 void skb_queue_head(struct sk_buff_head *list, struct sk_buff *newsk)
3659 {
3660 	unsigned long flags;
3661 
3662 	spin_lock_irqsave(&list->lock, flags);
3663 	__skb_queue_head(list, newsk);
3664 	spin_unlock_irqrestore(&list->lock, flags);
3665 }
3666 EXPORT_SYMBOL(skb_queue_head);
3667 
3668 /**
3669  *	skb_queue_tail - queue a buffer at the list tail
3670  *	@list: list to use
3671  *	@newsk: buffer to queue
3672  *
3673  *	Queue a buffer at the tail of the list. This function takes the
3674  *	list lock and can be used safely with other locking &sk_buff functions
3675  *	safely.
3676  *
3677  *	A buffer cannot be placed on two lists at the same time.
3678  */
3679 void skb_queue_tail(struct sk_buff_head *list, struct sk_buff *newsk)
3680 {
3681 	unsigned long flags;
3682 
3683 	spin_lock_irqsave(&list->lock, flags);
3684 	__skb_queue_tail(list, newsk);
3685 	spin_unlock_irqrestore(&list->lock, flags);
3686 }
3687 EXPORT_SYMBOL(skb_queue_tail);
3688 
3689 /**
3690  *	skb_unlink	-	remove a buffer from a list
3691  *	@skb: buffer to remove
3692  *	@list: list to use
3693  *
3694  *	Remove a packet from a list. The list locks are taken and this
3695  *	function is atomic with respect to other list locked calls
3696  *
3697  *	You must know what list the SKB is on.
3698  */
3699 void skb_unlink(struct sk_buff *skb, struct sk_buff_head *list)
3700 {
3701 	unsigned long flags;
3702 
3703 	spin_lock_irqsave(&list->lock, flags);
3704 	__skb_unlink(skb, list);
3705 	spin_unlock_irqrestore(&list->lock, flags);
3706 }
3707 EXPORT_SYMBOL(skb_unlink);
3708 
3709 /**
3710  *	skb_append	-	append a buffer
3711  *	@old: buffer to insert after
3712  *	@newsk: buffer to insert
3713  *	@list: list to use
3714  *
3715  *	Place a packet after a given packet in a list. The list locks are taken
3716  *	and this function is atomic with respect to other list locked calls.
3717  *	A buffer cannot be placed on two lists at the same time.
3718  */
3719 void skb_append(struct sk_buff *old, struct sk_buff *newsk, struct sk_buff_head *list)
3720 {
3721 	unsigned long flags;
3722 
3723 	spin_lock_irqsave(&list->lock, flags);
3724 	__skb_queue_after(list, old, newsk);
3725 	spin_unlock_irqrestore(&list->lock, flags);
3726 }
3727 EXPORT_SYMBOL(skb_append);
3728 
3729 static inline void skb_split_inside_header(struct sk_buff *skb,
3730 					   struct sk_buff* skb1,
3731 					   const u32 len, const int pos)
3732 {
3733 	int i;
3734 
3735 	skb_copy_from_linear_data_offset(skb, len, skb_put(skb1, pos - len),
3736 					 pos - len);
3737 	/* And move data appendix as is. */
3738 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
3739 		skb_shinfo(skb1)->frags[i] = skb_shinfo(skb)->frags[i];
3740 
3741 	skb_shinfo(skb1)->nr_frags = skb_shinfo(skb)->nr_frags;
3742 	skb_shinfo(skb)->nr_frags  = 0;
3743 	skb1->data_len		   = skb->data_len;
3744 	skb1->len		   += skb1->data_len;
3745 	skb->data_len		   = 0;
3746 	skb->len		   = len;
3747 	skb_set_tail_pointer(skb, len);
3748 }
3749 
3750 static inline void skb_split_no_header(struct sk_buff *skb,
3751 				       struct sk_buff* skb1,
3752 				       const u32 len, int pos)
3753 {
3754 	int i, k = 0;
3755 	const int nfrags = skb_shinfo(skb)->nr_frags;
3756 
3757 	skb_shinfo(skb)->nr_frags = 0;
3758 	skb1->len		  = skb1->data_len = skb->len - len;
3759 	skb->len		  = len;
3760 	skb->data_len		  = len - pos;
3761 
3762 	for (i = 0; i < nfrags; i++) {
3763 		int size = skb_frag_size(&skb_shinfo(skb)->frags[i]);
3764 
3765 		if (pos + size > len) {
3766 			skb_shinfo(skb1)->frags[k] = skb_shinfo(skb)->frags[i];
3767 
3768 			if (pos < len) {
3769 				/* Split frag.
3770 				 * We have two variants in this case:
3771 				 * 1. Move all the frag to the second
3772 				 *    part, if it is possible. F.e.
3773 				 *    this approach is mandatory for TUX,
3774 				 *    where splitting is expensive.
3775 				 * 2. Split is accurately. We make this.
3776 				 */
3777 				skb_frag_ref(skb, i);
3778 				skb_frag_off_add(&skb_shinfo(skb1)->frags[0], len - pos);
3779 				skb_frag_size_sub(&skb_shinfo(skb1)->frags[0], len - pos);
3780 				skb_frag_size_set(&skb_shinfo(skb)->frags[i], len - pos);
3781 				skb_shinfo(skb)->nr_frags++;
3782 			}
3783 			k++;
3784 		} else
3785 			skb_shinfo(skb)->nr_frags++;
3786 		pos += size;
3787 	}
3788 	skb_shinfo(skb1)->nr_frags = k;
3789 }
3790 
3791 /**
3792  * skb_split - Split fragmented skb to two parts at length len.
3793  * @skb: the buffer to split
3794  * @skb1: the buffer to receive the second part
3795  * @len: new length for skb
3796  */
3797 void skb_split(struct sk_buff *skb, struct sk_buff *skb1, const u32 len)
3798 {
3799 	int pos = skb_headlen(skb);
3800 	const int zc_flags = SKBFL_SHARED_FRAG | SKBFL_PURE_ZEROCOPY;
3801 
3802 	skb_zcopy_downgrade_managed(skb);
3803 
3804 	skb_shinfo(skb1)->flags |= skb_shinfo(skb)->flags & zc_flags;
3805 	skb_zerocopy_clone(skb1, skb, 0);
3806 	if (len < pos)	/* Split line is inside header. */
3807 		skb_split_inside_header(skb, skb1, len, pos);
3808 	else		/* Second chunk has no header, nothing to copy. */
3809 		skb_split_no_header(skb, skb1, len, pos);
3810 }
3811 EXPORT_SYMBOL(skb_split);
3812 
3813 /* Shifting from/to a cloned skb is a no-go.
3814  *
3815  * Caller cannot keep skb_shinfo related pointers past calling here!
3816  */
3817 static int skb_prepare_for_shift(struct sk_buff *skb)
3818 {
3819 	return skb_unclone_keeptruesize(skb, GFP_ATOMIC);
3820 }
3821 
3822 /**
3823  * skb_shift - Shifts paged data partially from skb to another
3824  * @tgt: buffer into which tail data gets added
3825  * @skb: buffer from which the paged data comes from
3826  * @shiftlen: shift up to this many bytes
3827  *
3828  * Attempts to shift up to shiftlen worth of bytes, which may be less than
3829  * the length of the skb, from skb to tgt. Returns number bytes shifted.
3830  * It's up to caller to free skb if everything was shifted.
3831  *
3832  * If @tgt runs out of frags, the whole operation is aborted.
3833  *
3834  * Skb cannot include anything else but paged data while tgt is allowed
3835  * to have non-paged data as well.
3836  *
3837  * TODO: full sized shift could be optimized but that would need
3838  * specialized skb free'er to handle frags without up-to-date nr_frags.
3839  */
3840 int skb_shift(struct sk_buff *tgt, struct sk_buff *skb, int shiftlen)
3841 {
3842 	int from, to, merge, todo;
3843 	skb_frag_t *fragfrom, *fragto;
3844 
3845 	BUG_ON(shiftlen > skb->len);
3846 
3847 	if (skb_headlen(skb))
3848 		return 0;
3849 	if (skb_zcopy(tgt) || skb_zcopy(skb))
3850 		return 0;
3851 
3852 	todo = shiftlen;
3853 	from = 0;
3854 	to = skb_shinfo(tgt)->nr_frags;
3855 	fragfrom = &skb_shinfo(skb)->frags[from];
3856 
3857 	/* Actual merge is delayed until the point when we know we can
3858 	 * commit all, so that we don't have to undo partial changes
3859 	 */
3860 	if (!to ||
3861 	    !skb_can_coalesce(tgt, to, skb_frag_page(fragfrom),
3862 			      skb_frag_off(fragfrom))) {
3863 		merge = -1;
3864 	} else {
3865 		merge = to - 1;
3866 
3867 		todo -= skb_frag_size(fragfrom);
3868 		if (todo < 0) {
3869 			if (skb_prepare_for_shift(skb) ||
3870 			    skb_prepare_for_shift(tgt))
3871 				return 0;
3872 
3873 			/* All previous frag pointers might be stale! */
3874 			fragfrom = &skb_shinfo(skb)->frags[from];
3875 			fragto = &skb_shinfo(tgt)->frags[merge];
3876 
3877 			skb_frag_size_add(fragto, shiftlen);
3878 			skb_frag_size_sub(fragfrom, shiftlen);
3879 			skb_frag_off_add(fragfrom, shiftlen);
3880 
3881 			goto onlymerged;
3882 		}
3883 
3884 		from++;
3885 	}
3886 
3887 	/* Skip full, not-fitting skb to avoid expensive operations */
3888 	if ((shiftlen == skb->len) &&
3889 	    (skb_shinfo(skb)->nr_frags - from) > (MAX_SKB_FRAGS - to))
3890 		return 0;
3891 
3892 	if (skb_prepare_for_shift(skb) || skb_prepare_for_shift(tgt))
3893 		return 0;
3894 
3895 	while ((todo > 0) && (from < skb_shinfo(skb)->nr_frags)) {
3896 		if (to == MAX_SKB_FRAGS)
3897 			return 0;
3898 
3899 		fragfrom = &skb_shinfo(skb)->frags[from];
3900 		fragto = &skb_shinfo(tgt)->frags[to];
3901 
3902 		if (todo >= skb_frag_size(fragfrom)) {
3903 			*fragto = *fragfrom;
3904 			todo -= skb_frag_size(fragfrom);
3905 			from++;
3906 			to++;
3907 
3908 		} else {
3909 			__skb_frag_ref(fragfrom);
3910 			skb_frag_page_copy(fragto, fragfrom);
3911 			skb_frag_off_copy(fragto, fragfrom);
3912 			skb_frag_size_set(fragto, todo);
3913 
3914 			skb_frag_off_add(fragfrom, todo);
3915 			skb_frag_size_sub(fragfrom, todo);
3916 			todo = 0;
3917 
3918 			to++;
3919 			break;
3920 		}
3921 	}
3922 
3923 	/* Ready to "commit" this state change to tgt */
3924 	skb_shinfo(tgt)->nr_frags = to;
3925 
3926 	if (merge >= 0) {
3927 		fragfrom = &skb_shinfo(skb)->frags[0];
3928 		fragto = &skb_shinfo(tgt)->frags[merge];
3929 
3930 		skb_frag_size_add(fragto, skb_frag_size(fragfrom));
3931 		__skb_frag_unref(fragfrom, skb->pp_recycle);
3932 	}
3933 
3934 	/* Reposition in the original skb */
3935 	to = 0;
3936 	while (from < skb_shinfo(skb)->nr_frags)
3937 		skb_shinfo(skb)->frags[to++] = skb_shinfo(skb)->frags[from++];
3938 	skb_shinfo(skb)->nr_frags = to;
3939 
3940 	BUG_ON(todo > 0 && !skb_shinfo(skb)->nr_frags);
3941 
3942 onlymerged:
3943 	/* Most likely the tgt won't ever need its checksum anymore, skb on
3944 	 * the other hand might need it if it needs to be resent
3945 	 */
3946 	tgt->ip_summed = CHECKSUM_PARTIAL;
3947 	skb->ip_summed = CHECKSUM_PARTIAL;
3948 
3949 	skb_len_add(skb, -shiftlen);
3950 	skb_len_add(tgt, shiftlen);
3951 
3952 	return shiftlen;
3953 }
3954 
3955 /**
3956  * skb_prepare_seq_read - Prepare a sequential read of skb data
3957  * @skb: the buffer to read
3958  * @from: lower offset of data to be read
3959  * @to: upper offset of data to be read
3960  * @st: state variable
3961  *
3962  * Initializes the specified state variable. Must be called before
3963  * invoking skb_seq_read() for the first time.
3964  */
3965 void skb_prepare_seq_read(struct sk_buff *skb, unsigned int from,
3966 			  unsigned int to, struct skb_seq_state *st)
3967 {
3968 	st->lower_offset = from;
3969 	st->upper_offset = to;
3970 	st->root_skb = st->cur_skb = skb;
3971 	st->frag_idx = st->stepped_offset = 0;
3972 	st->frag_data = NULL;
3973 	st->frag_off = 0;
3974 }
3975 EXPORT_SYMBOL(skb_prepare_seq_read);
3976 
3977 /**
3978  * skb_seq_read - Sequentially read skb data
3979  * @consumed: number of bytes consumed by the caller so far
3980  * @data: destination pointer for data to be returned
3981  * @st: state variable
3982  *
3983  * Reads a block of skb data at @consumed relative to the
3984  * lower offset specified to skb_prepare_seq_read(). Assigns
3985  * the head of the data block to @data and returns the length
3986  * of the block or 0 if the end of the skb data or the upper
3987  * offset has been reached.
3988  *
3989  * The caller is not required to consume all of the data
3990  * returned, i.e. @consumed is typically set to the number
3991  * of bytes already consumed and the next call to
3992  * skb_seq_read() will return the remaining part of the block.
3993  *
3994  * Note 1: The size of each block of data returned can be arbitrary,
3995  *       this limitation is the cost for zerocopy sequential
3996  *       reads of potentially non linear data.
3997  *
3998  * Note 2: Fragment lists within fragments are not implemented
3999  *       at the moment, state->root_skb could be replaced with
4000  *       a stack for this purpose.
4001  */
4002 unsigned int skb_seq_read(unsigned int consumed, const u8 **data,
4003 			  struct skb_seq_state *st)
4004 {
4005 	unsigned int block_limit, abs_offset = consumed + st->lower_offset;
4006 	skb_frag_t *frag;
4007 
4008 	if (unlikely(abs_offset >= st->upper_offset)) {
4009 		if (st->frag_data) {
4010 			kunmap_atomic(st->frag_data);
4011 			st->frag_data = NULL;
4012 		}
4013 		return 0;
4014 	}
4015 
4016 next_skb:
4017 	block_limit = skb_headlen(st->cur_skb) + st->stepped_offset;
4018 
4019 	if (abs_offset < block_limit && !st->frag_data) {
4020 		*data = st->cur_skb->data + (abs_offset - st->stepped_offset);
4021 		return block_limit - abs_offset;
4022 	}
4023 
4024 	if (st->frag_idx == 0 && !st->frag_data)
4025 		st->stepped_offset += skb_headlen(st->cur_skb);
4026 
4027 	while (st->frag_idx < skb_shinfo(st->cur_skb)->nr_frags) {
4028 		unsigned int pg_idx, pg_off, pg_sz;
4029 
4030 		frag = &skb_shinfo(st->cur_skb)->frags[st->frag_idx];
4031 
4032 		pg_idx = 0;
4033 		pg_off = skb_frag_off(frag);
4034 		pg_sz = skb_frag_size(frag);
4035 
4036 		if (skb_frag_must_loop(skb_frag_page(frag))) {
4037 			pg_idx = (pg_off + st->frag_off) >> PAGE_SHIFT;
4038 			pg_off = offset_in_page(pg_off + st->frag_off);
4039 			pg_sz = min_t(unsigned int, pg_sz - st->frag_off,
4040 						    PAGE_SIZE - pg_off);
4041 		}
4042 
4043 		block_limit = pg_sz + st->stepped_offset;
4044 		if (abs_offset < block_limit) {
4045 			if (!st->frag_data)
4046 				st->frag_data = kmap_atomic(skb_frag_page(frag) + pg_idx);
4047 
4048 			*data = (u8 *)st->frag_data + pg_off +
4049 				(abs_offset - st->stepped_offset);
4050 
4051 			return block_limit - abs_offset;
4052 		}
4053 
4054 		if (st->frag_data) {
4055 			kunmap_atomic(st->frag_data);
4056 			st->frag_data = NULL;
4057 		}
4058 
4059 		st->stepped_offset += pg_sz;
4060 		st->frag_off += pg_sz;
4061 		if (st->frag_off == skb_frag_size(frag)) {
4062 			st->frag_off = 0;
4063 			st->frag_idx++;
4064 		}
4065 	}
4066 
4067 	if (st->frag_data) {
4068 		kunmap_atomic(st->frag_data);
4069 		st->frag_data = NULL;
4070 	}
4071 
4072 	if (st->root_skb == st->cur_skb && skb_has_frag_list(st->root_skb)) {
4073 		st->cur_skb = skb_shinfo(st->root_skb)->frag_list;
4074 		st->frag_idx = 0;
4075 		goto next_skb;
4076 	} else if (st->cur_skb->next) {
4077 		st->cur_skb = st->cur_skb->next;
4078 		st->frag_idx = 0;
4079 		goto next_skb;
4080 	}
4081 
4082 	return 0;
4083 }
4084 EXPORT_SYMBOL(skb_seq_read);
4085 
4086 /**
4087  * skb_abort_seq_read - Abort a sequential read of skb data
4088  * @st: state variable
4089  *
4090  * Must be called if skb_seq_read() was not called until it
4091  * returned 0.
4092  */
4093 void skb_abort_seq_read(struct skb_seq_state *st)
4094 {
4095 	if (st->frag_data)
4096 		kunmap_atomic(st->frag_data);
4097 }
4098 EXPORT_SYMBOL(skb_abort_seq_read);
4099 
4100 #define TS_SKB_CB(state)	((struct skb_seq_state *) &((state)->cb))
4101 
4102 static unsigned int skb_ts_get_next_block(unsigned int offset, const u8 **text,
4103 					  struct ts_config *conf,
4104 					  struct ts_state *state)
4105 {
4106 	return skb_seq_read(offset, text, TS_SKB_CB(state));
4107 }
4108 
4109 static void skb_ts_finish(struct ts_config *conf, struct ts_state *state)
4110 {
4111 	skb_abort_seq_read(TS_SKB_CB(state));
4112 }
4113 
4114 /**
4115  * skb_find_text - Find a text pattern in skb data
4116  * @skb: the buffer to look in
4117  * @from: search offset
4118  * @to: search limit
4119  * @config: textsearch configuration
4120  *
4121  * Finds a pattern in the skb data according to the specified
4122  * textsearch configuration. Use textsearch_next() to retrieve
4123  * subsequent occurrences of the pattern. Returns the offset
4124  * to the first occurrence or UINT_MAX if no match was found.
4125  */
4126 unsigned int skb_find_text(struct sk_buff *skb, unsigned int from,
4127 			   unsigned int to, struct ts_config *config)
4128 {
4129 	struct ts_state state;
4130 	unsigned int ret;
4131 
4132 	BUILD_BUG_ON(sizeof(struct skb_seq_state) > sizeof(state.cb));
4133 
4134 	config->get_next_block = skb_ts_get_next_block;
4135 	config->finish = skb_ts_finish;
4136 
4137 	skb_prepare_seq_read(skb, from, to, TS_SKB_CB(&state));
4138 
4139 	ret = textsearch_find(config, &state);
4140 	return (ret <= to - from ? ret : UINT_MAX);
4141 }
4142 EXPORT_SYMBOL(skb_find_text);
4143 
4144 int skb_append_pagefrags(struct sk_buff *skb, struct page *page,
4145 			 int offset, size_t size)
4146 {
4147 	int i = skb_shinfo(skb)->nr_frags;
4148 
4149 	if (skb_can_coalesce(skb, i, page, offset)) {
4150 		skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], size);
4151 	} else if (i < MAX_SKB_FRAGS) {
4152 		skb_zcopy_downgrade_managed(skb);
4153 		get_page(page);
4154 		skb_fill_page_desc_noacc(skb, i, page, offset, size);
4155 	} else {
4156 		return -EMSGSIZE;
4157 	}
4158 
4159 	return 0;
4160 }
4161 EXPORT_SYMBOL_GPL(skb_append_pagefrags);
4162 
4163 /**
4164  *	skb_pull_rcsum - pull skb and update receive checksum
4165  *	@skb: buffer to update
4166  *	@len: length of data pulled
4167  *
4168  *	This function performs an skb_pull on the packet and updates
4169  *	the CHECKSUM_COMPLETE checksum.  It should be used on
4170  *	receive path processing instead of skb_pull unless you know
4171  *	that the checksum difference is zero (e.g., a valid IP header)
4172  *	or you are setting ip_summed to CHECKSUM_NONE.
4173  */
4174 void *skb_pull_rcsum(struct sk_buff *skb, unsigned int len)
4175 {
4176 	unsigned char *data = skb->data;
4177 
4178 	BUG_ON(len > skb->len);
4179 	__skb_pull(skb, len);
4180 	skb_postpull_rcsum(skb, data, len);
4181 	return skb->data;
4182 }
4183 EXPORT_SYMBOL_GPL(skb_pull_rcsum);
4184 
4185 static inline skb_frag_t skb_head_frag_to_page_desc(struct sk_buff *frag_skb)
4186 {
4187 	skb_frag_t head_frag;
4188 	struct page *page;
4189 
4190 	page = virt_to_head_page(frag_skb->head);
4191 	__skb_frag_set_page(&head_frag, page);
4192 	skb_frag_off_set(&head_frag, frag_skb->data -
4193 			 (unsigned char *)page_address(page));
4194 	skb_frag_size_set(&head_frag, skb_headlen(frag_skb));
4195 	return head_frag;
4196 }
4197 
4198 struct sk_buff *skb_segment_list(struct sk_buff *skb,
4199 				 netdev_features_t features,
4200 				 unsigned int offset)
4201 {
4202 	struct sk_buff *list_skb = skb_shinfo(skb)->frag_list;
4203 	unsigned int tnl_hlen = skb_tnl_header_len(skb);
4204 	unsigned int delta_truesize = 0;
4205 	unsigned int delta_len = 0;
4206 	struct sk_buff *tail = NULL;
4207 	struct sk_buff *nskb, *tmp;
4208 	int len_diff, err;
4209 
4210 	skb_push(skb, -skb_network_offset(skb) + offset);
4211 
4212 	skb_shinfo(skb)->frag_list = NULL;
4213 
4214 	while (list_skb) {
4215 		nskb = list_skb;
4216 		list_skb = list_skb->next;
4217 
4218 		err = 0;
4219 		delta_truesize += nskb->truesize;
4220 		if (skb_shared(nskb)) {
4221 			tmp = skb_clone(nskb, GFP_ATOMIC);
4222 			if (tmp) {
4223 				consume_skb(nskb);
4224 				nskb = tmp;
4225 				err = skb_unclone(nskb, GFP_ATOMIC);
4226 			} else {
4227 				err = -ENOMEM;
4228 			}
4229 		}
4230 
4231 		if (!tail)
4232 			skb->next = nskb;
4233 		else
4234 			tail->next = nskb;
4235 
4236 		if (unlikely(err)) {
4237 			nskb->next = list_skb;
4238 			goto err_linearize;
4239 		}
4240 
4241 		tail = nskb;
4242 
4243 		delta_len += nskb->len;
4244 
4245 		skb_push(nskb, -skb_network_offset(nskb) + offset);
4246 
4247 		skb_release_head_state(nskb);
4248 		len_diff = skb_network_header_len(nskb) - skb_network_header_len(skb);
4249 		__copy_skb_header(nskb, skb);
4250 
4251 		skb_headers_offset_update(nskb, skb_headroom(nskb) - skb_headroom(skb));
4252 		nskb->transport_header += len_diff;
4253 		skb_copy_from_linear_data_offset(skb, -tnl_hlen,
4254 						 nskb->data - tnl_hlen,
4255 						 offset + tnl_hlen);
4256 
4257 		if (skb_needs_linearize(nskb, features) &&
4258 		    __skb_linearize(nskb))
4259 			goto err_linearize;
4260 	}
4261 
4262 	skb->truesize = skb->truesize - delta_truesize;
4263 	skb->data_len = skb->data_len - delta_len;
4264 	skb->len = skb->len - delta_len;
4265 
4266 	skb_gso_reset(skb);
4267 
4268 	skb->prev = tail;
4269 
4270 	if (skb_needs_linearize(skb, features) &&
4271 	    __skb_linearize(skb))
4272 		goto err_linearize;
4273 
4274 	skb_get(skb);
4275 
4276 	return skb;
4277 
4278 err_linearize:
4279 	kfree_skb_list(skb->next);
4280 	skb->next = NULL;
4281 	return ERR_PTR(-ENOMEM);
4282 }
4283 EXPORT_SYMBOL_GPL(skb_segment_list);
4284 
4285 /**
4286  *	skb_segment - Perform protocol segmentation on skb.
4287  *	@head_skb: buffer to segment
4288  *	@features: features for the output path (see dev->features)
4289  *
4290  *	This function performs segmentation on the given skb.  It returns
4291  *	a pointer to the first in a list of new skbs for the segments.
4292  *	In case of error it returns ERR_PTR(err).
4293  */
4294 struct sk_buff *skb_segment(struct sk_buff *head_skb,
4295 			    netdev_features_t features)
4296 {
4297 	struct sk_buff *segs = NULL;
4298 	struct sk_buff *tail = NULL;
4299 	struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list;
4300 	skb_frag_t *frag = skb_shinfo(head_skb)->frags;
4301 	unsigned int mss = skb_shinfo(head_skb)->gso_size;
4302 	unsigned int doffset = head_skb->data - skb_mac_header(head_skb);
4303 	struct sk_buff *frag_skb = head_skb;
4304 	unsigned int offset = doffset;
4305 	unsigned int tnl_hlen = skb_tnl_header_len(head_skb);
4306 	unsigned int partial_segs = 0;
4307 	unsigned int headroom;
4308 	unsigned int len = head_skb->len;
4309 	__be16 proto;
4310 	bool csum, sg;
4311 	int nfrags = skb_shinfo(head_skb)->nr_frags;
4312 	int err = -ENOMEM;
4313 	int i = 0;
4314 	int pos;
4315 
4316 	if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) &&
4317 	    mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) {
4318 		struct sk_buff *check_skb;
4319 
4320 		for (check_skb = list_skb; check_skb; check_skb = check_skb->next) {
4321 			if (skb_headlen(check_skb) && !check_skb->head_frag) {
4322 				/* gso_size is untrusted, and we have a frag_list with
4323 				 * a linear non head_frag item.
4324 				 *
4325 				 * If head_skb's headlen does not fit requested gso_size,
4326 				 * it means that the frag_list members do NOT terminate
4327 				 * on exact gso_size boundaries. Hence we cannot perform
4328 				 * skb_frag_t page sharing. Therefore we must fallback to
4329 				 * copying the frag_list skbs; we do so by disabling SG.
4330 				 */
4331 				features &= ~NETIF_F_SG;
4332 				break;
4333 			}
4334 		}
4335 	}
4336 
4337 	__skb_push(head_skb, doffset);
4338 	proto = skb_network_protocol(head_skb, NULL);
4339 	if (unlikely(!proto))
4340 		return ERR_PTR(-EINVAL);
4341 
4342 	sg = !!(features & NETIF_F_SG);
4343 	csum = !!can_checksum_protocol(features, proto);
4344 
4345 	if (sg && csum && (mss != GSO_BY_FRAGS))  {
4346 		if (!(features & NETIF_F_GSO_PARTIAL)) {
4347 			struct sk_buff *iter;
4348 			unsigned int frag_len;
4349 
4350 			if (!list_skb ||
4351 			    !net_gso_ok(features, skb_shinfo(head_skb)->gso_type))
4352 				goto normal;
4353 
4354 			/* If we get here then all the required
4355 			 * GSO features except frag_list are supported.
4356 			 * Try to split the SKB to multiple GSO SKBs
4357 			 * with no frag_list.
4358 			 * Currently we can do that only when the buffers don't
4359 			 * have a linear part and all the buffers except
4360 			 * the last are of the same length.
4361 			 */
4362 			frag_len = list_skb->len;
4363 			skb_walk_frags(head_skb, iter) {
4364 				if (frag_len != iter->len && iter->next)
4365 					goto normal;
4366 				if (skb_headlen(iter) && !iter->head_frag)
4367 					goto normal;
4368 
4369 				len -= iter->len;
4370 			}
4371 
4372 			if (len != frag_len)
4373 				goto normal;
4374 		}
4375 
4376 		/* GSO partial only requires that we trim off any excess that
4377 		 * doesn't fit into an MSS sized block, so take care of that
4378 		 * now.
4379 		 */
4380 		partial_segs = len / mss;
4381 		if (partial_segs > 1)
4382 			mss *= partial_segs;
4383 		else
4384 			partial_segs = 0;
4385 	}
4386 
4387 normal:
4388 	headroom = skb_headroom(head_skb);
4389 	pos = skb_headlen(head_skb);
4390 
4391 	do {
4392 		struct sk_buff *nskb;
4393 		skb_frag_t *nskb_frag;
4394 		int hsize;
4395 		int size;
4396 
4397 		if (unlikely(mss == GSO_BY_FRAGS)) {
4398 			len = list_skb->len;
4399 		} else {
4400 			len = head_skb->len - offset;
4401 			if (len > mss)
4402 				len = mss;
4403 		}
4404 
4405 		hsize = skb_headlen(head_skb) - offset;
4406 
4407 		if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) &&
4408 		    (skb_headlen(list_skb) == len || sg)) {
4409 			BUG_ON(skb_headlen(list_skb) > len);
4410 
4411 			i = 0;
4412 			nfrags = skb_shinfo(list_skb)->nr_frags;
4413 			frag = skb_shinfo(list_skb)->frags;
4414 			frag_skb = list_skb;
4415 			pos += skb_headlen(list_skb);
4416 
4417 			while (pos < offset + len) {
4418 				BUG_ON(i >= nfrags);
4419 
4420 				size = skb_frag_size(frag);
4421 				if (pos + size > offset + len)
4422 					break;
4423 
4424 				i++;
4425 				pos += size;
4426 				frag++;
4427 			}
4428 
4429 			nskb = skb_clone(list_skb, GFP_ATOMIC);
4430 			list_skb = list_skb->next;
4431 
4432 			if (unlikely(!nskb))
4433 				goto err;
4434 
4435 			if (unlikely(pskb_trim(nskb, len))) {
4436 				kfree_skb(nskb);
4437 				goto err;
4438 			}
4439 
4440 			hsize = skb_end_offset(nskb);
4441 			if (skb_cow_head(nskb, doffset + headroom)) {
4442 				kfree_skb(nskb);
4443 				goto err;
4444 			}
4445 
4446 			nskb->truesize += skb_end_offset(nskb) - hsize;
4447 			skb_release_head_state(nskb);
4448 			__skb_push(nskb, doffset);
4449 		} else {
4450 			if (hsize < 0)
4451 				hsize = 0;
4452 			if (hsize > len || !sg)
4453 				hsize = len;
4454 
4455 			nskb = __alloc_skb(hsize + doffset + headroom,
4456 					   GFP_ATOMIC, skb_alloc_rx_flag(head_skb),
4457 					   NUMA_NO_NODE);
4458 
4459 			if (unlikely(!nskb))
4460 				goto err;
4461 
4462 			skb_reserve(nskb, headroom);
4463 			__skb_put(nskb, doffset);
4464 		}
4465 
4466 		if (segs)
4467 			tail->next = nskb;
4468 		else
4469 			segs = nskb;
4470 		tail = nskb;
4471 
4472 		__copy_skb_header(nskb, head_skb);
4473 
4474 		skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom);
4475 		skb_reset_mac_len(nskb);
4476 
4477 		skb_copy_from_linear_data_offset(head_skb, -tnl_hlen,
4478 						 nskb->data - tnl_hlen,
4479 						 doffset + tnl_hlen);
4480 
4481 		if (nskb->len == len + doffset)
4482 			goto perform_csum_check;
4483 
4484 		if (!sg) {
4485 			if (!csum) {
4486 				if (!nskb->remcsum_offload)
4487 					nskb->ip_summed = CHECKSUM_NONE;
4488 				SKB_GSO_CB(nskb)->csum =
4489 					skb_copy_and_csum_bits(head_skb, offset,
4490 							       skb_put(nskb,
4491 								       len),
4492 							       len);
4493 				SKB_GSO_CB(nskb)->csum_start =
4494 					skb_headroom(nskb) + doffset;
4495 			} else {
4496 				if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len))
4497 					goto err;
4498 			}
4499 			continue;
4500 		}
4501 
4502 		nskb_frag = skb_shinfo(nskb)->frags;
4503 
4504 		skb_copy_from_linear_data_offset(head_skb, offset,
4505 						 skb_put(nskb, hsize), hsize);
4506 
4507 		skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4508 					   SKBFL_SHARED_FRAG;
4509 
4510 		if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4511 		    skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4512 			goto err;
4513 
4514 		while (pos < offset + len) {
4515 			if (i >= nfrags) {
4516 				i = 0;
4517 				nfrags = skb_shinfo(list_skb)->nr_frags;
4518 				frag = skb_shinfo(list_skb)->frags;
4519 				frag_skb = list_skb;
4520 				if (!skb_headlen(list_skb)) {
4521 					BUG_ON(!nfrags);
4522 				} else {
4523 					BUG_ON(!list_skb->head_frag);
4524 
4525 					/* to make room for head_frag. */
4526 					i--;
4527 					frag--;
4528 				}
4529 				if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4530 				    skb_zerocopy_clone(nskb, frag_skb,
4531 						       GFP_ATOMIC))
4532 					goto err;
4533 
4534 				list_skb = list_skb->next;
4535 			}
4536 
4537 			if (unlikely(skb_shinfo(nskb)->nr_frags >=
4538 				     MAX_SKB_FRAGS)) {
4539 				net_warn_ratelimited(
4540 					"skb_segment: too many frags: %u %u\n",
4541 					pos, mss);
4542 				err = -EINVAL;
4543 				goto err;
4544 			}
4545 
4546 			*nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4547 			__skb_frag_ref(nskb_frag);
4548 			size = skb_frag_size(nskb_frag);
4549 
4550 			if (pos < offset) {
4551 				skb_frag_off_add(nskb_frag, offset - pos);
4552 				skb_frag_size_sub(nskb_frag, offset - pos);
4553 			}
4554 
4555 			skb_shinfo(nskb)->nr_frags++;
4556 
4557 			if (pos + size <= offset + len) {
4558 				i++;
4559 				frag++;
4560 				pos += size;
4561 			} else {
4562 				skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4563 				goto skip_fraglist;
4564 			}
4565 
4566 			nskb_frag++;
4567 		}
4568 
4569 skip_fraglist:
4570 		nskb->data_len = len - hsize;
4571 		nskb->len += nskb->data_len;
4572 		nskb->truesize += nskb->data_len;
4573 
4574 perform_csum_check:
4575 		if (!csum) {
4576 			if (skb_has_shared_frag(nskb) &&
4577 			    __skb_linearize(nskb))
4578 				goto err;
4579 
4580 			if (!nskb->remcsum_offload)
4581 				nskb->ip_summed = CHECKSUM_NONE;
4582 			SKB_GSO_CB(nskb)->csum =
4583 				skb_checksum(nskb, doffset,
4584 					     nskb->len - doffset, 0);
4585 			SKB_GSO_CB(nskb)->csum_start =
4586 				skb_headroom(nskb) + doffset;
4587 		}
4588 	} while ((offset += len) < head_skb->len);
4589 
4590 	/* Some callers want to get the end of the list.
4591 	 * Put it in segs->prev to avoid walking the list.
4592 	 * (see validate_xmit_skb_list() for example)
4593 	 */
4594 	segs->prev = tail;
4595 
4596 	if (partial_segs) {
4597 		struct sk_buff *iter;
4598 		int type = skb_shinfo(head_skb)->gso_type;
4599 		unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4600 
4601 		/* Update type to add partial and then remove dodgy if set */
4602 		type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4603 		type &= ~SKB_GSO_DODGY;
4604 
4605 		/* Update GSO info and prepare to start updating headers on
4606 		 * our way back down the stack of protocols.
4607 		 */
4608 		for (iter = segs; iter; iter = iter->next) {
4609 			skb_shinfo(iter)->gso_size = gso_size;
4610 			skb_shinfo(iter)->gso_segs = partial_segs;
4611 			skb_shinfo(iter)->gso_type = type;
4612 			SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4613 		}
4614 
4615 		if (tail->len - doffset <= gso_size)
4616 			skb_shinfo(tail)->gso_size = 0;
4617 		else if (tail != segs)
4618 			skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4619 	}
4620 
4621 	/* Following permits correct backpressure, for protocols
4622 	 * using skb_set_owner_w().
4623 	 * Idea is to tranfert ownership from head_skb to last segment.
4624 	 */
4625 	if (head_skb->destructor == sock_wfree) {
4626 		swap(tail->truesize, head_skb->truesize);
4627 		swap(tail->destructor, head_skb->destructor);
4628 		swap(tail->sk, head_skb->sk);
4629 	}
4630 	return segs;
4631 
4632 err:
4633 	kfree_skb_list(segs);
4634 	return ERR_PTR(err);
4635 }
4636 EXPORT_SYMBOL_GPL(skb_segment);
4637 
4638 #ifdef CONFIG_SKB_EXTENSIONS
4639 #define SKB_EXT_ALIGN_VALUE	8
4640 #define SKB_EXT_CHUNKSIZEOF(x)	(ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4641 
4642 static const u8 skb_ext_type_len[] = {
4643 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4644 	[SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4645 #endif
4646 #ifdef CONFIG_XFRM
4647 	[SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4648 #endif
4649 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4650 	[TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4651 #endif
4652 #if IS_ENABLED(CONFIG_MPTCP)
4653 	[SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4654 #endif
4655 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4656 	[SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4657 #endif
4658 };
4659 
4660 static __always_inline unsigned int skb_ext_total_length(void)
4661 {
4662 	return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4663 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4664 		skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4665 #endif
4666 #ifdef CONFIG_XFRM
4667 		skb_ext_type_len[SKB_EXT_SEC_PATH] +
4668 #endif
4669 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4670 		skb_ext_type_len[TC_SKB_EXT] +
4671 #endif
4672 #if IS_ENABLED(CONFIG_MPTCP)
4673 		skb_ext_type_len[SKB_EXT_MPTCP] +
4674 #endif
4675 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4676 		skb_ext_type_len[SKB_EXT_MCTP] +
4677 #endif
4678 		0;
4679 }
4680 
4681 static void skb_extensions_init(void)
4682 {
4683 	BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4684 	BUILD_BUG_ON(skb_ext_total_length() > 255);
4685 
4686 	skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4687 					     SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4688 					     0,
4689 					     SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4690 					     NULL);
4691 }
4692 #else
4693 static void skb_extensions_init(void) {}
4694 #endif
4695 
4696 void __init skb_init(void)
4697 {
4698 	skbuff_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4699 					      sizeof(struct sk_buff),
4700 					      0,
4701 					      SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4702 					      offsetof(struct sk_buff, cb),
4703 					      sizeof_field(struct sk_buff, cb),
4704 					      NULL);
4705 	skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4706 						sizeof(struct sk_buff_fclones),
4707 						0,
4708 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4709 						NULL);
4710 #ifdef HAVE_SKB_SMALL_HEAD_CACHE
4711 	/* usercopy should only access first SKB_SMALL_HEAD_HEADROOM bytes.
4712 	 * struct skb_shared_info is located at the end of skb->head,
4713 	 * and should not be copied to/from user.
4714 	 */
4715 	skb_small_head_cache = kmem_cache_create_usercopy("skbuff_small_head",
4716 						SKB_SMALL_HEAD_CACHE_SIZE,
4717 						0,
4718 						SLAB_HWCACHE_ALIGN | SLAB_PANIC,
4719 						0,
4720 						SKB_SMALL_HEAD_HEADROOM,
4721 						NULL);
4722 #endif
4723 	skb_extensions_init();
4724 }
4725 
4726 static int
4727 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4728 	       unsigned int recursion_level)
4729 {
4730 	int start = skb_headlen(skb);
4731 	int i, copy = start - offset;
4732 	struct sk_buff *frag_iter;
4733 	int elt = 0;
4734 
4735 	if (unlikely(recursion_level >= 24))
4736 		return -EMSGSIZE;
4737 
4738 	if (copy > 0) {
4739 		if (copy > len)
4740 			copy = len;
4741 		sg_set_buf(sg, skb->data + offset, copy);
4742 		elt++;
4743 		if ((len -= copy) == 0)
4744 			return elt;
4745 		offset += copy;
4746 	}
4747 
4748 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4749 		int end;
4750 
4751 		WARN_ON(start > offset + len);
4752 
4753 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4754 		if ((copy = end - offset) > 0) {
4755 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4756 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4757 				return -EMSGSIZE;
4758 
4759 			if (copy > len)
4760 				copy = len;
4761 			sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4762 				    skb_frag_off(frag) + offset - start);
4763 			elt++;
4764 			if (!(len -= copy))
4765 				return elt;
4766 			offset += copy;
4767 		}
4768 		start = end;
4769 	}
4770 
4771 	skb_walk_frags(skb, frag_iter) {
4772 		int end, ret;
4773 
4774 		WARN_ON(start > offset + len);
4775 
4776 		end = start + frag_iter->len;
4777 		if ((copy = end - offset) > 0) {
4778 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4779 				return -EMSGSIZE;
4780 
4781 			if (copy > len)
4782 				copy = len;
4783 			ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4784 					      copy, recursion_level + 1);
4785 			if (unlikely(ret < 0))
4786 				return ret;
4787 			elt += ret;
4788 			if ((len -= copy) == 0)
4789 				return elt;
4790 			offset += copy;
4791 		}
4792 		start = end;
4793 	}
4794 	BUG_ON(len);
4795 	return elt;
4796 }
4797 
4798 /**
4799  *	skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4800  *	@skb: Socket buffer containing the buffers to be mapped
4801  *	@sg: The scatter-gather list to map into
4802  *	@offset: The offset into the buffer's contents to start mapping
4803  *	@len: Length of buffer space to be mapped
4804  *
4805  *	Fill the specified scatter-gather list with mappings/pointers into a
4806  *	region of the buffer space attached to a socket buffer. Returns either
4807  *	the number of scatterlist items used, or -EMSGSIZE if the contents
4808  *	could not fit.
4809  */
4810 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4811 {
4812 	int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4813 
4814 	if (nsg <= 0)
4815 		return nsg;
4816 
4817 	sg_mark_end(&sg[nsg - 1]);
4818 
4819 	return nsg;
4820 }
4821 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4822 
4823 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4824  * sglist without mark the sg which contain last skb data as the end.
4825  * So the caller can mannipulate sg list as will when padding new data after
4826  * the first call without calling sg_unmark_end to expend sg list.
4827  *
4828  * Scenario to use skb_to_sgvec_nomark:
4829  * 1. sg_init_table
4830  * 2. skb_to_sgvec_nomark(payload1)
4831  * 3. skb_to_sgvec_nomark(payload2)
4832  *
4833  * This is equivalent to:
4834  * 1. sg_init_table
4835  * 2. skb_to_sgvec(payload1)
4836  * 3. sg_unmark_end
4837  * 4. skb_to_sgvec(payload2)
4838  *
4839  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4840  * is more preferable.
4841  */
4842 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4843 			int offset, int len)
4844 {
4845 	return __skb_to_sgvec(skb, sg, offset, len, 0);
4846 }
4847 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4848 
4849 
4850 
4851 /**
4852  *	skb_cow_data - Check that a socket buffer's data buffers are writable
4853  *	@skb: The socket buffer to check.
4854  *	@tailbits: Amount of trailing space to be added
4855  *	@trailer: Returned pointer to the skb where the @tailbits space begins
4856  *
4857  *	Make sure that the data buffers attached to a socket buffer are
4858  *	writable. If they are not, private copies are made of the data buffers
4859  *	and the socket buffer is set to use these instead.
4860  *
4861  *	If @tailbits is given, make sure that there is space to write @tailbits
4862  *	bytes of data beyond current end of socket buffer.  @trailer will be
4863  *	set to point to the skb in which this space begins.
4864  *
4865  *	The number of scatterlist elements required to completely map the
4866  *	COW'd and extended socket buffer will be returned.
4867  */
4868 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4869 {
4870 	int copyflag;
4871 	int elt;
4872 	struct sk_buff *skb1, **skb_p;
4873 
4874 	/* If skb is cloned or its head is paged, reallocate
4875 	 * head pulling out all the pages (pages are considered not writable
4876 	 * at the moment even if they are anonymous).
4877 	 */
4878 	if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4879 	    !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4880 		return -ENOMEM;
4881 
4882 	/* Easy case. Most of packets will go this way. */
4883 	if (!skb_has_frag_list(skb)) {
4884 		/* A little of trouble, not enough of space for trailer.
4885 		 * This should not happen, when stack is tuned to generate
4886 		 * good frames. OK, on miss we reallocate and reserve even more
4887 		 * space, 128 bytes is fair. */
4888 
4889 		if (skb_tailroom(skb) < tailbits &&
4890 		    pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4891 			return -ENOMEM;
4892 
4893 		/* Voila! */
4894 		*trailer = skb;
4895 		return 1;
4896 	}
4897 
4898 	/* Misery. We are in troubles, going to mincer fragments... */
4899 
4900 	elt = 1;
4901 	skb_p = &skb_shinfo(skb)->frag_list;
4902 	copyflag = 0;
4903 
4904 	while ((skb1 = *skb_p) != NULL) {
4905 		int ntail = 0;
4906 
4907 		/* The fragment is partially pulled by someone,
4908 		 * this can happen on input. Copy it and everything
4909 		 * after it. */
4910 
4911 		if (skb_shared(skb1))
4912 			copyflag = 1;
4913 
4914 		/* If the skb is the last, worry about trailer. */
4915 
4916 		if (skb1->next == NULL && tailbits) {
4917 			if (skb_shinfo(skb1)->nr_frags ||
4918 			    skb_has_frag_list(skb1) ||
4919 			    skb_tailroom(skb1) < tailbits)
4920 				ntail = tailbits + 128;
4921 		}
4922 
4923 		if (copyflag ||
4924 		    skb_cloned(skb1) ||
4925 		    ntail ||
4926 		    skb_shinfo(skb1)->nr_frags ||
4927 		    skb_has_frag_list(skb1)) {
4928 			struct sk_buff *skb2;
4929 
4930 			/* Fuck, we are miserable poor guys... */
4931 			if (ntail == 0)
4932 				skb2 = skb_copy(skb1, GFP_ATOMIC);
4933 			else
4934 				skb2 = skb_copy_expand(skb1,
4935 						       skb_headroom(skb1),
4936 						       ntail,
4937 						       GFP_ATOMIC);
4938 			if (unlikely(skb2 == NULL))
4939 				return -ENOMEM;
4940 
4941 			if (skb1->sk)
4942 				skb_set_owner_w(skb2, skb1->sk);
4943 
4944 			/* Looking around. Are we still alive?
4945 			 * OK, link new skb, drop old one */
4946 
4947 			skb2->next = skb1->next;
4948 			*skb_p = skb2;
4949 			kfree_skb(skb1);
4950 			skb1 = skb2;
4951 		}
4952 		elt++;
4953 		*trailer = skb1;
4954 		skb_p = &skb1->next;
4955 	}
4956 
4957 	return elt;
4958 }
4959 EXPORT_SYMBOL_GPL(skb_cow_data);
4960 
4961 static void sock_rmem_free(struct sk_buff *skb)
4962 {
4963 	struct sock *sk = skb->sk;
4964 
4965 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4966 }
4967 
4968 static void skb_set_err_queue(struct sk_buff *skb)
4969 {
4970 	/* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4971 	 * So, it is safe to (mis)use it to mark skbs on the error queue.
4972 	 */
4973 	skb->pkt_type = PACKET_OUTGOING;
4974 	BUILD_BUG_ON(PACKET_OUTGOING == 0);
4975 }
4976 
4977 /*
4978  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4979  */
4980 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4981 {
4982 	if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4983 	    (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4984 		return -ENOMEM;
4985 
4986 	skb_orphan(skb);
4987 	skb->sk = sk;
4988 	skb->destructor = sock_rmem_free;
4989 	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4990 	skb_set_err_queue(skb);
4991 
4992 	/* before exiting rcu section, make sure dst is refcounted */
4993 	skb_dst_force(skb);
4994 
4995 	skb_queue_tail(&sk->sk_error_queue, skb);
4996 	if (!sock_flag(sk, SOCK_DEAD))
4997 		sk_error_report(sk);
4998 	return 0;
4999 }
5000 EXPORT_SYMBOL(sock_queue_err_skb);
5001 
5002 static bool is_icmp_err_skb(const struct sk_buff *skb)
5003 {
5004 	return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
5005 		       SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
5006 }
5007 
5008 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
5009 {
5010 	struct sk_buff_head *q = &sk->sk_error_queue;
5011 	struct sk_buff *skb, *skb_next = NULL;
5012 	bool icmp_next = false;
5013 	unsigned long flags;
5014 
5015 	spin_lock_irqsave(&q->lock, flags);
5016 	skb = __skb_dequeue(q);
5017 	if (skb && (skb_next = skb_peek(q))) {
5018 		icmp_next = is_icmp_err_skb(skb_next);
5019 		if (icmp_next)
5020 			sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
5021 	}
5022 	spin_unlock_irqrestore(&q->lock, flags);
5023 
5024 	if (is_icmp_err_skb(skb) && !icmp_next)
5025 		sk->sk_err = 0;
5026 
5027 	if (skb_next)
5028 		sk_error_report(sk);
5029 
5030 	return skb;
5031 }
5032 EXPORT_SYMBOL(sock_dequeue_err_skb);
5033 
5034 /**
5035  * skb_clone_sk - create clone of skb, and take reference to socket
5036  * @skb: the skb to clone
5037  *
5038  * This function creates a clone of a buffer that holds a reference on
5039  * sk_refcnt.  Buffers created via this function are meant to be
5040  * returned using sock_queue_err_skb, or free via kfree_skb.
5041  *
5042  * When passing buffers allocated with this function to sock_queue_err_skb
5043  * it is necessary to wrap the call with sock_hold/sock_put in order to
5044  * prevent the socket from being released prior to being enqueued on
5045  * the sk_error_queue.
5046  */
5047 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
5048 {
5049 	struct sock *sk = skb->sk;
5050 	struct sk_buff *clone;
5051 
5052 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
5053 		return NULL;
5054 
5055 	clone = skb_clone(skb, GFP_ATOMIC);
5056 	if (!clone) {
5057 		sock_put(sk);
5058 		return NULL;
5059 	}
5060 
5061 	clone->sk = sk;
5062 	clone->destructor = sock_efree;
5063 
5064 	return clone;
5065 }
5066 EXPORT_SYMBOL(skb_clone_sk);
5067 
5068 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
5069 					struct sock *sk,
5070 					int tstype,
5071 					bool opt_stats)
5072 {
5073 	struct sock_exterr_skb *serr;
5074 	int err;
5075 
5076 	BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
5077 
5078 	serr = SKB_EXT_ERR(skb);
5079 	memset(serr, 0, sizeof(*serr));
5080 	serr->ee.ee_errno = ENOMSG;
5081 	serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
5082 	serr->ee.ee_info = tstype;
5083 	serr->opt_stats = opt_stats;
5084 	serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
5085 	if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
5086 		serr->ee.ee_data = skb_shinfo(skb)->tskey;
5087 		if (sk_is_tcp(sk))
5088 			serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
5089 	}
5090 
5091 	err = sock_queue_err_skb(sk, skb);
5092 
5093 	if (err)
5094 		kfree_skb(skb);
5095 }
5096 
5097 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
5098 {
5099 	bool ret;
5100 
5101 	if (likely(READ_ONCE(sysctl_tstamp_allow_data) || tsonly))
5102 		return true;
5103 
5104 	read_lock_bh(&sk->sk_callback_lock);
5105 	ret = sk->sk_socket && sk->sk_socket->file &&
5106 	      file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
5107 	read_unlock_bh(&sk->sk_callback_lock);
5108 	return ret;
5109 }
5110 
5111 void skb_complete_tx_timestamp(struct sk_buff *skb,
5112 			       struct skb_shared_hwtstamps *hwtstamps)
5113 {
5114 	struct sock *sk = skb->sk;
5115 
5116 	if (!skb_may_tx_timestamp(sk, false))
5117 		goto err;
5118 
5119 	/* Take a reference to prevent skb_orphan() from freeing the socket,
5120 	 * but only if the socket refcount is not zero.
5121 	 */
5122 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5123 		*skb_hwtstamps(skb) = *hwtstamps;
5124 		__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
5125 		sock_put(sk);
5126 		return;
5127 	}
5128 
5129 err:
5130 	kfree_skb(skb);
5131 }
5132 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
5133 
5134 void __skb_tstamp_tx(struct sk_buff *orig_skb,
5135 		     const struct sk_buff *ack_skb,
5136 		     struct skb_shared_hwtstamps *hwtstamps,
5137 		     struct sock *sk, int tstype)
5138 {
5139 	struct sk_buff *skb;
5140 	bool tsonly, opt_stats = false;
5141 
5142 	if (!sk)
5143 		return;
5144 
5145 	if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
5146 	    skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
5147 		return;
5148 
5149 	tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
5150 	if (!skb_may_tx_timestamp(sk, tsonly))
5151 		return;
5152 
5153 	if (tsonly) {
5154 #ifdef CONFIG_INET
5155 		if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
5156 		    sk_is_tcp(sk)) {
5157 			skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
5158 							     ack_skb);
5159 			opt_stats = true;
5160 		} else
5161 #endif
5162 			skb = alloc_skb(0, GFP_ATOMIC);
5163 	} else {
5164 		skb = skb_clone(orig_skb, GFP_ATOMIC);
5165 	}
5166 	if (!skb)
5167 		return;
5168 
5169 	if (tsonly) {
5170 		skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
5171 					     SKBTX_ANY_TSTAMP;
5172 		skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
5173 	}
5174 
5175 	if (hwtstamps)
5176 		*skb_hwtstamps(skb) = *hwtstamps;
5177 	else
5178 		__net_timestamp(skb);
5179 
5180 	__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
5181 }
5182 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
5183 
5184 void skb_tstamp_tx(struct sk_buff *orig_skb,
5185 		   struct skb_shared_hwtstamps *hwtstamps)
5186 {
5187 	return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
5188 			       SCM_TSTAMP_SND);
5189 }
5190 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
5191 
5192 #ifdef CONFIG_WIRELESS
5193 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
5194 {
5195 	struct sock *sk = skb->sk;
5196 	struct sock_exterr_skb *serr;
5197 	int err = 1;
5198 
5199 	skb->wifi_acked_valid = 1;
5200 	skb->wifi_acked = acked;
5201 
5202 	serr = SKB_EXT_ERR(skb);
5203 	memset(serr, 0, sizeof(*serr));
5204 	serr->ee.ee_errno = ENOMSG;
5205 	serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
5206 
5207 	/* Take a reference to prevent skb_orphan() from freeing the socket,
5208 	 * but only if the socket refcount is not zero.
5209 	 */
5210 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
5211 		err = sock_queue_err_skb(sk, skb);
5212 		sock_put(sk);
5213 	}
5214 	if (err)
5215 		kfree_skb(skb);
5216 }
5217 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
5218 #endif /* CONFIG_WIRELESS */
5219 
5220 /**
5221  * skb_partial_csum_set - set up and verify partial csum values for packet
5222  * @skb: the skb to set
5223  * @start: the number of bytes after skb->data to start checksumming.
5224  * @off: the offset from start to place the checksum.
5225  *
5226  * For untrusted partially-checksummed packets, we need to make sure the values
5227  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
5228  *
5229  * This function checks and sets those values and skb->ip_summed: if this
5230  * returns false you should drop the packet.
5231  */
5232 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
5233 {
5234 	u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
5235 	u32 csum_start = skb_headroom(skb) + (u32)start;
5236 
5237 	if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
5238 		net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
5239 				     start, off, skb_headroom(skb), skb_headlen(skb));
5240 		return false;
5241 	}
5242 	skb->ip_summed = CHECKSUM_PARTIAL;
5243 	skb->csum_start = csum_start;
5244 	skb->csum_offset = off;
5245 	skb_set_transport_header(skb, start);
5246 	return true;
5247 }
5248 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
5249 
5250 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
5251 			       unsigned int max)
5252 {
5253 	if (skb_headlen(skb) >= len)
5254 		return 0;
5255 
5256 	/* If we need to pullup then pullup to the max, so we
5257 	 * won't need to do it again.
5258 	 */
5259 	if (max > skb->len)
5260 		max = skb->len;
5261 
5262 	if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
5263 		return -ENOMEM;
5264 
5265 	if (skb_headlen(skb) < len)
5266 		return -EPROTO;
5267 
5268 	return 0;
5269 }
5270 
5271 #define MAX_TCP_HDR_LEN (15 * 4)
5272 
5273 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
5274 				      typeof(IPPROTO_IP) proto,
5275 				      unsigned int off)
5276 {
5277 	int err;
5278 
5279 	switch (proto) {
5280 	case IPPROTO_TCP:
5281 		err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
5282 					  off + MAX_TCP_HDR_LEN);
5283 		if (!err && !skb_partial_csum_set(skb, off,
5284 						  offsetof(struct tcphdr,
5285 							   check)))
5286 			err = -EPROTO;
5287 		return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
5288 
5289 	case IPPROTO_UDP:
5290 		err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
5291 					  off + sizeof(struct udphdr));
5292 		if (!err && !skb_partial_csum_set(skb, off,
5293 						  offsetof(struct udphdr,
5294 							   check)))
5295 			err = -EPROTO;
5296 		return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
5297 	}
5298 
5299 	return ERR_PTR(-EPROTO);
5300 }
5301 
5302 /* This value should be large enough to cover a tagged ethernet header plus
5303  * maximally sized IP and TCP or UDP headers.
5304  */
5305 #define MAX_IP_HDR_LEN 128
5306 
5307 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5308 {
5309 	unsigned int off;
5310 	bool fragment;
5311 	__sum16 *csum;
5312 	int err;
5313 
5314 	fragment = false;
5315 
5316 	err = skb_maybe_pull_tail(skb,
5317 				  sizeof(struct iphdr),
5318 				  MAX_IP_HDR_LEN);
5319 	if (err < 0)
5320 		goto out;
5321 
5322 	if (ip_is_fragment(ip_hdr(skb)))
5323 		fragment = true;
5324 
5325 	off = ip_hdrlen(skb);
5326 
5327 	err = -EPROTO;
5328 
5329 	if (fragment)
5330 		goto out;
5331 
5332 	csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5333 	if (IS_ERR(csum))
5334 		return PTR_ERR(csum);
5335 
5336 	if (recalculate)
5337 		*csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5338 					   ip_hdr(skb)->daddr,
5339 					   skb->len - off,
5340 					   ip_hdr(skb)->protocol, 0);
5341 	err = 0;
5342 
5343 out:
5344 	return err;
5345 }
5346 
5347 /* This value should be large enough to cover a tagged ethernet header plus
5348  * an IPv6 header, all options, and a maximal TCP or UDP header.
5349  */
5350 #define MAX_IPV6_HDR_LEN 256
5351 
5352 #define OPT_HDR(type, skb, off) \
5353 	(type *)(skb_network_header(skb) + (off))
5354 
5355 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5356 {
5357 	int err;
5358 	u8 nexthdr;
5359 	unsigned int off;
5360 	unsigned int len;
5361 	bool fragment;
5362 	bool done;
5363 	__sum16 *csum;
5364 
5365 	fragment = false;
5366 	done = false;
5367 
5368 	off = sizeof(struct ipv6hdr);
5369 
5370 	err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5371 	if (err < 0)
5372 		goto out;
5373 
5374 	nexthdr = ipv6_hdr(skb)->nexthdr;
5375 
5376 	len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5377 	while (off <= len && !done) {
5378 		switch (nexthdr) {
5379 		case IPPROTO_DSTOPTS:
5380 		case IPPROTO_HOPOPTS:
5381 		case IPPROTO_ROUTING: {
5382 			struct ipv6_opt_hdr *hp;
5383 
5384 			err = skb_maybe_pull_tail(skb,
5385 						  off +
5386 						  sizeof(struct ipv6_opt_hdr),
5387 						  MAX_IPV6_HDR_LEN);
5388 			if (err < 0)
5389 				goto out;
5390 
5391 			hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5392 			nexthdr = hp->nexthdr;
5393 			off += ipv6_optlen(hp);
5394 			break;
5395 		}
5396 		case IPPROTO_AH: {
5397 			struct ip_auth_hdr *hp;
5398 
5399 			err = skb_maybe_pull_tail(skb,
5400 						  off +
5401 						  sizeof(struct ip_auth_hdr),
5402 						  MAX_IPV6_HDR_LEN);
5403 			if (err < 0)
5404 				goto out;
5405 
5406 			hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5407 			nexthdr = hp->nexthdr;
5408 			off += ipv6_authlen(hp);
5409 			break;
5410 		}
5411 		case IPPROTO_FRAGMENT: {
5412 			struct frag_hdr *hp;
5413 
5414 			err = skb_maybe_pull_tail(skb,
5415 						  off +
5416 						  sizeof(struct frag_hdr),
5417 						  MAX_IPV6_HDR_LEN);
5418 			if (err < 0)
5419 				goto out;
5420 
5421 			hp = OPT_HDR(struct frag_hdr, skb, off);
5422 
5423 			if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5424 				fragment = true;
5425 
5426 			nexthdr = hp->nexthdr;
5427 			off += sizeof(struct frag_hdr);
5428 			break;
5429 		}
5430 		default:
5431 			done = true;
5432 			break;
5433 		}
5434 	}
5435 
5436 	err = -EPROTO;
5437 
5438 	if (!done || fragment)
5439 		goto out;
5440 
5441 	csum = skb_checksum_setup_ip(skb, nexthdr, off);
5442 	if (IS_ERR(csum))
5443 		return PTR_ERR(csum);
5444 
5445 	if (recalculate)
5446 		*csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5447 					 &ipv6_hdr(skb)->daddr,
5448 					 skb->len - off, nexthdr, 0);
5449 	err = 0;
5450 
5451 out:
5452 	return err;
5453 }
5454 
5455 /**
5456  * skb_checksum_setup - set up partial checksum offset
5457  * @skb: the skb to set up
5458  * @recalculate: if true the pseudo-header checksum will be recalculated
5459  */
5460 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5461 {
5462 	int err;
5463 
5464 	switch (skb->protocol) {
5465 	case htons(ETH_P_IP):
5466 		err = skb_checksum_setup_ipv4(skb, recalculate);
5467 		break;
5468 
5469 	case htons(ETH_P_IPV6):
5470 		err = skb_checksum_setup_ipv6(skb, recalculate);
5471 		break;
5472 
5473 	default:
5474 		err = -EPROTO;
5475 		break;
5476 	}
5477 
5478 	return err;
5479 }
5480 EXPORT_SYMBOL(skb_checksum_setup);
5481 
5482 /**
5483  * skb_checksum_maybe_trim - maybe trims the given skb
5484  * @skb: the skb to check
5485  * @transport_len: the data length beyond the network header
5486  *
5487  * Checks whether the given skb has data beyond the given transport length.
5488  * If so, returns a cloned skb trimmed to this transport length.
5489  * Otherwise returns the provided skb. Returns NULL in error cases
5490  * (e.g. transport_len exceeds skb length or out-of-memory).
5491  *
5492  * Caller needs to set the skb transport header and free any returned skb if it
5493  * differs from the provided skb.
5494  */
5495 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5496 					       unsigned int transport_len)
5497 {
5498 	struct sk_buff *skb_chk;
5499 	unsigned int len = skb_transport_offset(skb) + transport_len;
5500 	int ret;
5501 
5502 	if (skb->len < len)
5503 		return NULL;
5504 	else if (skb->len == len)
5505 		return skb;
5506 
5507 	skb_chk = skb_clone(skb, GFP_ATOMIC);
5508 	if (!skb_chk)
5509 		return NULL;
5510 
5511 	ret = pskb_trim_rcsum(skb_chk, len);
5512 	if (ret) {
5513 		kfree_skb(skb_chk);
5514 		return NULL;
5515 	}
5516 
5517 	return skb_chk;
5518 }
5519 
5520 /**
5521  * skb_checksum_trimmed - validate checksum of an skb
5522  * @skb: the skb to check
5523  * @transport_len: the data length beyond the network header
5524  * @skb_chkf: checksum function to use
5525  *
5526  * Applies the given checksum function skb_chkf to the provided skb.
5527  * Returns a checked and maybe trimmed skb. Returns NULL on error.
5528  *
5529  * If the skb has data beyond the given transport length, then a
5530  * trimmed & cloned skb is checked and returned.
5531  *
5532  * Caller needs to set the skb transport header and free any returned skb if it
5533  * differs from the provided skb.
5534  */
5535 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5536 				     unsigned int transport_len,
5537 				     __sum16(*skb_chkf)(struct sk_buff *skb))
5538 {
5539 	struct sk_buff *skb_chk;
5540 	unsigned int offset = skb_transport_offset(skb);
5541 	__sum16 ret;
5542 
5543 	skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5544 	if (!skb_chk)
5545 		goto err;
5546 
5547 	if (!pskb_may_pull(skb_chk, offset))
5548 		goto err;
5549 
5550 	skb_pull_rcsum(skb_chk, offset);
5551 	ret = skb_chkf(skb_chk);
5552 	skb_push_rcsum(skb_chk, offset);
5553 
5554 	if (ret)
5555 		goto err;
5556 
5557 	return skb_chk;
5558 
5559 err:
5560 	if (skb_chk && skb_chk != skb)
5561 		kfree_skb(skb_chk);
5562 
5563 	return NULL;
5564 
5565 }
5566 EXPORT_SYMBOL(skb_checksum_trimmed);
5567 
5568 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5569 {
5570 	net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5571 			     skb->dev->name);
5572 }
5573 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5574 
5575 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5576 {
5577 	if (head_stolen) {
5578 		skb_release_head_state(skb);
5579 		kmem_cache_free(skbuff_cache, skb);
5580 	} else {
5581 		__kfree_skb(skb);
5582 	}
5583 }
5584 EXPORT_SYMBOL(kfree_skb_partial);
5585 
5586 /**
5587  * skb_try_coalesce - try to merge skb to prior one
5588  * @to: prior buffer
5589  * @from: buffer to add
5590  * @fragstolen: pointer to boolean
5591  * @delta_truesize: how much more was allocated than was requested
5592  */
5593 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5594 		      bool *fragstolen, int *delta_truesize)
5595 {
5596 	struct skb_shared_info *to_shinfo, *from_shinfo;
5597 	int i, delta, len = from->len;
5598 
5599 	*fragstolen = false;
5600 
5601 	if (skb_cloned(to))
5602 		return false;
5603 
5604 	/* In general, avoid mixing page_pool and non-page_pool allocated
5605 	 * pages within the same SKB. Additionally avoid dealing with clones
5606 	 * with page_pool pages, in case the SKB is using page_pool fragment
5607 	 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5608 	 * references for cloned SKBs at the moment that would result in
5609 	 * inconsistent reference counts.
5610 	 * In theory we could take full references if @from is cloned and
5611 	 * !@to->pp_recycle but its tricky (due to potential race with
5612 	 * the clone disappearing) and rare, so not worth dealing with.
5613 	 */
5614 	if (to->pp_recycle != from->pp_recycle ||
5615 	    (from->pp_recycle && skb_cloned(from)))
5616 		return false;
5617 
5618 	if (len <= skb_tailroom(to)) {
5619 		if (len)
5620 			BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5621 		*delta_truesize = 0;
5622 		return true;
5623 	}
5624 
5625 	to_shinfo = skb_shinfo(to);
5626 	from_shinfo = skb_shinfo(from);
5627 	if (to_shinfo->frag_list || from_shinfo->frag_list)
5628 		return false;
5629 	if (skb_zcopy(to) || skb_zcopy(from))
5630 		return false;
5631 
5632 	if (skb_headlen(from) != 0) {
5633 		struct page *page;
5634 		unsigned int offset;
5635 
5636 		if (to_shinfo->nr_frags +
5637 		    from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5638 			return false;
5639 
5640 		if (skb_head_is_locked(from))
5641 			return false;
5642 
5643 		delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5644 
5645 		page = virt_to_head_page(from->head);
5646 		offset = from->data - (unsigned char *)page_address(page);
5647 
5648 		skb_fill_page_desc(to, to_shinfo->nr_frags,
5649 				   page, offset, skb_headlen(from));
5650 		*fragstolen = true;
5651 	} else {
5652 		if (to_shinfo->nr_frags +
5653 		    from_shinfo->nr_frags > MAX_SKB_FRAGS)
5654 			return false;
5655 
5656 		delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5657 	}
5658 
5659 	WARN_ON_ONCE(delta < len);
5660 
5661 	memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5662 	       from_shinfo->frags,
5663 	       from_shinfo->nr_frags * sizeof(skb_frag_t));
5664 	to_shinfo->nr_frags += from_shinfo->nr_frags;
5665 
5666 	if (!skb_cloned(from))
5667 		from_shinfo->nr_frags = 0;
5668 
5669 	/* if the skb is not cloned this does nothing
5670 	 * since we set nr_frags to 0.
5671 	 */
5672 	for (i = 0; i < from_shinfo->nr_frags; i++)
5673 		__skb_frag_ref(&from_shinfo->frags[i]);
5674 
5675 	to->truesize += delta;
5676 	to->len += len;
5677 	to->data_len += len;
5678 
5679 	*delta_truesize = delta;
5680 	return true;
5681 }
5682 EXPORT_SYMBOL(skb_try_coalesce);
5683 
5684 /**
5685  * skb_scrub_packet - scrub an skb
5686  *
5687  * @skb: buffer to clean
5688  * @xnet: packet is crossing netns
5689  *
5690  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5691  * into/from a tunnel. Some information have to be cleared during these
5692  * operations.
5693  * skb_scrub_packet can also be used to clean a skb before injecting it in
5694  * another namespace (@xnet == true). We have to clear all information in the
5695  * skb that could impact namespace isolation.
5696  */
5697 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5698 {
5699 	skb->pkt_type = PACKET_HOST;
5700 	skb->skb_iif = 0;
5701 	skb->ignore_df = 0;
5702 	skb_dst_drop(skb);
5703 	skb_ext_reset(skb);
5704 	nf_reset_ct(skb);
5705 	nf_reset_trace(skb);
5706 
5707 #ifdef CONFIG_NET_SWITCHDEV
5708 	skb->offload_fwd_mark = 0;
5709 	skb->offload_l3_fwd_mark = 0;
5710 #endif
5711 
5712 	if (!xnet)
5713 		return;
5714 
5715 	ipvs_reset(skb);
5716 	skb->mark = 0;
5717 	skb_clear_tstamp(skb);
5718 }
5719 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5720 
5721 /**
5722  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5723  *
5724  * @skb: GSO skb
5725  *
5726  * skb_gso_transport_seglen is used to determine the real size of the
5727  * individual segments, including Layer4 headers (TCP/UDP).
5728  *
5729  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5730  */
5731 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5732 {
5733 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
5734 	unsigned int thlen = 0;
5735 
5736 	if (skb->encapsulation) {
5737 		thlen = skb_inner_transport_header(skb) -
5738 			skb_transport_header(skb);
5739 
5740 		if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5741 			thlen += inner_tcp_hdrlen(skb);
5742 	} else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5743 		thlen = tcp_hdrlen(skb);
5744 	} else if (unlikely(skb_is_gso_sctp(skb))) {
5745 		thlen = sizeof(struct sctphdr);
5746 	} else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5747 		thlen = sizeof(struct udphdr);
5748 	}
5749 	/* UFO sets gso_size to the size of the fragmentation
5750 	 * payload, i.e. the size of the L4 (UDP) header is already
5751 	 * accounted for.
5752 	 */
5753 	return thlen + shinfo->gso_size;
5754 }
5755 
5756 /**
5757  * skb_gso_network_seglen - Return length of individual segments of a gso packet
5758  *
5759  * @skb: GSO skb
5760  *
5761  * skb_gso_network_seglen is used to determine the real size of the
5762  * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5763  *
5764  * The MAC/L2 header is not accounted for.
5765  */
5766 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5767 {
5768 	unsigned int hdr_len = skb_transport_header(skb) -
5769 			       skb_network_header(skb);
5770 
5771 	return hdr_len + skb_gso_transport_seglen(skb);
5772 }
5773 
5774 /**
5775  * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5776  *
5777  * @skb: GSO skb
5778  *
5779  * skb_gso_mac_seglen is used to determine the real size of the
5780  * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5781  * headers (TCP/UDP).
5782  */
5783 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5784 {
5785 	unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5786 
5787 	return hdr_len + skb_gso_transport_seglen(skb);
5788 }
5789 
5790 /**
5791  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5792  *
5793  * There are a couple of instances where we have a GSO skb, and we
5794  * want to determine what size it would be after it is segmented.
5795  *
5796  * We might want to check:
5797  * -    L3+L4+payload size (e.g. IP forwarding)
5798  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5799  *
5800  * This is a helper to do that correctly considering GSO_BY_FRAGS.
5801  *
5802  * @skb: GSO skb
5803  *
5804  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5805  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5806  *
5807  * @max_len: The maximum permissible length.
5808  *
5809  * Returns true if the segmented length <= max length.
5810  */
5811 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5812 				      unsigned int seg_len,
5813 				      unsigned int max_len) {
5814 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
5815 	const struct sk_buff *iter;
5816 
5817 	if (shinfo->gso_size != GSO_BY_FRAGS)
5818 		return seg_len <= max_len;
5819 
5820 	/* Undo this so we can re-use header sizes */
5821 	seg_len -= GSO_BY_FRAGS;
5822 
5823 	skb_walk_frags(skb, iter) {
5824 		if (seg_len + skb_headlen(iter) > max_len)
5825 			return false;
5826 	}
5827 
5828 	return true;
5829 }
5830 
5831 /**
5832  * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5833  *
5834  * @skb: GSO skb
5835  * @mtu: MTU to validate against
5836  *
5837  * skb_gso_validate_network_len validates if a given skb will fit a
5838  * wanted MTU once split. It considers L3 headers, L4 headers, and the
5839  * payload.
5840  */
5841 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5842 {
5843 	return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5844 }
5845 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5846 
5847 /**
5848  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5849  *
5850  * @skb: GSO skb
5851  * @len: length to validate against
5852  *
5853  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5854  * length once split, including L2, L3 and L4 headers and the payload.
5855  */
5856 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5857 {
5858 	return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5859 }
5860 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5861 
5862 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5863 {
5864 	int mac_len, meta_len;
5865 	void *meta;
5866 
5867 	if (skb_cow(skb, skb_headroom(skb)) < 0) {
5868 		kfree_skb(skb);
5869 		return NULL;
5870 	}
5871 
5872 	mac_len = skb->data - skb_mac_header(skb);
5873 	if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5874 		memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5875 			mac_len - VLAN_HLEN - ETH_TLEN);
5876 	}
5877 
5878 	meta_len = skb_metadata_len(skb);
5879 	if (meta_len) {
5880 		meta = skb_metadata_end(skb) - meta_len;
5881 		memmove(meta + VLAN_HLEN, meta, meta_len);
5882 	}
5883 
5884 	skb->mac_header += VLAN_HLEN;
5885 	return skb;
5886 }
5887 
5888 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5889 {
5890 	struct vlan_hdr *vhdr;
5891 	u16 vlan_tci;
5892 
5893 	if (unlikely(skb_vlan_tag_present(skb))) {
5894 		/* vlan_tci is already set-up so leave this for another time */
5895 		return skb;
5896 	}
5897 
5898 	skb = skb_share_check(skb, GFP_ATOMIC);
5899 	if (unlikely(!skb))
5900 		goto err_free;
5901 	/* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5902 	if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5903 		goto err_free;
5904 
5905 	vhdr = (struct vlan_hdr *)skb->data;
5906 	vlan_tci = ntohs(vhdr->h_vlan_TCI);
5907 	__vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5908 
5909 	skb_pull_rcsum(skb, VLAN_HLEN);
5910 	vlan_set_encap_proto(skb, vhdr);
5911 
5912 	skb = skb_reorder_vlan_header(skb);
5913 	if (unlikely(!skb))
5914 		goto err_free;
5915 
5916 	skb_reset_network_header(skb);
5917 	if (!skb_transport_header_was_set(skb))
5918 		skb_reset_transport_header(skb);
5919 	skb_reset_mac_len(skb);
5920 
5921 	return skb;
5922 
5923 err_free:
5924 	kfree_skb(skb);
5925 	return NULL;
5926 }
5927 EXPORT_SYMBOL(skb_vlan_untag);
5928 
5929 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5930 {
5931 	if (!pskb_may_pull(skb, write_len))
5932 		return -ENOMEM;
5933 
5934 	if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5935 		return 0;
5936 
5937 	return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5938 }
5939 EXPORT_SYMBOL(skb_ensure_writable);
5940 
5941 /* remove VLAN header from packet and update csum accordingly.
5942  * expects a non skb_vlan_tag_present skb with a vlan tag payload
5943  */
5944 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5945 {
5946 	struct vlan_hdr *vhdr;
5947 	int offset = skb->data - skb_mac_header(skb);
5948 	int err;
5949 
5950 	if (WARN_ONCE(offset,
5951 		      "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5952 		      offset)) {
5953 		return -EINVAL;
5954 	}
5955 
5956 	err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5957 	if (unlikely(err))
5958 		return err;
5959 
5960 	skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5961 
5962 	vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5963 	*vlan_tci = ntohs(vhdr->h_vlan_TCI);
5964 
5965 	memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5966 	__skb_pull(skb, VLAN_HLEN);
5967 
5968 	vlan_set_encap_proto(skb, vhdr);
5969 	skb->mac_header += VLAN_HLEN;
5970 
5971 	if (skb_network_offset(skb) < ETH_HLEN)
5972 		skb_set_network_header(skb, ETH_HLEN);
5973 
5974 	skb_reset_mac_len(skb);
5975 
5976 	return err;
5977 }
5978 EXPORT_SYMBOL(__skb_vlan_pop);
5979 
5980 /* Pop a vlan tag either from hwaccel or from payload.
5981  * Expects skb->data at mac header.
5982  */
5983 int skb_vlan_pop(struct sk_buff *skb)
5984 {
5985 	u16 vlan_tci;
5986 	__be16 vlan_proto;
5987 	int err;
5988 
5989 	if (likely(skb_vlan_tag_present(skb))) {
5990 		__vlan_hwaccel_clear_tag(skb);
5991 	} else {
5992 		if (unlikely(!eth_type_vlan(skb->protocol)))
5993 			return 0;
5994 
5995 		err = __skb_vlan_pop(skb, &vlan_tci);
5996 		if (err)
5997 			return err;
5998 	}
5999 	/* move next vlan tag to hw accel tag */
6000 	if (likely(!eth_type_vlan(skb->protocol)))
6001 		return 0;
6002 
6003 	vlan_proto = skb->protocol;
6004 	err = __skb_vlan_pop(skb, &vlan_tci);
6005 	if (unlikely(err))
6006 		return err;
6007 
6008 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6009 	return 0;
6010 }
6011 EXPORT_SYMBOL(skb_vlan_pop);
6012 
6013 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
6014  * Expects skb->data at mac header.
6015  */
6016 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
6017 {
6018 	if (skb_vlan_tag_present(skb)) {
6019 		int offset = skb->data - skb_mac_header(skb);
6020 		int err;
6021 
6022 		if (WARN_ONCE(offset,
6023 			      "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
6024 			      offset)) {
6025 			return -EINVAL;
6026 		}
6027 
6028 		err = __vlan_insert_tag(skb, skb->vlan_proto,
6029 					skb_vlan_tag_get(skb));
6030 		if (err)
6031 			return err;
6032 
6033 		skb->protocol = skb->vlan_proto;
6034 		skb->mac_len += VLAN_HLEN;
6035 
6036 		skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
6037 	}
6038 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
6039 	return 0;
6040 }
6041 EXPORT_SYMBOL(skb_vlan_push);
6042 
6043 /**
6044  * skb_eth_pop() - Drop the Ethernet header at the head of a packet
6045  *
6046  * @skb: Socket buffer to modify
6047  *
6048  * Drop the Ethernet header of @skb.
6049  *
6050  * Expects that skb->data points to the mac header and that no VLAN tags are
6051  * present.
6052  *
6053  * Returns 0 on success, -errno otherwise.
6054  */
6055 int skb_eth_pop(struct sk_buff *skb)
6056 {
6057 	if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
6058 	    skb_network_offset(skb) < ETH_HLEN)
6059 		return -EPROTO;
6060 
6061 	skb_pull_rcsum(skb, ETH_HLEN);
6062 	skb_reset_mac_header(skb);
6063 	skb_reset_mac_len(skb);
6064 
6065 	return 0;
6066 }
6067 EXPORT_SYMBOL(skb_eth_pop);
6068 
6069 /**
6070  * skb_eth_push() - Add a new Ethernet header at the head of a packet
6071  *
6072  * @skb: Socket buffer to modify
6073  * @dst: Destination MAC address of the new header
6074  * @src: Source MAC address of the new header
6075  *
6076  * Prepend @skb with a new Ethernet header.
6077  *
6078  * Expects that skb->data points to the mac header, which must be empty.
6079  *
6080  * Returns 0 on success, -errno otherwise.
6081  */
6082 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
6083 		 const unsigned char *src)
6084 {
6085 	struct ethhdr *eth;
6086 	int err;
6087 
6088 	if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
6089 		return -EPROTO;
6090 
6091 	err = skb_cow_head(skb, sizeof(*eth));
6092 	if (err < 0)
6093 		return err;
6094 
6095 	skb_push(skb, sizeof(*eth));
6096 	skb_reset_mac_header(skb);
6097 	skb_reset_mac_len(skb);
6098 
6099 	eth = eth_hdr(skb);
6100 	ether_addr_copy(eth->h_dest, dst);
6101 	ether_addr_copy(eth->h_source, src);
6102 	eth->h_proto = skb->protocol;
6103 
6104 	skb_postpush_rcsum(skb, eth, sizeof(*eth));
6105 
6106 	return 0;
6107 }
6108 EXPORT_SYMBOL(skb_eth_push);
6109 
6110 /* Update the ethertype of hdr and the skb csum value if required. */
6111 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
6112 			     __be16 ethertype)
6113 {
6114 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
6115 		__be16 diff[] = { ~hdr->h_proto, ethertype };
6116 
6117 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6118 	}
6119 
6120 	hdr->h_proto = ethertype;
6121 }
6122 
6123 /**
6124  * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
6125  *                   the packet
6126  *
6127  * @skb: buffer
6128  * @mpls_lse: MPLS label stack entry to push
6129  * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
6130  * @mac_len: length of the MAC header
6131  * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
6132  *            ethernet
6133  *
6134  * Expects skb->data at mac header.
6135  *
6136  * Returns 0 on success, -errno otherwise.
6137  */
6138 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
6139 		  int mac_len, bool ethernet)
6140 {
6141 	struct mpls_shim_hdr *lse;
6142 	int err;
6143 
6144 	if (unlikely(!eth_p_mpls(mpls_proto)))
6145 		return -EINVAL;
6146 
6147 	/* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
6148 	if (skb->encapsulation)
6149 		return -EINVAL;
6150 
6151 	err = skb_cow_head(skb, MPLS_HLEN);
6152 	if (unlikely(err))
6153 		return err;
6154 
6155 	if (!skb->inner_protocol) {
6156 		skb_set_inner_network_header(skb, skb_network_offset(skb));
6157 		skb_set_inner_protocol(skb, skb->protocol);
6158 	}
6159 
6160 	skb_push(skb, MPLS_HLEN);
6161 	memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
6162 		mac_len);
6163 	skb_reset_mac_header(skb);
6164 	skb_set_network_header(skb, mac_len);
6165 	skb_reset_mac_len(skb);
6166 
6167 	lse = mpls_hdr(skb);
6168 	lse->label_stack_entry = mpls_lse;
6169 	skb_postpush_rcsum(skb, lse, MPLS_HLEN);
6170 
6171 	if (ethernet && mac_len >= ETH_HLEN)
6172 		skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
6173 	skb->protocol = mpls_proto;
6174 
6175 	return 0;
6176 }
6177 EXPORT_SYMBOL_GPL(skb_mpls_push);
6178 
6179 /**
6180  * skb_mpls_pop() - pop the outermost MPLS header
6181  *
6182  * @skb: buffer
6183  * @next_proto: ethertype of header after popped MPLS header
6184  * @mac_len: length of the MAC header
6185  * @ethernet: flag to indicate if the packet is ethernet
6186  *
6187  * Expects skb->data at mac header.
6188  *
6189  * Returns 0 on success, -errno otherwise.
6190  */
6191 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
6192 		 bool ethernet)
6193 {
6194 	int err;
6195 
6196 	if (unlikely(!eth_p_mpls(skb->protocol)))
6197 		return 0;
6198 
6199 	err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
6200 	if (unlikely(err))
6201 		return err;
6202 
6203 	skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
6204 	memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
6205 		mac_len);
6206 
6207 	__skb_pull(skb, MPLS_HLEN);
6208 	skb_reset_mac_header(skb);
6209 	skb_set_network_header(skb, mac_len);
6210 
6211 	if (ethernet && mac_len >= ETH_HLEN) {
6212 		struct ethhdr *hdr;
6213 
6214 		/* use mpls_hdr() to get ethertype to account for VLANs. */
6215 		hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
6216 		skb_mod_eth_type(skb, hdr, next_proto);
6217 	}
6218 	skb->protocol = next_proto;
6219 
6220 	return 0;
6221 }
6222 EXPORT_SYMBOL_GPL(skb_mpls_pop);
6223 
6224 /**
6225  * skb_mpls_update_lse() - modify outermost MPLS header and update csum
6226  *
6227  * @skb: buffer
6228  * @mpls_lse: new MPLS label stack entry to update to
6229  *
6230  * Expects skb->data at mac header.
6231  *
6232  * Returns 0 on success, -errno otherwise.
6233  */
6234 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
6235 {
6236 	int err;
6237 
6238 	if (unlikely(!eth_p_mpls(skb->protocol)))
6239 		return -EINVAL;
6240 
6241 	err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
6242 	if (unlikely(err))
6243 		return err;
6244 
6245 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
6246 		__be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
6247 
6248 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
6249 	}
6250 
6251 	mpls_hdr(skb)->label_stack_entry = mpls_lse;
6252 
6253 	return 0;
6254 }
6255 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
6256 
6257 /**
6258  * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
6259  *
6260  * @skb: buffer
6261  *
6262  * Expects skb->data at mac header.
6263  *
6264  * Returns 0 on success, -errno otherwise.
6265  */
6266 int skb_mpls_dec_ttl(struct sk_buff *skb)
6267 {
6268 	u32 lse;
6269 	u8 ttl;
6270 
6271 	if (unlikely(!eth_p_mpls(skb->protocol)))
6272 		return -EINVAL;
6273 
6274 	if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
6275 		return -ENOMEM;
6276 
6277 	lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
6278 	ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
6279 	if (!--ttl)
6280 		return -EINVAL;
6281 
6282 	lse &= ~MPLS_LS_TTL_MASK;
6283 	lse |= ttl << MPLS_LS_TTL_SHIFT;
6284 
6285 	return skb_mpls_update_lse(skb, cpu_to_be32(lse));
6286 }
6287 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
6288 
6289 /**
6290  * alloc_skb_with_frags - allocate skb with page frags
6291  *
6292  * @header_len: size of linear part
6293  * @data_len: needed length in frags
6294  * @max_page_order: max page order desired.
6295  * @errcode: pointer to error code if any
6296  * @gfp_mask: allocation mask
6297  *
6298  * This can be used to allocate a paged skb, given a maximal order for frags.
6299  */
6300 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
6301 				     unsigned long data_len,
6302 				     int max_page_order,
6303 				     int *errcode,
6304 				     gfp_t gfp_mask)
6305 {
6306 	int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6307 	unsigned long chunk;
6308 	struct sk_buff *skb;
6309 	struct page *page;
6310 	int i;
6311 
6312 	*errcode = -EMSGSIZE;
6313 	/* Note this test could be relaxed, if we succeed to allocate
6314 	 * high order pages...
6315 	 */
6316 	if (npages > MAX_SKB_FRAGS)
6317 		return NULL;
6318 
6319 	*errcode = -ENOBUFS;
6320 	skb = alloc_skb(header_len, gfp_mask);
6321 	if (!skb)
6322 		return NULL;
6323 
6324 	skb->truesize += npages << PAGE_SHIFT;
6325 
6326 	for (i = 0; npages > 0; i++) {
6327 		int order = max_page_order;
6328 
6329 		while (order) {
6330 			if (npages >= 1 << order) {
6331 				page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6332 						   __GFP_COMP |
6333 						   __GFP_NOWARN,
6334 						   order);
6335 				if (page)
6336 					goto fill_page;
6337 				/* Do not retry other high order allocations */
6338 				order = 1;
6339 				max_page_order = 0;
6340 			}
6341 			order--;
6342 		}
6343 		page = alloc_page(gfp_mask);
6344 		if (!page)
6345 			goto failure;
6346 fill_page:
6347 		chunk = min_t(unsigned long, data_len,
6348 			      PAGE_SIZE << order);
6349 		skb_fill_page_desc(skb, i, page, 0, chunk);
6350 		data_len -= chunk;
6351 		npages -= 1 << order;
6352 	}
6353 	return skb;
6354 
6355 failure:
6356 	kfree_skb(skb);
6357 	return NULL;
6358 }
6359 EXPORT_SYMBOL(alloc_skb_with_frags);
6360 
6361 /* carve out the first off bytes from skb when off < headlen */
6362 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6363 				    const int headlen, gfp_t gfp_mask)
6364 {
6365 	int i;
6366 	unsigned int size = skb_end_offset(skb);
6367 	int new_hlen = headlen - off;
6368 	u8 *data;
6369 
6370 	if (skb_pfmemalloc(skb))
6371 		gfp_mask |= __GFP_MEMALLOC;
6372 
6373 	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6374 	if (!data)
6375 		return -ENOMEM;
6376 	size = SKB_WITH_OVERHEAD(size);
6377 
6378 	/* Copy real data, and all frags */
6379 	skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6380 	skb->len -= off;
6381 
6382 	memcpy((struct skb_shared_info *)(data + size),
6383 	       skb_shinfo(skb),
6384 	       offsetof(struct skb_shared_info,
6385 			frags[skb_shinfo(skb)->nr_frags]));
6386 	if (skb_cloned(skb)) {
6387 		/* drop the old head gracefully */
6388 		if (skb_orphan_frags(skb, gfp_mask)) {
6389 			skb_kfree_head(data, size);
6390 			return -ENOMEM;
6391 		}
6392 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6393 			skb_frag_ref(skb, i);
6394 		if (skb_has_frag_list(skb))
6395 			skb_clone_fraglist(skb);
6396 		skb_release_data(skb, SKB_CONSUMED, false);
6397 	} else {
6398 		/* we can reuse existing recount- all we did was
6399 		 * relocate values
6400 		 */
6401 		skb_free_head(skb, false);
6402 	}
6403 
6404 	skb->head = data;
6405 	skb->data = data;
6406 	skb->head_frag = 0;
6407 	skb_set_end_offset(skb, size);
6408 	skb_set_tail_pointer(skb, skb_headlen(skb));
6409 	skb_headers_offset_update(skb, 0);
6410 	skb->cloned = 0;
6411 	skb->hdr_len = 0;
6412 	skb->nohdr = 0;
6413 	atomic_set(&skb_shinfo(skb)->dataref, 1);
6414 
6415 	return 0;
6416 }
6417 
6418 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6419 
6420 /* carve out the first eat bytes from skb's frag_list. May recurse into
6421  * pskb_carve()
6422  */
6423 static int pskb_carve_frag_list(struct sk_buff *skb,
6424 				struct skb_shared_info *shinfo, int eat,
6425 				gfp_t gfp_mask)
6426 {
6427 	struct sk_buff *list = shinfo->frag_list;
6428 	struct sk_buff *clone = NULL;
6429 	struct sk_buff *insp = NULL;
6430 
6431 	do {
6432 		if (!list) {
6433 			pr_err("Not enough bytes to eat. Want %d\n", eat);
6434 			return -EFAULT;
6435 		}
6436 		if (list->len <= eat) {
6437 			/* Eaten as whole. */
6438 			eat -= list->len;
6439 			list = list->next;
6440 			insp = list;
6441 		} else {
6442 			/* Eaten partially. */
6443 			if (skb_shared(list)) {
6444 				clone = skb_clone(list, gfp_mask);
6445 				if (!clone)
6446 					return -ENOMEM;
6447 				insp = list->next;
6448 				list = clone;
6449 			} else {
6450 				/* This may be pulled without problems. */
6451 				insp = list;
6452 			}
6453 			if (pskb_carve(list, eat, gfp_mask) < 0) {
6454 				kfree_skb(clone);
6455 				return -ENOMEM;
6456 			}
6457 			break;
6458 		}
6459 	} while (eat);
6460 
6461 	/* Free pulled out fragments. */
6462 	while ((list = shinfo->frag_list) != insp) {
6463 		shinfo->frag_list = list->next;
6464 		consume_skb(list);
6465 	}
6466 	/* And insert new clone at head. */
6467 	if (clone) {
6468 		clone->next = list;
6469 		shinfo->frag_list = clone;
6470 	}
6471 	return 0;
6472 }
6473 
6474 /* carve off first len bytes from skb. Split line (off) is in the
6475  * non-linear part of skb
6476  */
6477 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6478 				       int pos, gfp_t gfp_mask)
6479 {
6480 	int i, k = 0;
6481 	unsigned int size = skb_end_offset(skb);
6482 	u8 *data;
6483 	const int nfrags = skb_shinfo(skb)->nr_frags;
6484 	struct skb_shared_info *shinfo;
6485 
6486 	if (skb_pfmemalloc(skb))
6487 		gfp_mask |= __GFP_MEMALLOC;
6488 
6489 	data = kmalloc_reserve(&size, gfp_mask, NUMA_NO_NODE, NULL);
6490 	if (!data)
6491 		return -ENOMEM;
6492 	size = SKB_WITH_OVERHEAD(size);
6493 
6494 	memcpy((struct skb_shared_info *)(data + size),
6495 	       skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6496 	if (skb_orphan_frags(skb, gfp_mask)) {
6497 		skb_kfree_head(data, size);
6498 		return -ENOMEM;
6499 	}
6500 	shinfo = (struct skb_shared_info *)(data + size);
6501 	for (i = 0; i < nfrags; i++) {
6502 		int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6503 
6504 		if (pos + fsize > off) {
6505 			shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6506 
6507 			if (pos < off) {
6508 				/* Split frag.
6509 				 * We have two variants in this case:
6510 				 * 1. Move all the frag to the second
6511 				 *    part, if it is possible. F.e.
6512 				 *    this approach is mandatory for TUX,
6513 				 *    where splitting is expensive.
6514 				 * 2. Split is accurately. We make this.
6515 				 */
6516 				skb_frag_off_add(&shinfo->frags[0], off - pos);
6517 				skb_frag_size_sub(&shinfo->frags[0], off - pos);
6518 			}
6519 			skb_frag_ref(skb, i);
6520 			k++;
6521 		}
6522 		pos += fsize;
6523 	}
6524 	shinfo->nr_frags = k;
6525 	if (skb_has_frag_list(skb))
6526 		skb_clone_fraglist(skb);
6527 
6528 	/* split line is in frag list */
6529 	if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6530 		/* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6531 		if (skb_has_frag_list(skb))
6532 			kfree_skb_list(skb_shinfo(skb)->frag_list);
6533 		skb_kfree_head(data, size);
6534 		return -ENOMEM;
6535 	}
6536 	skb_release_data(skb, SKB_CONSUMED, false);
6537 
6538 	skb->head = data;
6539 	skb->head_frag = 0;
6540 	skb->data = data;
6541 	skb_set_end_offset(skb, size);
6542 	skb_reset_tail_pointer(skb);
6543 	skb_headers_offset_update(skb, 0);
6544 	skb->cloned   = 0;
6545 	skb->hdr_len  = 0;
6546 	skb->nohdr    = 0;
6547 	skb->len -= off;
6548 	skb->data_len = skb->len;
6549 	atomic_set(&skb_shinfo(skb)->dataref, 1);
6550 	return 0;
6551 }
6552 
6553 /* remove len bytes from the beginning of the skb */
6554 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6555 {
6556 	int headlen = skb_headlen(skb);
6557 
6558 	if (len < headlen)
6559 		return pskb_carve_inside_header(skb, len, headlen, gfp);
6560 	else
6561 		return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6562 }
6563 
6564 /* Extract to_copy bytes starting at off from skb, and return this in
6565  * a new skb
6566  */
6567 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6568 			     int to_copy, gfp_t gfp)
6569 {
6570 	struct sk_buff  *clone = skb_clone(skb, gfp);
6571 
6572 	if (!clone)
6573 		return NULL;
6574 
6575 	if (pskb_carve(clone, off, gfp) < 0 ||
6576 	    pskb_trim(clone, to_copy)) {
6577 		kfree_skb(clone);
6578 		return NULL;
6579 	}
6580 	return clone;
6581 }
6582 EXPORT_SYMBOL(pskb_extract);
6583 
6584 /**
6585  * skb_condense - try to get rid of fragments/frag_list if possible
6586  * @skb: buffer
6587  *
6588  * Can be used to save memory before skb is added to a busy queue.
6589  * If packet has bytes in frags and enough tail room in skb->head,
6590  * pull all of them, so that we can free the frags right now and adjust
6591  * truesize.
6592  * Notes:
6593  *	We do not reallocate skb->head thus can not fail.
6594  *	Caller must re-evaluate skb->truesize if needed.
6595  */
6596 void skb_condense(struct sk_buff *skb)
6597 {
6598 	if (skb->data_len) {
6599 		if (skb->data_len > skb->end - skb->tail ||
6600 		    skb_cloned(skb))
6601 			return;
6602 
6603 		/* Nice, we can free page frag(s) right now */
6604 		__pskb_pull_tail(skb, skb->data_len);
6605 	}
6606 	/* At this point, skb->truesize might be over estimated,
6607 	 * because skb had a fragment, and fragments do not tell
6608 	 * their truesize.
6609 	 * When we pulled its content into skb->head, fragment
6610 	 * was freed, but __pskb_pull_tail() could not possibly
6611 	 * adjust skb->truesize, not knowing the frag truesize.
6612 	 */
6613 	skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6614 }
6615 EXPORT_SYMBOL(skb_condense);
6616 
6617 #ifdef CONFIG_SKB_EXTENSIONS
6618 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6619 {
6620 	return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6621 }
6622 
6623 /**
6624  * __skb_ext_alloc - allocate a new skb extensions storage
6625  *
6626  * @flags: See kmalloc().
6627  *
6628  * Returns the newly allocated pointer. The pointer can later attached to a
6629  * skb via __skb_ext_set().
6630  * Note: caller must handle the skb_ext as an opaque data.
6631  */
6632 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6633 {
6634 	struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6635 
6636 	if (new) {
6637 		memset(new->offset, 0, sizeof(new->offset));
6638 		refcount_set(&new->refcnt, 1);
6639 	}
6640 
6641 	return new;
6642 }
6643 
6644 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6645 					 unsigned int old_active)
6646 {
6647 	struct skb_ext *new;
6648 
6649 	if (refcount_read(&old->refcnt) == 1)
6650 		return old;
6651 
6652 	new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6653 	if (!new)
6654 		return NULL;
6655 
6656 	memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6657 	refcount_set(&new->refcnt, 1);
6658 
6659 #ifdef CONFIG_XFRM
6660 	if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6661 		struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6662 		unsigned int i;
6663 
6664 		for (i = 0; i < sp->len; i++)
6665 			xfrm_state_hold(sp->xvec[i]);
6666 	}
6667 #endif
6668 	__skb_ext_put(old);
6669 	return new;
6670 }
6671 
6672 /**
6673  * __skb_ext_set - attach the specified extension storage to this skb
6674  * @skb: buffer
6675  * @id: extension id
6676  * @ext: extension storage previously allocated via __skb_ext_alloc()
6677  *
6678  * Existing extensions, if any, are cleared.
6679  *
6680  * Returns the pointer to the extension.
6681  */
6682 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6683 		    struct skb_ext *ext)
6684 {
6685 	unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6686 
6687 	skb_ext_put(skb);
6688 	newlen = newoff + skb_ext_type_len[id];
6689 	ext->chunks = newlen;
6690 	ext->offset[id] = newoff;
6691 	skb->extensions = ext;
6692 	skb->active_extensions = 1 << id;
6693 	return skb_ext_get_ptr(ext, id);
6694 }
6695 
6696 /**
6697  * skb_ext_add - allocate space for given extension, COW if needed
6698  * @skb: buffer
6699  * @id: extension to allocate space for
6700  *
6701  * Allocates enough space for the given extension.
6702  * If the extension is already present, a pointer to that extension
6703  * is returned.
6704  *
6705  * If the skb was cloned, COW applies and the returned memory can be
6706  * modified without changing the extension space of clones buffers.
6707  *
6708  * Returns pointer to the extension or NULL on allocation failure.
6709  */
6710 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6711 {
6712 	struct skb_ext *new, *old = NULL;
6713 	unsigned int newlen, newoff;
6714 
6715 	if (skb->active_extensions) {
6716 		old = skb->extensions;
6717 
6718 		new = skb_ext_maybe_cow(old, skb->active_extensions);
6719 		if (!new)
6720 			return NULL;
6721 
6722 		if (__skb_ext_exist(new, id))
6723 			goto set_active;
6724 
6725 		newoff = new->chunks;
6726 	} else {
6727 		newoff = SKB_EXT_CHUNKSIZEOF(*new);
6728 
6729 		new = __skb_ext_alloc(GFP_ATOMIC);
6730 		if (!new)
6731 			return NULL;
6732 	}
6733 
6734 	newlen = newoff + skb_ext_type_len[id];
6735 	new->chunks = newlen;
6736 	new->offset[id] = newoff;
6737 set_active:
6738 	skb->slow_gro = 1;
6739 	skb->extensions = new;
6740 	skb->active_extensions |= 1 << id;
6741 	return skb_ext_get_ptr(new, id);
6742 }
6743 EXPORT_SYMBOL(skb_ext_add);
6744 
6745 #ifdef CONFIG_XFRM
6746 static void skb_ext_put_sp(struct sec_path *sp)
6747 {
6748 	unsigned int i;
6749 
6750 	for (i = 0; i < sp->len; i++)
6751 		xfrm_state_put(sp->xvec[i]);
6752 }
6753 #endif
6754 
6755 #ifdef CONFIG_MCTP_FLOWS
6756 static void skb_ext_put_mctp(struct mctp_flow *flow)
6757 {
6758 	if (flow->key)
6759 		mctp_key_unref(flow->key);
6760 }
6761 #endif
6762 
6763 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6764 {
6765 	struct skb_ext *ext = skb->extensions;
6766 
6767 	skb->active_extensions &= ~(1 << id);
6768 	if (skb->active_extensions == 0) {
6769 		skb->extensions = NULL;
6770 		__skb_ext_put(ext);
6771 #ifdef CONFIG_XFRM
6772 	} else if (id == SKB_EXT_SEC_PATH &&
6773 		   refcount_read(&ext->refcnt) == 1) {
6774 		struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6775 
6776 		skb_ext_put_sp(sp);
6777 		sp->len = 0;
6778 #endif
6779 	}
6780 }
6781 EXPORT_SYMBOL(__skb_ext_del);
6782 
6783 void __skb_ext_put(struct skb_ext *ext)
6784 {
6785 	/* If this is last clone, nothing can increment
6786 	 * it after check passes.  Avoids one atomic op.
6787 	 */
6788 	if (refcount_read(&ext->refcnt) == 1)
6789 		goto free_now;
6790 
6791 	if (!refcount_dec_and_test(&ext->refcnt))
6792 		return;
6793 free_now:
6794 #ifdef CONFIG_XFRM
6795 	if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6796 		skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6797 #endif
6798 #ifdef CONFIG_MCTP_FLOWS
6799 	if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6800 		skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6801 #endif
6802 
6803 	kmem_cache_free(skbuff_ext_cache, ext);
6804 }
6805 EXPORT_SYMBOL(__skb_ext_put);
6806 #endif /* CONFIG_SKB_EXTENSIONS */
6807 
6808 /**
6809  * skb_attempt_defer_free - queue skb for remote freeing
6810  * @skb: buffer
6811  *
6812  * Put @skb in a per-cpu list, using the cpu which
6813  * allocated the skb/pages to reduce false sharing
6814  * and memory zone spinlock contention.
6815  */
6816 void skb_attempt_defer_free(struct sk_buff *skb)
6817 {
6818 	int cpu = skb->alloc_cpu;
6819 	struct softnet_data *sd;
6820 	unsigned long flags;
6821 	unsigned int defer_max;
6822 	bool kick;
6823 
6824 	if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6825 	    !cpu_online(cpu) ||
6826 	    cpu == raw_smp_processor_id()) {
6827 nodefer:	__kfree_skb(skb);
6828 		return;
6829 	}
6830 
6831 	sd = &per_cpu(softnet_data, cpu);
6832 	defer_max = READ_ONCE(sysctl_skb_defer_max);
6833 	if (READ_ONCE(sd->defer_count) >= defer_max)
6834 		goto nodefer;
6835 
6836 	spin_lock_irqsave(&sd->defer_lock, flags);
6837 	/* Send an IPI every time queue reaches half capacity. */
6838 	kick = sd->defer_count == (defer_max >> 1);
6839 	/* Paired with the READ_ONCE() few lines above */
6840 	WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6841 
6842 	skb->next = sd->defer_list;
6843 	/* Paired with READ_ONCE() in skb_defer_free_flush() */
6844 	WRITE_ONCE(sd->defer_list, skb);
6845 	spin_unlock_irqrestore(&sd->defer_lock, flags);
6846 
6847 	/* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6848 	 * if we are unlucky enough (this seems very unlikely).
6849 	 */
6850 	if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6851 		smp_call_function_single_async(cpu, &sd->defer_csd);
6852 }
6853