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

//! Provides userspace access to a Crc unit.
//!
//! ## Instantiation
//!
//! Instantiate the capsule for use as a system call driver with a hardware
//! implementation and a `Grant` for the `App` type, and set the result as a
//! client of the hardware implementation. For example, using the SAM4L's `CrcU`
//! driver:
//!
//! ```rust,ignore
//! # use kernel::static_init;
//!
//! let crc_buffer = static_init!([u8; 64], [0; 64]);
//!
//! let crc = static_init!(
//!     capsules::crc::CrcDriver<'static, sam4l::crccu::Crccu<'static>>,
//!     capsules::crc::CrcDriver::new(
//!         &mut sam4l::crccu::CRCCU,
//!         crc_buffer,
//!         board_kernel.create_grant(&grant_cap)
//!      )
//! );
//! sam4l::crccu::CRCCU.set_client(crc);
//!
//! ```
//!
//! ## Crc Algorithms
//!
//! The capsule supports two general purpose Crc algorithms, as well as a few
//! hardware specific algorithms implemented on the Atmel SAM4L.
//!
//! In the values used to identify polynomials below, more-significant bits
//! correspond to higher-order terms, and the most significant bit is omitted
//! because it always equals one.  All algorithms listed here consume each input
//! byte from most-significant bit to least-significant.
//!
//! ### Crc-32
//!
//! __Polynomial__: `0x04C11DB7`
//!
//! This algorithm is used in Ethernet and many other applications. It bit-
//! reverses and then bit-inverts the output.
//!
//! ### Crc-32C
//!
//! __Polynomial__: `0x1EDC6F41`
//!
//! Bit-reverses and then bit-inverts the output. It *may* be equivalent to
//! various Crc functions using the same name.
//!
//! ### SAM4L-16
//!
//! __Polynomial__: `0x1021`
//!
//! This algorithm does no post-processing on the output value. The sixteen-bit
//! Crc result is placed in the low-order bits of the returned result value, and
//! the high-order bits will all be set.  That is, result values will always be
//! of the form `0xFFFFxxxx` for this algorithm.  It can be performed purely in
//! hardware on the SAM4L.
//!
//! ### SAM4L-32
//!
//! __Polynomial__: `0x04C11DB7`
//!
//! This algorithm uses the same polynomial as `Crc-32`, but does no post-
//! processing on the output value.  It can be performed purely in hardware on
//! the SAM4L.
//!
//! ### SAM4L-32C
//!
//! __Polynomial__: `0x1EDC6F41`
//!
//! This algorithm uses the same polynomial as `Crc-32C`, but does no post-
//! processing on the output value.  It can be performed purely in hardware on
//! the SAM4L.

use core::cell::Cell;
use core::cmp;

use kernel::grant::{AllowRoCount, AllowRwCount, Grant, UpcallCount};
use kernel::hil::crc::{Client, Crc, CrcAlgorithm, CrcOutput};
use kernel::processbuffer::{ReadableProcessBuffer, ReadableProcessSlice};
use kernel::syscall::{CommandReturn, SyscallDriver};
use kernel::utilities::cells::NumericCellExt;
use kernel::utilities::cells::{OptionalCell, TakeCell};
use kernel::utilities::leasable_buffer::SubSliceMut;
use kernel::{ErrorCode, ProcessId};

/// Syscall driver number.
use capsules_core::driver;
pub const DRIVER_NUM: usize = driver::NUM::Crc as usize;
pub const DEFAULT_CRC_BUF_LENGTH: usize = 256;

/// Ids for read-only allow buffers
mod ro_allow {
    pub const BUFFER: usize = 0;
    /// The number of allow buffers the kernel stores for this grant
    pub const COUNT: u8 = 1;
}

/// An opaque value maintaining state for one application's request
#[derive(Default)]
pub struct App {
    // if Some, the process is waiting for the result of CRC
    // of len bytes using the given algorithm
    request: Option<(CrcAlgorithm, usize)>,
}

