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