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