/// Struct that holds the state of the Crc driver and implements the `Driver` trait for use by
/// processes through the system call interface.
pub struct CrcDriver<'a, C: Crc<'a>> {
    crc: &'a C,
    crc_buffer: TakeCell<'static, [u8]>,
    grant: Grant<App, UpcallCount<1>, AllowRoCount<{ ro_allow::COUNT }>, AllowRwCount<0>>,
    current_process: OptionalCell<ProcessId>,
    // We need to save our current
    app_buffer_written: Cell<usize>,
}

impl<'a, C: Crc<'a>> CrcDriver<'a, C> {
    /// Create a `Crc` driver
    ///
    /// The argument `crc_unit` must implement the abstract `Crc`
    /// hardware interface.  The argument `apps` should be an empty
    /// kernel `Grant`, and will be used to track application
    /// requests.
    ///
    /// ## Example
    ///
    /// ```rust,ignore
    /// capsules::crc::Crc::new(&sam4l::crccu::CrcCU, board_kernel.create_grant(&grant_cap));
    /// ```
    ///
    pub fn new(
        crc: &'a C,
        crc_buffer: &'static mut [u8],
        grant: Grant<App, UpcallCount<1>, AllowRoCount<{ ro_allow::COUNT }>, AllowRwCount<0>>,
    ) -> CrcDriver<'a, C> {
        CrcDriver {
            crc,
            crc_buffer: TakeCell::new(crc_buffer),
            grant,
            current_process: OptionalCell::empty(),
            app_buffer_written: Cell::new(0),
        }
    }

    fn do_next_input(&self, data: &ReadableProcessSlice, len: usize) -> usize {
        let count = self.crc_buffer.take().map_or(0, |kbuffer| {
            let copy_len = cmp::min(len, kbuffer.len());
            for i in 0..copy_len {
                kbuffer[i] = data[i].get();
            }
            if copy_len > 0 {
                let mut leasable = SubSliceMut::new(kbuffer);
                leasable.slice(0..copy_len);
                let res = self.crc.input(leasable);
                match res {
                    Ok(()) => copy_len,
                    Err((_err, leasable)) => {
                        self.crc_buffer.put(Some(leasable.take()));
                        0
                    }
                }
            } else {
                0
            }
        });
        count
    }

    // Start a new request. Return Ok(()) if one started, Err(FAIL) if not.
    // Issue callbacks for any requests that are invalid, either because
    // they are zero-length or requested an invalid algorithm.
    fn next_request(&self) -> Result<(), ErrorCode> {
        self.app_buffer_written.set(0);
        for process in self.grant.iter() {
            let process_id = process.processid();
            let started = process.enter(|grant, kernel_data| {
                // If there's no buffer this means the process is dead, so
                // no need to issue a callback on this error case.
                let res: Result<(), ErrorCode> = kernel_data
                    .get_readonly_processbuffer(ro_allow::BUFFER)
                    .and_then(|buffer| {
                        buffer.enter(|buffer| {
                            if let Some((algorithm, len)) = grant.request {
                                let copy_len = cmp::min(len, buffer.len());
                                if copy_len == 0 {
                                    // 0-length or 0-size buffer
                                    Err(ErrorCode::SIZE)
                                } else {
                                    let res = self.crc.set_algorithm(algorithm);
                                    match res {
                                        Ok(()) => {
                                            let copy_len = self.do_next_input(buffer, copy_len);
                                            if copy_len > 0 {
                                                self.app_buffer_written.set(copy_len);
                                                self.current_process.set(process_id);
                                                Ok(())
                                            } else {
                                                // Next input failed
                                                Err(ErrorCode::FAIL)
                                            }
                                        }
                                        Err(_) => {
                                            // Setting the algorithm failed
                                            Err(ErrorCode::INVAL)
                                        }
                                    }
                                }
                            } else {
                                // no request
                                Err(ErrorCode::FAIL)
                            }
                        })
                    })
                    .unwrap_or(Err(ErrorCode::NOMEM));
                match res {
                    Ok(()) => Ok(()),
                    Err(e) => {
                        if grant.request.is_some() {
                            kernel_data
                                .schedule_upcall(
                                    0,
                                    (kernel::errorcode::into_statuscode(Err(e)), 0, 0),
                                )
                                .ok();
                            grant.request = None;
                        }
                        Err(e)
                    }
                }
            });
            if started.is_ok() {
                return started;
            }
        }
        Err(ErrorCode::FAIL)
    }
}

