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