Research GitLab has introduced a user quota limitation. The new rule limits each user to have 50 Gb. The quota doesn't restrict group projects. If you have any concern with this, please talk to CECS Gitlab Admin at N110 (b) CSIT building.

mod.rs 16.8 KB
Newer Older
qinsoon's avatar
qinsoon committed
1 2 3 4 5 6 7 8 9 10
use heap::immix::MUTATORS;
use heap::immix::N_MUTATORS;
use heap::immix::ImmixMutatorLocal;
use heap::immix::ImmixSpace;
use heap::immix::ImmixLineMarkTable;
use heap::freelist::FreeListSpace;
use objectmodel;

use common::AddressMap;
use utils::{Address, ObjectReference};
qinsoon's avatar
qinsoon committed
11
use utils::{LOG_POINTER_SIZE, POINTER_SIZE};
qinsoon's avatar
qinsoon committed
12
use utils::bit_utils;
13 14 15 16

use std::sync::atomic::{AtomicIsize, Ordering};
use std::sync::{Arc, Mutex, Condvar, RwLock};

qinsoon's avatar
qinsoon committed
17
#[cfg(feature = "parallel-gc")]
qinsoon's avatar
qinsoon committed
18
use crossbeam::sync::chase_lev::*;
qinsoon's avatar
qinsoon committed
19
#[cfg(feature = "parallel-gc")]
20
use std::sync::mpsc;
qinsoon's avatar
qinsoon committed
21
#[cfg(feature = "parallel-gc")]
22
use std::sync::mpsc::channel;
qinsoon's avatar
qinsoon committed
23
#[cfg(feature = "parallel-gc")]
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
use std::thread;

use std::sync::atomic;

lazy_static! {
    static ref STW_COND : Arc<(Mutex<usize>, Condvar)> = {
        Arc::new((Mutex::new(0), Condvar::new()))
    };
    
    static ref GET_ROOTS : RwLock<Box<Fn()->Vec<ObjectReference> + Sync + Send>> = RwLock::new(Box::new(get_roots));
    
    static ref GC_CONTEXT : RwLock<GCContext> = RwLock::new(GCContext{immix_space: None, lo_space: None});
    
    static ref ROOTS : RwLock<Vec<ObjectReference>> = RwLock::new(vec![]);
}

static CONTROLLER : AtomicIsize = atomic::ATOMIC_ISIZE_INIT;
const  NO_CONTROLLER : isize    = -1;

pub struct GCContext {
    immix_space : Option<Arc<ImmixSpace>>,
    lo_space    : Option<Arc<RwLock<FreeListSpace>>>
}

fn get_roots() -> Vec<ObjectReference> {
    vec![]
}

pub fn init(immix_space: Arc<ImmixSpace>, lo_space: Arc<RwLock<FreeListSpace>>) {
    CONTROLLER.store(NO_CONTROLLER, Ordering::SeqCst);
    let mut gccontext = GC_CONTEXT.write().unwrap();
    gccontext.immix_space = Some(immix_space);
    gccontext.lo_space = Some(lo_space);
}

pub fn init_get_roots(get_roots: Box<Fn()->Vec<ObjectReference> + Sync + Send>) {
    *GET_ROOTS.write().unwrap() = get_roots;
}

pub fn trigger_gc() {
    trace!("Triggering GC...");
    
    for mut m in MUTATORS.write().unwrap().iter_mut() {
        if m.is_some() {
            m.as_mut().unwrap().set_take_yield(true);
        }
    }
}

use std::os::raw::c_void;
#[cfg(target_arch = "x86_64")]
#[link(name = "gc_clib_x64")]
extern "C" {
    pub fn malloc_zero(size: usize) -> *const c_void;
    fn immmix_get_stack_ptr() -> Address;
    pub fn set_low_water_mark();
    fn get_low_water_mark() -> Address;
    fn get_registers() -> *const Address;
    fn get_registers_count() -> i32;
}