/// Processes can use the Crc system call driver to compute Crc redundancy checks over process
/// memory.
///
/// At a high level, the client first provides a callback for the result of computations through
/// the `subscribe` system call and `allow`s the driver access to the buffer over-which to compute.
/// Then, it initiates a Crc computation using the `command` system call. See function-specific
/// comments for details.
impl<'a, C: Crc<'a>> SyscallDriver for CrcDriver<'a, C> {
    /// The `allow` syscall for this driver supports the single
    /// `allow_num` zero, which is used to provide a buffer over which
    /// to compute a Crc computation.

    // The `subscribe` syscall supports the single `subscribe_number`
    // zero, which is used to provide a callback that will receive the
    // result of a Crc computation.  The signature of the callback is
    //
    // ```
    //
    // fn callback(status: Result<(), ErrorCode>, result: usize) {}
    // ```
    //
    // where
    //
    //   * `status` is indicates whether the computation
    //     succeeded. The status `BUSY` indicates the unit is already
    //     busy. The status `SIZE` indicates the provided buffer is
    //     too large for the unit to handle.
    //
    //   * `result` is the result of the Crc computation when `status == BUSY`.
    //

    /// The command system call for this driver return meta-data about the driver and kicks off
    /// Crc computations returned through callbacks.
    ///
    /// ### Command Numbers
    ///
    ///   *   `0`: Returns non-zero to indicate the driver is present.
    ///
    ///   *   `1`: Requests that a Crc be computed over the buffer
    ///       previously provided by `allow`.  If none was provided,
    ///       this command will return `INVAL`.
    ///
    ///       This command's driver-specific argument indicates what Crc
    ///       algorithm to perform, as listed below.  If an invalid
    ///       algorithm specifier is provided, this command will return
    ///       `INVAL`.
    ///
    ///       If a callback was not previously registered with
    ///       `subscribe`, this command will return `INVAL`.
    ///
    ///       If a computation has already been requested by this
    ///       application but the callback has not yet been invoked to
    ///       receive the result, this command will return `BUSY`.
    ///
    ///       When `Ok(())` is returned, this means the request has been
    ///       queued and the callback will be invoked when the Crc
    ///       computation is complete.
    ///
    /// ### Algorithm
    ///
    /// The Crc algorithms supported by this driver are listed below.  In
    /// the values used to identify polynomials, more-significant bits
    /// correspond to higher-order terms, and the most significant bit is
    /// omitted because it always equals one.  All algorithms listed here
    /// consume each input byte from most-significant bit to
    /// least-significant.
    ///
    ///   * `0: Crc-32`  This algorithm is used in Ethernet and many other
    ///   applications.  It uses polynomial 0x04C11DB7 and it bit-reverses
    ///   and then bit-inverts the output.
    ///
    ///   * `1: Crc-32C`  This algorithm uses polynomial 0x1EDC6F41 (due
    ///   to Castagnoli) and it bit-reverses and then bit-inverts the
    ///   output.  It *may* be equivalent to various Crc functions using
    ///   the same name.
    ///
    ///   * `2: Crc-16CCITT`  This algorithm uses polynomial 0x1021 and does
    ///   no post-processing on the output value. The sixteen-bit Crc
    ///   result is placed in the low-order bits of the returned result
    ///   value. That is, result values will always be of the form `0x0000xxxx`
    ///   for this algorithm.  It can be performed purely in hardware on the SAM4L.
    fn command(
        &self,
        command_num: usize,
        algorithm_id: usize,
        length: usize,
        process_id: ProcessId,
    ) -> CommandReturn {
        match command_num {
            // This driver is present
            0 => CommandReturn::success(),

            // Request a Crc computation
            1 => {
                // Parse the user provided algorithm number
                let algorithm = if let Some(alg) = alg_from_user_int(algorithm_id) {
                    alg
                } else {
                    return CommandReturn::failure(ErrorCode::INVAL);
                };
                let res = self
                    .grant
                    .enter(process_id, |grant, kernel_data| {
                        if grant.request.is_some() {
                            Err(ErrorCode::BUSY)
                        } else if length
                            > kernel_data
                                .get_readonly_processbuffer(ro_allow::BUFFER)
                                .map_or(0, |buffer| buffer.len())
                        {
                            Err(ErrorCode::SIZE)
                        } else {
                            grant.request = Some((algorithm, length));
                            Ok(())
                        }
                    })
                    .unwrap_or_else(|e| Err(ErrorCode::from(e)));

                match res {
                    Ok(()) => {
                        if self.current_process.is_none() {
                            self.next_request().map_or_else(
                                |e| CommandReturn::failure(ErrorCode::into(e)),
                                |()| CommandReturn::success(),
                            )
                        } else {
                            // Another request is ongoing. We've enqueued this one,
                            // wait for it to be started when it's its turn.
                            CommandReturn::success()
                        }
                    }
                    Err(e) => CommandReturn::failure(e),
                }
            }
            _ => CommandReturn::failure(ErrorCode::NOSUPPORT),
        }
    }

    fn allocate_grant(&self, processid: ProcessId) -> Result<(), kernel::process::Error> {
        self.grant.enter(processid, |_, _| {})
    }
}

