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