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
//! Provides userspace applications with the ability to communicate over the SPI
//! bus.

use core::cell::Cell;
use core::cmp;
use kernel::{AppId, AppSlice, Callback, Driver, ReturnCode, Shared};
use kernel::common::take_cell::{MapCell, TakeCell};
use kernel::hil::spi::{SpiMasterClient, SpiMasterDevice, SpiSlaveClient, SpiSlaveDevice};
use kernel::hil::spi::ClockPhase;
use kernel::hil::spi::ClockPolarity;

/// Syscall number
pub const DRIVER_NUM: usize = 0x20001;

// SPI operations are handled by coping into a kernel buffer for
// writes and copying out of a kernel buffer for reads.
//
// If the application buffer is larger than the kernel buffer,
// the driver issues multiple HAL operations. The len field
// of an application keeps track of the length of the desired
// operation, while the index variable keeps track of the
// index an ongoing operation is at in the buffers.

struct App {
    callback: Option<Callback>,
    app_read: Option<AppSlice<Shared, u8>>,
    app_write: Option<AppSlice<Shared, u8>>,
    len: usize,
    index: usize,
}

impl Default for App {
    fn default() -> App {
        App {
            callback: None,
            app_read: None,
            app_write: None,
            len: 0,
            index: 0,
        }
    }
}

// Since we provide an additional callback in slave mode for
// when the chip is selected, we have added a "SlaveApp" struct
// that includes this new callback field.
struct SlaveApp {
    callback: Option<Callback>,
    selected_callback: Option<Callback>,
    app_read: Option<AppSlice<Shared, u8>>,
    app_write: Option<AppSlice<Shared, u8>>,
    len: usize,
    index: usize,
}

impl Default for SlaveApp {
    fn default() -> SlaveApp {
        SlaveApp {
            callback: None,
            selected_callback: None,
            app_read: None,
            app_write: None,
            len: 0,
            index: 0,
        }
    }
}

pub struct Spi<'a, S: SpiMasterDevice + 'a> {
    spi_master: &'a S,
    busy: Cell<bool>,
    app: MapCell<App>,
    kernel_read: TakeCell<'static, [u8]>,
    kernel_write: TakeCell<'static, [u8]>,
    kernel_len: Cell<usize>,
}

pub struct SpiSlave<'a, S: SpiSlaveDevice + 'a> {
    spi_slave: &'a S,
    busy: Cell<bool>,
    app: MapCell<SlaveApp>,
    kernel_read: TakeCell<'static, [u8]>,
    kernel_write: TakeCell<'static, [u8]>,
    kernel_len: Cell<usize>,
}

impl<'a, S: SpiMasterDevice> Spi<'a, S> {
    pub fn new(spi_master: &'a S) -> Spi<'a, S> {
        Spi {
            spi_master: spi_master,
            busy: Cell::new(false),
            app: MapCell::new(App::default()),
            kernel_len: Cell::new(0),
            kernel_read: TakeCell::empty(),
            kernel_write: TakeCell::empty(),
        }
    }

    pub fn config_buffers(&mut self, read: &'static mut [u8], write: &'static mut [u8]) {
        let len = cmp::min(read.len(), write.len());
        self.kernel_len.set(len);
        self.kernel_read.replace(read);
        self.kernel_write.replace(write);
    }

    // Assumes checks for busy/etc. already done
    // Updates app.index to be index + length of op
    fn do_next_read_write(&self, app: &mut App) {
        let start = app.index;
        let len = cmp::min(app.len - start, self.kernel_len.get());
        let end = start + len;
        app.index = end;

        self.kernel_write.map(|kwbuf| {
            app.app_write.as_mut().map(|src| {
                for (i, c) in src.as_ref()[start..end].iter().enumerate() {
                    kwbuf[i] = *c;
                }
            });
        });
        self.spi_master.read_write_bytes(
            self.kernel_write.take().unwrap(),
            self.kernel_read.take(),
            len,
        );
    }
}

impl<'a, S: SpiMasterDevice> Driver for Spi<'a, S> {
    fn allow(&self, _appid: AppId, allow_num: usize, slice: AppSlice<Shared, u8>) -> ReturnCode {
        match allow_num {
            // Pass in a read buffer to receive bytes into.
            0 => {
                self.app.map(|app| {
                    app.app_read = Some(slice);
                });
                ReturnCode::SUCCESS
            }
            // Pass in a write buffer to transmit bytes from.
            1 => {
                self.app.map(|app| {
                    app.app_write = Some(slice);
                });
                ReturnCode::SUCCESS
            }
            _ => ReturnCode::ENOSUPPORT,
        }
    }

