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