treadmill.rs 14.6 KB
Newer Older
Isaac Oscar Gariano's avatar
Isaac Oscar Gariano committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright 2017 The Australian National University
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

qinsoon's avatar
qinsoon committed
15 16 17 18
#![allow(dead_code)]

use utils::Address;
use utils::mem::memmap;
19 20
use common::AddressMap;

21 22
use objectmodel;

qinsoon's avatar
qinsoon committed
23
use std::sync::Arc;
24 25
use std::fmt;
use std::sync::Mutex;
qinsoon's avatar
qinsoon committed
26 27 28 29

const SPACE_ALIGN : usize = 1 << 19;
const BLOCK_SIZE  : usize = 1 << 12;    // 4kb

30 31
const TRACE_TREADMILL : bool = false;

qinsoon's avatar
qinsoon committed
32 33 34 35 36 37 38 39 40 41 42
#[repr(C)]
pub struct FreeListSpace {
    start : Address,
    end   : Address,

    pub alloc_map : Arc<AddressMap<u8>>,
    pub trace_map : Arc<AddressMap<u8>>,

    #[allow(dead_code)]
    mmap : memmap::Mmap,

43
    treadmill: Mutex<Treadmill>
qinsoon's avatar
qinsoon committed
44 45 46 47 48 49 50 51 52
}

impl FreeListSpace {
    pub fn new(space_size: usize) -> FreeListSpace {
        let anon_mmap : memmap::Mmap = match memmap::Mmap::anonymous(space_size + SPACE_ALIGN, memmap::Protection::ReadWrite) {
            Ok(m) => m,
            Err(_) => panic!("failed to call mmap")
        };
        let start : Address = Address::from_ptr::<u8>(anon_mmap.ptr()).align_up(SPACE_ALIGN);
53
        let end   : Address = start + space_size;
qinsoon's avatar
qinsoon committed
54

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        let trace_map = AddressMap::new(start, end);
        let alloc_map = AddressMap::new(start, end);
        if cfg!(debug_assertions) {
            trace_map.init_all(0);
            alloc_map.init_all(0);
        }

        let treadmill = Treadmill::new(start, end);

        FreeListSpace {
            start: start,
            end: end,
            alloc_map: Arc::new(alloc_map),
            trace_map: Arc::new(trace_map),
            mmap: anon_mmap,
            treadmill: Mutex::new(treadmill)
        }
    }

    pub fn alloc(&self, size: usize, align: usize) -> Address {
        // every block is 'BLOCK_SIZE' aligned, usually we do not need to align
        assert!(BLOCK_SIZE % align == 0);

78 79
        let size = size + objectmodel::OBJECT_HEADER_SIZE;

80 81 82 83 84 85
        let blocks_needed = if size % BLOCK_SIZE == 0 {
            size / BLOCK_SIZE
        } else {
            size / BLOCK_SIZE + 1
        };

86
        if TRACE_TREADMILL {
87 88
            trace!("---before allocation---");
            trace!("{}", self);
89
        }
90

91
        trace!("requiring {} bytes ({} blocks)", size, blocks_needed);
92 93 94 95 96
        let res = {
            let mut treadmill = self.treadmill.lock().unwrap();
            treadmill.alloc_blocks(blocks_needed)
        };

97
        if TRACE_TREADMILL {
98 99
            trace!("---after allocation---");
            trace!("{}", self);
100
        }
101

102 103 104
        if res.is_zero() {
            res
        } else {
105
            res + (-objectmodel::OBJECT_HEADER_OFFSET)
106
        }
107 108
    }

109 110 111 112 113 114 115 116 117 118 119 120
    #[inline(always)]
    #[cfg(feature = "use-sidemap")]
    fn is_traced(&self, addr: Address, mark_state: u8) -> bool {
        objectmodel::is_traced(self.trace_map(), self.start, unsafe { addr.to_object_reference() }, mark_state)
    }

