1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Mapping

use crate::mem::VirtualAddress;
use crate::paging::{PAGE_SIZE, MappingAccessRights};
use crate::error::KernelError;
use crate::frame_allocator::PhysicalMemRegion;
use alloc::{vec::Vec, sync::Arc};
use crate::utils::check_nonzero_length;
use failure::Backtrace;
use sunrise_libkern::{MemoryType, MemoryState};
use crate::sync::{SpinRwLock, SpinRwLockReadGuard};
use core::ops::Range;
use core::fmt;
use core::iter::StepBy;
use crate::mem::PhysicalAddress;

/// A memory mapping.
/// Stores the address, the length, and the type it maps.
/// A mapping is guaranteed to have page aligned address, length and offset,
/// and the length will never be zero.
///
/// If the mapping maps physical frames, we also guarantee that the mapping
/// contains enough physical frames to cover the whole virtual mapping (taking
/// into account length and offset).
///
/// Getting the last address of this mapping (length - 1 + address) is guaranteed to not overflow.
/// However we do not make any assumption on address + length, which falls outside of the mapping.
#[allow(clippy::len_without_is_empty)] // length **cannot** be zero.
pub struct Mapping {
    /// The first address of this mapping.
    address: VirtualAddress,
    /// The length of this mapping.
    length: usize,
    /// The type of this mapping.
    state: MemoryState,
    /// The frames this mapping is referencing.
    frames: MappingFrames,
    /// Physical frame offset of this mapping,
    offset: usize,
    /// The access rights of this mapping.
    flags: MappingAccessRights,
}

impl fmt::Debug for Mapping {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("Mapping")
            .field("address", &self.address)
            .field("length", &self.length)
            .field("ty", &self.state.ty())
            .field("state", &self.state)
            .field("frames", &self.frames)
            .field("offset", &self.offset)
            .field("flags", &self.flags)
            .finish()
    }
}

/// Frames associated with a [Mapping].
#[derive(Debug)]
pub enum MappingFrames {
    /// The frames are Shared between multiple mappings.
    Shared(Arc<SpinRwLock<Vec<PhysicalMemRegion>>>),
    /// The frames are Owned by this mapping.
    Owned(Vec<PhysicalMemRegion>),
    /// This Mapping has no frames.
    None,
}

impl Mapping {
    /// Tries to construct a mapping.
    ///
    /// # Errors
    ///
    /// * `InvalidAddress`:
    ///     * `address` is not page aligned.
    ///     * `offset` is not page aligned.
    ///     * `offset` is bigger than the amount of pages in `frames`.
    ///     * `address` plus `length` would overflow.
    /// * `InvalidSize`:
    ///     * `length` is bigger than the amount of pages in `frames`, minus the offset.
    ///     * `length` is zero.
    ///     * `length` is not page-aligned.
    /// * `WrongMappingFramesForTy`:
    ///     * `frames` didnt' contain the variant of [MappingFrames] expected by `ty`.
    pub fn new(address: VirtualAddress, frames: MappingFrames, offset: usize, length: usize, ty: MemoryType, flags: MappingAccessRights) -> Result<Mapping, KernelError> {
        address.check_aligned_to(PAGE_SIZE)?;
        VirtualAddress(offset).check_aligned_to(PAGE_SIZE)?;
        VirtualAddress(length).check_aligned_to(PAGE_SIZE)?;
        check_nonzero_length(length)?;

        let frames_len = match &frames {
            MappingFrames::Owned(v) => v.iter().flatten().count() * PAGE_SIZE,
            MappingFrames::Shared(v) => v.read().iter().flatten().count() * PAGE_SIZE,
            MappingFrames::None => usize::max_value()
        };

        if frames_len < offset {
            return Err(KernelError::InvalidAddress { address: offset, backtrace: Backtrace::new() });
        }

        if frames_len - offset < length {
            return Err(KernelError::InvalidSize { size: length, backtrace: Backtrace::new() });
        }

        address.checked_add(length - 1)
            .ok_or_else(|| KernelError::InvalidAddress { address: address.addr(), backtrace: Backtrace::new()})?;

        let state = ty.get_memory_state();
        match (&frames, state.contains(MemoryState::IS_REFERENCE_COUNTED), ty) {
            (MappingFrames::None, _, MemoryType::Unmapped) => (),
            (MappingFrames::None, _, MemoryType::Reserved) => (),
            (MappingFrames::None, _, MemoryType::KernelStack) => (),
            (MappingFrames::Shared(_), true, _) => (),
            (MappingFrames::Owned(_), false, _) => (),
            _ => return Err(KernelError::WrongMappingFramesForTy { ty, backtrace: Backtrace::new() })
        }

        Ok(Mapping { address, frames, offset, length, state: ty.get_memory_state(), flags })
    }