#[inline(always)]
qinsoon's avatar
qinsoon committed
86
pub fn is_valid_object(addr: Address, start: Address, end: Address, live_map: *mut u8) -> bool {
87 88 89 90
    if addr >= end || addr < start {
        return false;
    }
    
qinsoon's avatar
qinsoon committed
91 92 93
    let index = (addr.diff(start) >> LOG_POINTER_SIZE) as isize;
    
    bit_utils::test_nth_bit(unsafe {*live_map.offset(index)}, objectmodel::OBJ_START_BIT)
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
}

pub fn stack_scan() -> Vec<ObjectReference> {
    let stack_ptr : Address = unsafe {immmix_get_stack_ptr()};
    let low_water_mark : Address = unsafe {get_low_water_mark()};
    
    let mut cursor = stack_ptr;
    let mut ret = vec![];
    
    let gccontext = GC_CONTEXT.read().unwrap();
    let immix_space = gccontext.immix_space.as_ref().unwrap();
    
    while cursor < low_water_mark {
        let value : Address = unsafe {cursor.load::<Address>()};
        
qinsoon's avatar
qinsoon committed
109
        if is_valid_object(value, immix_space.start(), immix_space.end(), immix_space.alloc_map.ptr) {
110 111 112
            ret.push(unsafe {value.to_object_reference()});
        }
        
qinsoon's avatar
qinsoon committed
113
        cursor = cursor.plus(POINTER_SIZE);
114 115 116 117 118 119 120 121 122 123
    }
    
    let roots_from_stack = ret.len();
    
    let registers_count = unsafe {get_registers_count()};
    let registers = unsafe {get_registers()};
    
    for i in 0..registers_count {
        let value = unsafe {*registers.offset(i as isize)};
        
qinsoon's avatar
qinsoon committed
124
        if is_valid_object(value, immix_space.start(), immix_space.end(), immix_space.alloc_map.ptr) {
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
            ret.push(unsafe {value.to_object_reference()});
        }
    }
    
    let roots_from_registers = ret.len() - roots_from_stack;
    
    trace!("roots: {} from stack, {} from registers", roots_from_stack, roots_from_registers);
    
    ret
}

#[inline(never)]
pub fn sync_barrier(mutator: &mut ImmixMutatorLocal) {
    let controller_id = CONTROLLER.compare_and_swap(-1, mutator.id() as isize, Ordering::SeqCst);
    
    trace!("Mutator{} saw the controller is {}", mutator.id(), controller_id);
    
    // prepare the mutator for gc - return current block (if it has)
    mutator.prepare_for_gc();
    
    // scan its stack
    let mut thread_roots = stack_scan();
    ROOTS.write().unwrap().append(&mut thread_roots);
    
    // user thread call back to prepare for gc
//    USER_THREAD_PREPARE_FOR_GC.read().unwrap()();
    
    if controller_id != NO_CONTROLLER {
        // this thread will block
        block_current_thread(mutator);
        
        // reset current mutator
        mutator.reset();
    } else {
        // this thread is controller
        // other threads should block
        
        // wait for all mutators to be blocked
        let &(ref lock, ref cvar) = &*STW_COND.clone();
        let mut count = 0;
        
        trace!("expect {} mutators to park", *N_MUTATORS.read().unwrap() - 1);
        while count < *N_MUTATORS.read().unwrap() - 1 {
            let new_count = {*lock.lock().unwrap()};
            if new_count != count {				
                count = new_count;
                trace!("count = {}", count);
            }
        }
        
        trace!("everyone stopped, gc will start");
        
        // roots->trace->sweep
        gc();
        
        // mutators will resume
        CONTROLLER.store(NO_CONTROLLER, Ordering::SeqCst);
        for mut t in MUTATORS.write().unwrap().iter_mut() {
            if t.is_some() {
                let t_mut = t.as_mut().unwrap();
                t_mut.set_take_yield(false);
                t_mut.set_still_blocked(false);
            }
        }
        // every mutator thread will reset themselves, so only reset current mutator here
        mutator.reset();

        // resume
        {
            let mut count = lock.lock().unwrap();
            *count = 0;
            cvar.notify_all();
        }
    }
}

