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