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