    /// Returns the address of this mapping.
    ///
    /// Because we make guarantees about a mapping being always valid, this field cannot be public.
    pub fn address(&self) -> VirtualAddress { self.address }

    /// Returns the address of this mapping.
    ///
    /// Because we make guarantees about a mapping being always valid, this field cannot be public.
    pub fn length(&self) -> usize { self.length }

    /// Returns the frames in this mapping.
    pub fn frames(&self) -> &MappingFrames { &self.frames }

    /// Returns an iterator over the Physical Addresses mapped by this region.
    /// This takes into account the physical offset and the length of the
    /// mapping.
    pub fn frames_it(&self) -> impl Iterator<Item = PhysicalAddress> + Clone + core::fmt::Debug + '_ {
        /// Anonymous iterator over mapping frames' PhysicalAddresses.
        #[derive(Debug)]
        #[allow(clippy::missing_docs_in_private_items)]
        enum MappingFramesIt<'a> {
            None,
            Owned(&'a [PhysicalMemRegion], usize, StepBy<Range<usize>>),
            Shared(&'a Arc<SpinRwLock<Vec<PhysicalMemRegion>>>, SpinRwLockReadGuard<'a, Vec<PhysicalMemRegion>>, usize, StepBy<Range<usize>>),
        }
        impl<'a> Iterator for MappingFramesIt<'a> {
            type Item = PhysicalAddress;
            fn next(&mut self) -> Option<Self::Item> {
                let (frames, curframe, rangeit) = match self {
                    MappingFramesIt::Owned(ref frames, ref mut curframe, ref mut rangeit) => {
                        (*frames, curframe, rangeit)
                    },
                    MappingFramesIt::Shared(_, frames, ref mut curframe, ref mut rangeit) => {
                        (&***frames, curframe, rangeit)
                    },
                    _ => return None
                };

                if let Some(s) = rangeit.next().map(PhysicalAddress) {
                    Some(s)
                } else if *curframe < frames.len() {
                    let frame = &frames[*curframe];
                    *rangeit = (frame.address().0..frame.address().0 + frame.size()).step_by(PAGE_SIZE);
                    *curframe += 1;
                    rangeit.next().map(PhysicalAddress)
                } else {
                    None
                }
            }
        }

        impl<'a> Clone for MappingFramesIt<'a> {
            fn clone(&self) -> MappingFramesIt<'a> {
                match self {
                    MappingFramesIt::Owned(frames, curframe, rangeit) => MappingFramesIt::Owned(frames, *curframe, rangeit.clone()),
                    MappingFramesIt::Shared(frames, _lock, curframe, rangeit) => MappingFramesIt::Shared(frames, frames.read(), *curframe, rangeit.clone()),
                    MappingFramesIt::None => MappingFramesIt::None,
                }
            }
        }

        // We default to creating an empty range, that will get replaced during
        // iteration.
        #[allow(clippy::reversed_empty_ranges)]
        let it = match self.frames() {
            MappingFrames::Owned(frames) => MappingFramesIt::Owned(&frames[..], 0, (0..0).step_by(1)),
            MappingFrames::Shared(frames) => MappingFramesIt::Shared(frames, frames.read(), 0, (0..0).step_by(1)),
            MappingFrames::None => MappingFramesIt::None,
        };
        it
            .skip(self.phys_offset() / PAGE_SIZE)
            .take(self.length() / PAGE_SIZE)
    }

    /// Returns the offset in `frames` this mapping starts from.
    ///
    /// This will be different from 0 when this mapping was created as a partial
    /// remapping of a different shared memory mapping (such as when creating
    /// an IPC buffer).
    pub fn phys_offset(&self) -> usize { self.offset }

    /// Returns the [MemoryState] of this mapping.
    pub fn state(&self) -> MemoryState { self.state }

    /// Returns the type of this mapping.
    ///
    /// Because we make guarantees about a mapping being always valid, this field cannot be public.
    pub fn flags(&self) -> MappingAccessRights { self.flags }
}

#[cfg(test)]
mod test {
    use super::Mapping;
    use super::MappingAccessRights;
    use super::MappingFrames;
    use super::MemoryType;
    use crate::mem::{VirtualAddress, PhysicalAddress};
    use crate::paging::PAGE_SIZE;
    use crate::frame_allocator::{PhysicalMemRegion, FrameAllocator, FrameAllocatorTrait};
    use std::sync::Arc;
    use std::vec::Vec;
    use crate::utils::Splittable;
    use crate::error::KernelError;
    use crate::sync::SpinRwLock;

