1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2021 FUJITSU LIMITED. All rights reserved.
4 * Author: Yang Xu <xuyang2018.jy@fujitsu.com>
5 */
6
7 /*\
8 * [Description]
9 *
10 * It is a basic test for shm_next_id.
11 *
12 * When the shared memory segment identifier that shm_next_id stored is already
13 * in use, call shmget with different key just use another unused value in range
14 * [0,INT_MAX]. Kernel doesn't guarantee the desired id.
15 */
16
17 #include <errno.h>
18 #include <string.h>
19 #include <sys/types.h>
20 #include <sys/ipc.h>
21 #include <sys/shm.h>
22 #include "tst_test.h"
23 #include "tst_safe_sysv_ipc.h"
24 #include "libnewipc.h"
25
26 #define NEXT_ID_PATH "/proc/sys/kernel/shm_next_id"
27
28 static int shm_id[2], pid;
29 static key_t shmkey[2];
30
verify_shmget(void)31 static void verify_shmget(void)
32 {
33 SAFE_FILE_PRINTF(NEXT_ID_PATH, "%d", shm_id[0]);
34
35 shm_id[1] = SAFE_SHMGET(shmkey[1], SHM_SIZE, IPC_CREAT | SHM_RW);
36 if (shm_id[1] == shm_id[0])
37 tst_res(TFAIL, "shm id %d has existed, shmget() returns the"
38 " same shm id unexpectedly", shm_id[0]);
39 else
40 tst_res(TPASS, "shm id %d has existed, shmget() returns the"
41 " new shm id %d", shm_id[0], shm_id[1]);
42
43 SAFE_SHMCTL(shm_id[1], IPC_RMID, NULL);
44 }
45
setup(void)46 static void setup(void)
47 {
48 shmkey[0] = GETIPCKEY();
49 shmkey[1] = GETIPCKEY();
50 pid = getpid();
51 SAFE_FILE_PRINTF(NEXT_ID_PATH, "%d", pid);
52 shm_id[0] = SAFE_SHMGET(shmkey[0], SHM_SIZE, IPC_CREAT | SHM_RW);
53 }
54
cleanup(void)55 static void cleanup(void)
56 {
57 int i;
58
59 for (i = 0; i < 2; i++) {
60 if (shm_id[i] != -1)
61 SAFE_SHMCTL(shm_id[i], IPC_RMID, NULL);
62 }
63 }
64
65 static struct tst_test test = {
66 .needs_tmpdir = 1,
67 .setup = setup,
68 .cleanup = cleanup,
69 .test_all = verify_shmget,
70 .needs_kconfigs = (const char *[]) {
71 "CONFIG_CHECKPOINT_RESTORE=y",
72 NULL
73 },
74 .needs_root = 1,
75 };
76