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