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