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