imix/
main.rs

1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Board file for Imix development platform.
6//!
7//! - <https://github.com/tock/tock/tree/master/boards/imix>
8//! - <https://github.com/tock/imix>
9
10#![no_std]
11#![no_main]
12#![deny(missing_docs)]
13
14mod imix_components;
15
16use capsules_core::alarm::AlarmDriver;
17use capsules_core::console_ordered::ConsoleOrdered;
18use capsules_core::virtualizers::virtual_aes_ccm::MuxAES128CCM;
19use capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm;
20use capsules_core::virtualizers::virtual_i2c::MuxI2C;
21use capsules_core::virtualizers::virtual_spi::VirtualSpiMasterDevice;
22use capsules_extra::net::ieee802154::MacAddress;
23use capsules_extra::net::ipv6::ip_utils::IPAddr;
24use kernel::capabilities;
25use kernel::component::Component;
26use kernel::deferred_call::DeferredCallClient;
27use kernel::hil::i2c::I2CMaster;
28use kernel::hil::radio;
29#[allow(unused_imports)]
30use kernel::hil::radio::{RadioConfig, RadioData};
31use kernel::hil::symmetric_encryption::AES128;
32use kernel::platform::{KernelResources, SyscallDriverLookup};
33use kernel::process::ProcessArray;
34use kernel::scheduler::round_robin::RoundRobinSched;
35
36//use kernel::hil::time::Alarm;
37use kernel::hil::led::LedHigh;
38use kernel::hil::Controller;
39#[allow(unused_imports)]
40use kernel::{create_capability, debug, debug_gpio, static_buf, static_init};
41use sam4l::chip::Sam4lDefaultPeripherals;
42
43use components::alarm::{AlarmDriverComponent, AlarmMuxComponent};
44use components::console::{ConsoleOrderedComponent, UartMuxComponent};
45use components::crc::CrcComponent;
46use components::debug_writer::DebugWriterComponent;
47use components::gpio::GpioComponent;
48use components::isl29035::AmbientLightComponent;
49use components::isl29035::Isl29035Component;
50use components::led::LedsComponent;
51use components::nrf51822::Nrf51822Component;
52use components::process_console::ProcessConsoleComponent;
53use components::rng::RngComponent;
54use components::si7021::SI7021Component;
55use components::spi::{SpiComponent, SpiSyscallComponent};
56
57/// Support routines for debugging I/O.
58///
59/// Note: Use of this module will trample any other USART3 configuration.
60pub mod io;
61
62// Unit Tests for drivers.
63#[allow(dead_code)]
64mod test;
65
66// Helper functions for enabling/disabling power on Imix submodules
67mod power;
68
69#[allow(dead_code)]
70mod alarm_test;
71
72#[allow(dead_code)]
73mod multi_timer_test;
74
75// State for loading apps.
76
77const NUM_PROCS: usize = 4;
78
79// Constants related to the configuration of the 15.4 network stack
80// TODO: Notably, the radio MAC addresses can be configured from userland at the moment
81// We probably want to change this from a security perspective (multiple apps being
82// able to change the MAC address seems problematic), but it is very convenient for
83// development to be able to just flash two corresponding apps onto two devices and
84// have those devices talk to each other without having to modify the kernel flashed
85// onto each device. This makes MAC address configuration a good target for capabilities -
86// only allow one app per board to have control of MAC address configuration?
87const RADIO_CHANNEL: radio::RadioChannel = radio::RadioChannel::Channel26;
88const DST_MAC_ADDR: MacAddress = MacAddress::Short(49138);
89const DEFAULT_CTX_PREFIX_LEN: u8 = 8; //Length of context for 6LoWPAN compression
90const DEFAULT_CTX_PREFIX: [u8; 16] = [0x0_u8; 16]; //Context for 6LoWPAN Compression
91const PAN_ID: u16 = 0xABCD;
92
93// how should the kernel respond when a process faults
94const FAULT_RESPONSE: capsules_system::process_policies::StopFaultPolicy =
95    capsules_system::process_policies::StopFaultPolicy {};
96
97type ChipHw = sam4l::chip::Sam4l<Sam4lDefaultPeripherals>;
98
99/// Static variables used by io.rs.
100static mut PROCESSES: Option<&'static ProcessArray<NUM_PROCS>> = None;
101static mut CHIP: Option<&'static sam4l::chip::Sam4l<Sam4lDefaultPeripherals>> = None;
102static mut PROCESS_PRINTER: Option<&'static capsules_system::process_printer::ProcessPrinterText> =
103    None;
104
105kernel::stack_size! {0x2000}
106
107type SI7021Sensor = components::si7021::SI7021ComponentType<
108    capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<'static, sam4l::ast::Ast<'static>>,
109    capsules_core::virtualizers::virtual_i2c::I2CDevice<'static, sam4l::i2c::I2CHw<'static>>,
110>;
111type TemperatureDriver = components::temperature::TemperatureComponentType<SI7021Sensor>;
112type HumidityDriver = components::humidity::HumidityComponentType<SI7021Sensor>;
113type RngDriver = components::rng::RngComponentType<sam4l::trng::Trng<'static>>;
114
115type Rf233 = capsules_extra::rf233::RF233<
116    'static,
117    VirtualSpiMasterDevice<'static, sam4l::spi::SpiHw<'static>>,
118>;
119type Ieee802154MacDevice =
120    components::ieee802154::Ieee802154ComponentMacDeviceType<Rf233, sam4l::aes::Aes<'static>>;
121
122struct Imix {
123    pconsole: &'static capsules_core::process_console::ProcessConsole<
124        'static,
125        { capsules_core::process_console::DEFAULT_COMMAND_HISTORY_LEN },
126        capsules_core::virtualizers::virtual_alarm::VirtualMuxAlarm<
127            'static,
128            sam4l::ast::Ast<'static>,
129        >,
130        components::process_console::Capability,
131    >,
132    console: &'static capsules_core::console_ordered::ConsoleOrdered<
133        'static,
134        VirtualMuxAlarm<'static, sam4l::ast::Ast<'static>>,
135    >,
136    gpio: &'static capsules_core::gpio::GPIO<'static, sam4l::gpio::GPIOPin<'static>>,
137    alarm: &'static AlarmDriver<'static, VirtualMuxAlarm<'static, sam4l::ast::Ast<'static>>>,
138    temp: &'static TemperatureDriver,
139    humidity: &'static HumidityDriver,
140    ambient_light: &'static capsules_extra::ambient_light::AmbientLight<'static>,
141    adc: &'static capsules_core::adc::AdcDedicated<'static, sam4l::adc::Adc<'static>>,
142    led: &'static capsules_core::led::LedDriver<
143        'static,
144        LedHigh<'static, sam4l::gpio::GPIOPin<'static>>,
145        1,
146    >,
147    button: &'static capsules_core::button::Button<'static, sam4l::gpio::GPIOPin<'static>>,
148    rng: &'static RngDriver,
149    analog_comparator: &'static capsules_extra::analog_comparator::AnalogComparator<
150        'static,
151        sam4l::acifc::Acifc<'static>,
152    >,
153    spi: &'static capsules_core::spi_controller::Spi<
154        'static,
155        VirtualSpiMasterDevice<'static, sam4l::spi::SpiHw<'static>>,
156    >,
157    ipc: kernel::ipc::IPC<{ NUM_PROCS as u8 }>,
158    ninedof: &'static capsules_extra::ninedof::NineDof<'static>,
159    udp_driver: &'static capsules_extra::net::udp::UDPDriver<'static>,
160    crc: &'static capsules_extra::crc::CrcDriver<'static, sam4l::crccu::Crccu<'static>>,
161    usb_driver: &'static capsules_extra::usb::usb_user::UsbSyscallDriver<
162        'static,
163        capsules_extra::usb::usbc_client::Client<'static, sam4l::usbc::Usbc<'static>>,
164    >,
165    nrf51822: &'static capsules_extra::nrf51822_serialization::Nrf51822Serialization<'static>,
166    nonvolatile_storage:
167        &'static capsules_extra::nonvolatile_storage_driver::NonvolatileStorage<'static>,
168    scheduler: &'static RoundRobinSched<'static>,
169    systick: cortexm4::systick::SysTick,
170}
171
172impl SyscallDriverLookup for Imix {
173    fn with_driver<F, R>(&self, driver_num: usize, f: F) -> R
174    where
175        F: FnOnce(Option<&dyn kernel::syscall::SyscallDriver>) -> R,
176    {
177        match driver_num {
178            capsules_core::console_ordered::DRIVER_NUM => f(Some(self.console)),
179            capsules_core::gpio::DRIVER_NUM => f(Some(self.gpio)),
180            capsules_core::alarm::DRIVER_NUM => f(Some(self.alarm)),
181            capsules_core::spi_controller::DRIVER_NUM => f(Some(self.spi)),
182            capsules_core::adc::DRIVER_NUM => f(Some(self.adc)),
183            capsules_core::led::DRIVER_NUM => f(Some(self.led)),
184            capsules_core::button::DRIVER_NUM => f(Some(self.button)),
185            capsules_extra::analog_comparator::DRIVER_NUM => f(Some(self.analog_comparator)),
186            capsules_extra::ambient_light::DRIVER_NUM => f(Some(self.ambient_light)),
187            capsules_extra::temperature::DRIVER_NUM => f(Some(self.temp)),
188            capsules_extra::humidity::DRIVER_NUM => f(Some(self.humidity)),
189            capsules_extra::ninedof::DRIVER_NUM => f(Some(self.ninedof)),
190            capsules_extra::crc::DRIVER_NUM => f(Some(self.crc)),
191            capsules_extra::usb::usb_user::DRIVER_NUM => f(Some(self.usb_driver)),
192            capsules_extra::net::udp::DRIVER_NUM => f(Some(self.udp_driver)),
193            capsules_extra::nrf51822_serialization::DRIVER_NUM => f(Some(self.nrf51822)),
194            capsules_extra::nonvolatile_storage_driver::DRIVER_NUM => {
195                f(Some(self.nonvolatile_storage))
196            }
197            capsules_core::rng::DRIVER_NUM => f(Some(self.rng)),
198            kernel::ipc::DRIVER_NUM => f(Some(&self.ipc)),
199            _ => f(None),
200        }
201    }
202}
203
204impl KernelResources<sam4l::chip::Sam4l<Sam4lDefaultPeripherals>> for Imix {
205    type SyscallDriverLookup = Self;
206    type SyscallFilter = ();
207    type ProcessFault = ();
208    type Scheduler = RoundRobinSched<'static>;
209    type SchedulerTimer = cortexm4::systick::SysTick;
210    type WatchDog = ();
211    type ContextSwitchCallback = ();
212
213    fn syscall_driver_lookup(&self) -> &Self::SyscallDriverLookup {
214        self
215    }
216    fn syscall_filter(&self) -> &Self::SyscallFilter {
217        &()
218    }
219    fn process_fault(&self) -> &Self::ProcessFault {
220        &()
221    }
222    fn scheduler(&self) -> &Self::Scheduler {
223        self.scheduler
224    }
225    fn scheduler_timer(&self) -> &Self::SchedulerTimer {
226        &self.systick
227    }
228    fn watchdog(&self) -> &Self::WatchDog {
229        &()
230    }
231    fn context_switch_callback(&self) -> &Self::ContextSwitchCallback {
232        &()
233    }
234}
235
236unsafe fn set_pin_primary_functions(peripherals: &Sam4lDefaultPeripherals) {
237    use sam4l::gpio::PeripheralFunction::{A, B, C, E};
238
239    // Right column: Imix pin name
240    // Left  column: SAM4L peripheral function
241    peripherals.pa[04].configure(Some(A)); // AD0         --  ADCIFE AD0
242    peripherals.pa[05].configure(Some(A)); // AD1         --  ADCIFE AD1
243    peripherals.pa[06].configure(Some(C)); // EXTINT1     --  EIC EXTINT1
244    peripherals.pa[07].configure(Some(A)); // AD1         --  ADCIFE AD2
245    peripherals.pa[08].configure(None); //... RF233 IRQ   --  GPIO pin
246    peripherals.pa[09].configure(None); //... RF233 RST   --  GPIO pin
247    peripherals.pa[10].configure(None); //... RF233 SLP   --  GPIO pin
248    peripherals.pa[13].configure(None); //... TRNG EN     --  GPIO pin
249    peripherals.pa[14].configure(None); //... TRNG_OUT    --  GPIO pin
250    peripherals.pa[17].configure(None); //... NRF INT     -- GPIO pin
251    peripherals.pa[18].configure(Some(A)); // NRF CLK     -- USART2_CLK
252    peripherals.pa[20].configure(None); //... D8          -- GPIO pin
253    peripherals.pa[21].configure(Some(E)); // TWI2 SDA    -- TWIM2_SDA
254    peripherals.pa[22].configure(Some(E)); // TWI2 SCL    --  TWIM2 TWCK
255    peripherals.pa[25].configure(Some(A)); // USB_N       --  USB DM
256    peripherals.pa[26].configure(Some(A)); // USB_P       --  USB DP
257    peripherals.pb[00].configure(Some(A)); // TWI1_SDA    --  TWIMS1 TWD
258    peripherals.pb[01].configure(Some(A)); // TWI1_SCL    --  TWIMS1 TWCK
259    peripherals.pb[02].configure(Some(A)); // AD3         --  ADCIFE AD3
260    peripherals.pb[03].configure(Some(A)); // AD4         --  ADCIFE AD4
261    peripherals.pb[04].configure(Some(A)); // AD5         --  ADCIFE AD5
262    peripherals.pb[05].configure(Some(A)); // VHIGHSAMPLE --  ADCIFE AD6
263    peripherals.pb[06].configure(Some(A)); // RTS3        --  USART3 RTS
264    peripherals.pb[07].configure(None); //... NRF RESET   --  GPIO
265    peripherals.pb[09].configure(Some(A)); // RX3         --  USART3 RX
266    peripherals.pb[10].configure(Some(A)); // TX3         --  USART3 TX
267    peripherals.pb[11].configure(Some(A)); // CTS0        --  USART0 CTS
268    peripherals.pb[12].configure(Some(A)); // RTS0        --  USART0 RTS
269    peripherals.pb[13].configure(Some(A)); // CLK0        --  USART0 CLK
270    peripherals.pb[14].configure(Some(A)); // RX0         --  USART0 RX
271    peripherals.pb[15].configure(Some(A)); // TX0         --  USART0 TX
272    peripherals.pc[00].configure(Some(A)); // CS2         --  SPI Nperipherals.pcS2
273    peripherals.pc[01].configure(Some(A)); // CS3 (RF233) --  SPI Nperipherals.pcS3
274    peripherals.pc[02].configure(Some(A)); // CS1         --  SPI Nperipherals.pcS1
275    peripherals.pc[03].configure(Some(A)); // CS0         --  SPI Nperipherals.pcS0
276    peripherals.pc[04].configure(Some(A)); // MISO        --  SPI MISO
277    peripherals.pc[05].configure(Some(A)); // MOSI        --  SPI MOSI
278    peripherals.pc[06].configure(Some(A)); // SCK         --  SPI CLK
279    peripherals.pc[07].configure(Some(B)); // RTS2 (BLE)  -- USART2_RTS
280    peripherals.pc[08].configure(Some(E)); // CTS2 (BLE)  -- USART2_CTS
281                                           //peripherals.pc[09].configure(None); //... NRF GPIO    -- GPIO
282                                           //peripherals.pc[10].configure(None); //... USER LED    -- GPIO
283    peripherals.pc[09].configure(Some(E)); // ACAN1       -- ACIFC comparator
284    peripherals.pc[10].configure(Some(E)); // ACAP1       -- ACIFC comparator
285    peripherals.pc[11].configure(Some(B)); // RX2 (BLE)   -- USART2_RX
286    peripherals.pc[12].configure(Some(B)); // TX2 (BLE)   -- USART2_TX
287                                           //peripherals.pc[13].configure(None); //... ACC_INT1    -- GPIO
288                                           //peripherals.pc[14].configure(None); //... ACC_INT2    -- GPIO
289    peripherals.pc[13].configure(Some(E)); //... ACBN1    -- ACIFC comparator
290    peripherals.pc[14].configure(Some(E)); //... ACBP1    -- ACIFC comparator
291    peripherals.pc[16].configure(None); //... SENSE_PWR   --  GPIO pin
292    peripherals.pc[17].configure(None); //... NRF_PWR     --  GPIO pin
293    peripherals.pc[18].configure(None); //... RF233_PWR   --  GPIO pin
294    peripherals.pc[19].configure(None); //... TRNG_PWR    -- GPIO Pin
295    peripherals.pc[22].configure(None); //... KERNEL LED  -- GPIO Pin
296    peripherals.pc[24].configure(None); //... USER_BTN    -- GPIO Pin
297    peripherals.pc[25].configure(Some(B)); // LI_INT      --  EIC EXTINT2
298    peripherals.pc[26].configure(None); //... D7          -- GPIO Pin
299    peripherals.pc[27].configure(None); //... D6          -- GPIO Pin
300    peripherals.pc[28].configure(None); //... D5          -- GPIO Pin
301    peripherals.pc[29].configure(None); //... D4          -- GPIO Pin
302    peripherals.pc[30].configure(None); //... D3          -- GPIO Pin
303    peripherals.pc[31].configure(None); //... D2          -- GPIO Pin
304}
305
306/// This is in a separate, inline(never) function so that its stack frame is
307/// removed when this function returns. Otherwise, the stack space used for
308/// these static_inits is wasted.
309#[inline(never)]
310unsafe fn start() -> (
311    &'static kernel::Kernel,
312    Imix,
313    &'static sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
314) {
315    sam4l::init();
316
317    // Initialize deferred calls very early.
318    kernel::deferred_call::initialize_deferred_call_state::<
319        <ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider,
320    >();
321
322    let pm = static_init!(sam4l::pm::PowerManager, sam4l::pm::PowerManager::new());
323    let peripherals = static_init!(Sam4lDefaultPeripherals, Sam4lDefaultPeripherals::new(pm));
324
325    pm.setup_system_clock(
326        sam4l::pm::SystemClockSource::PllExternalOscillatorAt48MHz {
327            frequency: sam4l::pm::OscillatorFrequency::Frequency16MHz,
328            startup_mode: sam4l::pm::OscillatorStartup::FastStart,
329        },
330        &peripherals.flash_controller,
331    );
332
333    // Source 32Khz and 1Khz clocks from RC23K (SAM4L Datasheet 11.6.8)
334    sam4l::bpm::set_ck32source(sam4l::bpm::CK32Source::RC32K);
335
336    set_pin_primary_functions(peripherals);
337
338    peripherals.setup_circular_deps();
339    let chip = static_init!(
340        sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
341        sam4l::chip::Sam4l::new(pm, peripherals)
342    );
343    CHIP = Some(chip);
344
345    // Create capabilities that the board needs to call certain protected kernel
346    // functions.
347    let grant_cap = create_capability!(capabilities::MemoryAllocationCapability);
348
349    power::configure_submodules(
350        &peripherals.pa,
351        &peripherals.pb,
352        &peripherals.pc,
353        power::SubmoduleConfig {
354            rf233: true,
355            nrf51422: true,
356            sensors: true,
357            trng: true,
358        },
359    );
360
361    // Create an array to hold process references.
362    let processes = components::process_array::ProcessArrayComponent::new()
363        .finalize(components::process_array_component_static!(NUM_PROCS));
364    PROCESSES = Some(processes);
365
366    // Setup space to store the core kernel data structure.
367    let board_kernel = static_init!(kernel::Kernel, kernel::Kernel::new(processes.as_slice()));
368
369    let process_printer = components::process_printer::ProcessPrinterTextComponent::new()
370        .finalize(components::process_printer_text_component_static!());
371    PROCESS_PRINTER = Some(process_printer);
372
373    // # CONSOLE
374    // Create a shared UART channel for the consoles and for kernel debug.
375    peripherals.usart3.set_mode(sam4l::usart::UsartMode::Uart);
376    let uart_mux = UartMuxComponent::new(&peripherals.usart3, 115200)
377        .finalize(components::uart_mux_component_static!());
378
379    // # TIMER
380    let mux_alarm = AlarmMuxComponent::new(&peripherals.ast)
381        .finalize(components::alarm_mux_component_static!(sam4l::ast::Ast));
382    peripherals.ast.configure(mux_alarm);
383
384    let alarm =
385        AlarmDriverComponent::new(board_kernel, capsules_core::alarm::DRIVER_NUM, mux_alarm)
386            .finalize(components::alarm_component_static!(sam4l::ast::Ast));
387
388    let pconsole = ProcessConsoleComponent::new(
389        board_kernel,
390        uart_mux,
391        mux_alarm,
392        process_printer,
393        Some(cortexm4::support::reset),
394    )
395    .finalize(components::process_console_component_static!(
396        sam4l::ast::Ast
397    ));
398
399    let console = ConsoleOrderedComponent::new(
400        board_kernel,
401        capsules_core::console_ordered::DRIVER_NUM,
402        uart_mux,
403        mux_alarm,
404        200,
405        5,
406        5,
407    )
408    .finalize(components::console_ordered_component_static!(
409        sam4l::ast::Ast
410    ));
411    DebugWriterComponent::new::<<ChipHw as kernel::platform::chip::Chip>::ThreadIdProvider>(
412        uart_mux,
413        create_capability!(capabilities::SetDebugWriterCapability),
414    )
415    .finalize(components::debug_writer_component_static!());
416
417    // Allow processes to communicate over BLE through the nRF51822
418    peripherals.usart2.set_mode(sam4l::usart::UsartMode::Uart);
419    let nrf_serialization = Nrf51822Component::new(
420        board_kernel,
421        capsules_extra::nrf51822_serialization::DRIVER_NUM,
422        &peripherals.usart2,
423        &peripherals.pb[07],
424    )
425    .finalize(components::nrf51822_component_static!());
426
427    // # I2C and I2C Sensors
428    let mux_i2c = static_init!(
429        MuxI2C<'static, sam4l::i2c::I2CHw<'static>>,
430        MuxI2C::new(&peripherals.i2c2, None)
431    );
432    kernel::deferred_call::DeferredCallClient::register(mux_i2c);
433    peripherals.i2c2.set_master_client(mux_i2c);
434
435    let isl29035 = Isl29035Component::new(mux_i2c, mux_alarm).finalize(
436        components::isl29035_component_static!(sam4l::ast::Ast, sam4l::i2c::I2CHw<'static>),
437    );
438    let ambient_light = AmbientLightComponent::new(
439        board_kernel,
440        capsules_extra::ambient_light::DRIVER_NUM,
441        isl29035,
442    )
443    .finalize(components::ambient_light_component_static!());
444
445    let si7021 = SI7021Component::new(mux_i2c, mux_alarm, 0x40).finalize(
446        components::si7021_component_static!(sam4l::ast::Ast, sam4l::i2c::I2CHw<'static>),
447    );
448    let temp = components::temperature::TemperatureComponent::new(
449        board_kernel,
450        capsules_extra::temperature::DRIVER_NUM,
451        si7021,
452    )
453    .finalize(components::temperature_component_static!(SI7021Sensor));
454    let humidity = components::humidity::HumidityComponent::new(
455        board_kernel,
456        capsules_extra::humidity::DRIVER_NUM,
457        si7021,
458    )
459    .finalize(components::humidity_component_static!(SI7021Sensor));
460
461    let fxos8700 = components::fxos8700::Fxos8700Component::new(mux_i2c, 0x1e, &peripherals.pc[13])
462        .finalize(components::fxos8700_component_static!(
463            sam4l::i2c::I2CHw<'static>
464        ));
465
466    let ninedof = components::ninedof::NineDofComponent::new(
467        board_kernel,
468        capsules_extra::ninedof::DRIVER_NUM,
469    )
470    .finalize(components::ninedof_component_static!(fxos8700));
471
472    // SPI MUX, SPI syscall driver and RF233 radio
473    let mux_spi = components::spi::SpiMuxComponent::new(&peripherals.spi).finalize(
474        components::spi_mux_component_static!(sam4l::spi::SpiHw<'static>),
475    );
476
477    let spi_syscalls = SpiSyscallComponent::new(
478        board_kernel,
479        mux_spi,
480        sam4l::spi::Peripheral::Peripheral2,
481        capsules_core::spi_controller::DRIVER_NUM,
482    )
483    .finalize(components::spi_syscall_component_static!(
484        sam4l::spi::SpiHw<'static>
485    ));
486    let rf233_spi = SpiComponent::new(mux_spi, sam4l::spi::Peripheral::Peripheral3).finalize(
487        components::spi_component_static!(sam4l::spi::SpiHw<'static>),
488    );
489    let rf233 = components::rf233::RF233Component::new(
490        rf233_spi,
491        &peripherals.pa[09], // reset
492        &peripherals.pa[10], // sleep
493        &peripherals.pa[08], // irq
494        &peripherals.pa[08],
495        RADIO_CHANNEL,
496    )
497    .finalize(components::rf233_component_static!(
498        sam4l::spi::SpiHw<'static>
499    ));
500
501    // Setup ADC
502    let adc_channels = static_init!(
503        [sam4l::adc::AdcChannel; 6],
504        [
505            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD1), // AD0
506            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD2), // AD1
507            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD3), // AD2
508            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD4), // AD3
509            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD5), // AD4
510            sam4l::adc::AdcChannel::new(sam4l::adc::Channel::AD6), // AD5
511        ]
512    );
513    let adc = components::adc::AdcDedicatedComponent::new(
514        &peripherals.adc,
515        adc_channels,
516        board_kernel,
517        capsules_core::adc::DRIVER_NUM,
518    )
519    .finalize(components::adc_dedicated_component_static!(sam4l::adc::Adc));
520
521    let gpio = GpioComponent::new(
522        board_kernel,
523        capsules_core::gpio::DRIVER_NUM,
524        components::gpio_component_helper!(
525            sam4l::gpio::GPIOPin,
526            0 => &peripherals.pc[31],
527            1 => &peripherals.pc[30],
528            2 => &peripherals.pc[29],
529            3 => &peripherals.pc[28],
530            4 => &peripherals.pc[27],
531            5 => &peripherals.pc[26],
532            6 => &peripherals.pa[20]
533        ),
534    )
535    .finalize(components::gpio_component_static!(sam4l::gpio::GPIOPin));
536
537    let led = LedsComponent::new().finalize(components::led_component_static!(
538        LedHigh<'static, sam4l::gpio::GPIOPin>,
539        LedHigh::new(&peripherals.pc[10]),
540    ));
541
542    let button = components::button::ButtonComponent::new(
543        board_kernel,
544        capsules_core::button::DRIVER_NUM,
545        components::button_component_helper!(
546            sam4l::gpio::GPIOPin,
547            (
548                &peripherals.pc[24],
549                kernel::hil::gpio::ActivationMode::ActiveLow,
550                kernel::hil::gpio::FloatingState::PullNone
551            )
552        ),
553    )
554    .finalize(components::button_component_static!(sam4l::gpio::GPIOPin));
555
556    let crc = CrcComponent::new(
557        board_kernel,
558        capsules_extra::crc::DRIVER_NUM,
559        &peripherals.crccu,
560    )
561    .finalize(components::crc_component_static!(sam4l::crccu::Crccu));
562
563    let ac_0 = static_init!(
564        sam4l::acifc::AcChannel,
565        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
566    );
567    let ac_1 = static_init!(
568        sam4l::acifc::AcChannel,
569        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
570    );
571    let ac_2 = static_init!(
572        sam4l::acifc::AcChannel,
573        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
574    );
575    let ac_3 = static_init!(
576        sam4l::acifc::AcChannel,
577        sam4l::acifc::AcChannel::new(sam4l::acifc::Channel::AC0)
578    );
579    let analog_comparator = components::analog_comparator::AnalogComparatorComponent::new(
580        &peripherals.acifc,
581        components::analog_comparator_component_helper!(
582            <sam4l::acifc::Acifc as kernel::hil::analog_comparator::AnalogComparator>::Channel,
583            ac_0,
584            ac_1,
585            ac_2,
586            ac_3
587        ),
588        board_kernel,
589        capsules_extra::analog_comparator::DRIVER_NUM,
590    )
591    .finalize(components::analog_comparator_component_static!(
592        sam4l::acifc::Acifc
593    ));
594    let rng = RngComponent::new(
595        board_kernel,
596        capsules_core::rng::DRIVER_NUM,
597        &peripherals.trng,
598    )
599    .finalize(components::rng_component_static!(sam4l::trng::Trng));
600
601    // For now, assign the 802.15.4 MAC address on the device as
602    // simply a 16-bit short address which represents the last 16 bits
603    // of the serial number of the sam4l for this device.  In the
604    // future, we could generate the DEFAULT_EXT_SRC_MAC address by hashing the full
605    // 120-bit serial number
606    let serial_num: sam4l::serial_num::SerialNum = sam4l::serial_num::SerialNum::new();
607    let serial_num_bottom_16 = (serial_num.get_lower_64() & 0x0000_0000_0000_ffff) as u16;
608    let src_mac_from_serial_num: MacAddress = MacAddress::Short(serial_num_bottom_16);
609    const DEFAULT_EXT_SRC_MAC: [u8; 8] = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77];
610
611    let aes_mux = static_init!(
612        MuxAES128CCM<'static, sam4l::aes::Aes>,
613        MuxAES128CCM::new(&peripherals.aes)
614    );
615    aes_mux.register();
616    peripherals.aes.set_client(aes_mux);
617
618    let (_, mux_mac) = components::ieee802154::Ieee802154Component::new(
619        board_kernel,
620        capsules_extra::ieee802154::DRIVER_NUM,
621        rf233,
622        aes_mux,
623        PAN_ID,
624        serial_num_bottom_16,
625        DEFAULT_EXT_SRC_MAC,
626    )
627    .finalize(components::ieee802154_component_static!(
628        capsules_extra::rf233::RF233<
629            'static,
630            VirtualSpiMasterDevice<'static, sam4l::spi::SpiHw<'static>>,
631        >,
632        sam4l::aes::Aes<'static>
633    ));
634
635    let usb_driver = components::usb::UsbComponent::new(
636        board_kernel,
637        capsules_extra::usb::usb_user::DRIVER_NUM,
638        &peripherals.usbc,
639    )
640    .finalize(components::usb_component_static!(sam4l::usbc::Usbc));
641
642    // Kernel storage region, allocated with the storage_volume!
643    // macro in common/utils.rs
644    extern "C" {
645        /// Beginning on the ROM region containing app images.
646        static _sstorage: u8;
647        static _estorage: u8;
648    }
649
650    let nonvolatile_storage = components::nonvolatile_storage::NonvolatileStorageComponent::new(
651        board_kernel,
652        capsules_extra::nonvolatile_storage_driver::DRIVER_NUM,
653        &peripherals.flash_controller,
654        0x60000, // Start address for userspace accessible region
655        0x20000, // Length of userspace accessible region
656        core::ptr::addr_of!(_sstorage) as usize, //start address of kernel region
657        core::ptr::addr_of!(_estorage) as usize - core::ptr::addr_of!(_sstorage) as usize, // length of kernel region
658    )
659    .finalize(components::nonvolatile_storage_component_static!(
660        sam4l::flashcalw::FLASHCALW
661    ));
662
663    let local_ip_ifaces = static_init!(
664        [IPAddr; 3],
665        [
666            IPAddr([
667                0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
668                0x0e, 0x0f,
669            ]),
670            IPAddr([
671                0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
672                0x1e, 0x1f,
673            ]),
674            IPAddr::generate_from_mac(src_mac_from_serial_num),
675        ]
676    );
677
678    let (udp_send_mux, udp_recv_mux, udp_port_table) = components::udp_mux::UDPMuxComponent::new(
679        mux_mac,
680        DEFAULT_CTX_PREFIX_LEN,
681        DEFAULT_CTX_PREFIX,
682        DST_MAC_ADDR,
683        src_mac_from_serial_num, //comment out for dual rx test only
684        //MacAddress::Short(49138), //comment in for dual rx test only
685        local_ip_ifaces,
686        mux_alarm,
687    )
688    .finalize(components::udp_mux_component_static!(
689        sam4l::ast::Ast,
690        Ieee802154MacDevice
691    ));
692
693    // UDP driver initialization happens here
694    let udp_driver = components::udp_driver::UDPDriverComponent::new(
695        board_kernel,
696        capsules_extra::net::udp::driver::DRIVER_NUM,
697        udp_send_mux,
698        udp_recv_mux,
699        udp_port_table,
700        local_ip_ifaces,
701    )
702    .finalize(components::udp_driver_component_static!(sam4l::ast::Ast));
703
704    let scheduler = components::sched::round_robin::RoundRobinComponent::new(processes)
705        .finalize(components::round_robin_component_static!(NUM_PROCS));
706
707    // Create the software-based SHA engine.
708    let sha = components::sha::ShaSoftware256Component::new()
709        .finalize(components::sha_software_256_component_static!());
710
711    // Create the credential checker.
712    let checking_policy = components::appid::checker_sha::AppCheckerSha256Component::new(sha)
713        .finalize(components::app_checker_sha256_component_static!());
714
715    // Create the AppID assigner.
716    let assigner = components::appid::assigner_name::AppIdAssignerNamesComponent::new()
717        .finalize(components::appid_assigner_names_component_static!());
718
719    // Create the process checking machine.
720    let checker = components::appid::checker::ProcessCheckerMachineComponent::new(checking_policy)
721        .finalize(components::process_checker_machine_component_static!());
722
723    //--------------------------------------------------------------------------
724    // STORAGE PERMISSIONS
725    //--------------------------------------------------------------------------
726
727    let storage_permissions_policy =
728        components::storage_permissions::individual::StoragePermissionsIndividualComponent::new()
729            .finalize(
730                components::storage_permissions_individual_component_static!(
731                    sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
732                    kernel::process::ProcessStandardDebugFull,
733                ),
734            );
735
736    //--------------------------------------------------------------------------
737    // PROCESS LOADING
738    //--------------------------------------------------------------------------
739
740    // These symbols are defined in the standard Tock linker script.
741    extern "C" {
742        /// Beginning of the ROM region containing app images.
743        static _sapps: u8;
744        /// End of the ROM region containing app images.
745        static _eapps: u8;
746        /// Beginning of the RAM region for app memory.
747        static mut _sappmem: u8;
748        /// End of the RAM region for app memory.
749        static _eappmem: u8;
750    }
751
752    let app_flash = core::slice::from_raw_parts(
753        core::ptr::addr_of!(_sapps),
754        core::ptr::addr_of!(_eapps) as usize - core::ptr::addr_of!(_sapps) as usize,
755    );
756    let app_memory = core::slice::from_raw_parts_mut(
757        core::ptr::addr_of_mut!(_sappmem),
758        core::ptr::addr_of!(_eappmem) as usize - core::ptr::addr_of!(_sappmem) as usize,
759    );
760
761    // Create and start the asynchronous process loader.
762    let _loader = components::loader::sequential::ProcessLoaderSequentialComponent::new(
763        checker,
764        board_kernel,
765        chip,
766        &FAULT_RESPONSE,
767        assigner,
768        storage_permissions_policy,
769        app_flash,
770        app_memory,
771    )
772    .finalize(components::process_loader_sequential_component_static!(
773        sam4l::chip::Sam4l<Sam4lDefaultPeripherals>,
774        kernel::process::ProcessStandardDebugFull,
775        NUM_PROCS
776    ));
777
778    let imix = Imix {
779        pconsole,
780        console,
781        alarm,
782        gpio,
783        temp,
784        humidity,
785        ambient_light,
786        adc,
787        led,
788        button,
789        rng,
790        analog_comparator,
791        crc,
792        spi: spi_syscalls,
793        ipc: kernel::ipc::IPC::new(board_kernel, kernel::ipc::DRIVER_NUM, &grant_cap),
794        ninedof,
795        udp_driver,
796        usb_driver,
797        nrf51822: nrf_serialization,
798        nonvolatile_storage,
799        scheduler,
800        systick: cortexm4::systick::SysTick::new(),
801    };
802
803    // Need to initialize the UART for the nRF51 serialization.
804    imix.nrf51822.initialize();
805
806    // These two lines need to be below the creation of the chip for
807    // initialization to work.
808    let _ = rf233.reset();
809    let _ = rf233.start();
810
811    let _ = imix.pconsole.start();
812
813    // Optional kernel tests. Note that these might conflict
814    // with normal operation (e.g., steal callbacks from drivers, etc.),
815    // so do not run these and expect all services/applications to work.
816    // Once everything is virtualized in the kernel this won't be a problem.
817    // -pal, 11/20/18
818    //
819    //test::virtual_uart_rx_test::run_virtual_uart_receive(uart_mux);
820    //test::rng_test::run_entropy32(&peripherals.trng);
821    //test::virtual_aes_ccm_test::run(&peripherals.aes);
822    //test::aes_test::run_aes128_ctr(&peripherals.aes);
823    //test::aes_test::run_aes128_cbc(&peripherals.aes);
824    //test::log_test::run(
825    //    mux_alarm,
826    //    &peripherals.flash_controller,
827    //);
828    //test::linear_log_test::run(
829    //    mux_alarm,
830    //    &peripherals.flash_controller,
831    //);
832    //test::icmp_lowpan_test::run(mux_mac, mux_alarm);
833    //let lowpan_frag_test = test::ipv6_lowpan_test::initialize_all(mux_mac, mux_alarm);
834    //lowpan_frag_test.start(); // If flashing the transmitting Imix
835    /*let udp_lowpan_test = test::udp_lowpan_test::initialize_all(
836       udp_send_mux,
837        udp_recv_mux,
838        udp_port_table,
839        mux_alarm,
840    );*/
841    //udp_lowpan_test.start();
842
843    // alarm_test::run_alarm(&peripherals.ast);
844    /*let virtual_alarm_timer = static_init!(
845        VirtualMuxAlarm<'static, sam4l::ast::Ast>,
846        VirtualMuxAlarm::new(mux_alarm)
847    );
848    virtual_alarm_timer.setup();
849
850    let mux_timer = static_init!(
851        MuxTimer<'static, sam4l::ast::Ast>,
852        MuxTimer::new(virtual_alarm_timer)
853    );*/
854    //virtual_alarm_timer.set_alarm_client(mux_timer);
855
856    //test::sha256_test::run_sha256();
857
858    /*components::test::multi_alarm_test::MultiAlarmTestComponent::new(mux_alarm)
859    .finalize(components::multi_alarm_test_component_buf!(sam4l::ast::Ast))
860    .run();*/
861
862    debug!("Initialization complete. Entering main loop");
863
864    (board_kernel, imix, chip)
865}
866
867/// Main function called after RAM initialized.
868#[no_mangle]
869pub unsafe fn main() {
870    let main_loop_capability = create_capability!(capabilities::MainLoopCapability);
871
872    let (board_kernel, platform, chip) = start();
873    board_kernel.kernel_loop(&platform, chip, Some(&platform.ipc), &main_loop_capability);
874}