fn block_current_thread(mutator: &mut ImmixMutatorLocal) {
    trace!("Mutator{} blocked", mutator.id());
    
    let &(ref lock, ref cvar) = &*STW_COND.clone();
    let mut count = lock.lock().unwrap();
    *count += 1;
    
    mutator.global.set_still_blocked(true);
    
    while mutator.global.is_still_blocked() {
        count = cvar.wait(count).unwrap();
    }
    
    trace!("Mutator{} unblocked", mutator.id());
}

pub static GC_COUNT : atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT;

fn gc() {
    GC_COUNT.store(GC_COUNT.load(atomic::Ordering::SeqCst) + 1, atomic::Ordering::SeqCst);
    
    trace!("GC starts");
    
    // creates root deque
    let mut roots : &mut Vec<ObjectReference> = &mut ROOTS.write().unwrap();
    
    // mark & trace
    {
        let gccontext = GC_CONTEXT.read().unwrap();
        let (immix_space, lo_space) = (gccontext.immix_space.as_ref().unwrap(), gccontext.lo_space.as_ref().unwrap());
        
        start_trace(&mut roots, immix_space.clone(), lo_space.clone());
    }
    
    trace!("trace done");
    
    // sweep
    {
        let mut gccontext = GC_CONTEXT.write().unwrap();
        let immix_space = gccontext.immix_space.as_mut().unwrap();
        
        immix_space.sweep();
    }
    
    objectmodel::flip_mark_state();
    trace!("GC finishes");
}

pub const MULTI_THREAD_TRACE_THRESHOLD : usize = 10;

pub const PUSH_BACK_THRESHOLD : usize = 50;
pub static GC_THREADS : atomic::AtomicUsize = atomic::ATOMIC_USIZE_INIT;

#[allow(unused_variables)]
#[inline(never)]
qinsoon's avatar
qinsoon committed
256
#[cfg(feature = "parallel-gc")]
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
pub fn start_trace(work_stack: &mut Vec<ObjectReference>, immix_space: Arc<ImmixSpace>, lo_space: Arc<RwLock<FreeListSpace>>) {
    // creates root deque
    let (mut worker, stealer) = deque();
    
    while !work_stack.is_empty() {
        worker.push(work_stack.pop().unwrap());
    }

    loop {
        let (sender, receiver) = channel::<ObjectReference>();        
        
        let mut gc_threads = vec![];
        for _ in 0..GC_THREADS.load(atomic::Ordering::SeqCst) {
            let new_immix_space = immix_space.clone();
            let new_lo_space = lo_space.clone();
            let new_stealer = stealer.clone();
            let new_sender = sender.clone();
            let t = thread::spawn(move || {
                start_steal_trace(new_stealer, new_sender, new_immix_space, new_lo_space);
            });
            gc_threads.push(t);
        }
        
        // only stealers own sender, when all stealers quit, the following loop finishes
        drop(sender);
        
        loop {
            let recv = receiver.recv();
            match recv {
                Ok(obj) => worker.push(obj),
                Err(_) => break
            }
        }
        
        match worker.try_pop() {
            Some(obj_ref) => worker.push(obj_ref),
            None => break
        }
    }
}

#[allow(unused_variables)]
#[inline(never)]
qinsoon's avatar
qinsoon committed
300
#[cfg(not(feature = "parallel-gc"))]
301 302 303 304 305 306 307 308 309
pub fn start_trace(local_queue: &mut Vec<ObjectReference>, immix_space: Arc<ImmixSpace>, lo_space: Arc<RwLock<FreeListSpace>>) {
    let mark_state = objectmodel::MARK_STATE.load(Ordering::SeqCst) as u8;
    
    while !local_queue.is_empty() {
        trace_object(local_queue.pop().unwrap(), local_queue, immix_space.alloc_map.ptr, immix_space.trace_map.ptr, &immix_space.line_mark_table, immix_space.start(), immix_space.end(), mark_state);
    }    
}

