Repository navigation
Expand file tree
/
Copy pathshell.rs
More file actions
758 lines (717 loc) · 30.3 KB
/
Copy pathshell.rs
File metadata and controls
758 lines (717 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
256
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
300
301
302
303
304
305
306
307
308
309
310
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
//! Minimal line-oriented debug shell on the kernel console.
use crate::sched::{self, State};
use crate::sync::{Mutex, Semaphore};
use crate::{clock, console, heap, irq, kprint, kprintln, time};
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};
/// Room for `wifi save` with a 32-byte SSID and a 63-character password,
/// and for `config set` with an OAuth client ID.
const MAX_LINE: usize = 192;
pub fn run(_: usize) {
let mut line = [0u8; MAX_LINE];
let mut len = 0;
kprint!("p4os> ");
loop {
let byte = console::read_byte_blocking();
match byte {
b'\r' | b'\n' => {
kprintln!();
execute(core::str::from_utf8(&line[..len]).unwrap_or(""), true);
len = 0;
kprint!("p4os> ");
}
0x08 | 0x7F if len > 0 => {
len -= 1;
kprint!("\x08 \x08");
}
0x20..=0x7E if len < MAX_LINE => {
// Typed credentials are echoed as '*' so they stay out of
// serial logs.
let echo = if typing_hidden_value(&line[..len]) { b'*' } else { byte };
line[len] = byte;
len += 1;
console::write_bytes(&[echo]);
}
_ => {}
}
}
}
/// True once `typed` is `config set KEY ` for a key whose value is masked.
fn typing_hidden_value(typed: &[u8]) -> bool {
let Some(rest) = typed.strip_prefix(b"config set ") else { return false };
let Some(space) = rest.iter().position(|&b| b == b' ') else { return false };
core::str::from_utf8(&rest[..space]).is_ok_and(p4os_sdk::config::is_masked)
}
/// Run a command and return its output instead of printing it. Used by
/// the Terminal app, so commands reserved for the serial console are refused.
pub fn capture(cmd: &str) -> alloc::string::String {
console::capture_start();
execute(cmd, false);
console::capture_end()
}
/// `serial`: typed on the physical serial console (trusted), as opposed to
/// coming from an app.
fn execute(cmd: &str, serial: bool) {
match cmd.trim() {
"" => {}
"help" => kprintln!(
"commands: help uptime clock irq ps mem demo membench bench lcd hwscan flash config \"config set KEY VALUE\" \"config unset KEY\" \"config stress N\" wifi lock get yt dl play stop power smpdemo apps run start kill top tap swipe pmp crash screenshot"
),
"flash" => crate::flash::diagnose(),
c if c == "power" || c.starts_with("power ") => crate::power::command(&c["power".len()..]),
c if c == "crash" || c.starts_with("crash ") => crate::fault::command(&c[5..]),
"apps" => crate::apploader::list(),
"pmp" => pmp_survey(),
c if c == "run" || c.starts_with("run ") => run_app(c[3..].trim(), true),
c if c == "start" || c.starts_with("start ") => run_app(c[5..].trim(), false),
c if c.starts_with("kill ") => match c[5..].trim().parse::<usize>() {
Ok(tid) if crate::appctl::kill(tid) => kprintln!("killing app thread {}", tid),
Ok(tid) => kprintln!("kill: thread {} runs no user app", tid),
Err(_) => kprintln!("usage: kill THREAD (see top)"),
},
"top" => crate::appctl::print_top(),
"config" | "config list" => config_list(),
c if c.starts_with("config set ") => config_set(c["config set ".len()..].trim()),
c if c.starts_with("config unset ") => config_unset(c["config unset ".len()..].trim()),
c if c.starts_with("config stress") => match c["config stress".len()..].trim().parse() {
Ok(n) => config_stress(n),
Err(_) => kprintln!("usage: config stress N"),
},
c if c == "screenshot" || c.starts_with("screenshot ") => crate::screenshot::command(c[10..].trim(), serial),
"lock" => lock_status(),
"lock now" => crate::gui::request_lock(),
"lock bench" => lock_bench(),
"lock reset" => kprintln!("this removes the lock screen passcode; type: lock reset {}", LOCK_RESET_WORD),
c if c.strip_prefix("lock reset ") == Some(LOCK_RESET_WORD) => lock_reset(serial),
"wifi" => wifi_status(),
"wifi forget" => wifi_forget(),
c if c.starts_with("wifi save ") => wifi_join(c["wifi save ".len()..].trim(), true),
c if c.starts_with("wifi connect ") => wifi_join(c["wifi connect ".len()..].trim(), false),
"membench" => membench(),
"bench" => crate::bench::run(),
"lcd" => crate::display::diagnose(),
"hwscan" => hwscan(),
"sd" => sd_probe(crate::sdmmc::DEFAULT_BUS),
"audio" => crate::audio::diagnose(),
"c6" => crate::c6::probe(),
c if c.starts_with("get ") => http_get(c[4..].trim()),
c if c == "yt" || c.starts_with("yt ") => crate::yt::command(&c[2..]),
c if c.starts_with("dl ") => download(c[3..].trim()),
c if c.starts_with("play ") => play_file(c[5..].trim()),
"stop" => {
use p4os_sdk::Audio;
crate::audio::Speaker.stop();
}
c if c.starts_with("tone") => {
use p4os_sdk::Audio;
let freq = c[4..].trim().parse().unwrap_or(1000);
crate::audio::Speaker.play(alloc::boxed::Box::new(crate::audio::Tone::new(freq, 3000)));
}
c if c == "ls" || c.starts_with("ls ") => ls(c[2..].trim()),
"format sd" => kprintln!("this erases the whole SD card; type: format sd ERASE-ALL"),
"format sd ERASE-ALL" => match crate::fs::format() {
Ok(()) => kprintln!("SD card formatted"),
Err(e) => kprintln!("format failed: {}", e),
},
"sd slow1" => sd_probe(crate::sdmmc::BusConfig { four_bit: false, clock: (10, 20) }),
"sd slow4" => sd_probe(crate::sdmmc::BusConfig { four_bit: true, clock: (10, 20) }),
"sd fast1" => sd_probe(crate::sdmmc::BusConfig { four_bit: false, clock: (8, 0) }),
c if c.starts_with("fill ") => fill(&c[5..]),
c if c.starts_with("tap ") => {
let mut it = c[4..].split_whitespace().map(|v| v.parse::<u16>());
match (it.next(), it.next()) {
(Some(Ok(x)), Some(Ok(y))) => crate::gui::inject_tap(x, y),
_ => kprintln!("usage: tap X Y"),
}
}
c if c.starts_with("swipe ") => {
let parts: alloc::vec::Vec<&str> = c[6..].split_whitespace().collect();
let n: alloc::vec::Vec<Option<u16>> = parts.iter().take(5).map(|v| v.parse().ok()).collect();
let hold = match parts.get(5).copied() {
None => Some(false),
Some("hold") => Some(true),
Some(_) => None,
};
match (n.as_slice(), hold) {
([Some(x1), Some(y1), Some(x2), Some(y2), Some(ms)], Some(hold)) if parts.len() <= 6 => {
crate::gui::inject_swipe((*x1, *y1), (*x2, *y2), *ms as u32, hold)
}
_ => kprintln!("usage: swipe X1 Y1 X2 Y2 MS [hold]"),
}
}
c if c.starts_with("bl ") => match c[3..].trim().parse::<u32>() {
Ok(pct) => {
// A lit, awake panel first; the GUI sets its own level on wake.
crate::power::wake_screen_blocking(1000);
crate::backlight::set(pct as f32 / 100.0)
}
Err(_) => kprintln!("usage: bl 0..100"),
},
"vpg on" => crate::display::test_pattern(true),
"vpg off" => crate::display::test_pattern(false),
"ps" => dump_threads(),
"mem" => {
let (used, total) = heap::usage();
let (pused, ptotal) = heap::psram_usage();
kprintln!("sram: {} / {} bytes used, largest free block {}", used, total, heap::largest_free());
kprintln!("psram: {} / {} bytes used", pused, ptotal);
let (stacks, stack_bytes) = heap::stack_pool_idle();
kprintln!("stack pool: {} idle stacks, {} bytes (counted as used)", stacks, stack_bytes);
let (speak, ppeak) = heap::take_peaks();
kprintln!("peak since last mem: sram {} psram {}", speak, ppeak);
}
"demo" => demo(),
"smpdemo" => smpdemo(),
"uptime" => kprintln!("{} ms", time::ticks()),
"clock" => kprintln!("{}, cpu ~{} MHz", clock::dividers(), crate::measure_cpu_mhz()),
"irq" => kprintln!("tick {} Hz, worst alarm latency {:.2} us", time::TICK_HZ, time::max_latency_us()),
other => kprintln!("unknown command: {}", other),
}
}
/// `pmp`: per core, how well PMP can confine user apps (probes each core
/// once and logs its locked entries).
fn pmp_survey() {
for (hart, verdict) in crate::pmp::survey().iter().enumerate() {
kprintln!("core {}: {:?}", hart, verdict);
}
match crate::pmp::app_hart() {
Ok(h) => kprintln!("user apps run on core {}", h),
Err(e) => kprintln!("user apps unavailable: {}", e),
}
}
/// `run SLOT [ARG]`: start the user app in a flash slot and wait for it to
/// end. The kernel logs how it ended (exit code or the fault that killed it).
/// `start SLOT [ARG]` does not wait. Both go through the user-app limits.
fn run_app(args: &str, wait: bool) {
let mut it = args.split_whitespace().map(str::parse::<u32>);
let (slot, arg) = match (it.next(), it.next(), it.next()) {
(Some(Ok(slot)), None, None) => (slot, 0),
(Some(Ok(slot)), Some(Ok(arg)), None) => (slot, arg),
_ => {
kprintln!("usage: run|start SLOT [ARG]");
return;
}
};
match crate::appctl::start(slot as usize, arg) {
Ok((_, status)) if wait => {
while status.outcome().is_none() {
sched::sleep_ms(10);
}
}
Ok((tid, _)) => kprintln!("started in thread {}", tid),
Err(e) => kprintln!("run: slot {}: {}", slot, e),
}
}
pub fn dump_threads() {
let threads = match sched::snapshot() {
Ok(threads) => threads,
Err(owner) => {
kprintln!("*** scheduler lock stuck (held by hart {:?})", owner);
return;
}
};
let loads: [f32; irq::HART_COUNT] = core::array::from_fn(sched::cpu_load);
kprintln!("cpu load: core0 {:.0}% core1 {:.0}%", loads[0] * 100.0, loads[1] * 100.0);
kprintln!(" id name prio state core pin cpu ms stack used");
for t in threads.into_iter().flatten() {
let state = match t.state {
State::Ready if t.cpu.is_some() => "running",
State::Ready => "ready",
State::Sleeping { .. } => "sleeping",
State::Blocked => "blocked",
State::Exited => "exited",
};
// Core running the thread, or the last one that did.
let core = t.cpu.or(t.last_cpu).map_or('-', |c| (b'0' + c as u8) as char);
let pin = t.affinity.map_or("any", |c| if c == 0 { "0" } else { "1" });
kprintln!(
"{:>3} {:<12} {:>4} {:<14} {:>4} {:<4} {:>7} {:>5}/{}",
t.id, t.name, t.priority, state, core, pin, t.run_ticks, t.stack_used, t.stack_size
);
}
}
static COUNTER: Mutex<u32> = Mutex::new(0);
const DEMO_ITERATIONS: u32 = 200_000;
/// Two equal-priority threads hammer a mutex while a third does float math,
/// exercising preemption, blocking and FP context switching together.
fn demo() {
*COUNTER.lock() = 0;
let start = time::ticks();
sched::spawn("worker-a", 1, 2048, worker, 0);
sched::spawn("worker-b", 1, 2048, worker, 1);
sched::spawn("float", 1, 2048, float_worker, 0);
while *COUNTER.lock() < 2 * DEMO_ITERATIONS {
sched::sleep_ms(20);
}
kprintln!("demo: counter = {} after {} ms", *COUNTER.lock(), time::ticks() - start);
}
fn worker(_: usize) {
for _ in 0..DEMO_ITERATIONS {
*COUNTER.lock() += 1;
}
}
fn float_worker(_: usize) {
let mut x = 1.0f32;
for i in 0..2_000_000u32 {
x = x * 1.000_000_1 + (i & 7) as f32 * 1e-7;
}
let expected_close = (x - 1.6).abs() < 1.0;
kprintln!("float: x = {} ({})", x, if expected_close { "plausible" } else { "SUSPICIOUS" });
}
const SMP_WORK: u32 = 40_000_000;
/// Above the GUI and audio threads, so the run compares raw core
/// throughput instead of whatever time the desktop leaves over.
const SMP_PRIORITY: u8 = 5;
static SMP_DONE: Semaphore = Semaphore::new(0);
/// Bitmask of the cores each worker was seen running on.
static SMP_CORES: [AtomicU32; 2] = [AtomicU32::new(0), AtomicU32::new(0)];
/// Run the same CPU-bound job on one thread, then on two threads at once,
/// and compare throughput. With both cores in use the pair should finish
/// in about the time one thread needs.
fn smpdemo() {
let one = smp_run(1);
let two = smp_run(2);
kprintln!(
"smpdemo: 1 thread {} ms, 2 threads {} ms -> {:.2}x throughput",
one, two, 2.0 * one as f32 / two.max(1) as f32
);
}
const SMP_NAMES: [&str; 2] = ["spin0", "spin1"];
/// Tick at which the current run started.
static SMP_START: AtomicU32 = AtomicU32::new(0);
fn smp_run(threads: usize) -> u32 {
for cores in &SMP_CORES {
cores.store(0, Ordering::Relaxed);
}
// Spawned from a thread that outranks the workers, so the first worker
// cannot preempt the spawner before the second one exists.
sched::spawn("spin-start", SMP_PRIORITY + 1, 4096, smp_launch, threads);
for _ in 0..threads {
SMP_DONE.acquire();
}
let ms = time::ticks() - SMP_START.load(Ordering::Relaxed);
for (i, cores) in SMP_CORES.iter().enumerate().take(threads) {
kprintln!(" {}: ran on core mask {:#b}", SMP_NAMES[i], cores.load(Ordering::Relaxed));
}
ms
}
fn smp_launch(threads: usize) {
SMP_START.store(time::ticks(), Ordering::Relaxed);
for (i, name) in SMP_NAMES.iter().enumerate().take(threads) {
sched::spawn(name, SMP_PRIORITY, 4096, smp_worker, i);
}
}
static BURN_STOP: AtomicBool = AtomicBool::new(false);
/// Like an `smpdemo` worker, but runs until `BURN_STOP` at low priority.
fn burner(i: usize) {
let mut x = 0x1234_5678u32.wrapping_add(i as u32);
while !BURN_STOP.load(Ordering::Relaxed) {
for _ in 0..0x1000 {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
}
SMP_CORES[i].fetch_or(1 << irq::hart_id(), Ordering::Relaxed);
}
core::hint::black_box(x);
SMP_DONE.release();
}
/// Save settings `n` times while two threads keep both cores busy, so the
/// flash path must park the other core every time. A scratch key is
/// written and removed; every other entry must survive unchanged.
fn config_stress(n: u32) {
const KEY: &str = "test.stress";
let before = crate::config::entries();
BURN_STOP.store(false, Ordering::Relaxed);
for (i, cores) in SMP_CORES.iter().enumerate() {
cores.store(0, Ordering::Relaxed);
sched::spawn(["burn0", "burn1"][i], 1, 4096, burner, i);
}
let start = time::ticks();
let mut failed = None;
for i in 0..n {
let value = alloc::format!("{}", i);
if let Err(e) = crate::config::set(KEY, &value) {
failed = Some(alloc::format!("save {} failed: {:?}", i, e));
break;
}
if crate::config::get(KEY).as_deref() != Some(value.as_str()) {
failed = Some(alloc::format!("save {} read back wrong", i));
break;
}
}
let ms = time::ticks() - start;
BURN_STOP.store(true, Ordering::Relaxed);
SMP_DONE.acquire();
SMP_DONE.acquire();
let cleanup = crate::config::update(|e| {
e.remove(KEY);
});
let intact = crate::config::entries() == before;
kprintln!(
"config stress: {} in {} ms, burners on core masks {:#b}/{:#b}, cleanup {:?}, other entries {}",
failed.as_deref().unwrap_or("all saves ok"),
ms,
SMP_CORES[0].load(Ordering::Relaxed),
SMP_CORES[1].load(Ordering::Relaxed),
cleanup,
if intact { "intact" } else { "CHANGED" }
);
}
fn smp_worker(i: usize) {
let mut x = 0x1234_5678u32.wrapping_add(i as u32);
for k in 0..SMP_WORK {
x ^= x << 13;
x ^= x >> 17;
x ^= x << 5;
if k & 0xFFFF == 0 {
SMP_CORES[i].fetch_or(1 << irq::hart_id(), Ordering::Relaxed);
}
}
core::hint::black_box(x);
SMP_DONE.release();
}
/// Sequential write/read/copy throughput of a 1 MiB block in SRAM-backed
/// heap vs PSRAM, through the caches (what a framebuffer sees).
fn membench() {
use alloc::vec;
const LEN: usize = 1 << 20;
let mut psram = vec![0u32; LEN / 4];
let mut psram2 = vec![0u32; LEN / 4];
let addr = psram.as_ptr() as usize;
let mb_per_s = |ticks: u64| (LEN as u64 * crate::systimer::TICKS_PER_US) / ticks.max(1);
let t = crate::systimer::now_ticks();
for (i, w) in psram.iter_mut().enumerate() {
unsafe { core::ptr::write_volatile(w, i as u32) };
}
crate::psram::cache_writeback(addr, LEN);
let write = mb_per_s(crate::systimer::now_ticks() - t);
crate::psram::cache_invalidate(addr, LEN);
let t = crate::systimer::now_ticks();
let mut sum = 0u32;
for w in psram.iter() {
sum = sum.wrapping_add(unsafe { core::ptr::read_volatile(w) });
}
let read = mb_per_s(crate::systimer::now_ticks() - t);
let t = crate::systimer::now_ticks();
psram2.copy_from_slice(&psram);
crate::psram::cache_writeback(psram2.as_ptr() as usize, LEN);
let copy = mb_per_s(crate::systimer::now_ticks() - t);
kprintln!("1 MiB at {:#x}: write {} MB/s, read {} MB/s, copy {} MB/s (sum {:#x})", addr, write, read, copy, sum);
}
/// Probe every device the OS is expected to manage and report what answers.
fn hwscan() {
use crate::{gpio, i2c, touch};
kprintln!("I2C1 (SDA=GPIO7, SCL=GPIO8):");
let mut found = 0;
for addr in 0x08u8..0x78 {
if i2c::probe(addr) {
found += 1;
let name = match addr {
0x18 => "ES8311 audio codec",
0x5D | 0x14 => "GT911 touch controller",
0x36 => "camera sensor (OV02C10/OV5647 class)",
0x30 | 0x32 => "camera sensor (SC2336 class)",
0x3C | 0x3D => "camera sensor or OLED",
0x68 | 0x69 => "IMU (MPU/ICM/BMI class)",
0x6A | 0x6B => "IMU (LSM6/QMI8658 class)",
0x19 | 0x1E => "accelerometer/magnetometer",
0x51 => "RTC (PCF8563 class)",
0x40 | 0x41 | 0x44 | 0x45 => "power/temperature/humidity sensor",
0x76 | 0x77 => "pressure sensor (BMP/BME class)",
_ => "unknown device",
};
kprintln!(" {:#04x} {}", addr, name);
}
}
kprintln!(" {} device(s) answered", found);
if let Some(id) = touch::product_id() {
kprintln!("GT911 product id: {:?}", core::str::from_utf8(&id).unwrap_or("?"));
}
let mut chip = [0u8; 2];
if i2c::write_read(0x18, &[0xFD], &mut chip[..1]).is_ok() && i2c::write_read(0x18, &[0xFE], &mut chip[1..]).is_ok() {
kprintln!("ES8311 chip id: {:02x}{:02x}", chip[0], chip[1]);
}
gpio::input(35, true);
kprintln!("BOOT button (GPIO35): {}", if gpio::read(35) { "released" } else { "pressed" });
}
/// `fill RRGGBB` paints the whole screen one colour; `fill off` returns to
/// the desktop.
fn fill(arg: &str) {
use core::sync::atomic::Ordering;
let arg = arg.trim();
if arg == "off" {
crate::display::OVERRIDE.store(0, Ordering::Relaxed);
return;
}
match u32::from_str_radix(arg, 16) {
Ok(rgb) if arg.len() == 6 => {
let (r, g, b) = ((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);
let c565 = ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
crate::display::OVERRIDE.store(0x1_0000 | c565, Ordering::Relaxed);
}
_ => kprintln!("usage: fill RRGGBB | fill off"),
}
}
/// Initialise the SD card and dump the partition table from sector 0.
fn sd_probe(bus: crate::sdmmc::BusConfig) {
match crate::sdmmc::init_with(bus) {
Ok(blocks) => {
let mut mbr = alloc::vec![0u8; 512];
match crate::sdmmc::read_blocks(0, &mut mbr) {
Ok(()) => {
kprintln!("sector 0 signature {:02x}{:02x}, first bytes {:02x?}", mbr[510], mbr[511], &mbr[..16]);
for p in 0..4 {
let e = &mbr[446 + p * 16..462 + p * 16];
let lba = u32::from_le_bytes(e[8..12].try_into().unwrap());
let len = u32::from_le_bytes(e[12..16].try_into().unwrap());
if e[4] != 0 {
kprintln!(" partition {}: type {:#04x} start {} size {} MiB", p, e[4], lba, len / 2048);
}
}
}
Err(e) => kprintln!("sd read failed: {:?}", e),
}
kprintln!("capacity {} blocks", blocks);
}
Err(e) => kprintln!("sd init failed: {:?}", e),
}
}
fn ls(path: &str) {
use p4os_sdk::FileSystem;
let path = if path.is_empty() { "/sd" } else { path };
match crate::fs::SdFs.list(path) {
Ok(entries) => {
for e in entries {
if e.is_dir {
kprintln!(" {}/", e.name);
} else {
kprintln!(" {:<40} {:>10}", e.name, e.size);
}
}
}
Err(e) => kprintln!("ls {}: {:?}", path, e),
}
}
/// Fetch a URL through the network service and print a summary.
fn http_get(url: &str) {
let id = crate::net::fetch(url);
let start = crate::time::ticks();
loop {
match crate::net::poll_fetch(id) {
// Requests queue until DHCP is up; do not hang the shell forever.
p4os_sdk::FetchState::Pending if crate::time::ticks().wrapping_sub(start) > 60_000 => {
kprintln!("fetch still pending after 60 s (is Wi-Fi up?)");
return;
}
p4os_sdk::FetchState::Pending => crate::sched::sleep_ms(50),
p4os_sdk::FetchState::Done { status, content_type, body } => {
let preview = alloc::string::String::from_utf8_lossy(&body[..body.len().min(300)]).into_owned();
kprintln!("HTTP {} {} ({} bytes, {} ms)\n{}", status, content_type, body.len(), crate::time::ticks() - start, preview);
return;
}
p4os_sdk::FetchState::Failed(e) => {
kprintln!("fetch failed: {}", e);
return;
}
}
}
}
/// `dl URL /sd/PATH`: fetch a URL and save the body to the SD card.
fn download(args: &str) {
use p4os_sdk::FileSystem;
let Some((url, path)) = args.split_once(' ') else {
kprintln!("usage: dl URL /sd/PATH");
return;
};
let (url, path) = (url.trim(), path.trim());
let id = crate::net::fetch(url);
let start = crate::time::ticks();
loop {
match crate::net::poll_fetch(id) {
p4os_sdk::FetchState::Pending if crate::time::ticks().wrapping_sub(start) > 300_000 => {
kprintln!("download still pending after 300 s");
return;
}
p4os_sdk::FetchState::Pending => crate::sched::sleep_ms(100),
p4os_sdk::FetchState::Done { status, body, .. } if status == 200 => {
let fetched = crate::time::ticks() - start;
match crate::fs::SdFs.write(path, &body) {
Ok(()) => kprintln!("saved {} bytes to {} (fetch {} ms, total {} ms)", body.len(), path, fetched, crate::time::ticks() - start),
Err(e) => kprintln!("write {} failed: {:?}", path, e),
}
return;
}
p4os_sdk::FetchState::Done { status, .. } => {
kprintln!("HTTP {}: not saved", status);
return;
}
p4os_sdk::FetchState::Failed(e) => {
kprintln!("download failed: {}", e);
return;
}
}
}
}
/// `play /sd/PATH`: play an MP3 or WAV file through the speaker; `stop` ends it.
fn play_file(path: &str) {
use p4os_sdk::{Audio, FileSystem};
let name = path.rsplit('/').next().unwrap_or(path);
match crate::fs::SdFs.open(path).ok().and_then(|r| p4os_media::audio::open(name, r)) {
Some(src) => {
crate::audio::Speaker.play(src);
kprintln!("playing {}", path);
}
None => kprintln!("can't play {}", path),
}
}
/// Print the settings; secrets show only whether they are set.
fn config_list() {
let entries = crate::config::entries();
if entries.is_empty() {
kprintln!("config: empty");
}
for (k, v) in entries {
let shown = if p4os_sdk::config::is_masked(&k) { "[set]" } else { v.as_str() };
kprintln!("{} = {}", k, shown);
}
}
/// `config set KEY VALUE`: store a setting. Masked values (credentials)
/// are never echoed back; `lock.*` keys are refused so the passcode only
/// changes through Settings or `lock reset`.
fn config_set(args: &str) {
let Some((key, value)) = args.split_once(' ') else {
kprintln!("usage: config set KEY VALUE");
return;
};
if p4os_sdk::config::is_protected(key) {
kprintln!("config: {} can only be changed in Settings or with `lock reset`", key);
return;
}
let value = value.trim();
if let Err(e) = p4os_sdk::config::check_entry(key, value) {
kprintln!("config: {} rejected: {:?}", key, e);
return;
}
match crate::config::set(key, value) {
Ok(()) if p4os_sdk::config::is_masked(key) => kprintln!("{} = [set]", key),
Ok(()) => kprintln!("{} = {}", key, value),
Err(e) => kprintln!("config: saving {} failed: {:?}", key, e),
}
}
fn config_unset(key: &str) {
if p4os_sdk::config::is_protected(key) {
kprintln!("config: {} can only be changed in Settings or with `lock reset`", key);
return;
}
match crate::config::update(|e| {
e.remove(key);
}) {
Ok(()) => kprintln!("{} removed", key),
Err(e) => kprintln!("config: removing {} failed: {:?}", key, e),
}
}
const LOCK_RESET_WORD: &str = "CLEAR-PASSCODE";
/// Lock screen state, without the passcode hash.
fn lock_status() {
use p4os_sdk::config::{LOCK_AUTO, LOCK_ENABLED, LOCK_FAILS, LOCK_PIN, LOCK_UNTIL};
let get = |k| crate::config::get(k).filter(|v| !v.is_empty());
kprintln!(
"lock: {}, passcode {}, auto-lock {}, failed attempts {}, lockout {}",
if get(LOCK_ENABLED).as_deref() == Some("1") { "on" } else { "off" },
if get(LOCK_PIN).is_some() { "set" } else { "not set" },
get(LOCK_AUTO).as_deref().unwrap_or("screen-off"),
get(LOCK_FAILS).as_deref().unwrap_or("0"),
if get(LOCK_UNTIL).is_some() { "pending" } else { "none" },
);
}
/// Forget the passcode and the attempt counter. Only from the serial
/// console: physical access to it is the recovery path by design.
fn lock_reset(serial: bool) {
use p4os_sdk::config::{LOCK_ENABLED, LOCK_FAILS, LOCK_PIN, LOCK_UNTIL};
if !serial {
kprintln!("lock reset is only accepted on the serial console");
return;
}
match crate::config::update(|e| {
for k in [LOCK_PIN, LOCK_ENABLED, LOCK_FAILS, LOCK_UNTIL] {
e.remove(k);
}
}) {
Ok(()) => kprintln!("lock: passcode cleared, lock screen off"),
Err(e) => kprintln!("config: saving failed: {:?}", e),
}
}
/// Time one passcode check at the configured PBKDF2 cost (dummy digits).
fn lock_bench() {
use p4os_apps::lock::pin::{ITERATIONS, PinEntry, PinHash, SALT_LEN};
let mut digits = PinEntry::default();
for d in *b"000000" {
digits.push(d);
}
let mut salt = [0u8; SALT_LEN];
crate::rng::fill(&mut salt);
let start = crate::systimer::now_ticks();
let hash = PinHash::new(&digits, salt, ITERATIONS);
let derive_us = (crate::systimer::now_ticks() - start) / crate::systimer::TICKS_PER_US;
let start = crate::systimer::now_ticks();
let ok = hash.verify(&digits);
let verify_us = (crate::systimer::now_ticks() - start) / crate::systimer::TICKS_PER_US;
kprintln!(
"lock bench: PBKDF2-HMAC-SHA256 x{}: hash {} ms, verify {} ms ({})",
ITERATIONS,
derive_us / 1000,
verify_us / 1000,
if ok { "ok" } else { "MISMATCH" }
);
}
fn wifi_status() {
use crate::wifi_auto::Phase;
let ssid = crate::config::get(p4os_sdk::config::WIFI_SSID);
kprintln!("saved network: {}", ssid.as_deref().unwrap_or("none"));
match (crate::wifi_auto::phase(), crate::net::ip()) {
(Phase::Up, Some(ip)) => kprintln!("link: up, {}", ip),
(Phase::Up, None) => kprintln!("link: associated, waiting for DHCP"),
(Phase::Connecting, _) => kprintln!("link: connecting"),
(Phase::Retrying { error, .. }, _) => kprintln!("link: down ({}), retrying", error),
(Phase::Idle, _) => kprintln!("link: down"),
}
}
/// `wifi connect|save SSID [PASSWORD]`: join through the background
/// manager and report the first attempt. The password is never printed.
fn wifi_join(args: &str, save: bool) {
let (ssid, password) = args.split_once(' ').unwrap_or((args, ""));
let password = password.trim();
if let Err(e) = p4os_sdk::config::check_wifi(ssid, password) {
kprintln!("wifi: {}", e);
kprintln!("usage: wifi {} SSID [PASSWORD]", if save { "save" } else { "connect" });
return;
}
if save {
use p4os_sdk::config::{WIFI_PASSWORD, WIFI_SSID};
let saved = crate::config::update(|e| {
e.insert(WIFI_SSID.into(), ssid.into());
e.insert(WIFI_PASSWORD.into(), password.into());
});
match saved {
Ok(()) => kprintln!("config: saved Wi-Fi network '{}'", ssid),
Err(e) => kprintln!("config: saving failed: {:?}", e),
}
}
let generation = crate::wifi_auto::request(ssid, password);
match crate::wifi_auto::wait(generation, 45_000) {
Some(Ok(())) => kprintln!("wifi: up"),
Some(Err(e)) => kprintln!("wifi: {} (retrying in the background)", e),
None => kprintln!("wifi: still connecting in the background"),
}
}
fn wifi_forget() {
use p4os_sdk::config::{WIFI_PASSWORD, WIFI_SSID};
crate::wifi_auto::cancel();
match crate::config::update(|e| {
e.remove(WIFI_SSID);
e.remove(WIFI_PASSWORD);
}) {
Ok(()) => kprintln!("wifi: saved network forgotten (an active link stays up until reset)"),
Err(e) => kprintln!("config: saving failed: {:?}", e),
}
}