    #[inline(always)]
    #[cfg(not(feature = "use-sidemap"))]
    fn is_traced(&self, addr: Address, mark_state: u8) -> bool {
        objectmodel::is_traced(unsafe{addr.to_object_reference()}, mark_state)
    }

121
    pub fn sweep(&self) {
122
        trace!("going to sweep treadmill space");
123 124 125 126 127 128 129
        if TRACE_TREADMILL {
            trace!("{}", self);
        }

        let mut nodes_scanned = 0;
        let mut free_nodes_scanned = 0;
        let mut alive_nodes_scanned = 0;
130

131
        let mut treadmill = self.treadmill.lock().unwrap();
132

133 134
        {
            let mark_state = objectmodel::load_mark_state();
135

136 137
            let from = treadmill.from;
            let to   = treadmill.to;
138

139 140 141 142 143
            let total_nodes = treadmill.spaces[from].len();
            let mut i = 0;
            while nodes_scanned < total_nodes {
                trace!("scanning {}", treadmill.spaces[from][i]);
                let addr = treadmill.spaces[from][i].payload;
144

145
                nodes_scanned += 1;
146

147 148 149
                let traced = self.is_traced(addr, mark_state);

                if traced {
150 151
                    // this object is alive
                    alive_nodes_scanned += 1;
152

153 154
                    // move to tospace
                    let node = treadmill.spaces[from].remove(i);
155
                    treadmill.spaces[to].push(node);
156

157
                    trace!("is alive");
158

159
                    // do not increment i
160
                } else {
161 162
                    free_nodes_scanned += 1;
                    i += 1;
163 164 165
                }
            }

166 167
            // check if we have any free nodes
            if free_nodes_scanned == 0 && treadmill.spaces[treadmill.to].len() == 0 {
168 169 170 171
                println!("didnt free up any memory in treadmill space");
                panic!("we ran out of memory in large object space")
            }
        }
172

173 174 175 176 177 178 179 180 181 182 183 184
        // next allocation in to_space will starts from alive_nodes_scanned
        treadmill.from_space_next = alive_nodes_scanned;

        // flip
        if treadmill.from == 0 {
            treadmill.from = 1;
            treadmill.to   = 0;
        } else {
            treadmill.from = 0;
            treadmill.to   = 1;
        }

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
        // sort from_space from from_space_next so contiguous blocks are together (easier to allocate)
        let from = treadmill.from;
        let ref mut from_space = treadmill.spaces[from];

        // we do not care about alive nodes in from space
        for start in alive_nodes_scanned..from_space.len() {
            let first = {
                let mut ret = start;
                for i in start..from_space.len() {
                    if from_space[i].payload < from_space[ret].payload {
                        ret = i;
                    }
                }
                ret
            };

            if first != start {
                let block = from_space.remove(first);
                from_space.insert(start, block);
            }
        }

207 208 209 210 211 212
        if cfg!(debug_assertions) {
            debug!("---tread mill space---");
            debug!("total nodes scanned: {}", nodes_scanned);
            debug!("alive nodes scanned: {}", alive_nodes_scanned);
            debug!("free  nodes scanned: {}", free_nodes_scanned);
        }
qinsoon's avatar
qinsoon committed
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
use heap::Space;

impl Space for FreeListSpace {
    #[inline(always)]
    fn start(&self) -> Address {
        self.start
    }

    #[inline(always)]
    fn end(&self) -> Address {
        self.end
    }

    #[inline(always)]
    fn alloc_map(&self) -> *mut u8 {
        self.alloc_map.ptr
    }

    #[inline(always)]
    fn trace_map(&self) -> *mut u8 {
        self.trace_map.ptr
    }
}

unsafe impl Sync for FreeListSpace {}
unsafe impl Send for FreeListSpace {}

impl fmt::Display for FreeListSpace {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "FreeListSpace\n").unwrap();
        write!(f, "range={:#X} ~ {:#X}\n", self.start, self.end).unwrap();

        let treadmill : &Treadmill = &self.treadmill.lock().unwrap();
        write!(f, "treadmill: {}", treadmill)
    }
qinsoon's avatar
qinsoon committed
251 252
}

