litex_sim/
main.rs

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
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Board file for a LiteX SoC running in a Verilated simulation

#![no_std]
// Disable this attribute when documenting, as a workaround for
// https://github.com/rust-lang/rust/issues/62184.
#![cfg_attr(not(doc), no_main)]

use core::ptr::{addr_of, addr_of_mut};

use capsules_core::virtualizers::virtual_alarm::{MuxAlarm, VirtualMuxAlarm};
use kernel::capabilities;
use kernel::component::Component;
use kernel::hil::led::LedHigh;
use kernel::hil::time::{Alarm, Timer};
use kernel::platform::chip::InterruptService;
use kernel::platform::scheduler_timer::VirtualSchedulerTimer;
use kernel::platform::{KernelResources, SyscallDriverLookup};
use kernel::scheduler::mlfq::MLFQSched;
use kernel::utilities::registers::interfaces::ReadWriteable;
use kernel::utilities::StaticRef;
use kernel::{create_capability, debug, static_init};
use rv32i::csr;

mod io;
mod litex_generated_constants;

// This module contains the LiteX SoC configuration options, register
// positions, interrupt mappings and other implementation details of
// the generated bitstream.
//
// Its values are used throughout the file, hence import it under a
// short name.
use litex_generated_constants as socc;

/// Structure for dynamic interrupt mapping, depending on the SoC
/// configuration
///
/// This struct is deliberately kept in the board crate. Because of
/// the configurable nature of LiteX, it does not make sense to define
/// a default interrupt mapping, as the interrupt numbers are
/// generated sequentially for all softcores.
struct LiteXSimInterruptablePeripherals {
    gpio0: &'static litex_vexriscv::gpio::LiteXGPIOController<'static, socc::SoCRegisterFmt>,
    uart0: &'static litex_vexriscv::uart::LiteXUart<'static, socc::SoCRegisterFmt>,
    timer0: &'static litex_vexriscv::timer::LiteXTimer<
        'static,
        socc::SoCRegisterFmt,
        socc::ClockFrequency,
    >,
    ethmac0: &'static litex_vexriscv::liteeth::LiteEth<'static, socc::SoCRegisterFmt>,
}

impl LiteXSimInterruptablePeripherals {
    // Resolve any recursive dependencies and set up deferred calls:
    pub fn init(&'static self) {
        kernel::deferred_call::DeferredCallClient::register(self.uart0);
    }
}

impl InterruptService for LiteXSimInterruptablePeripherals {
    unsafe fn service_interrupt(&self, interrupt: u32) -> bool {
        match interrupt as usize {
            socc::UART_INTERRUPT => {
                self.uart0.service_interrupt();
                true
            }
            socc::TIMER0_INTERRUPT => {
                self.timer0.service_interrupt();
                true
            }
            socc::ETHMAC_INTERRUPT => {
                self.ethmac0.service_interrupt();
                true
            }
            socc::GPIO_INTERRUPT => {
                self.gpio0.service_interrupt();
                true
            }
            _ => false,
        }
    }
}

const NUM_PROCS: usize = 4;

