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