#[allow(unused_variables)]
qinsoon's avatar
qinsoon committed
310
#[cfg(feature = "parallel-gc")]
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
fn start_steal_trace(stealer: Stealer<ObjectReference>, job_sender:mpsc::Sender<ObjectReference>, immix_space: Arc<ImmixSpace>, lo_space: Arc<RwLock<FreeListSpace>>) {
    use objectmodel;
    
    let mut local_queue = vec![];
    
    let line_mark_table = &immix_space.line_mark_table;
    let (alloc_map, trace_map) = (immix_space.alloc_map.ptr, immix_space.trace_map.ptr);
    let (space_start, space_end) = (immix_space.start(), immix_space.end());
    let mark_state = objectmodel::MARK_STATE.load(Ordering::SeqCst) as u8;
    
    loop {
        let work = {
            if !local_queue.is_empty() {
                local_queue.pop().unwrap()
            } else {
                let work = stealer.steal();
                match work {
                    Steal::Empty => return,
                    Steal::Abort => continue,
                    Steal::Data(obj) => obj
                }
            }
        };
        
        steal_trace_object(work, &mut local_queue, &job_sender, alloc_map, trace_map, line_mark_table, space_start, space_end, mark_state, &lo_space);
    }
} 

#[inline(always)]
qinsoon's avatar
qinsoon committed
340
#[cfg(feature = "parallel-gc")]
341
pub fn steal_trace_object(obj: ObjectReference, local_queue: &mut Vec<ObjectReference>, job_sender: &mpsc::Sender<ObjectReference>, alloc_map: *mut u8, trace_map: *mut u8, line_mark_table: &ImmixLineMarkTable, immix_start: Address, immix_end: Address, mark_state: u8, lo_space: &Arc<RwLock<FreeListSpace>>) {
qinsoon's avatar
qinsoon committed
342 343 344 345 346 347 348 349 350 351 352 353
    if cfg!(debug_assertions) {
        // check if this object in within the heap, if it is an object
        if !is_valid_object(obj.to_address(), immix_start, immix_end, alloc_map) {
            println!("trying to trace an object that is not valid");
            println!("address: 0x{:x}", obj);
            println!("---");
            println!("immix space: 0x{:x} - 0x{:x}", immix_start, immix_end);
            println!("lo space: {}", *lo_space.read().unwrap());
            
            panic!("invalid object during tracing");
        }
    }
354 355 356 357 358 359 360 361 362 363 364 365 366 367
    
    objectmodel::mark_as_traced(trace_map, immix_start, obj, mark_state);
    
    let addr = obj.to_address();
    
    if addr >= immix_start && addr < immix_end {
        line_mark_table.mark_line_live(addr);        
    } else {
        // freelist mark
    }
    
    let mut base = addr;
    loop {
        let value = objectmodel::get_ref_byte(alloc_map, immix_start, obj);
qinsoon's avatar
qinsoon committed
368
        let (ref_bits, short_encode) = (bit_utils::lower_bits(value, objectmodel::REF_BITS_LEN), bit_utils::test_nth_bit(value, objectmodel::SHORT_ENCODE_BIT));
369 370
        match ref_bits {
            0b0000_0001 => {
qinsoon's avatar
qinsoon committed
371
                steal_process_edge(base, 0, local_queue, alloc_map, trace_map, immix_start, immix_end, job_sender, mark_state);
372 373
            },            
            0b0000_0011 => {
qinsoon's avatar
qinsoon committed
374 375
                steal_process_edge(base, 0, local_queue, alloc_map, trace_map, immix_start, immix_end, job_sender, mark_state);
                steal_process_edge(base, 8, local_queue, alloc_map, trace_map, immix_start, immix_end, job_sender, mark_state);
376 377
            },
            0b0000_1111 => {
qinsoon's avatar
qinsoon committed
378 379 380 381
                steal_process_edge(base, 0, local_queue, alloc_map, trace_map, immix_start, immix_end, job_sender, mark_state);
                steal_process_edge(base, 8, local_queue, alloc_map, trace_map, immix_start, immix_end, job_sender, mark_state);
                steal_process_edge(base, 16,local_queue, alloc_map, trace_map, immix_start, immix_end, job_sender, mark_state);
                steal_process_edge(base, 24,local_queue, alloc_map, trace_map, immix_start, immix_end, job_sender, mark_state);                
382 383 384 385 386 387 388 389 390 391
            },            
            _ => {
                panic!("unexpcted ref_bits patterns: {:b}", ref_bits);
            }
        }
        
        assert!(short_encode);
        if short_encode {
            return;
        } else {
qinsoon's avatar
qinsoon committed
392
            base = base.plus(objectmodel::REF_BITS_LEN * POINTER_SIZE);
393 394 395 396 397
        } 
    }
}

