Skip to main content

strat9_kernel/shell/commands/top/
mod.rs

1//! Top command with Ratatui no_std backend.
2//!
3//! This command keeps Chevron shell as default UX and only uses Ratatui while `top` is running.
4
5pub(crate) mod ratatui_backend;
6
7use crate::{arch::x86_64::vga, shell::ShellError, shell_println};
8use alloc::{format, string::String, vec, vec::Vec};
9use core::sync::atomic::Ordering;
10use ratatui::{
11    layout::{Constraint, Direction, Layout},
12    style::{Color, Modifier, Style},
13    widgets::{Block, Borders, Cell, Gauge, Paragraph, Row, Table, TableState},
14    Terminal,
15};
16pub(crate) use ratatui_backend::Strat9RatatuiBackend;
17
18const TOP_REFRESH_TICKS: u64 = 10; // 100ms at 100Hz
19const MAX_CPU_GAUGES: usize = 8;
20
21#[derive(Clone)]
22struct TaskRowData {
23    pid: String,
24    name: String,
25    state: &'static str,
26    priority: String,
27    ticks: u64,
28}
29
30#[derive(Clone)]
31struct SiloRowData {
32    sid: String,
33    name: String,
34    state: String,
35    tasks: String,
36    label: String,
37}
38
39#[derive(Clone)]
40struct StrateRowData {
41    name: String,
42    silos: String,
43}
44
45struct TopSnapshot {
46    cpu_count: usize,
47    total_pages: usize,
48    used_pages: usize,
49    tasks: Vec<TaskRowData>,
50    silos: Vec<SiloRowData>,
51    strates: Vec<StrateRowData>,
52    scheduler: crate::process::SchedulerStateSnapshot,
53}
54
55#[derive(Clone, Copy)]
56struct CpuUsageWindow {
57    per_cpu_ratio: [f64; crate::arch::x86_64::percpu::MAX_CPUS],
58    avg_ratio: f64,
59}
60
61#[derive(Clone, Copy)]
62struct SchedulerMetricsWindow {
63    rt_ratio: f64,
64    fair_ratio: f64,
65    idle_ratio: f64,
66    switch_delta: u64,
67    preempt_delta: u64,
68    steal_in_delta: u64,
69    steal_out_delta: u64,
70}
71
72fn collect_silos_from_proc_scheme() -> Option<(Vec<SiloRowData>, Vec<StrateRowData>)> {
73    let fd = crate::vfs::open("/proc/silos", crate::vfs::OpenFlags::READ).ok()?;
74    let bytes = match crate::vfs::read_all(fd) {
75        Ok(b) => b,
76        Err(_) => {
77            let _ = crate::vfs::close(fd);
78            return None;
79        }
80    };
81    let _ = crate::vfs::close(fd);
82    let body = core::str::from_utf8(&bytes).ok()?;
83
84    let mut silos = Vec::new();
85    let mut strate_index: Vec<(String, Vec<String>)> = Vec::new();
86    for (line_idx, line) in body.lines().enumerate() {
87        if line_idx == 0 || line.is_empty() {
88            continue;
89        }
90        let mut fields = line.split('\t');
91        let sid = fields.next()?;
92        let state = fields.next()?;
93        let tasks = fields.next()?;
94        let _mem_used = fields.next()?;
95        let _mem_min = fields.next()?;
96        let _mem_max = fields.next()?;
97        let _gfx_flags = fields.next()?;
98        let _gfx_sessions = fields.next()?;
99        let _gfx_ttl = fields.next()?;
100        let label = fields.next()?;
101        let name = fields.next()?;
102
103        let strate_name = if label != "-" && !label.is_empty() {
104            String::from(label)
105        } else {
106            String::from(name)
107        };
108        if let Some((_, belongs)) = strate_index
109            .iter_mut()
110            .find(|(entry_name, _)| *entry_name == strate_name)
111        {
112            if !belongs.iter().any(|x| x == name) {
113                belongs.push(String::from(name));
114            }
115        } else {
116            strate_index.push((strate_name, vec![String::from(name)]));
117        }
118
119        silos.push(SiloRowData {
120            sid: String::from(sid),
121            name: String::from(name),
122            state: String::from(state),
123            tasks: String::from(tasks),
124            label: String::from(label),
125        });
126    }
127
128    silos.sort_by_key(|s| s.sid.parse::<u32>().unwrap_or(u32::MAX));
129    strate_index.sort_by(|a, b| a.0.cmp(&b.0));
130
131    let mut strates = Vec::with_capacity(strate_index.len());
132    for (name, belongs) in strate_index {
133        let mut silos_csv = String::new();
134        for (i, silo_name) in belongs.iter().enumerate() {
135            if i != 0 {
136                silos_csv.push_str(", ");
137            }
138            silos_csv.push_str(silo_name);
139        }
140        strates.push(StrateRowData {
141            name,
142            silos: silos_csv,
143        });
144    }
145
146    Some((silos, strates))
147}
148
149/// Performs the collect snapshot operation.
150fn collect_snapshot() -> TopSnapshot {
151    let cpu_count = crate::arch::x86_64::percpu::cpu_count();
152    let (total_pages, used_pages) = {
153        let guard = crate::memory::buddy::get_allocator().lock();
154        guard.as_ref().map(|a| a.page_totals()).unwrap_or((0, 0))
155    };
156
157    let mut tasks = Vec::new();
158    if let Some(all_tasks) = crate::process::get_all_tasks() {
159        for task in all_tasks {
160            let state = task.get_state();
161            let state_str = match state {
162                crate::process::TaskState::Ready => "Ready",
163                crate::process::TaskState::Running => "Running",
164                crate::process::TaskState::Blocked => "Blocked",
165                crate::process::TaskState::Dead => "Dead",
166            };
167            tasks.push(TaskRowData {
168                pid: format!("{}", task.pid),
169                name: String::from(task.name),
170                state: state_str,
171                priority: format!("{:?}", task.priority),
172                ticks: task.ticks.load(Ordering::Relaxed),
173            });
174        }
175    }
176
177    // Top-like behavior: most CPU-consumed tasks first.
178    tasks.sort_by(|a, b| b.ticks.cmp(&a.ticks));
179
180    let (silos, strates) = collect_silos_from_proc_scheme().unwrap_or_else(|| {
181        let mut silos = Vec::new();
182        let mut strate_index: Vec<(String, Vec<String>)> = Vec::new();
183        let mut silo_snapshots = crate::silo::list_silos_snapshot();
184        silo_snapshots.sort_by_key(|s| s.id);
185
186        for s in silo_snapshots {
187            let label = s.strate_label.unwrap_or_default();
188            let strate_name = if !label.is_empty() {
189                label.clone()
190            } else {
191                s.name.clone()
192            };
193            if let Some((_, belongs)) = strate_index
194                .iter_mut()
195                .find(|(name, _)| *name == strate_name)
196            {
197                if !belongs.iter().any(|x| x == &s.name) {
198                    belongs.push(s.name.clone());
199                }
200            } else {
201                strate_index.push((strate_name, vec![s.name.clone()]));
202            }
203            silos.push(SiloRowData {
204                sid: format!("{}", s.id),
205                name: s.name,
206                state: format!("{:?}", s.state),
207                tasks: format!("{}", s.task_count),
208                label: if label.is_empty() {
209                    String::from("-")
210                } else {
211                    label
212                },
213            });
214        }
215
216        strate_index.sort_by(|a, b| a.0.cmp(&b.0));
217        let mut strates = Vec::with_capacity(strate_index.len());
218        for (name, belongs) in strate_index {
219            let mut silos_csv = String::new();
220            for (i, silo_name) in belongs.iter().enumerate() {
221                if i != 0 {
222                    silos_csv.push_str(", ");
223                }
224                silos_csv.push_str(silo_name);
225            }
226            strates.push(StrateRowData {
227                name,
228                silos: silos_csv,
229            });
230        }
231
232        (silos, strates)
233    });
234
235    TopSnapshot {
236        cpu_count,
237        total_pages,
238        used_pages,
239        tasks,
240        silos,
241        strates,
242        scheduler: crate::process::scheduler_state_snapshot(),
243    }
244}
245
246/// Performs the compute cpu usage window operation.
247fn compute_cpu_usage_window(
248    prev: &crate::process::CpuUsageSnapshot,
249    now: &crate::process::CpuUsageSnapshot,
250) -> CpuUsageWindow {
251    let cpu_count = now.cpu_count.min(crate::arch::x86_64::percpu::MAX_CPUS);
252    let mut ratios = [0.0f64; crate::arch::x86_64::percpu::MAX_CPUS];
253    let mut sum = 0.0;
254
255    for i in 0..cpu_count {
256        let delta_total = now.total_ticks[i].saturating_sub(prev.total_ticks[i]);
257        let delta_idle = now.idle_ticks[i].saturating_sub(prev.idle_ticks[i]);
258        let ratio = if delta_total == 0 {
259            0.0
260        } else {
261            let busy = delta_total.saturating_sub(delta_idle);
262            (busy as f64 / delta_total as f64).clamp(0.0, 1.0)
263        };
264        ratios[i] = ratio;
265        sum += ratio;
266    }
267
268    CpuUsageWindow {
269        per_cpu_ratio: ratios,
270        avg_ratio: if cpu_count == 0 {
271            0.0
272        } else {
273            (sum / cpu_count as f64).clamp(0.0, 1.0)
274        },
275    }
276}
277
278/// Performs the compute scheduler metrics window operation.
279fn compute_scheduler_metrics_window(
280    prev: &crate::process::SchedulerMetricsSnapshot,
281    now: &crate::process::SchedulerMetricsSnapshot,
282) -> SchedulerMetricsWindow {
283    let cpu_count = now.cpu_count.min(crate::arch::x86_64::percpu::MAX_CPUS);
284    let mut rt_delta = 0u64;
285    let mut fair_delta = 0u64;
286    let mut idle_delta = 0u64;
287    let mut switch_delta = 0u64;
288    let mut preempt_delta = 0u64;
289    let mut steal_in_delta = 0u64;
290    let mut steal_out_delta = 0u64;
291    for i in 0..cpu_count {
292        rt_delta = rt_delta
293            .saturating_add(now.rt_runtime_ticks[i].saturating_sub(prev.rt_runtime_ticks[i]));
294        fair_delta = fair_delta
295            .saturating_add(now.fair_runtime_ticks[i].saturating_sub(prev.fair_runtime_ticks[i]));
296        idle_delta = idle_delta
297            .saturating_add(now.idle_runtime_ticks[i].saturating_sub(prev.idle_runtime_ticks[i]));
298        switch_delta =
299            switch_delta.saturating_add(now.switch_count[i].saturating_sub(prev.switch_count[i]));
300        preempt_delta = preempt_delta
301            .saturating_add(now.preempt_count[i].saturating_sub(prev.preempt_count[i]));
302        steal_in_delta = steal_in_delta
303            .saturating_add(now.steal_in_count[i].saturating_sub(prev.steal_in_count[i]));
304        steal_out_delta = steal_out_delta
305            .saturating_add(now.steal_out_count[i].saturating_sub(prev.steal_out_count[i]));
306    }
307    let total = rt_delta
308        .saturating_add(fair_delta)
309        .saturating_add(idle_delta);
310    let to_ratio = |v: u64| {
311        if total == 0 {
312            0.0
313        } else {
314            (v as f64 / total as f64).clamp(0.0, 1.0)
315        }
316    };
317    SchedulerMetricsWindow {
318        rt_ratio: to_ratio(rt_delta),
319        fair_ratio: to_ratio(fair_delta),
320        idle_ratio: to_ratio(idle_delta),
321        switch_delta,
322        preempt_delta,
323        steal_in_delta,
324        steal_out_delta,
325    }
326}
327
328/// Performs the scheduler runtime lines operation.
329fn scheduler_runtime_lines(
330    s: &crate::process::SchedulerStateSnapshot,
331    w: &SchedulerMetricsWindow,
332) -> (String, String, String) {
333    let line1 = format!(
334        "Win: RT {:>3}% | FAIR {:>3}% | IDLE {:>3}% | sw {} | pre {} | st+ {} | st- {}",
335        (w.rt_ratio * 100.0) as u16,
336        (w.fair_ratio * 100.0) as u16,
337        (w.idle_ratio * 100.0) as u16,
338        w.switch_delta,
339        w.preempt_delta,
340        w.steal_in_delta,
341        w.steal_out_delta
342    );
343    let line2 = format!(
344        "Cfg: init={} blocked={} pick=[{},{},{}] steal=[{},{}]",
345        s.initialized,
346        s.blocked_tasks,
347        s.pick_order[0].as_str(),
348        s.pick_order[1].as_str(),
349        s.pick_order[2].as_str(),
350        s.steal_order[0].as_str(),
351        s.steal_order[1].as_str()
352    );
353    let cpu_count = s.cpu_count.min(crate::arch::x86_64::percpu::MAX_CPUS);
354
355    let line3 = if cpu_count == 0 {
356        String::from("CPU: n/a")
357    } else {
358        let c0 = format!(
359            "cpu0 cur={} rq={}/{}/{} nr={}",
360            s.current_task[0], s.rq_rt[0], s.rq_fair[0], s.rq_idle[0], s.need_resched[0]
361        );
362
363        if cpu_count == 1 {
364            format!("CPU: {}", c0)
365        } else {
366            let c1 = format!(
367                "cpu1 cur={} rq={}/{}/{} nr={}",
368                s.current_task[1], s.rq_rt[1], s.rq_fair[1], s.rq_idle[1], s.need_resched[1]
369            );
370            format!("CPU: {} | {}", c0, c1)
371        }
372    };
373    (line1, line2, line3)
374}
375
376/// Top command main loop
377pub fn cmd_top(_args: &[alloc::string::String]) -> Result<(), ShellError> {
378    if !vga::is_available() {
379        shell_println!("Error: 'top' requires a graphical framebuffer console.");
380        return Ok(());
381    }
382
383    // Switch to double buffering for flicker-free updates.
384    let was_db = vga::double_buffer_mode();
385    vga::set_double_buffer_mode(true);
386    let backend = Strat9RatatuiBackend::new().map_err(|_| ShellError::ExecutionFailed)?;
387    let mut terminal = Terminal::new(backend).map_err(|_| ShellError::ExecutionFailed)?;
388    terminal.clear().map_err(|_| ShellError::ExecutionFailed)?;
389
390    let mut last_refresh_tick = crate::process::scheduler::ticks();
391    let boot_tick = last_refresh_tick;
392    let mut prev_cpu_sample = crate::process::cpu_usage_snapshot();
393    let mut prev_sched_sample = crate::process::scheduler_metrics_snapshot();
394    let mut selected_task: usize = 0;
395
396    loop {
397        let ticks = crate::process::scheduler::ticks();
398
399        // Keep input responsive even between render ticks.
400        if let Some(ch) = crate::arch::x86_64::keyboard::read_char() {
401            match ch {
402                b'q' | 0x1B | 0x03 => break,
403                crate::arch::x86_64::keyboard::KEY_UP => {
404                    selected_task = selected_task.saturating_sub(1);
405                }
406                crate::arch::x86_64::keyboard::KEY_DOWN => {
407                    selected_task = selected_task.saturating_add(1);
408                }
409                _ => {}
410            }
411        }
412
413        // Refresh every 100ms with a 100Hz timer.
414        if ticks.saturating_sub(last_refresh_tick) < TOP_REFRESH_TICKS {
415            crate::process::yield_task();
416            continue;
417        }
418        last_refresh_tick = ticks;
419        let snapshot = collect_snapshot();
420        let cpu_sample = crate::process::cpu_usage_snapshot();
421        let cpu_window = compute_cpu_usage_window(&prev_cpu_sample, &cpu_sample);
422        prev_cpu_sample = cpu_sample;
423        let sched_sample = crate::process::scheduler_metrics_snapshot();
424        let sched_window = compute_scheduler_metrics_window(&prev_sched_sample, &sched_sample);
425        prev_sched_sample = sched_sample;
426        let mem_ratio = if snapshot.total_pages > 0 {
427            (snapshot.used_pages as f64) / (snapshot.total_pages as f64)
428        } else {
429            0.0
430        };
431
432        let rows: Vec<Row> = snapshot
433            .tasks
434            .iter()
435            .map(|task| {
436                Row::new(vec![
437                    Cell::from(task.pid.as_str()),
438                    Cell::from(task.name.as_str()),
439                    Cell::from(task.state),
440                    Cell::from(task.priority.as_str()),
441                    Cell::from(format!("{}", task.ticks)),
442                ])
443            })
444            .collect();
445        let row_count = rows.len();
446        if row_count == 0 {
447            selected_task = 0;
448        } else if selected_task >= row_count {
449            selected_task = row_count - 1;
450        }
451        let mut table_state = TableState::default();
452        if row_count > 0 {
453            table_state.select(Some(selected_task));
454        }
455
456        let uptime_secs = ticks.saturating_sub(boot_tick) / 100;
457
458        let frame_started = vga::begin_frame();
459        terminal
460            .draw(|frame| {
461                let title_style = Style::default().fg(Color::Cyan).add_modifier(Modifier::BOLD);
462                let primary_text = Style::default().fg(Color::White);
463                let muted_text = Style::default().fg(Color::Gray);
464                let header_style = Style::default().fg(Color::Yellow).add_modifier(Modifier::BOLD);
465
466                let area = frame.area();
467                let vertical = Layout::default()
468                    .direction(Direction::Vertical)
469                    .constraints([
470                        Constraint::Length(2),
471                        Constraint::Length(3),
472                        Constraint::Length(5),
473                        Constraint::Length(6),
474                        Constraint::Min(8),
475                        Constraint::Length(1),
476                    ])
477                    .split(area);
478
479                let title = Paragraph::new("Strat9 system monitor")
480                    .style(title_style)
481                    .block(Block::default().borders(Borders::BOTTOM).title("Top"));
482                frame.render_widget(title, vertical[0]);
483
484                let stats_line = Paragraph::new(format!(
485                    "CPUs: {} | Tasks: {} | Silos: {} | Strates: {} | CPU(avg): {:>3}% | Uptime: {}s",
486                    snapshot.cpu_count,
487                    snapshot.tasks.len(),
488                    snapshot.silos.len(),
489                    snapshot.strates.len(),
490                    (cpu_window.avg_ratio * 100.0) as u16,
491                    uptime_secs
492                ))
493                .style(primary_text)
494                .block(Block::default().borders(Borders::BOTTOM).title("Stats"));
495                frame.render_widget(stats_line, vertical[1]);
496
497                let (sched_line1, sched_line2, sched_line3) =
498                    scheduler_runtime_lines(&snapshot.scheduler, &sched_window);
499                let sched_line = Paragraph::new(format!(
500                    "{}\n{}\n{}",
501                    sched_line1, sched_line2, sched_line3
502                ))
503                .style(primary_text)
504                .block(Block::default().borders(Borders::BOTTOM).title("Scheduler"));
505                frame.render_widget(sched_line, vertical[2]);
506
507                let cpu_split = Layout::default()
508                    .direction(Direction::Horizontal)
509                    .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
510                    .split(vertical[3]);
511
512                let mem_gauge = Gauge::default()
513                    .block(
514                        Block::default()
515                            .borders(Borders::TOP | Borders::BOTTOM)
516                            .title(format!(
517                                "Memory {} / {} pages",
518                                snapshot.used_pages, snapshot.total_pages
519                            )),
520                    )
521                    .gauge_style(Style::default().fg(Color::Blue))
522                    .use_unicode(false)
523                    .ratio(mem_ratio.clamp(0.0, 1.0))
524                    .label(format!("{:.1}%", mem_ratio * 100.0));
525                frame.render_widget(mem_gauge, cpu_split[0]);
526
527                let cpu_gauge_count = snapshot.cpu_count.min(MAX_CPU_GAUGES);
528                if cpu_gauge_count > 0 {
529                    let mut constraints = Vec::with_capacity(cpu_gauge_count);
530                    for _ in 0..cpu_gauge_count {
531                        constraints.push(Constraint::Length(1));
532                    }
533                    let cpu_rows = Layout::default()
534                        .direction(Direction::Vertical)
535                        .constraints(constraints)
536                        .split(cpu_split[1]);
537
538                    for i in 0..cpu_gauge_count {
539                        let ratio = cpu_window.per_cpu_ratio[i];
540                        let gauge = Gauge::default()
541                            .block(Block::default().title(format!("CPU{}", i)).borders(Borders::NONE))
542                            .gauge_style(Style::default().fg(Color::Green))
543                            .use_unicode(false)
544                            .ratio(ratio)
545                            .label(format!("{:>3}%", (ratio * 100.0) as u16));
546                        frame.render_widget(gauge, cpu_rows[i]);
547                    }
548                }
549
550                let main_split = Layout::default()
551                    .direction(Direction::Horizontal)
552                    .constraints([Constraint::Percentage(64), Constraint::Percentage(36)])
553                    .split(vertical[4]);
554
555                let task_table = Table::new(
556                    rows.iter().cloned(),
557                    [
558                        Constraint::Length(5),  // PID
559                        Constraint::Min(18),    // Name (takes remaining width)
560                        Constraint::Length(9),  // State
561                        Constraint::Length(8),  // Prio
562                        Constraint::Length(10), // Ticks
563                    ],
564                )
565                .header(
566                    Row::new(vec!["PID", "Name", "State", "Prio", "Ticks"]).style(header_style),
567                )
568                .column_spacing(1)
569                .style(primary_text)
570                .row_highlight_style(
571                    Style::default()
572                        .bg(Color::White)
573                        .fg(Color::Black)
574                        .add_modifier(Modifier::BOLD),
575                )
576                .block(
577                    Block::default()
578                        .borders(Borders::TOP)
579                        .title("Tasks (sorted by ticks)"),
580                );
581                frame.render_stateful_widget(task_table, main_split[0], &mut table_state);
582
583                let right_split = Layout::default()
584                    .direction(Direction::Vertical)
585                    .constraints([Constraint::Percentage(52), Constraint::Percentage(48)])
586                    .split(main_split[1]);
587
588                let silo_rows: Vec<Row> = snapshot
589                    .silos
590                    .iter()
591                    .map(|s| {
592                        Row::new(vec![
593                            Cell::from(s.sid.as_str()),
594                            Cell::from(s.name.as_str()),
595                            Cell::from(s.state.as_str()),
596                            Cell::from(s.tasks.as_str()),
597                            Cell::from(s.label.as_str()),
598                        ])
599                    })
600                    .collect();
601                let silo_table = Table::new(
602                    silo_rows,
603                    [
604                        Constraint::Length(5),
605                        Constraint::Length(10),
606                        Constraint::Length(8),
607                        Constraint::Length(5),
608                        Constraint::Min(8),
609                    ],
610                )
611                .header(
612                    Row::new(vec!["SID", "Name", "State", "T", "Label"]).style(
613                        Style::default().fg(Color::LightGreen).add_modifier(Modifier::BOLD),
614                    ),
615                )
616                .column_spacing(1)
617                .style(primary_text)
618                .block(Block::default().borders(Borders::TOP).title("Silos"));
619                frame.render_widget(silo_table, right_split[0]);
620
621                let strate_rows: Vec<Row> = snapshot
622                    .strates
623                    .iter()
624                    .map(|s| Row::new(vec![Cell::from(s.name.as_str()), Cell::from(s.silos.as_str())]))
625                    .collect();
626                let strate_table = Table::new(
627                    strate_rows,
628                    [Constraint::Length(12), Constraint::Min(10)],
629                )
630                .header(
631                    Row::new(vec!["Strate", "BelongsTo"]).style(
632                        Style::default().fg(Color::LightCyan).add_modifier(Modifier::BOLD),
633                    ),
634                )
635                .column_spacing(1)
636                .style(primary_text)
637                .block(Block::default().borders(Borders::TOP).title("Strates"));
638                frame.render_widget(strate_table, right_split[1]);
639
640                let footer = Paragraph::new("[Up/Down] Select process | [q|Esc] Exit")
641                    .style(muted_text)
642                    .block(Block::default().borders(Borders::TOP));
643                frame.render_widget(footer, vertical[5]);
644            })
645            .map_err(|_| ShellError::ExecutionFailed)?;
646
647        if frame_started {
648            vga::end_frame();
649        } else {
650            vga::present();
651        }
652
653        crate::process::yield_task();
654    }
655
656    // Clean exit.
657    vga::set_double_buffer_mode(was_db);
658    crate::shell::output::clear_screen();
659    vga::set_text_cursor(0, 0);
660    shell_println!("Top exited.");
661    Ok(())
662}