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

//! Abstraction Interface for several busses.
//! Useful for devices that support multiple protocols
//!
//! Usage
//! -----
//!
//! I2C example
//! ```rust,ignore
//! let bus = components::bus::I2CMasterBusComponent::new(i2c_mux, address)
//!     .finalize(components::spi_bus_component_helper!());
//! ```
//!
//! SPI example
//! ```rust,ignore
//! let bus =
//!     components::bus::SpiMasterBusComponent::new().finalize(components::spi_bus_component_helper!(
//!         // spi type
//!         nrf52840::spi::SPIM,
//!         // chip select
//!         &nrf52840::gpio::PORT[GPIO_D4],
//!          // spi mux
//!         spi_mux
//!     ));
//! ```

use core::cell::Cell;
use kernel::debug;
use kernel::hil::bus8080::{self, Bus8080, BusAddr8080};
use kernel::hil::i2c::{Error, I2CClient, I2CDevice};
use kernel::hil::spi::{ClockPhase, ClockPolarity, SpiMasterClient, SpiMasterDevice};
use kernel::utilities::cells::OptionalCell;
use kernel::utilities::leasable_buffer::SubSliceMut;
use kernel::ErrorCode;

// Buses, such as I2C or SPI, are generally serial and transmit data byte by byte,
// without taking endianness into account. The receiving device—in this case,
// the screen—interprets the data and determines the endianness.
// In Tock, the lower-level screen driver sets the address endianness.
// For most buses, with the exception of the parallel 8080 bus, endianness
// is largely transparent.
// We store addresses using primitive data types like `u8`, `u16`, `u32`, and `u64`.

/// The `DataWidth` enum and associated `BusAddr` structs define the width
/// of the data transmitted over a bus. The `BusAddr::bytes`` function transforms
/// the address into the specified endianness and returns an iterator.
pub enum DataWidth {
    Bits8,
    Bits16LE,
    Bits16BE,
    Bits32LE,
    Bits32BE,
    Bits64LE,
    Bits64BE,
}

/// Each `BusAddr` struct represents a specific data width and endianness.

/// 8 bit Bus Address
pub struct BusAddr8(u8);

/// 16 bit Big Endian Bus Address
pub struct BusAddr16BE(u16);

/// 16 bit Little Endian Bus Address
pub struct BusAddr16LE(u16);

/// 32 bit Big Endian Bus Address
pub struct BusAddr32BE(u32);

/// 32 bit Little Endian Bus Address
pub struct BusAddr32LE(u32);

/// 64 bit Big Endian Bus Address
pub struct BusAddr64BE(u64);

/// 64 bit Little Endian Bus Address
pub struct BusAddr64LE(u64);

impl From<BusAddr8> for BusAddr8080 {
    fn from(value: BusAddr8) -> Self {
        BusAddr8080::BusAddr8(value.0)
    }
}
impl From<BusAddr16BE> for BusAddr8080 {
    fn from(value: BusAddr16BE) -> Self {
        BusAddr8080::BusAddr16BE(value.0)
    }
}
impl From<BusAddr16LE> for BusAddr8080 {
    fn from(value: BusAddr16LE) -> Self {
        BusAddr8080::BusAddr16LE(value.0)
    }
}

