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