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