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