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