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