--- nono/vm/scheduler.cpp 2026/04/29 17:04:29 1.1.1.2 +++ nono/vm/scheduler.cpp 2026/04/29 17:04:45 1.1.1.7 @@ -1,32 +1,33 @@ // // nono -// Copyright (C) 2017 isaki@NetBSD.org +// Copyright (C) 2020 nono project +// Licensed under nono-license.txt // +#include "scheduler.h" +#include "config.h" +#include "mainapp.h" #include "mfp.h" -#include "mpu.h" +#include "mpu680x0.h" +#include "mpu88xx0.h" +#include "mythread.h" #include "rtc.h" -#include "scheduler.h" -#include "configfile.h" #include "vm.h" // VM スケジューラは、仮想時間とイベントを管理する。 // -// 仮想時間は MPU の起動時からのクロックサイクルの経過数で表すこととする。 -// このエミュレータはシングルプロセッサシステムのみがターゲットであり、 -// 実行中に動作クロックが変わることはないので、これで問題ない。 -// VM 界からは gMPU->total_cycle() で取得する。 +// 仮想時間は起動時からの nsec で表し、MPU デバイス (実際はその向こうの +// CPU コア) が管理している。VM 界からは gMPU->GetVirtTime() で取得する。 static void *scheduler_run(void *arg); -Scheduler *gScheduler; +std::unique_ptr gScheduler; // コンストラクタ Scheduler::Scheduler() { logname = "scheduler"; devname = "Scheduler"; - monitor.Init(68, 30); eventlist.clear(); } @@ -34,35 +35,19 @@ Scheduler::Scheduler() // デストラクタ Scheduler::~Scheduler() { + Terminate(); } // 初期化 -// ここで mpu_clock が(非ゼロに)初期化されるとこれ以降 putlog() が使える。 -// そのため、Scheduler デバイスを必ずデバイスリストの先頭に置くことで、 -// これ以外のオブジェクトの Init() は putlog() を使ってよいとできる。 bool Scheduler::Init() { - int new_clock; - - // 先に初期値を設定しておく - // MPU クロック数 [kHz] (25MHz = 25000) - if (gVM->GetType() == VM::TYPE_LUNA) { - mpu_clock = 20000; - } else { - mpu_clock = 25000; - } - new_clock = gConfig->ReadInt("mpu_clock", mpu_clock); - // ReadInt() は変数があって値が解釈できなければ 0 を返す - if (new_clock == 0) { - gConfig->Err("mpu_clock", "invalid number"); - return false; - } - mpu_clock = new_clock; + // 起動時引数指定の高速モード + SetFullSpeed(gMainApp.fast_mode); // スケジューラ(VM)スレッド起動 - pthread_t th; - pthread_create(&th, NULL, scheduler_run, NULL); + pthread_create(&thread, NULL, scheduler_run, NULL); + thread_created = true; return true; } @@ -80,8 +65,7 @@ Scheduler::Run() void * scheduler_run(void *arg) { - pthread_setname_np("VM"); - pthread_detach(pthread_self()); + PTHREAD_SETNAME("VM"); gScheduler->ThreadRun(); return NULL; @@ -91,13 +75,24 @@ scheduler_run(void *arg) void Scheduler::ThreadRun() { - uint64 cycle; // 今回実行するサイクル数 + uint32 req; // 最初の電源オンを待つ - { + for (;;) { std::unique_lock lock(cvmtx); - cv.wait(lock, [&] { return (atomic_reqflag & REQ_POWER_ON); }); - atomic_reqflag &= ~REQ_POWER_ON; + cv.wait(lock, [&] { return (atomic_reqflag != 0); }); + req = atomic_reqflag.load(); + // 終了 + if ((req & REQ_EXIT)) { + return; + } + // REQ_POWER_ON なら他のフラグを書き戻して抜ける。 + // REQ_{SYNC|FAST} は以降のメインループで処理するため。 + if ((req & REQ_POWER_ON)) { + req &= ~REQ_POWER_ON; + atomic_reqflag.store(req); + break; + } } // ここからは電源オン @@ -105,19 +100,21 @@ Scheduler::ThreadRun() rtimestart = GetRealTime(); rtc_last_clock = rtimestart; - cycle = INT64_MAX; mode = 0; for (;;) { - uint32 req; req = atomic_reqflag.exchange(0); if (req) { if ((req & REQ_SYNC)) { // スケジューラを同期モードに mode |= SCHED_SYNC; + // 同期モードでは RAM アクセスはデバイス経由 + ::direct_ram_size = 0; } if ((req & REQ_FAST)) { // スケジューラを高速モードに mode &= ~SCHED_SYNC; + // 高速モードでは RAM は直接アクセス + ::direct_ram_size = ::ram_size; } if ((req & REQ_RUN)) { // MPU が通常状態になった @@ -139,7 +136,7 @@ Scheduler::ThreadRun() // 基準時刻をリセット rtimebase = ::GetRealTime(); - vtimebase = GetVirtTime(); + vtimebase = gMPU->GetVirtTime(); // 該当ビットを落としておく req &= ~REQ_MODEMASK; @@ -154,6 +151,15 @@ Scheduler::ThreadRun() req &= ~REQ_POWER_OFF; } + if ((req & REQ_RESET)) { + // リセット要求の場合 + + // 全デバイスをリセット + gVM->ResetHard(); + + req &= ~REQ_RESET; + } + if ((req & REQ_EXIT)) { // 終了要求 // この for ブロックをいきなり抜けるだけなので @@ -163,7 +169,7 @@ Scheduler::ThreadRun() } // 電源オン要求は来ないはず - assert(req == 0); + assertmsg(req == 0, "req=$%x", req); } // RTC は常にホスト時刻で動いており @@ -173,57 +179,72 @@ Scheduler::ThreadRun() rtc_last_clock += 31.25_msec; } - // まず CPU を駆動する。MPU::Run() はデバイスアクセスなどによって - // スケジューラにイベントが登録されると、その命令の終了とともに - // 処理を打ち切って戻ってくる。 - // ここでイベントリストを調べ、その時点から最も早く発生するイベント - // までの必要サイクル数が、次のループでの駆動サイクル数になる。 - - // CPU 駆動 - uint32 outer; - outer = gMPU->Run(cycle); + // イベントリストを調べ現時点から最も早く発生するイベントまでの必要 + // 時間を求めて、この時間分だけ MPU を駆動する。 + // MPU 実行中にデバイスアクセスなどによってスケジューラにイベントが + // 登録されると、その命令の終了とともに処理を打ち切って戻ってくる。 + // また、電源オン(リセット)時には MPU デバイスが 0nsec で MPU の + // リセット例外イベントを起こすようになっている。 + + // delta_vtime が今回進める仮想時間。 + // とりあえず初期値を仮置きしとくけど、イベントは通常 20msec 以内には + // 必ず起きるので (例えば LUNA の sysclk は 10 or 16 msec 周期)、 + // この初期値は実質上限値。20msec 程度より大きければいくらでもよくて + // 100msec とかでいいんだけど、二進数で置数しやすいよう + // 0x200'0000 (約33.5msec) にしておく。 + uint64 delta_vtime = 0x200'0000; // イベント + uint64 vtime = gMPU->GetVirtTime(); for (;;) { - evcs.lock(); - if (eventlist.empty()) { - cycle = INT64_MAX; - break; + Event *e; + // ロック区間 + { + std::lock_guard lock(evcs); + + if (eventlist.empty()) { + break; + } + e = eventlist.front(); + if (e->vtime > vtime) { + // まだ時刻に到達していない + delta_vtime = e->vtime - vtime; + break; + } + + // 到達したのでこのイベントをリストから削除 + e->active = false; + eventlist.pop_front(); } - Event *e = eventlist.front(); - if (gMPU->total_cycle() < e->cycle) { - // まだ時刻に到達していない - cycle = e->cycle - gMPU->total_cycle(); - break; - } - - // 到達したのでこのイベントをリストから削除 - e->active = false; - eventlist.pop_front(); - evcs.unlock(); // コールバック - putlog(2, "イベント '%s' 時刻到達", e->GetName().c_str()); - ((e->dev)->*(e->func))(e->code); + e->dev->putlog(3, "イベント '%s' 時刻到達", e->GetName().c_str()); + ((e->dev)->*(e->func))(*e); // 同時刻のイベントがあるかも知れないのでなくなるまで調べる } - evcs.unlock(); + + // CPU を駆動 + uint32 outer; + outer = gMPU->Run(delta_vtime); + + // CPU 駆動によって進んだ仮想時刻を再取得 + vtime = gMPU->GetVirtTime(); // 同期モードなら実時間調整。 // あるいは高速モードであってもストップ状態なら実時間駆動する。 if (mode != 0) { // 通常モード - uint64 vtime; - uint64 rtime; + uint64 vspan; + uint64 rspan; // 基準時からの経過時間 - vtime = GetVirtTime() - vtimebase; - rtime = GetRealTime() - rtimebase; + vspan = vtime - vtimebase; + rspan = GetRealTime() - rtimebase; - if (vtime > rtime) { + if (vspan > rspan) { // 仮想時間のほうが進んでいれば、スリープして待つ - uint64 diff = vtime - rtime; + uint64 diff = vspan - rspan; struct timespec ts; ts.tv_sec = diff / (1000 * 1000 * 1000); ts.tv_nsec = diff % (1000 * 1000 * 1000); @@ -237,9 +258,10 @@ Scheduler::ThreadRun() // CPU の STOP 状態をこっちのモードに反映。 // このために SCHED_STOP と CPU_REQ_STOP は同じビット位置にしてある。 + // CPU の HALT はスケジューラ的には STOP と同じ扱いでいい。 if (((mode ^ outer) & SCHED_STOP)) { // 状態変更要求 - if ((outer & CPU_REQ_STOP)) { + if ((outer & (CPU_REQ_STOP | CPU_REQ_HALT)) != 0) { atomic_reqflag |= REQ_STOP; } else { atomic_reqflag |= REQ_RUN; @@ -248,11 +270,15 @@ Scheduler::ThreadRun() } } -// スレッド終了指示 +// 必要ならスレッドの終了を指示して完了まで待つ。 void Scheduler::Terminate() { - atomic_reqflag |= REQ_EXIT; + if (thread_created) { + atomic_reqflag |= REQ_EXIT; + pthread_join(thread, NULL); + thread_created = false; + } } // 動作モードを設定する。 @@ -267,18 +293,18 @@ Scheduler::SetFullSpeed(bool enable) } } -// イベントをスケジューラに登録する。 +// 指定のイベントを開始する。 // すでに同イベントが登録されている場合は古いイベントを削除してから // 新しいイベントを再登録となる。 // イベントはワンショットのみ。 void -Scheduler::AddEvent(Event *newev) +Scheduler::StartEvent(Event *newev) { bool inserted = false; bool updated = false; - // 相対 time から絶対 cycle を計算 - newev->cycle = gMPU->total_cycle() + Vtime2Cycle(newev->time); + // time は仮想相対時間 [nsec]、vtime は仮想絶対時刻 [nsec] + newev->vtime = gMPU->GetVirtTime() + newev->time; evcs.lock(); // すでにあれば削除 @@ -295,7 +321,7 @@ Scheduler::AddEvent(Event *newev) // ソートされているところに自身を挿入 for (auto it = eventlist.begin(); it != eventlist.end(); ++it) { Event *e = *it; - if (newev->cycle <= e->cycle) { + if (newev->vtime <= e->vtime) { // このイベントの前に入れる eventlist.insert(it, newev); inserted = true; @@ -311,17 +337,17 @@ Scheduler::AddEvent(Event *newev) gMPU->Release(); - putlog(2, "イベント '%s' %s %d.%03d usec 後", + newev->dev->putlog(3, "イベント '%s' %s %d.%03d usec 後", newev->GetName().c_str(), - updated ? "更新" : "追加", + updated ? "更新" : "開始", (int)(newev->time / 1000), (int)(newev->time % 1000)); } -// 指定のイベントを削除する。 +// 指定のイベントを停止する。 // 指定されたイベントが登録されていなければ何もしない。 void -Scheduler::DelEvent(Event *event) +Scheduler::StopEvent(Event *event) { bool found = false; @@ -337,13 +363,13 @@ Scheduler::DelEvent(Event *event) } evcs.unlock(); - // イベントを削除した場合は MPU の実行中断はしなくてよい。 + // イベントを停止した場合は MPU の実行中断はしなくてよい。 // 1msec 後にイベントを追加した後、やっぱりそのイベントを取り消した // 場合 (LUNA の電源オフとか) はここで MPU 処理を中断するよりも // そのまま 1msec 走って問題ない。 if (found) { - putlog(2, "イベント '%s' 削除", event->GetName().c_str()); + event->dev->putlog(3, "イベント '%s' 停止", event->GetName().c_str()); } } @@ -390,8 +416,17 @@ TimeToStr(uint64 t) return std::string(buf, p - buf); } -bool -Scheduler::MonitorUpdate() +// モニターサイズ取得 +nnSize +Scheduler::GetMonitorSize() +{ + // 本当は Init() 完了時点でイベント個数は確定しているはずだけど、 + // そのタイミングで一度だけ呼ばれるフックが今の所ない。 + return nnSize(68, 11 + gEvents.size()); +} + +void +Scheduler::MonitorUpdate(TextScreen& monitor) { int x, y; @@ -399,28 +434,29 @@ Scheduler::MonitorUpdate() x = 0; y = 0; + int clock_khz = gMPU->GetClockSpeed(); + monitor.Print(0, y++, "Mode: %s %s", (mode & SCHED_SYNC) ? "Sync" : "Full", (mode & SCHED_STOP) ? "STOP" : "Run "); monitor.Print(0, y++, "Req: %08x", (uint32)atomic_reqflag); monitor.Print(0, y++, "MPU Speed: %d.%03dMHz", - (mpu_clock / 1000), (mpu_clock % 1000)); - uint64 cycle = gMPU->total_cycle(); - uint64 vt = GetVirtTime(); - uint64 rt = GetRealTime(); - uint64 relvt = vt - vtimebase; - uint64 relrt = rt - rtimebase; + (clock_khz / 1000), (clock_khz % 1000)); + uint64 vtime = gMPU->GetVirtTime(); + uint64 rtime = GetRealTime(); + uint64 vspan = vtime - vtimebase; + uint64 rspan = rtime - rtimebase; // RealTime は実時間なのでスケジューラ開始からの時間に変換 - rt -= rtimestart; - monitor.Print(0, y++, "Total Real Time: %18s", TimeToStr(rt).c_str()); - monitor.Print(0, y++, " Virtual Time: %18s", TimeToStr(vt).c_str()); - double ratio = (double)vt / rt * 100; + rtime -= rtimestart; + monitor.Print(0, y++, "Total Real Time: %18s", TimeToStr(rtime).c_str()); + monitor.Print(0, y++, " Virtual Time: %18s", TimeToStr(vtime).c_str()); + double ratio = (double)vtime / rtime * 100; monitor.Print(0, y++, " Ratio : %3d.%01d%%", (int)ratio, ((int)(ratio * 10) % 10)); - monitor.Print(0, y++, "Moment Real Time: %18s", TimeToStr(relrt).c_str()); - monitor.Print(0, y++, " Virtual Time: %18s", TimeToStr(relvt).c_str()); + monitor.Print(0, y++, "Moment Real Time: %18s", TimeToStr(rspan).c_str()); + monitor.Print(0, y++, " Virtual Time: %18s", TimeToStr(vspan).c_str()); // XXX 移動平均をとる - double relratio = (double)relvt / relrt * 100; + double relratio = (double)vspan / rspan * 100; monitor.Print(0, y++, " Ratio : %3d.%01d%%", (int)relratio, ((int)(relratio * 10) % 10)); @@ -430,17 +466,26 @@ Scheduler::MonitorUpdate() // 3.123'456'789 3.123'456'789 0123456789012345678901234 $01234567 x = 0; y++; - monitor.Print(x, y, "Set Time"); - monitor.Print(x + 16, y, "Remain Time"); - monitor.Print(x + 32, y, "Description"); - monitor.Print(x + 58, y, "Code"); + monitor.Puts(x, y, "Set Time"); + monitor.Puts(x + 16, y, "Remain Time"); + monitor.Puts(x + 32, y, "Description"); + monitor.Puts(x + 58, y, "Code"); y++; + for (const auto& e : gEvents) { uint64 rem; - uint attr; + TA attr; if (e->active) { - attr = 0; - rem = Cycle2Vtime(e->cycle - cycle); + attr = TA::Normal; + if (e->vtime > vtime) { + rem = e->vtime - vtime; + } else { + // XXX 実際には起きないけど、この表示をするにあたって + // スケジューラスレッドと一切調停していないので、仮想時刻が + // e->cycle (イベント発生時刻) をすぎていることがある。 + // すぎてるので残り時間 0 と表示しておく。 + rem = 0; + } } else { attr = TA::Disable; rem = 0; @@ -458,6 +503,4 @@ Scheduler::MonitorUpdate() e->GetName().c_str(), e->code); } - - return true; }