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