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