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