    /// Applies the same tests to Unmapped, Reserved and KernelStack.
    macro_rules! test_empty_mapping {
        ($($x:ident),*) => {
            mashup! {
                $(
                m["new_" $x] = new_ $x;
                m["mapping_ok_" $x] = $x _mapping_ok;
                m["mapping_zero_length_" $x] = $x _mapping_zero_length;
                m["mapping_non_aligned_addr_" $x] = $x _mapping_non_aligned_addr;
                m["mapping_non_aligned_length_" $x] = $x _mapping_non_aligned_length;
                m["mapping_length_threshold_" $x] = $x _mapping_length_threshold;
                m["mapping_length_overflow_" $x] = $x _mapping_length_overflow;
                )*
            }
            m! {
                $(
                #[test]
                fn "mapping_ok_" $x () {
                    Mapping::new(VirtualAddress(0x40000000), MappingFrames::None, 0, 3 * PAGE_SIZE, MemoryType::$x, MappingAccessRights::empty()).unwrap();
                }

                #[test]
                fn "mapping_zero_length_" $x () {
                    Mapping::new(VirtualAddress(0x40000000), MappingFrames::None, 0, 0, MemoryType::$x, MappingAccessRights::empty()).unwrap_err();
                }

                #[test]
                fn "mapping_non_aligned_addr_" $x () {
                    Mapping::new(VirtualAddress(0x40000007), MappingFrames::None, 0, 3 * PAGE_SIZE, MemoryType::$x, MappingAccessRights::empty()).unwrap_err();
                }

                #[test]
                fn "mapping_non_aligned_length_" $x () {
                    Mapping::new(VirtualAddress(0x40000000), MappingFrames::None, 0, 3, MemoryType::$x, MappingAccessRights::empty()).unwrap_err();
                }

                #[test]
                fn "mapping_length_threshold_" $x () {
                    Mapping::new(VirtualAddress(usize::max_value() - 2 * PAGE_SIZE + 1), MappingFrames::None, 0, 2 * PAGE_SIZE, MemoryType::$x, MappingAccessRights::empty()).unwrap();
                }

                #[test]
                fn "mapping_length_overflow_" $x () {
                    Mapping::new(VirtualAddress(usize::max_value() - 2 * PAGE_SIZE + 1), MappingFrames::None, 0, 3 * PAGE_SIZE, MemoryType::$x, MappingAccessRights::empty()).unwrap_err();
                }
                )*
            }
        }
    }

    test_empty_mapping!(Unmapped, Reserved, KernelStack);