253
struct Treadmill{
254 255 256
    from_space_next : usize, // next available node in from_space
    from: usize,
    to  : usize,
257
    spaces      : [Vec<TreadmillNode>; 2]
258 259 260 261
}

impl Treadmill {
    fn new(start: Address, end: Address) -> Treadmill {
262
        let half_space = start + ((end - start) / 2);
qinsoon's avatar
qinsoon committed
263

264 265
        let mut from_space = vec![];
        let mut to_space   = vec![];
266

267 268 269
        let mut addr = start;

        while addr < half_space {
270
            from_space.push(TreadmillNode::new(addr));
271
            addr = addr + BLOCK_SIZE;
272
        }
qinsoon's avatar
qinsoon committed
273 274

        while addr < end {
275
            to_space.push(TreadmillNode::new(addr));
276
            addr = addr + BLOCK_SIZE;
qinsoon's avatar
qinsoon committed
277 278
        }

279
        Treadmill {
280 281 282 283
            from_space_next: 0,
            from: 0,
            to  : 1,
            spaces: [from_space, to_space]
284 285 286 287
        }
    }

    fn alloc_blocks(&mut self, n_blocks: usize) -> Address {
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
        match self.find_contiguous_blocks(n_blocks) {
            Some(start) => {
                if TRACE_TREADMILL {
                    trace!("found contiguous {} blocks, starting from {}", n_blocks, start);
                }

                let ref mut from_space = self.spaces[self.from];

                // zero blocks
                let return_address = from_space[start].payload;
                Treadmill::zeroing_blocks(return_address, n_blocks);

                if start != self.from_space_next {
                    // contiguous blocks are not next few ones
                    // we need to move the blocks

                    // take the allocated blocks out
                    let new_allocated = {
                        let mut ret = vec![];

                        for _ in 0..n_blocks {
                            let block = from_space.remove(start);

                            if TRACE_TREADMILL {
                                trace!("remove allocated block from from_space: {}", block);
                                trace!("from space: ");
                                for i in 0..from_space.len() {
                                    trace!("{}", from_space[i]);
                                }
                            }

                            ret.push(block);
                        }

                        ret
                    };

                    // insert back and mov cursor
                    let mut cursor = self.from_space_next;
                    for block in new_allocated {
                        if TRACE_TREADMILL {
                            trace!("insert block {} to from_space at {}", block, cursor);
                        }

                        from_space.insert(cursor, block);

                        if TRACE_TREADMILL {
                            trace!("from space: ");
                            for i in 0..from_space.len() {
                                trace!("{}", from_space[i]);
                            }
                        }

                        cursor += 1;
                    }
                    self.from_space_next = cursor;
                } else {
                    // just move cursor
                    self.from_space_next += n_blocks;
                }
348

349
                return_address
350
            }
351 352 353 354 355 356 357 358
            None => {
                if TRACE_TREADMILL {
                    trace!("cannot find {} contiguous blocks", n_blocks);
                }
                unsafe {Address::zero()}
            }
        }
    }
359

360 361 362 363 364 365 366 367 368 369 370 371 372
    fn find_contiguous_blocks(&mut self, n_blocks: usize) -> Option<usize> {
        // e.g. we have 10 blocks, and we require 3 blocks,
        // we wont be able to find contiguous blocks if starting block is more than 7 (only 8, 9 might be available)
        // 7 = 10 (total) - 3 (required)
        // Rust range is exclusive of the end, so we use (total - required + 1)

        // we can always assume contiguous blocks are arrange next to each other
        // since we will do a sort after GC

        // we do not have enough blocks (no need to check if they are contiguous
        if self.from_space_next + n_blocks > self.spaces[self.from].len() {
            return None;
        }
373

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
        for i in self.from_space_next..(self.spaces[self.from].len() - n_blocks + 1) {
            if self.has_contiguous_blocks_starting_at(n_blocks, i) {
                return Some(i);
            }
        }

        None
    }

