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