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