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