impl From<u8> for BusAddr8 {
    fn from(value: u8) -> Self {
        Self(value)
    }
}
impl From<u16> for BusAddr16BE {
    fn from(value: u16) -> Self {
        Self(value)
    }
}
impl From<u16> for BusAddr16LE {
    fn from(value: u16) -> Self {
        Self(value)
    }
}
impl From<u32> for BusAddr32BE {
    fn from(value: u32) -> Self {
        Self(value)
    }
}
impl From<u32> for BusAddr32LE {
    fn from(value: u32) -> Self {
        Self(value)
    }
}
impl From<u64> for BusAddr64BE {
    fn from(value: u64) -> Self {
        Self(value)
    }
}
impl From<u64> for BusAddr64LE {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

/// The `BusAddr` trait is implemented for each BusAddr struct.
/// It provides information about the data width and a way
/// to access the underlying byte representation.
pub trait BusAddr {
    const DATA_WIDTH: DataWidth;
    fn len(&self) -> usize {
        Self::DATA_WIDTH.width_in_bytes()
    }
    fn bytes(&self) -> impl Iterator<Item = u8>;
}
impl BusAddr for BusAddr8 {
    const DATA_WIDTH: DataWidth = DataWidth::Bits8;
    fn bytes(&self) -> impl Iterator<Item = u8> {
        self.0.to_be_bytes().into_iter()
    }
}
impl BusAddr for BusAddr16BE {
    const DATA_WIDTH: DataWidth = DataWidth::Bits16BE;
    fn bytes(&self) -> impl Iterator<Item = u8> {
        self.0.to_be_bytes().into_iter()
    }
}
impl BusAddr for BusAddr16LE {
    const DATA_WIDTH: DataWidth = DataWidth::Bits16LE;
    fn bytes(&self) -> impl Iterator<Item = u8> {
        self.0.to_le_bytes().into_iter()
    }
}
impl BusAddr for BusAddr32BE {
    const DATA_WIDTH: DataWidth = DataWidth::Bits32BE;
    fn bytes(&self) -> impl Iterator<Item = u8> {
        self.0.to_be_bytes().into_iter()
    }
}
impl BusAddr for BusAddr32LE {
    const DATA_WIDTH: DataWidth = DataWidth::Bits32LE;
    fn bytes(&self) -> impl Iterator<Item = u8> {
        self.0.to_le_bytes().into_iter()
    }
}
impl BusAddr for BusAddr64BE {
    const DATA_WIDTH: DataWidth = DataWidth::Bits64BE;
    fn bytes(&self) -> impl Iterator<Item = u8> {
        self.0.to_be_bytes().into_iter()
    }
}
impl BusAddr for BusAddr64LE {
    const DATA_WIDTH: DataWidth = DataWidth::Bits64LE;
    fn bytes(&self) -> impl Iterator<Item = u8> {
        self.0.to_le_bytes().into_iter()
    }
}

impl DataWidth {
    pub fn width_in_bytes(&self) -> usize {
        match self {
            DataWidth::Bits8 => 1,
            DataWidth::Bits16BE | DataWidth::Bits16LE => 2,
            DataWidth::Bits32BE | DataWidth::Bits32LE => 4,
            DataWidth::Bits64BE | DataWidth::Bits64LE => 8,
        }
    }
}

pub trait Bus<'a, A: BusAddr> {
    /// Set the address to write to
    ///
    /// If the underlying bus does not support addresses (eg UART)
    /// this function returns ENOSUPPORT
    fn set_addr(&self, addr: A) -> Result<(), ErrorCode>;
    /// Write data items to the previously set address
    ///
    /// data_width specifies the encoding of the data items placed in the buffer
    /// len specifies the number of data items (the number of bytes is len * data_width.width_in_bytes)
    fn write(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])>;

    /// Read data items from the previously set address
    ///
    /// data_width specifies the encoding of the data items placed in the buffer
    /// len specifies the number of data items (the number of bytes is len * data_width.width_in_bytes)
    fn read(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])>;

    fn set_client(&self, client: &'a dyn Client);
}

pub trait Client {
    /// Called when set_addr, write or read are complete
    ///
    /// set_address does not return a buffer
    /// write and read return a buffer
    /// len should be set to the number of data elements written
    fn command_complete(
        &self,
        buffer: Option<&'static mut [u8]>,
        len: usize,
        status: Result<(), ErrorCode>,
    );
}

#[derive(Copy, Clone)]
enum BusStatus {
    Idle,
    SetAddress,
    Write,
    Read,
}

/*********** SPI ************/

pub struct SpiMasterBus<'a, S: SpiMasterDevice<'a>> {
    spi: &'a S,
    read_write_buffer: OptionalCell<SubSliceMut<'static, u8>>,
    bus_width: Cell<usize>,
    client: OptionalCell<&'a dyn Client>,
    addr_buffer: OptionalCell<SubSliceMut<'static, u8>>,
    status: Cell<BusStatus>,
}

impl<'a, S: SpiMasterDevice<'a>> SpiMasterBus<'a, S> {
    pub fn new(spi: &'a S, addr_buffer: &'static mut [u8]) -> SpiMasterBus<'a, S> {
        SpiMasterBus {
            spi,
            read_write_buffer: OptionalCell::empty(),
            bus_width: Cell::new(1),
            client: OptionalCell::empty(),
            addr_buffer: OptionalCell::new(addr_buffer.into()),
            status: Cell::new(BusStatus::Idle),
        }
    }

    pub fn set_read_write_buffer(&self, buffer: &'static mut [u8]) {
        self.read_write_buffer.replace(buffer.into());
    }

    pub fn configure(
        &self,
        cpol: ClockPolarity,
        cpal: ClockPhase,
        rate: u32,
    ) -> Result<(), ErrorCode> {
        self.spi.configure(cpol, cpal, rate)
    }
}