// Actual memory for holding the active process structures. Need an
// empty list at least.
static mut PROCESSES: [Option<&'static dyn kernel::process::Process>; NUM_PROCS] =
    [None; NUM_PROCS];

// Reference to the chip and UART hardware for panic dumps
struct LiteXSimPanicReferences {
    chip: Option<&'static litex_vexriscv::chip::LiteXVexRiscv<LiteXSimInterruptablePeripherals>>,
    uart: Option<&'static litex_vexriscv::uart::LiteXUart<'static, socc::SoCRegisterFmt>>,
    process_printer: Option<&'static capsules_system::process_printer::ProcessPrinterText>,
}
static mut PANIC_REFERENCES: LiteXSimPanicReferences = LiteXSimPanicReferences {
    chip: None,
    uart: None,
    process_printer: None,
};

// How should the kernel respond when a process faults.
const FAULT_RESPONSE: capsules_system::process_policies::PanicFaultPolicy =
    capsules_system::process_policies::PanicFaultPolicy {};

/// Dummy buffer that causes the linker to reserve enough space for the stack.
#[no_mangle]
#[link_section = ".stack_buffer"]
pub static mut STACK_MEMORY: [u8; 0x2000] = [0; 0x2000];

/// A structure representing this platform that holds references to all
/// capsules for this platform.
struct LiteXSim {
    gpio_driver: &'static capsules_core::gpio::GPIO<
        'static,
        litex_vexriscv::gpio::LiteXGPIOPin<'static, 'static, socc::SoCRegisterFmt>,
    >,
    button_driver: &'static capsules_core::button::Button<
        'static,
        litex_vexriscv::gpio::LiteXGPIOPin<'static, 'static, socc::SoCRegisterFmt>,
    >,
    led_driver: &'static capsules_core::led::LedDriver<
        'static,
        LedHigh<
            'static,
            litex_vexriscv::gpio::LiteXGPIOPin<'static, 'static, socc::SoCRegisterFmt>,
        >,
        8,
    >,
    console: &'static capsules_core::console::Console<'static>,
    lldb: &'static capsules_core::low_level_debug::LowLevelDebug<
        'static,
        capsules_core::virtualizers::virtual_uart::UartDevice<'static>,
    >,
    alarm: &'static capsules_core::alarm::AlarmDriver<
        'static,
        VirtualMuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
    >,
    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
    scheduler: &'static MLFQSched<
        'static,
        VirtualMuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
    >,
    scheduler_timer: &'static VirtualSchedulerTimer<
        VirtualMuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
    >,
}

/// Mapping of integer syscalls to objects that implement syscalls.
impl SyscallDriverLookup for LiteXSim {
    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
    where
        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
    {
        match driver_num {
            capsules_core::button::DRIVER_NUM => f(Some(self.button_driver)),
            capsules_core::led::DRIVER_NUM => f(Some(self.led_driver)),
            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio_driver)),
            capsules_core::console::DRIVER_NUM => f(Some(self.console)),
            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
            capsules_core::low_level_debug::DRIVER_NUM => f(Some(self.lldb)),
            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
            _ => f(None),
        }
    }
}

impl KernelResources<litex_vexriscv::chip::LiteXVexRiscv<LiteXSimInterruptablePeripherals>>
    for LiteXSim
{
    type SyscallDriverLookup = Self;
    type SyscallFilter = ();
    type ProcessFault = ();
    type Scheduler = MLFQSched<
        'static,
        VirtualMuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
    >;
    type SchedulerTimer = VirtualSchedulerTimer<
        VirtualMuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
    >;
    type WatchDog = ();
    type ContextSwitchCallback = ();

    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
        self
    }
    fn syscall_filter(&self) -> &Self::SyscallFilter {
        &()
    }
    fn process_fault(&self) -> &Self::ProcessFault {
        &()
    }
    fn scheduler(&self) -> &Self::Scheduler {
        self.scheduler
    }
    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
        self.scheduler_timer
    }
    fn watchdog(&self) -> &Self::WatchDog {
        &()
    }
    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
        &()
    }
}

