-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.rs
More file actions
2711 lines (2486 loc) · 84.6 KB
/
Copy pathmain.rs
File metadata and controls
2711 lines (2486 loc) · 84.6 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
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Neotron Pico BIOS
//!
//! This is the BIOS for the Neotron Pico. It:
//!
//! * initialises the hardware on the Neotron Pico,
//! * loads the Neotron OS (or any other compatible OS), and
//! * implements the Neotron Common BIOS API, to provide hardware abstraction
//! services for the OS.
//!
//! The BIOS is started by having standard Cortex-M Interrupt Vector Table at
//! address `0x1000_0100`. This IVT is found and jumped to by the RP2040 boot
//! block (`0x1000_0000` to `0x1000_00FF`).
// -----------------------------------------------------------------------------
// Licence Statement
// -----------------------------------------------------------------------------
// Copyright (c) Jonathan 'theJPster' Pallant and the Neotron Developers, 2024
//
// This program is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public License as published by the Free Software
// Foundation, either version 3 of the License, or (at your option) any later
// version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
// details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------
#![no_std]
#![no_main]
// -----------------------------------------------------------------------------
// Sub-modules
// -----------------------------------------------------------------------------
mod console;
mod i2s;
mod mcp23s17;
mod multicore;
mod mutex;
mod rtc;
mod sdcard;
mod vga;
// -----------------------------------------------------------------------------
// Imports
// -----------------------------------------------------------------------------
// Standard Library Stuff
use core::{
convert::{TryFrom, TryInto},
fmt::Write,
ptr::{addr_of, addr_of_mut},
sync::atomic::{AtomicBool, AtomicU32, Ordering},
};
// Third Party Stuff
use chrono::DateTime;
use defmt::info;
use defmt_rtt as _;
use ds1307::{Datelike, Timelike};
use embedded_hal::{
blocking::i2c::{
Read as _I2cRead, WriteIter as _I2cWriteIter, WriteIterRead as _I2cWriteIterRead,
},
blocking::spi::{Transfer as _SpiTransfer, Write as _SpiWrite},
digital::v2::{InputPin, OutputPin},
};
use fugit::RateExtU32;
use hal::{
clocks::ClocksManager,
entry,
gpio::{
bank0::{self, Gpio16, Gpio18, Gpio19},
FunctionPio0, FunctionPio1, FunctionSioOutput, FunctionSpi, Pin, PullNone,
},
pac::{self, interrupt},
Clock,
};
use panic_probe as _;
use pc_keyboard::{KeyCode, ScancodeSet};
use rp2040_hal as hal;
// Other Neotron Crates
use mutex::NeoMutex;
use neotron_bmc_commands::Command;
use neotron_bmc_protocol::Receivable;
use neotron_common_bios::{
self as common,
hid::HidEvent,
video::{Attr, TextBackgroundColour, TextForegroundColour},
ApiResult, Error as CError, FfiBuffer, FfiByteSlice, FfiOption, FfiString, MemoryRegion,
};
// -----------------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------------
/// What we count our system ticks in
type Duration = fugit::Duration<u64, 1, 1_000_000>;
/// The type of our IRQ input pin from the MCP23S17.
type IrqPin = Pin<bank0::Gpio20, hal::gpio::FunctionSioInput, hal::gpio::PullUp>;
type I2cPins = (
Pin<bank0::Gpio14, hal::gpio::FunctionI2C, hal::gpio::PullNone>,
Pin<bank0::Gpio15, hal::gpio::FunctionI2C, hal::gpio::PullNone>,
);
type SpiBus = hal::Spi<
hal::spi::Enabled,
pac::SPI0,
(
Pin<Gpio19, FunctionSpi, PullNone>,
Pin<Gpio16, FunctionSpi, PullNone>,
Pin<Gpio18, FunctionSpi, PullNone>,
),
8,
>;
/// What state our SD Card can be in
#[derive(defmt::Format, Debug, Clone, PartialEq, Eq)]
enum CardState {
Unplugged,
Uninitialised,
#[allow(unused)]
Online(CardInfo),
#[allow(unused)]
Errored,
}
/// Describes an SD card we've discovered
#[derive(defmt::Format, Debug, Clone, PartialEq, Eq)]
struct CardInfo {
/// Number of blocks on the SD card
num_blocks: u64,
/// Type of card
card_type: embedded_sdmmc::sdcard::CardType,
}
/// All the hardware we use on the Pico
struct Hardware {
/// All the pins we use on the Raspberry Pi Pico
pins: Pins,
/// The SPI bus connected to all the slots
spi_bus: SpiBus,
/// Something to perform small delays with. Uses SysTICK.
delay: cortex_m::delay::Delay,
/// Current 5-bit value shown on the LEDs (including the HDD in bit 0).
led_state: u8,
/// The last CS pin we selected
last_cs: u8,
/// Our keyboard decoder
keyboard: pc_keyboard::ScancodeSet2,
/// Our queue of HID events
event_queue: heapless::Deque<common::hid::HidEvent, 16>,
/// A place to send/receive bytes to/from the BMC
bmc_buffer: [u8; 64],
/// Our last interrupt read from the IO chip. It's inverted, so a bit set
/// means an interrupt is pending on that slot.
interrupts_pending: u8,
/// The number of IRQs we've had
irq_count: u32,
/// Our I2C Bus
i2c: shared_bus::BusManagerSimple<hal::i2c::I2C<pac::I2C1, I2cPins, hal::i2c::Controller>>,
/// Our External RTC (on the I2C bus)
rtc: rtc::Rtc,
/// The time we started up at, in microseconds since the Neotron epoch
bootup_at: Duration,
/// A 1 MHz Timer
timer: hal::timer::Timer,
/// the state of our SD Card
card_state: CardState,
/// Tracks all the clocks in the RP2040
clocks: ClocksManager,
/// The watchdog
watchdog: hal::Watchdog,
/// The audio CODEC
audio_codec: tlv320aic23::Codec,
/// PCM sample output queue
audio_player: i2s::Player,
/// How we are currently configured
audio_config: common::audio::Config,
}
/// Flips between true and false so we always send a unique read request
struct UseAlt(AtomicBool);
impl UseAlt {
const fn new() -> UseAlt {
UseAlt(AtomicBool::new(false))
}
fn get(&self) -> bool {
let use_alt = self.0.load(Ordering::Relaxed);
self.0.store(!use_alt, Ordering::Relaxed);
use_alt
}
}
/// All the pins we use on the Pico, in the right mode.
///
/// We ignore the 'unused' lint, because these pins merely need to exist in
/// order to demonstrate the hardware is in the right state.
#[allow(unused)]
struct Pins {
h_sync: Pin<bank0::Gpio0, FunctionPio0, PullNone>,
v_sync: Pin<bank0::Gpio1, FunctionPio0, PullNone>,
red0: Pin<bank0::Gpio2, FunctionPio0, PullNone>,
red1: Pin<bank0::Gpio3, FunctionPio0, PullNone>,
red2: Pin<bank0::Gpio4, FunctionPio0, PullNone>,
red3: Pin<bank0::Gpio5, FunctionPio0, PullNone>,
green0: Pin<bank0::Gpio6, FunctionPio0, PullNone>,
green1: Pin<bank0::Gpio7, FunctionPio0, PullNone>,
green2: Pin<bank0::Gpio8, FunctionPio0, PullNone>,
green3: Pin<bank0::Gpio9, FunctionPio0, PullNone>,
blue0: Pin<bank0::Gpio10, FunctionPio0, PullNone>,
blue1: Pin<bank0::Gpio11, FunctionPio0, PullNone>,
blue2: Pin<bank0::Gpio12, FunctionPio0, PullNone>,
blue3: Pin<bank0::Gpio13, FunctionPio0, PullNone>,
npower_save: Pin<bank0::Gpio23, FunctionSioOutput, PullNone>,
nspi_cs_io: Pin<bank0::Gpio17, FunctionSioOutput, PullNone>,
noutput_en: Pin<bank0::Gpio21, FunctionSioOutput, PullNone>,
i2s_adc_data: Pin<bank0::Gpio22, FunctionPio1, PullNone>,
i2s_dac_data: Pin<bank0::Gpio26, FunctionPio1, PullNone>,
i2s_bit_clock: Pin<bank0::Gpio27, FunctionPio1, PullNone>,
i2s_lr_clock: Pin<bank0::Gpio28, FunctionPio1, PullNone>,
}
// -----------------------------------------------------------------------------
// Static and Const Data
// -----------------------------------------------------------------------------
/// The linker will place this boot block at the start of our program image. We
/// need this to help the ROM bootloader get our code up and running.
#[link_section = ".boot2"]
#[no_mangle]
#[used]
pub static BOOT2_FIRMWARE: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080;
/// Version string auto-generated in build.rs
static VERSION: &str = include_str!(concat!(env!("OUT_DIR"), "/version.txt"));
/// Ensures we always send a unique read request
static USE_ALT: UseAlt = UseAlt::new();
/// Our global hardware object.
///
/// You need to grab this to do anything with the hardware.
static HARDWARE: NeoMutex<Option<Hardware>> = NeoMutex::new(None);
/// The pin we use for external interrupt input
static IRQ_PIN: NeoMutex<Option<IrqPin>> = NeoMutex::new(None);
/// Tracks if we have had an IO interrupt.
///
/// Set by the GPIO interrupt routine to reflect the level state of the IRQ input
/// from the IO chip. This this value is `true` if any of `IRQ0` through `IRQ7`
/// is currently active (low).
static INTERRUPT_PENDING: AtomicBool = AtomicBool::new(false);
/// Stack for Core 1
static mut CORE1_STACK: [usize; 256] = [0; 256];
/// The table of API calls we provide the OS
static API_CALLS: common::Api = common::Api {
api_version_get,
bios_version_get,
serial_configure,
serial_get_info,
serial_write,
serial_read,
time_clock_get,
time_clock_set,
configuration_get,
configuration_set,
video_is_valid_mode,
video_set_mode,
video_get_mode,
video_get_framebuffer,
memory_get_region,
video_mode_needs_vram,
hid_get_event,
hid_set_leds,
video_wait_for_line,
block_dev_get_info,
block_write,
block_read,
block_verify,
time_ticks_get,
time_ticks_per_second,
video_get_palette,
video_set_palette,
video_set_whole_palette,
i2c_bus_get_info,
i2c_write_read,
audio_mixer_channel_get_info,
audio_mixer_channel_set_level,
audio_output_set_config,
audio_output_get_config,
audio_output_data,
audio_output_get_space,
audio_input_set_config,
audio_input_get_config,
audio_input_data,
audio_input_get_count,
bus_select,
bus_get_info,
bus_write_read,
bus_exchange,
bus_interrupt_status,
block_dev_eject,
power_idle,
power_control,
compare_and_swap_bool,
};
/// Seconds between the Neotron Epoch (2000-01-01T00:00:00) and the UNIX Epoch (1970-01-01T00:00:00).
const SECONDS_BETWEEN_UNIX_AND_NEOTRON_EPOCH: i64 = 946684800;
extern "C" {
static _flash_os_start: u32;
static _flash_os_len: u32;
static _ram_os_start: u32;
static _ram_os_len: u32;
}
/// What we paint Core 0's stack with
const CORE0_STACK_PAINT_WORD: usize = 0xBBBB_BBBB;
/// What we paint Core 1's stack with
const CORE1_STACK_PAINT_WORD: usize = 0xCCCC_CCCC;
const XOSC_CRYSTAL_FREQ: u32 = 12_000_000;
// -----------------------------------------------------------------------------
// Functions
// -----------------------------------------------------------------------------
/// This is the entry-point to the BIOS. It is called by cortex-m-rt once the
/// `.bss` and `.data` sections have been initialised.
#[entry]
fn main() -> ! {
cortex_m::interrupt::disable();
// Grab the singleton containing all the RP2040 peripherals
let mut pp = pac::Peripherals::take().unwrap();
// Grab the singleton containing all the generic Cortex-M peripherals
let cp = cortex_m::Peripherals::take().unwrap();
// Check if stuff is running that shouldn't be. If so, do a full watchdog reboot.
if stuff_running(&mut pp) {
watchdog_reboot();
}
// Reset the DMA engine. If we don't do this, starting from probe-rs
// (as opposed to a cold-start) is unreliable.
reset_dma_engine(&mut pp);
// Reset the spinlocks.
pp.SIO.spinlock(31).reset();
paint_stacks();
check_stacks();
// Needed by the clock setup
let mut watchdog = hal::watchdog::Watchdog::new(pp.WATCHDOG);
// VERSION has a trailing `\0` as that is what the BIOS/OS API requires.
info!(
"Neotron BIOS v{} (git:{}) starting...",
env!("CARGO_PKG_VERSION"),
VERSION.trim_matches('\0')
);
// Run at 151.2 MHz SYS_PLL, 48 MHz, USB_PLL. This is important, we as clock
// the PIO at ÷ 6, to give 25.2 MHz (which is close enough to the 25.175
// MHz standard VGA pixel clock).
// Step 1. Turn on the crystal.
let xosc = hal::xosc::setup_xosc_blocking(pp.XOSC, XOSC_CRYSTAL_FREQ.Hz())
.map_err(|_x| false)
.unwrap();
// Step 2. Configure watchdog tick generation to tick over every microsecond.
watchdog.enable_tick_generation((XOSC_CRYSTAL_FREQ / 1_000_000) as u8);
// Step 3. Create a clocks manager.
let mut clocks = hal::clocks::ClocksManager::new(pp.CLOCKS);
// Step 4. Set up the system PLL.
//
// We take the Crystal Oscillator (=12 MHz) with no divider, and ×126 to
// give a FOUTVCO of 1512 MHz. This must be in the range 750 MHz - 1600 MHz.
// The factor of 126 is calculated automatically given the desired FOUTVCO.
//
// Next we ÷5 on the first post divider to give 302.4 MHz.
//
// Finally we ÷2 on the second post divider to give 151.2 MHz.
//
// We note from the [RP2040
// Datasheet](https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf),
// Section 2.18.2.1:
//
// > Jitter is minimised by running the VCO at the highest possible
// > frequency, so that higher post-divide values can be used.
let pll_sys = hal::pll::setup_pll_blocking(
pp.PLL_SYS,
xosc.operating_frequency(),
hal::pll::PLLConfig {
vco_freq: 1512.MHz(),
refdiv: 1,
post_div1: 5,
post_div2: 2,
},
&mut clocks,
&mut pp.RESETS,
)
.map_err(|_x| false)
.unwrap();
// Step 5. Set up a 48 MHz PLL for the USB system.
let pll_usb = hal::pll::setup_pll_blocking(
pp.PLL_USB,
xosc.operating_frequency(),
hal::pll::common_configs::PLL_USB_48MHZ,
&mut clocks,
&mut pp.RESETS,
)
.map_err(|_x| false)
.unwrap();
// Step 6. Set the system to run from the PLLs we just configured.
clocks
.init_default(&xosc, &pll_sys, &pll_usb)
.map_err(|_x| false)
.unwrap();
info!("Clocks OK");
// sio is the *Single-cycle Input/Output* peripheral. It has all our GPIO
// pins, as well as some mailboxes and other useful things for inter-core
// communications.
let mut sio = hal::sio::Sio::new(pp.SIO);
// This object lets us wait for long periods of time (to make things readable on screen)
let delay = cortex_m::delay::Delay::new(cp.SYST, clocks.system_clock.freq().to_Hz());
// Configure and grab all the RP2040 pins the Pico exposes, along with the non-VGA peripherals.
let (mut hw, nirq_io) = Hardware::build(
pp.IO_BANK0,
pp.PADS_BANK0,
sio.gpio_bank0,
pp.SPI0,
pp.I2C1,
pp.TIMER,
pp.PIO1,
clocks,
delay,
watchdog,
&mut pp.RESETS,
);
hw.init_io_chip();
hw.set_hdd_led(false);
nirq_io.set_interrupt_enabled(hal::gpio::Interrupt::EdgeLow, true);
nirq_io.set_interrupt_enabled(hal::gpio::Interrupt::EdgeHigh, true);
info!("Pins OK");
vga::init(
pp.PIO0,
pp.DMA,
&mut pp.RESETS,
&mut pp.PPB,
&mut sio.fifo,
&mut pp.PSM,
);
info!("VGA OK");
// Did we start with an interrupt pending?
INTERRUPT_PENDING.store(nirq_io.is_low().unwrap(), Ordering::Relaxed);
// Check for interrupts on start-up (particularly the SD card being in)
hw.io_poll_interrupts(true);
{
let mut lock = HARDWARE.lock();
lock.replace(hw);
}
{
// You can only do this before interrupts are enabled. Otherwise you may
// try and grab the mutex in an ISR whilst it's held in the main thread,
// and that causes a panic.
let mut lock = IRQ_PIN.lock();
lock.replace(nirq_io);
}
// Unmask the IO_BANK0 IRQ so that the NVIC interrupt controller
// will jump to the interrupt function when the interrupt occurs.
// Then enable interrupts on Core 0.
//
// We do this last so that the interrupt can't go off while
// it is in the middle of being configured.
unsafe {
cortex_m::peripheral::NVIC::unmask(pac::Interrupt::IO_IRQ_BANK0);
cortex_m::interrupt::enable();
}
// Empty the keyboard FIFO
while let ApiResult::Ok(FfiOption::Some(_x)) = hid_get_event() {
// Spin
}
// Say hello over VGA
sign_on();
// Now jump to the OS
unsafe {
let entry_fn_addr: *const usize = addr_of!(_flash_os_start) as *const usize;
info!("entry_fn_addr = 0x{:08x}", entry_fn_addr);
let entry_fn = entry_fn_addr.read_volatile();
info!("entry_fn = 0x{:08x}", entry_fn);
if entry_fn != 0xFFFF_FFFF && entry_fn != 0x0000_0000 {
// looks like it's not blank at least - let's jump to it
let code: common::OsStartFn = core::mem::transmute(entry_fn);
code(&API_CALLS);
} else {
// flash looks blank - sit at the splash screen
loop {
cortex_m::asm::wfe();
}
}
}
}
/// Check if the rest of the system appears to be running already.
///
/// If so, returns `true`, else `false`.
///
/// This probably means Core 0 reset but the rest of the system did not, and you
/// should do a hard reset to get everything back into sync.
fn stuff_running(p: &mut pac::Peripherals) -> bool {
// Look at scratch register 7 and see what we left ourselves. If it's zero,
// this was a full clean boot-up. If it's 0xDEADC0DE, this means we were
// running and Core 0 restarted without restarting everything else.
let scratch = p.WATCHDOG.scratch7().read().bits();
defmt::info!("WD Scratch is 0x{:08x}", scratch);
if scratch == 0xDEADC0DE {
// we need a hard reset
true
} else {
// set the marker so we know Core 0 has booted up
p.WATCHDOG
.scratch7()
.write(|w| unsafe { w.bits(0xDEADC0DE) });
false
}
}
/// Clear the scratch register so we don't force a full watchdog reboot on the
/// next boot.
fn clear_scratch() {
let p = unsafe { pac::Peripherals::steal() };
p.WATCHDOG.scratch7().write(|w| unsafe { w.bits(0) });
}
/// Do a full watchdog reboot
fn watchdog_reboot() -> ! {
clear_scratch();
if let Some(hw) = HARDWARE.lock().as_mut() {
hw.watchdog
.start(fugit::Duration::<u32, 1, 1000000>::millis(10));
} else {
// Hardware hasn't been initialised, so make a temporary watchdog driver
let p = unsafe { pac::Peripherals::steal() };
let mut watchdog = hal::Watchdog::new(p.WATCHDOG);
watchdog.start(fugit::Duration::<u32, 1, 1000000>::millis(10));
}
loop {
cortex_m::asm::wfi();
}
}
/// Print the BIOS boot-up messages on a temporary text console
fn sign_on() {
static LOGO_ANSI_BYTES: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/logo.bytes"));
static COPYRIGHT_TEXT: &str = "\
\n\
Copyright © Jonathan 'theJPster' Pallant and the Neotron Developers, 2024\n\
This program is free software under GPL v3 (or later)\n\
You are entitled to the Complete and Corresponding Source for this BIOS\n\
\n\
BIOS: \n\
BMC : \n\
\n\
Press ESC to pause...";
// Create a new temporary console for some boot-up messages
let tc = console::TextConsole::new();
unsafe {
tc.set_text_buffer(vga::GLYPH_ATTR_ARRAY.as_ptr());
}
tc.change_attr(Attr::new(
TextForegroundColour::White,
TextBackgroundColour::Blue,
false,
));
// A crude way to clear the screen
for _col in 0..vga::MAX_TEXT_ROWS {
writeln!(&tc, " ").unwrap();
}
// Draw the logo
tc.move_to(0, 0);
for pair in LOGO_ANSI_BYTES.chunks(2) {
tc.change_attr(Attr(pair[0]));
tc.write_font_glyph(neotron_common_bios::video::Glyph(pair[1]));
}
tc.change_attr(Attr::new(
TextForegroundColour::White,
TextBackgroundColour::Blue,
false,
));
write!(&tc, "{}", COPYRIGHT_TEXT).unwrap();
// Draw the BIOS version
tc.change_attr(Attr::new(
TextForegroundColour::Yellow,
TextBackgroundColour::Black,
false,
));
tc.move_to(12, 6);
write!(
&tc,
"v{} (git:{})",
env!("CARGO_PKG_VERSION"),
VERSION.trim_matches('\0')
)
.unwrap();
// Draw the BMC version
tc.move_to(13, 6);
tc.change_attr(Attr::new(
TextForegroundColour::White,
TextBackgroundColour::Red,
false,
));
let bmc_ver = {
let mut lock = HARDWARE.lock();
let hw = lock.as_mut().unwrap();
let ver = hw.bmc_read_firmware_version();
let _ = hw.play_startup_tune();
ver
};
match bmc_ver {
Ok(string_bytes) => match core::str::from_utf8(&string_bytes) {
Ok(s) => {
write!(&tc, "{}", s.trim_matches('\0')).unwrap();
}
Err(_e) => {
write!(&tc, "Version Unknown").unwrap();
}
},
Err(_e) => {
write!(&tc, "Error reading version").unwrap();
}
}
tc.change_attr(Attr::new(
TextForegroundColour::White,
TextBackgroundColour::Blue,
false,
));
let _ = writeln!(&tc);
// Show the time.
if let Some(hw) = HARDWARE.lock().as_mut() {
if let Some(rtc_kind) = hw.rtc.get_kind() {
let _ = writeln!(&tc, "RTC : Found {}", rtc_kind);
} else {
let _ = writeln!(&tc, "RTC : None");
}
}
// Do a delay.
//
// This is in 100ms units
let mut countdown = 15;
loop {
{
let mut lock = HARDWARE.lock();
let hw = lock.as_mut().unwrap();
hw.delay.delay_ms(100);
}
tc.move_to(15, 0);
match hid_get_event() {
ApiResult::Ok(FfiOption::Some(HidEvent::KeyPress(KeyCode::Escape))) => {
write!(&tc, "Paused - Press SPACE to continue...").unwrap();
countdown = 0;
}
ApiResult::Ok(FfiOption::Some(HidEvent::KeyPress(KeyCode::Spacebar))) => {
write!(&tc, "Unpaused ").unwrap();
countdown = 10;
}
_ => {
// ignore
}
}
if countdown == 1 {
break;
} else {
countdown -= 1;
}
}
write!(&tc, "Looking for OS at 0x1002_0000....").unwrap();
}
/// Paint the Core 0 and Core 1 stacks
fn paint_stacks() {
extern "C" {
static mut __sheap: usize;
static mut _stack_start: usize;
}
unsafe {
let stack_len = (addr_of!(_stack_start) as usize) - (addr_of!(__sheap) as usize);
// But not the top 64 words, because we're using the stack right now!
let stack = core::slice::from_raw_parts_mut(
addr_of_mut!(__sheap),
(stack_len / core::mem::size_of::<usize>()) - 256,
);
info!("Painting Core 1 stack: {:?}", stack.as_ptr_range());
for b in stack.iter_mut() {
*b = CORE0_STACK_PAINT_WORD;
}
let stack_start = addr_of_mut!(CORE1_STACK) as *mut usize;
let stack_end = addr_of_mut!(CORE1_STACK).add(1) as *mut usize;
info!("Painting Core 1 stack @ {:?}", stack_start..stack_end);
let mut p = stack_start;
while p != stack_end {
p.write_volatile(CORE1_STACK_PAINT_WORD);
p = p.add(1);
}
}
}
/// Reset the DMA Peripheral.
fn reset_dma_engine(pp: &mut pac::Peripherals) {
pp.RESETS.reset().modify(|_r, w| w.dma().set_bit());
cortex_m::asm::nop();
pp.RESETS.reset().modify(|_r, w| w.dma().clear_bit());
while pp.RESETS.reset_done().read().dma().bit_is_clear() {}
}
/// Measure how much stack space remains unused.
#[cfg(feature = "check-stack")]
fn check_stacks() {
extern "C" {
static mut __sheap: usize;
static mut _stack_start: usize;
}
let stack_len = (addr_of!(_stack_start) as usize) - (addr_of!(__sheap) as usize);
check_stack(addr_of!(__sheap), stack_len, CORE0_STACK_PAINT_WORD);
let stack_start = addr_of!(CORE1_STACK) as *const usize;
let stack_end = unsafe { addr_of!(CORE1_STACK).add(1) } as *const usize;
let stack_len = unsafe { stack_end.offset_from(stack_start) } as usize;
check_stack(stack_start, stack_len, CORE1_STACK_PAINT_WORD);
}
/// Dummy stack checker that does nothing
#[cfg(not(feature = "check-stack"))]
fn check_stacks() {}
/// Check an individual stack to see how much has been used
#[cfg(feature = "check-stack")]
fn check_stack(start: *const usize, stack_len_bytes: usize, check_word: usize) {
let mut p: *const usize = start;
let mut free_bytes = 0;
loop {
let value = unsafe { p.read_volatile() };
if value != check_word {
break;
}
// Safety: We must hit a used stack value somewhere!
p = unsafe { p.offset(1) };
free_bytes += core::mem::size_of::<usize>();
}
defmt::info!(
"Stack free at 0x{:08x}: {} bytes used of {} bytes",
start,
stack_len_bytes - free_bytes,
stack_len_bytes
);
}
// -----------------------------------------------------------------------------
// Type impl blocks
// -----------------------------------------------------------------------------
impl Hardware {
/// How fast can the I/O chip SPI CLK input go?
const CLOCK_IO: fugit::Rate<u32, 1, 1> = fugit::Rate::<u32, 1, 1>::Hz(10_000_000);
/// How fast can the BMC SPI CLK input go?
const CLOCK_BMC: fugit::Rate<u32, 1, 1> = fugit::Rate::<u32, 1, 1>::Hz(2_000_000);
/// How many nano seconds per clock cycle (at 126 MHz)?
const NS_PER_CLOCK_CYCLE: u32 = 1_000_000_000 / 126_000_000;
/// MCP23S17 CS pin setup time (before transaction). At least 50ns, we give 100ns.
const CS_IO_SETUP_CPU_CLOCKS: u32 = 100 / Self::NS_PER_CLOCK_CYCLE;
/// MCP23S17 CS pin hold time (and end of transaction). At least 50ns, we give 100ns.
const CS_IO_HOLD_CPU_CLOCKS: u32 = 100 / Self::NS_PER_CLOCK_CYCLE;
/// MCP23S17 CS pin disable time (between transactions). At least 50ns, we give 100ns.
const CS_IO_DISABLE_CPU_CLOCKS: u32 = 100 / Self::NS_PER_CLOCK_CYCLE;
/// Give the device 10us to get ready.
///
/// This seems to reduce the error rate on the BMC link to an acceptable level.
const CS_BUS_SETUP_CPU_CLOCKS: u32 = 10_000 / Self::NS_PER_CLOCK_CYCLE;
/// Give the device 2000ns before we take away CS.
const CS_BUS_HOLD_CPU_CLOCKS: u32 = 2000 / Self::NS_PER_CLOCK_CYCLE;
/// Give the device 100ms to sort itself out when we do a retry.
const BMC_RETRY_CPU_CLOCKS: u32 = 100_000_000 / Self::NS_PER_CLOCK_CYCLE;
/// Give the BMC 6us to calculate its response
const BMC_REQUEST_RESPONSE_DELAY_CLOCKS: u32 = 6_000 / Self::NS_PER_CLOCK_CYCLE;
/// Build all our hardware drivers.
///
/// Puts the pins into the right modes, builds the SPI driver, etc.
#[allow(clippy::too_many_arguments)]
fn build(
bank: pac::IO_BANK0,
pads: pac::PADS_BANK0,
sio: hal::sio::SioGpioBank0,
spi: pac::SPI0,
i2c: pac::I2C1,
timer: pac::TIMER,
pio1: pac::PIO1,
clocks: ClocksManager,
delay: cortex_m::delay::Delay,
watchdog: hal::Watchdog,
resets: &mut pac::RESETS,
) -> (Hardware, IrqPin) {
let hal_pins = hal::gpio::Pins::new(bank, pads, sio, resets);
// We construct the pin here and then throw it away. Then Core 1 does
// some unsafe writes to the GPIO_SET/GPIO_CLEAR registers to set/clear
// pin 25 to track render loop timing. This avoids trying to 'move' the pin
// over to Core 1.
let _pico_led = hal_pins.gpio25.into_push_pull_output();
let raw_i2c = hal::i2c::I2C::i2c1_with_external_pull_up(
i2c,
{
let mut pin = hal_pins.gpio14.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
{
let mut pin = hal_pins.gpio15.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
100.kHz(),
resets,
&clocks.system_clock,
);
let i2c = shared_bus::BusManagerSimple::new(raw_i2c);
let mut proxy = i2c.acquire_i2c();
defmt::info!("Probing I2C bus...");
for test_address in 0x09..=0x77 {
let mut readbuf: [u8; 1] = [0; 1];
match proxy.read(test_address, &mut readbuf) {
Ok(_) => {
defmt::info!("{:02x} found <<<<", test_address);
}
Err(_) => {
defmt::info!("{:02x} missing", test_address);
}
}
}
let mut external_rtc = rtc::Rtc::new(proxy);
let timer = hal::timer::Timer::new(timer, resets, &clocks);
// Do a conversion from external RTC time (chrono::NaiveDateTime) to a format we can track
let ticks_at_boot_us = match external_rtc.get_time(i2c.acquire_i2c()) {
Ok(time) => {
defmt::info!(
"Time: {:04}-{:02}-{:02} {:02}:{:02}:{:02}",
time.year(),
time.month(),
time.day(),
time.hour(),
time.minute(),
time.second()
);
let ticks_at_boot_us = time.and_utc().timestamp_micros()
- (SECONDS_BETWEEN_UNIX_AND_NEOTRON_EPOCH * 1_000_000);
defmt::info!("Ticks at boot: {}", ticks_at_boot_us);
ticks_at_boot_us
}
Err(_) => {
defmt::info!("Time: Unknown");
0
}
};
let pins = Pins {
// Disable power save mode to force SMPS into low-efficiency, low-noise mode.
npower_save: {
let mut pin = hal_pins.gpio23.reconfigure();
pin.set_high().unwrap();
pin
},
// Give H-Sync, V-Sync and 12 RGB colour pins to PIO0 to output video
h_sync: {
let mut pin = hal_pins.gpio0.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
v_sync: {
let mut pin = hal_pins.gpio1.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
red0: {
let mut pin = hal_pins.gpio2.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
red1: {
let mut pin = hal_pins.gpio3.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
red2: {
let mut pin = hal_pins.gpio4.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
red3: {
let mut pin = hal_pins.gpio5.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
green0: {
let mut pin = hal_pins.gpio6.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
green1: {
let mut pin = hal_pins.gpio7.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
green2: {
let mut pin = hal_pins.gpio8.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
green3: {
let mut pin = hal_pins.gpio9.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
blue0: {
let mut pin = hal_pins.gpio10.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);
pin.set_slew_rate(hal::gpio::OutputSlewRate::Fast);
pin
},
blue1: {
let mut pin = hal_pins.gpio11.reconfigure();
pin.set_drive_strength(hal::gpio::OutputDriveStrength::EightMilliAmps);