1 /*
2  * Copyright (c) 2001-2019, Arm Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 
8 
9 /************* Include Files ****************/
10 #include <unistd.h>
11 #include <sys/mman.h>
12 #include <fcntl.h>
13 #include "cc_pal_types.h"
14 #include "cc_pal_memmap.h"
15 
16 /************************ Defines ******************************/
17 static int halFileH = -1;
18 
19 /************************ Enums ******************************/
20 
21 /************************ Typedefs ******************************/
22 
23 /************************ Global Data ******************************/
24 
25 /************************ Private Functions ******************************/
26 
27 /************************ Public Functions ******************************/
28 
29 /**
30  * @brief This function purpose is to return the base virtual address that maps the
31  *        base physical address
32  *
33  * @param[in] physicalAddress - Starts physical address of the I/O range to be mapped.
34  * @param[in] mapSize - Number of bytes that were mapped
35  * @param[out] ppVirtBuffAddr - Pointer to the base virtual address to which the physical pages were mapped
36  *
37  * @return Returns a non-zero value in case of failure
38  */
CC_PalMemMap(CCDmaAddr_t physicalAddress,uint32_t mapSize,uint32_t ** ppVirtBuffAddr)39 uint32_t CC_PalMemMap(CCDmaAddr_t physicalAddress,
40                    uint32_t mapSize,
41                uint32_t **ppVirtBuffAddr)
42 {
43         /* Open device file if not already opened */
44         if (halFileH >= 0) { /* already opened */
45             return 0;
46         }
47 
48         halFileH = open("/dev/mem", O_RDWR|O_SYNC);
49         if (halFileH < 0) {
50             return 1;
51         }
52         (void)fcntl(halFileH, F_SETFD, FD_CLOEXEC);
53 
54         *ppVirtBuffAddr = (uint32_t *)mmap(0, mapSize, PROT_READ|PROT_WRITE, MAP_SHARED, halFileH, physicalAddress);
55         if ((*ppVirtBuffAddr == NULL) || (*ppVirtBuffAddr == MAP_FAILED)) {
56             close(halFileH);
57             halFileH = -1;
58             return 2;
59         }
60         return 0;
61 }/* End of CC_PalMemMap */
62 
63 
64 /**
65  * @brief This function purpose is to Unmaps a specified address range previously mapped
66  *        by CC_PalMemMap
67  *
68  *
69  * @param[in] pVirtBuffAddr - Pointer to the base virtual address to which the physical
70  *            pages were mapped
71  * @param[in] mapSize - Number of bytes that were mapped
72  *
73  * @return Returns a non-zero value in case of failure
74  */
CC_PalMemUnMap(uint32_t * pVirtBuffAddr,uint32_t mapSize)75 uint32_t CC_PalMemUnMap(uint32_t *pVirtBuffAddr,
76                      uint32_t mapSize)
77 {
78         if (halFileH < 0) {
79             return 1;
80         }
81 
82         munmap(pVirtBuffAddr, mapSize);
83         close(halFileH);
84         halFileH = -1;
85         return 0;
86 }/* End of CC_PalMemUnMap */
87