    #[test]
    fn mapping_regular_ok() {
        let _f = crate::frame_allocator::init();
        let frames = FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap();
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Owned(frames), 0, 2 * PAGE_SIZE, MemoryType::Normal, flags).unwrap();
    }

    #[test]
    fn mapping_shared_ok() {
        let _f = crate::frame_allocator::init();
        let frames = Arc::new(SpinRwLock::new(FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap()));
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Shared(frames), 0, 2 * PAGE_SIZE, MemoryType::Stack, flags).unwrap();
    }

    #[test]
    fn mapping_regular_empty_vec() {
        let _f = crate::frame_allocator::init();
        let frames = Vec::new();
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Owned(frames), 0, 2 * PAGE_SIZE, MemoryType::Normal, flags).unwrap_err();
    }

    #[test]
    fn mapping_shared_empty_vec() {
        let _f = crate::frame_allocator::init();
        let frames = Arc::new(SpinRwLock::new(Vec::new()));
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Shared(frames), 0, 2 * PAGE_SIZE, MemoryType::Stack, flags).unwrap_err();
    }

    #[test]
    fn mapping_regular_zero_sized_region() {
        let _f = crate::frame_allocator::init();
        let region = unsafe { PhysicalMemRegion::reconstruct_no_dealloc(PhysicalAddress(PAGE_SIZE), 0) };
        let frames = vec![region];
        let flags = MappingAccessRights::u_rw();
        let _mapping_err = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Owned(frames), 0, 0, MemoryType::Normal, flags).unwrap_err();
    }

    #[test]
    fn mapping_regular_zero_sized_regions() {
        let _f = crate::frame_allocator::init();
        let region1 = unsafe { PhysicalMemRegion::reconstruct_no_dealloc(PhysicalAddress(PAGE_SIZE), 0) };
        let region2 = unsafe { PhysicalMemRegion::reconstruct_no_dealloc(PhysicalAddress(PAGE_SIZE), 0) };
        let frames = vec![region1, region2];
        let flags = MappingAccessRights::u_rw();
        let _mapping_err = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Owned(frames), 0, 0, MemoryType::Normal, flags).unwrap_err();
    }

    #[test]
    fn mapping_regular_unaligned_addr() {
        let _f = crate::frame_allocator::init();
        let frames = FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap();
        let flags = MappingAccessRights::u_rw();
        let _mapping_err = Mapping::new(VirtualAddress(0x40000007), MappingFrames::Owned(frames), 0, 2 * PAGE_SIZE, MemoryType::Normal, flags).unwrap_err();
    }

    #[test]
    fn mapping_shared_unaligned_addr() {
        let _f = crate::frame_allocator::init();
        let frames = Arc::new(SpinRwLock::new(FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap()));
        let flags = MappingAccessRights::u_rw();
        let _mapping_err = Mapping::new(VirtualAddress(0x40000007), MappingFrames::Shared(frames), 0, 2 * PAGE_SIZE, MemoryType::Stack, flags).unwrap_err();
    }


    #[test]
    #[should_panic]
    fn mapping_regular_unaligned_len() {
        let _f = crate::frame_allocator::init();
        let frames = FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE + 7).unwrap();
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Owned(frames), 0, 2 * PAGE_SIZE + 7, MemoryType::Normal, flags).unwrap();
    }

    #[test]
    #[should_panic]
    fn mapping_shared_unaligned_len() {
        let _f = crate::frame_allocator::init();
        let frames = Arc::new(SpinRwLock::new(FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE + 7).unwrap()));
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(0x40000000), MappingFrames::Shared(frames), 0, 2 * PAGE_SIZE + 7, MemoryType::Stack, flags).unwrap();
    }

    #[test]
    fn mapping_regular_threshold() {
        let _f = crate::frame_allocator::init();
        let frames = FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap();
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(usize::max_value() - 2 * PAGE_SIZE + 1), MappingFrames::Owned(frames), 0, 2 * PAGE_SIZE, MemoryType::Normal, flags).unwrap();
    }

    #[test]
    fn mapping_shared_threshold() {
        let _f = crate::frame_allocator::init();
        let frames = Arc::new(SpinRwLock::new(FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap()));
        let flags = MappingAccessRights::u_rw();
        let _mapping = Mapping::new(VirtualAddress(usize::max_value() - 2 * PAGE_SIZE + 1), MappingFrames::Shared(frames), 0, 2 * PAGE_SIZE, MemoryType::Stack, flags).unwrap();
    }

    #[test]
    fn mapping_regular_overflow() {
        let _f = crate::frame_allocator::init();
        let frames = FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap();
        let flags = MappingAccessRights::u_rw();
        let _mapping_err = Mapping::new(VirtualAddress(usize::max_value() - 2 * PAGE_SIZE), MappingFrames::Owned(frames), 0, 2 * PAGE_SIZE, MemoryType::Normal, flags).unwrap_err();
    }

    #[test]
    fn mapping_shared_overflow() {
        let _f = crate::frame_allocator::init();
        let frames = Arc::new(SpinRwLock::new(FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap()));
        let flags = MappingAccessRights::u_rw();
        let _mapping_err = Mapping::new(VirtualAddress(usize::max_value() - 2 * PAGE_SIZE), MappingFrames::Shared(frames), 0, 2 * PAGE_SIZE, MemoryType::Stack, flags).unwrap_err();
    }

    #[test]
    fn mapping_shared_offset() {
        let _f = crate::frame_allocator::init();
        let frames = FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap();

        // Get the address that will get mapped
        let test_addr = frames.iter().flatten().last().unwrap();

        let frames = Arc::new(SpinRwLock::new(frames));
        let flags = MappingAccessRights::u_rw();
        let mapping = Mapping::new(VirtualAddress(0), MappingFrames::Shared(frames), 1 * PAGE_SIZE, 1 * PAGE_SIZE, MemoryType::Stack, flags).unwrap();
        assert!(mapping.frames_it().count() == 1, "Frames_it has the wrong size.");
        assert!(mapping.frames_it().next().unwrap() == test_addr, "Frames_it has the wrong value.");
    }

    #[test]
    fn mapping_shared_offset_overflow() {
        let _f = crate::frame_allocator::init();
        let frames = Arc::new(SpinRwLock::new(FrameAllocator::allocate_frames_fragmented(2 * PAGE_SIZE).unwrap()));
        let flags = MappingAccessRights::u_rw();
        let _mapping_err = Mapping::new(VirtualAddress(0), MappingFrames::Shared(frames), 1 * PAGE_SIZE, 2 * PAGE_SIZE, MemoryType::Stack, flags).unwrap_err();
    }
}