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