impl<'a, C: Crc<'a>> Client for CrcDriver<'a, C> {
    fn input_done(&self, result: Result<(), ErrorCode>, buffer: SubSliceMut<'static, u8>) {
        // A call to `input` has finished. This can mean that either
        // we have processed the entire buffer passed in, or it was
        // truncated by the CRC unit as it was too large. In the first
        // case, we can see whether there is more outstanding data
        // from the app, whereas in the latter we need to advance the
        // SubSliceMut window and pass it in again.
        let mut computing = false;
        // There are three outcomes to this match:
        //   - crc_buffer is not put back: input is ongoing
        //   - crc_buffer is put back and computing is true: compute is ongoing
        //   - crc_buffer is put back and computing is false: something failed, start a new request
        match result {
            Ok(()) => {
                // Completed leasable buffer, either refill it or compute
                if buffer.len() == 0 {
                    // Put the kernel buffer back
                    self.crc_buffer.replace(buffer.take());
                    self.current_process.map(|pid| {
                        let _res = self.grant.enter(pid, |grant, kernel_data| {
                            // This shouldn't happen unless there's a way to clear out a request
                            // through a system call: regardless, the request is gone, so cancel
                            // the CRC.
                            if grant.request.is_none() {
                                kernel_data
                                    .schedule_upcall(
                                        0,
                                        (
                                            kernel::errorcode::into_statuscode(Err(
                                                ErrorCode::FAIL,
                                            )),
                                            0,
                                            0,
                                        ),
                                    )
                                    .ok();
                                return;
                            }

                            // Compute how many remaining bytes to compute over
                            let (alg, size) = grant.request.unwrap();
                            grant.request = Some((alg, size));
                            let size = kernel_data
                                .get_readonly_processbuffer(ro_allow::BUFFER)
                                .map_or(0, |buffer| buffer.len())
                                .min(size);
                            // If the buffer has shrunk, size might be less than
                            // app_buffer_written: don't allow wraparound
                            let remaining = size - cmp::min(self.app_buffer_written.get(), size);

                            if remaining == 0 {
                                // No more bytes to input: compute
                                let res = self.crc.compute();
                                match res {
                                    Ok(()) => {
                                        computing = true;
                                    }
                                    Err(_) => {
                                        grant.request = None;
                                        kernel_data
                                            .schedule_upcall(
                                                0,
                                                (
                                                    kernel::errorcode::into_statuscode(Err(
                                                        ErrorCode::FAIL,
                                                    )),
                                                    0,
                                                    0,
                                                ),
                                            )
                                            .ok();
                                    }
                                }
                            } else {
                                // More bytes: do the next input
                                let amount = kernel_data
                                    .get_readonly_processbuffer(ro_allow::BUFFER)
                                    .and_then(|buffer| {
                                        buffer.enter(|app_slice| {
                                            self.do_next_input(
                                                &app_slice[self.app_buffer_written.get()..],
                                                remaining,
                                            )
                                        })
                                    })
                                    .unwrap_or(0);
                                if amount == 0 {
                                    grant.request = None;
                                    kernel_data
                                        .schedule_upcall(
                                            0,
                                            (
                                                kernel::errorcode::into_statuscode(Err(
                                                    ErrorCode::NOMEM,
                                                )),
                                                0,
                                                0,
                                            ),
                                        )
                                        .ok();
                                } else {
                                    self.app_buffer_written.add(amount);
                                }
                            }
                        });
                    });
                } else {
                    // There's more in the leasable buffer: pass it to input again
                    let res = self.crc.input(buffer);
                    match res {
                        Ok(()) => {}
                        Err((e, returned_buffer)) => {
                            self.crc_buffer.replace(returned_buffer.take());
                            self.current_process.map(|pid| {
                                let _res = self.grant.enter(pid, |grant, kernel_data| {
                                    grant.request = None;
                                    kernel_data
                                        .schedule_upcall(
                                            0,
                                            (kernel::errorcode::into_statuscode(Err(e)), 0, 0),
                                        )
                                        .ok();
                                });
                            });
                        }
                    }
                }
            }
            Err(e) => {
                // The callback returned an error, pass it back to userspace
                self.crc_buffer.replace(buffer.take());
                self.current_process.map(|pid| {
                    let _res = self.grant.enter(pid, |grant, kernel_data| {
                        grant.request = None;
                        kernel_data
                            .schedule_upcall(0, (kernel::errorcode::into_statuscode(Err(e)), 0, 0))
                            .ok();
                    });
                });
            }
        }
        // The buffer was put back (there is no input ongoing) but computing is false,
        // so no compute is ongoing. Start a new request if there is one.
        if self.crc_buffer.is_some() && !computing {
            let _ = self.next_request();
        }
    }

    fn crc_done(&self, result: Result<CrcOutput, ErrorCode>) {
        // First of all, inform the app about the finished operation /
        // the result
        self.current_process.take().map(|process_id| {
            let _ = self.grant.enter(process_id, |grant, kernel_data| {
                grant.request = None;
                match result {
                    Ok(output) => {
                        let (val, user_int) = encode_upcall_crc_output(output);
                        kernel_data
                            .schedule_upcall(
                                0,
                                (
                                    kernel::errorcode::into_statuscode(Ok(())),
                                    val as usize,
                                    user_int as usize,
                                ),
                            )
                            .ok();
                    }
                    Err(e) => {
                        kernel_data
                            .schedule_upcall(0, (kernel::errorcode::into_statuscode(Err(e)), 0, 0))
                            .ok();
                    }
                }
            });
        });
        let _ = self.next_request();
    }
}

fn alg_from_user_int(i: usize) -> Option<CrcAlgorithm> {
    match i {
        0 => Some(CrcAlgorithm::Crc32),
        1 => Some(CrcAlgorithm::Crc32C),
        2 => Some(CrcAlgorithm::Crc16CCITT),
        _ => None,
    }
}

fn encode_upcall_crc_output(output: CrcOutput) -> (u32, u32) {
    match output {
        CrcOutput::Crc32(val) => (val, 0),
        CrcOutput::Crc32C(val) => (val, 1),
        CrcOutput::Crc16CCITT(val) => (val as u32, 2),
    }
}