1// SPDX-License-Identifier: LGPL-2.1-or-later
2/*
3 * Copyright (C) 2005-2006 IBM Corporation.
4 * Author: David Gibson & Adam Litke
5 */
6
7/*\
8 * [Description]
9 *
10 * This Test perform Direct Write/Read from/To hugetlbfs file
11 * which is mapped to process address space. The test is checking if it
12 * succeeds and data written or read is not corrupted.
13 */
14
15#define _GNU_SOURCE
16#include <stdio.h>
17#include <sys/mount.h>
18#include <limits.h>
19#include <sys/param.h>
20#include <sys/types.h>
21
22#include "hugetlb.h"
23
24#define P0 "ffffffff"
25#define IOSZ 4096
26#define NORMAL_PATH ""
27#define MNTPOINT "hugetlbfs/"
28
29static long hpage_size;
30static int fd = -1, nfd = -1;
31
32static void run_test(void)
33{
34	void *p;
35	char buf[IOSZ] __attribute__((aligned(IOSZ)));
36
37	fd = tst_creat_unlinked(MNTPOINT, 0);
38	nfd = tst_creat_unlinked(NORMAL_PATH, O_DIRECT);
39	p = SAFE_MMAP(NULL, hpage_size, PROT_READ|PROT_WRITE, MAP_PRIVATE, fd, 0);
40	memcpy(p, P0, 8);
41
42	SAFE_WRITE(1, nfd, p, IOSZ);
43	SAFE_LSEEK(nfd, 0, SEEK_SET);
44
45	SAFE_READ(1, nfd, buf, IOSZ);
46	if (memcmp(P0, buf, 8)) {
47		tst_res(TFAIL, "Memory mismatch after Direct-IO write");
48		goto cleanup;
49	}
50	SAFE_LSEEK(nfd, 0, SEEK_SET);
51
52	memset(p, 0, IOSZ);
53	SAFE_READ(1, nfd, p, IOSZ);
54
55	if (memcmp(p, P0, 8))
56		tst_res(TFAIL, "Memory mismatch after Direct-IO read");
57	else
58		tst_res(TPASS, "Direct-IO read/write to/from hugepages is successful");
59cleanup:
60	SAFE_MUNMAP(p, hpage_size);
61	SAFE_CLOSE(fd);
62	SAFE_CLOSE(nfd);
63}
64
65static void setup(void)
66{
67	hpage_size = SAFE_READ_MEMINFO(MEMINFO_HPAGE_SIZE)*1024;
68}
69
70static void cleanup(void)
71{
72	if (fd > 0)
73		SAFE_CLOSE(fd);
74	if (nfd > 0)
75		SAFE_CLOSE(nfd);
76}
77
78static struct tst_test test = {
79	.needs_root = 1,
80	.mntpoint = MNTPOINT,
81	.needs_hugetlbfs = 1,
82	.setup = setup,
83	.cleanup = cleanup,
84	.test_all = run_test,
85	.hugepages = {1, TST_NEEDS},
86};
87