xref: /openbmc/linux/net/core/skbuff.c (revision 6726d552)
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 				skb_copy_bits(head_skb, offset,
4209 					      skb_put(nskb, len),
4210 					      len);
4211 			}
4212 			continue;
4213 		}
4214 
4215 		nskb_frag = skb_shinfo(nskb)->frags;
4216 
4217 		skb_copy_from_linear_data_offset(head_skb, offset,
4218 						 skb_put(nskb, hsize), hsize);
4219 
4220 		skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags &
4221 					   SKBFL_SHARED_FRAG;
4222 
4223 		if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4224 		    skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC))
4225 			goto err;
4226 
4227 		while (pos < offset + len) {
4228 			if (i >= nfrags) {
4229 				i = 0;
4230 				nfrags = skb_shinfo(list_skb)->nr_frags;
4231 				frag = skb_shinfo(list_skb)->frags;
4232 				frag_skb = list_skb;
4233 				if (!skb_headlen(list_skb)) {
4234 					BUG_ON(!nfrags);
4235 				} else {
4236 					BUG_ON(!list_skb->head_frag);
4237 
4238 					/* to make room for head_frag. */
4239 					i--;
4240 					frag--;
4241 				}
4242 				if (skb_orphan_frags(frag_skb, GFP_ATOMIC) ||
4243 				    skb_zerocopy_clone(nskb, frag_skb,
4244 						       GFP_ATOMIC))
4245 					goto err;
4246 
4247 				list_skb = list_skb->next;
4248 			}
4249 
4250 			if (unlikely(skb_shinfo(nskb)->nr_frags >=
4251 				     MAX_SKB_FRAGS)) {
4252 				net_warn_ratelimited(
4253 					"skb_segment: too many frags: %u %u\n",
4254 					pos, mss);
4255 				err = -EINVAL;
4256 				goto err;
4257 			}
4258 
4259 			*nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag;
4260 			__skb_frag_ref(nskb_frag);
4261 			size = skb_frag_size(nskb_frag);
4262 
4263 			if (pos < offset) {
4264 				skb_frag_off_add(nskb_frag, offset - pos);
4265 				skb_frag_size_sub(nskb_frag, offset - pos);
4266 			}
4267 
4268 			skb_shinfo(nskb)->nr_frags++;
4269 
4270 			if (pos + size <= offset + len) {
4271 				i++;
4272 				frag++;
4273 				pos += size;
4274 			} else {
4275 				skb_frag_size_sub(nskb_frag, pos + size - (offset + len));
4276 				goto skip_fraglist;
4277 			}
4278 
4279 			nskb_frag++;
4280 		}
4281 
4282 skip_fraglist:
4283 		nskb->data_len = len - hsize;
4284 		nskb->len += nskb->data_len;
4285 		nskb->truesize += nskb->data_len;
4286 
4287 perform_csum_check:
4288 		if (!csum) {
4289 			if (skb_has_shared_frag(nskb) &&
4290 			    __skb_linearize(nskb))
4291 				goto err;
4292 
4293 			if (!nskb->remcsum_offload)
4294 				nskb->ip_summed = CHECKSUM_NONE;
4295 			SKB_GSO_CB(nskb)->csum =
4296 				skb_checksum(nskb, doffset,
4297 					     nskb->len - doffset, 0);
4298 			SKB_GSO_CB(nskb)->csum_start =
4299 				skb_headroom(nskb) + doffset;
4300 		}
4301 	} while ((offset += len) < head_skb->len);
4302 
4303 	/* Some callers want to get the end of the list.
4304 	 * Put it in segs->prev to avoid walking the list.
4305 	 * (see validate_xmit_skb_list() for example)
4306 	 */
4307 	segs->prev = tail;
4308 
4309 	if (partial_segs) {
4310 		struct sk_buff *iter;
4311 		int type = skb_shinfo(head_skb)->gso_type;
4312 		unsigned short gso_size = skb_shinfo(head_skb)->gso_size;
4313 
4314 		/* Update type to add partial and then remove dodgy if set */
4315 		type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL;
4316 		type &= ~SKB_GSO_DODGY;
4317 
4318 		/* Update GSO info and prepare to start updating headers on
4319 		 * our way back down the stack of protocols.
4320 		 */
4321 		for (iter = segs; iter; iter = iter->next) {
4322 			skb_shinfo(iter)->gso_size = gso_size;
4323 			skb_shinfo(iter)->gso_segs = partial_segs;
4324 			skb_shinfo(iter)->gso_type = type;
4325 			SKB_GSO_CB(iter)->data_offset = skb_headroom(iter) + doffset;
4326 		}
4327 
4328 		if (tail->len - doffset <= gso_size)
4329 			skb_shinfo(tail)->gso_size = 0;
4330 		else if (tail != segs)
4331 			skb_shinfo(tail)->gso_segs = DIV_ROUND_UP(tail->len - doffset, gso_size);
4332 	}
4333 
4334 	/* Following permits correct backpressure, for protocols
4335 	 * using skb_set_owner_w().
4336 	 * Idea is to tranfert ownership from head_skb to last segment.
4337 	 */
4338 	if (head_skb->destructor == sock_wfree) {
4339 		swap(tail->truesize, head_skb->truesize);
4340 		swap(tail->destructor, head_skb->destructor);
4341 		swap(tail->sk, head_skb->sk);
4342 	}
4343 	return segs;
4344 
4345 err:
4346 	kfree_skb_list(segs);
4347 	return ERR_PTR(err);
4348 }
4349 EXPORT_SYMBOL_GPL(skb_segment);
4350 
4351 #ifdef CONFIG_SKB_EXTENSIONS
4352 #define SKB_EXT_ALIGN_VALUE	8
4353 #define SKB_EXT_CHUNKSIZEOF(x)	(ALIGN((sizeof(x)), SKB_EXT_ALIGN_VALUE) / SKB_EXT_ALIGN_VALUE)
4354 
4355 static const u8 skb_ext_type_len[] = {
4356 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4357 	[SKB_EXT_BRIDGE_NF] = SKB_EXT_CHUNKSIZEOF(struct nf_bridge_info),
4358 #endif
4359 #ifdef CONFIG_XFRM
4360 	[SKB_EXT_SEC_PATH] = SKB_EXT_CHUNKSIZEOF(struct sec_path),
4361 #endif
4362 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4363 	[TC_SKB_EXT] = SKB_EXT_CHUNKSIZEOF(struct tc_skb_ext),
4364 #endif
4365 #if IS_ENABLED(CONFIG_MPTCP)
4366 	[SKB_EXT_MPTCP] = SKB_EXT_CHUNKSIZEOF(struct mptcp_ext),
4367 #endif
4368 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4369 	[SKB_EXT_MCTP] = SKB_EXT_CHUNKSIZEOF(struct mctp_flow),
4370 #endif
4371 };
4372 
4373 static __always_inline unsigned int skb_ext_total_length(void)
4374 {
4375 	return SKB_EXT_CHUNKSIZEOF(struct skb_ext) +
4376 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
4377 		skb_ext_type_len[SKB_EXT_BRIDGE_NF] +
4378 #endif
4379 #ifdef CONFIG_XFRM
4380 		skb_ext_type_len[SKB_EXT_SEC_PATH] +
4381 #endif
4382 #if IS_ENABLED(CONFIG_NET_TC_SKB_EXT)
4383 		skb_ext_type_len[TC_SKB_EXT] +
4384 #endif
4385 #if IS_ENABLED(CONFIG_MPTCP)
4386 		skb_ext_type_len[SKB_EXT_MPTCP] +
4387 #endif
4388 #if IS_ENABLED(CONFIG_MCTP_FLOWS)
4389 		skb_ext_type_len[SKB_EXT_MCTP] +
4390 #endif
4391 		0;
4392 }
4393 
4394 static void skb_extensions_init(void)
4395 {
4396 	BUILD_BUG_ON(SKB_EXT_NUM >= 8);
4397 	BUILD_BUG_ON(skb_ext_total_length() > 255);
4398 
4399 	skbuff_ext_cache = kmem_cache_create("skbuff_ext_cache",
4400 					     SKB_EXT_ALIGN_VALUE * skb_ext_total_length(),
4401 					     0,
4402 					     SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4403 					     NULL);
4404 }
4405 #else
4406 static void skb_extensions_init(void) {}
4407 #endif
4408 
4409 void __init skb_init(void)
4410 {
4411 	skbuff_head_cache = kmem_cache_create_usercopy("skbuff_head_cache",
4412 					      sizeof(struct sk_buff),
4413 					      0,
4414 					      SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4415 					      offsetof(struct sk_buff, cb),
4416 					      sizeof_field(struct sk_buff, cb),
4417 					      NULL);
4418 	skbuff_fclone_cache = kmem_cache_create("skbuff_fclone_cache",
4419 						sizeof(struct sk_buff_fclones),
4420 						0,
4421 						SLAB_HWCACHE_ALIGN|SLAB_PANIC,
4422 						NULL);
4423 	skb_extensions_init();
4424 }
4425 
4426 static int
4427 __skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len,
4428 	       unsigned int recursion_level)
4429 {
4430 	int start = skb_headlen(skb);
4431 	int i, copy = start - offset;
4432 	struct sk_buff *frag_iter;
4433 	int elt = 0;
4434 
4435 	if (unlikely(recursion_level >= 24))
4436 		return -EMSGSIZE;
4437 
4438 	if (copy > 0) {
4439 		if (copy > len)
4440 			copy = len;
4441 		sg_set_buf(sg, skb->data + offset, copy);
4442 		elt++;
4443 		if ((len -= copy) == 0)
4444 			return elt;
4445 		offset += copy;
4446 	}
4447 
4448 	for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
4449 		int end;
4450 
4451 		WARN_ON(start > offset + len);
4452 
4453 		end = start + skb_frag_size(&skb_shinfo(skb)->frags[i]);
4454 		if ((copy = end - offset) > 0) {
4455 			skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
4456 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4457 				return -EMSGSIZE;
4458 
4459 			if (copy > len)
4460 				copy = len;
4461 			sg_set_page(&sg[elt], skb_frag_page(frag), copy,
4462 				    skb_frag_off(frag) + offset - start);
4463 			elt++;
4464 			if (!(len -= copy))
4465 				return elt;
4466 			offset += copy;
4467 		}
4468 		start = end;
4469 	}
4470 
4471 	skb_walk_frags(skb, frag_iter) {
4472 		int end, ret;
4473 
4474 		WARN_ON(start > offset + len);
4475 
4476 		end = start + frag_iter->len;
4477 		if ((copy = end - offset) > 0) {
4478 			if (unlikely(elt && sg_is_last(&sg[elt - 1])))
4479 				return -EMSGSIZE;
4480 
4481 			if (copy > len)
4482 				copy = len;
4483 			ret = __skb_to_sgvec(frag_iter, sg+elt, offset - start,
4484 					      copy, recursion_level + 1);
4485 			if (unlikely(ret < 0))
4486 				return ret;
4487 			elt += ret;
4488 			if ((len -= copy) == 0)
4489 				return elt;
4490 			offset += copy;
4491 		}
4492 		start = end;
4493 	}
4494 	BUG_ON(len);
4495 	return elt;
4496 }
4497 
4498 /**
4499  *	skb_to_sgvec - Fill a scatter-gather list from a socket buffer
4500  *	@skb: Socket buffer containing the buffers to be mapped
4501  *	@sg: The scatter-gather list to map into
4502  *	@offset: The offset into the buffer's contents to start mapping
4503  *	@len: Length of buffer space to be mapped
4504  *
4505  *	Fill the specified scatter-gather list with mappings/pointers into a
4506  *	region of the buffer space attached to a socket buffer. Returns either
4507  *	the number of scatterlist items used, or -EMSGSIZE if the contents
4508  *	could not fit.
4509  */
4510 int skb_to_sgvec(struct sk_buff *skb, struct scatterlist *sg, int offset, int len)
4511 {
4512 	int nsg = __skb_to_sgvec(skb, sg, offset, len, 0);
4513 
4514 	if (nsg <= 0)
4515 		return nsg;
4516 
4517 	sg_mark_end(&sg[nsg - 1]);
4518 
4519 	return nsg;
4520 }
4521 EXPORT_SYMBOL_GPL(skb_to_sgvec);
4522 
4523 /* As compared with skb_to_sgvec, skb_to_sgvec_nomark only map skb to given
4524  * sglist without mark the sg which contain last skb data as the end.
4525  * So the caller can mannipulate sg list as will when padding new data after
4526  * the first call without calling sg_unmark_end to expend sg list.
4527  *
4528  * Scenario to use skb_to_sgvec_nomark:
4529  * 1. sg_init_table
4530  * 2. skb_to_sgvec_nomark(payload1)
4531  * 3. skb_to_sgvec_nomark(payload2)
4532  *
4533  * This is equivalent to:
4534  * 1. sg_init_table
4535  * 2. skb_to_sgvec(payload1)
4536  * 3. sg_unmark_end
4537  * 4. skb_to_sgvec(payload2)
4538  *
4539  * When mapping mutilple payload conditionally, skb_to_sgvec_nomark
4540  * is more preferable.
4541  */
4542 int skb_to_sgvec_nomark(struct sk_buff *skb, struct scatterlist *sg,
4543 			int offset, int len)
4544 {
4545 	return __skb_to_sgvec(skb, sg, offset, len, 0);
4546 }
4547 EXPORT_SYMBOL_GPL(skb_to_sgvec_nomark);
4548 
4549 
4550 
4551 /**
4552  *	skb_cow_data - Check that a socket buffer's data buffers are writable
4553  *	@skb: The socket buffer to check.
4554  *	@tailbits: Amount of trailing space to be added
4555  *	@trailer: Returned pointer to the skb where the @tailbits space begins
4556  *
4557  *	Make sure that the data buffers attached to a socket buffer are
4558  *	writable. If they are not, private copies are made of the data buffers
4559  *	and the socket buffer is set to use these instead.
4560  *
4561  *	If @tailbits is given, make sure that there is space to write @tailbits
4562  *	bytes of data beyond current end of socket buffer.  @trailer will be
4563  *	set to point to the skb in which this space begins.
4564  *
4565  *	The number of scatterlist elements required to completely map the
4566  *	COW'd and extended socket buffer will be returned.
4567  */
4568 int skb_cow_data(struct sk_buff *skb, int tailbits, struct sk_buff **trailer)
4569 {
4570 	int copyflag;
4571 	int elt;
4572 	struct sk_buff *skb1, **skb_p;
4573 
4574 	/* If skb is cloned or its head is paged, reallocate
4575 	 * head pulling out all the pages (pages are considered not writable
4576 	 * at the moment even if they are anonymous).
4577 	 */
4578 	if ((skb_cloned(skb) || skb_shinfo(skb)->nr_frags) &&
4579 	    !__pskb_pull_tail(skb, __skb_pagelen(skb)))
4580 		return -ENOMEM;
4581 
4582 	/* Easy case. Most of packets will go this way. */
4583 	if (!skb_has_frag_list(skb)) {
4584 		/* A little of trouble, not enough of space for trailer.
4585 		 * This should not happen, when stack is tuned to generate
4586 		 * good frames. OK, on miss we reallocate and reserve even more
4587 		 * space, 128 bytes is fair. */
4588 
4589 		if (skb_tailroom(skb) < tailbits &&
4590 		    pskb_expand_head(skb, 0, tailbits-skb_tailroom(skb)+128, GFP_ATOMIC))
4591 			return -ENOMEM;
4592 
4593 		/* Voila! */
4594 		*trailer = skb;
4595 		return 1;
4596 	}
4597 
4598 	/* Misery. We are in troubles, going to mincer fragments... */
4599 
4600 	elt = 1;
4601 	skb_p = &skb_shinfo(skb)->frag_list;
4602 	copyflag = 0;
4603 
4604 	while ((skb1 = *skb_p) != NULL) {
4605 		int ntail = 0;
4606 
4607 		/* The fragment is partially pulled by someone,
4608 		 * this can happen on input. Copy it and everything
4609 		 * after it. */
4610 
4611 		if (skb_shared(skb1))
4612 			copyflag = 1;
4613 
4614 		/* If the skb is the last, worry about trailer. */
4615 
4616 		if (skb1->next == NULL && tailbits) {
4617 			if (skb_shinfo(skb1)->nr_frags ||
4618 			    skb_has_frag_list(skb1) ||
4619 			    skb_tailroom(skb1) < tailbits)
4620 				ntail = tailbits + 128;
4621 		}
4622 
4623 		if (copyflag ||
4624 		    skb_cloned(skb1) ||
4625 		    ntail ||
4626 		    skb_shinfo(skb1)->nr_frags ||
4627 		    skb_has_frag_list(skb1)) {
4628 			struct sk_buff *skb2;
4629 
4630 			/* Fuck, we are miserable poor guys... */
4631 			if (ntail == 0)
4632 				skb2 = skb_copy(skb1, GFP_ATOMIC);
4633 			else
4634 				skb2 = skb_copy_expand(skb1,
4635 						       skb_headroom(skb1),
4636 						       ntail,
4637 						       GFP_ATOMIC);
4638 			if (unlikely(skb2 == NULL))
4639 				return -ENOMEM;
4640 
4641 			if (skb1->sk)
4642 				skb_set_owner_w(skb2, skb1->sk);
4643 
4644 			/* Looking around. Are we still alive?
4645 			 * OK, link new skb, drop old one */
4646 
4647 			skb2->next = skb1->next;
4648 			*skb_p = skb2;
4649 			kfree_skb(skb1);
4650 			skb1 = skb2;
4651 		}
4652 		elt++;
4653 		*trailer = skb1;
4654 		skb_p = &skb1->next;
4655 	}
4656 
4657 	return elt;
4658 }
4659 EXPORT_SYMBOL_GPL(skb_cow_data);
4660 
4661 static void sock_rmem_free(struct sk_buff *skb)
4662 {
4663 	struct sock *sk = skb->sk;
4664 
4665 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
4666 }
4667 
4668 static void skb_set_err_queue(struct sk_buff *skb)
4669 {
4670 	/* pkt_type of skbs received on local sockets is never PACKET_OUTGOING.
4671 	 * So, it is safe to (mis)use it to mark skbs on the error queue.
4672 	 */
4673 	skb->pkt_type = PACKET_OUTGOING;
4674 	BUILD_BUG_ON(PACKET_OUTGOING == 0);
4675 }
4676 
4677 /*
4678  * Note: We dont mem charge error packets (no sk_forward_alloc changes)
4679  */
4680 int sock_queue_err_skb(struct sock *sk, struct sk_buff *skb)
4681 {
4682 	if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
4683 	    (unsigned int)READ_ONCE(sk->sk_rcvbuf))
4684 		return -ENOMEM;
4685 
4686 	skb_orphan(skb);
4687 	skb->sk = sk;
4688 	skb->destructor = sock_rmem_free;
4689 	atomic_add(skb->truesize, &sk->sk_rmem_alloc);
4690 	skb_set_err_queue(skb);
4691 
4692 	/* before exiting rcu section, make sure dst is refcounted */
4693 	skb_dst_force(skb);
4694 
4695 	skb_queue_tail(&sk->sk_error_queue, skb);
4696 	if (!sock_flag(sk, SOCK_DEAD))
4697 		sk_error_report(sk);
4698 	return 0;
4699 }
4700 EXPORT_SYMBOL(sock_queue_err_skb);
4701 
4702 static bool is_icmp_err_skb(const struct sk_buff *skb)
4703 {
4704 	return skb && (SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP ||
4705 		       SKB_EXT_ERR(skb)->ee.ee_origin == SO_EE_ORIGIN_ICMP6);
4706 }
4707 
4708 struct sk_buff *sock_dequeue_err_skb(struct sock *sk)
4709 {
4710 	struct sk_buff_head *q = &sk->sk_error_queue;
4711 	struct sk_buff *skb, *skb_next = NULL;
4712 	bool icmp_next = false;
4713 	unsigned long flags;
4714 
4715 	spin_lock_irqsave(&q->lock, flags);
4716 	skb = __skb_dequeue(q);
4717 	if (skb && (skb_next = skb_peek(q))) {
4718 		icmp_next = is_icmp_err_skb(skb_next);
4719 		if (icmp_next)
4720 			sk->sk_err = SKB_EXT_ERR(skb_next)->ee.ee_errno;
4721 	}
4722 	spin_unlock_irqrestore(&q->lock, flags);
4723 
4724 	if (is_icmp_err_skb(skb) && !icmp_next)
4725 		sk->sk_err = 0;
4726 
4727 	if (skb_next)
4728 		sk_error_report(sk);
4729 
4730 	return skb;
4731 }
4732 EXPORT_SYMBOL(sock_dequeue_err_skb);
4733 
4734 /**
4735  * skb_clone_sk - create clone of skb, and take reference to socket
4736  * @skb: the skb to clone
4737  *
4738  * This function creates a clone of a buffer that holds a reference on
4739  * sk_refcnt.  Buffers created via this function are meant to be
4740  * returned using sock_queue_err_skb, or free via kfree_skb.
4741  *
4742  * When passing buffers allocated with this function to sock_queue_err_skb
4743  * it is necessary to wrap the call with sock_hold/sock_put in order to
4744  * prevent the socket from being released prior to being enqueued on
4745  * the sk_error_queue.
4746  */
4747 struct sk_buff *skb_clone_sk(struct sk_buff *skb)
4748 {
4749 	struct sock *sk = skb->sk;
4750 	struct sk_buff *clone;
4751 
4752 	if (!sk || !refcount_inc_not_zero(&sk->sk_refcnt))
4753 		return NULL;
4754 
4755 	clone = skb_clone(skb, GFP_ATOMIC);
4756 	if (!clone) {
4757 		sock_put(sk);
4758 		return NULL;
4759 	}
4760 
4761 	clone->sk = sk;
4762 	clone->destructor = sock_efree;
4763 
4764 	return clone;
4765 }
4766 EXPORT_SYMBOL(skb_clone_sk);
4767 
4768 static void __skb_complete_tx_timestamp(struct sk_buff *skb,
4769 					struct sock *sk,
4770 					int tstype,
4771 					bool opt_stats)
4772 {
4773 	struct sock_exterr_skb *serr;
4774 	int err;
4775 
4776 	BUILD_BUG_ON(sizeof(struct sock_exterr_skb) > sizeof(skb->cb));
4777 
4778 	serr = SKB_EXT_ERR(skb);
4779 	memset(serr, 0, sizeof(*serr));
4780 	serr->ee.ee_errno = ENOMSG;
4781 	serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING;
4782 	serr->ee.ee_info = tstype;
4783 	serr->opt_stats = opt_stats;
4784 	serr->header.h4.iif = skb->dev ? skb->dev->ifindex : 0;
4785 	if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) {
4786 		serr->ee.ee_data = skb_shinfo(skb)->tskey;
4787 		if (sk_is_tcp(sk))
4788 			serr->ee.ee_data -= atomic_read(&sk->sk_tskey);
4789 	}
4790 
4791 	err = sock_queue_err_skb(sk, skb);
4792 
4793 	if (err)
4794 		kfree_skb(skb);
4795 }
4796 
4797 static bool skb_may_tx_timestamp(struct sock *sk, bool tsonly)
4798 {
4799 	bool ret;
4800 
4801 	if (likely(sysctl_tstamp_allow_data || tsonly))
4802 		return true;
4803 
4804 	read_lock_bh(&sk->sk_callback_lock);
4805 	ret = sk->sk_socket && sk->sk_socket->file &&
4806 	      file_ns_capable(sk->sk_socket->file, &init_user_ns, CAP_NET_RAW);
4807 	read_unlock_bh(&sk->sk_callback_lock);
4808 	return ret;
4809 }
4810 
4811 void skb_complete_tx_timestamp(struct sk_buff *skb,
4812 			       struct skb_shared_hwtstamps *hwtstamps)
4813 {
4814 	struct sock *sk = skb->sk;
4815 
4816 	if (!skb_may_tx_timestamp(sk, false))
4817 		goto err;
4818 
4819 	/* Take a reference to prevent skb_orphan() from freeing the socket,
4820 	 * but only if the socket refcount is not zero.
4821 	 */
4822 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4823 		*skb_hwtstamps(skb) = *hwtstamps;
4824 		__skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND, false);
4825 		sock_put(sk);
4826 		return;
4827 	}
4828 
4829 err:
4830 	kfree_skb(skb);
4831 }
4832 EXPORT_SYMBOL_GPL(skb_complete_tx_timestamp);
4833 
4834 void __skb_tstamp_tx(struct sk_buff *orig_skb,
4835 		     const struct sk_buff *ack_skb,
4836 		     struct skb_shared_hwtstamps *hwtstamps,
4837 		     struct sock *sk, int tstype)
4838 {
4839 	struct sk_buff *skb;
4840 	bool tsonly, opt_stats = false;
4841 
4842 	if (!sk)
4843 		return;
4844 
4845 	if (!hwtstamps && !(sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TX_SWHW) &&
4846 	    skb_shinfo(orig_skb)->tx_flags & SKBTX_IN_PROGRESS)
4847 		return;
4848 
4849 	tsonly = sk->sk_tsflags & SOF_TIMESTAMPING_OPT_TSONLY;
4850 	if (!skb_may_tx_timestamp(sk, tsonly))
4851 		return;
4852 
4853 	if (tsonly) {
4854 #ifdef CONFIG_INET
4855 		if ((sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS) &&
4856 		    sk_is_tcp(sk)) {
4857 			skb = tcp_get_timestamping_opt_stats(sk, orig_skb,
4858 							     ack_skb);
4859 			opt_stats = true;
4860 		} else
4861 #endif
4862 			skb = alloc_skb(0, GFP_ATOMIC);
4863 	} else {
4864 		skb = skb_clone(orig_skb, GFP_ATOMIC);
4865 	}
4866 	if (!skb)
4867 		return;
4868 
4869 	if (tsonly) {
4870 		skb_shinfo(skb)->tx_flags |= skb_shinfo(orig_skb)->tx_flags &
4871 					     SKBTX_ANY_TSTAMP;
4872 		skb_shinfo(skb)->tskey = skb_shinfo(orig_skb)->tskey;
4873 	}
4874 
4875 	if (hwtstamps)
4876 		*skb_hwtstamps(skb) = *hwtstamps;
4877 	else
4878 		__net_timestamp(skb);
4879 
4880 	__skb_complete_tx_timestamp(skb, sk, tstype, opt_stats);
4881 }
4882 EXPORT_SYMBOL_GPL(__skb_tstamp_tx);
4883 
4884 void skb_tstamp_tx(struct sk_buff *orig_skb,
4885 		   struct skb_shared_hwtstamps *hwtstamps)
4886 {
4887 	return __skb_tstamp_tx(orig_skb, NULL, hwtstamps, orig_skb->sk,
4888 			       SCM_TSTAMP_SND);
4889 }
4890 EXPORT_SYMBOL_GPL(skb_tstamp_tx);
4891 
4892 void skb_complete_wifi_ack(struct sk_buff *skb, bool acked)
4893 {
4894 	struct sock *sk = skb->sk;
4895 	struct sock_exterr_skb *serr;
4896 	int err = 1;
4897 
4898 	skb->wifi_acked_valid = 1;
4899 	skb->wifi_acked = acked;
4900 
4901 	serr = SKB_EXT_ERR(skb);
4902 	memset(serr, 0, sizeof(*serr));
4903 	serr->ee.ee_errno = ENOMSG;
4904 	serr->ee.ee_origin = SO_EE_ORIGIN_TXSTATUS;
4905 
4906 	/* Take a reference to prevent skb_orphan() from freeing the socket,
4907 	 * but only if the socket refcount is not zero.
4908 	 */
4909 	if (likely(refcount_inc_not_zero(&sk->sk_refcnt))) {
4910 		err = sock_queue_err_skb(sk, skb);
4911 		sock_put(sk);
4912 	}
4913 	if (err)
4914 		kfree_skb(skb);
4915 }
4916 EXPORT_SYMBOL_GPL(skb_complete_wifi_ack);
4917 
4918 /**
4919  * skb_partial_csum_set - set up and verify partial csum values for packet
4920  * @skb: the skb to set
4921  * @start: the number of bytes after skb->data to start checksumming.
4922  * @off: the offset from start to place the checksum.
4923  *
4924  * For untrusted partially-checksummed packets, we need to make sure the values
4925  * for skb->csum_start and skb->csum_offset are valid so we don't oops.
4926  *
4927  * This function checks and sets those values and skb->ip_summed: if this
4928  * returns false you should drop the packet.
4929  */
4930 bool skb_partial_csum_set(struct sk_buff *skb, u16 start, u16 off)
4931 {
4932 	u32 csum_end = (u32)start + (u32)off + sizeof(__sum16);
4933 	u32 csum_start = skb_headroom(skb) + (u32)start;
4934 
4935 	if (unlikely(csum_start > U16_MAX || csum_end > skb_headlen(skb))) {
4936 		net_warn_ratelimited("bad partial csum: csum=%u/%u headroom=%u headlen=%u\n",
4937 				     start, off, skb_headroom(skb), skb_headlen(skb));
4938 		return false;
4939 	}
4940 	skb->ip_summed = CHECKSUM_PARTIAL;
4941 	skb->csum_start = csum_start;
4942 	skb->csum_offset = off;
4943 	skb_set_transport_header(skb, start);
4944 	return true;
4945 }
4946 EXPORT_SYMBOL_GPL(skb_partial_csum_set);
4947 
4948 static int skb_maybe_pull_tail(struct sk_buff *skb, unsigned int len,
4949 			       unsigned int max)
4950 {
4951 	if (skb_headlen(skb) >= len)
4952 		return 0;
4953 
4954 	/* If we need to pullup then pullup to the max, so we
4955 	 * won't need to do it again.
4956 	 */
4957 	if (max > skb->len)
4958 		max = skb->len;
4959 
4960 	if (__pskb_pull_tail(skb, max - skb_headlen(skb)) == NULL)
4961 		return -ENOMEM;
4962 
4963 	if (skb_headlen(skb) < len)
4964 		return -EPROTO;
4965 
4966 	return 0;
4967 }
4968 
4969 #define MAX_TCP_HDR_LEN (15 * 4)
4970 
4971 static __sum16 *skb_checksum_setup_ip(struct sk_buff *skb,
4972 				      typeof(IPPROTO_IP) proto,
4973 				      unsigned int off)
4974 {
4975 	int err;
4976 
4977 	switch (proto) {
4978 	case IPPROTO_TCP:
4979 		err = skb_maybe_pull_tail(skb, off + sizeof(struct tcphdr),
4980 					  off + MAX_TCP_HDR_LEN);
4981 		if (!err && !skb_partial_csum_set(skb, off,
4982 						  offsetof(struct tcphdr,
4983 							   check)))
4984 			err = -EPROTO;
4985 		return err ? ERR_PTR(err) : &tcp_hdr(skb)->check;
4986 
4987 	case IPPROTO_UDP:
4988 		err = skb_maybe_pull_tail(skb, off + sizeof(struct udphdr),
4989 					  off + sizeof(struct udphdr));
4990 		if (!err && !skb_partial_csum_set(skb, off,
4991 						  offsetof(struct udphdr,
4992 							   check)))
4993 			err = -EPROTO;
4994 		return err ? ERR_PTR(err) : &udp_hdr(skb)->check;
4995 	}
4996 
4997 	return ERR_PTR(-EPROTO);
4998 }
4999 
5000 /* This value should be large enough to cover a tagged ethernet header plus
5001  * maximally sized IP and TCP or UDP headers.
5002  */
5003 #define MAX_IP_HDR_LEN 128
5004 
5005 static int skb_checksum_setup_ipv4(struct sk_buff *skb, bool recalculate)
5006 {
5007 	unsigned int off;
5008 	bool fragment;
5009 	__sum16 *csum;
5010 	int err;
5011 
5012 	fragment = false;
5013 
5014 	err = skb_maybe_pull_tail(skb,
5015 				  sizeof(struct iphdr),
5016 				  MAX_IP_HDR_LEN);
5017 	if (err < 0)
5018 		goto out;
5019 
5020 	if (ip_is_fragment(ip_hdr(skb)))
5021 		fragment = true;
5022 
5023 	off = ip_hdrlen(skb);
5024 
5025 	err = -EPROTO;
5026 
5027 	if (fragment)
5028 		goto out;
5029 
5030 	csum = skb_checksum_setup_ip(skb, ip_hdr(skb)->protocol, off);
5031 	if (IS_ERR(csum))
5032 		return PTR_ERR(csum);
5033 
5034 	if (recalculate)
5035 		*csum = ~csum_tcpudp_magic(ip_hdr(skb)->saddr,
5036 					   ip_hdr(skb)->daddr,
5037 					   skb->len - off,
5038 					   ip_hdr(skb)->protocol, 0);
5039 	err = 0;
5040 
5041 out:
5042 	return err;
5043 }
5044 
5045 /* This value should be large enough to cover a tagged ethernet header plus
5046  * an IPv6 header, all options, and a maximal TCP or UDP header.
5047  */
5048 #define MAX_IPV6_HDR_LEN 256
5049 
5050 #define OPT_HDR(type, skb, off) \
5051 	(type *)(skb_network_header(skb) + (off))
5052 
5053 static int skb_checksum_setup_ipv6(struct sk_buff *skb, bool recalculate)
5054 {
5055 	int err;
5056 	u8 nexthdr;
5057 	unsigned int off;
5058 	unsigned int len;
5059 	bool fragment;
5060 	bool done;
5061 	__sum16 *csum;
5062 
5063 	fragment = false;
5064 	done = false;
5065 
5066 	off = sizeof(struct ipv6hdr);
5067 
5068 	err = skb_maybe_pull_tail(skb, off, MAX_IPV6_HDR_LEN);
5069 	if (err < 0)
5070 		goto out;
5071 
5072 	nexthdr = ipv6_hdr(skb)->nexthdr;
5073 
5074 	len = sizeof(struct ipv6hdr) + ntohs(ipv6_hdr(skb)->payload_len);
5075 	while (off <= len && !done) {
5076 		switch (nexthdr) {
5077 		case IPPROTO_DSTOPTS:
5078 		case IPPROTO_HOPOPTS:
5079 		case IPPROTO_ROUTING: {
5080 			struct ipv6_opt_hdr *hp;
5081 
5082 			err = skb_maybe_pull_tail(skb,
5083 						  off +
5084 						  sizeof(struct ipv6_opt_hdr),
5085 						  MAX_IPV6_HDR_LEN);
5086 			if (err < 0)
5087 				goto out;
5088 
5089 			hp = OPT_HDR(struct ipv6_opt_hdr, skb, off);
5090 			nexthdr = hp->nexthdr;
5091 			off += ipv6_optlen(hp);
5092 			break;
5093 		}
5094 		case IPPROTO_AH: {
5095 			struct ip_auth_hdr *hp;
5096 
5097 			err = skb_maybe_pull_tail(skb,
5098 						  off +
5099 						  sizeof(struct ip_auth_hdr),
5100 						  MAX_IPV6_HDR_LEN);
5101 			if (err < 0)
5102 				goto out;
5103 
5104 			hp = OPT_HDR(struct ip_auth_hdr, skb, off);
5105 			nexthdr = hp->nexthdr;
5106 			off += ipv6_authlen(hp);
5107 			break;
5108 		}
5109 		case IPPROTO_FRAGMENT: {
5110 			struct frag_hdr *hp;
5111 
5112 			err = skb_maybe_pull_tail(skb,
5113 						  off +
5114 						  sizeof(struct frag_hdr),
5115 						  MAX_IPV6_HDR_LEN);
5116 			if (err < 0)
5117 				goto out;
5118 
5119 			hp = OPT_HDR(struct frag_hdr, skb, off);
5120 
5121 			if (hp->frag_off & htons(IP6_OFFSET | IP6_MF))
5122 				fragment = true;
5123 
5124 			nexthdr = hp->nexthdr;
5125 			off += sizeof(struct frag_hdr);
5126 			break;
5127 		}
5128 		default:
5129 			done = true;
5130 			break;
5131 		}
5132 	}
5133 
5134 	err = -EPROTO;
5135 
5136 	if (!done || fragment)
5137 		goto out;
5138 
5139 	csum = skb_checksum_setup_ip(skb, nexthdr, off);
5140 	if (IS_ERR(csum))
5141 		return PTR_ERR(csum);
5142 
5143 	if (recalculate)
5144 		*csum = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
5145 					 &ipv6_hdr(skb)->daddr,
5146 					 skb->len - off, nexthdr, 0);
5147 	err = 0;
5148 
5149 out:
5150 	return err;
5151 }
5152 
5153 /**
5154  * skb_checksum_setup - set up partial checksum offset
5155  * @skb: the skb to set up
5156  * @recalculate: if true the pseudo-header checksum will be recalculated
5157  */
5158 int skb_checksum_setup(struct sk_buff *skb, bool recalculate)
5159 {
5160 	int err;
5161 
5162 	switch (skb->protocol) {
5163 	case htons(ETH_P_IP):
5164 		err = skb_checksum_setup_ipv4(skb, recalculate);
5165 		break;
5166 
5167 	case htons(ETH_P_IPV6):
5168 		err = skb_checksum_setup_ipv6(skb, recalculate);
5169 		break;
5170 
5171 	default:
5172 		err = -EPROTO;
5173 		break;
5174 	}
5175 
5176 	return err;
5177 }
5178 EXPORT_SYMBOL(skb_checksum_setup);
5179 
5180 /**
5181  * skb_checksum_maybe_trim - maybe trims the given skb
5182  * @skb: the skb to check
5183  * @transport_len: the data length beyond the network header
5184  *
5185  * Checks whether the given skb has data beyond the given transport length.
5186  * If so, returns a cloned skb trimmed to this transport length.
5187  * Otherwise returns the provided skb. Returns NULL in error cases
5188  * (e.g. transport_len exceeds skb length or out-of-memory).
5189  *
5190  * Caller needs to set the skb transport header and free any returned skb if it
5191  * differs from the provided skb.
5192  */
5193 static struct sk_buff *skb_checksum_maybe_trim(struct sk_buff *skb,
5194 					       unsigned int transport_len)
5195 {
5196 	struct sk_buff *skb_chk;
5197 	unsigned int len = skb_transport_offset(skb) + transport_len;
5198 	int ret;
5199 
5200 	if (skb->len < len)
5201 		return NULL;
5202 	else if (skb->len == len)
5203 		return skb;
5204 
5205 	skb_chk = skb_clone(skb, GFP_ATOMIC);
5206 	if (!skb_chk)
5207 		return NULL;
5208 
5209 	ret = pskb_trim_rcsum(skb_chk, len);
5210 	if (ret) {
5211 		kfree_skb(skb_chk);
5212 		return NULL;
5213 	}
5214 
5215 	return skb_chk;
5216 }
5217 
5218 /**
5219  * skb_checksum_trimmed - validate checksum of an skb
5220  * @skb: the skb to check
5221  * @transport_len: the data length beyond the network header
5222  * @skb_chkf: checksum function to use
5223  *
5224  * Applies the given checksum function skb_chkf to the provided skb.
5225  * Returns a checked and maybe trimmed skb. Returns NULL on error.
5226  *
5227  * If the skb has data beyond the given transport length, then a
5228  * trimmed & cloned skb is checked and returned.
5229  *
5230  * Caller needs to set the skb transport header and free any returned skb if it
5231  * differs from the provided skb.
5232  */
5233 struct sk_buff *skb_checksum_trimmed(struct sk_buff *skb,
5234 				     unsigned int transport_len,
5235 				     __sum16(*skb_chkf)(struct sk_buff *skb))
5236 {
5237 	struct sk_buff *skb_chk;
5238 	unsigned int offset = skb_transport_offset(skb);
5239 	__sum16 ret;
5240 
5241 	skb_chk = skb_checksum_maybe_trim(skb, transport_len);
5242 	if (!skb_chk)
5243 		goto err;
5244 
5245 	if (!pskb_may_pull(skb_chk, offset))
5246 		goto err;
5247 
5248 	skb_pull_rcsum(skb_chk, offset);
5249 	ret = skb_chkf(skb_chk);
5250 	skb_push_rcsum(skb_chk, offset);
5251 
5252 	if (ret)
5253 		goto err;
5254 
5255 	return skb_chk;
5256 
5257 err:
5258 	if (skb_chk && skb_chk != skb)
5259 		kfree_skb(skb_chk);
5260 
5261 	return NULL;
5262 
5263 }
5264 EXPORT_SYMBOL(skb_checksum_trimmed);
5265 
5266 void __skb_warn_lro_forwarding(const struct sk_buff *skb)
5267 {
5268 	net_warn_ratelimited("%s: received packets cannot be forwarded while LRO is enabled\n",
5269 			     skb->dev->name);
5270 }
5271 EXPORT_SYMBOL(__skb_warn_lro_forwarding);
5272 
5273 void kfree_skb_partial(struct sk_buff *skb, bool head_stolen)
5274 {
5275 	if (head_stolen) {
5276 		skb_release_head_state(skb);
5277 		kmem_cache_free(skbuff_head_cache, skb);
5278 	} else {
5279 		__kfree_skb(skb);
5280 	}
5281 }
5282 EXPORT_SYMBOL(kfree_skb_partial);
5283 
5284 /**
5285  * skb_try_coalesce - try to merge skb to prior one
5286  * @to: prior buffer
5287  * @from: buffer to add
5288  * @fragstolen: pointer to boolean
5289  * @delta_truesize: how much more was allocated than was requested
5290  */
5291 bool skb_try_coalesce(struct sk_buff *to, struct sk_buff *from,
5292 		      bool *fragstolen, int *delta_truesize)
5293 {
5294 	struct skb_shared_info *to_shinfo, *from_shinfo;
5295 	int i, delta, len = from->len;
5296 
5297 	*fragstolen = false;
5298 
5299 	if (skb_cloned(to))
5300 		return false;
5301 
5302 	/* In general, avoid mixing slab allocated and page_pool allocated
5303 	 * pages within the same SKB. However when @to is not pp_recycle and
5304 	 * @from is cloned, we can transition frag pages from page_pool to
5305 	 * reference counted.
5306 	 *
5307 	 * On the other hand, don't allow coalescing two pp_recycle SKBs if
5308 	 * @from is cloned, in case the SKB is using page_pool fragment
5309 	 * references (PP_FLAG_PAGE_FRAG). Since we only take full page
5310 	 * references for cloned SKBs at the moment that would result in
5311 	 * inconsistent reference counts.
5312 	 */
5313 	if (to->pp_recycle != (from->pp_recycle && !skb_cloned(from)))
5314 		return false;
5315 
5316 	if (len <= skb_tailroom(to)) {
5317 		if (len)
5318 			BUG_ON(skb_copy_bits(from, 0, skb_put(to, len), len));
5319 		*delta_truesize = 0;
5320 		return true;
5321 	}
5322 
5323 	to_shinfo = skb_shinfo(to);
5324 	from_shinfo = skb_shinfo(from);
5325 	if (to_shinfo->frag_list || from_shinfo->frag_list)
5326 		return false;
5327 	if (skb_zcopy(to) || skb_zcopy(from))
5328 		return false;
5329 
5330 	if (skb_headlen(from) != 0) {
5331 		struct page *page;
5332 		unsigned int offset;
5333 
5334 		if (to_shinfo->nr_frags +
5335 		    from_shinfo->nr_frags >= MAX_SKB_FRAGS)
5336 			return false;
5337 
5338 		if (skb_head_is_locked(from))
5339 			return false;
5340 
5341 		delta = from->truesize - SKB_DATA_ALIGN(sizeof(struct sk_buff));
5342 
5343 		page = virt_to_head_page(from->head);
5344 		offset = from->data - (unsigned char *)page_address(page);
5345 
5346 		skb_fill_page_desc(to, to_shinfo->nr_frags,
5347 				   page, offset, skb_headlen(from));
5348 		*fragstolen = true;
5349 	} else {
5350 		if (to_shinfo->nr_frags +
5351 		    from_shinfo->nr_frags > MAX_SKB_FRAGS)
5352 			return false;
5353 
5354 		delta = from->truesize - SKB_TRUESIZE(skb_end_offset(from));
5355 	}
5356 
5357 	WARN_ON_ONCE(delta < len);
5358 
5359 	memcpy(to_shinfo->frags + to_shinfo->nr_frags,
5360 	       from_shinfo->frags,
5361 	       from_shinfo->nr_frags * sizeof(skb_frag_t));
5362 	to_shinfo->nr_frags += from_shinfo->nr_frags;
5363 
5364 	if (!skb_cloned(from))
5365 		from_shinfo->nr_frags = 0;
5366 
5367 	/* if the skb is not cloned this does nothing
5368 	 * since we set nr_frags to 0.
5369 	 */
5370 	for (i = 0; i < from_shinfo->nr_frags; i++)
5371 		__skb_frag_ref(&from_shinfo->frags[i]);
5372 
5373 	to->truesize += delta;
5374 	to->len += len;
5375 	to->data_len += len;
5376 
5377 	*delta_truesize = delta;
5378 	return true;
5379 }
5380 EXPORT_SYMBOL(skb_try_coalesce);
5381 
5382 /**
5383  * skb_scrub_packet - scrub an skb
5384  *
5385  * @skb: buffer to clean
5386  * @xnet: packet is crossing netns
5387  *
5388  * skb_scrub_packet can be used after encapsulating or decapsulting a packet
5389  * into/from a tunnel. Some information have to be cleared during these
5390  * operations.
5391  * skb_scrub_packet can also be used to clean a skb before injecting it in
5392  * another namespace (@xnet == true). We have to clear all information in the
5393  * skb that could impact namespace isolation.
5394  */
5395 void skb_scrub_packet(struct sk_buff *skb, bool xnet)
5396 {
5397 	skb->pkt_type = PACKET_HOST;
5398 	skb->skb_iif = 0;
5399 	skb->ignore_df = 0;
5400 	skb_dst_drop(skb);
5401 	skb_ext_reset(skb);
5402 	nf_reset_ct(skb);
5403 	nf_reset_trace(skb);
5404 
5405 #ifdef CONFIG_NET_SWITCHDEV
5406 	skb->offload_fwd_mark = 0;
5407 	skb->offload_l3_fwd_mark = 0;
5408 #endif
5409 
5410 	if (!xnet)
5411 		return;
5412 
5413 	ipvs_reset(skb);
5414 	skb->mark = 0;
5415 	skb_clear_tstamp(skb);
5416 }
5417 EXPORT_SYMBOL_GPL(skb_scrub_packet);
5418 
5419 /**
5420  * skb_gso_transport_seglen - Return length of individual segments of a gso packet
5421  *
5422  * @skb: GSO skb
5423  *
5424  * skb_gso_transport_seglen is used to determine the real size of the
5425  * individual segments, including Layer4 headers (TCP/UDP).
5426  *
5427  * The MAC/L2 or network (IP, IPv6) headers are not accounted for.
5428  */
5429 static unsigned int skb_gso_transport_seglen(const struct sk_buff *skb)
5430 {
5431 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
5432 	unsigned int thlen = 0;
5433 
5434 	if (skb->encapsulation) {
5435 		thlen = skb_inner_transport_header(skb) -
5436 			skb_transport_header(skb);
5437 
5438 		if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6)))
5439 			thlen += inner_tcp_hdrlen(skb);
5440 	} else if (likely(shinfo->gso_type & (SKB_GSO_TCPV4 | SKB_GSO_TCPV6))) {
5441 		thlen = tcp_hdrlen(skb);
5442 	} else if (unlikely(skb_is_gso_sctp(skb))) {
5443 		thlen = sizeof(struct sctphdr);
5444 	} else if (shinfo->gso_type & SKB_GSO_UDP_L4) {
5445 		thlen = sizeof(struct udphdr);
5446 	}
5447 	/* UFO sets gso_size to the size of the fragmentation
5448 	 * payload, i.e. the size of the L4 (UDP) header is already
5449 	 * accounted for.
5450 	 */
5451 	return thlen + shinfo->gso_size;
5452 }
5453 
5454 /**
5455  * skb_gso_network_seglen - Return length of individual segments of a gso packet
5456  *
5457  * @skb: GSO skb
5458  *
5459  * skb_gso_network_seglen is used to determine the real size of the
5460  * individual segments, including Layer3 (IP, IPv6) and L4 headers (TCP/UDP).
5461  *
5462  * The MAC/L2 header is not accounted for.
5463  */
5464 static unsigned int skb_gso_network_seglen(const struct sk_buff *skb)
5465 {
5466 	unsigned int hdr_len = skb_transport_header(skb) -
5467 			       skb_network_header(skb);
5468 
5469 	return hdr_len + skb_gso_transport_seglen(skb);
5470 }
5471 
5472 /**
5473  * skb_gso_mac_seglen - Return length of individual segments of a gso packet
5474  *
5475  * @skb: GSO skb
5476  *
5477  * skb_gso_mac_seglen is used to determine the real size of the
5478  * individual segments, including MAC/L2, Layer3 (IP, IPv6) and L4
5479  * headers (TCP/UDP).
5480  */
5481 static unsigned int skb_gso_mac_seglen(const struct sk_buff *skb)
5482 {
5483 	unsigned int hdr_len = skb_transport_header(skb) - skb_mac_header(skb);
5484 
5485 	return hdr_len + skb_gso_transport_seglen(skb);
5486 }
5487 
5488 /**
5489  * skb_gso_size_check - check the skb size, considering GSO_BY_FRAGS
5490  *
5491  * There are a couple of instances where we have a GSO skb, and we
5492  * want to determine what size it would be after it is segmented.
5493  *
5494  * We might want to check:
5495  * -    L3+L4+payload size (e.g. IP forwarding)
5496  * - L2+L3+L4+payload size (e.g. sanity check before passing to driver)
5497  *
5498  * This is a helper to do that correctly considering GSO_BY_FRAGS.
5499  *
5500  * @skb: GSO skb
5501  *
5502  * @seg_len: The segmented length (from skb_gso_*_seglen). In the
5503  *           GSO_BY_FRAGS case this will be [header sizes + GSO_BY_FRAGS].
5504  *
5505  * @max_len: The maximum permissible length.
5506  *
5507  * Returns true if the segmented length <= max length.
5508  */
5509 static inline bool skb_gso_size_check(const struct sk_buff *skb,
5510 				      unsigned int seg_len,
5511 				      unsigned int max_len) {
5512 	const struct skb_shared_info *shinfo = skb_shinfo(skb);
5513 	const struct sk_buff *iter;
5514 
5515 	if (shinfo->gso_size != GSO_BY_FRAGS)
5516 		return seg_len <= max_len;
5517 
5518 	/* Undo this so we can re-use header sizes */
5519 	seg_len -= GSO_BY_FRAGS;
5520 
5521 	skb_walk_frags(skb, iter) {
5522 		if (seg_len + skb_headlen(iter) > max_len)
5523 			return false;
5524 	}
5525 
5526 	return true;
5527 }
5528 
5529 /**
5530  * skb_gso_validate_network_len - Will a split GSO skb fit into a given MTU?
5531  *
5532  * @skb: GSO skb
5533  * @mtu: MTU to validate against
5534  *
5535  * skb_gso_validate_network_len validates if a given skb will fit a
5536  * wanted MTU once split. It considers L3 headers, L4 headers, and the
5537  * payload.
5538  */
5539 bool skb_gso_validate_network_len(const struct sk_buff *skb, unsigned int mtu)
5540 {
5541 	return skb_gso_size_check(skb, skb_gso_network_seglen(skb), mtu);
5542 }
5543 EXPORT_SYMBOL_GPL(skb_gso_validate_network_len);
5544 
5545 /**
5546  * skb_gso_validate_mac_len - Will a split GSO skb fit in a given length?
5547  *
5548  * @skb: GSO skb
5549  * @len: length to validate against
5550  *
5551  * skb_gso_validate_mac_len validates if a given skb will fit a wanted
5552  * length once split, including L2, L3 and L4 headers and the payload.
5553  */
5554 bool skb_gso_validate_mac_len(const struct sk_buff *skb, unsigned int len)
5555 {
5556 	return skb_gso_size_check(skb, skb_gso_mac_seglen(skb), len);
5557 }
5558 EXPORT_SYMBOL_GPL(skb_gso_validate_mac_len);
5559 
5560 static struct sk_buff *skb_reorder_vlan_header(struct sk_buff *skb)
5561 {
5562 	int mac_len, meta_len;
5563 	void *meta;
5564 
5565 	if (skb_cow(skb, skb_headroom(skb)) < 0) {
5566 		kfree_skb(skb);
5567 		return NULL;
5568 	}
5569 
5570 	mac_len = skb->data - skb_mac_header(skb);
5571 	if (likely(mac_len > VLAN_HLEN + ETH_TLEN)) {
5572 		memmove(skb_mac_header(skb) + VLAN_HLEN, skb_mac_header(skb),
5573 			mac_len - VLAN_HLEN - ETH_TLEN);
5574 	}
5575 
5576 	meta_len = skb_metadata_len(skb);
5577 	if (meta_len) {
5578 		meta = skb_metadata_end(skb) - meta_len;
5579 		memmove(meta + VLAN_HLEN, meta, meta_len);
5580 	}
5581 
5582 	skb->mac_header += VLAN_HLEN;
5583 	return skb;
5584 }
5585 
5586 struct sk_buff *skb_vlan_untag(struct sk_buff *skb)
5587 {
5588 	struct vlan_hdr *vhdr;
5589 	u16 vlan_tci;
5590 
5591 	if (unlikely(skb_vlan_tag_present(skb))) {
5592 		/* vlan_tci is already set-up so leave this for another time */
5593 		return skb;
5594 	}
5595 
5596 	skb = skb_share_check(skb, GFP_ATOMIC);
5597 	if (unlikely(!skb))
5598 		goto err_free;
5599 	/* We may access the two bytes after vlan_hdr in vlan_set_encap_proto(). */
5600 	if (unlikely(!pskb_may_pull(skb, VLAN_HLEN + sizeof(unsigned short))))
5601 		goto err_free;
5602 
5603 	vhdr = (struct vlan_hdr *)skb->data;
5604 	vlan_tci = ntohs(vhdr->h_vlan_TCI);
5605 	__vlan_hwaccel_put_tag(skb, skb->protocol, vlan_tci);
5606 
5607 	skb_pull_rcsum(skb, VLAN_HLEN);
5608 	vlan_set_encap_proto(skb, vhdr);
5609 
5610 	skb = skb_reorder_vlan_header(skb);
5611 	if (unlikely(!skb))
5612 		goto err_free;
5613 
5614 	skb_reset_network_header(skb);
5615 	if (!skb_transport_header_was_set(skb))
5616 		skb_reset_transport_header(skb);
5617 	skb_reset_mac_len(skb);
5618 
5619 	return skb;
5620 
5621 err_free:
5622 	kfree_skb(skb);
5623 	return NULL;
5624 }
5625 EXPORT_SYMBOL(skb_vlan_untag);
5626 
5627 int skb_ensure_writable(struct sk_buff *skb, unsigned int write_len)
5628 {
5629 	if (!pskb_may_pull(skb, write_len))
5630 		return -ENOMEM;
5631 
5632 	if (!skb_cloned(skb) || skb_clone_writable(skb, write_len))
5633 		return 0;
5634 
5635 	return pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
5636 }
5637 EXPORT_SYMBOL(skb_ensure_writable);
5638 
5639 /* remove VLAN header from packet and update csum accordingly.
5640  * expects a non skb_vlan_tag_present skb with a vlan tag payload
5641  */
5642 int __skb_vlan_pop(struct sk_buff *skb, u16 *vlan_tci)
5643 {
5644 	struct vlan_hdr *vhdr;
5645 	int offset = skb->data - skb_mac_header(skb);
5646 	int err;
5647 
5648 	if (WARN_ONCE(offset,
5649 		      "__skb_vlan_pop got skb with skb->data not at mac header (offset %d)\n",
5650 		      offset)) {
5651 		return -EINVAL;
5652 	}
5653 
5654 	err = skb_ensure_writable(skb, VLAN_ETH_HLEN);
5655 	if (unlikely(err))
5656 		return err;
5657 
5658 	skb_postpull_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5659 
5660 	vhdr = (struct vlan_hdr *)(skb->data + ETH_HLEN);
5661 	*vlan_tci = ntohs(vhdr->h_vlan_TCI);
5662 
5663 	memmove(skb->data + VLAN_HLEN, skb->data, 2 * ETH_ALEN);
5664 	__skb_pull(skb, VLAN_HLEN);
5665 
5666 	vlan_set_encap_proto(skb, vhdr);
5667 	skb->mac_header += VLAN_HLEN;
5668 
5669 	if (skb_network_offset(skb) < ETH_HLEN)
5670 		skb_set_network_header(skb, ETH_HLEN);
5671 
5672 	skb_reset_mac_len(skb);
5673 
5674 	return err;
5675 }
5676 EXPORT_SYMBOL(__skb_vlan_pop);
5677 
5678 /* Pop a vlan tag either from hwaccel or from payload.
5679  * Expects skb->data at mac header.
5680  */
5681 int skb_vlan_pop(struct sk_buff *skb)
5682 {
5683 	u16 vlan_tci;
5684 	__be16 vlan_proto;
5685 	int err;
5686 
5687 	if (likely(skb_vlan_tag_present(skb))) {
5688 		__vlan_hwaccel_clear_tag(skb);
5689 	} else {
5690 		if (unlikely(!eth_type_vlan(skb->protocol)))
5691 			return 0;
5692 
5693 		err = __skb_vlan_pop(skb, &vlan_tci);
5694 		if (err)
5695 			return err;
5696 	}
5697 	/* move next vlan tag to hw accel tag */
5698 	if (likely(!eth_type_vlan(skb->protocol)))
5699 		return 0;
5700 
5701 	vlan_proto = skb->protocol;
5702 	err = __skb_vlan_pop(skb, &vlan_tci);
5703 	if (unlikely(err))
5704 		return err;
5705 
5706 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5707 	return 0;
5708 }
5709 EXPORT_SYMBOL(skb_vlan_pop);
5710 
5711 /* Push a vlan tag either into hwaccel or into payload (if hwaccel tag present).
5712  * Expects skb->data at mac header.
5713  */
5714 int skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci)
5715 {
5716 	if (skb_vlan_tag_present(skb)) {
5717 		int offset = skb->data - skb_mac_header(skb);
5718 		int err;
5719 
5720 		if (WARN_ONCE(offset,
5721 			      "skb_vlan_push got skb with skb->data not at mac header (offset %d)\n",
5722 			      offset)) {
5723 			return -EINVAL;
5724 		}
5725 
5726 		err = __vlan_insert_tag(skb, skb->vlan_proto,
5727 					skb_vlan_tag_get(skb));
5728 		if (err)
5729 			return err;
5730 
5731 		skb->protocol = skb->vlan_proto;
5732 		skb->mac_len += VLAN_HLEN;
5733 
5734 		skb_postpush_rcsum(skb, skb->data + (2 * ETH_ALEN), VLAN_HLEN);
5735 	}
5736 	__vlan_hwaccel_put_tag(skb, vlan_proto, vlan_tci);
5737 	return 0;
5738 }
5739 EXPORT_SYMBOL(skb_vlan_push);
5740 
5741 /**
5742  * skb_eth_pop() - Drop the Ethernet header at the head of a packet
5743  *
5744  * @skb: Socket buffer to modify
5745  *
5746  * Drop the Ethernet header of @skb.
5747  *
5748  * Expects that skb->data points to the mac header and that no VLAN tags are
5749  * present.
5750  *
5751  * Returns 0 on success, -errno otherwise.
5752  */
5753 int skb_eth_pop(struct sk_buff *skb)
5754 {
5755 	if (!pskb_may_pull(skb, ETH_HLEN) || skb_vlan_tagged(skb) ||
5756 	    skb_network_offset(skb) < ETH_HLEN)
5757 		return -EPROTO;
5758 
5759 	skb_pull_rcsum(skb, ETH_HLEN);
5760 	skb_reset_mac_header(skb);
5761 	skb_reset_mac_len(skb);
5762 
5763 	return 0;
5764 }
5765 EXPORT_SYMBOL(skb_eth_pop);
5766 
5767 /**
5768  * skb_eth_push() - Add a new Ethernet header at the head of a packet
5769  *
5770  * @skb: Socket buffer to modify
5771  * @dst: Destination MAC address of the new header
5772  * @src: Source MAC address of the new header
5773  *
5774  * Prepend @skb with a new Ethernet header.
5775  *
5776  * Expects that skb->data points to the mac header, which must be empty.
5777  *
5778  * Returns 0 on success, -errno otherwise.
5779  */
5780 int skb_eth_push(struct sk_buff *skb, const unsigned char *dst,
5781 		 const unsigned char *src)
5782 {
5783 	struct ethhdr *eth;
5784 	int err;
5785 
5786 	if (skb_network_offset(skb) || skb_vlan_tag_present(skb))
5787 		return -EPROTO;
5788 
5789 	err = skb_cow_head(skb, sizeof(*eth));
5790 	if (err < 0)
5791 		return err;
5792 
5793 	skb_push(skb, sizeof(*eth));
5794 	skb_reset_mac_header(skb);
5795 	skb_reset_mac_len(skb);
5796 
5797 	eth = eth_hdr(skb);
5798 	ether_addr_copy(eth->h_dest, dst);
5799 	ether_addr_copy(eth->h_source, src);
5800 	eth->h_proto = skb->protocol;
5801 
5802 	skb_postpush_rcsum(skb, eth, sizeof(*eth));
5803 
5804 	return 0;
5805 }
5806 EXPORT_SYMBOL(skb_eth_push);
5807 
5808 /* Update the ethertype of hdr and the skb csum value if required. */
5809 static void skb_mod_eth_type(struct sk_buff *skb, struct ethhdr *hdr,
5810 			     __be16 ethertype)
5811 {
5812 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
5813 		__be16 diff[] = { ~hdr->h_proto, ethertype };
5814 
5815 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5816 	}
5817 
5818 	hdr->h_proto = ethertype;
5819 }
5820 
5821 /**
5822  * skb_mpls_push() - push a new MPLS header after mac_len bytes from start of
5823  *                   the packet
5824  *
5825  * @skb: buffer
5826  * @mpls_lse: MPLS label stack entry to push
5827  * @mpls_proto: ethertype of the new MPLS header (expects 0x8847 or 0x8848)
5828  * @mac_len: length of the MAC header
5829  * @ethernet: flag to indicate if the resulting packet after skb_mpls_push is
5830  *            ethernet
5831  *
5832  * Expects skb->data at mac header.
5833  *
5834  * Returns 0 on success, -errno otherwise.
5835  */
5836 int skb_mpls_push(struct sk_buff *skb, __be32 mpls_lse, __be16 mpls_proto,
5837 		  int mac_len, bool ethernet)
5838 {
5839 	struct mpls_shim_hdr *lse;
5840 	int err;
5841 
5842 	if (unlikely(!eth_p_mpls(mpls_proto)))
5843 		return -EINVAL;
5844 
5845 	/* Networking stack does not allow simultaneous Tunnel and MPLS GSO. */
5846 	if (skb->encapsulation)
5847 		return -EINVAL;
5848 
5849 	err = skb_cow_head(skb, MPLS_HLEN);
5850 	if (unlikely(err))
5851 		return err;
5852 
5853 	if (!skb->inner_protocol) {
5854 		skb_set_inner_network_header(skb, skb_network_offset(skb));
5855 		skb_set_inner_protocol(skb, skb->protocol);
5856 	}
5857 
5858 	skb_push(skb, MPLS_HLEN);
5859 	memmove(skb_mac_header(skb) - MPLS_HLEN, skb_mac_header(skb),
5860 		mac_len);
5861 	skb_reset_mac_header(skb);
5862 	skb_set_network_header(skb, mac_len);
5863 	skb_reset_mac_len(skb);
5864 
5865 	lse = mpls_hdr(skb);
5866 	lse->label_stack_entry = mpls_lse;
5867 	skb_postpush_rcsum(skb, lse, MPLS_HLEN);
5868 
5869 	if (ethernet && mac_len >= ETH_HLEN)
5870 		skb_mod_eth_type(skb, eth_hdr(skb), mpls_proto);
5871 	skb->protocol = mpls_proto;
5872 
5873 	return 0;
5874 }
5875 EXPORT_SYMBOL_GPL(skb_mpls_push);
5876 
5877 /**
5878  * skb_mpls_pop() - pop the outermost MPLS header
5879  *
5880  * @skb: buffer
5881  * @next_proto: ethertype of header after popped MPLS header
5882  * @mac_len: length of the MAC header
5883  * @ethernet: flag to indicate if the packet is ethernet
5884  *
5885  * Expects skb->data at mac header.
5886  *
5887  * Returns 0 on success, -errno otherwise.
5888  */
5889 int skb_mpls_pop(struct sk_buff *skb, __be16 next_proto, int mac_len,
5890 		 bool ethernet)
5891 {
5892 	int err;
5893 
5894 	if (unlikely(!eth_p_mpls(skb->protocol)))
5895 		return 0;
5896 
5897 	err = skb_ensure_writable(skb, mac_len + MPLS_HLEN);
5898 	if (unlikely(err))
5899 		return err;
5900 
5901 	skb_postpull_rcsum(skb, mpls_hdr(skb), MPLS_HLEN);
5902 	memmove(skb_mac_header(skb) + MPLS_HLEN, skb_mac_header(skb),
5903 		mac_len);
5904 
5905 	__skb_pull(skb, MPLS_HLEN);
5906 	skb_reset_mac_header(skb);
5907 	skb_set_network_header(skb, mac_len);
5908 
5909 	if (ethernet && mac_len >= ETH_HLEN) {
5910 		struct ethhdr *hdr;
5911 
5912 		/* use mpls_hdr() to get ethertype to account for VLANs. */
5913 		hdr = (struct ethhdr *)((void *)mpls_hdr(skb) - ETH_HLEN);
5914 		skb_mod_eth_type(skb, hdr, next_proto);
5915 	}
5916 	skb->protocol = next_proto;
5917 
5918 	return 0;
5919 }
5920 EXPORT_SYMBOL_GPL(skb_mpls_pop);
5921 
5922 /**
5923  * skb_mpls_update_lse() - modify outermost MPLS header and update csum
5924  *
5925  * @skb: buffer
5926  * @mpls_lse: new MPLS label stack entry to update to
5927  *
5928  * Expects skb->data at mac header.
5929  *
5930  * Returns 0 on success, -errno otherwise.
5931  */
5932 int skb_mpls_update_lse(struct sk_buff *skb, __be32 mpls_lse)
5933 {
5934 	int err;
5935 
5936 	if (unlikely(!eth_p_mpls(skb->protocol)))
5937 		return -EINVAL;
5938 
5939 	err = skb_ensure_writable(skb, skb->mac_len + MPLS_HLEN);
5940 	if (unlikely(err))
5941 		return err;
5942 
5943 	if (skb->ip_summed == CHECKSUM_COMPLETE) {
5944 		__be32 diff[] = { ~mpls_hdr(skb)->label_stack_entry, mpls_lse };
5945 
5946 		skb->csum = csum_partial((char *)diff, sizeof(diff), skb->csum);
5947 	}
5948 
5949 	mpls_hdr(skb)->label_stack_entry = mpls_lse;
5950 
5951 	return 0;
5952 }
5953 EXPORT_SYMBOL_GPL(skb_mpls_update_lse);
5954 
5955 /**
5956  * skb_mpls_dec_ttl() - decrement the TTL of the outermost MPLS header
5957  *
5958  * @skb: buffer
5959  *
5960  * Expects skb->data at mac header.
5961  *
5962  * Returns 0 on success, -errno otherwise.
5963  */
5964 int skb_mpls_dec_ttl(struct sk_buff *skb)
5965 {
5966 	u32 lse;
5967 	u8 ttl;
5968 
5969 	if (unlikely(!eth_p_mpls(skb->protocol)))
5970 		return -EINVAL;
5971 
5972 	if (!pskb_may_pull(skb, skb_network_offset(skb) + MPLS_HLEN))
5973 		return -ENOMEM;
5974 
5975 	lse = be32_to_cpu(mpls_hdr(skb)->label_stack_entry);
5976 	ttl = (lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT;
5977 	if (!--ttl)
5978 		return -EINVAL;
5979 
5980 	lse &= ~MPLS_LS_TTL_MASK;
5981 	lse |= ttl << MPLS_LS_TTL_SHIFT;
5982 
5983 	return skb_mpls_update_lse(skb, cpu_to_be32(lse));
5984 }
5985 EXPORT_SYMBOL_GPL(skb_mpls_dec_ttl);
5986 
5987 /**
5988  * alloc_skb_with_frags - allocate skb with page frags
5989  *
5990  * @header_len: size of linear part
5991  * @data_len: needed length in frags
5992  * @max_page_order: max page order desired.
5993  * @errcode: pointer to error code if any
5994  * @gfp_mask: allocation mask
5995  *
5996  * This can be used to allocate a paged skb, given a maximal order for frags.
5997  */
5998 struct sk_buff *alloc_skb_with_frags(unsigned long header_len,
5999 				     unsigned long data_len,
6000 				     int max_page_order,
6001 				     int *errcode,
6002 				     gfp_t gfp_mask)
6003 {
6004 	int npages = (data_len + (PAGE_SIZE - 1)) >> PAGE_SHIFT;
6005 	unsigned long chunk;
6006 	struct sk_buff *skb;
6007 	struct page *page;
6008 	int i;
6009 
6010 	*errcode = -EMSGSIZE;
6011 	/* Note this test could be relaxed, if we succeed to allocate
6012 	 * high order pages...
6013 	 */
6014 	if (npages > MAX_SKB_FRAGS)
6015 		return NULL;
6016 
6017 	*errcode = -ENOBUFS;
6018 	skb = alloc_skb(header_len, gfp_mask);
6019 	if (!skb)
6020 		return NULL;
6021 
6022 	skb->truesize += npages << PAGE_SHIFT;
6023 
6024 	for (i = 0; npages > 0; i++) {
6025 		int order = max_page_order;
6026 
6027 		while (order) {
6028 			if (npages >= 1 << order) {
6029 				page = alloc_pages((gfp_mask & ~__GFP_DIRECT_RECLAIM) |
6030 						   __GFP_COMP |
6031 						   __GFP_NOWARN,
6032 						   order);
6033 				if (page)
6034 					goto fill_page;
6035 				/* Do not retry other high order allocations */
6036 				order = 1;
6037 				max_page_order = 0;
6038 			}
6039 			order--;
6040 		}
6041 		page = alloc_page(gfp_mask);
6042 		if (!page)
6043 			goto failure;
6044 fill_page:
6045 		chunk = min_t(unsigned long, data_len,
6046 			      PAGE_SIZE << order);
6047 		skb_fill_page_desc(skb, i, page, 0, chunk);
6048 		data_len -= chunk;
6049 		npages -= 1 << order;
6050 	}
6051 	return skb;
6052 
6053 failure:
6054 	kfree_skb(skb);
6055 	return NULL;
6056 }
6057 EXPORT_SYMBOL(alloc_skb_with_frags);
6058 
6059 /* carve out the first off bytes from skb when off < headlen */
6060 static int pskb_carve_inside_header(struct sk_buff *skb, const u32 off,
6061 				    const int headlen, gfp_t gfp_mask)
6062 {
6063 	int i;
6064 	int size = skb_end_offset(skb);
6065 	int new_hlen = headlen - off;
6066 	u8 *data;
6067 
6068 	size = SKB_DATA_ALIGN(size);
6069 
6070 	if (skb_pfmemalloc(skb))
6071 		gfp_mask |= __GFP_MEMALLOC;
6072 	data = kmalloc_reserve(size +
6073 			       SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6074 			       gfp_mask, NUMA_NO_NODE, NULL);
6075 	if (!data)
6076 		return -ENOMEM;
6077 
6078 	size = SKB_WITH_OVERHEAD(ksize(data));
6079 
6080 	/* Copy real data, and all frags */
6081 	skb_copy_from_linear_data_offset(skb, off, data, new_hlen);
6082 	skb->len -= off;
6083 
6084 	memcpy((struct skb_shared_info *)(data + size),
6085 	       skb_shinfo(skb),
6086 	       offsetof(struct skb_shared_info,
6087 			frags[skb_shinfo(skb)->nr_frags]));
6088 	if (skb_cloned(skb)) {
6089 		/* drop the old head gracefully */
6090 		if (skb_orphan_frags(skb, gfp_mask)) {
6091 			kfree(data);
6092 			return -ENOMEM;
6093 		}
6094 		for (i = 0; i < skb_shinfo(skb)->nr_frags; i++)
6095 			skb_frag_ref(skb, i);
6096 		if (skb_has_frag_list(skb))
6097 			skb_clone_fraglist(skb);
6098 		skb_release_data(skb);
6099 	} else {
6100 		/* we can reuse existing recount- all we did was
6101 		 * relocate values
6102 		 */
6103 		skb_free_head(skb);
6104 	}
6105 
6106 	skb->head = data;
6107 	skb->data = data;
6108 	skb->head_frag = 0;
6109 	skb_set_end_offset(skb, size);
6110 	skb_set_tail_pointer(skb, skb_headlen(skb));
6111 	skb_headers_offset_update(skb, 0);
6112 	skb->cloned = 0;
6113 	skb->hdr_len = 0;
6114 	skb->nohdr = 0;
6115 	atomic_set(&skb_shinfo(skb)->dataref, 1);
6116 
6117 	return 0;
6118 }
6119 
6120 static int pskb_carve(struct sk_buff *skb, const u32 off, gfp_t gfp);
6121 
6122 /* carve out the first eat bytes from skb's frag_list. May recurse into
6123  * pskb_carve()
6124  */
6125 static int pskb_carve_frag_list(struct sk_buff *skb,
6126 				struct skb_shared_info *shinfo, int eat,
6127 				gfp_t gfp_mask)
6128 {
6129 	struct sk_buff *list = shinfo->frag_list;
6130 	struct sk_buff *clone = NULL;
6131 	struct sk_buff *insp = NULL;
6132 
6133 	do {
6134 		if (!list) {
6135 			pr_err("Not enough bytes to eat. Want %d\n", eat);
6136 			return -EFAULT;
6137 		}
6138 		if (list->len <= eat) {
6139 			/* Eaten as whole. */
6140 			eat -= list->len;
6141 			list = list->next;
6142 			insp = list;
6143 		} else {
6144 			/* Eaten partially. */
6145 			if (skb_shared(list)) {
6146 				clone = skb_clone(list, gfp_mask);
6147 				if (!clone)
6148 					return -ENOMEM;
6149 				insp = list->next;
6150 				list = clone;
6151 			} else {
6152 				/* This may be pulled without problems. */
6153 				insp = list;
6154 			}
6155 			if (pskb_carve(list, eat, gfp_mask) < 0) {
6156 				kfree_skb(clone);
6157 				return -ENOMEM;
6158 			}
6159 			break;
6160 		}
6161 	} while (eat);
6162 
6163 	/* Free pulled out fragments. */
6164 	while ((list = shinfo->frag_list) != insp) {
6165 		shinfo->frag_list = list->next;
6166 		consume_skb(list);
6167 	}
6168 	/* And insert new clone at head. */
6169 	if (clone) {
6170 		clone->next = list;
6171 		shinfo->frag_list = clone;
6172 	}
6173 	return 0;
6174 }
6175 
6176 /* carve off first len bytes from skb. Split line (off) is in the
6177  * non-linear part of skb
6178  */
6179 static int pskb_carve_inside_nonlinear(struct sk_buff *skb, const u32 off,
6180 				       int pos, gfp_t gfp_mask)
6181 {
6182 	int i, k = 0;
6183 	int size = skb_end_offset(skb);
6184 	u8 *data;
6185 	const int nfrags = skb_shinfo(skb)->nr_frags;
6186 	struct skb_shared_info *shinfo;
6187 
6188 	size = SKB_DATA_ALIGN(size);
6189 
6190 	if (skb_pfmemalloc(skb))
6191 		gfp_mask |= __GFP_MEMALLOC;
6192 	data = kmalloc_reserve(size +
6193 			       SKB_DATA_ALIGN(sizeof(struct skb_shared_info)),
6194 			       gfp_mask, NUMA_NO_NODE, NULL);
6195 	if (!data)
6196 		return -ENOMEM;
6197 
6198 	size = SKB_WITH_OVERHEAD(ksize(data));
6199 
6200 	memcpy((struct skb_shared_info *)(data + size),
6201 	       skb_shinfo(skb), offsetof(struct skb_shared_info, frags[0]));
6202 	if (skb_orphan_frags(skb, gfp_mask)) {
6203 		kfree(data);
6204 		return -ENOMEM;
6205 	}
6206 	shinfo = (struct skb_shared_info *)(data + size);
6207 	for (i = 0; i < nfrags; i++) {
6208 		int fsize = skb_frag_size(&skb_shinfo(skb)->frags[i]);
6209 
6210 		if (pos + fsize > off) {
6211 			shinfo->frags[k] = skb_shinfo(skb)->frags[i];
6212 
6213 			if (pos < off) {
6214 				/* Split frag.
6215 				 * We have two variants in this case:
6216 				 * 1. Move all the frag to the second
6217 				 *    part, if it is possible. F.e.
6218 				 *    this approach is mandatory for TUX,
6219 				 *    where splitting is expensive.
6220 				 * 2. Split is accurately. We make this.
6221 				 */
6222 				skb_frag_off_add(&shinfo->frags[0], off - pos);
6223 				skb_frag_size_sub(&shinfo->frags[0], off - pos);
6224 			}
6225 			skb_frag_ref(skb, i);
6226 			k++;
6227 		}
6228 		pos += fsize;
6229 	}
6230 	shinfo->nr_frags = k;
6231 	if (skb_has_frag_list(skb))
6232 		skb_clone_fraglist(skb);
6233 
6234 	/* split line is in frag list */
6235 	if (k == 0 && pskb_carve_frag_list(skb, shinfo, off - pos, gfp_mask)) {
6236 		/* skb_frag_unref() is not needed here as shinfo->nr_frags = 0. */
6237 		if (skb_has_frag_list(skb))
6238 			kfree_skb_list(skb_shinfo(skb)->frag_list);
6239 		kfree(data);
6240 		return -ENOMEM;
6241 	}
6242 	skb_release_data(skb);
6243 
6244 	skb->head = data;
6245 	skb->head_frag = 0;
6246 	skb->data = data;
6247 	skb_set_end_offset(skb, size);
6248 	skb_reset_tail_pointer(skb);
6249 	skb_headers_offset_update(skb, 0);
6250 	skb->cloned   = 0;
6251 	skb->hdr_len  = 0;
6252 	skb->nohdr    = 0;
6253 	skb->len -= off;
6254 	skb->data_len = skb->len;
6255 	atomic_set(&skb_shinfo(skb)->dataref, 1);
6256 	return 0;
6257 }
6258 
6259 /* remove len bytes from the beginning of the skb */
6260 static int pskb_carve(struct sk_buff *skb, const u32 len, gfp_t gfp)
6261 {
6262 	int headlen = skb_headlen(skb);
6263 
6264 	if (len < headlen)
6265 		return pskb_carve_inside_header(skb, len, headlen, gfp);
6266 	else
6267 		return pskb_carve_inside_nonlinear(skb, len, headlen, gfp);
6268 }
6269 
6270 /* Extract to_copy bytes starting at off from skb, and return this in
6271  * a new skb
6272  */
6273 struct sk_buff *pskb_extract(struct sk_buff *skb, int off,
6274 			     int to_copy, gfp_t gfp)
6275 {
6276 	struct sk_buff  *clone = skb_clone(skb, gfp);
6277 
6278 	if (!clone)
6279 		return NULL;
6280 
6281 	if (pskb_carve(clone, off, gfp) < 0 ||
6282 	    pskb_trim(clone, to_copy)) {
6283 		kfree_skb(clone);
6284 		return NULL;
6285 	}
6286 	return clone;
6287 }
6288 EXPORT_SYMBOL(pskb_extract);
6289 
6290 /**
6291  * skb_condense - try to get rid of fragments/frag_list if possible
6292  * @skb: buffer
6293  *
6294  * Can be used to save memory before skb is added to a busy queue.
6295  * If packet has bytes in frags and enough tail room in skb->head,
6296  * pull all of them, so that we can free the frags right now and adjust
6297  * truesize.
6298  * Notes:
6299  *	We do not reallocate skb->head thus can not fail.
6300  *	Caller must re-evaluate skb->truesize if needed.
6301  */
6302 void skb_condense(struct sk_buff *skb)
6303 {
6304 	if (skb->data_len) {
6305 		if (skb->data_len > skb->end - skb->tail ||
6306 		    skb_cloned(skb))
6307 			return;
6308 
6309 		/* Nice, we can free page frag(s) right now */
6310 		__pskb_pull_tail(skb, skb->data_len);
6311 	}
6312 	/* At this point, skb->truesize might be over estimated,
6313 	 * because skb had a fragment, and fragments do not tell
6314 	 * their truesize.
6315 	 * When we pulled its content into skb->head, fragment
6316 	 * was freed, but __pskb_pull_tail() could not possibly
6317 	 * adjust skb->truesize, not knowing the frag truesize.
6318 	 */
6319 	skb->truesize = SKB_TRUESIZE(skb_end_offset(skb));
6320 }
6321 
6322 #ifdef CONFIG_SKB_EXTENSIONS
6323 static void *skb_ext_get_ptr(struct skb_ext *ext, enum skb_ext_id id)
6324 {
6325 	return (void *)ext + (ext->offset[id] * SKB_EXT_ALIGN_VALUE);
6326 }
6327 
6328 /**
6329  * __skb_ext_alloc - allocate a new skb extensions storage
6330  *
6331  * @flags: See kmalloc().
6332  *
6333  * Returns the newly allocated pointer. The pointer can later attached to a
6334  * skb via __skb_ext_set().
6335  * Note: caller must handle the skb_ext as an opaque data.
6336  */
6337 struct skb_ext *__skb_ext_alloc(gfp_t flags)
6338 {
6339 	struct skb_ext *new = kmem_cache_alloc(skbuff_ext_cache, flags);
6340 
6341 	if (new) {
6342 		memset(new->offset, 0, sizeof(new->offset));
6343 		refcount_set(&new->refcnt, 1);
6344 	}
6345 
6346 	return new;
6347 }
6348 
6349 static struct skb_ext *skb_ext_maybe_cow(struct skb_ext *old,
6350 					 unsigned int old_active)
6351 {
6352 	struct skb_ext *new;
6353 
6354 	if (refcount_read(&old->refcnt) == 1)
6355 		return old;
6356 
6357 	new = kmem_cache_alloc(skbuff_ext_cache, GFP_ATOMIC);
6358 	if (!new)
6359 		return NULL;
6360 
6361 	memcpy(new, old, old->chunks * SKB_EXT_ALIGN_VALUE);
6362 	refcount_set(&new->refcnt, 1);
6363 
6364 #ifdef CONFIG_XFRM
6365 	if (old_active & (1 << SKB_EXT_SEC_PATH)) {
6366 		struct sec_path *sp = skb_ext_get_ptr(old, SKB_EXT_SEC_PATH);
6367 		unsigned int i;
6368 
6369 		for (i = 0; i < sp->len; i++)
6370 			xfrm_state_hold(sp->xvec[i]);
6371 	}
6372 #endif
6373 	__skb_ext_put(old);
6374 	return new;
6375 }
6376 
6377 /**
6378  * __skb_ext_set - attach the specified extension storage to this skb
6379  * @skb: buffer
6380  * @id: extension id
6381  * @ext: extension storage previously allocated via __skb_ext_alloc()
6382  *
6383  * Existing extensions, if any, are cleared.
6384  *
6385  * Returns the pointer to the extension.
6386  */
6387 void *__skb_ext_set(struct sk_buff *skb, enum skb_ext_id id,
6388 		    struct skb_ext *ext)
6389 {
6390 	unsigned int newlen, newoff = SKB_EXT_CHUNKSIZEOF(*ext);
6391 
6392 	skb_ext_put(skb);
6393 	newlen = newoff + skb_ext_type_len[id];
6394 	ext->chunks = newlen;
6395 	ext->offset[id] = newoff;
6396 	skb->extensions = ext;
6397 	skb->active_extensions = 1 << id;
6398 	return skb_ext_get_ptr(ext, id);
6399 }
6400 
6401 /**
6402  * skb_ext_add - allocate space for given extension, COW if needed
6403  * @skb: buffer
6404  * @id: extension to allocate space for
6405  *
6406  * Allocates enough space for the given extension.
6407  * If the extension is already present, a pointer to that extension
6408  * is returned.
6409  *
6410  * If the skb was cloned, COW applies and the returned memory can be
6411  * modified without changing the extension space of clones buffers.
6412  *
6413  * Returns pointer to the extension or NULL on allocation failure.
6414  */
6415 void *skb_ext_add(struct sk_buff *skb, enum skb_ext_id id)
6416 {
6417 	struct skb_ext *new, *old = NULL;
6418 	unsigned int newlen, newoff;
6419 
6420 	if (skb->active_extensions) {
6421 		old = skb->extensions;
6422 
6423 		new = skb_ext_maybe_cow(old, skb->active_extensions);
6424 		if (!new)
6425 			return NULL;
6426 
6427 		if (__skb_ext_exist(new, id))
6428 			goto set_active;
6429 
6430 		newoff = new->chunks;
6431 	} else {
6432 		newoff = SKB_EXT_CHUNKSIZEOF(*new);
6433 
6434 		new = __skb_ext_alloc(GFP_ATOMIC);
6435 		if (!new)
6436 			return NULL;
6437 	}
6438 
6439 	newlen = newoff + skb_ext_type_len[id];
6440 	new->chunks = newlen;
6441 	new->offset[id] = newoff;
6442 set_active:
6443 	skb->slow_gro = 1;
6444 	skb->extensions = new;
6445 	skb->active_extensions |= 1 << id;
6446 	return skb_ext_get_ptr(new, id);
6447 }
6448 EXPORT_SYMBOL(skb_ext_add);
6449 
6450 #ifdef CONFIG_XFRM
6451 static void skb_ext_put_sp(struct sec_path *sp)
6452 {
6453 	unsigned int i;
6454 
6455 	for (i = 0; i < sp->len; i++)
6456 		xfrm_state_put(sp->xvec[i]);
6457 }
6458 #endif
6459 
6460 #ifdef CONFIG_MCTP_FLOWS
6461 static void skb_ext_put_mctp(struct mctp_flow *flow)
6462 {
6463 	if (flow->key)
6464 		mctp_key_unref(flow->key);
6465 }
6466 #endif
6467 
6468 void __skb_ext_del(struct sk_buff *skb, enum skb_ext_id id)
6469 {
6470 	struct skb_ext *ext = skb->extensions;
6471 
6472 	skb->active_extensions &= ~(1 << id);
6473 	if (skb->active_extensions == 0) {
6474 		skb->extensions = NULL;
6475 		__skb_ext_put(ext);
6476 #ifdef CONFIG_XFRM
6477 	} else if (id == SKB_EXT_SEC_PATH &&
6478 		   refcount_read(&ext->refcnt) == 1) {
6479 		struct sec_path *sp = skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH);
6480 
6481 		skb_ext_put_sp(sp);
6482 		sp->len = 0;
6483 #endif
6484 	}
6485 }
6486 EXPORT_SYMBOL(__skb_ext_del);
6487 
6488 void __skb_ext_put(struct skb_ext *ext)
6489 {
6490 	/* If this is last clone, nothing can increment
6491 	 * it after check passes.  Avoids one atomic op.
6492 	 */
6493 	if (refcount_read(&ext->refcnt) == 1)
6494 		goto free_now;
6495 
6496 	if (!refcount_dec_and_test(&ext->refcnt))
6497 		return;
6498 free_now:
6499 #ifdef CONFIG_XFRM
6500 	if (__skb_ext_exist(ext, SKB_EXT_SEC_PATH))
6501 		skb_ext_put_sp(skb_ext_get_ptr(ext, SKB_EXT_SEC_PATH));
6502 #endif
6503 #ifdef CONFIG_MCTP_FLOWS
6504 	if (__skb_ext_exist(ext, SKB_EXT_MCTP))
6505 		skb_ext_put_mctp(skb_ext_get_ptr(ext, SKB_EXT_MCTP));
6506 #endif
6507 
6508 	kmem_cache_free(skbuff_ext_cache, ext);
6509 }
6510 EXPORT_SYMBOL(__skb_ext_put);
6511 #endif /* CONFIG_SKB_EXTENSIONS */
6512 
6513 /**
6514  * skb_attempt_defer_free - queue skb for remote freeing
6515  * @skb: buffer
6516  *
6517  * Put @skb in a per-cpu list, using the cpu which
6518  * allocated the skb/pages to reduce false sharing
6519  * and memory zone spinlock contention.
6520  */
6521 void skb_attempt_defer_free(struct sk_buff *skb)
6522 {
6523 	int cpu = skb->alloc_cpu;
6524 	struct softnet_data *sd;
6525 	unsigned long flags;
6526 	unsigned int defer_max;
6527 	bool kick;
6528 
6529 	if (WARN_ON_ONCE(cpu >= nr_cpu_ids) ||
6530 	    !cpu_online(cpu) ||
6531 	    cpu == raw_smp_processor_id()) {
6532 nodefer:	__kfree_skb(skb);
6533 		return;
6534 	}
6535 
6536 	sd = &per_cpu(softnet_data, cpu);
6537 	defer_max = READ_ONCE(sysctl_skb_defer_max);
6538 	if (READ_ONCE(sd->defer_count) >= defer_max)
6539 		goto nodefer;
6540 
6541 	spin_lock_irqsave(&sd->defer_lock, flags);
6542 	/* Send an IPI every time queue reaches half capacity. */
6543 	kick = sd->defer_count == (defer_max >> 1);
6544 	/* Paired with the READ_ONCE() few lines above */
6545 	WRITE_ONCE(sd->defer_count, sd->defer_count + 1);
6546 
6547 	skb->next = sd->defer_list;
6548 	/* Paired with READ_ONCE() in skb_defer_free_flush() */
6549 	WRITE_ONCE(sd->defer_list, skb);
6550 	spin_unlock_irqrestore(&sd->defer_lock, flags);
6551 
6552 	/* Make sure to trigger NET_RX_SOFTIRQ on the remote CPU
6553 	 * if we are unlucky enough (this seems very unlikely).
6554 	 */
6555 	if (unlikely(kick) && !cmpxchg(&sd->defer_ipi_scheduled, 0, 1))
6556 		smp_call_function_single_async(cpu, &sd->defer_csd);
6557 }
6558