Skip to main content

obkrnl/uma/
zone.rs

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
19/// Implementation of `uma_zone` structure.
20pub 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>,                                              // uz_size
26    slab: unsafe fn(&Arc<UmaKeg>, Alloc) -> Option<Pin<Strong<Slab>>>, // uz_slab
27    init: Option<fn(*mut u8, NonZero<usize>, Alloc) -> bool>,          // uz_init
28    ctor: Option<fn(*mut u8, NonZero<usize>, Alloc) -> bool>,          // uz_ctor
29    dtor: Option<fn()>,                                                // uz_dtor
30    caches: CpuLocal<RefCell<UmaCache>>,                               // uz_cpu
31    state: Mutex<ZoneState>,
32}
33
34impl UmaZone {
35    const ALIGN_CACHE: usize = 63; // uma_align_cache
36
37    /// See `zone_ctor` on Orbis for a reference.
38    ///
39    /// # Reference offsets
40    /// | Version | Offset |
41    /// |---------|--------|
42    /// |PS4 11.00|0x13D490|
43    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            // We use a different approach here to make it idiomatic to Rust. On Orbis it will
56            // construct a keg here if it is passed from the caller. If not it will allocate a new
57            // keg from masterzone_k.
58            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        // Get type and uz_count.
73        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        // Construct uma_zone.
109        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    /// See `uma_zalloc_arg` on the Orbis for a reference.
148    ///
149    /// # Reference offsets
150    /// | Version | Offset |
151    /// |---------|--------|
152    /// |PS4 11.00|0x13E750|
153    pub fn alloc(&self, flags: Alloc) -> *mut u8 {
154        if flags.has_any(Alloc::Wait) {
155            // TODO: The Orbis also modify td_pflags on a certain condition.
156            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        loop {
164            // Try allocate from per-CPU cache first so we don't need to acquire a mutex lock.
165            let caches = self.caches.lock();
166            let mem = Self::alloc_from_cache(caches.borrow_mut().deref_mut());
167
168            if !mem.is_null() {
169                return mem;
170            }
171
172            drop(caches); // Exit from non-sleeping context before acquire the mutex.
173
174            // Cache not found, allocate from the zone. We need to re-check the cache again because
175            // we may on a different CPU since we drop the CPU pinning on the above.
176            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                return mem;
183            }
184
185            // TODO: What actually we are doing here?
186            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                // Seems like this should never fail.
197                let m = Self::alloc_from_cache(&mut cache);
198
199                assert!(!m.is_null());
200
201                return m;
202            }
203
204            drop(cache);
205            drop(caches);
206
207            // TODO: What is this?
208            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            // TODO: What is this?
223            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
241    /// See `uma_zfree_arg` on the Orbis for a reference.
242    ///
243    /// # Safety
244    /// `item` either allocated from [Self::alloc()] or null.
245    ///
246    /// # Reference offsets
247    /// | Version | Offset |
248    /// |---------|--------|
249    /// |PS4 11.00|0x13EFC0|
250    pub unsafe fn free(&self, item: *mut u8) {
251        if item.is_null() {
252            return;
253        } else if self.dtor.is_some() {
254            todo!()
255        }
256
257        // Check zone type.
258        let mut state = self.state.lock();
259
260        if self.ty != ZoneType::MbufPacket
261            && self.ty != ZoneType::MbufClusterPack
262            && self.ty != ZoneType::MbufJumboPage
263            && self.ty != ZoneType::Mbuf
264            && self.ty != ZoneType::MbufCluster
265            && state.flags.has_any(UmaFlags::Full)
266        {
267            todo!()
268        }
269
270        // TODO: The uz_flags check on above defeat below optimization. On Orbis they did not put
271        // uz_flags behind a uz_lock.
272        loop {
273            let caches = self.caches.lock();
274            let mut cache = caches.borrow_mut();
275
276            while cache.free.is_some() {
277                todo!()
278            }
279
280            state.alloc_count += core::mem::take(&mut cache.allocs);
281            state.free_count += core::mem::take(&mut cache.frees);
282
283            if cache.free.take().is_some() {
284                todo!()
285            }
286
287            if state.free_buckets.front().is_some() {
288                todo!()
289            }
290
291            drop(cache);
292            drop(caches);
293
294            if !self.bucket_enable.load(Ordering::Relaxed) {
295                todo!()
296            }
297
298            // Get bucket zone.
299            let i = (state.count + 15) >> Uma::BUCKET_SHIFT;
300            let k = self.bucket_keys[i];
301            let b = &self.bucket_zones[k];
302            let f = Alloc::from((u32::from(state.flags) >> 31) << 9); // TODO: Refactor this.
303
304            drop(state);
305
306            // Alloc a bucket. The Orbis does not force M_ZERO here but we do the opposite to
307            // eliminate the chance of dangling pointer in bucket items.
308            let b = b.alloc_item(&mut b.state.lock(), f | Alloc::Zero | Alloc::NoWait);
309
310            if b.is_null() {
311                todo!()
312            }
313
314            // Initialize bucket.
315            let h = BucketHdr { len: 0 };
316            let b = unsafe {
317                core::ptr::write(b.cast(), h);
318                core::ptr::slice_from_raw_parts_mut(b, Uma::BUCKET_SIZES[k]) as *mut UmaBucket
319            };
320
321            // Add to free list.
322            state = self.state.lock();
323            state
324                .free_buckets
325                .push_front(unsafe { NonNull::new_unchecked(b) });
326        }
327    }
328
329    fn alloc_from_cache(c: &mut UmaCache) -> *mut u8 {
330        while let Some(b) = c.alloc.map(|v| v.as_ptr()) {
331            if unsafe { (*b).hdr.len != 0 } {
332                todo!()
333            }
334
335            if c.free
336                .map(|v| v.as_ptr())
337                .is_some_and(|b| unsafe { (*b).hdr.len != 0 })
338            {
339                core::mem::swap(&mut c.alloc, &mut c.free);
340                continue;
341            }
342
343            break;
344        }
345
346        null_mut()
347    }
348
349    /// See `zone_alloc_bucket` on the Orbis for a reference.
350    ///
351    /// # Reference offsets
352    /// | Version | Offset |
353    /// |---------|--------|
354    /// |PS4 11.00|0x13EBA0|
355    fn alloc_bucket(&self, state: &mut ZoneState, flags: Alloc) -> bool {
356        // Get bucket.
357        let b = match state.free_buckets.front() {
358            Some(_) => todo!(),
359            None => {
360                if self.bucket_enable.load(Ordering::Relaxed) {
361                    // Get allocation flags. On Orbis it will remove M_ZERO from the flags but we do
362                    // the opposite to eliminate the chance of dangling pointer in bucket items.
363                    let mut flags = flags | Alloc::Zero;
364
365                    if state.flags.has_any(UmaFlags::CacheOnly) {
366                        flags |= Alloc::NoVm;
367                    }
368
369                    // Alloc a bucket.
370                    let i = (state.count + 15) >> Uma::BUCKET_SHIFT;
371                    let k = self.bucket_keys[i];
372                    let b = &self.bucket_zones[k];
373                    let b = b.alloc_item(&mut b.state.lock(), flags);
374
375                    if b.is_null() {
376                        todo!()
377                    }
378
379                    // Initialize bucket.
380                    let h = BucketHdr { len: 0 };
381                    let s = Uma::BUCKET_SIZES[k];
382
383                    unsafe {
384                        core::ptr::write(b.cast(), h);
385                        core::ptr::slice_from_raw_parts_mut(b, s) as *mut UmaBucket
386                    }
387                } else {
388                    todo!()
389                }
390            }
391        };
392
393        // SAFETY: We have exclusive access to the bucket.
394        let b = unsafe { &mut *b };
395
396        if state.fills < config().cpu_count().get().into() {
397            let n = min(b.items.len(), state.count);
398            let k = state.kegs.front().unwrap();
399            let mut f = flags;
400
401            state.fills += 1;
402
403            while b.hdr.len < n {
404                let s = match unsafe { (self.slab)(k, f) } {
405                    Some(v) => v,
406                    None => todo!(),
407                };
408
409                while b.hdr.len < n {
410                    let i = s.alloc_item();
411
412                    if i.is_null() {
413                        break;
414                    }
415
416                    b.items[b.hdr.len] = i;
417                    b.hdr.len += 1;
418                }
419
420                f |= Alloc::NoWait;
421            }
422
423            if self.init.is_some() {
424                todo!()
425            }
426
427            state.fills -= 1;
428
429            if b.hdr.len != 0 {
430                state
431                    .full_buckets
432                    .push_front(unsafe { NonNull::new_unchecked(b) });
433
434                return true;
435            }
436
437            todo!()
438        }
439
440        todo!()
441    }
442
443    /// See `zone_alloc_item` on the Orbis for a reference.
444    ///
445    /// # Reference offsets
446    /// | Version | Offset |
447    /// |---------|--------|
448    /// |PS4 11.00|0x13DD50|
449    fn alloc_item(&self, state: &mut ZoneState, flags: Alloc) -> *mut u8 {
450        // Get a slab.
451        let keg = state.kegs.front().unwrap();
452        let slab = unsafe { (self.slab)(keg, flags) };
453
454        if let Some(slab) = slab {
455            let item = slab.alloc_item();
456
457            state.alloc_count += 1;
458
459            if self.init.is_none_or(|f| f(item, self.size, flags)) {
460                if self.ctor.is_none_or(|f| f(item, self.size, flags)) {
461                    if flags.has_any(Alloc::Zero) {
462                        unsafe { item.write_bytes(0, self.size.get()) };
463                    }
464
465                    return item;
466                } else {
467                    todo!()
468                }
469            } else {
470                todo!()
471            }
472        }
473
474        todo!()
475    }
476
477    /// See `zone_fetch_slab` on the Orbis for a reference.
478    ///
479    /// # Reference offsets
480    /// | Version | Offset |
481    /// |---------|--------|
482    /// |PS4 11.00|0x141DB0|
483    unsafe fn fetch_slab(keg: &Arc<UmaKeg>, flags: Alloc) -> Option<Pin<Strong<Slab>>> {
484        if !keg.flags().has_any(UmaFlags::Bucket) || keg.recurse() == 0 {
485            loop {
486                if let Some(v) = unsafe { keg.fetch_slab(flags) } {
487                    return Some(v);
488                }
489
490                if flags.has_any(Alloc::NoWait | Alloc::NoVm) {
491                    break;
492                }
493            }
494        }
495
496        None
497    }
498}
499
500/// Contains mutable data for [UmaZone].
501struct ZoneState {
502    kegs: LinkedList<Arc<UmaKeg>>,              // uz_kegs + uz_klink
503    full_buckets: VecDeque<NonNull<UmaBucket>>, // uz_full_bucket
504    free_buckets: VecDeque<NonNull<UmaBucket>>, // uz_free_bucket
505    alloc_count: u64,                           // uz_allocs
506    free_count: u64,                            // uz_frees
507    count: usize,                               // uz_count
508    fills: u16,                                 // uz_fills
509    flags: UmaFlags,                            // uz_flags
510}
511
512unsafe impl Send for ZoneState {}
513
514/// Type of [UmaZone].
515#[derive(Clone, Copy, PartialEq, Eq)]
516enum ZoneType {
517    Other,
518    /// `zone_pack`.
519    MbufPacket,
520    /// `zone_jumbop`.
521    MbufJumboPage,
522    /// `zone_mbuf`.
523    Mbuf,
524    /// `zone_clust`.
525    MbufCluster,
526    /// `zone_clust_pack`.
527    MbufClusterPack,
528}
529
530/// Implementation of `uma_cache` structure.
531#[derive(Default)]
532struct UmaCache {
533    alloc: Option<NonNull<UmaBucket>>, // uc_allocbucket
534    free: Option<NonNull<UmaBucket>>,  // uc_freebucket
535    allocs: u64,                       // uc_allocs
536    frees: u64,                        // uc_frees
537}
538
539unsafe impl Send for UmaCache {}
540
541/// Implementation of `uma_zctor_args` structure.
542pub struct ZoneArgs {
543    pub name: String,                                             // name
544    pub keg: Option<Arc<UmaKeg>>,                                 // keg
545    pub size: NonZero<usize>,                                     // size
546    pub align: Option<usize>,                                     // align
547    pub init: Option<fn()>,                                       // uminit
548    pub ctor: Option<fn(*mut u8, NonZero<usize>, Alloc) -> bool>, // ctor
549    pub dtor: Option<fn()>,                                       // dtor
550    pub flags: UmaFlags,                                          // flags
551}