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