impl<'a, A: BusAddr, S: SpiMasterDevice<'a>> Bus<'a, A> for SpiMasterBus<'a, S> {
    fn set_addr(&self, addr: A) -> Result<(), ErrorCode> {
        self.addr_buffer
            .take()
            .map_or(Err(ErrorCode::NOMEM), |mut buffer| {
                let bytes = addr.bytes();
                if buffer.len() >= addr.len() {
                    buffer.reset();
                    buffer.slice(0..addr.len());
                    self.status.set(BusStatus::SetAddress);
                    buffer
                        .as_slice()
                        .iter_mut()
                        .zip(bytes)
                        .for_each(|(d, s)| *d = s);
                    if let Err((error, buffer, _)) = self.spi.read_write_bytes(buffer, None) {
                        self.status.set(BusStatus::Idle);
                        self.addr_buffer.replace(buffer);
                        Err(error)
                    } else {
                        Ok(())
                    }
                } else {
                    self.addr_buffer.replace(buffer);
                    Err(ErrorCode::SIZE)
                }
            })
    }

    fn write(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        // endianess does not matter as the buffer is sent as is
        let bytes = data_width.width_in_bytes();
        self.bus_width.set(bytes);
        if buffer.len() >= len * bytes {
            let mut buffer_slice: SubSliceMut<'static, u8> = buffer.into();
            buffer_slice.slice(0..(len * bytes));
            self.status.set(BusStatus::Write);
            if let Err((error, buffer, _)) = self.spi.read_write_bytes(buffer_slice, None) {
                self.status.set(BusStatus::Idle);
                Err((error, buffer.take()))
            } else {
                Ok(())
            }
        } else {
            Err((ErrorCode::NOMEM, buffer))
        }
    }

    fn read(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        // endianess does not matter as the buffer is read as is
        let bytes = data_width.width_in_bytes();
        self.bus_width.set(bytes);
        self.read_write_buffer.take().map_or_else(
            || panic!("bus::read: spi did not return the read write buffer"),
            move |write_buffer| {
                if write_buffer.len() >= len * bytes
                    && write_buffer.len() > 0
                    && buffer.len() > len * bytes
                {
                    let mut buffer_slice: SubSliceMut<'static, u8> = buffer.into();
                    buffer_slice.slice(0..(len * bytes));
                    self.status.set(BusStatus::Read);
                    if let Err((error, write_buffer, buffer)) =
                        self.spi.read_write_bytes(write_buffer, Some(buffer_slice))
                    {
                        self.status.set(BusStatus::Idle);
                        self.read_write_buffer.replace(write_buffer);
                        Err((error, buffer.map_or(&mut [] as &mut [u8], |b| b.take())))
                    } else {
                        Ok(())
                    }
                } else {
                    Err((ErrorCode::NOMEM, buffer))
                }
            },
        )
    }

    fn set_client(&self, client: &'a dyn Client) {
        self.client.replace(client);
    }
}

impl<'a, S: SpiMasterDevice<'a>> SpiMasterClient for SpiMasterBus<'a, S> {
    fn read_write_done(
        &self,
        write_buffer: SubSliceMut<'static, u8>,
        read_buffer: Option<SubSliceMut<'static, u8>>,
        status: Result<usize, ErrorCode>,
    ) {
        match self.status.get() {
            BusStatus::SetAddress => {
                self.addr_buffer.replace(write_buffer);
                self.client.map(move |client| {
                    client.command_complete(None, status.unwrap_or(0), status.map(|_| ()))
                });
            }
            BusStatus::Write | BusStatus::Read => {
                let mut buffer = write_buffer;
                if let Some(buf) = read_buffer {
                    self.read_write_buffer.replace(buffer);
                    buffer = buf;
                }
                self.client.map(move |client| {
                    client.command_complete(
                        Some(buffer.take()),
                        status.unwrap_or(0) / self.bus_width.get(),
                        status.map(|_| ()),
                    )
                });
            }
            _ => {
                panic!("spi sent an extra read_write_done");
            }
        }
    }
}

/*********** I2C ************/

pub struct I2CMasterBus<'a, I: I2CDevice> {
    i2c: &'a I,
    len: Cell<usize>,
    client: OptionalCell<&'a dyn Client>,
    addr_buffer: OptionalCell<&'static mut [u8]>,
    status: Cell<BusStatus>,
}

impl<'a, I: I2CDevice> I2CMasterBus<'a, I> {
    pub fn new(i2c: &'a I, addr_buffer: &'static mut [u8]) -> I2CMasterBus<'a, I> {
        I2CMasterBus {
            i2c,
            len: Cell::new(0),
            client: OptionalCell::empty(),
            addr_buffer: OptionalCell::new(addr_buffer),
            status: Cell::new(BusStatus::Idle),
        }
    }
}

