2 * SPDX-License-Identifier: MIT
4 * Copyright 2010 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
7 #ifndef _BABELTRACE_MMAP_ALIGN_H
8 #define _BABELTRACE_MMAP_ALIGN_H
10 #include "common/align.h"
13 #include "compat/mman.h"
14 #include "common/common.h"
17 * This header implements a wrapper over mmap (mmap_align) that memory
18 * maps a file region that is not necessarily multiple of the page size.
19 * It returns a structure (instead of a pointer) that contains the mmap
20 * pointer (page-aligned) and a pointer to the offset requested within
21 * that page. Note: in the current implementation, the "addr" parameter
22 * cannot be forced, so we allocate at an address chosen by the OS.
25 struct mmap_align_data
{
26 void *page_aligned_addr
; /* mmap address, aligned to floor */
27 size_t page_aligned_length
; /* mmap length, containing range */
29 void *addr
; /* virtual mmap address */
30 size_t length
; /* virtual mmap length */
34 off_t
get_page_aligned_offset(off_t offset
, int log_level
)
36 return BT_ALIGN_FLOOR(offset
, bt_mmap_get_offset_align_size(log_level
));
40 struct mmap_align_data
*mmap_align(size_t length
, int prot
,
41 int flags
, int fd
, off_t offset
, int log_level
)
43 struct mmap_align_data
*mma
;
44 off_t page_aligned_offset
; /* mmap offset, aligned to floor */
47 page_size
= bt_common_get_page_size(log_level
);
49 mma
= (struct mmap_align_data
*) malloc(sizeof(*mma
));
51 return (struct mmap_align_data
*) MAP_FAILED
;
53 page_aligned_offset
= get_page_aligned_offset(offset
, log_level
);
55 * Page aligned length needs to contain the requested range.
56 * E.g., for a small range that fits within a single page, we might
57 * require a 2 pages page_aligned_length if the range crosses a page
60 mma
->page_aligned_length
= BT_ALIGN(length
+ offset
- page_aligned_offset
, page_size
);
61 mma
->page_aligned_addr
= bt_mmap(mma
->page_aligned_length
,
62 prot
, flags
, fd
, page_aligned_offset
, log_level
);
63 if (mma
->page_aligned_addr
== MAP_FAILED
) {
65 return (struct mmap_align_data
*) MAP_FAILED
;
67 mma
->addr
= ((uint8_t *) mma
->page_aligned_addr
) + (offset
- page_aligned_offset
);
72 int munmap_align(struct mmap_align_data
*mma
)
74 void *page_aligned_addr
;
75 size_t page_aligned_length
;
77 page_aligned_addr
= mma
->page_aligned_addr
;
78 page_aligned_length
= mma
->page_aligned_length
;
80 return bt_munmap(page_aligned_addr
, page_aligned_length
);
84 void *mmap_align_addr(struct mmap_align_data
*mma
)
90 * Helper for special-cases, normally unused.
93 void mmap_align_set_addr(struct mmap_align_data
*mma
, void *addr
)
98 #endif /* _BABELTRACE_MMAP_ALIGN_H */