    fn has_contiguous_blocks_starting_at(&mut self, n_blocks: usize, start: usize) -> bool {
        let ref from_space = self.spaces[self.from];

        if start + n_blocks > from_space.len() {
            // if we have fewer blocks than required, it is impossible to find required blocks
            false
389
        } else {
390 391 392 393 394
            // we need to check if next n_blocks are contiguous
            // e.g. we have 10 blocks, and we want to check if we have 3 contiguous blocks from #7
            // we need to check if 7&8, 8&9 (cursor is 7, and 8)
            let mut cursor = start;
            while cursor < start + n_blocks - 1 {
395
                if from_space[cursor].payload + BLOCK_SIZE != from_space[cursor + 1].payload {
396 397 398 399 400 401 402
                    return false;
                }

                cursor += 1;
            }

            true
403
        }
qinsoon's avatar
qinsoon committed
404
    }
405

406
    fn zeroing_blocks(start: Address, n_blocks: usize) {
407 408 409
        use utils::mem::memsec;

        unsafe {
410
            memsec::memzero(start.to_ptr_mut::<u8>(), BLOCK_SIZE * n_blocks);
411 412
        }
    }
qinsoon's avatar
qinsoon committed
413 414
}

415 416
impl fmt::Display for Treadmill {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
417
        write!(f, "next: {}\n", self.from_space_next).unwrap();
418 419 420 421
        write!(f, "from:").unwrap();
        for i in 0..self.spaces[self.from].len() {
            write!(f, "{}->", self.spaces[self.from][i]).unwrap();
        }
422
        write!(f, "\n").unwrap();
423 424 425
        write!(f, "to:").unwrap();
        for i in 0..self.spaces[self.to].len() {
            write!(f, "{}->", self.spaces[self.to][i]).unwrap();
426
        }
427
        Ok(())
428 429 430 431
    }
}

struct TreadmillNode {
432
    payload: Address
433 434 435
}

impl TreadmillNode {
436 437 438
    fn new(addr: Address) -> TreadmillNode {
        TreadmillNode {
            payload: addr
439 440
        }
    }
441
}
442

443

444 445 446
impl fmt::Display for TreadmillNode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.payload)
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::BLOCK_SIZE;

    #[test]
    fn test_new_treadmill_space() {
        let space = FreeListSpace::new(BLOCK_SIZE * 10);

        println!("{}", space);
    }

    #[test]
    fn test_treadmill_alloc() {
464
        let space = FreeListSpace::new(BLOCK_SIZE * 20);
465 466

        for i in 0..10 {
467
            let ret = space.alloc(BLOCK_SIZE / 2, 8);
468
            println!("Allocation{}: {}", i, ret);
469
            assert!(!ret.is_zero());
470 471 472 473 474
        }
    }

    #[test]
    fn test_treadmill_alloc_spanblock() {
475 476 477 478
        use simple_logger;
        simple_logger::init().unwrap();

        let space = FreeListSpace::new(BLOCK_SIZE * 20);
479 480

        for i in 0..5 {
481
            let ret = space.alloc(BLOCK_SIZE + BLOCK_SIZE / 2, 8);
482
            println!("Allocation{}: {}", i, ret);
483
            assert!(!ret.is_zero());
484 485 486 487
        }
    }

    #[test]
488 489 490
    fn test_treadmill_sweep() {
        use simple_logger;
        simple_logger::init().unwrap();
491

492 493 494 495
        let space = FreeListSpace::new(BLOCK_SIZE * 20);

        for i in 0..5 {
            let ret = space.alloc(BLOCK_SIZE + BLOCK_SIZE / 2, 8);
496
            println!("Allocation{}: {}", i, ret);
497
            assert!(!ret.is_zero());
498 499
        }
    }
500
}