1 /*
2  * Copyright (c) 2021-2022, Arm Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include <stddef.h>
8 #include <stdio.h>
9 #include <sys/mman.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include "carveout.h"
13 
14 #ifndef MM_COMM_BUFFER_ADDRESS
15 #error "MM_COMM_BUFFER_ADDRESS macro is undefined!"
16 #endif
17 #ifndef MM_COMM_BUFFER_SIZE
18 #error "MM_COMM_BUFFER_SIZE macro is undefined!"
19 #endif
20 
carveout_claim(uint8_t ** buf,size_t * buf_size)21 int carveout_claim(uint8_t **buf, size_t *buf_size)
22 {
23 	int status = -1;
24 	int fd = open("/dev/mem", O_RDWR | O_SYNC);
25 
26 	if (fd >= 0) {
27 
28 		uint8_t *mem = mmap(NULL, (size_t)(MM_COMM_BUFFER_SIZE),
29 			PROT_READ | PROT_WRITE, MAP_SHARED,
30 			fd, (off_t)(MM_COMM_BUFFER_ADDRESS));
31 
32 		if (mem != MAP_FAILED) {
33 
34 			*buf = mem;
35 			*buf_size = (size_t)(MM_COMM_BUFFER_SIZE);
36 
37 			status = 0;
38 		}
39 
40 		close(fd);
41 	}
42 
43 	return status;
44 }
45 
carveout_relinquish(uint8_t * buf,size_t buf_size)46 void carveout_relinquish(uint8_t *buf, size_t buf_size)
47 {
48 	munmap(buf, buf_size);
49 }
50