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