// BozoEngine's EE kernel. See bozo/ee/kernel.h and docs/specs/kernel.md. #include "bozo/ee/kernel.h" #include "bozo/runtime.h" #include #include #include #include namespace bozo::ee { namespace { constexpr uint64_t kEeClock = 294'912'000ull; // The vblank (INTC cause 2) starts every field; its end (cause 3) follows 147,456 EE cycles later (half a // millisecond: the reference's model, from the boot log's idle stretches). constexpr uint64_t kVblankLength = 147'456ull; constexpr uint32_t kIntcVblankStart = 2, kIntcVblankEnd = 3; constexpr uint32_t kAlarmKeys = 0x80000000u; // the deadline keys alarms own uint64_t fieldCycles(uint32_t numerator, uint32_t denominator) { return numerator ? kEeClock * denominator / numerator : 0; } } const char *opName(uint32_t op) { static const char *const names[] = { "?", "queue", "block", "wake", "irq", "task", "event", "create", "start", "exit", "terminate", "priority", "rotate", "suspend", "resume", "wakeup", "cancel-wakeup", "release-wait", "sema-create", "sema-delete", "signal", "poll-sema", "wait-sema", "flag-create", "flag-delete", "flag-set", "flag-clear", "flag-poll", "flag-wait", "alarm-set", "alarm-cancel", "handler-add", "handler-remove", "handler-enable", "cause-enable", "vsync-flag", "gs-vsync-callback", "field-rate", "thread-setup", "transfer", "deadline-set", "deadline-cancel"}; return op < kOpCount ? names[op] : "?"; } Kernel::Kernel() { fieldCycles_ = fieldCycles(60000, 1001); // NTSC until the game sets its field rate nextStart_ = fieldCycles_; nextEnd_ = nextStart_ + kVblankLength; } void Kernel::emit(uint32_t op, std::initializer_list args, uint64_t wide) { OpEvent e; e.op = op; e.origin = origin_; e.depth = depth_; e.originCall = origin_ == kOriginCall ? originCall_ : kNoCall; e.wide = wide; for (uint32_t a : args) if (e.argc < 16) e.args[e.argc++] = a; e.thread = running_; (observer_ ? observer_ : &defaultObserver_)->op(e); } Thread *Kernel::thread(int32_t id) { auto it = threads_.find(id); return it == threads_.end() ? nullptr : it->second.get(); } // The ready queues hold the ready threads; the running thread is outside them (calllog: a thread that gives way // goes to the tail of its queue, behind the threads already there). void Kernel::noteQueue(uint32_t p) { const uint64_t bit = 1ull << (p & 63u); if (ready_[p].empty()) readyMask_[p >> 6] &= ~bit; else readyMask_[p >> 6] |= bit; } int32_t Kernel::firstReady() const { // The lowest non-empty queue, by the mask of non-empty queues (the dispatcher asks at every pick, and at every // transfer: scanning 128 queues was ~2.5% of a 1P match's game thread). if (readyMask_[0]) return ready_[std::countr_zero(readyMask_[0])].front(); if (readyMask_[1]) return ready_[64 + std::countr_zero(readyMask_[1])].front(); return 0; } int32_t Kernel::best() const { const int32_t head = firstReady(); if (running_ > 0) if (const Thread *r = threads_.count(running_) ? threads_.at(running_).get() : nullptr; r && r->state == ThreadState::Running) { if (!head || threads_.at(head)->priority >= r->priority) return running_; } return head; } bool Kernel::sliceContender() const { auto it = threads_.find(running_); if (running_ <= 0 || it == threads_.end() || it->second->state != ThreadState::Running) return false; const uint32_t p = it->second->priority % kPriorities; // any non-empty queue at p or below if (p < 64) return (readyMask_[0] & (p == 63 ? ~0ull : (2ull << p) - 1u)) != 0; return readyMask_[0] != 0 || (readyMask_[1] & (p == 127 ? ~0ull : (2ull << (p - 64)) - 1u)) != 0; } void Kernel::runOrder(std::vector &out) const { out.clear(); out.push_back(running_); for (const auto &q : ready_) for (int32_t id : q) out.push_back(id); } namespace { void freshContext(Frame &f) { f.ctx = R5900Context(); f.ctx.vu0_q_bits = kOne; f.status = kFreshStatus; f.last.fill(0); f.ran = false; f.parkedStack = 0; } } void Kernel::boot(uint32_t entry, uint32_t sp) { auto t = std::make_unique(); t->id = 1; t->state = ThreadState::Running; t->priority = t->initPriority = 0; auto f = std::make_unique(); freshContext(*f); f->ctx.r[29].ud[0] = sp; f->ctx.pc = entry; f->ctx.vu0_r = kOne; t->frames.push_back(std::move(f)); running_ = 1; threads_[1] = std::move(t); } void Kernel::makeReady(Thread &t) { t.state = ThreadState::Ready; ready_[t.priority % kPriorities].push_back(t.id); noteQueue(t.priority % kPriorities); } void Kernel::removeFromQueue(Thread &t) { auto &q = ready_[t.priority % kPriorities]; q.erase(std::remove(q.begin(), q.end(), t.id), q.end()); noteQueue(t.priority % kPriorities); } void Kernel::deschedule(bool toTail) { if (running_ == 0) return; if (Thread *t = thread(running_); t && t->state == ThreadState::Running) { t->state = ThreadState::Ready; if (!t->pseudo) { auto &q = ready_[t->priority % kPriorities]; if (toTail) q.push_back(t->id); else q.push_front(t->id); noteQueue(t->priority % kPriorities); } } running_ = 0; } void Kernel::setRunning(int32_t id) { if (running_ == id) return; deschedule(false); // preempted: it runs again before the threads of its priority running_ = id; ++picks_; if (Thread *t = thread(id); t && (t->state == ThreadState::Ready || t->pseudo)) { removeFromQueue(*t); t->state = ThreadState::Running; } } // ---- Threads ----------------------------------------------------------------------------------------------- int32_t Kernel::createThread(uint32_t entry, uint32_t stack, uint32_t stackSize, uint32_t priority, uint32_t gp, uint32_t attr, uint32_t option) { int32_t id = 2; if (!threads_.empty()) id = std::max(id, threads_.rbegin()->first + 1); id = std::max(id, nextThreadId_); nextThreadId_ = id + 1; emit(kOpCreate, {static_cast(id), entry, stack, stackSize, priority, gp, attr, option}); auto t = std::make_unique(); t->id = id; t->entry = entry; t->stack = stack; t->stackSize = stackSize; t->priority = t->initPriority = priority; t->gp = gp; t->attr = attr; t->option = option; t->frames.push_back(std::make_unique()); threads_[id] = std::move(t); return id; } int32_t Kernel::startThread(int32_t id, uint32_t arg, bool interruptSafe) { Thread *t = thread(id); if (!t || t->state != ThreadState::Dormant) return -405; // KE_NOT_DORMANT emit(kOpStart, {static_cast(id), arg, interruptSafe ? 1u : 0u}); t->arg = arg; t->wakeupCount = 0; t->priority = t->initPriority; t->frames.resize(1); Frame &f = *t->frames[0]; freshContext(f); f.ctx.r[4].sd[0] = static_cast(arg); f.ctx.r[28].sd[0] = static_cast(t->gp); f.ctx.r[29].sd[0] = static_cast(t->stack + t->stackSize); f.ctx.pc = t->entry; makeReady(*t); return id; } void Kernel::exitThread(int32_t id, bool deleted) { Thread *t = thread(id); if (!t) return; emit(kOpExit, {static_cast(id), deleted ? 1u : 0u}); removeFromQueue(*t); t->state = ThreadState::Dormant; if (running_ == id) running_ = 0; if (deleted) threads_.erase(id); } int32_t Kernel::terminateThread(int32_t id, bool deleted, bool interruptSafe) { Thread *t = thread(id); if (!t) return -407; // KE_UNKNOWN_THID (match4p #11334755: TerminateThread of a thread that was never made) if (t->state == ThreadState::Dormant) return -413; // KE_DORMANT (calllog: TerminateThread of a thread that has ended) emit(kOpTerminate, {static_cast(id), deleted ? 1u : 0u, interruptSafe ? 1u : 0u}); removeFromQueue(*t); t->state = ThreadState::Dormant; t->frames.resize(1); if (running_ == id) running_ = 0; if (deleted) threads_.erase(id); return 0; // calllog: TerminateThread returns 0 } int32_t Kernel::deleteThread(int32_t id, bool) { Thread *t = thread(id); if (!t) return -407; // KE_UNKNOWN_THID (match4p #11334756) if (t->state != ThreadState::Dormant) return -405; emit(kOpTerminate, {static_cast(id), 1u}); threads_.erase(id); return 0; // calllog: DeleteThread returns 0 } int32_t Kernel::changePriority(int32_t id, uint32_t priority, bool interruptSafe) { emit(kOpPriority, {static_cast(id), priority, interruptSafe ? 1u : 0u}); Thread *t = thread(id == 0 ? running_ : id); if (!t) return -406; const int32_t old = static_cast(t->priority); if (t->state == ThreadState::Ready) { removeFromQueue(*t); t->priority = priority; ready_[priority % kPriorities].push_back(t->id); noteQueue(priority % kPriorities); } else t->priority = priority; return old; } int32_t Kernel::rotateReadyQueue(uint32_t priority, bool interruptSafe) { emit(kOpRotate, {priority, interruptSafe ? 1u : 0u}); // Rotating the running thread's own priority: it gives way at the next transfer, to the tail of its queue // (even when it is alone there: the dispatcher then picks it again). Another priority: the head of that // queue goes to its tail. if (Thread *t = thread(running_); t && t->state == ThreadState::Running && t->priority == priority % kPriorities) switchRequested_ = true; else if (auto &q = ready_[priority % kPriorities]; q.size() > 1) { q.push_back(q.front()); q.pop_front(); } // 0 (KE_OK), as the reference answers it (boot #228421: v0 0 after the rotations TMB makes, all through its // switchThread override; none has v0 the priority). return 0; } int32_t Kernel::sleepThread() { Thread *t = thread(running_); if (!t || t->depth() != 0) return -1; // SleepThread is a thread-context operation. if (t->wakeupCount != 0) t->wakeupCount = static_cast(static_cast(t->wakeupCount) - 1u); else block(t->id, kWaitSleep, 0, 0, 0, false, 0, 0); return 0; } int32_t Kernel::wakeupThread(int32_t id, bool interruptSafe) { if (id == 0 || id == running_) return -406; // KE_ILLEGAL_THID: the SDK wrapper disallows self wakeup. Thread *t = thread(id); if (!t) return -407; // KE_UNKNOWN_THID if (t->state == ThreadState::Dormant) return -413; // KE_DORMANT emit(kOpWakeup, {static_cast(id), interruptSafe ? 1u : 0u}); Nested n(*this); if ((t->state == ThreadState::Waiting || t->state == ThreadState::WaitSuspended) && t->waitReason == kWaitSleep) wake(id, 0, false, kWaitSleep); else t->wakeupCount = static_cast(static_cast(t->wakeupCount) + 1u); return id; // SDK ABI returns the target id on success. } int32_t Kernel::cancelWakeupThread(int32_t id, bool interruptSafe) { Thread *t = thread(id == 0 ? running_ : id); if (!t) return -407; emit(kOpCancelWakeup, {static_cast(id), interruptSafe ? 1u : 0u}); const int32_t count = t->wakeupCount; t->wakeupCount = 0; return count; } int32_t Kernel::suspendThread(int32_t id, bool interruptSafe) { if (id == 0 || id == running_) return -406; // KE_ILLEGAL_THID Thread *t = thread(id); if (!t) return -407; // KE_UNKNOWN_THID if (t->state == ThreadState::Dormant) return -413; // KE_DORMANT emit(kOpSuspend, {static_cast(id), interruptSafe ? 1u : 0u}); if (t->state == ThreadState::Ready) { removeFromQueue(*t); t->state = ThreadState::Suspended; } else if (t->state == ThreadState::Waiting) t->state = ThreadState::WaitSuspended; return id; } int32_t Kernel::resumeThread(int32_t id, bool interruptSafe) { if (id == 0 || id == running_) return -406; // KE_ILLEGAL_THID Thread *t = thread(id); if (!t) return -407; // KE_UNKNOWN_THID if (t->state != ThreadState::Suspended && t->state != ThreadState::WaitSuspended) return -415; // KE_NOT_SUSPEND emit(kOpResume, {static_cast(id), interruptSafe ? 1u : 0u}); if (t->state == ThreadState::WaitSuspended) t->state = ThreadState::Waiting; else makeReady(*t); return id; } void Kernel::block(int32_t id, uint32_t reason, uint32_t object, uint32_t bits, uint32_t mode, bool completion, uint64_t token, int32_t fixedResult) { emit(kOpBlock, {static_cast(id), reason, object, bits, mode, completion ? 1u : 0u}, token); Thread *t = thread(id); if (!t) return; removeFromQueue(*t); t->state = ThreadState::Waiting; t->waitReason = reason; t->waitObject = object; t->flagBits = bits; t->flagMode = mode; t->waitToken = token; t->fixedResult = fixedResult; t->waitCompletion = completion; if (running_ == id) running_ = 0; } void Kernel::wake(int32_t id, uint32_t result, bool completion, uint32_t reason) { emit(kOpWake, {static_cast(id), result, completion ? 1u : 0u, reason}); Thread *t = thread(id); if (!t || (t->state != ThreadState::Waiting && t->state != ThreadState::WaitSuspended)) return; const bool suspended = t->state == ThreadState::WaitSuspended; if (reason == kWaitSemaphore) if (Semaphore *s = sema(static_cast(t->waitObject))) s->waiters.erase(std::remove(s->waiters.begin(), s->waiters.end(), id), s->waiters.end()); t->top().ctx.r[2].sd[0] = static_cast(result); t->waitReason = kWaitNone; t->completionDue = completion; if (suspended) t->state = ThreadState::Suspended; else makeReady(*t); } // ---- Semaphores ---------------------------------------------------------------------------------------------- Semaphore *Kernel::sema(int32_t id) { auto it = semas_.find(id); return it == semas_.end() ? nullptr : &it->second; } int32_t Kernel::createSema(int32_t init, int32_t max, uint32_t attr, uint32_t option) { emit(kOpSemaCreate, {static_cast(init), static_cast(max), attr, option}); const int32_t id = nextSemaId_++; Semaphore &s = semas_[id]; s.id = id; s.count = s.init = init; s.max = max; s.attr = attr; s.option = option; return id; } int32_t Kernel::deleteSema(int32_t id, bool interruptSafe) { // The operation is made (and logged) for an unknown id too (match4p #11334775-6: DeleteSema(8) a second time, // -408 with its sema-delete operation). emit(kOpSemaDelete, {static_cast(id), interruptSafe ? 1u : 0u}); Semaphore *s = sema(id); if (!s) return -408; // KE_UNKNOWN_SEMID const std::deque waiters = s->waiters; semas_.erase(id); Nested n(*this); for (int32_t w : waiters) wake(w, static_cast(-425), false, kWaitSemaphore); // KE_WAIT_DELETE return id; } int32_t Kernel::signalSema(int32_t id, bool interruptSafe) { Semaphore *s = sema(id); if (!s) return -408; emit(kOpSignal, {static_cast(id), interruptSafe ? 1u : 0u}); if (!s->waiters.empty()) { const int32_t w = s->waiters.front(); Nested n(*this); wake(w, static_cast(id), false, kWaitSemaphore); } else ++s->count; return id; } int32_t Kernel::waitSema(int32_t id) { Semaphore *s = sema(id); if (!s) return -408; emit(kOpWaitSema, {static_cast(id)}); if (s->count > 0) { --s->count; return id; } s->waiters.push_back(running_); Nested n(*this); block(running_, kWaitSemaphore, static_cast(id), 0, 0, false, 0, 0); return id; } int32_t Kernel::pollSema(int32_t id) { Semaphore *s = sema(id); if (!s) return -408; emit(kOpPollSema, {static_cast(id)}); if (s->count > 0) { --s->count; return id; } return -419; // KE_SEMA_ZERO } // ---- Interrupts -------------------------------------------------------------------------------------------- void Kernel::irq(bool dmac, uint32_t cause) { const uint32_t bit = 1u << (cause & 31u); const bool enabled = ((dmac ? dmacMask_ : intcMask_) & bit) != 0; emit(kOpIrq, {dmac ? 1u : 0u, cause, enabled ? 1u : 0u}); if (!enabled) { (dmac ? dmacPending_ : intcPending_) |= bit; return; } Nested n(*this); for (const InterruptHandler &h : (dmac ? dmac_ : intc_)[cause & 15u]) if (h.enabled) { QueuedHandler q; q.kind = kInvokeInterrupt; q.pc = h.pc; q.a[0] = cause; q.a[1] = h.arg; q.gp = h.gp; queue(q); } } int32_t Kernel::addHandler(bool dmac, uint32_t cause, uint32_t pc, int32_t next, uint32_t arg, uint32_t gp, uint32_t sp) { emit(kOpHandlerAdd, {dmac ? 1u : 0u, cause, pc, static_cast(next), arg, gp, sp}); InterruptHandler h; h.id = dmac ? nextDmacHandler_++ : nextIntcHandler_++; h.cause = cause; h.pc = pc; h.arg = arg; h.gp = gp; h.sp = sp; auto &list = (dmac ? dmac_ : intc_)[cause & 15u]; if (next == 0) list.insert(list.begin(), h); else list.push_back(h); return h.id; } int32_t Kernel::removeHandler(bool dmac, uint32_t cause, int32_t id) { emit(kOpHandlerRemove, {dmac ? 1u : 0u, cause, static_cast(id)}); auto &list = (dmac ? dmac_ : intc_)[cause & 15u]; const auto before = list.size(); list.erase(std::remove_if(list.begin(), list.end(), [&](const InterruptHandler &h) { return h.id == id; }), list.end()); // 0 whether or not it was there (match4p #11334761: the movie player torn down a second time removes its // DMAC handler 9 again; the reference answers 0). (void)before; return 0; } int32_t Kernel::causeEnable(bool dmac, uint32_t cause, bool on) { const uint32_t bit = 1u << (cause & 31u); uint32_t &mask = dmac ? dmacMask_ : intcMask_; const bool was = (mask & bit) != 0; emit(kOpCauseEnable, {dmac ? 1u : 0u, cause, on ? 1u : 0u}); mask = on ? (mask | bit) : (mask & ~bit); uint32_t &pending = dmac ? dmacPending_ : intcPending_; if (on && !was && (pending & bit)) { pending &= ~bit; KernelObserver *o = observer_ ? observer_ : &defaultObserver_; if (!dmac || o->dmacStatusSet(cause)) { Nested n(*this); irq(dmac, cause); } } (void)was; return 0; // calllog: EnableIntc/Dmac and DisableIntc/Dmac return 0 in every TMB record } void Kernel::queue(const QueuedHandler &h, int32_t thread) { QueuedHandler q = h; q.sequence = ++sequence_; // counted from 1 if (thread) handlerThreads_[q.sequence] = thread; emit(kOpQueue, {q.kind, q.pc, q.a[0], q.a[1], q.a[2], q.a[3], q.gp, q.sp, q.ra, q.completion ? 1u : 0u, static_cast(q.sequence), static_cast(q.tag)}, q.tag); queued_.push_back(q); } void Kernel::parkThreadStack(uint32_t sp) { Thread *on = thread(running_); Thread *owner = on && on->pseudo ? thread(1) : on; if (!on || !owner || on->frames.empty() || !sp || on->top().parkedStack || sp != on->top().ctx.r[29].uw[0] || !owner->stack || !owner->stackSize || uint64_t(sp) < owner->stack || uint64_t(sp) > uint64_t(owner->stack) + owner->stackSize) throw std::runtime_error("native work-stack switch requires a live owned stack pointer"); const auto offset = GuestMemory::flatOffset(owner->stack, owner->stackSize); if (offset < 0 || uint64_t(offset) + owner->stackSize > kFlatScratchpadOffset) throw std::runtime_error("native work-stack declaration is outside RAM"); on->top().parkedStack = sp; } void Kernel::resumeThreadStack(uint32_t sp) { Thread *on = thread(running_); if (!on || on->frames.empty() || !sp || on->top().parkedStack != sp) throw std::runtime_error("native work-stack return does not match its parked pointer"); on->top().parkedStack = 0; } uint32_t Kernel::ownedHandlerStack(const Thread &on) const { const auto main = threads_.find(1); const Thread *owner = on.pseudo ? (main == threads_.end() ? nullptr : main->second.get()) : &on; if (!owner || owner->pseudo || !owner->stack || !owner->stackSize || uint64_t(owner->stack) + owner->stackSize > 0x100000000ull) throw std::runtime_error("native handler requires a declared thread stack"); const uint64_t begin = owner->stack, end = begin + owner->stackSize; const auto offset = GuestMemory::flatOffset(owner->stack, owner->stackSize); if (offset < 0 || uint64_t(offset) + owner->stackSize > kFlatScratchpadOffset) throw std::runtime_error("native handler stack declaration is outside RAM"); const auto contains = [&](uint32_t sp) { return sp >= begin && sp <= end; }; const auto liveStack = [&](const Thread &thread) -> uint32_t { for (auto it = thread.frames.rbegin(); it != thread.frames.rend(); ++it) { const auto &frame = **it; const auto sp = frame.parkedStack ? frame.parkedStack : frame.ctx.r[29].uw[0]; if (contains(sp)) { if (uint64_t(sp) < begin + kHandlerCallAreaBytes + 16) throw std::runtime_error("native handler has no owned stack headroom"); return (sp - kHandlerCallAreaBytes) & ~15u; } // Do not fall back above an automatic frame that overflowed. if (frame.sp && contains(frame.sp)) throw std::runtime_error("native handler context left its owned stack"); } return 0; }; if (const auto sp = liveStack(on)) return sp; // The dispatcher finishes an active pseudo-handler before scheduling // ready user threads. Its idle invocation can borrow below the main // thread's parked frame; nested invocations use their live frame above. if (on.pseudo) if (const auto sp = liveStack(*owner)) return sp; std::ostringstream message; message << "native handler has no live owned stack frame: thread=" << on.id << " owner=" << owner->id << std::hex << " bounds=" << begin << ".." << end; for (const auto &frame : owner->frames) message << " sp=" << frame->ctx.r[29].uw[0] << " entry-sp=" << frame->sp << " pc=" << frame->ctx.pc; throw std::runtime_error(message.str()); } Frame &Kernel::stackOn(Thread &on, const QueuedHandler &h) { const uint32_t nativeStack = !h.sp && ownedHandlerStacks_ ? ownedHandlerStack(on) : 0; if (!ownedHandlerStacks_ && on.handlerSlot < 0) on.handlerSlot = handlerSlots_++; auto f = std::make_unique(); freshContext(*f); f->kind = h.kind; f->pc = h.pc; for (int i = 0; i < 4; ++i) f->a[i] = h.a[i]; f->gp = h.gp; f->sp = h.sp ? h.sp : ownedHandlerStacks_ ? nativeStack : kHandlerStackTop - static_cast(on.handlerSlot) * kHandlerStackBytes; f->ra = h.ra; f->completion = h.completion; f->sequence = h.sequence; f->tag = h.tag; for (int i = 0; i < 4; ++i) if (h.aHigh[i]) f->ctx.r[4 + i].ud[0] = (static_cast(h.aHigh[i]) << 32) | f->a[i]; else f->ctx.r[4 + i].sd[0] = static_cast(f->a[i]); f->ctx.r[28].sd[0] = static_cast(f->gp); f->ctx.r[29].sd[0] = static_cast(f->sp); f->ctx.r[31].sd[0] = static_cast(f->ra); f->ctx.pc = f->pc; on.frames.push_back(std::move(f)); return *on.frames.back(); } bool Kernel::handlerQueuedFor(int32_t thread) const { if (handlerThreads_.empty()) return !queued_.empty(); for (const QueuedHandler &h : queued_) { const auto it = handlerThreads_.find(h.sequence); if (it == handlerThreads_.end() || it->second == thread) return true; } return false; } Frame &Kernel::stackHandler(Thread &on) { auto at = queued_.begin(); if (!handlerThreads_.empty()) for (; at != queued_.end(); ++at) { const auto it = handlerThreads_.find(at->sequence); if (it == handlerThreads_.end() || it->second == on.id) break; } if (at == queued_.end()) throw std::runtime_error("no queued handler may run on this thread"); const QueuedHandler h = *at; Frame &frame = stackOn(on, h); handlerThreads_.erase(h.sequence); queued_.erase(at); return frame; } Thread &Kernel::pseudoThread() { for (auto &[id, t] : threads_) if (t->pseudo && t->frames.size() == 1) return *t; auto t = std::make_unique(); t->id = nextPseudo_--; t->pseudo = true; t->state = ThreadState::Dormant; t->frames.push_back(std::make_unique()); Thread &r = *t; threads_[r.id] = std::move(t); return r; } void Kernel::endHandler(Thread &t) { if (t.frames.size() > 1) t.frames.pop_back(); if (t.pseudo && t.frames.size() == 1 && running_ == t.id) running_ = 0; } // ---- Setup --------------------------------------------------------------------------------------------------- void Kernel::fieldRate(uint32_t numerator, uint32_t denominator) { emit(kOpFieldRate, {numerator, denominator}); if (const uint64_t c = fieldCycles(numerator, denominator)) { // The next vblank a field of the new length after the last one: counted from the start (vblanks x the // field), a change after many fields of another length moved it far off (Shinobido at 60: NTSC's fields // for minutes, then PAL's for a movie put the next vblank 16 s away, the movie's sound waiting for it). if (c != fieldCycles_ && nextStart_ >= fieldCycles_) nextStart_ = nextStart_ - fieldCycles_ + c; fieldCycles_ = c; lines_ = numerator / denominator < 55 ? 625 : 525; } } uint32_t Kernel::threadSetup(uint32_t stack, uint32_t stackSize, uint32_t gp) { emit(kOpThreadSetup, {stack, stackSize, gp}); // A stack of -1 (the SDK crt0's default `_stack`, Shinobido's) asks the kernel for the end of RAM: the stack is // the stackSize bytes below 32 MB. Without it the stack pointer is -1 + size, an odd address in the program. if (stack == 0xffffffffu && stackSize != 0u && stackSize < kRamTop) stack = kRamTop - stackSize; if (Thread *self = thread(running_)) { // A size of 0 (Twisted Metal: Black's crt0) gives the stack's top only: the stack pointer starts there and // the stack grows below it, undeclared. The owned handler stacks need bounds, so it is taken as the // kUndeclaredStackBytes below that top. The call's result (the stack pointer) is unchanged. const bool undeclared = stackSize == 0u && stack != 0xffffffffu && stack >= kUndeclaredStackBytes; self->stack = undeclared ? stack - kUndeclaredStackBytes : stack; self->stackSize = undeclared ? kUndeclaredStackBytes : stackSize; self->gp = gp; } return stack + stackSize; } bool Kernel::transfer(bool interruptSafe) { const bool give = !interruptSafe && running_ > 0 && (switchRequested_ || best() != running_); if (!interruptSafe) switchRequested_ = false; if (give) deschedule(true); emit(kOpTransfer, {interruptSafe ? 1u : 0u}); return give; } void Kernel::replay(uint32_t op, const uint32_t *a, uint32_t argc, uint64_t wide) { auto arg = [&](uint32_t i) { return i < argc ? a[i] : 0u; }; switch (op) { case kOpQueue: { QueuedHandler q; q.kind = static_cast(arg(0)); q.pc = arg(1); for (uint32_t i = 0; i < 4; ++i) q.a[i] = arg(2 + i); q.gp = arg(6); q.sp = arg(7); q.ra = arg(8); q.completion = arg(9) != 0; q.tag = wide; queue(q); break; } case kOpBlock: block(static_cast(arg(0)), arg(1), arg(2), arg(3), arg(4), arg(5) != 0, wide, static_cast(arg(3))); break; case kOpWake: wake(static_cast(arg(0)), arg(1), arg(2) != 0, arg(3)); break; case kOpIrq: irq(arg(0) != 0, arg(1)); break; case kOpCreate: createThread(arg(1), arg(2), arg(3), arg(4), arg(5), arg(6), arg(7)); break; case kOpStart: startThread(static_cast(arg(0)), arg(1), arg(2) != 0); break; case kOpExit: exitThread(static_cast(arg(0)), arg(1) != 0); break; case kOpTerminate: if (arg(1)) deleteThread(static_cast(arg(0)), false); else terminateThread(static_cast(arg(0)), false, arg(2) != 0); break; case kOpPriority: changePriority(static_cast(arg(0)), arg(1), arg(2) != 0); break; case kOpRotate: rotateReadyQueue(arg(0), arg(1) != 0); break; case kOpWakeup: wakeupThread(static_cast(arg(0)), arg(1) != 0); break; case kOpCancelWakeup: cancelWakeupThread(static_cast(arg(0)), arg(1) != 0); break; case kOpSuspend: suspendThread(static_cast(arg(0)), arg(1) != 0); break; case kOpResume: resumeThread(static_cast(arg(0)), arg(1) != 0); break; case kOpSemaCreate: createSema(static_cast(arg(0)), static_cast(arg(1)), arg(2), arg(3)); break; case kOpSemaDelete: deleteSema(static_cast(arg(0)), arg(1) != 0); break; case kOpSignal: signalSema(static_cast(arg(0)), arg(1) != 0); break; case kOpPollSema: pollSema(static_cast(arg(0))); break; case kOpWaitSema: waitSema(static_cast(arg(0))); break; case kOpHandlerAdd: addHandler(arg(0) != 0, arg(1), arg(2), static_cast(arg(3)), arg(4), arg(5), arg(6)); break; case kOpHandlerRemove: removeHandler(arg(0) != 0, arg(1), static_cast(arg(2))); break; case kOpCauseEnable: causeEnable(arg(0) != 0, arg(1), arg(2) != 0); break; case kOpFieldRate: fieldRate(arg(0), arg(1)); break; case kOpThreadSetup: threadSetup(arg(0), arg(1), arg(2)); break; case kOpTransfer: transfer(arg(0) != 0); break; case kOpDeadlineSet: { QueuedHandler h; h.kind=static_cast(arg(1)); h.pc=arg(2); for(uint32_t i=0;i<4;++i) h.a[i]=arg(3+i); h.gp=arg(7); h.sp=arg(8); h.ra=arg(9); h.completion=arg(10)!=0; h.tag=static_cast(arg(11)) | (static_cast(arg(12))<<32); scheduleDeadline(arg(0),wide,h); break; } case kOpDeadlineCancel: cancelDeadline(arg(0)); break; case kOpAlarmSet: setAlarm(wide, arg(0), arg(1), arg(2), arg(3) != 0); break; case kOpAlarmCancel: releaseAlarm(static_cast(arg(0)), arg(1) != 0); break; default: // Not used by TMB (alarms, event flags, suspend/resume...): recorded as made, no effect yet. { OpEvent e; e.op = op; e.origin = origin_; e.depth = depth_; e.originCall = origin_ == kOriginCall ? originCall_ : kNoCall; e.wide = wide; e.argc = std::min(argc, 16); for (uint32_t i = 0; i < e.argc; ++i) e.args[i] = a[i]; e.thread = running_; (observer_ ? observer_ : &defaultObserver_)->op(e); } break; } } // ---- Events -------------------------------------------------------------------------------------------------- void Kernel::raise(bool dmac, uint32_t cause) { irq(dmac, cause); } void Kernel::vblankStart() { ++vblankCount_; nextStart_ += fieldCycles_; // a field after this one ((vblanks + 1) x the field while its length never changed) // Threads waiting for this vblank, by thread id (calllog: not in the order they blocked). std::vector woken; for (const auto &[id, t] : threads_) if (t->state == ThreadState::Waiting && t->waitReason == kWaitVblank && vblankCount_ > t->waitToken) woken.push_back(id); for (int32_t id : woken) { Thread *t = thread(id); const uint32_t result = t->fixedResult == -1 ? ((vblankCount_ & 1u) ^ 1u) : static_cast(t->fixedResult); wake(id, result, t->waitCompletion, kWaitVblank); } raise(false, kIntcVblankStart); if (vblankHandler_.pc) queue(vblankHandler_); } void Kernel::vblankEnd() { nextEnd_ = nextStart_ + kVblankLength; raise(false, kIntcVblankEnd); } uint64_t Kernel::nextEvent() const { uint64_t next=std::min(nextStart_,nextEnd_); for(const auto &[key,deadline]:deadlines_) next=std::min(next,deadline.cycle); return next; } void Kernel::scheduleDeadline(uint32_t key,uint64_t cycle,const QueuedHandler &h) { if(cycle==~0ull || !h.pc) throw std::invalid_argument("native deadline requires a finite cycle and callback"); emit(kOpDeadlineSet,{key,h.kind,h.pc,h.a[0],h.a[1],h.a[2],h.a[3],h.gp,h.sp,h.ra, h.completion?1u:0u,static_cast(h.tag),static_cast(h.tag>>32)},cycle); deadlines_[key]={cycle,h,{}}; } void Kernel::scheduleNative(uint32_t key,uint64_t cycle,std::function fn) { if(cycle==~0ull || !fn) throw std::invalid_argument("native deadline requires a finite cycle and callback"); deadlines_[key]={cycle,{},std::move(fn)}; } bool Kernel::cancelDeadline(uint32_t key) { emit(kOpDeadlineCancel,{key}); return deadlines_.erase(key)!=0; } int32_t Kernel::setAlarm(uint64_t due, uint32_t pc, uint32_t arg, uint32_t gp, bool interruptSafe) { emit(kOpAlarmSet, {pc, arg, gp, interruptSafe ? 1u : 0u}, due); for (int32_t id = 0; id < kAlarms; ++id) { const uint32_t key = kAlarmKeys | static_cast(id); if (deadlines_.count(key)) continue; QueuedHandler h; h.kind = kInvokeAlarm; h.pc = pc; h.a[0] = static_cast(id); h.a[1] = static_cast((due / hblank()) & 0xFFFFu); h.a[2] = arg; h.gp = gp; Nested n(*this); scheduleDeadline(key, due, h); return id; } return -1; } int32_t Kernel::releaseAlarm(int32_t id, bool interruptSafe) { emit(kOpAlarmCancel, {static_cast(id), interruptSafe ? 1u : 0u}); if (id < 0 || id >= kAlarms) return -1; Nested n(*this); return cancelDeadline(kAlarmKeys | static_cast(id)) ? 0 : -1; } void Kernel::processEvents(uint64_t cycle) { while (nextEvent() <= cycle) processNextEvent(); } void Kernel::processNextEvent() { auto first=deadlines_.end(); for(auto it=deadlines_.begin();it!=deadlines_.end();++it) if(first==deadlines_.end() || it->second.cyclesecond.cycle) first=it; // Existing field events win equal-cycle ties; callback ties use key order. if(first!=deadlines_.end() && first->second.cyclesecond.cycle; const auto handler=first->second.handler; const auto native=first->second.native; deadlines_.erase(first); Nested n(*this); if(native) native(due); else queue(handler); return; } if (nextStart_ <= nextEnd_) vblankStart(); else vblankEnd(); } } namespace bozo::ee { void Kernel::scheduleNative(uint32_t key, uint64_t cycle, uint32_t kind, std::array args, std::function fn) { scheduleNative(key, cycle, std::move(fn)); deadlines_[key].nativeKind = kind; deadlines_[key].nativeArgs = args; } // ---- Save states ---- void io(state::Archive &a, QueuedHandler &h) { state::fields(a, h.kind, h.pc, h.a, h.gp, h.sp, h.ra, h.aHigh, h.completion, h.sequence, h.tag); } void io(state::Archive &a, Frame &f) { state::pod(a, f.ctx); state::pod(a, f.last); state::fields(a, f.status, f.ran, f.parkedStack, f.kind, f.pc, f.a, f.gp, f.sp, f.ra, f.completion, f.sequence, f.tag); } void io(state::Archive &a, Thread &t) { state::fields(a, t.id, t.state, t.priority, t.initPriority, t.entry, t.stack, t.stackSize, t.gp, t.attr, t.option, t.arg, t.waitReason, t.waitObject, t.flagBits, t.flagMode, t.waitToken, t.fixedResult, t.waitCompletion, t.completionDue, t.wakeupCount, t.pseudo, t.handlerSlot, t.frames); } void io(state::Archive &a, InterruptHandler &h) { state::fields(a, h.id, h.cause, h.pc, h.arg, h.gp, h.sp, h.enabled); } void io(state::Archive &a, Semaphore &s) { state::fields(a, s.id, s.count, s.max, s.init, s.attr, s.option, s.waiters); } std::string Kernel::unsaveable() const { if (depth_) return "inside a kernel operation"; for (const auto &[key, d] : deadlines_) if (d.native && !d.nativeKind) return "a native deadline (key 0x" + std::to_string(key) + ") has no saveable kind"; return {}; } void Kernel::serialize(state::Archive &a) { a.begin("kernel"); state::fields(a, vblankHandler_, origin_, originCall_, threads_, ready_, readyMask_, running_, switchRequested_, picks_, nextPseudo_, handlerSlots_, ownedHandlerStacks_, nextThreadId_, nextSemaId_, nextIntcHandler_, nextDmacHandler_, semas_, intc_, dmac_, nextHandlerId_, intcMask_, dmacMask_, intcPending_, dmacPending_, queued_, sequence_, vblankCount_, fieldCycles_, lines_, nextStart_, nextEnd_); uint64_t n = state::count(a, deadlines_.size()); if (!a.loading()) for (auto &[key, d] : deadlines_) { uint32_t k = key; state::fields(a, k, d.cycle, d.handler, d.nativeKind, d.nativeArgs); } else { deadlines_.clear(); for (uint64_t i = 0; i < n; ++i) { uint32_t key = 0; Deadline d; state::fields(a, key, d.cycle, d.handler, d.nativeKind, d.nativeArgs); if (d.nativeKind) { if (!nativeRebuild) throw state::Error("save state: a native deadline but no rebuilder"); d.native = nativeRebuild(d.nativeKind, d.nativeArgs); if (!d.native) throw state::Error("save state: unknown native deadline kind " + std::to_string(d.nativeKind)); } deadlines_[key] = std::move(d); } } // Added after the format above: a state saved before it has no thread-bound handlers. if (!a.loading() || a.sectionLeft()) { a.begin("handlerThreads"); state::fields(a, handlerThreads_); a.end(); } else handlerThreads_.clear(); a.end(); } }