1use super::{Alloc, BucketHdr, Slab, Uma, UmaBucket, UmaFlags, UmaKeg};
2use crate::context::{CpuLocal, config, current_thread};
3use crate::lock::Mutex;
4use crate::mem::Strong;
5use crate::vm::Vm;
6use alloc::collections::VecDeque;
7use alloc::collections::linked_list::LinkedList;
8use alloc::string::String;
9use alloc::sync::Arc;
10use alloc::vec::Vec;
11use core::cell::RefCell;
12use core::cmp::min;
13use core::num::NonZero;
14use core::ops::DerefMut;
15use core::pin::Pin;
16use core::ptr::{NonNull, null_mut};
17use core::sync::atomic::{AtomicBool, Ordering};
18
19pub struct UmaZone {
21 bucket_enable: Arc<AtomicBool>,
22 bucket_keys: Arc<Vec<usize>>,
23 bucket_zones: Arc<Vec<UmaZone>>,
24 ty: ZoneType,
25 size: NonZero<usize>, slab: unsafe fn(&Arc<UmaKeg>, Alloc) -> Option<Pin<Strong<Slab>>>, init: Option<fn(*mut u8, NonZero<usize>, Alloc) -> bool>, ctor: Option<fn(*mut u8, NonZero<usize>, Alloc) -> bool>, dtor: Option<fn()>, caches: CpuLocal<RefCell<UmaCache>>, state: Mutex<ZoneState>,
32}
33
34impl UmaZone {
35 const ALIGN_CACHE: usize = 63; pub(super) fn new(
44 vm: &'static Vm,
45 bucket_enable: Arc<AtomicBool>,
46 bucket_keys: Arc<Vec<usize>>,
47 bucket_zones: Arc<Vec<UmaZone>>,
48 args: ZoneArgs,
49 ) -> Self {
50 let name = args.name;
51 let flags = args.flags;
52 let (keg, mut flags) = if flags.has_any(UmaFlags::Secondary) {
53 todo!()
54 } else {
55 let keg = match args.keg {
59 Some(v) => v,
60 None => UmaKeg::new(
61 vm,
62 args.size,
63 args.align.unwrap_or(Self::ALIGN_CACHE),
64 args.init,
65 flags,
66 ),
67 };
68
69 (keg, UmaFlags::zeroed())
70 };
71
72 let mut ty = ZoneType::Other;
74 let mut count = 0;
75
76 if !keg.flags().has_any(UmaFlags::Internal) {
77 count = if !keg.flags().has_any(UmaFlags::MaxBucket) {
78 min(keg.item_per_slab(), Uma::BUCKET_MAX)
79 } else {
80 Uma::BUCKET_MAX
81 };
82
83 match name.as_str() {
84 "mbuf_packet" => {
85 ty = ZoneType::MbufPacket;
86 count = 4;
87 }
88 "mbuf_cluster_pack" => {
89 ty = ZoneType::MbufClusterPack;
90 count = Uma::BUCKET_MAX;
91 }
92 "mbuf_jumbo_page" => {
93 ty = ZoneType::MbufJumboPage;
94 count = 1;
95 }
96 "mbuf" => {
97 ty = ZoneType::Mbuf;
98 count = 16;
99 }
100 "mbuf_cluster" => {
101 ty = ZoneType::MbufCluster;
102 count = 1;
103 }
104 _ => (),
105 }
106 }
107
108 let inherit = UmaFlags::Offpage
110 | UmaFlags::Malloc
111 | UmaFlags::Hash
112 | UmaFlags::VToSlab
113 | UmaFlags::Bucket
114 | UmaFlags::Internal
115 | UmaFlags::CacheOnly;
116
117 flags |= keg.flags() & inherit;
118
119 Self {
120 bucket_enable,
121 bucket_keys,
122 bucket_zones,
123 ty,
124 size: keg.size(),
125 slab: Self::fetch_slab,
126 init: None,
127 ctor: args.ctor,
128 dtor: args.dtor,
129 caches: CpuLocal::new(|_| RefCell::default()),
130 state: Mutex::new(ZoneState {
131 kegs: LinkedList::from([keg]),
132 full_buckets: VecDeque::default(),
133 free_buckets: VecDeque::default(),
134 alloc_count: 0,
135 free_count: 0,
136 count,
137 fills: 0,
138 flags,
139 }),
140 }
141 }
142
143 pub fn size(&self) -> NonZero<usize> {
144 self.size
145 }
146
147 pub fn alloc(&self, flags: Alloc) -> *mut u8 {
154 if flags.has_any(Alloc::Wait) {
155 let td = current_thread();
157
158 if !td.can_sleep() {
159 panic!("attempt to do waitable heap allocation in a non-sleeping context");
160 }
161 }
162
163 let m = loop {
164 let caches = self.caches.lock();
166 let mem = Self::alloc_from_cache(caches.borrow_mut().deref_mut());
167
168 if !mem.is_null() {
169 break mem;
170 }
171
172 drop(caches); let mut state = self.state.lock();
177 let caches = self.caches.lock();
178 let mut cache = caches.borrow_mut();
179 let mem = Self::alloc_from_cache(&mut cache);
180
181 if !mem.is_null() {
182 break mem;
183 }
184
185 state.alloc_count += core::mem::take(&mut cache.allocs);
187 state.free_count += core::mem::take(&mut cache.frees);
188
189 if let Some(b) = cache.alloc.take() {
190 state.free_buckets.push_front(b);
191 }
192
193 if let Some(b) = state.full_buckets.pop_front() {
194 cache.alloc = Some(b);
195
196 let m = Self::alloc_from_cache(&mut cache);
198
199 debug_assert!(!m.is_null());
200
201 break m;
202 }
203
204 drop(cache);
205 drop(caches);
206
207 if matches!(
209 self.ty,
210 ZoneType::MbufPacket
211 | ZoneType::MbufJumboPage
212 | ZoneType::Mbuf
213 | ZoneType::MbufCluster
214 ) {
215 if flags.has_any(Alloc::Wait) {
216 todo!()
217 }
218
219 todo!()
220 }
221
222 if !matches!(
224 self.ty,
225 ZoneType::MbufCluster
226 | ZoneType::Mbuf
227 | ZoneType::MbufJumboPage
228 | ZoneType::MbufPacket
229 | ZoneType::MbufClusterPack
230 ) && state.count < Uma::BUCKET_MAX
231 {
232 state.count += 1;
233 }
234
235 if self.alloc_bucket(&mut state, flags) {
236 return self.alloc_item(&mut state, flags);
237 }
238 };
239
240 if flags.has_any(Alloc::Zero) {
242 unsafe { m.write_bytes(0, self.size.get()) };
243 }
244
245 if self.ctor.is_none_or(move |f| f(m, self.size, flags)) {
246 m
247 } else {
248 todo!()
249 }
250 }
251
252 pub unsafe fn free(&self, item: *mut u8) {
262 if item.is_null() {
263 return;
264 } else if self.dtor.is_some() {
265 todo!()
266 }
267
268 let mut state = self.state.lock();
270
271 if self.ty != ZoneType::MbufPacket
272 && self.ty != ZoneType::MbufClusterPack
273 && self.ty != ZoneType::MbufJumboPage
274 && self.ty != ZoneType::Mbuf
275 && self.ty != ZoneType::MbufCluster
276 && state.flags.has_any(UmaFlags::Full)
277 {
278 todo!()
279 }
280
281 loop {
284 let caches = self.caches.lock();
285 let mut cache = caches.borrow_mut();
286
287 while cache.free.is_some() {
288 todo!()
289 }
290
291 state.alloc_count += core::mem::take(&mut cache.allocs);
292 state.free_count += core::mem::take(&mut cache.frees);
293
294 if cache.free.take().is_some() {
295 todo!()
296 }
297
298 if state.free_buckets.front().is_some() {
299 todo!()
300 }
301
302 drop(cache);
303 drop(caches);
304
305 if !self.bucket_enable.load(Ordering::Relaxed) {
306 todo!()
307 }
308
309 let i = (state.count + 15) >> Uma::BUCKET_SHIFT;
311 let k = self.bucket_keys[i];
312 let b = &self.bucket_zones[k];
313 let f = Alloc::from((u32::from(state.flags) >> 31) << 9); drop(state);
316
317 let b = b.alloc_item(&mut b.state.lock(), f | Alloc::Zero | Alloc::NoWait);
320
321 if b.is_null() {
322 todo!()
323 }
324
325 let h = BucketHdr { len: 0 };
327 let b = unsafe {
328 core::ptr::write(b.cast(), h);
329 core::ptr::slice_from_raw_parts_mut(b, Uma::BUCKET_SIZES[k]) as *mut UmaBucket
330 };
331
332 state = self.state.lock();
334 state
335 .free_buckets
336 .push_front(unsafe { NonNull::new_unchecked(b) });
337 }
338 }
339
340 fn alloc_from_cache(c: &mut UmaCache) -> *mut u8 {
341 while let Some(b) = c.alloc.map(|v| v.as_ptr()) {
342 if let Some(v) = unsafe { (*b).hdr.len.checked_sub(1) } {
343 unsafe { (*b).hdr.len = v };
344
345 c.allocs += 1;
346
347 return unsafe { (*b).items[v] };
348 }
349
350 if c.free
351 .map(|v| v.as_ptr())
352 .is_some_and(|b| unsafe { (*b).hdr.len != 0 })
353 {
354 core::mem::swap(&mut c.alloc, &mut c.free);
355 continue;
356 }
357
358 break;
359 }
360
361 null_mut()
362 }
363
364 fn alloc_bucket(&self, state: &mut ZoneState, flags: Alloc) -> bool {
371 let b = match state.free_buckets.front() {
373 Some(_) => todo!(),
374 None => {
375 if self.bucket_enable.load(Ordering::Relaxed) {
376 let mut flags = flags | Alloc::Zero;
379
380 if state.flags.has_any(UmaFlags::CacheOnly) {
381 flags |= Alloc::NoVm;
382 }
383
384 let i = (state.count + 15) >> Uma::BUCKET_SHIFT;
386 let k = self.bucket_keys[i];
387 let b = &self.bucket_zones[k];
388 let b = b.alloc_item(&mut b.state.lock(), flags);
389
390 if b.is_null() {
391 todo!()
392 }
393
394 let h = BucketHdr { len: 0 };
396 let s = Uma::BUCKET_SIZES[k];
397
398 unsafe {
399 core::ptr::write(b.cast(), h);
400 core::ptr::slice_from_raw_parts_mut(b, s) as *mut UmaBucket
401 }
402 } else {
403 todo!()
404 }
405 }
406 };
407
408 let b = unsafe { &mut *b };
410
411 if state.fills < config().cpu_count().get().into() {
412 let n = min(b.items.len(), state.count);
413 let k = state.kegs.front().unwrap();
414 let mut f = flags;
415
416 state.fills += 1;
417
418 while b.hdr.len < n {
419 let s = match unsafe { (self.slab)(k, f) } {
420 Some(v) => v,
421 None => todo!(),
422 };
423
424 while b.hdr.len < n {
425 let i = s.alloc_item();
426
427 if i.is_null() {
428 break;
429 }
430
431 b.items[b.hdr.len] = i;
432 b.hdr.len += 1;
433 }
434
435 f |= Alloc::NoWait;
436 }
437
438 if self.init.is_some() {
439 todo!()
440 }
441
442 state.fills -= 1;
443
444 if b.hdr.len != 0 {
445 state
446 .full_buckets
447 .push_front(unsafe { NonNull::new_unchecked(b) });
448
449 return true;
450 }
451
452 todo!()
453 }
454
455 todo!()
456 }
457
458 fn alloc_item(&self, state: &mut ZoneState, flags: Alloc) -> *mut u8 {
465 let keg = state.kegs.front().unwrap();
467 let slab = unsafe { (self.slab)(keg, flags) };
468
469 if let Some(slab) = slab {
470 let item = slab.alloc_item();
471
472 state.alloc_count += 1;
473
474 if self.init.is_none_or(|f| f(item, self.size, flags)) {
475 if self.ctor.is_none_or(|f| f(item, self.size, flags)) {
476 if flags.has_any(Alloc::Zero) {
477 unsafe { item.write_bytes(0, self.size.get()) };
478 }
479
480 return item;
481 } else {
482 todo!()
483 }
484 } else {
485 todo!()
486 }
487 }
488
489 todo!()
490 }
491
492 unsafe fn fetch_slab(keg: &Arc<UmaKeg>, flags: Alloc) -> Option<Pin<Strong<Slab>>> {
499 if !keg.flags().has_any(UmaFlags::Bucket) || keg.recurse() == 0 {
500 loop {
501 if let Some(v) = unsafe { keg.fetch_slab(flags) } {
502 return Some(v);
503 }
504
505 if flags.has_any(Alloc::NoWait | Alloc::NoVm) {
506 break;
507 }
508 }
509 }
510
511 None
512 }
513}
514
515struct ZoneState {
517 kegs: LinkedList<Arc<UmaKeg>>, full_buckets: VecDeque<NonNull<UmaBucket>>, free_buckets: VecDeque<NonNull<UmaBucket>>, alloc_count: u64, free_count: u64, count: usize, fills: u16, flags: UmaFlags, }
526
527unsafe impl Send for ZoneState {}
528
529#[derive(Clone, Copy, PartialEq, Eq)]
531enum ZoneType {
532 Other,
533 MbufPacket,
535 MbufJumboPage,
537 Mbuf,
539 MbufCluster,
541 MbufClusterPack,
543}
544
545#[derive(Default)]
547struct UmaCache {
548 alloc: Option<NonNull<UmaBucket>>, free: Option<NonNull<UmaBucket>>, allocs: u64, frees: u64, }
553
554unsafe impl Send for UmaCache {}
555
556pub struct ZoneArgs {
558 pub name: String, pub keg: Option<Arc<UmaKeg>>, pub size: NonZero<usize>, pub align: Option<usize>, pub init: Option<fn()>, pub ctor: Option<fn(*mut u8, NonZero<usize>, Alloc) -> bool>, pub dtor: Option<fn()>, pub flags: UmaFlags, }