1 // SPDX-License-Identifier: GPL-2.0-only
3 #include <linux/pagemap.h>
4 #include <linux/xarray.h>
5 #include <linux/slab.h>
6 #include <linux/swap.h>
7 #include <linux/swapops.h>
10 static DEFINE_XARRAY(mte_pages
);
12 void *mte_allocate_tag_storage(void)
14 /* tags granule is 16 bytes, 2 tags stored per byte */
15 return kmalloc(PAGE_SIZE
/ 16 / 2, GFP_KERNEL
);
18 void mte_free_tag_storage(char *storage
)
23 int mte_save_tags(struct page
*page
)
25 void *tag_storage
, *ret
;
27 if (!test_bit(PG_mte_tagged
, &page
->flags
))
30 tag_storage
= mte_allocate_tag_storage();
34 mte_save_page_tags(page_address(page
), tag_storage
);
36 /* page_private contains the swap entry.val set in do_swap_page */
37 ret
= xa_store(&mte_pages
, page_private(page
), tag_storage
, GFP_KERNEL
);
38 if (WARN(xa_is_err(ret
), "Failed to store MTE tags")) {
39 mte_free_tag_storage(tag_storage
);
42 /* Entry is being replaced, free the old entry */
43 mte_free_tag_storage(ret
);
49 bool mte_restore_tags(swp_entry_t entry
, struct page
*page
)
51 void *tags
= xa_load(&mte_pages
, entry
.val
);
56 page_kasan_tag_reset(page
);
58 * We need smp_wmb() in between setting the flags and clearing the
59 * tags because if another thread reads page->flags and builds a
60 * tagged address out of it, there is an actual dependency to the
61 * memory access, but on the current thread we do not guarantee that
62 * the new page->flags are visible before the tags were updated.
65 mte_restore_page_tags(page_address(page
), tags
);
70 void mte_invalidate_tags(int type
, pgoff_t offset
)
72 swp_entry_t entry
= swp_entry(type
, offset
);
73 void *tags
= xa_erase(&mte_pages
, entry
.val
);
75 mte_free_tag_storage(tags
);
78 void mte_invalidate_tags_area(int type
)
80 swp_entry_t entry
= swp_entry(type
, 0);
81 swp_entry_t last_entry
= swp_entry(type
+ 1, 0);
84 XA_STATE(xa_state
, &mte_pages
, entry
.val
);
87 xas_for_each(&xa_state
, tags
, last_entry
.val
- 1) {
88 __xa_erase(&mte_pages
, xa_state
.xa_index
);
89 mte_free_tag_storage(tags
);
91 xa_unlock(&mte_pages
);