impl<'a, A: BusAddr, I: I2CDevice> Bus<'a, A> for I2CMasterBus<'a, I> {
    fn set_addr(&self, addr: A) -> Result<(), ErrorCode> {
        self.addr_buffer
            .take()
            .map_or(Err(ErrorCode::NOMEM), |buffer| {
                self.status.set(BusStatus::SetAddress);
                let bytes = addr.bytes();
                if buffer.len() >= addr.len() {
                    let () = buffer.iter_mut().zip(bytes).for_each(|(d, s)| *d = s);
                    match self.i2c.write(buffer, addr.len()) {
                        Ok(()) => Ok(()),
                        Err((error, buffer)) => {
                            self.addr_buffer.replace(buffer);
                            Err(error.into())
                        }
                    }
                } else {
                    self.addr_buffer.replace(buffer);
                    Err(ErrorCode::SIZE)
                }
            })
    }

    fn write(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        // endianess does not matter as the buffer is sent as is
        let bytes = data_width.width_in_bytes();
        self.len.set(len * bytes);
        if len * bytes < 255 && buffer.len() >= len * bytes {
            debug!("write len {}", len);
            self.len.set(len);
            self.status.set(BusStatus::Write);
            match self.i2c.write(buffer, len * bytes) {
                Ok(()) => Ok(()),
                Err((error, buffer)) => Err((error.into(), buffer)),
            }
        } else {
            Err((ErrorCode::NOMEM, buffer))
        }
    }

    fn read(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        // endianess does not matter as the buffer is read as is
        let bytes = data_width.width_in_bytes();
        self.len.set(len * bytes);
        if len & bytes < 255 && buffer.len() >= len * bytes {
            self.len.set(len);
            self.status.set(BusStatus::Read);
            match self.i2c.read(buffer, len * bytes) {
                Ok(()) => Ok(()),
                Err((error, buffer)) => Err((error.into(), buffer)),
            }
        } else {
            Err((ErrorCode::NOMEM, buffer))
        }
    }

    fn set_client(&self, client: &'a dyn Client) {
        self.client.replace(client);
    }
}

impl<'a, I: I2CDevice> I2CClient for I2CMasterBus<'a, I> {
    fn command_complete(&self, buffer: &'static mut [u8], status: Result<(), Error>) {
        let len = match status {
            Ok(()) => self.len.get(),
            _ => 0,
        };
        let report_status = match status {
            Ok(()) => Ok(()),
            Err(error) => Err(error.into()),
        };
        match self.status.get() {
            BusStatus::SetAddress => {
                self.addr_buffer.replace(buffer);
                self.client
                    .map(move |client| client.command_complete(None, 0, report_status));
            }
            BusStatus::Write | BusStatus::Read => {
                self.client
                    .map(move |client| client.command_complete(Some(buffer), len, report_status));
            }
            _ => {
                panic!("i2c sent an extra read_write_done");
            }
        }
    }
}

/*************** Bus 8080  ***************/
pub struct Bus8080Bus<'a, B: Bus8080<'static>> {
    bus: &'a B,
    client: OptionalCell<&'a dyn Client>,
    status: Cell<BusStatus>,
}

impl<'a, B: Bus8080<'static>> Bus8080Bus<'a, B> {
    pub fn new(bus: &'a B) -> Bus8080Bus<'a, B> {
        Bus8080Bus {
            bus,
            client: OptionalCell::empty(),
            status: Cell::new(BusStatus::Idle),
        }
    }

    fn to_bus8080_width(bus_width: DataWidth) -> Option<bus8080::BusWidth> {
        match bus_width {
            DataWidth::Bits8 => Some(bus8080::BusWidth::Bits8),
            DataWidth::Bits16LE => Some(bus8080::BusWidth::Bits16LE),
            DataWidth::Bits16BE => Some(bus8080::BusWidth::Bits16BE),
            _ => None,
        }
    }
}

impl<'a, A: BusAddr + Into<BusAddr8080>, B: Bus8080<'static>> Bus<'a, A> for Bus8080Bus<'a, B> {
    fn set_addr(&self, addr: A) -> Result<(), ErrorCode> {
        let _ = self.bus.set_addr(addr.into());
        Ok(())
    }

    fn write(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        if let Some(bus_width) = Self::to_bus8080_width(data_width) {
            self.bus.write(bus_width, buffer, len)
        } else {
            Err((ErrorCode::INVAL, buffer))
        }
    }

    fn read(
        &self,
        data_width: DataWidth,
        buffer: &'static mut [u8],
        len: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        if let Some(bus_width) = Self::to_bus8080_width(data_width) {
            self.bus.read(bus_width, buffer, len)
        } else {
            Err((ErrorCode::INVAL, buffer))
        }
    }

    fn set_client(&self, client: &'a dyn Client) {
        self.client.replace(client);
    }
}

impl<'a, B: Bus8080<'static>> bus8080::Client for Bus8080Bus<'a, B> {
    fn command_complete(
        &self,
        buffer: Option<&'static mut [u8]>,
        len: usize,
        status: Result<(), ErrorCode>,
    ) {
        self.status.set(BusStatus::Idle);
        self.client.map(|client| {
            client.command_complete(buffer, len, status);
        });
    }
}