    fn subscribe(&self, subscribe_num: usize, callback: Callback) -> ReturnCode {
        match subscribe_num {
            0 /* read_write */ => {
                self.app.map(|app| {
                    app.callback = Some(callback);
                });
                ReturnCode::SUCCESS
            },
            _ => ReturnCode::ENOSUPPORT
        }
    }

    // 2: read/write buffers
    //   - requires write buffer registered with allow
    //   - read buffer optional
    // 3: set chip select
    //   - selects which peripheral (CS line) the SPI should
    //     activate
    //   - valid values are 0-3 for SAM4L
    //   - invalid value will result in CS 0
    // 4: get chip select
    //   - returns current selected peripheral
    // 5: set rate on current peripheral
    //   - parameter in bps
    // 6: get rate on current peripheral
    //   - value in bps
    // 7: set clock phase on current peripheral
    //   - 0 is sample leading
    //   - non-zero is sample trailing
    // 8: get clock phase on current peripheral
    //   - 0 is sample leading
    //   - non-zero is sample trailing
    // 9: set clock polarity on current peripheral
    //   - 0 is idle low
    //   - non-zero is idle high
    // 10: get clock polarity on current peripheral
    //   - 0 is idle low
    //   - non-zero is idle high
    //
    // x: lock spi
    //   - if you perform an operation without the lock,
    //     it implicitly acquires the lock before the
    //     operation and releases it after
    //   - while an app holds the lock no other app can issue
    //     operations on SPI (they are buffered)
    // x+1: unlock spi
    //   - does nothing if lock not held
    //
    fn command(&self, cmd_num: usize, arg1: usize, _: usize, _: AppId) -> ReturnCode {
        match cmd_num {
            0 /* check if present */ => ReturnCode::SUCCESS,
            // No longer supported, wrap inside a read_write_bytes
            1 /* read_write_byte */ => ReturnCode::ENOSUPPORT,
            2 /* read_write_bytes */ => {
                if self.busy.get() {
                    return ReturnCode::EBUSY;
                }
                self.app.map_or(ReturnCode::FAIL, |app| {
                    let mut mlen = 0;
                    app.app_write.as_mut().map(|w| {
                        mlen = w.len();
                    });
                    app.app_read.as_mut().map(|r| {
                        mlen = cmp::min(mlen, r.len());
                    });
                    if mlen >= arg1 {
                        app.len = arg1;
                        app.index = 0;
                        self.busy.set(true);
                        self.do_next_read_write(app);
                        ReturnCode::SUCCESS
                    } else {
                        ReturnCode::EINVAL /* write buffer too small */
                    }
                })
            }
            3 /* set chip select */ => {
                // XXX: TODO: do nothing, for now, until we fix interface
                // so virtual instances can use multiple chip selects
                ReturnCode::ENOSUPPORT
            }
            4 /* get chip select */ => {
                // XXX: We don't really know what chip select is being used
                // since we can't set it. Return error until set chip select
                // works.
                ReturnCode::ENOSUPPORT
            }
            5 /* set baud rate */ => {
                self.spi_master.set_rate(arg1 as u32);
                ReturnCode::SUCCESS
            }
            6 /* get baud rate */ => {
                ReturnCode::SuccessWithValue { value: self.spi_master.get_rate() as usize }
            }
            7 /* set phase */ => {
                match arg1 {
                    0 => self.spi_master.set_phase(ClockPhase::SampleLeading),
                    _ => self.spi_master.set_phase(ClockPhase::SampleTrailing),
                };
                ReturnCode::SUCCESS
            }
            8 /* get phase */ => {
                ReturnCode::SuccessWithValue { value: self.spi_master.get_phase() as usize }
            }
            9 /* set polarity */ => {
                match arg1 {
                    0 => self.spi_master.set_polarity(ClockPolarity::IdleLow),
                    _ => self.spi_master.set_polarity(ClockPolarity::IdleHigh),
                };
                ReturnCode::SUCCESS
            }
            10 /* get polarity */ => {
                ReturnCode::SuccessWithValue { value: self.spi_master.get_polarity() as usize }
            }
            _ => ReturnCode::ENOSUPPORT
        }
    }
}

impl<'a, S: SpiMasterDevice> SpiMasterClient for Spi<'a, S> {
    fn read_write_done(
        &self,
        writebuf: &'static mut [u8],
        readbuf: Option<&'static mut [u8]>,
        length: usize,
    ) {
        self.app.map(move |app| {
            if app.app_read.is_some() {
                let src = readbuf.as_ref().unwrap();
                let dest = app.app_read.as_mut().unwrap();
                let start = app.index - length;
                let end = start + length;

                let d = &mut dest.as_mut()[start..end];
                for (i, c) in src[0..length].iter().enumerate() {
                    d[i] = *c;
                }
            }

            self.kernel_read.put(readbuf);
            self.kernel_write.replace(writebuf);

            if app.index == app.len {
                self.busy.set(false);
                app.len = 0;
                app.index = 0;
                app.callback.take().map(|mut cb| {
                    cb.schedule(app.len, 0, 0);
                });
            } else {
                self.do_next_read_write(app);
            }
        });
    }
}

impl<'a, S: SpiSlaveDevice> SpiSlave<'a, S> {
    pub fn new(spi_slave: &'a S) -> SpiSlave<'a, S> {
        SpiSlave {
            spi_slave: spi_slave,
            busy: Cell::new(false),
            app: MapCell::new(SlaveApp::default()),
            kernel_len: Cell::new(0),
            kernel_read: TakeCell::empty(),
            kernel_write: TakeCell::empty(),
        }
    }

    pub fn config_buffers(&mut self, read: &'static mut [u8], write: &'static mut [u8]) {
        let len = cmp::min(read.len(), write.len());
        self.kernel_len.set(len);
        self.kernel_read.replace(read);
        self.kernel_write.replace(write);
    }

    // Assumes checks for busy/etc. already done
    // Updates app.index to be index + length of op
    fn do_next_read_write(&self, app: &mut SlaveApp) {
        let start = app.index;
        let len = cmp::min(app.len - start, self.kernel_len.get());
        let end = start + len;
        app.index = end;

        self.kernel_write.map(|kwbuf| {
            app.app_write.as_mut().map(|src| {
                for (i, c) in src.as_ref()[start..end].iter().enumerate() {
                    kwbuf[i] = *c;
                }
            });
        });
        self.spi_slave
            .read_write_bytes(self.kernel_write.take(), self.kernel_read.take(), len);
    }
}

impl<'a, S: SpiSlaveDevice> Driver for SpiSlave<'a, S> {
    /// Provide read/write buffers to SpiSlave
    ///
    /// - allow_num 0: Provides an app_read buffer to receive transfers into.
    ///
    /// - allow_num 1: Provides an app_write buffer to send transfers from.
    ///
    fn allow(&self, _appid: AppId, allow_num: usize, slice: AppSlice<Shared, u8>) -> ReturnCode {
        match allow_num {
            0 => {
                self.app.map(|app| app.app_read = Some(slice));
                ReturnCode::SUCCESS
            }
            1 => {
                self.app.map(|app| app.app_write = Some(slice));
                ReturnCode::SUCCESS
            }
            _ => ReturnCode::ENOSUPPORT,
        }
    }

