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