1f08c3bdfSopenharmony_ci// SPDX-License-Identifier: GPL-2.0-or-later
2f08c3bdfSopenharmony_ci/*
3f08c3bdfSopenharmony_ci * Copyright (c) 2019 Red Hat, Inc.
4f08c3bdfSopenharmony_ci * Copyright (c) Linux Test Project, 2019
5f08c3bdfSopenharmony_ci */
6f08c3bdfSopenharmony_ci
7f08c3bdfSopenharmony_ci#ifndef PKEYS_H
8f08c3bdfSopenharmony_ci#define PKEYS_H
9f08c3bdfSopenharmony_ci
10f08c3bdfSopenharmony_ci#include "tst_test.h"
11f08c3bdfSopenharmony_ci#include "lapi/syscalls.h"
12f08c3bdfSopenharmony_ci#include "lapi/mmap.h"
13f08c3bdfSopenharmony_ci
14f08c3bdfSopenharmony_ci#ifndef PKEY_DISABLE_ACCESS
15f08c3bdfSopenharmony_ci# define PKEY_DISABLE_ACCESS 0x1
16f08c3bdfSopenharmony_ci# define PKEY_DISABLE_WRITE  0x2
17f08c3bdfSopenharmony_ci#endif
18f08c3bdfSopenharmony_ci
19f08c3bdfSopenharmony_ci#ifndef HAVE_PKEY_MPROTECT
20f08c3bdfSopenharmony_ciinline int ltp_pkey_mprotect(void *addr, size_t len, int prot, int pkey)
21f08c3bdfSopenharmony_ci{
22f08c3bdfSopenharmony_ci	return tst_syscall(__NR_pkey_mprotect, addr, len, prot, pkey);
23f08c3bdfSopenharmony_ci}
24f08c3bdfSopenharmony_ci
25f08c3bdfSopenharmony_ciinline int ltp_pkey_alloc(unsigned int flags, unsigned int access_rights)
26f08c3bdfSopenharmony_ci{
27f08c3bdfSopenharmony_ci	return tst_syscall(__NR_pkey_alloc, flags, access_rights);
28f08c3bdfSopenharmony_ci}
29f08c3bdfSopenharmony_ci
30f08c3bdfSopenharmony_ciinline int ltp_pkey_free(int pkey)
31f08c3bdfSopenharmony_ci{
32f08c3bdfSopenharmony_ci	return tst_syscall(__NR_pkey_free, pkey);
33f08c3bdfSopenharmony_ci}
34f08c3bdfSopenharmony_ci#else
35f08c3bdfSopenharmony_ci#define ltp_pkey_alloc pkey_alloc
36f08c3bdfSopenharmony_ci#define ltp_pkey_free pkey_free
37f08c3bdfSopenharmony_ci#define ltp_pkey_mprotect pkey_mprotect
38f08c3bdfSopenharmony_ci#endif /* HAVE_PKEY_MPROTECT */
39f08c3bdfSopenharmony_ci
40f08c3bdfSopenharmony_cistatic inline void check_pkey_support(void)
41f08c3bdfSopenharmony_ci{
42f08c3bdfSopenharmony_ci	int pkey = ltp_pkey_alloc(0, 0);
43f08c3bdfSopenharmony_ci
44f08c3bdfSopenharmony_ci	if (pkey == -1) {
45f08c3bdfSopenharmony_ci		if (errno == ENOSYS)
46f08c3bdfSopenharmony_ci			tst_brk(TCONF, "pkey_alloc is not implemented");
47f08c3bdfSopenharmony_ci		if (errno == EINVAL)
48f08c3bdfSopenharmony_ci			tst_brk(TCONF, "pku is not supported on this CPU");
49f08c3bdfSopenharmony_ci		if (errno == ENOSPC)
50f08c3bdfSopenharmony_ci			tst_brk(TCONF, "pkeys are not available for test");
51f08c3bdfSopenharmony_ci	}
52f08c3bdfSopenharmony_ci
53f08c3bdfSopenharmony_ci	ltp_pkey_free(pkey);
54f08c3bdfSopenharmony_ci}
55f08c3bdfSopenharmony_ci
56f08c3bdfSopenharmony_ci#endif /* PKEYS_H */
57