#[inline(always)]
qinsoon's avatar
qinsoon committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
#[cfg(feature = "parallel-gc")]
pub fn steal_process_edge(base: Address, offset: usize, local_queue:&mut Vec<ObjectReference>, alloc_map: *mut u8, trace_map: *mut u8, immix_start: Address, immix_end: Address, job_sender: &mpsc::Sender<ObjectReference>, mark_state: u8) {
    let field_addr = base.plus(offset);
    let edge = unsafe{field_addr.load::<ObjectReference>()};
    
    if cfg!(debug_assertions) {
        // check if this object in within the heap, if it is an object
        if !is_valid_object(edge.to_address(), immix_start, immix_end, alloc_map) {
            println!("trying to follow an edge that is not a valid object");
            println!("edge address: 0x{:x}", edge);
            println!("base address: 0x{:x}", base);
            println!("---");
            objectmodel::print_object(base, immix_start, trace_map, alloc_map);
            println!("---");
            println!("immix space: 0x{:x} - 0x{:x}", immix_start, immix_end);
            
            panic!("invalid object during tracing");
        }
    }
417

qinsoon's avatar
qinsoon committed
418
    if !edge.to_address().is_zero() && !objectmodel::is_traced(trace_map, immix_start, edge, mark_state) {
419
        if local_queue.len() >= PUSH_BACK_THRESHOLD {
qinsoon's avatar
qinsoon committed
420
            job_sender.send(edge).unwrap();
421
        } else {
qinsoon's avatar
qinsoon committed
422
            local_queue.push(edge);
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
        }
    } 
}

#[inline(always)]
pub fn trace_object(obj: ObjectReference, local_queue: &mut Vec<ObjectReference>, alloc_map: *mut u8, trace_map: *mut u8, line_mark_table: &ImmixLineMarkTable, immix_start: Address, immix_end: Address, mark_state: u8) {
    objectmodel::mark_as_traced(trace_map, immix_start, obj, mark_state);

    let addr = obj.to_address();
    
    if addr >= immix_start && addr < immix_end {
        line_mark_table.mark_line_live(addr);        
    } else {
        // freelist mark
    }
    
    let mut base = addr;
    loop {
        let value = objectmodel::get_ref_byte(alloc_map, immix_start, obj);
qinsoon's avatar
qinsoon committed
442
        let (ref_bits, short_encode) = (bit_utils::lower_bits(value, objectmodel::REF_BITS_LEN), bit_utils::test_nth_bit(value, objectmodel::SHORT_ENCODE_BIT));
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
        
        match ref_bits {
            0b0000_0001 => {
                process_edge(base, local_queue, trace_map, immix_start, mark_state);
            },            
            0b0000_0011 => {
                process_edge(base, local_queue, trace_map, immix_start, mark_state);
                process_edge(base.plus(8), local_queue, trace_map, immix_start, mark_state);
            },
            0b0000_1111 => {
                process_edge(base, local_queue, trace_map, immix_start, mark_state);
                process_edge(base.plus(8), local_queue, trace_map, immix_start, mark_state);
                process_edge(base.plus(16), local_queue, trace_map, immix_start, mark_state);
                process_edge(base.plus(24), local_queue, trace_map, immix_start, mark_state);                
            },
            _ => {
                panic!("unexpcted ref_bits patterns: {:b}", ref_bits);
            }
        }
        
        debug_assert!(short_encode);
        if short_encode {
            return;
        } else {
            base = base.plus(objectmodel::REF_BITS_LEN * 8);
        } 
    }
}

#[inline(always)]
pub fn process_edge(addr: Address, local_queue:&mut Vec<ObjectReference>, trace_map: *mut u8, space_start: Address, mark_state: u8) {
    let obj_addr : ObjectReference = unsafe{addr.load()};

    if !obj_addr.to_address().is_zero() && !objectmodel::is_traced(trace_map, space_start, obj_addr, mark_state) {
        local_queue.push(obj_addr);
    }
}