Skip to content

Commit d0bfe4e

Browse files
committed
add mi_urealloc_aligned; rust: base MiMallocExcess on the mi_u* API and avoid the aligned path for size < align, issue #1513
1 parent db66db4 commit d0bfe4e

9 files changed

Lines changed: 113 additions & 116 deletions

File tree

‎contrib/rust/src/allocator.rs‎

Lines changed: 41 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ terms of the MIT license. A copy of the license can be found in the file
55
"LICENSE" at the root of this distribution.
66
-----------------------------------------------------------------------------*/
77
use crate::heap::realloc_in;
8-
use crate::{free_sized, realloc_aligned, sys, Heap, MiMalloc, MAX_ALIGN_SIZE};
8+
use crate::{free_sized, malloc_aligned_size, realloc_aligned, sys, Heap, MiMalloc};
99
use core::alloc::{AllocError, Allocator, GlobalAlloc, Layout};
10-
use core::mem::size_of;
11-
use core::ptr::NonNull;
10+
use core::ptr::{self, NonNull};
1211

1312
#[inline(always)]
1413
fn block(ptr: *mut u8, size: usize) -> Result<NonNull<[u8]>, AllocError> {
@@ -135,70 +134,56 @@ unsafe impl Allocator for &Heap {
135134
}
136135
}
137136

138-
/// As [`MiMalloc`] but `allocate` returns the full usable size by requesting `good_size` bytes.
137+
/// As [`MiMalloc`] but returns the full usable size of the allocated block (using the `mi_u*` functions).
139138
/// This can be useful for vector or buffer allocations to maximise the usable memory and reduce reallocations.
140139
#[derive(Clone, Copy, Debug, Default)]
141140
pub struct MiMallocExcess;
142141

143-
// As `mi_good_size` for sizes up to `MI_SMALL_SIZE_MAX` (in words, see `mi_bin`); a mismatch only wastes space as we allocate the returned size.
144-
// (If the size classes ever change, we catch this in the tests where we verify `small_good_wsize` against `mi_good_size`.)
145142
#[inline(always)]
146-
pub(crate) const fn small_good_wsize(size: usize) -> usize {
147-
const ALIGN_WSIZE: usize = MAX_ALIGN_SIZE / size_of::<usize>();
148-
let wsize = crate::wsize_from_size(size);
149-
if wsize <= 1 {
150-
1
151-
} else if size <= 16 {
152-
(wsize + 1) & !1
153-
} else if size <= 64 {
154-
(wsize + ALIGN_WSIZE - 1) & !(ALIGN_WSIZE - 1)
155-
} else {
156-
// 4 size classes per power of two
157-
let w = wsize - 1;
158-
let shift = (usize::BITS - 1 - w.leading_zeros()) - 2;
159-
((w >> shift) + 1) << shift
160-
}
161-
}
162-
163-
#[inline(always)]
164-
fn small_alloc(layout: Layout, zero: bool) -> Option<Result<NonNull<[u8]>, AllocError>> {
165-
if layout.align() > MAX_ALIGN_SIZE || layout.size() > sys::MI_SMALL_SIZE_MAX {
166-
return None;
167-
}
168-
let wsize = small_good_wsize(layout.size());
143+
unsafe fn urealloc(ptr: *mut u8, new: Layout) -> (*mut u8, usize) {
144+
let mut usable = 0;
169145
let p = unsafe {
170-
if zero {
171-
sys::mi_wzalloc_small(wsize)
172-
} else {
173-
sys::mi_wmalloc_small(wsize)
146+
match malloc_aligned_size(new.size(), new.align()) {
147+
Some(size) => sys::mi_urealloc(ptr.cast(), size, ptr::null_mut(), &mut usable),
148+
None => sys::mi_urealloc_aligned(
149+
ptr.cast(),
150+
new.size(),
151+
new.align(),
152+
ptr::null_mut(),
153+
&mut usable,
154+
),
174155
}
175156
};
176-
Some(block(p.cast(), wsize * size_of::<usize>()))
177-
}
178-
179-
#[inline(always)]
180-
fn good_layout(layout: Layout) -> Layout {
181-
let size = crate::good_size(layout.size());
182-
unsafe { Layout::from_size_align_unchecked(size, layout.align()) }
157+
(p.cast(), usable)
183158
}
184159

185160
unsafe impl Allocator for MiMallocExcess {
186161
#[inline]
187162
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
188-
if let Some(r) = small_alloc(layout, false) {
189-
return r;
190-
}
191-
let layout = good_layout(layout);
192-
block(unsafe { MiMalloc.alloc(layout) }, layout.size())
163+
let (size, align) = (layout.size(), layout.align());
164+
let mut usable = 0;
165+
let p = unsafe {
166+
if let Some(size) = malloc_aligned_size(size, align) {
167+
sys::mi_umalloc(size, &mut usable)
168+
} else {
169+
sys::mi_umalloc_aligned(size, align, &mut usable)
170+
}
171+
};
172+
block(p.cast(), usable)
193173
}
194174

195175
#[inline]
196176
fn allocate_zeroed(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
197-
if let Some(r) = small_alloc(layout, true) {
198-
return r;
199-
}
200-
let layout = good_layout(layout);
201-
block(unsafe { MiMalloc.alloc_zeroed(layout) }, layout.size())
177+
let (size, align) = (layout.size(), layout.align());
178+
let mut usable = 0;
179+
let p = unsafe {
180+
if let Some(size) = malloc_aligned_size(size, align) {
181+
sys::mi_uzalloc(size, &mut usable)
182+
} else {
183+
sys::mi_uzalloc_aligned(size, align, &mut usable)
184+
}
185+
};
186+
block(p.cast(), usable)
202187
}
203188

204189
#[inline]
@@ -213,11 +198,8 @@ unsafe impl Allocator for MiMallocExcess {
213198
_old: Layout,
214199
new: Layout,
215200
) -> Result<NonNull<[u8]>, AllocError> {
216-
let size = crate::good_size(new.size());
217-
block(
218-
unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) },
219-
size,
220-
)
201+
let (p, usable) = unsafe { urealloc(ptr.as_ptr(), new) };
202+
block(p, usable)
221203
}
222204

