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