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