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