    /// Setup callbacks for SpiSlave
    ///
    /// - subscribe_num 0: Sets up a callback for when read_write completes. This
    ///                  is called after completing a transfer/reception with
    ///                  the Spi master. Note that this occurs after the pending
    ///                  DMA transfer initiated by read_write_bytes completes.
    ///
    /// - subscribe_num 1: Sets up a callback for when the chip select line is
    ///                  driven low, meaning that the slave was selected by
    ///                  the Spi master. This occurs immediately before
    ///                  a data transfer.
    fn subscribe(&self, subscribe_num: usize, callback: Callback) -> ReturnCode {
        match subscribe_num {
            0 /* read_write */ => {
                self.app.map(|app| app.callback = Some(callback));
                ReturnCode::SUCCESS
            },
            1 /* chip selected */ => {
                self.app.map(|app| app.selected_callback = Some(callback));
                ReturnCode::SUCCESS
            },
            _ => ReturnCode::ENOSUPPORT
        }
    }

    /// - 0: check if present
    /// - 1: read/write buffers
    ///   - read and write buffers optional
    ///   - fails if arg1 (bytes to write) >
    ///     write_buffer.len()
    /// - 2: get chip select
    ///   - returns current selected peripheral
    ///   - in slave mode, always returns 0
    /// - 3: set clock phase on current peripheral
    ///   - 0 is sample leading
    ///   - non-zero is sample trailing
    /// - 4: get clock phase on current peripheral
    ///   - 0 is sample leading
    ///   - non-zero is sample trailing
    /// - 5: set clock polarity on current peripheral
    ///   - 0 is idle low
    ///   - non-zero is idle high
    /// - 6: get clock polarity on current peripheral
    ///   - 0 is idle low
    ///   - non-zero is idle high
    /// - x: lock spi
    ///   - if you perform an operation without the lock,
    ///     it implicitly acquires the lock before the
    ///     operation and releases it after
    ///   - while an app holds the lock no other app can issue
    ///     operations on SPI (they are buffered)
    ///   - not implemented or currently supported
    /// - x+1: unlock spi
    ///   - does nothing if lock not held
    ///   - not implemented or currently supported
    fn command(&self, cmd_num: usize, arg1: usize, _: usize, _: AppId) -> ReturnCode {
        match cmd_num {
            0 /* check if present */ => ReturnCode::SUCCESS,
            1 /* read_write_bytes */ => {
                if self.busy.get() {
                    return ReturnCode::EBUSY;
                }
                self.app.map_or(ReturnCode::FAIL /* XXX app is null? */, |app| {
                    let mut mlen = 0;
                    app.app_write.as_mut().map(|w| {
                        mlen = w.len();
                    });
                    app.app_read.as_mut().map(|r| {
                        mlen = cmp::min(mlen, r.len());
                    });
                    if mlen >= arg1 {
                        app.len = arg1;
                        app.index = 0;
                        self.busy.set(true);
                        self.do_next_read_write(app);
                        ReturnCode::SUCCESS
                    } else {
                        ReturnCode::EINVAL /* write buffer too small */
                    }
                })
            }
            2 /* get chip select */ => {
                // When in slave mode, the only possible chip select is 0
                ReturnCode::SuccessWithValue { value: 0 }
            }
            3 /* set phase */ => {
                match arg1 {
                    0 => self.spi_slave.set_phase(ClockPhase::SampleLeading),
                    _ => self.spi_slave.set_phase(ClockPhase::SampleTrailing),
                };
                ReturnCode::SUCCESS
            }
            4 /* get phase */ => {
                ReturnCode::SuccessWithValue { value: self.spi_slave.get_phase() as usize }
            }
            5 /* set polarity */ => {
                match arg1 {
                    0 => self.spi_slave.set_polarity(ClockPolarity::IdleLow),
                    _ => self.spi_slave.set_polarity(ClockPolarity::IdleHigh),
                };
                ReturnCode::SUCCESS
            }
            6 /* get polarity */ => {
                ReturnCode::SuccessWithValue { value: self.spi_slave.get_polarity() as usize }
            }
            _ => ReturnCode::ENOSUPPORT
        }
    }
}

impl<'a, S: SpiSlaveDevice> SpiSlaveClient for SpiSlave<'a, S> {
    fn read_write_done(
        &self,
        writebuf: Option<&'static mut [u8]>,
        readbuf: Option<&'static mut [u8]>,
        length: usize,
    ) {
        self.app.map(move |app| {
            if app.app_read.is_some() {
                let src = readbuf.as_ref().unwrap();
                let dest = app.app_read.as_mut().unwrap();
                let start = app.index - length;
                let end = start + length;

                let d = &mut dest.as_mut()[start..end];
                for (i, c) in src[0..length].iter().enumerate() {
                    d[i] = *c;
                }
            }

            self.kernel_read.put(readbuf);
            self.kernel_write.put(writebuf);

            if app.index == app.len {
                self.busy.set(false);
                app.len = 0;
                app.index = 0;
                app.callback.take().map(|mut cb| {
                    cb.schedule(app.len, 0, 0);
                });
            } else {
                self.do_next_read_write(app);
            }
        });
    }

    // Simple callback for when chip has been selected
    fn chip_selected(&self) {
        self.app.map(move |app| {
            app.selected_callback.take().map(|mut cb| {
                cb.schedule(app.len, 0, 0);
            });
        });
    }
}