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