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