Skip to content

Commit

Permalink
spinlock in BinAllocator
Browse files Browse the repository at this point in the history
Signed-off-by: smallkirby <ssmallkirby@gmail.com>
  • Loading branch information
smallkirby committed Aug 17, 2024
1 parent dd8b0e7 commit 9adfa03
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
11 changes: 11 additions & 0 deletions ymir/mem/BinAllocator.zig
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

const std = @import("std");
const Allocator = std.mem.Allocator;
const spin = @import("ymir").spin;

const Self = @This();

Expand All @@ -28,19 +29,23 @@ comptime {
page_allocator: Allocator,
/// Heads of the chunk lists.
list_heads: [bin_sizes.len]ChunkMetaPointer,
/// Spin lock.
lock: spin.SpinLock = spin.SpinLock{},

/// Get a instance of BinAllocator without initialization.
pub fn newUninit() Self {
return Self{
.page_allocator = undefined,
.list_heads = undefined,
.lock = spin.SpinLock{},
};
}

/// Initialize the BinAllocator.
pub fn init(self: *Self, page_allocator: Allocator) void {
self.page_allocator = page_allocator;
@memset(self.list_heads[0..self.list_heads.len], null);
self.lock = spin.SpinLock{};
}

/// Get the bin index for the given size.
Expand All @@ -55,13 +60,19 @@ fn binIndex(size: usize) ?usize {
}

fn allocFromBin(self: *Self, bin_index: usize) ?[*]u8 {
self.lock.lockDisableIrq();
defer self.lock.unlockEnableIrq();

if (self.list_heads[bin_index] == null) {
initBinPage(self, bin_index) orelse return null;
}
return @ptrCast(pop(&self.list_heads[bin_index]));
}

fn freeToBin(self: *Self, bin_index: usize, ptr: [*]u8) void {
self.lock.lockDisableIrq();
defer self.lock.unlockEnableIrq();

const chunk: *ChunkMetaNode = @alignCast(@ptrCast(ptr));
push(&self.list_heads[bin_index], chunk);
}
Expand Down
6 changes: 4 additions & 2 deletions ymir/spin.zig
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const is_test = @import("builtin").is_test;

const ymir = @import("ymir");
const arch = ymir.arch;

Expand Down Expand Up @@ -25,7 +27,7 @@ pub const SpinLock = struct {
/// Must be paired with `unlockEnableIrq()`.
pub inline fn lockDisableIrq(self: *SpinLock) void {
self.lock();
arch.disableIntr();
if (!is_test) arch.disableIntr();
}

/// Unlock the spin lock.
Expand All @@ -43,6 +45,6 @@ pub const SpinLock = struct {
/// Unlock the spin lock and enable interrupts.
pub inline fn unlockEnableIrq(self: *SpinLock) void {
self.unlock();
arch.enableIntr();
if (!is_test) arch.enableIntr();
}
};

0 comments on commit 9adfa03

Please sign in to comment.