Skip to main content

capsules_extra/
crc.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//! Provides userspace access to a Crc unit.
6//!
7//! ## Instantiation
8//!
9//! Instantiate the capsule for use as a system call driver with a hardware
10//! implementation and a `Grant` for the `App` type, and set the result as a
11//! client of the hardware implementation. For example, using the SAM4L's `CrcU`
12//! driver:
13//!
14//! ```rust,ignore
15//! # use kernel::static_init;
16//!
17//! let crc_buffer = static_init!([u8; 64], [0; 64]);
18//!
19//! let crc = static_init!(
20//!     capsules::crc::CrcDriver<'static, sam4l::crccu::Crccu<'static>>,
21//!     capsules::crc::CrcDriver::new(
22//!         &mut sam4l::crccu::CRCCU,
23//!         crc_buffer,
24//!         board_kernel.create_grant(&grant_cap)
25//!      )
26//! );
27//! sam4l::crccu::CRCCU.set_client(crc);
28//!
29//! ```
30//!
31//! ## Crc Algorithms
32//!
33//! The capsule supports two general purpose Crc algorithms, as well as a few
34//! hardware specific algorithms implemented on the Atmel SAM4L.
35//!
36//! In the values used to identify polynomials below, more-significant bits
37//! correspond to higher-order terms, and the most significant bit is omitted
38//! because it always equals one.  All algorithms listed here consume each input
39//! byte from most-significant bit to least-significant.
40//!
41//! ### Crc-32
42//!
43//! __Polynomial__: `0x04C11DB7`
44//!
45//! This algorithm is used in Ethernet and many other applications. It bit-
46//! reverses and then bit-inverts the output.
47//!
48//! ### Crc-32C
49//!
50//! __Polynomial__: `0x1EDC6F41`
51//!
52//! Bit-reverses and then bit-inverts the output. It *may* be equivalent to
53//! various Crc functions using the same name.
54//!
55//! ### SAM4L-16
56//!
57//! __Polynomial__: `0x1021`
58//!
59//! This algorithm does no post-processing on the output value. The sixteen-bit
60//! Crc result is placed in the low-order bits of the returned result value, and
61//! the high-order bits will all be set.  That is, result values will always be
62//! of the form `0xFFFFxxxx` for this algorithm.  It can be performed purely in
63//! hardware on the SAM4L.
64//!
65//! ### SAM4L-32
66//!
67//! __Polynomial__: `0x04C11DB7`
68//!
69//! This algorithm uses the same polynomial as `Crc-32`, but does no post-
70//! processing on the output value.  It can be performed purely in hardware on
71//! the SAM4L.
72//!
73//! ### SAM4L-32C
74//!
75//! __Polynomial__: `0x1EDC6F41`
76//!
77//! This algorithm uses the same polynomial as `Crc-32C`, but does no post-
78//! processing on the output value.  It can be performed purely in hardware on
79//! the SAM4L.
80
81use core::cell::Cell;
82use core::cmp;
83
84use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
85use kernel::hil::crc::{Client, Crc, CrcAlgorithm, CrcOutput};
86use kernel::processbuffer::{ReadableProcessBuffer, ReadableProcessSlice};
87use kernel::syscall::{CommandReturn, SyscallDriver};
88use kernel::utilities::cells::NumericCellExt;
89use kernel::utilities::cells::{OptionalCell, TakeCell};
90use kernel::utilities::leasable_buffer::SubSliceMut;
91use kernel::{ErrorCode, ProcessId};
92
93/// Syscall driver number.
94use capsules_core::driver;
95pub const DRIVER_NUM: usize = driver::NUM::Crc as usize;
96pub const DEFAULT_CRC_BUF_LENGTH: usize = 256;
97
98/// Ids for read-only allow buffers
99mod ro_allow {
100    pub const BUFFER: usize = 0;
101    /// The number of allow buffers the kernel stores for this grant
102    pub const COUNT: u8 = 1;
103}
104
105/// An opaque value maintaining state for one application's request
106#[derive(Default)]
107pub struct App {
108    // if Some, the process is waiting for the result of CRC
109    // of len bytes using the given algorithm
110    request: Option<(CrcAlgorithm, usize)>,
111}
112
113/// Struct that holds the state of the Crc driver and implements the `Driver` trait for use by
114/// processes through the system call interface.
115pub struct CrcDriver<'a, C: Crc<'a>> {
116    crc: &'a C,
117    crc_buffer: TakeCell<'static, [u8]>,
118    grant: Grant<App, UpcallCount<1>, AllowRoCount<{ ro_allow::COUNT }>, AllowRwCount<0>>,
119    current_process: OptionalCell<ProcessId>,
120    // We need to save our current
121    app_buffer_written: Cell<usize>,
122}
123
124impl<'a, C: Crc<'a>> CrcDriver<'a, C> {
125    /// Create a `Crc` driver
126    ///
127    /// The argument `crc_unit` must implement the abstract `Crc`
128    /// hardware interface.  The argument `apps` should be an empty
129    /// kernel `Grant`, and will be used to track application
130    /// requests.
131    ///
132    /// ## Example
133    ///
134    /// ```rust,ignore
135    /// capsules::crc::Crc::new(&sam4l::crccu::CrcCU, board_kernel.create_grant(&grant_cap));
136    /// ```
137    ///
138    pub fn new(
139        crc: &'a C,
140        crc_buffer: &'static mut [u8],
141        grant: Grant<App, UpcallCount<1>, AllowRoCount<{ ro_allow::COUNT }>, AllowRwCount<0>>,
142    ) -> CrcDriver<'a, C> {
143        CrcDriver {
144            crc,
145            crc_buffer: TakeCell::new(crc_buffer),
146            grant,
147            current_process: OptionalCell::empty(),
148            app_buffer_written: Cell::new(0),
149        }
150    }
151
152    fn do_next_input(&self, data: &ReadableProcessSlice, len: usize) -> usize {
153        self.crc_buffer.take().map_or(0, |kbuffer| {
154            let copy_len = cmp::min(len, kbuffer.len());
155            for i in 0..copy_len {
156                kbuffer[i] = data[i].get();
157            }
158            if copy_len > 0 {
159                let mut leasable = SubSliceMut::new(kbuffer);
160                leasable.slice(0..copy_len);
161                let res = self.crc.input(leasable);
162                match res {
163                    Ok(()) => copy_len,
164                    Err((_err, leasable)) => {
165                        self.crc_buffer.put(Some(leasable.take()));
166                        0
167                    }
168                }
169            } else {
170                0
171            }
172        })
173    }
174
175    // Start a new request. Return Ok(()) if one started, Err(FAIL) if not.
176    // Issue callbacks for any requests that are invalid, either because
177    // they are zero-length or requested an invalid algorithm.
178    fn next_request(&self) -> Result<(), ErrorCode> {
179        self.app_buffer_written.set(0);
180        for process in self.grant.iter() {
181            let process_id = process.processid();
182            let started = process.enter(|grant, kernel_data| {
183                // If there's no buffer this means the process is dead, so
184                // no need to issue a callback on this error case.
185                let res: Result<(), ErrorCode> = kernel_data
186                    .get_readonly_processbuffer(ro_allow::BUFFER)
187                    .and_then(|buffer| {
188                        buffer.enter(|buffer| {
189                            if let Some((algorithm, len)) = grant.request {
190                                let copy_len = cmp::min(len, buffer.len());
191                                if copy_len == 0 {
192                                    // 0-length or 0-size buffer
193                                    Err(ErrorCode::SIZE)
194                                } else {
195                                    let res = self.crc.set_algorithm(algorithm);
196                                    match res {
197                                        Ok(()) => {
198                                            let copy_len = self.do_next_input(buffer, copy_len);
199                                            if copy_len > 0 {
200                                                self.app_buffer_written.set(copy_len);
201                                                self.current_process.set(process_id);
202                                                Ok(())
203                                            } else {
204                                                // Next input failed
205                                                Err(ErrorCode::FAIL)
206                                            }
207                                        }
208                                        Err(_) => {
209                                            // Setting the algorithm failed
210                                            Err(ErrorCode::INVAL)
211                                        }
212                                    }
213                                }
214                            } else {
215                                // no request
216                                Err(ErrorCode::FAIL)
217                            }
218                        })
219                    })
220                    .unwrap_or(Err(ErrorCode::NOMEM));
221                match res {
222                    Ok(()) => Ok(()),
223                    Err(e) => {
224                        if grant.request.is_some() {
225                            let _ = kernel_data.schedule_upcall(
226                                0,
227                                (kernel::errorcode::into_statuscode(Err(e)), 0, 0),
228                            );
229                            grant.request = None;
230                        }
231                        Err(e)
232                    }
233                }
234            });
235            if started.is_ok() {
236                return started;
237            }
238        }
239        Err(ErrorCode::FAIL)
240    }
241}
242
243/// Processes can use the Crc system call driver to compute Crc redundancy checks over process
244/// memory.
245///
246/// At a high level, the client first provides a callback for the result of computations through
247/// the `subscribe` system call and `allow`s the driver access to the buffer over-which to compute.
248/// Then, it initiates a Crc computation using the `command` system call. See function-specific
249/// comments for details.
250impl<'a, C: Crc<'a>> SyscallDriver for CrcDriver<'a, C> {
251    // The `allow` syscall for this driver supports the single
252    // `allow_num` zero, which is used to provide a buffer over which
253    // to compute a Crc computation.
254
255    // The `subscribe` syscall supports the single `subscribe_number`
256    // zero, which is used to provide a callback that will receive the
257    // result of a Crc computation.  The signature of the callback is
258    //
259    // ```
260    //
261    // fn callback(status: Result<(), ErrorCode>, result: usize) {}
262    // ```
263    //
264    // where
265    //
266    // * `status` is indicates whether the computation succeeded. The status
267    //   `BUSY` indicates the unit is already busy. The status `SIZE` indicates
268    //   the provided buffer is too large for the unit to handle.
269    //
270    // * `result` is the result of the Crc computation when `status == BUSY`.
271    //
272
273    /// The command system call for this driver return meta-data about the driver and kicks off
274    /// Crc computations returned through callbacks.
275    ///
276    /// ### Command Numbers
277    ///
278    /// * `0`: Returns non-zero to indicate the driver is present.
279    ///
280    /// * `1`: Requests that a Crc be computed over the buffer previously
281    ///   provided by `allow`.  If none was provided, this command will return
282    ///   `INVAL`.
283    ///
284    ///   This command's driver-specific argument indicates what Crc algorithm
285    ///   to perform, as listed below.  If an invalid algorithm specifier is
286    ///   provided, this command will return `INVAL`.
287    ///
288    ///   If a callback was not previously registered with `subscribe`, this
289    ///   command will return `INVAL`.
290    ///
291    ///   If a computation has already been requested by this application but
292    ///   the callback has not yet been invoked to receive the result, this
293    ///   command will return `BUSY`.
294    ///
295    ///   When `Ok(())` is returned, this means the request has been queued and
296    ///   the callback will be invoked when the Crc computation is complete.
297    ///
298    /// ### Algorithm
299    ///
300    /// The Crc algorithms supported by this driver are listed below.  In
301    /// the values used to identify polynomials, more-significant bits
302    /// correspond to higher-order terms, and the most significant bit is
303    /// omitted because it always equals one.  All algorithms listed here
304    /// consume each input byte from most-significant bit to
305    /// least-significant.
306    ///
307    /// * `0: Crc-32`  This algorithm is used in Ethernet and many other
308    ///   applications.  It uses polynomial 0x04C11DB7 and it bit-reverses
309    ///   and then bit-inverts the output.
310    ///
311    /// * `1: Crc-32C`  This algorithm uses polynomial 0x1EDC6F41 (due
312    ///   to Castagnoli) and it bit-reverses and then bit-inverts the
313    ///   output.  It *may* be equivalent to various Crc functions using
314    ///   the same name.
315    ///
316    /// * `2: Crc-16CCITT`  This algorithm uses polynomial 0x1021 and does
317    ///   no post-processing on the output value. The sixteen-bit Crc
318    ///   result is placed in the low-order bits of the returned result
319    ///   value. That is, result values will always be of the form `0x0000xxxx`
320    ///   for this algorithm.  It can be performed purely in hardware on the SAM4L.
321    fn command(
322        &self,
323        command_num: usize,
324        algorithm_id: usize,
325        length: usize,
326        process_id: ProcessId,
327    ) -> CommandReturn {
328        match command_num {
329            // This driver is present
330            0 => CommandReturn::success(),
331
332            // Request a Crc computation
333            1 => {
334                // Parse the user provided algorithm number
335                let algorithm = if let Some(alg) = alg_from_user_int(algorithm_id) {
336                    alg
337                } else {
338                    return CommandReturn::failure(ErrorCode::INVAL);
339                };
340                let res = self
341                    .grant
342                    .enter(process_id, |grant, kernel_data| {
343                        if grant.request.is_some() {
344                            Err(ErrorCode::BUSY)
345                        } else if length
346                            > kernel_data
347                                .get_readonly_processbuffer(ro_allow::BUFFER)
348                                .map_or(0, |buffer| buffer.len())
349                        {
350                            Err(ErrorCode::SIZE)
351                        } else {
352                            grant.request = Some((algorithm, length));
353                            Ok(())
354                        }
355                    })
356                    .unwrap_or_else(|e| Err(ErrorCode::from(e)));
357
358                match res {
359                    Ok(()) => {
360                        if self.current_process.is_none() {
361                            self.next_request().map_or_else(
362                                |e| CommandReturn::failure(ErrorCode::into(e)),
363                                |()| CommandReturn::success(),
364                            )
365                        } else {
366                            // Another request is ongoing. We've enqueued this one,
367                            // wait for it to be started when it's its turn.
368                            CommandReturn::success()
369                        }
370                    }
371                    Err(e) => CommandReturn::failure(e),
372                }
373            }
374            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
375        }
376    }
377
378    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
379        self.grant.enter(processid, |_, _| {})
380    }
381}
382
383impl<'a, C: Crc<'a>> Client for CrcDriver<'a, C> {
384    fn input_done(&self, result: Result<(), ErrorCode>, buffer: SubSliceMut<'static, u8>) {
385        // A call to `input` has finished. This can mean that either
386        // we have processed the entire buffer passed in, or it was
387        // truncated by the CRC unit as it was too large. In the first
388        // case, we can see whether there is more outstanding data
389        // from the app, whereas in the latter we need to advance the
390        // SubSliceMut window and pass it in again.
391        let mut computing = false;
392        // There are three outcomes to this match:
393        // - crc_buffer is not put back: input is ongoing
394        // - crc_buffer is put back and computing is true: compute is ongoing
395        // - crc_buffer is put back and computing is false: something failed, start a new request
396        match result {
397            Ok(()) => {
398                // Completed leasable buffer, either refill it or compute
399                if buffer.len() == 0 {
400                    // Put the kernel buffer back
401                    self.crc_buffer.replace(buffer.take());
402                    self.current_process.map(|pid| {
403                        let _res = self.grant.enter(pid, |grant, kernel_data| {
404                            // This shouldn't happen unless there's a way to clear out a request
405                            // through a system call: regardless, the request is gone, so cancel
406                            // the CRC.
407                            if grant.request.is_none() {
408                                let _ = kernel_data.schedule_upcall(
409                                    0,
410                                    (
411                                        kernel::errorcode::into_statuscode(Err(ErrorCode::FAIL)),
412                                        0,
413                                        0,
414                                    ),
415                                );
416                                return;
417                            }
418
419                            // Compute how many remaining bytes to compute over
420                            let (alg, size) = grant.request.unwrap();
421                            grant.request = Some((alg, size));
422                            let size = kernel_data
423                                .get_readonly_processbuffer(ro_allow::BUFFER)
424                                .map_or(0, |buffer| buffer.len())
425                                .min(size);
426                            // If the buffer has shrunk, size might be less than
427                            // app_buffer_written: don't allow wraparound
428                            let remaining = size - cmp::min(self.app_buffer_written.get(), size);
429
430                            if remaining == 0 {
431                                // No more bytes to input: compute
432                                let res = self.crc.compute();
433                                match res {
434                                    Ok(()) => {
435                                        computing = true;
436                                    }
437                                    Err(_) => {
438                                        grant.request = None;
439                                        let _ = kernel_data.schedule_upcall(
440                                            0,
441                                            (
442                                                kernel::errorcode::into_statuscode(Err(
443                                                    ErrorCode::FAIL,
444                                                )),
445                                                0,
446                                                0,
447                                            ),
448                                        );
449                                    }
450                                }
451                            } else {
452                                // More bytes: do the next input
453                                let amount = kernel_data
454                                    .get_readonly_processbuffer(ro_allow::BUFFER)
455                                    .and_then(|buffer| {
456                                        buffer.enter(|app_slice| {
457                                            self.do_next_input(
458                                                &app_slice[self.app_buffer_written.get()..],
459                                                remaining,
460                                            )
461                                        })
462                                    })
463                                    .unwrap_or(0);
464                                if amount == 0 {
465                                    grant.request = None;
466                                    let _ = kernel_data.schedule_upcall(
467                                        0,
468                                        (
469                                            kernel::errorcode::into_statuscode(Err(
470                                                ErrorCode::NOMEM,
471                                            )),
472                                            0,
473                                            0,
474                                        ),
475                                    );
476                                } else {
477                                    self.app_buffer_written.add(amount);
478                                }
479                            }
480                        });
481                    });
482                } else {
483                    // There's more in the leasable buffer: pass it to input again
484                    let res = self.crc.input(buffer);
485                    match res {
486                        Ok(()) => {}
487                        Err((e, returned_buffer)) => {
488                            self.crc_buffer.replace(returned_buffer.take());
489                            self.current_process.map(|pid| {
490                                let _res = self.grant.enter(pid, |grant, kernel_data| {
491                                    grant.request = None;
492                                    let _ = kernel_data.schedule_upcall(
493                                        0,
494                                        (kernel::errorcode::into_statuscode(Err(e)), 0, 0),
495                                    );
496                                });
497                            });
498                        }
499                    }
500                }
501            }
502            Err(e) => {
503                // The callback returned an error, pass it back to userspace
504                self.crc_buffer.replace(buffer.take());
505                self.current_process.map(|pid| {
506                    let _res = self.grant.enter(pid, |grant, kernel_data| {
507                        grant.request = None;
508                        let _ = kernel_data
509                            .schedule_upcall(0, (kernel::errorcode::into_statuscode(Err(e)), 0, 0));
510                    });
511                });
512            }
513        }
514        // The buffer was put back (there is no input ongoing) but computing is false,
515        // so no compute is ongoing. Start a new request if there is one.
516        if self.crc_buffer.is_some() && !computing {
517            let _ = self.next_request();
518        }
519    }
520
521    fn crc_done(&self, result: Result<CrcOutput, ErrorCode>) {
522        // First of all, inform the app about the finished operation /
523        // the result
524        self.current_process.take().map(|process_id| {
525            let _ = self.grant.enter(process_id, |grant, kernel_data| {
526                grant.request = None;
527                match result {
528                    Ok(output) => {
529                        let (val, user_int) = encode_upcall_crc_output(output);
530                        let _ = kernel_data.schedule_upcall(
531                            0,
532                            (
533                                kernel::errorcode::into_statuscode(Ok(())),
534                                val as usize,
535                                user_int as usize,
536                            ),
537                        );
538                    }
539                    Err(e) => {
540                        let _ = kernel_data
541                            .schedule_upcall(0, (kernel::errorcode::into_statuscode(Err(e)), 0, 0));
542                    }
543                }
544            });
545        });
546        let _ = self.next_request();
547    }
548}
549
550fn alg_from_user_int(i: usize) -> Option<CrcAlgorithm> {
551    match i {
552        0 => Some(CrcAlgorithm::Crc32),
553        1 => Some(CrcAlgorithm::Crc32C),
554        2 => Some(CrcAlgorithm::Crc16CCITT),
555        _ => None,
556    }
557}
558
559fn encode_upcall_crc_output(output: CrcOutput) -> (u32, u32) {
560    match output {
561        CrcOutput::Crc32(val) => (val, 0),
562        CrcOutput::Crc32C(val) => (val, 1),
563        CrcOutput::Crc16CCITT(val) => (val as u32, 2),
564    }
565}