223205
#[inline]
@@ -227,9 +209,8 @@ unsafe impl Allocator for MiMallocExcess {
227209
old: Layout,
228210
new: Layout,
229211
) -> Result<NonNull<[u8]>, AllocError> {
230-
let size = crate::good_size(new.size());
231-
let p = unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) };
232-
block(unsafe { zero_tail(p, old.size(), size) }, size)
212+
let (p, usable) = unsafe { urealloc(ptr.as_ptr(), new) };
213+
block(unsafe { zero_tail(p, old.size(), usable) }, usable)
233214
}
234215

235216
#[inline]
@@ -239,10 +220,7 @@ unsafe impl Allocator for MiMallocExcess {
239220
_old: Layout,
240221
new: Layout,
241222
) -> Result<NonNull<[u8]>, AllocError> {
242-
let size = crate::good_size(new.size());
243-
block(
244-
unsafe { realloc_aligned(ptr.as_ptr(), new.align(), size) },
245-
size,
246-
)
223+
let (p, usable) = unsafe { urealloc(ptr.as_ptr(), new) };
224+
block(p, usable)
247225
}
248226
}

‎contrib/rust/src/heap.rs‎

Lines changed: 18 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ This is free software; you can redistribute it and/or modify it under the
44
terms of the MIT license. A copy of the license can be found in the file
55
"LICENSE" at the root of this distribution.
66
-----------------------------------------------------------------------------*/
7-
use crate::{free_sized, is_malloc_aligned, sys, Arena, MiString};
7+
use crate::{free_sized, malloc_aligned_size, sys, Arena, MiString};
88
use core::alloc::Layout;
99
use core::ptr::{self, NonNull};
1010

