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