/// This is in a separate, inline(never) function so that its stack frame is
/// removed when this function returns. Otherwise, the stack space used for
/// these static_inits is wasted.
#[inline(never)]
unsafe fn start() -> (
    &'static kernel::Kernel,
    LiteXSim,
    &'static litex_vexriscv::chip::LiteXVexRiscv<LiteXSimInterruptablePeripherals>,
) {
    // These symbols are defined in the linker script.
    extern "C" {
        /// Beginning of the ROM region containing app images.
        static _sapps: u8;
        /// End of the ROM region containing app images.
        static _eapps: u8;
        /// Beginning of the RAM region for app memory.
        static mut _sappmem: u8;
        /// End of the RAM region for app memory.
        static _eappmem: u8;
        /// The start of the kernel text (Included only for kernel PMP)
        static _stext: u8;
        /// The end of the kernel text (Included only for kernel PMP)
        static _etext: u8;
        /// The start of the kernel / app / storage flash (Included only for kernel PMP)
        static _sflash: u8;
        /// The end of the kernel / app / storage flash (Included only for kernel PMP)
        static _eflash: u8;
        /// The start of the kernel / app RAM (Included only for kernel PMP)
        static _ssram: u8;
        /// The end of the kernel / app RAM (Included only for kernel PMP)
        static _esram: u8;
    }

    // ---------- BASIC INITIALIZATION ----------

    // Basic setup of the riscv platform.
    rv32i::configure_trap_handler();

    // Set up memory protection immediately after setting the trap handler, to
    // ensure that much of the board initialization routine runs with PMP kernel
    // memory protection.
    let pmp = rv32i::pmp::kernel_protection::KernelProtectionPMP::new(
        rv32i::pmp::kernel_protection::FlashRegion(
            rv32i::pmp::NAPOTRegionSpec::new(
                core::ptr::addr_of!(_sflash),
                core::ptr::addr_of!(_eflash) as usize - core::ptr::addr_of!(_sflash) as usize,
            )
            .unwrap(),
        ),
        rv32i::pmp::kernel_protection::RAMRegion(
            rv32i::pmp::NAPOTRegionSpec::new(
                core::ptr::addr_of!(_ssram),
                core::ptr::addr_of!(_esram) as usize - core::ptr::addr_of!(_ssram) as usize,
            )
            .unwrap(),
        ),
        rv32i::pmp::kernel_protection::MMIORegion(
            rv32i::pmp::NAPOTRegionSpec::new(
                0xf0000000 as *const u8, // start
                0x10000000,              // size
            )
            .unwrap(),
        ),
        rv32i::pmp::kernel_protection::KernelTextRegion(
            rv32i::pmp::TORRegionSpec::new(
                core::ptr::addr_of!(_stext),
                core::ptr::addr_of!(_etext),
            )
            .unwrap(),
        ),
    )
    .unwrap();

    // initialize capabilities
    let process_mgmt_cap = create_capability!(capabilities::ProcessManagementCapability);
    let memory_allocation_cap = create_capability!(capabilities::MemoryAllocationCapability);

    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(&*addr_of!(PROCESSES)));

    // --------- TIMER & UPTIME CORE; ALARM INITIALIZATION ----------

    // Initialize the hardware timer
    let timer0 = static_init!(
        litex_vexriscv::timer::LiteXTimer<'static, socc::SoCRegisterFmt, socc::ClockFrequency>,
        litex_vexriscv::timer::LiteXTimer::new(StaticRef::new(
            socc::CSR_TIMER0_BASE
                as *const litex_vexriscv::timer::LiteXTimerRegisters<socc::SoCRegisterFmt>
        ),)
    );

    // The SoC is expected to feature the 64-bit uptime extension to the timer hardware
    let timer0_uptime = static_init!(
        litex_vexriscv::timer::LiteXTimerUptime<
            'static,
            socc::SoCRegisterFmt,
            socc::ClockFrequency,
        >,
        litex_vexriscv::timer::LiteXTimerUptime::new(timer0)
    );

    // Create the LiteXAlarm based on the hardware LiteXTimer core and
    // the uptime peripheral
    let litex_alarm = static_init!(
        litex_vexriscv::timer::LiteXAlarm<
            'static,
            'static,
            socc::SoCRegisterFmt,
            socc::ClockFrequency,
        >,
        litex_vexriscv::timer::LiteXAlarm::new(timer0_uptime, timer0)
    );
    timer0.set_timer_client(litex_alarm);
    litex_alarm.initialize();

    // Create a shared virtualization mux layer on top of a single hardware
    // alarm.
    let mux_alarm = static_init!(
        MuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
        MuxAlarm::new(litex_alarm)
    );
    litex_alarm.set_alarm_client(mux_alarm);

    // Userspace alarm driver
    let virtual_alarm_user = static_init!(
        VirtualMuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
        VirtualMuxAlarm::new(mux_alarm)
    );
    virtual_alarm_user.setup();

    let alarm = static_init!(
        capsules_core::alarm::AlarmDriver<
            'static,
            VirtualMuxAlarm<
                'static,
                litex_vexriscv::timer::LiteXAlarm<
                    'static,
                    'static,
                    socc::SoCRegisterFmt,
                    socc::ClockFrequency,
                >,
            >,
        >,
        capsules_core::alarm::AlarmDriver::new(
            virtual_alarm_user,
            board_kernel.create_grant(capsules_core::alarm::DRIVER_NUM, &memory_allocation_cap)
        )
    );
    virtual_alarm_user.set_alarm_client(alarm);

    // Systick virtual alarm for scheduling
    let systick_virtual_alarm = static_init!(
        VirtualMuxAlarm<
            'static,
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
        >,
        VirtualMuxAlarm::new(mux_alarm)
    );
    systick_virtual_alarm.setup();

    let scheduler_timer = static_init!(
        VirtualSchedulerTimer<
            VirtualMuxAlarm<
                'static,
                litex_vexriscv::timer::LiteXAlarm<
                    'static,
                    'static,
                    socc::SoCRegisterFmt,
                    socc::ClockFrequency,
                >,
            >,
        >,
        VirtualSchedulerTimer::new(systick_virtual_alarm)
    );

    // ---------- UART ----------

    // Initialize the HW UART
    let uart0 = static_init!(
        litex_vexriscv::uart::LiteXUart<socc::SoCRegisterFmt>,
        litex_vexriscv::uart::LiteXUart::new(
            StaticRef::new(
                socc::CSR_UART_BASE
                    as *const litex_vexriscv::uart::LiteXUartRegisters<socc::SoCRegisterFmt>,
            ),
            None, // LiteX simulator has no UART phy
        )
    );
    uart0.initialize();

    PANIC_REFERENCES.uart = Some(uart0);

    // Create a shared UART channel for the console and for kernel debug.
    //
    // The baudrate is ingnored, as no UART phy is present in the
    // verilated simulation.
    let uart_mux = components::console::UartMuxComponent::new(uart0, 115200)
        .finalize(components::uart_mux_component_static!());

    // ---------- ETHERNET ----------

    // Packet receive buffer
    let ethmac0_rxbuf0 = static_init!([u8; 1522], [0; 1522]);

    // ETHMAC peripheral
    let ethmac0 = static_init!(
        litex_vexriscv::liteeth::LiteEth<socc::SoCRegisterFmt>,
        litex_vexriscv::liteeth::LiteEth::new(
            StaticRef::new(
                socc::CSR_ETHMAC_BASE
                    as *const litex_vexriscv::liteeth::LiteEthMacRegisters<socc::SoCRegisterFmt>,
            ),
            socc::MEM_ETHMAC_BASE,
            socc::MEM_ETHMAC_SIZE,
            socc::ETHMAC_SLOT_SIZE,
            socc::ETHMAC_RX_SLOTS,
            socc::ETHMAC_TX_SLOTS,
            ethmac0_rxbuf0,
        )
    );

    // Initialize the ETHMAC controller
    ethmac0.initialize();

    // --------- GPIO CONTROLLER ----------
    type GPIOPin = litex_vexriscv::gpio::LiteXGPIOPin<'static, 'static, socc::SoCRegisterFmt>;

    // GPIO hardware controller
    let gpio0 = static_init!(
        litex_vexriscv::gpio::LiteXGPIOController<'static, socc::SoCRegisterFmt>,
        litex_vexriscv::gpio::LiteXGPIOController::new(
            StaticRef::new(
                socc::CSR_GPIO_BASE
                    as *const litex_vexriscv::gpio::LiteXGPIORegisters<socc::SoCRegisterFmt>
            ),
            32, // 32 GPIOs in the simulation
        ),
    );
    gpio0.initialize();

    // --------- GPIO DRIVER ----------

    let gpio_driver = components::gpio::GpioComponent::new(
        board_kernel,
        capsules_core::gpio::DRIVER_NUM,
        components::gpio_component_helper_owned!(
            GPIOPin,
            16 => gpio0.get_gpio_pin(16).unwrap(),
            17 => gpio0.get_gpio_pin(17).unwrap(),
            18 => gpio0.get_gpio_pin(18).unwrap(),
            19 => gpio0.get_gpio_pin(19).unwrap(),
            20 => gpio0.get_gpio_pin(20).unwrap(),
            21 => gpio0.get_gpio_pin(21).unwrap(),
            22 => gpio0.get_gpio_pin(22).unwrap(),
            23 => gpio0.get_gpio_pin(23).unwrap(),
            24 => gpio0.get_gpio_pin(24).unwrap(),
            25 => gpio0.get_gpio_pin(25).unwrap(),
            26 => gpio0.get_gpio_pin(26).unwrap(),
            27 => gpio0.get_gpio_pin(27).unwrap(),
            28 => gpio0.get_gpio_pin(28).unwrap(),
            29 => gpio0.get_gpio_pin(29).unwrap(),
            30 => gpio0.get_gpio_pin(30).unwrap(),
            31 => gpio0.get_gpio_pin(31).unwrap(),
        ),
    )
    .finalize(components::gpio_component_static!(GPIOPin));

    // ---------- LED DRIVER ----------

    let led_gpios = static_init!(
        [GPIOPin; 8],
        [
            gpio0.get_gpio_pin(0).unwrap(),
            gpio0.get_gpio_pin(1).unwrap(),
            gpio0.get_gpio_pin(2).unwrap(),
            gpio0.get_gpio_pin(3).unwrap(),
            gpio0.get_gpio_pin(4).unwrap(),
            gpio0.get_gpio_pin(5).unwrap(),
            gpio0.get_gpio_pin(6).unwrap(),
            gpio0.get_gpio_pin(7).unwrap(),
        ]
    );

    let led_driver =
        components::led::LedsComponent::new().finalize(components::led_component_static!(
            kernel::hil::led::LedHigh<GPIOPin>,
            LedHigh::new(&led_gpios[0]),
            LedHigh::new(&led_gpios[1]),
            LedHigh::new(&led_gpios[2]),
            LedHigh::new(&led_gpios[3]),
            LedHigh::new(&led_gpios[4]),
            LedHigh::new(&led_gpios[5]),
            LedHigh::new(&led_gpios[6]),
            LedHigh::new(&led_gpios[7]),
        ));

    // ---------- BUTTON ----------

    let button_driver = components::button::ButtonComponent::new(
        board_kernel,
        capsules_core::button::DRIVER_NUM,
        components::button_component_helper_owned!(
            GPIOPin,
            (
                gpio0.get_gpio_pin(8).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
            (
                gpio0.get_gpio_pin(9).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
            (
                gpio0.get_gpio_pin(10).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
            (
                gpio0.get_gpio_pin(11).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
            (
                gpio0.get_gpio_pin(12).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
            (
                gpio0.get_gpio_pin(13).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
            (
                gpio0.get_gpio_pin(14).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
            (
                gpio0.get_gpio_pin(15).unwrap(),
                kernel::hil::gpio::ActivationMode::ActiveHigh,
                kernel::hil::gpio::FloatingState::PullNone
            ),
        ),
    )
    .finalize(components::button_component_static!(GPIOPin));

    // ---------- INITIALIZE CHIP, ENABLE INTERRUPTS ----------

    let interrupt_service = static_init!(
        LiteXSimInterruptablePeripherals,
        LiteXSimInterruptablePeripherals {
            gpio0,
            uart0,
            timer0,
            ethmac0,
        }
    );
    interrupt_service.init();

    let chip = static_init!(
        litex_vexriscv::chip::LiteXVexRiscv<
            LiteXSimInterruptablePeripherals,
        >,
        litex_vexriscv::chip::LiteXVexRiscv::new(
            "Verilated LiteX on VexRiscv",
            interrupt_service,
            pmp,
        )
    );

    PANIC_REFERENCES.chip = Some(chip);

    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
        .finalize(components::process_printer_text_component_static!());

    PANIC_REFERENCES.process_printer = Some(process_printer);

    // Enable RISC-V interrupts globally
    csr::CSR
        .mie
        .modify(csr::mie::mie::mext::SET + csr::mie::mie::msoft::SET);
    csr::CSR.mstatus.modify(csr::mstatus::mstatus::mie::SET);

    // Unmask all interrupt sources in the interrupt controller
    chip.unmask_interrupts();

    // Setup the console.
    let console = components::console::ConsoleComponent::new(
        board_kernel,
        capsules_core::console::DRIVER_NUM,
        uart_mux,
    )
    .finalize(components::console_component_static!());
    // Create the debugger object that handles calls to `debug!()`.
    components::debug_writer::DebugWriterComponent::new(uart_mux)
        .finalize(components::debug_writer_component_static!());

    let lldb = components::lldb::LowLevelDebugComponent::new(
        board_kernel,
        capsules_core::low_level_debug::DRIVER_NUM,
        uart_mux,
    )
    .finalize(components::low_level_debug_component_static!());

    let scheduler = components::sched::mlfq::MLFQComponent::new(mux_alarm, &*addr_of!(PROCESSES))
        .finalize(components::mlfq_component_static!(
            litex_vexriscv::timer::LiteXAlarm<
                'static,
                'static,
                socc::SoCRegisterFmt,
                socc::ClockFrequency,
            >,
            NUM_PROCS
        ));

    let litex_sim = LiteXSim {
        gpio_driver,
        button_driver,
        led_driver,
        console,
        alarm,
        lldb,
        ipc: kernel::ipc::IPC::new(
            board_kernel,
            kernel::ipc::DRIVER_NUM,
            &memory_allocation_cap,
        ),
        scheduler,
        scheduler_timer,
    };

    debug!("Verilated LiteX+VexRiscv: initialization complete, entering main loop.");

    kernel::process::load_processes(
        board_kernel,
        chip,
        core::slice::from_raw_parts(
            core::ptr::addr_of!(_sapps),
            core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
        ),
        core::slice::from_raw_parts_mut(
            core::ptr::addr_of_mut!(_sappmem),
            core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
        ),
        &mut *addr_of_mut!(PROCESSES),
        &FAULT_RESPONSE,
        &process_mgmt_cap,
    )
    .unwrap_or_else(|err| {
        debug!("Error loading processes!");
        debug!("{:?}", err);
    });

    (board_kernel, litex_sim, chip)
}

/// Main function called after RAM initialized.
#[no_mangle]
pub unsafe fn main() {
    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);

    let (board_kernel, board, chip) = start();
    board_kernel.kernel_loop(&board, chip, Some(&board.ipc), &main_loop_capability);
}