xref: /openbmc/hiomapd/vpnor/test/write_rw.cpp (revision 8cef63e3)
1 // SPDX-License-Identifier: Apache-2.0
2 // Copyright (C) 2018 IBM Corp.
3 #include "config.h"
4 
5 extern "C" {
6 #include "backend.h"
7 #include "common.h"
8 #include "mboxd.h"
9 }
10 
11 #include "vpnor/test/tmpd.hpp"
12 
13 #include <fcntl.h>
14 #include <sys/mman.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18 
19 #include <cassert>
20 
21 static constexpr auto BLOCK_SIZE = 0x1000;
22 
23 const std::string toc[] = {
24     "partition01=TEST1,00001000,00002000,80,ECC,READWRITE",
25 };
26 
27 int main(void)
28 {
29     namespace fs = std::experimental::filesystem;
30     namespace test = openpower::virtual_pnor::test;
31 
32     struct mbox_context _ctx, *ctx = &_ctx;
33     uint8_t src[8] = {0};
34     void* map;
35     int rc;
36     int fd;
37 
38     /* Setup */
39     memset(ctx, 0, sizeof(mbox_context));
40 
41     mbox_vlog = &mbox_log_console;
42     verbosity = (verbose)2;
43 
44     ctx->backend.flash_size = 0x2000;
45     test::VpnorRoot root(&ctx->backend, toc, BLOCK_SIZE);
46     /* flash_write() doesn't copy the file for us */
47     assert(fs::copy_file(root.ro() / "TEST1", root.rw() / "TEST1"));
48 
49     /* Test */
50     memset(src, 0xbb, sizeof(src));
51     rc = backend_write(&ctx->backend, 0x1000, src, sizeof(src));
52     assert(rc == 0);
53     fd = open((root.rw() / "TEST1").c_str(), O_RDONLY);
54     map = mmap(NULL, sizeof(src), PROT_READ, MAP_SHARED, fd, 0);
55     assert(map != MAP_FAILED);
56     rc = memcmp(src, map, sizeof(src));
57     assert(rc == 0);
58 
59     /* Ensure single byte writes function */
60     memset(src, 0xcc, sizeof(src));
61     rc = backend_write(&ctx->backend, 0x1000, src, sizeof(src));
62     assert(rc == 0);
63     rc = memcmp(src, map, sizeof(src));
64     assert(rc == 0);
65 
66     src[0] = 0xff;
67     rc = backend_write(&ctx->backend, 0x1000, src, 1);
68     assert(rc == 0);
69     rc = memcmp(src, map, sizeof(src));
70     assert(rc == 0);
71 
72     src[1] = 0xff;
73     rc = backend_write(&ctx->backend, 0x1000 + 1, &src[1], 1);
74     assert(rc == 0);
75     rc = memcmp(src, map, sizeof(src));
76     assert(rc == 0);
77 
78     src[2] = 0xff;
79     rc = backend_write(&ctx->backend, 0x1000 + 2, &src[2], 1);
80     assert(rc == 0);
81     rc = memcmp(src, map, sizeof(src));
82     assert(rc == 0);
83 
84     /* Writes past the end of the partition should fail */
85     rc = backend_write(&ctx->backend, 0x1000 + 0xff9, src, sizeof(src));
86     assert(rc < 0);
87 
88     /* Check that RW file is unmodified after the bad write */
89     fd = open((root.rw() / "TEST1").c_str(), O_RDONLY);
90     map = mmap(NULL, sizeof(src), PROT_READ, MAP_SHARED, fd, 0);
91     assert(map != MAP_FAILED);
92     rc = memcmp(src, map, sizeof(src));
93     assert(rc == 0);
94 
95     munmap(map, sizeof(src));
96     close(fd);
97 
98     return 0;
99 }
100