Skip to main content

capsules_core/
i2c_master.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//! SyscallDriver for an I2C Master interface.
6
7use enum_primitive::enum_from_primitive;
8
9use kernel::grant::{AllowRoCount, AllowRwCount, Grant, GrantKernelData, UpcallCount};
10use kernel::hil::i2c;
11use kernel::processbuffer::{ReadableProcessBuffer, WriteableProcessBuffer};
12use kernel::syscall::{CommandReturn, SyscallDriver};
13use kernel::utilities::cells::{MapCell, OptionalCell, TakeCell};
14use kernel::{ErrorCode, ProcessId};
15
16/// Syscall driver number.
17use crate::driver;
18pub const DRIVER_NUM: usize = driver::NUM::I2cMaster as usize;
19
20/// Ids for read-write allow buffers
21mod rw_allow {
22    pub const BUFFER: usize = 1;
23    /// The number of allow buffers the kernel stores for this grant
24    pub const COUNT: u8 = 2;
25}
26
27#[derive(Default)]
28pub struct App;
29
30pub const BUFFER_LENGTH: usize = 64;
31
32struct Transaction {
33    /// The buffer containing the bytes to transmit as it should be returned to
34    /// the client
35    processid: ProcessId,
36    /// The total amount to transmit
37    read_len: OptionalCell<usize>,
38}
39
40pub struct I2CMasterDriver<'a, I: i2c::I2CMaster<'a>> {
41    i2c: &'a I,
42    buf: TakeCell<'static, [u8]>,
43    tx: MapCell<Transaction>,
44    apps: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<{ rw_allow::COUNT }>>,
45}
46
47impl<'a, I: i2c::I2CMaster<'a>> I2CMasterDriver<'a, I> {
48    pub fn new(
49        i2c: &'a I,
50        buf: &'static mut [u8],
51        apps: Grant<App, UpcallCount<1>, AllowRoCount<0>, AllowRwCount<{ rw_allow::COUNT }>>,
52    ) -> I2CMasterDriver<'a, I> {
53        I2CMasterDriver {
54            i2c,
55            buf: TakeCell::new(buf),
56            tx: MapCell::empty(),
57            apps,
58        }
59    }
60
61    fn operation(
62        &self,
63        processid: ProcessId,
64        kernel_data: &GrantKernelData,
65        command: Cmd,
66        addr: u8,
67        wlen: usize,
68        rlen: usize,
69    ) -> Result<(), ErrorCode> {
70        kernel_data
71            .get_readwrite_processbuffer(rw_allow::BUFFER)
72            .and_then(|buffer| {
73                buffer.enter(|app_buffer| {
74                    self.buf.take().map_or(Err(ErrorCode::NOMEM), |buffer| {
75                        if wlen > app_buffer.len() || wlen > buffer.len() || rlen > buffer.len() {
76                            self.buf.put(Some(buffer));
77                            return Err(ErrorCode::SIZE);
78                        }
79                        app_buffer[..wlen].copy_to_slice(&mut buffer[..wlen]);
80
81                        let read_len = if rlen == 0 {
82                            OptionalCell::empty()
83                        } else {
84                            OptionalCell::new(rlen)
85                        };
86                        self.tx.put(Transaction {
87                            processid,
88                            read_len,
89                        });
90
91                        let res = match command {
92                            Cmd::Ping => {
93                                self.buf.put(Some(buffer));
94                                return Err(ErrorCode::INVAL);
95                            }
96                            Cmd::Write => self.i2c.write(addr, buffer, wlen),
97                            Cmd::Read => self.i2c.read(addr, buffer, rlen),
98                            Cmd::WriteRead => self.i2c.write_read(addr, buffer, wlen, rlen),
99                        };
100                        match res {
101                            Ok(()) => Ok(()),
102                            Err((error, data)) => {
103                                self.buf.put(Some(data));
104                                Err(error.into())
105                            }
106                        }
107                    })
108                })
109            })
110            .unwrap_or(Err(ErrorCode::INVAL))
111    }
112}
113
114use enum_primitive::cast::FromPrimitive;
115
116enum_from_primitive! {
117#[derive(Debug, PartialEq, Clone, Copy)]
118pub enum Cmd {
119    Ping = 0,
120    Write = 1,
121    Read = 2,
122    WriteRead = 3,
123}
124}
125
126impl<'a, I: i2c::I2CMaster<'a>> SyscallDriver for I2CMasterDriver<'a, I> {
127    // Setup shared buffers.
128    //
129    // ### `allow_num`
130    //
131    // - `1`: buffer for command
132
133    // Setup callbacks.
134    //
135    // ### `subscribe_num`
136    //
137    // - `0`: Write buffer completed callback
138
139    /// Initiate transfers
140    fn command(
141        &self,
142        cmd_num: usize,
143        arg1: usize,
144        arg2: usize,
145        processid: ProcessId,
146    ) -> CommandReturn {
147        if let Some(cmd) = Cmd::from_usize(cmd_num) {
148            match cmd {
149                Cmd::Ping => CommandReturn::success(),
150                Cmd::Write => self
151                    .apps
152                    .enter(processid, |_, kernel_data| {
153                        let addr = arg1 as u8;
154                        let write_len = arg2;
155                        self.operation(processid, kernel_data, Cmd::Write, addr, write_len, 0)
156                            .into()
157                    })
158                    .unwrap_or_else(|err| err.into()),
159                Cmd::Read => self
160                    .apps
161                    .enter(processid, |_, kernel_data| {
162                        let addr = arg1 as u8;
163                        let read_len = arg2;
164                        self.operation(processid, kernel_data, Cmd::Read, addr, 0, read_len)
165                            .into()
166                    })
167                    .unwrap_or_else(|err| err.into()),
168                Cmd::WriteRead => {
169                    let addr = arg1 as u8;
170                    let write_len = arg1 >> 8; // can extend to 24 bit write length
171                    let read_len = arg2; // can extend to 32 bit read length
172                    self.apps
173                        .enter(processid, |_, kernel_data| {
174                            self.operation(
175                                processid,
176                                kernel_data,
177                                Cmd::WriteRead,
178                                addr,
179                                write_len,
180                                read_len,
181                            )
182                            .into()
183                        })
184                        .unwrap_or_else(|err| err.into())
185                }
186            }
187        } else {
188            CommandReturn::failure(ErrorCode::NOSUPPORT)
189        }
190    }
191
192    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
193        self.apps.enter(processid, |_, _| {})
194    }
195}
196
197impl<'a, I: i2c::I2CMaster<'a>> i2c::I2CHwMasterClient for I2CMasterDriver<'a, I> {
198    fn command_complete(&self, buffer: &'static mut [u8], status: Result<(), i2c::Error>) {
199        self.tx.take().map(|tx| {
200            self.apps.enter(tx.processid, |_, kernel_data| {
201                if let Some(read_len) = tx.read_len.take() {
202                    let _ = kernel_data
203                        .get_readwrite_processbuffer(rw_allow::BUFFER)
204                        .and_then(|app_buffer| {
205                            app_buffer.mut_enter(|app_buffer| {
206                                // The app may have swapped in a smaller buffer since the command.
207                                let len = read_len.min(app_buffer.len());
208                                app_buffer[..len].copy_from_slice(&buffer[..len]);
209                            })
210                        });
211                }
212
213                // signal to driver that tx complete
214                let _ = kernel_data.schedule_upcall(
215                    0,
216                    (
217                        kernel::errorcode::into_statuscode(status.map_err(|e| e.into())),
218                        0,
219                        0,
220                    ),
221                );
222            })
223        });
224
225        //recover buffer
226        self.buf.put(Some(buffer));
227    }
228}