@@ -50,14 +50,14 @@ impl Heap {
5050
/// Allocate a block for `layout`; returns null when out of memory.
5151
#[inline]
5252
pub fn alloc(&self, layout: Layout) -> *mut u8 {
53-
let (heap, size) = (self.as_ptr(), layout.size());
53+
let heap = self.as_ptr();
5454
unsafe {
55-
if !is_malloc_aligned(size, layout.align()) {
56-
sys::mi_heap_malloc_aligned(heap, size, layout.align())
57-
} else if size <= sys::MI_SMALL_SIZE_MAX {
58-
sys::mi_heap_malloc_small(heap, size)
59-
} else {
60-
sys::mi_heap_malloc(heap, size)
55+
match malloc_aligned_size(layout.size(), layout.align()) {
56+
Some(size) if size <= sys::MI_SMALL_SIZE_MAX => {
57+
sys::mi_heap_malloc_small(heap, size)
58+
}
59+
Some(size) => sys::mi_heap_malloc(heap, size),
60+
None => sys::mi_heap_malloc_aligned(heap, layout.size(), layout.align()),
6161
}
6262
}
6363
.cast()
@@ -66,14 +66,14 @@ impl Heap {
6666
/// Allocate a zero-initialized block for `layout`; returns null when out of memory.
6767
#[inline]
6868
pub fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
69-
let (heap, size) = (self.as_ptr(), layout.size());
69+
let heap = self.as_ptr();
7070
unsafe {
71-
if !is_malloc_aligned(size, layout.align()) {
72-
sys::mi_heap_zalloc_aligned(heap, size, layout.align())
73-
} else if size <= sys::MI_SMALL_SIZE_MAX {
74-
sys::mi_heap_zalloc_small(heap, size)
75-
} else {
76-
sys::mi_heap_zalloc(heap, size)
71+
match malloc_aligned_size(layout.size(), layout.align()) {
72+
Some(size) if size <= sys::MI_SMALL_SIZE_MAX => {
73+
sys::mi_heap_zalloc_small(heap, size)
74+
}
75+
Some(size) => sys::mi_heap_zalloc(heap, size),
76+
None => sys::mi_heap_zalloc_aligned(heap, layout.size(), layout.align()),
7777
}
7878
}
7979
.cast()
@@ -137,10 +137,9 @@ pub(crate) unsafe fn realloc_in(
137137
new_size: usize,
138138
) -> *mut u8 {
139139
unsafe {
140-
if is_malloc_aligned(new_size, align) {
141-
sys::mi_heap_realloc(heap, ptr.cast(), new_size)
142-
} else {
143-
sys::mi_heap_realloc_aligned(heap, ptr.cast(), new_size, align)
140+
match malloc_aligned_size(new_size, align) {
141+
Some(size) => sys::mi_heap_realloc(heap, ptr.cast(), size),
142+
None => sys::mi_heap_realloc_aligned(heap, ptr.cast(), new_size, align),
144143
}
145144
}
146145
.cast()

‎contrib/rust/src/lib.rs‎

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,16 @@ use core::ptr::{self, NonNull};
4343
// As `MI_MAX_ALIGN_SIZE`
4444
pub(crate) const MAX_ALIGN_SIZE: usize = 16;
4545

46-
// Fast check if `mi_malloc(size)` is already `align`-aligned (a subset of `mi_malloc_is_naturally_aligned`)
46+
// The size for which `mi_malloc` returns an `align`-aligned block, or `None` if `mi_malloc_aligned` is needed
4747
#[inline(always)]
48-
pub(crate) const fn is_malloc_aligned(size: usize, align: usize) -> bool {
49-
align <= MAX_ALIGN_SIZE && align <= size
48+
pub(crate) const fn malloc_aligned_size(size: usize, align: usize) -> Option<usize> {
49+
if align > MAX_ALIGN_SIZE {
50+
None
51+
} else if size < align {
52+
Some(align)
53+
} else {
54+
Some(size)
55+
}
5056
}
5157

5258
// As `_mi_wsize_from_size`
@@ -80,10 +86,9 @@ pub(crate) unsafe fn free_sized(ptr: *mut u8, layout: Layout) {
8086
#[inline(always)]
8187
pub(crate) unsafe fn realloc_aligned(ptr: *mut u8, align: usize, new_size: usize) -> *mut u8 {
8288
unsafe {
83-
if is_malloc_aligned(new_size, align) {
84-
sys::mi_realloc(ptr.cast(), new_size)
85-
} else {
86-
sys::mi_realloc_aligned(ptr.cast(), new_size, align)
89+
match malloc_aligned_size(new_size, align) {
90+
Some(size) => sys::mi_realloc(ptr.cast(), size),
91+
None => sys::mi_realloc_aligned(ptr.cast(), new_size, align),
8792
}
8893
}
8994
.cast()
@@ -92,29 +97,27 @@ pub(crate) unsafe fn realloc_aligned(ptr: *mut u8, align: usize, new_size: usize
9297
unsafe impl GlobalAlloc for MiMalloc {
9398
#[inline]
9499
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
95-
let size = layout.size();
96100
unsafe {
97-
if !is_malloc_aligned(size, layout.align()) {
98-
sys::mi_malloc_aligned(size, layout.align())
99-
} else if size <= sys::MI_SMALL_SIZE_MAX {
100-
sys::mi_wmalloc_small(wsize_from_size(size))
101-
} else {
102-
sys::mi_malloc(size)
101+
match malloc_aligned_size(layout.size(), layout.align()) {
102+
Some(size) if size <= sys::MI_SMALL_SIZE_MAX => {
103+
sys::mi_wmalloc_small(wsize_from_size(size))
104+
}
105+
Some(size) => sys::mi_malloc(size),
106+
None => sys::mi_malloc_aligned(layout.size(), layout.align()),
103107
}
104108
}
105109
.cast()
106110
}
107111

108112
#[inline]
109113
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
110-
let size = layout.size();
111114
unsafe {
112-
if !is_malloc_aligned(size, layout.align()) {
113-
sys::mi_zalloc_aligned(size, layout.align())
114-
} else if size <= sys::MI_SMALL_SIZE_MAX {
115-
sys::mi_wzalloc_small(wsize_from_size(size))
116-
} else {
117-
sys::mi_zalloc(size)
115+
match malloc_aligned_size(layout.size(), layout.align()) {
116+
Some(size) if size <= sys::MI_SMALL_SIZE_MAX => {
117+
sys::mi_wzalloc_small(wsize_from_size(size))
118+
}
119+
Some(size) => sys::mi_zalloc(size),
120+
None => sys::mi_zalloc_aligned(layout.size(), layout.align()),
118121
}
119122
}
120123
.cast()

‎contrib/rust/sys/src/lib.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,13 @@ extern "C" {
218218
alignment: usize,
219219
usable_size: *mut usize,
220220
) -> *mut c_void;
221+
pub fn mi_urealloc_aligned(
222+
p: *mut c_void,
223+
newsize: usize,
224+
alignment: usize,
225+
usable_size_pre: *mut usize,
226+
usable_size_post: *mut usize,
227+
) -> *mut c_void;
221228
pub fn mi_umalloc_small(size: usize, usable_size: *mut usize) -> *mut c_void;
222229
pub fn mi_uzalloc_small(size: usize, usable_size: *mut usize) -> *mut c_void;
223230

‎contrib/rust/tests/allocator.rs‎

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#![cfg(any(feature = "nightly", allocator_api_stable))]
22
#![cfg_attr(feature = "nightly", feature(allocator_api), allow(stable_features))]
33

4+
use core::alloc::{Allocator, Layout};
45
use mimalloc::{Heap, MiMalloc};
56

67
#[repr(align(64))]
@@ -38,7 +39,6 @@ fn heap_allocator_api() {
3839

3940
#[test]
4041
fn grow_zeroed() {
41-
use core::alloc::{Allocator, Layout};
4242
let heap = Heap::new();
4343
for (old, new, align) in [
4444
(8, 1000, 8),
@@ -69,15 +69,13 @@ fn grow_zeroed() {
6969

7070
#[test]
7171
fn excess_allocator_api() {
72-
use core::alloc::{Allocator, Layout};
73-
use mimalloc::{good_size, usable_size, MiMallocExcess};
72+
use mimalloc::{usable_size, MiMallocExcess};
73+
// returns exactly the usable size
7474
let a = MiMallocExcess;
75-
// returned sizes match `good_size` (unless padding is enabled)
76-
let exact = good_size(mimalloc::sys::MI_SMALL_SIZE_MAX) == mimalloc::sys::MI_SMALL_SIZE_MAX;
77-
// (with memory tagging the minimal block is 16 bytes but we may still return 8)
78-
let is_good = |len: usize, size: usize| !exact || len == good_size(size) || len == 8;
7975
for (size, align) in [
8076
(0, 1),
77+
(1, 16),
78+
(8, 16),
8179
(100, 8),
8280
(1000, 8),
8381
(5000, 16),
@@ -88,8 +86,7 @@ fn excess_allocator_api() {
8886
.allocate_zeroed(Layout::from_size_align(size, align).unwrap())
8987
.unwrap();
9088
let q = p.cast::<u8>().as_ptr();
91-
assert!(p.len() >= size && is_good(p.len(), size));
92-
assert!(p.len() <= unsafe { usable_size(q) });
89+
assert!(p.len() >= size && p.len() == unsafe { usable_size(q) });
9390
assert!((0..p.len()).all(|i| unsafe { q.add(i).read() } == 0));
9491
assert_eq!(q as usize % align, 0);
9592
let (old, new) = (
@@ -98,16 +95,14 @@ fn excess_allocator_api() {
9895
);
9996
let r = unsafe { a.grow_zeroed(p.cast(), old, new) }.unwrap();
10097
let q = r.cast::<u8>().as_ptr();
101-
assert!(r.len() >= new.size() && is_good(r.len(), new.size()));
102-
assert!(r.len() <= unsafe { usable_size(q) });
98+
assert!(r.len() >= new.size() && r.len() == unsafe { usable_size(q) });
10399
assert!((old.size()..r.len()).all(|i| unsafe { q.add(i).read() } == 0));
104100
unsafe { a.deallocate(r.cast(), Layout::from_size_align(r.len(), align).unwrap()) };
105101
}
106102
for size in 0..=mimalloc::sys::MI_SMALL_SIZE_MAX {
107103
let layout = Layout::from_size_align(size, 1).unwrap();
108104
let p = a.allocate(layout).unwrap();
109-
let len = unsafe { usable_size(p.cast::<u8>().as_ptr()) };
110-
assert!(p.len() >= size && p.len() <= len && is_good(p.len(), size));
105+
assert!(p.len() >= size && p.len() == unsafe { usable_size(p.cast::<u8>().as_ptr()) });
111106
unsafe { a.deallocate(p.cast(), Layout::from_size_align(p.len(), 1).unwrap()) };
112107
}
113108
// `Vec` ignores the excess for now

‎doc/mimalloc-doc.h‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -378,6 +378,9 @@ void* mi_umalloc_aligned(size_t size, size_t alignment, size_t* pusable_size);
378378
/// As mi_zalloc_aligned(), additionally reporting the usable size on success.
379379
void* mi_uzalloc_aligned(size_t size, size_t alignment, size_t* pusable_size);
380380

381+
/// As mi_realloc_aligned(), additionally reporting the old and new usable sizes (as mi_urealloc()).
382+
void* mi_urealloc_aligned(void* p, size_t newsize, size_t alignment, size_t* pusable_size_pre, size_t* pusable_size_post);
383+
381384
/// As mi_malloc_small(), additionally reporting the usable size on success.
382385
/// \a size must not exceed #MI_SMALL_SIZE_MAX.
383386
void* mi_umalloc_small(size_t size, size_t* pusable_size);

‎include/mimalloc.h‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,7 @@ mi_decl_export void mi_ufree(void* p, size_t* usable_size) mi_attr_noexcept;
239239

240240
mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc_aligned(size_t size, size_t alignment, size_t* usable_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_align(2);
241241
mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_uzalloc_aligned(size_t size, size_t alignment, size_t* usable_size) mi_attr_noexcept mi_attr_malloc mi_attr_alloc_align(2);
242+
mi_decl_nodiscard mi_decl_export void* mi_urealloc_aligned(void* p, size_t newsize, size_t alignment, size_t* usable_size_pre, size_t* usable_size_post) mi_attr_noexcept mi_attr_alloc_align(3);
242243

243244
mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_umalloc_small(size_t size, size_t* usable_size) mi_attr_noexcept mi_attr_malloc;
244245
mi_decl_nodiscard mi_decl_export mi_decl_restrict void* mi_uzalloc_small(size_t size, size_t* usable_size) mi_attr_noexcept mi_attr_malloc;

0 commit comments

Comments
 (0)