Loading...
1// SPDX-License-Identifier: GPL-2.0-only
2/* net/core/xdp.c
3 *
4 * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
5 */
6#include <linux/bpf.h>
7#include <linux/btf.h>
8#include <linux/btf_ids.h>
9#include <linux/filter.h>
10#include <linux/types.h>
11#include <linux/mm.h>
12#include <linux/netdevice.h>
13#include <linux/slab.h>
14#include <linux/idr.h>
15#include <linux/rhashtable.h>
16#include <linux/bug.h>
17#include <net/page_pool/helpers.h>
18
19#include <net/hotdata.h>
20#include <net/xdp.h>
21#include <net/xdp_priv.h> /* struct xdp_mem_allocator */
22#include <trace/events/xdp.h>
23#include <net/xdp_sock_drv.h>
24
25#define REG_STATE_NEW 0x0
26#define REG_STATE_REGISTERED 0x1
27#define REG_STATE_UNREGISTERED 0x2
28#define REG_STATE_UNUSED 0x3
29
30static DEFINE_IDA(mem_id_pool);
31static DEFINE_MUTEX(mem_id_lock);
32#define MEM_ID_MAX 0xFFFE
33#define MEM_ID_MIN 1
34static int mem_id_next = MEM_ID_MIN;
35
36static bool mem_id_init; /* false */
37static struct rhashtable *mem_id_ht;
38
39static u32 xdp_mem_id_hashfn(const void *data, u32 len, u32 seed)
40{
41 const u32 *k = data;
42 const u32 key = *k;
43
44 BUILD_BUG_ON(sizeof_field(struct xdp_mem_allocator, mem.id)
45 != sizeof(u32));
46
47 /* Use cyclic increasing ID as direct hash key */
48 return key;
49}
50
51static int xdp_mem_id_cmp(struct rhashtable_compare_arg *arg,
52 const void *ptr)
53{
54 const struct xdp_mem_allocator *xa = ptr;
55 u32 mem_id = *(u32 *)arg->key;
56
57 return xa->mem.id != mem_id;
58}
59
60static const struct rhashtable_params mem_id_rht_params = {
61 .nelem_hint = 64,
62 .head_offset = offsetof(struct xdp_mem_allocator, node),
63 .key_offset = offsetof(struct xdp_mem_allocator, mem.id),
64 .key_len = sizeof_field(struct xdp_mem_allocator, mem.id),
65 .max_size = MEM_ID_MAX,
66 .min_size = 8,
67 .automatic_shrinking = true,
68 .hashfn = xdp_mem_id_hashfn,
69 .obj_cmpfn = xdp_mem_id_cmp,
70};
71
72static void __xdp_mem_allocator_rcu_free(struct rcu_head *rcu)
73{
74 struct xdp_mem_allocator *xa;
75
76 xa = container_of(rcu, struct xdp_mem_allocator, rcu);
77
78 /* Allow this ID to be reused */
79 ida_free(&mem_id_pool, xa->mem.id);
80
81 kfree(xa);
82}
83
84static void mem_xa_remove(struct xdp_mem_allocator *xa)
85{
86 trace_mem_disconnect(xa);
87
88 if (!rhashtable_remove_fast(mem_id_ht, &xa->node, mem_id_rht_params))
89 call_rcu(&xa->rcu, __xdp_mem_allocator_rcu_free);
90}
91
92static void mem_allocator_disconnect(void *allocator)
93{
94 struct xdp_mem_allocator *xa;
95 struct rhashtable_iter iter;
96
97 mutex_lock(&mem_id_lock);
98
99 rhashtable_walk_enter(mem_id_ht, &iter);
100 do {
101 rhashtable_walk_start(&iter);
102
103 while ((xa = rhashtable_walk_next(&iter)) && !IS_ERR(xa)) {
104 if (xa->allocator == allocator)
105 mem_xa_remove(xa);
106 }
107
108 rhashtable_walk_stop(&iter);
109
110 } while (xa == ERR_PTR(-EAGAIN));
111 rhashtable_walk_exit(&iter);
112
113 mutex_unlock(&mem_id_lock);
114}
115
116void xdp_unreg_mem_model(struct xdp_mem_info *mem)
117{
118 struct xdp_mem_allocator *xa;
119 int type = mem->type;
120 int id = mem->id;
121
122 /* Reset mem info to defaults */
123 mem->id = 0;
124 mem->type = 0;
125
126 if (id == 0)
127 return;
128
129 if (type == MEM_TYPE_PAGE_POOL) {
130 xa = rhashtable_lookup_fast(mem_id_ht, &id, mem_id_rht_params);
131 page_pool_destroy(xa->page_pool);
132 }
133}
134EXPORT_SYMBOL_GPL(xdp_unreg_mem_model);
135
136void xdp_rxq_info_unreg_mem_model(struct xdp_rxq_info *xdp_rxq)
137{
138 if (xdp_rxq->reg_state != REG_STATE_REGISTERED) {
139 WARN(1, "Missing register, driver bug");
140 return;
141 }
142
143 xdp_unreg_mem_model(&xdp_rxq->mem);
144}
145EXPORT_SYMBOL_GPL(xdp_rxq_info_unreg_mem_model);
146
147void xdp_rxq_info_unreg(struct xdp_rxq_info *xdp_rxq)
148{
149 /* Simplify driver cleanup code paths, allow unreg "unused" */
150 if (xdp_rxq->reg_state == REG_STATE_UNUSED)
151 return;
152
153 xdp_rxq_info_unreg_mem_model(xdp_rxq);
154
155 xdp_rxq->reg_state = REG_STATE_UNREGISTERED;
156 xdp_rxq->dev = NULL;
157}
158EXPORT_SYMBOL_GPL(xdp_rxq_info_unreg);
159
160static void xdp_rxq_info_init(struct xdp_rxq_info *xdp_rxq)
161{
162 memset(xdp_rxq, 0, sizeof(*xdp_rxq));
163}
164
165/* Returns 0 on success, negative on failure */
166int __xdp_rxq_info_reg(struct xdp_rxq_info *xdp_rxq,
167 struct net_device *dev, u32 queue_index,
168 unsigned int napi_id, u32 frag_size)
169{
170 if (!dev) {
171 WARN(1, "Missing net_device from driver");
172 return -ENODEV;
173 }
174
175 if (xdp_rxq->reg_state == REG_STATE_UNUSED) {
176 WARN(1, "Driver promised not to register this");
177 return -EINVAL;
178 }
179
180 if (xdp_rxq->reg_state == REG_STATE_REGISTERED) {
181 WARN(1, "Missing unregister, handled but fix driver");
182 xdp_rxq_info_unreg(xdp_rxq);
183 }
184
185 /* State either UNREGISTERED or NEW */
186 xdp_rxq_info_init(xdp_rxq);
187 xdp_rxq->dev = dev;
188 xdp_rxq->queue_index = queue_index;
189 xdp_rxq->frag_size = frag_size;
190
191 xdp_rxq->reg_state = REG_STATE_REGISTERED;
192 return 0;
193}
194EXPORT_SYMBOL_GPL(__xdp_rxq_info_reg);
195
196void xdp_rxq_info_unused(struct xdp_rxq_info *xdp_rxq)
197{
198 xdp_rxq->reg_state = REG_STATE_UNUSED;
199}
200EXPORT_SYMBOL_GPL(xdp_rxq_info_unused);
201
202bool xdp_rxq_info_is_reg(struct xdp_rxq_info *xdp_rxq)
203{
204 return (xdp_rxq->reg_state == REG_STATE_REGISTERED);
205}
206EXPORT_SYMBOL_GPL(xdp_rxq_info_is_reg);
207
208static int __mem_id_init_hash_table(void)
209{
210 struct rhashtable *rht;
211 int ret;
212
213 if (unlikely(mem_id_init))
214 return 0;
215
216 rht = kzalloc(sizeof(*rht), GFP_KERNEL);
217 if (!rht)
218 return -ENOMEM;
219
220 ret = rhashtable_init(rht, &mem_id_rht_params);
221 if (ret < 0) {
222 kfree(rht);
223 return ret;
224 }
225 mem_id_ht = rht;
226 smp_mb(); /* mutex lock should provide enough pairing */
227 mem_id_init = true;
228
229 return 0;
230}
231
232/* Allocate a cyclic ID that maps to allocator pointer.
233 * See: https://www.kernel.org/doc/html/latest/core-api/idr.html
234 *
235 * Caller must lock mem_id_lock.
236 */
237static int __mem_id_cyclic_get(gfp_t gfp)
238{
239 int retries = 1;
240 int id;
241
242again:
243 id = ida_alloc_range(&mem_id_pool, mem_id_next, MEM_ID_MAX - 1, gfp);
244 if (id < 0) {
245 if (id == -ENOSPC) {
246 /* Cyclic allocator, reset next id */
247 if (retries--) {
248 mem_id_next = MEM_ID_MIN;
249 goto again;
250 }
251 }
252 return id; /* errno */
253 }
254 mem_id_next = id + 1;
255
256 return id;
257}
258
259static bool __is_supported_mem_type(enum xdp_mem_type type)
260{
261 if (type == MEM_TYPE_PAGE_POOL)
262 return is_page_pool_compiled_in();
263
264 if (type >= MEM_TYPE_MAX)
265 return false;
266
267 return true;
268}
269
270static struct xdp_mem_allocator *__xdp_reg_mem_model(struct xdp_mem_info *mem,
271 enum xdp_mem_type type,
272 void *allocator)
273{
274 struct xdp_mem_allocator *xdp_alloc;
275 gfp_t gfp = GFP_KERNEL;
276 int id, errno, ret;
277 void *ptr;
278
279 if (!__is_supported_mem_type(type))
280 return ERR_PTR(-EOPNOTSUPP);
281
282 mem->type = type;
283
284 if (!allocator) {
285 if (type == MEM_TYPE_PAGE_POOL)
286 return ERR_PTR(-EINVAL); /* Setup time check page_pool req */
287 return NULL;
288 }
289
290 /* Delay init of rhashtable to save memory if feature isn't used */
291 if (!mem_id_init) {
292 mutex_lock(&mem_id_lock);
293 ret = __mem_id_init_hash_table();
294 mutex_unlock(&mem_id_lock);
295 if (ret < 0)
296 return ERR_PTR(ret);
297 }
298
299 xdp_alloc = kzalloc(sizeof(*xdp_alloc), gfp);
300 if (!xdp_alloc)
301 return ERR_PTR(-ENOMEM);
302
303 mutex_lock(&mem_id_lock);
304 id = __mem_id_cyclic_get(gfp);
305 if (id < 0) {
306 errno = id;
307 goto err;
308 }
309 mem->id = id;
310 xdp_alloc->mem = *mem;
311 xdp_alloc->allocator = allocator;
312
313 /* Insert allocator into ID lookup table */
314 ptr = rhashtable_insert_slow(mem_id_ht, &id, &xdp_alloc->node);
315 if (IS_ERR(ptr)) {
316 ida_free(&mem_id_pool, mem->id);
317 mem->id = 0;
318 errno = PTR_ERR(ptr);
319 goto err;
320 }
321
322 if (type == MEM_TYPE_PAGE_POOL)
323 page_pool_use_xdp_mem(allocator, mem_allocator_disconnect, mem);
324
325 mutex_unlock(&mem_id_lock);
326
327 return xdp_alloc;
328err:
329 mutex_unlock(&mem_id_lock);
330 kfree(xdp_alloc);
331 return ERR_PTR(errno);
332}
333
334int xdp_reg_mem_model(struct xdp_mem_info *mem,
335 enum xdp_mem_type type, void *allocator)
336{
337 struct xdp_mem_allocator *xdp_alloc;
338
339 xdp_alloc = __xdp_reg_mem_model(mem, type, allocator);
340 if (IS_ERR(xdp_alloc))
341 return PTR_ERR(xdp_alloc);
342 return 0;
343}
344EXPORT_SYMBOL_GPL(xdp_reg_mem_model);
345
346int xdp_rxq_info_reg_mem_model(struct xdp_rxq_info *xdp_rxq,
347 enum xdp_mem_type type, void *allocator)
348{
349 struct xdp_mem_allocator *xdp_alloc;
350
351 if (xdp_rxq->reg_state != REG_STATE_REGISTERED) {
352 WARN(1, "Missing register, driver bug");
353 return -EFAULT;
354 }
355
356 xdp_alloc = __xdp_reg_mem_model(&xdp_rxq->mem, type, allocator);
357 if (IS_ERR(xdp_alloc))
358 return PTR_ERR(xdp_alloc);
359
360 if (trace_mem_connect_enabled() && xdp_alloc)
361 trace_mem_connect(xdp_alloc, xdp_rxq);
362 return 0;
363}
364
365EXPORT_SYMBOL_GPL(xdp_rxq_info_reg_mem_model);
366
367/* XDP RX runs under NAPI protection, and in different delivery error
368 * scenarios (e.g. queue full), it is possible to return the xdp_frame
369 * while still leveraging this protection. The @napi_direct boolean
370 * is used for those calls sites. Thus, allowing for faster recycling
371 * of xdp_frames/pages in those cases.
372 */
373void __xdp_return(void *data, struct xdp_mem_info *mem, bool napi_direct,
374 struct xdp_buff *xdp)
375{
376 struct page *page;
377
378 switch (mem->type) {
379 case MEM_TYPE_PAGE_POOL:
380 page = virt_to_head_page(data);
381 if (napi_direct && xdp_return_frame_no_direct())
382 napi_direct = false;
383 /* No need to check ((page->pp_magic & ~0x3UL) == PP_SIGNATURE)
384 * as mem->type knows this a page_pool page
385 */
386 page_pool_put_full_page(page->pp, page, napi_direct);
387 break;
388 case MEM_TYPE_PAGE_SHARED:
389 page_frag_free(data);
390 break;
391 case MEM_TYPE_PAGE_ORDER0:
392 page = virt_to_page(data); /* Assumes order0 page*/
393 put_page(page);
394 break;
395 case MEM_TYPE_XSK_BUFF_POOL:
396 /* NB! Only valid from an xdp_buff! */
397 xsk_buff_free(xdp);
398 break;
399 default:
400 /* Not possible, checked in xdp_rxq_info_reg_mem_model() */
401 WARN(1, "Incorrect XDP memory type (%d) usage", mem->type);
402 break;
403 }
404}
405
406void xdp_return_frame(struct xdp_frame *xdpf)
407{
408 struct skb_shared_info *sinfo;
409 int i;
410
411 if (likely(!xdp_frame_has_frags(xdpf)))
412 goto out;
413
414 sinfo = xdp_get_shared_info_from_frame(xdpf);
415 for (i = 0; i < sinfo->nr_frags; i++) {
416 struct page *page = skb_frag_page(&sinfo->frags[i]);
417
418 __xdp_return(page_address(page), &xdpf->mem, false, NULL);
419 }
420out:
421 __xdp_return(xdpf->data, &xdpf->mem, false, NULL);
422}
423EXPORT_SYMBOL_GPL(xdp_return_frame);
424
425void xdp_return_frame_rx_napi(struct xdp_frame *xdpf)
426{
427 struct skb_shared_info *sinfo;
428 int i;
429
430 if (likely(!xdp_frame_has_frags(xdpf)))
431 goto out;
432
433 sinfo = xdp_get_shared_info_from_frame(xdpf);
434 for (i = 0; i < sinfo->nr_frags; i++) {
435 struct page *page = skb_frag_page(&sinfo->frags[i]);
436
437 __xdp_return(page_address(page), &xdpf->mem, true, NULL);
438 }
439out:
440 __xdp_return(xdpf->data, &xdpf->mem, true, NULL);
441}
442EXPORT_SYMBOL_GPL(xdp_return_frame_rx_napi);
443
444/* XDP bulk APIs introduce a defer/flush mechanism to return
445 * pages belonging to the same xdp_mem_allocator object
446 * (identified via the mem.id field) in bulk to optimize
447 * I-cache and D-cache.
448 * The bulk queue size is set to 16 to be aligned to how
449 * XDP_REDIRECT bulking works. The bulk is flushed when
450 * it is full or when mem.id changes.
451 * xdp_frame_bulk is usually stored/allocated on the function
452 * call-stack to avoid locking penalties.
453 */
454void xdp_flush_frame_bulk(struct xdp_frame_bulk *bq)
455{
456 struct xdp_mem_allocator *xa = bq->xa;
457
458 if (unlikely(!xa || !bq->count))
459 return;
460
461 page_pool_put_page_bulk(xa->page_pool, bq->q, bq->count);
462 /* bq->xa is not cleared to save lookup, if mem.id same in next bulk */
463 bq->count = 0;
464}
465EXPORT_SYMBOL_GPL(xdp_flush_frame_bulk);
466
467/* Must be called with rcu_read_lock held */
468void xdp_return_frame_bulk(struct xdp_frame *xdpf,
469 struct xdp_frame_bulk *bq)
470{
471 struct xdp_mem_info *mem = &xdpf->mem;
472 struct xdp_mem_allocator *xa;
473
474 if (mem->type != MEM_TYPE_PAGE_POOL) {
475 xdp_return_frame(xdpf);
476 return;
477 }
478
479 xa = bq->xa;
480 if (unlikely(!xa)) {
481 xa = rhashtable_lookup(mem_id_ht, &mem->id, mem_id_rht_params);
482 bq->count = 0;
483 bq->xa = xa;
484 }
485
486 if (bq->count == XDP_BULK_QUEUE_SIZE)
487 xdp_flush_frame_bulk(bq);
488
489 if (unlikely(mem->id != xa->mem.id)) {
490 xdp_flush_frame_bulk(bq);
491 bq->xa = rhashtable_lookup(mem_id_ht, &mem->id, mem_id_rht_params);
492 }
493
494 if (unlikely(xdp_frame_has_frags(xdpf))) {
495 struct skb_shared_info *sinfo;
496 int i;
497
498 sinfo = xdp_get_shared_info_from_frame(xdpf);
499 for (i = 0; i < sinfo->nr_frags; i++) {
500 skb_frag_t *frag = &sinfo->frags[i];
501
502 bq->q[bq->count++] = skb_frag_address(frag);
503 if (bq->count == XDP_BULK_QUEUE_SIZE)
504 xdp_flush_frame_bulk(bq);
505 }
506 }
507 bq->q[bq->count++] = xdpf->data;
508}
509EXPORT_SYMBOL_GPL(xdp_return_frame_bulk);
510
511void xdp_return_buff(struct xdp_buff *xdp)
512{
513 struct skb_shared_info *sinfo;
514 int i;
515
516 if (likely(!xdp_buff_has_frags(xdp)))
517 goto out;
518
519 sinfo = xdp_get_shared_info_from_buff(xdp);
520 for (i = 0; i < sinfo->nr_frags; i++) {
521 struct page *page = skb_frag_page(&sinfo->frags[i]);
522
523 __xdp_return(page_address(page), &xdp->rxq->mem, true, xdp);
524 }
525out:
526 __xdp_return(xdp->data, &xdp->rxq->mem, true, xdp);
527}
528EXPORT_SYMBOL_GPL(xdp_return_buff);
529
530void xdp_attachment_setup(struct xdp_attachment_info *info,
531 struct netdev_bpf *bpf)
532{
533 if (info->prog)
534 bpf_prog_put(info->prog);
535 info->prog = bpf->prog;
536 info->flags = bpf->flags;
537}
538EXPORT_SYMBOL_GPL(xdp_attachment_setup);
539
540struct xdp_frame *xdp_convert_zc_to_xdp_frame(struct xdp_buff *xdp)
541{
542 unsigned int metasize, totsize;
543 void *addr, *data_to_copy;
544 struct xdp_frame *xdpf;
545 struct page *page;
546
547 /* Clone into a MEM_TYPE_PAGE_ORDER0 xdp_frame. */
548 metasize = xdp_data_meta_unsupported(xdp) ? 0 :
549 xdp->data - xdp->data_meta;
550 totsize = xdp->data_end - xdp->data + metasize;
551
552 if (sizeof(*xdpf) + totsize > PAGE_SIZE)
553 return NULL;
554
555 page = dev_alloc_page();
556 if (!page)
557 return NULL;
558
559 addr = page_to_virt(page);
560 xdpf = addr;
561 memset(xdpf, 0, sizeof(*xdpf));
562
563 addr += sizeof(*xdpf);
564 data_to_copy = metasize ? xdp->data_meta : xdp->data;
565 memcpy(addr, data_to_copy, totsize);
566
567 xdpf->data = addr + metasize;
568 xdpf->len = totsize - metasize;
569 xdpf->headroom = 0;
570 xdpf->metasize = metasize;
571 xdpf->frame_sz = PAGE_SIZE;
572 xdpf->mem.type = MEM_TYPE_PAGE_ORDER0;
573
574 xsk_buff_free(xdp);
575 return xdpf;
576}
577EXPORT_SYMBOL_GPL(xdp_convert_zc_to_xdp_frame);
578
579/* Used by XDP_WARN macro, to avoid inlining WARN() in fast-path */
580void xdp_warn(const char *msg, const char *func, const int line)
581{
582 WARN(1, "XDP_WARN: %s(line:%d): %s\n", func, line, msg);
583};
584EXPORT_SYMBOL_GPL(xdp_warn);
585
586int xdp_alloc_skb_bulk(void **skbs, int n_skb, gfp_t gfp)
587{
588 n_skb = kmem_cache_alloc_bulk(net_hotdata.skbuff_cache, gfp, n_skb, skbs);
589 if (unlikely(!n_skb))
590 return -ENOMEM;
591
592 return 0;
593}
594EXPORT_SYMBOL_GPL(xdp_alloc_skb_bulk);
595
596struct sk_buff *__xdp_build_skb_from_frame(struct xdp_frame *xdpf,
597 struct sk_buff *skb,
598 struct net_device *dev)
599{
600 struct skb_shared_info *sinfo = xdp_get_shared_info_from_frame(xdpf);
601 unsigned int headroom, frame_size;
602 void *hard_start;
603 u8 nr_frags;
604
605 /* xdp frags frame */
606 if (unlikely(xdp_frame_has_frags(xdpf)))
607 nr_frags = sinfo->nr_frags;
608
609 /* Part of headroom was reserved to xdpf */
610 headroom = sizeof(*xdpf) + xdpf->headroom;
611
612 /* Memory size backing xdp_frame data already have reserved
613 * room for build_skb to place skb_shared_info in tailroom.
614 */
615 frame_size = xdpf->frame_sz;
616
617 hard_start = xdpf->data - headroom;
618 skb = build_skb_around(skb, hard_start, frame_size);
619 if (unlikely(!skb))
620 return NULL;
621
622 skb_reserve(skb, headroom);
623 __skb_put(skb, xdpf->len);
624 if (xdpf->metasize)
625 skb_metadata_set(skb, xdpf->metasize);
626
627 if (unlikely(xdp_frame_has_frags(xdpf)))
628 xdp_update_skb_shared_info(skb, nr_frags,
629 sinfo->xdp_frags_size,
630 nr_frags * xdpf->frame_sz,
631 xdp_frame_is_frag_pfmemalloc(xdpf));
632
633 /* Essential SKB info: protocol and skb->dev */
634 skb->protocol = eth_type_trans(skb, dev);
635
636 /* Optional SKB info, currently missing:
637 * - HW checksum info (skb->ip_summed)
638 * - HW RX hash (skb_set_hash)
639 * - RX ring dev queue index (skb_record_rx_queue)
640 */
641
642 if (xdpf->mem.type == MEM_TYPE_PAGE_POOL)
643 skb_mark_for_recycle(skb);
644
645 /* Allow SKB to reuse area used by xdp_frame */
646 xdp_scrub_frame(xdpf);
647
648 return skb;
649}
650EXPORT_SYMBOL_GPL(__xdp_build_skb_from_frame);
651
652struct sk_buff *xdp_build_skb_from_frame(struct xdp_frame *xdpf,
653 struct net_device *dev)
654{
655 struct sk_buff *skb;
656
657 skb = kmem_cache_alloc(net_hotdata.skbuff_cache, GFP_ATOMIC);
658 if (unlikely(!skb))
659 return NULL;
660
661 memset(skb, 0, offsetof(struct sk_buff, tail));
662
663 return __xdp_build_skb_from_frame(xdpf, skb, dev);
664}
665EXPORT_SYMBOL_GPL(xdp_build_skb_from_frame);
666
667struct xdp_frame *xdpf_clone(struct xdp_frame *xdpf)
668{
669 unsigned int headroom, totalsize;
670 struct xdp_frame *nxdpf;
671 struct page *page;
672 void *addr;
673
674 headroom = xdpf->headroom + sizeof(*xdpf);
675 totalsize = headroom + xdpf->len;
676
677 if (unlikely(totalsize > PAGE_SIZE))
678 return NULL;
679 page = dev_alloc_page();
680 if (!page)
681 return NULL;
682 addr = page_to_virt(page);
683
684 memcpy(addr, xdpf, totalsize);
685
686 nxdpf = addr;
687 nxdpf->data = addr + headroom;
688 nxdpf->frame_sz = PAGE_SIZE;
689 nxdpf->mem.type = MEM_TYPE_PAGE_ORDER0;
690 nxdpf->mem.id = 0;
691
692 return nxdpf;
693}
694
695__bpf_kfunc_start_defs();
696
697/**
698 * bpf_xdp_metadata_rx_timestamp - Read XDP frame RX timestamp.
699 * @ctx: XDP context pointer.
700 * @timestamp: Return value pointer.
701 *
702 * Return:
703 * * Returns 0 on success or ``-errno`` on error.
704 * * ``-EOPNOTSUPP`` : means device driver does not implement kfunc
705 * * ``-ENODATA`` : means no RX-timestamp available for this frame
706 */
707__bpf_kfunc int bpf_xdp_metadata_rx_timestamp(const struct xdp_md *ctx, u64 *timestamp)
708{
709 return -EOPNOTSUPP;
710}
711
712/**
713 * bpf_xdp_metadata_rx_hash - Read XDP frame RX hash.
714 * @ctx: XDP context pointer.
715 * @hash: Return value pointer.
716 * @rss_type: Return value pointer for RSS type.
717 *
718 * The RSS hash type (@rss_type) specifies what portion of packet headers NIC
719 * hardware used when calculating RSS hash value. The RSS type can be decoded
720 * via &enum xdp_rss_hash_type either matching on individual L3/L4 bits
721 * ``XDP_RSS_L*`` or by combined traditional *RSS Hashing Types*
722 * ``XDP_RSS_TYPE_L*``.
723 *
724 * Return:
725 * * Returns 0 on success or ``-errno`` on error.
726 * * ``-EOPNOTSUPP`` : means device driver doesn't implement kfunc
727 * * ``-ENODATA`` : means no RX-hash available for this frame
728 */
729__bpf_kfunc int bpf_xdp_metadata_rx_hash(const struct xdp_md *ctx, u32 *hash,
730 enum xdp_rss_hash_type *rss_type)
731{
732 return -EOPNOTSUPP;
733}
734
735/**
736 * bpf_xdp_metadata_rx_vlan_tag - Get XDP packet outermost VLAN tag
737 * @ctx: XDP context pointer.
738 * @vlan_proto: Destination pointer for VLAN Tag protocol identifier (TPID).
739 * @vlan_tci: Destination pointer for VLAN TCI (VID + DEI + PCP)
740 *
741 * In case of success, ``vlan_proto`` contains *Tag protocol identifier (TPID)*,
742 * usually ``ETH_P_8021Q`` or ``ETH_P_8021AD``, but some networks can use
743 * custom TPIDs. ``vlan_proto`` is stored in **network byte order (BE)**
744 * and should be used as follows:
745 * ``if (vlan_proto == bpf_htons(ETH_P_8021Q)) do_something();``
746 *
747 * ``vlan_tci`` contains the remaining 16 bits of a VLAN tag.
748 * Driver is expected to provide those in **host byte order (usually LE)**,
749 * so the bpf program should not perform byte conversion.
750 * According to 802.1Q standard, *VLAN TCI (Tag control information)*
751 * is a bit field that contains:
752 * *VLAN identifier (VID)* that can be read with ``vlan_tci & 0xfff``,
753 * *Drop eligible indicator (DEI)* - 1 bit,
754 * *Priority code point (PCP)* - 3 bits.
755 * For detailed meaning of DEI and PCP, please refer to other sources.
756 *
757 * Return:
758 * * Returns 0 on success or ``-errno`` on error.
759 * * ``-EOPNOTSUPP`` : device driver doesn't implement kfunc
760 * * ``-ENODATA`` : VLAN tag was not stripped or is not available
761 */
762__bpf_kfunc int bpf_xdp_metadata_rx_vlan_tag(const struct xdp_md *ctx,
763 __be16 *vlan_proto, u16 *vlan_tci)
764{
765 return -EOPNOTSUPP;
766}
767
768__bpf_kfunc_end_defs();
769
770BTF_KFUNCS_START(xdp_metadata_kfunc_ids)
771#define XDP_METADATA_KFUNC(_, __, name, ___) BTF_ID_FLAGS(func, name, KF_TRUSTED_ARGS)
772XDP_METADATA_KFUNC_xxx
773#undef XDP_METADATA_KFUNC
774BTF_KFUNCS_END(xdp_metadata_kfunc_ids)
775
776static const struct btf_kfunc_id_set xdp_metadata_kfunc_set = {
777 .owner = THIS_MODULE,
778 .set = &xdp_metadata_kfunc_ids,
779};
780
781BTF_ID_LIST(xdp_metadata_kfunc_ids_unsorted)
782#define XDP_METADATA_KFUNC(name, _, str, __) BTF_ID(func, str)
783XDP_METADATA_KFUNC_xxx
784#undef XDP_METADATA_KFUNC
785
786u32 bpf_xdp_metadata_kfunc_id(int id)
787{
788 /* xdp_metadata_kfunc_ids is sorted and can't be used */
789 return xdp_metadata_kfunc_ids_unsorted[id];
790}
791
792bool bpf_dev_bound_kfunc_id(u32 btf_id)
793{
794 return btf_id_set8_contains(&xdp_metadata_kfunc_ids, btf_id);
795}
796
797static int __init xdp_metadata_init(void)
798{
799 return register_btf_kfunc_id_set(BPF_PROG_TYPE_XDP, &xdp_metadata_kfunc_set);
800}
801late_initcall(xdp_metadata_init);
802
803void xdp_set_features_flag(struct net_device *dev, xdp_features_t val)
804{
805 val &= NETDEV_XDP_ACT_MASK;
806 if (dev->xdp_features == val)
807 return;
808
809 dev->xdp_features = val;
810
811 if (dev->reg_state == NETREG_REGISTERED)
812 call_netdevice_notifiers(NETDEV_XDP_FEAT_CHANGE, dev);
813}
814EXPORT_SYMBOL_GPL(xdp_set_features_flag);
815
816void xdp_features_set_redirect_target(struct net_device *dev, bool support_sg)
817{
818 xdp_features_t val = (dev->xdp_features | NETDEV_XDP_ACT_NDO_XMIT);
819
820 if (support_sg)
821 val |= NETDEV_XDP_ACT_NDO_XMIT_SG;
822 xdp_set_features_flag(dev, val);
823}
824EXPORT_SYMBOL_GPL(xdp_features_set_redirect_target);
825
826void xdp_features_clear_redirect_target(struct net_device *dev)
827{
828 xdp_features_t val = dev->xdp_features;
829
830 val &= ~(NETDEV_XDP_ACT_NDO_XMIT | NETDEV_XDP_ACT_NDO_XMIT_SG);
831 xdp_set_features_flag(dev, val);
832}
833EXPORT_SYMBOL_GPL(xdp_features_clear_redirect_target);
1// SPDX-License-Identifier: GPL-2.0-only
2/* net/core/xdp.c
3 *
4 * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
5 */
6#include <linux/bpf.h>
7#include <linux/filter.h>
8#include <linux/types.h>
9#include <linux/mm.h>
10#include <linux/netdevice.h>
11#include <linux/slab.h>
12#include <linux/idr.h>
13#include <linux/rhashtable.h>
14#include <linux/bug.h>
15#include <net/page_pool.h>
16
17#include <net/xdp.h>
18#include <net/xdp_priv.h> /* struct xdp_mem_allocator */
19#include <trace/events/xdp.h>
20#include <net/xdp_sock_drv.h>
21
22#define REG_STATE_NEW 0x0
23#define REG_STATE_REGISTERED 0x1
24#define REG_STATE_UNREGISTERED 0x2
25#define REG_STATE_UNUSED 0x3
26
27static DEFINE_IDA(mem_id_pool);
28static DEFINE_MUTEX(mem_id_lock);
29#define MEM_ID_MAX 0xFFFE
30#define MEM_ID_MIN 1
31static int mem_id_next = MEM_ID_MIN;
32
33static bool mem_id_init; /* false */
34static struct rhashtable *mem_id_ht;
35
36static u32 xdp_mem_id_hashfn(const void *data, u32 len, u32 seed)
37{
38 const u32 *k = data;
39 const u32 key = *k;
40
41 BUILD_BUG_ON(sizeof_field(struct xdp_mem_allocator, mem.id)
42 != sizeof(u32));
43
44 /* Use cyclic increasing ID as direct hash key */
45 return key;
46}
47
48static int xdp_mem_id_cmp(struct rhashtable_compare_arg *arg,
49 const void *ptr)
50{
51 const struct xdp_mem_allocator *xa = ptr;
52 u32 mem_id = *(u32 *)arg->key;
53
54 return xa->mem.id != mem_id;
55}
56
57static const struct rhashtable_params mem_id_rht_params = {
58 .nelem_hint = 64,
59 .head_offset = offsetof(struct xdp_mem_allocator, node),
60 .key_offset = offsetof(struct xdp_mem_allocator, mem.id),
61 .key_len = sizeof_field(struct xdp_mem_allocator, mem.id),
62 .max_size = MEM_ID_MAX,
63 .min_size = 8,
64 .automatic_shrinking = true,
65 .hashfn = xdp_mem_id_hashfn,
66 .obj_cmpfn = xdp_mem_id_cmp,
67};
68
69static void __xdp_mem_allocator_rcu_free(struct rcu_head *rcu)
70{
71 struct xdp_mem_allocator *xa;
72
73 xa = container_of(rcu, struct xdp_mem_allocator, rcu);
74
75 /* Allow this ID to be reused */
76 ida_simple_remove(&mem_id_pool, xa->mem.id);
77
78 kfree(xa);
79}
80
81static void mem_xa_remove(struct xdp_mem_allocator *xa)
82{
83 trace_mem_disconnect(xa);
84
85 if (!rhashtable_remove_fast(mem_id_ht, &xa->node, mem_id_rht_params))
86 call_rcu(&xa->rcu, __xdp_mem_allocator_rcu_free);
87}
88
89static void mem_allocator_disconnect(void *allocator)
90{
91 struct xdp_mem_allocator *xa;
92 struct rhashtable_iter iter;
93
94 mutex_lock(&mem_id_lock);
95
96 rhashtable_walk_enter(mem_id_ht, &iter);
97 do {
98 rhashtable_walk_start(&iter);
99
100 while ((xa = rhashtable_walk_next(&iter)) && !IS_ERR(xa)) {
101 if (xa->allocator == allocator)
102 mem_xa_remove(xa);
103 }
104
105 rhashtable_walk_stop(&iter);
106
107 } while (xa == ERR_PTR(-EAGAIN));
108 rhashtable_walk_exit(&iter);
109
110 mutex_unlock(&mem_id_lock);
111}
112
113void xdp_rxq_info_unreg_mem_model(struct xdp_rxq_info *xdp_rxq)
114{
115 struct xdp_mem_allocator *xa;
116 int id = xdp_rxq->mem.id;
117
118 if (xdp_rxq->reg_state != REG_STATE_REGISTERED) {
119 WARN(1, "Missing register, driver bug");
120 return;
121 }
122
123 if (id == 0)
124 return;
125
126 if (xdp_rxq->mem.type == MEM_TYPE_PAGE_POOL) {
127 rcu_read_lock();
128 xa = rhashtable_lookup(mem_id_ht, &id, mem_id_rht_params);
129 page_pool_destroy(xa->page_pool);
130 rcu_read_unlock();
131 }
132}
133EXPORT_SYMBOL_GPL(xdp_rxq_info_unreg_mem_model);
134
135void xdp_rxq_info_unreg(struct xdp_rxq_info *xdp_rxq)
136{
137 /* Simplify driver cleanup code paths, allow unreg "unused" */
138 if (xdp_rxq->reg_state == REG_STATE_UNUSED)
139 return;
140
141 WARN(!(xdp_rxq->reg_state == REG_STATE_REGISTERED), "Driver BUG");
142
143 xdp_rxq_info_unreg_mem_model(xdp_rxq);
144
145 xdp_rxq->reg_state = REG_STATE_UNREGISTERED;
146 xdp_rxq->dev = NULL;
147
148 /* Reset mem info to defaults */
149 xdp_rxq->mem.id = 0;
150 xdp_rxq->mem.type = 0;
151}
152EXPORT_SYMBOL_GPL(xdp_rxq_info_unreg);
153
154static void xdp_rxq_info_init(struct xdp_rxq_info *xdp_rxq)
155{
156 memset(xdp_rxq, 0, sizeof(*xdp_rxq));
157}
158
159/* Returns 0 on success, negative on failure */
160int xdp_rxq_info_reg(struct xdp_rxq_info *xdp_rxq,
161 struct net_device *dev, u32 queue_index)
162{
163 if (xdp_rxq->reg_state == REG_STATE_UNUSED) {
164 WARN(1, "Driver promised not to register this");
165 return -EINVAL;
166 }
167
168 if (xdp_rxq->reg_state == REG_STATE_REGISTERED) {
169 WARN(1, "Missing unregister, handled but fix driver");
170 xdp_rxq_info_unreg(xdp_rxq);
171 }
172
173 if (!dev) {
174 WARN(1, "Missing net_device from driver");
175 return -ENODEV;
176 }
177
178 /* State either UNREGISTERED or NEW */
179 xdp_rxq_info_init(xdp_rxq);
180 xdp_rxq->dev = dev;
181 xdp_rxq->queue_index = queue_index;
182
183 xdp_rxq->reg_state = REG_STATE_REGISTERED;
184 return 0;
185}
186EXPORT_SYMBOL_GPL(xdp_rxq_info_reg);
187
188void xdp_rxq_info_unused(struct xdp_rxq_info *xdp_rxq)
189{
190 xdp_rxq->reg_state = REG_STATE_UNUSED;
191}
192EXPORT_SYMBOL_GPL(xdp_rxq_info_unused);
193
194bool xdp_rxq_info_is_reg(struct xdp_rxq_info *xdp_rxq)
195{
196 return (xdp_rxq->reg_state == REG_STATE_REGISTERED);
197}
198EXPORT_SYMBOL_GPL(xdp_rxq_info_is_reg);
199
200static int __mem_id_init_hash_table(void)
201{
202 struct rhashtable *rht;
203 int ret;
204
205 if (unlikely(mem_id_init))
206 return 0;
207
208 rht = kzalloc(sizeof(*rht), GFP_KERNEL);
209 if (!rht)
210 return -ENOMEM;
211
212 ret = rhashtable_init(rht, &mem_id_rht_params);
213 if (ret < 0) {
214 kfree(rht);
215 return ret;
216 }
217 mem_id_ht = rht;
218 smp_mb(); /* mutex lock should provide enough pairing */
219 mem_id_init = true;
220
221 return 0;
222}
223
224/* Allocate a cyclic ID that maps to allocator pointer.
225 * See: https://www.kernel.org/doc/html/latest/core-api/idr.html
226 *
227 * Caller must lock mem_id_lock.
228 */
229static int __mem_id_cyclic_get(gfp_t gfp)
230{
231 int retries = 1;
232 int id;
233
234again:
235 id = ida_simple_get(&mem_id_pool, mem_id_next, MEM_ID_MAX, gfp);
236 if (id < 0) {
237 if (id == -ENOSPC) {
238 /* Cyclic allocator, reset next id */
239 if (retries--) {
240 mem_id_next = MEM_ID_MIN;
241 goto again;
242 }
243 }
244 return id; /* errno */
245 }
246 mem_id_next = id + 1;
247
248 return id;
249}
250
251static bool __is_supported_mem_type(enum xdp_mem_type type)
252{
253 if (type == MEM_TYPE_PAGE_POOL)
254 return is_page_pool_compiled_in();
255
256 if (type >= MEM_TYPE_MAX)
257 return false;
258
259 return true;
260}
261
262int xdp_rxq_info_reg_mem_model(struct xdp_rxq_info *xdp_rxq,
263 enum xdp_mem_type type, void *allocator)
264{
265 struct xdp_mem_allocator *xdp_alloc;
266 gfp_t gfp = GFP_KERNEL;
267 int id, errno, ret;
268 void *ptr;
269
270 if (xdp_rxq->reg_state != REG_STATE_REGISTERED) {
271 WARN(1, "Missing register, driver bug");
272 return -EFAULT;
273 }
274
275 if (!__is_supported_mem_type(type))
276 return -EOPNOTSUPP;
277
278 xdp_rxq->mem.type = type;
279
280 if (!allocator) {
281 if (type == MEM_TYPE_PAGE_POOL)
282 return -EINVAL; /* Setup time check page_pool req */
283 return 0;
284 }
285
286 /* Delay init of rhashtable to save memory if feature isn't used */
287 if (!mem_id_init) {
288 mutex_lock(&mem_id_lock);
289 ret = __mem_id_init_hash_table();
290 mutex_unlock(&mem_id_lock);
291 if (ret < 0) {
292 WARN_ON(1);
293 return ret;
294 }
295 }
296
297 xdp_alloc = kzalloc(sizeof(*xdp_alloc), gfp);
298 if (!xdp_alloc)
299 return -ENOMEM;
300
301 mutex_lock(&mem_id_lock);
302 id = __mem_id_cyclic_get(gfp);
303 if (id < 0) {
304 errno = id;
305 goto err;
306 }
307 xdp_rxq->mem.id = id;
308 xdp_alloc->mem = xdp_rxq->mem;
309 xdp_alloc->allocator = allocator;
310
311 /* Insert allocator into ID lookup table */
312 ptr = rhashtable_insert_slow(mem_id_ht, &id, &xdp_alloc->node);
313 if (IS_ERR(ptr)) {
314 ida_simple_remove(&mem_id_pool, xdp_rxq->mem.id);
315 xdp_rxq->mem.id = 0;
316 errno = PTR_ERR(ptr);
317 goto err;
318 }
319
320 if (type == MEM_TYPE_PAGE_POOL)
321 page_pool_use_xdp_mem(allocator, mem_allocator_disconnect);
322
323 mutex_unlock(&mem_id_lock);
324
325 trace_mem_connect(xdp_alloc, xdp_rxq);
326 return 0;
327err:
328 mutex_unlock(&mem_id_lock);
329 kfree(xdp_alloc);
330 return errno;
331}
332EXPORT_SYMBOL_GPL(xdp_rxq_info_reg_mem_model);
333
334/* XDP RX runs under NAPI protection, and in different delivery error
335 * scenarios (e.g. queue full), it is possible to return the xdp_frame
336 * while still leveraging this protection. The @napi_direct boolean
337 * is used for those calls sites. Thus, allowing for faster recycling
338 * of xdp_frames/pages in those cases. This path is never used by the
339 * MEM_TYPE_XSK_BUFF_POOL memory type, so it's explicitly not part of
340 * the switch-statement.
341 */
342static void __xdp_return(void *data, struct xdp_mem_info *mem, bool napi_direct)
343{
344 struct xdp_mem_allocator *xa;
345 struct page *page;
346
347 switch (mem->type) {
348 case MEM_TYPE_PAGE_POOL:
349 rcu_read_lock();
350 /* mem->id is valid, checked in xdp_rxq_info_reg_mem_model() */
351 xa = rhashtable_lookup(mem_id_ht, &mem->id, mem_id_rht_params);
352 page = virt_to_head_page(data);
353 napi_direct &= !xdp_return_frame_no_direct();
354 page_pool_put_full_page(xa->page_pool, page, napi_direct);
355 rcu_read_unlock();
356 break;
357 case MEM_TYPE_PAGE_SHARED:
358 page_frag_free(data);
359 break;
360 case MEM_TYPE_PAGE_ORDER0:
361 page = virt_to_page(data); /* Assumes order0 page*/
362 put_page(page);
363 break;
364 default:
365 /* Not possible, checked in xdp_rxq_info_reg_mem_model() */
366 WARN(1, "Incorrect XDP memory type (%d) usage", mem->type);
367 break;
368 }
369}
370
371void xdp_return_frame(struct xdp_frame *xdpf)
372{
373 __xdp_return(xdpf->data, &xdpf->mem, false);
374}
375EXPORT_SYMBOL_GPL(xdp_return_frame);
376
377void xdp_return_frame_rx_napi(struct xdp_frame *xdpf)
378{
379 __xdp_return(xdpf->data, &xdpf->mem, true);
380}
381EXPORT_SYMBOL_GPL(xdp_return_frame_rx_napi);
382
383void xdp_return_buff(struct xdp_buff *xdp)
384{
385 __xdp_return(xdp->data, &xdp->rxq->mem, true);
386}
387
388/* Only called for MEM_TYPE_PAGE_POOL see xdp.h */
389void __xdp_release_frame(void *data, struct xdp_mem_info *mem)
390{
391 struct xdp_mem_allocator *xa;
392 struct page *page;
393
394 rcu_read_lock();
395 xa = rhashtable_lookup(mem_id_ht, &mem->id, mem_id_rht_params);
396 page = virt_to_head_page(data);
397 if (xa)
398 page_pool_release_page(xa->page_pool, page);
399 rcu_read_unlock();
400}
401EXPORT_SYMBOL_GPL(__xdp_release_frame);
402
403bool xdp_attachment_flags_ok(struct xdp_attachment_info *info,
404 struct netdev_bpf *bpf)
405{
406 if (info->prog && (bpf->flags ^ info->flags) & XDP_FLAGS_MODES) {
407 NL_SET_ERR_MSG(bpf->extack,
408 "program loaded with different flags");
409 return false;
410 }
411 return true;
412}
413EXPORT_SYMBOL_GPL(xdp_attachment_flags_ok);
414
415void xdp_attachment_setup(struct xdp_attachment_info *info,
416 struct netdev_bpf *bpf)
417{
418 if (info->prog)
419 bpf_prog_put(info->prog);
420 info->prog = bpf->prog;
421 info->flags = bpf->flags;
422}
423EXPORT_SYMBOL_GPL(xdp_attachment_setup);
424
425struct xdp_frame *xdp_convert_zc_to_xdp_frame(struct xdp_buff *xdp)
426{
427 unsigned int metasize, totsize;
428 void *addr, *data_to_copy;
429 struct xdp_frame *xdpf;
430 struct page *page;
431
432 /* Clone into a MEM_TYPE_PAGE_ORDER0 xdp_frame. */
433 metasize = xdp_data_meta_unsupported(xdp) ? 0 :
434 xdp->data - xdp->data_meta;
435 totsize = xdp->data_end - xdp->data + metasize;
436
437 if (sizeof(*xdpf) + totsize > PAGE_SIZE)
438 return NULL;
439
440 page = dev_alloc_page();
441 if (!page)
442 return NULL;
443
444 addr = page_to_virt(page);
445 xdpf = addr;
446 memset(xdpf, 0, sizeof(*xdpf));
447
448 addr += sizeof(*xdpf);
449 data_to_copy = metasize ? xdp->data_meta : xdp->data;
450 memcpy(addr, data_to_copy, totsize);
451
452 xdpf->data = addr + metasize;
453 xdpf->len = totsize - metasize;
454 xdpf->headroom = 0;
455 xdpf->metasize = metasize;
456 xdpf->frame_sz = PAGE_SIZE;
457 xdpf->mem.type = MEM_TYPE_PAGE_ORDER0;
458
459 xsk_buff_free(xdp);
460 return xdpf;
461}
462EXPORT_SYMBOL_GPL(xdp_convert_zc_to_xdp_frame);
463
464/* Used by XDP_WARN macro, to avoid inlining WARN() in fast-path */
465void xdp_warn(const char *msg, const char *func, const int line)
466{
467 WARN(1, "XDP_WARN: %s(line:%d): %s\n", func, line, msg);
468};
469EXPORT_SYMBOL_GPL(xdp_warn);