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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Implements a log storage abstraction for storing persistent data in flash.
//!
//! Data entries can be appended to the end of a log and read back in-order. Logs may be linear
//! (denying writes when full) or circular (overwriting the oldest entries with the newest entries
//! when the underlying flash volume is full). The storage volumes that logs operate upon are
//! statically allocated at compile time and cannot be dynamically created at runtime.
//!
//! Entries can be identified and seeked-to with their unique Entry IDs. Entry IDs maintain the
//! ordering of the underlying entries, and an entry with a larger entry ID is newer and comes
//! after an entry with a smaller ID. IDs can also be used to determine the physical position of
//! entries within the log's underlying storage volume - taking the ID modulo the size of the
//! underlying storage volume yields the position of the entry's header relative to the start of
//! the volume. Entries should not be created manually by clients, only retrieved through the
//! `log_start()`, `log_end()`, and `next_read_entry_id()` functions.
//!
//! Entry IDs are not explicitly stored in the log. Instead, each page of the log contains a header
//! containing the page's offset relative to the start of the log (i.e. if the page size is 512
//! bytes, then page #0 will have an offset of 0, page #1 an offset of 512, etc.). The offsets
//! continue to increase even after a circular log wraps around (so if 5 512-byte pages of data are
//! written to a 4 page log, then page #0 will now have an offset of 2048). Thus, the ID of an
//! entry can be calculated by taking the offset of the page within the log and adding the offset
//! of the entry within the page to find the position of the entry within the log (which is the
//! ID). Entries also have a header of their own, which contains the length of the entry.
//!
//! Logs support the following basic operations:
//!     * Read:     Read back previously written entries in whole. Entries are read in their
//!                 entirety (no partial reads) from oldest to newest.
//!     * Seek:     Seek to different entries to begin reading from a different entry (can only
//!                 seek to the start of entries).
//!     * Append:   Append new data entries onto the end of a log. Can fail if the new entry is too
//!                 large to fit within the log.
//!     * Sync:     Sync a log to flash to ensure that all changes are persistent.
//!     * Erase:    Erase a log in its entirety, clearing the underlying flash volume.
//! See the documentation for each individual function for more detail on how they operate.
//!
//! Note that while logs persist across reboots, they will be erased upon flashing a new kernel.
//!
//! Usage
//! -----
//!
//! ```rust,ignore
//!     storage_volume!(VOLUME, 2);
//!     static mut PAGEBUFFER: sam4l::flashcalw::Sam4lPage = sam4l::flashcalw::Sam4lPage::new();
//!
//!     let log = static_init!(
//!         capsules::log::Log,
//!         capsules::log::Log::new(
//!             &VOLUME,
//!             &mut sam4l::flashcalw::FLASH_CONTROLLER,
//!             &mut PAGEBUFFER,
//!             true
//!         )
//!     );
//!     log.register();
//!     kernel::hil::flash::HasClient::set_client(&sam4l::flashcalw::FLASH_CONTROLLER, log);
//!
//!     log.set_read_client(log_storage_read_client);
//!     log.set_append_client(log_storage_append_client);
//! ```

use core::cell::Cell;
use core::mem::size_of;
use core::unreachable;

use kernel::deferred_call::{DeferredCall, DeferredCallClient};
use kernel::hil::flash::{self, Flash};
use kernel::hil::log::{LogRead, LogReadClient, LogWrite, LogWriteClient};
use kernel::utilities::cells::{OptionalCell, TakeCell};
use kernel::ErrorCode;

/// Globally declare entry ID type.
type EntryID = usize;

/// Maximum page header size.
pub const PAGE_HEADER_SIZE: usize = size_of::<EntryID>();
/// Maximum entry header size.
pub const ENTRY_HEADER_SIZE: usize = size_of::<usize>();

/// Byte used to pad the end of a page.
const PAD_BYTE: u8 = 0xFF;

/// Log state keeps track of any in-progress asynchronous operations.
#[derive(Clone, Copy, PartialEq)]
enum State {
    Idle,
    Read,
    Seek,
    Append,
    Sync,
    Erase,
}

pub struct Log<'a, F: Flash + 'static> {
    /// Underlying storage volume.
    volume: &'static [u8],
    /// Capacity of log in bytes.
    capacity: usize,
    /// Flash interface.
    driver: &'a F,
    /// Buffer for a flash page.
    pagebuffer: TakeCell<'static, F::Page>,
    /// Size of a flash page.
    page_size: usize,
    /// Whether or not the log is circular.
    circular: bool,
    /// Read client using Log.
    read_client: OptionalCell<&'a dyn LogReadClient>,
    /// Append client using Log.
    append_client: OptionalCell<&'a dyn LogWriteClient>,

    /// Current operation being executed, if asynchronous.
    state: Cell<State>,
    /// Entry ID of oldest entry remaining in log.
    oldest_entry_id: Cell<EntryID>,
    /// Entry ID of next entry to read.
    read_entry_id: Cell<EntryID>,
    /// Entry ID of next entry to append.
    append_entry_id: Cell<EntryID>,

    /// Deferred call for deferring client callbacks.
    deferred_call: DeferredCall,

    // Note: for saving state across stack ripping.
    /// Client-provided buffer to write from.
    buffer: TakeCell<'static, [u8]>,
    /// Length of data within buffer.
    length: Cell<usize>,
    /// Whether or not records were lost in the previous append.
    records_lost: Cell<bool>,
    /// Error returned by previously executed operation (or Ok(())).
    error: Cell<Result<(), ErrorCode>>,
}

impl<'a, F: Flash + 'static> Log<'a, F> {
    pub fn new(
        volume: &'static [u8],
        driver: &'a F,
        pagebuffer: &'static mut F::Page,
        circular: bool,
    ) -> Self {
        let page_size = pagebuffer.as_mut().len();
        let capacity = volume.len() - PAGE_HEADER_SIZE * (volume.len() / page_size);

        let log: Log<'a, F> = Self {
            volume,
            capacity,
            driver,
            pagebuffer: TakeCell::new(pagebuffer),
            page_size,
            circular,
            read_client: OptionalCell::empty(),
            append_client: OptionalCell::empty(),
            state: Cell::new(State::Idle),
            oldest_entry_id: Cell::new(PAGE_HEADER_SIZE),
            read_entry_id: Cell::new(PAGE_HEADER_SIZE),
            append_entry_id: Cell::new(PAGE_HEADER_SIZE),
            deferred_call: DeferredCall::new(),
            buffer: TakeCell::empty(),
            length: Cell::new(0),
            records_lost: Cell::new(false),
            error: Cell::new(Err(ErrorCode::NODEVICE)),
        };

        log.reconstruct();
        log
    }

    /// Returns the page number of the page containing the entry with the given ID.
    fn page_number(&self, entry_id: EntryID) -> usize {
        (self.volume.as_ptr() as usize + entry_id % self.volume.len()) / self.page_size
    }

    /// Gets the buffer containing the byte at the given position in the log.
    fn get_buffer<'b>(&self, pos: usize, pagebuffer: &'b mut F::Page) -> &'b [u8] {
        // Subtract 1 from append entry ID to get position of last bit written. This is needed
        // because the pagebuffer always contains the last written bit, but not necessarily the
        // position represented by the append entry ID (i.e. the pagebuffer isn't flushed yet when
        // `append_entry_id % page_size == 0`).
        if pos / self.page_size == (self.append_entry_id.get() - 1) / self.page_size {
            pagebuffer.as_mut()
        } else {
            self.volume
        }
    }

    /// Gets the byte at the given position in the log.
    fn get_byte(&self, pos: usize, pagebuffer: &mut F::Page) -> u8 {
        let buffer = self.get_buffer(pos, pagebuffer);
        buffer[pos % buffer.len()]
    }

    /// Gets a `num_bytes` long slice of bytes starting from a position within the log.
    fn get_bytes<'b>(&self, pos: usize, num_bytes: usize, pagebuffer: &'b mut F::Page) -> &'b [u8] {
        let buffer = self.get_buffer(pos, pagebuffer);
        let offset = pos % buffer.len();
        &buffer[offset..offset + num_bytes]
    }

    /// Resets a log back to an empty log. Returns whether or not the log was reset successfully.
    fn reset(&self) -> bool {
        self.oldest_entry_id.set(PAGE_HEADER_SIZE);
        self.read_entry_id.set(PAGE_HEADER_SIZE);
        self.append_entry_id.set(PAGE_HEADER_SIZE);
        self.pagebuffer.take().map_or(false, move |pagebuffer| {
            for e in pagebuffer.as_mut().iter_mut() {
                *e = 0;
            }
            self.pagebuffer.replace(pagebuffer);
            true
        })
    }

    /// Reconstructs a log from flash.
    fn reconstruct(&self) {
        // Read page headers, get IDs of oldest and newest pages.
        let mut oldest_page_id: EntryID = usize::MAX;
        let mut newest_page_id: EntryID = 0;
        for header_pos in (0..self.volume.len()).step_by(self.page_size) {
            let page_id = {
                const ID_SIZE: usize = size_of::<EntryID>();
                let id_bytes = &self.volume[header_pos..header_pos + ID_SIZE];
                let id_bytes = <[u8; ID_SIZE]>::try_from(id_bytes).unwrap();
                usize::from_ne_bytes(id_bytes)
            };

            // Validate page ID read from header.
            if page_id % self.volume.len() == header_pos {
                if page_id < oldest_page_id {
                    oldest_page_id = page_id;
                }
                if page_id > newest_page_id {
                    newest_page_id = page_id;
                }
            }
        }

        // Reconstruct log if at least one valid page was found (meaning oldest page ID was set to
        // something not usize::MAX).
        if oldest_page_id != usize::MAX {
            // Walk entries in last (newest) page to calculate last page length.
            let mut last_page_len = PAGE_HEADER_SIZE;
            loop {
                // Check if next byte is start of valid entry.
                let volume_offset = newest_page_id % self.volume.len() + last_page_len;
                if self.volume[volume_offset] == 0 || self.volume[volume_offset] == PAD_BYTE {
                    break;
                }

                // Get next entry length.
                let entry_length = {
                    const LENGTH_SIZE: usize = size_of::<usize>();
                    let length_bytes = &self.volume[volume_offset..volume_offset + LENGTH_SIZE];
                    let length_bytes = <[u8; LENGTH_SIZE]>::try_from(length_bytes).unwrap();
                    usize::from_ne_bytes(length_bytes)
                } + ENTRY_HEADER_SIZE;

                // Add to page length if length is valid (fits within remainder of page.
                if last_page_len + entry_length <= self.page_size {
                    last_page_len += entry_length;
                    if last_page_len == self.page_size {
                        break;
                    }
                } else {
                    break;
                }
            }

            // Set tracked entry IDs.
            self.oldest_entry_id.set(oldest_page_id + PAGE_HEADER_SIZE);
            self.read_entry_id.set(oldest_page_id + PAGE_HEADER_SIZE);
            self.append_entry_id.set(newest_page_id + last_page_len);

            // Populate page buffer.
            self.pagebuffer
                .take()
                .map(move |pagebuffer| {
                    // Determine if pagebuffer should be reset or copied from flash.
                    let mut copy_pagebuffer = last_page_len % self.page_size != 0;
                    if !copy_pagebuffer {
                        // Last page full, reset pagebuffer for next page.
                        copy_pagebuffer = !self.reset_pagebuffer(pagebuffer);
                    }
                    if copy_pagebuffer {
                        // Copy last page into pagebuffer.
                        for i in 0..self.page_size {
                            pagebuffer.as_mut()[i] =
                                self.volume[newest_page_id % self.volume.len() + i];
                        }
                    }
                    self.pagebuffer.replace(pagebuffer);
                })
                .unwrap();
        } else {
            // No valid pages found, create fresh log.
            self.reset();
        }
    }

    /// Returns the ID of the next entry to read or an error if no entry could be retrieved.
    /// Result<(), ErrorCode>s used:
    ///     * FAIL: reached end of log, nothing to read.
    ///     * RESERVE: client or internal pagebuffer missing.
    fn get_next_entry(&self) -> Result<EntryID, Result<(), ErrorCode>> {
        self.pagebuffer
            .take()
            .map_or(Err(Err(ErrorCode::RESERVE)), move |pagebuffer| {
                let mut entry_id = self.read_entry_id.get();

                // Skip page header if at start of page or skip padded bytes if at end of page.
                if entry_id % self.page_size == 0 {
                    entry_id += PAGE_HEADER_SIZE;
                } else if self.get_byte(entry_id, pagebuffer) == PAD_BYTE {
                    entry_id += self.page_size - entry_id % self.page_size + PAGE_HEADER_SIZE;
                }

                // Check if end of log was reached and return.
                self.pagebuffer.replace(pagebuffer);
                if entry_id >= self.append_entry_id.get() {
                    Err(Err(ErrorCode::FAIL))
                } else {
                    Ok(entry_id)
                }
            })
    }

    /// Reads and returns the contents of an entry header with the given ID. Fails if the header
    /// data is invalid.
    /// Result<(), ErrorCode>s used:
    ///     * FAIL: entry header invalid.
    ///     * RESERVE: client or internal pagebuffer missing.
    fn read_entry_header(&self, entry_id: EntryID) -> Result<usize, Result<(), ErrorCode>> {
        self.pagebuffer
            .take()
            .map_or(Err(Err(ErrorCode::RESERVE)), move |pagebuffer| {
                // Get length.
                const LENGTH_SIZE: usize = size_of::<usize>();
                let length_bytes = self.get_bytes(entry_id, LENGTH_SIZE, pagebuffer);
                let length_bytes = <[u8; LENGTH_SIZE]>::try_from(length_bytes).unwrap();
                let length = usize::from_ne_bytes(length_bytes);

                // Return length of next entry.
                self.pagebuffer.replace(pagebuffer);
                if length == 0 || length > self.page_size - PAGE_HEADER_SIZE - ENTRY_HEADER_SIZE {
                    Err(Err(ErrorCode::FAIL))
                } else {
                    Ok(length)
                }
            })
    }

    /// Reads the next entry into a buffer. Returns the number of bytes read on success, or an
    /// error otherwise.
    /// Result<(), ErrorCode>s used:
    ///     * FAIL: reached end of log, nothing to read.
    ///     * RESERVE: internal pagebuffer missing, log is presumably broken.
    ///     * SIZE: buffer not large enough to contain entry being read.
    fn read_entry(&self, buffer: &mut [u8], length: usize) -> Result<usize, Result<(), ErrorCode>> {
        // Get next entry to read. Immediately returns FAIL in event of failure.
        let entry_id = self.get_next_entry()?;
        let entry_length = self.read_entry_header(entry_id)?;

        // Read entry into buffer.
        self.pagebuffer
            .take()
            .map_or(Err(Err(ErrorCode::RESERVE)), move |pagebuffer| {
                // Ensure buffer is large enough to hold log entry.
                if entry_length > length {
                    self.pagebuffer.replace(pagebuffer);
                    return Err(Err(ErrorCode::SIZE));
                }
                let entry_id = entry_id + ENTRY_HEADER_SIZE;

                // Copy data into client buffer.
                let data = self.get_bytes(entry_id, entry_length, pagebuffer);
                buffer[..entry_length].copy_from_slice(&data[..entry_length]);

                // Update read entry ID and return number of bytes read.
                self.read_entry_id.set(entry_id + entry_length);
                self.pagebuffer.replace(pagebuffer);
                Ok(entry_length)
            })
    }

    /// Writes an entry header at the given position within a page. Must write at most
    /// ENTRY_HEADER_SIZE bytes.
    fn write_entry_header(&self, length: usize, pos: usize, pagebuffer: &mut F::Page) {
        for (offset, byte) in length.to_ne_bytes().iter().enumerate() {
            pagebuffer.as_mut()[pos + offset] = *byte;
        }
    }

    /// Appends data from a buffer onto the end of the log. Requires that there is enough space
    /// remaining in the pagebuffer for the entry (including metadata).
    fn append_entry(
        &self,
        buffer: &'static mut [u8],
        length: usize,
        pagebuffer: &'static mut F::Page,
    ) {
        // Offset within page to append to.
        let append_entry_id = self.append_entry_id.get();
        let mut page_offset = append_entry_id % self.page_size;

        // Write entry header to pagebuffer.
        self.write_entry_header(length, page_offset, pagebuffer);
        page_offset += ENTRY_HEADER_SIZE;

        // Copy data to pagebuffer.
        pagebuffer.as_mut()[page_offset..(length + page_offset)].copy_from_slice(&buffer[..length]);

        // Increment append offset by number of bytes appended.
        let append_entry_id = append_entry_id + length + ENTRY_HEADER_SIZE;
        self.append_entry_id.set(append_entry_id);

        // Replace pagebuffer and callback client.
        self.pagebuffer.replace(pagebuffer);
        self.buffer.replace(buffer);
        self.records_lost
            .set(self.oldest_entry_id.get() != PAGE_HEADER_SIZE);
        self.error.set(Ok(()));
        self.client_callback();
    }

    /// Flushes the pagebuffer to flash. Log state must be non-idle before calling, else data races
    /// may occur due to asynchronous page write.
    /// Result<(), ErrorCode>s used:
    ///     * Ok(()): flush started successfully.
    ///     * FAIL: flash driver not configured.
    ///     * BUSY: flash driver busy.
    fn flush_pagebuffer(&self, pagebuffer: &'static mut F::Page) -> Result<(), ErrorCode> {
        // Pad end of page.
        let mut pad_ptr = self.append_entry_id.get();
        while pad_ptr % self.page_size != 0 {
            pagebuffer.as_mut()[pad_ptr % self.page_size] = PAD_BYTE;
            pad_ptr += 1;
        }

        // Get flash page to write to and log page being overwritten. Subtract page_size since
        // padding pointer points to start of the page following the one we want to flush after the
        // padding operation.
        let page_number = self.page_number(pad_ptr - self.page_size);
        let overwritten_page = (pad_ptr - self.volume.len() - self.page_size) / self.page_size;

        // Advance read and oldest entry IDs, if within flash page being overwritten.
        let read_entry_id = self.read_entry_id.get();
        if read_entry_id / self.page_size == overwritten_page {
            // Move read entry ID to start of next page.
            self.read_entry_id.set(
                read_entry_id + self.page_size + PAGE_HEADER_SIZE - read_entry_id % self.page_size,
            );
        }

        let oldest_entry_id = self.oldest_entry_id.get();
        if oldest_entry_id / self.page_size == overwritten_page {
            self.oldest_entry_id.set(oldest_entry_id + self.page_size);
        }

        // Sync page to flash.
        match self.driver.write_page(page_number, pagebuffer) {
            Ok(()) => Ok(()),
            Err((ecode, pagebuffer)) => {
                self.pagebuffer.replace(pagebuffer);
                Err(ecode)
            }
        }
    }

    /// Resets the pagebuffer so that new data can be written. Note that this also increments the
    /// append entry ID to point to the start of writable data in this new page. Does not reset
    /// pagebuffer or modify append entry ID if the end of a non-circular log is reached. Returns
    /// whether or not the pagebuffer was reset.
    fn reset_pagebuffer(&self, pagebuffer: &mut F::Page) -> bool {
        // Make sure this is not the last page of a non-circular buffer.
        let mut append_entry_id = self.append_entry_id.get();
        if !self.circular && append_entry_id + self.page_size > self.volume.len() {
            return false;
        }

        // Increment append entry ID to point at start of next page.
        if append_entry_id % self.page_size != 0 {
            append_entry_id += self.page_size - append_entry_id % self.page_size;
        }

        // Write page header to pagebuffer.
        let id_bytes = append_entry_id.to_ne_bytes();
        pagebuffer.as_mut()[..id_bytes.len()].copy_from_slice(&id_bytes[..]);

        // Note: this is the only place where the append entry ID can cross page boundaries.
        self.append_entry_id.set(append_entry_id + PAGE_HEADER_SIZE);
        true
    }

    /// Erases a single page from storage.
    fn erase_page(&self) -> Result<(), ErrorCode> {
        // Uses oldest entry ID to keep track of which page to erase. Thus, the oldest pages will be
        // erased first and the log will remain in a valid state even if it fails to be erased
        // completely.
        self.driver
            .erase_page(self.page_number(self.oldest_entry_id.get()))
    }

    /// Defers a client callback until later.
    fn deferred_client_callback(&self) {
        self.deferred_call.set();
    }

    /// Resets the log state to idle and makes a client callback. The values returned by via the
    /// callback must be saved within the log's state before making a callback.
    fn client_callback(&self) {
        let state = self.state.get();
        match state {
            State::Read | State::Seek => {
                self.state.set(State::Idle);
                self.read_client
                    .map(move |read_client| match state {
                        State::Read => self
                            .buffer
                            .take()
                            .map(move |buffer| {
                                read_client.read_done(buffer, self.length.get(), self.error.get());
                            })
                            .unwrap(),
                        State::Seek => read_client.seek_done(self.error.get()),
                        _ => unreachable!(),
                    })
                    .unwrap();
            }
            State::Append | State::Sync | State::Erase => {
                self.state.set(State::Idle);
                self.append_client
                    .map(move |append_client| match state {
                        State::Append => self
                            .buffer
                            .take()
                            .map(move |buffer| {
                                append_client.append_done(
                                    buffer,
                                    self.length.get(),
                                    self.records_lost.get(),
                                    self.error.get(),
                                );
                            })
                            .unwrap(),
                        State::Sync => append_client.sync_done(self.error.get()),
                        State::Erase => append_client.erase_done(self.error.get()),
                        _ => unreachable!(),
                    })
                    .unwrap();
            }
            State::Idle => (),
        }
    }
}

impl<'a, F: Flash + 'static> LogRead<'a> for Log<'a, F> {
    type EntryID = EntryID;

    /// Set the client for read operation callbacks.
    fn set_read_client(&self, read_client: &'a dyn LogReadClient) {
        self.read_client.set(read_client);
    }

    /// Read an entire log entry into a buffer, if there are any remaining. Updates the read entry
    /// ID to point at the next entry when done.
    /// Returns:
    ///     * `Ok(())` on success.
    ///     * `Err((Result<(), ErrorCode>, Option<buffer>))` on failure. The
    ///       buffer will only be `None` if the error is due to a loss of the
    ///       buffer.
    /// `Result<(), ErrorCode>`s used:
    ///     * `FAIL`: reached end of log, nothing to read.
    ///     * `BUSY`: log busy with another operation, try again later.
    ///     * `INVAL`: provided client buffer is too small.
    ///     * `CANCEL`: invalid internal state, read entry ID was reset to start of log.
    ///     * `RESERVE`: client or internal pagebuffer missing.
    ///     * `SIZE`: buffer not large enough to contain entry being read.
    /// `Result<(), ErrorCode>`s used in read_done callback:
    ///     * `Ok(())`: read succeeded.
    fn read(
        &self,
        buffer: &'static mut [u8],
        length: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        // Check for failure cases.
        if self.state.get() != State::Idle {
            // Log busy, try reading again later.
            return Err((ErrorCode::BUSY, buffer));
        } else if buffer.len() < length {
            // Client buffer too small for provided length.
            return Err((ErrorCode::INVAL, buffer));
        } else if self.read_entry_id.get() > self.append_entry_id.get() {
            // Read entry ID beyond append entry ID, must be invalid.
            self.read_entry_id.set(self.oldest_entry_id.get());
            return Err((ErrorCode::CANCEL, buffer));
        } else if self.read_client.is_none() {
            // No client for callback.
            return Err((ErrorCode::RESERVE, buffer));
        }

        // Try reading next entry.
        match self.read_entry(buffer, length) {
            Ok(bytes_read) => {
                self.state.set(State::Read);
                self.buffer.replace(buffer);
                self.length.set(bytes_read);
                self.error.set(Ok(()));
                self.deferred_client_callback();
                Ok(())
            }
            Err(return_code) => Err((return_code.unwrap_err(), buffer)),
        }
    }

    /// Returns the ID of the oldest remaining entry in the log.
    fn log_start(&self) -> Self::EntryID {
        self.oldest_entry_id.get()
    }

    /// Returns the ID of the newest entry in the log.
    fn log_end(&self) -> Self::EntryID {
        self.append_entry_id.get()
    }

    /// Returns the ID of the next entry to be read.
    fn next_read_entry_id(&self) -> Self::EntryID {
        self.read_entry_id.get()
    }

    /// Seek to a new read entry ID. It is only legal to seek to entry IDs retrieved through the
    /// `log_start()`, `log_end()`, and `next_read_entry_id()` functions.
    /// Result<(), ErrorCode>s used:
    ///     * Ok(()): seek succeeded.
    ///     * INVAL: entry ID not valid seek position within current log.
    ///     * RESERVE: no log client set.
    fn seek(&self, entry_id: Self::EntryID) -> Result<(), ErrorCode> {
        if entry_id <= self.append_entry_id.get() && entry_id >= self.oldest_entry_id.get() {
            self.read_entry_id.set(entry_id);

            self.state.set(State::Seek);
            self.error.set(Ok(()));
            self.deferred_client_callback();
            Ok(())
        } else {
            Err(ErrorCode::INVAL)
        }
    }

    /// Get approximate log capacity in bytes.
    fn get_size(&self) -> usize {
        self.capacity
    }
}

impl<'a, F: Flash + 'static> LogWrite<'a> for Log<'a, F> {
    /// Set the client for append operation callbacks.
    fn set_append_client(&self, append_client: &'a dyn LogWriteClient) {
        self.append_client.set(append_client);
    }

    /// Appends an entry onto the end of the log. Entry must fit within a page (including log
    /// metadata).
    /// Returns:
    ///     * `Ok(())` on success.
    ///     * `Err((Result<(), ErrorCode>, Option<buffer>))1 on failure. The buffer will only be `None` if the
    ///       error is due to a loss of the buffer.
    /// `Result<(), ErrorCode>`s used:
    ///     * `FAIL`: end of non-circular log reached, cannot append any more entries.
    ///     * `BUSY`: log busy with another operation, try again later.
    ///     * `INVAL`: provided client buffer is too small.
    ///     * `RESERVE`: client or internal pagebuffer missing.
    ///     * `SIZE`: entry too large to append to log.
    /// `Result<(), ErrorCode>`s used in append_done callback:
    ///     * `Ok(())`: append succeeded.
    ///     * `FAIL`: write failed due to flash error.
    ///     * `CANCEL`: write failed due to reaching the end of a non-circular log.
    fn append(
        &self,
        buffer: &'static mut [u8],
        length: usize,
    ) -> Result<(), (ErrorCode, &'static mut [u8])> {
        let entry_size = length + ENTRY_HEADER_SIZE;

        // Check for failure cases.
        if self.state.get() != State::Idle {
            // Log busy, try appending again later.
            return Err((ErrorCode::BUSY, buffer));
        } else if length == 0 || buffer.len() < length {
            // Invalid length provided.
            return Err((ErrorCode::INVAL, buffer));
        } else if entry_size + PAGE_HEADER_SIZE > self.page_size {
            // Entry too big, won't fit within a single page.
            return Err((ErrorCode::SIZE, buffer));
        } else if !self.circular && self.append_entry_id.get() + entry_size > self.volume.len() {
            // End of non-circular log has been reached.
            return Err((ErrorCode::FAIL, buffer));
        }

        // Perform append.
        match self.pagebuffer.take() {
            Some(pagebuffer) => {
                self.state.set(State::Append);
                self.length.set(length);

                // Check if previous page needs to be flushed and new entry will fit within space
                // remaining in current page.
                let append_entry_id = self.append_entry_id.get();
                let flush_prev_page = append_entry_id % self.page_size == 0;
                let space_remaining = self.page_size - append_entry_id % self.page_size;
                if !flush_prev_page && entry_size <= space_remaining {
                    // Entry fits, append it.
                    self.append_entry(buffer, length, pagebuffer);
                    Ok(())
                } else {
                    // Need to sync pagebuffer first, then append to new page.
                    self.buffer.replace(buffer);
                    let return_code = self.flush_pagebuffer(pagebuffer);
                    if return_code == Ok(()) {
                        Ok(())
                    } else {
                        self.state.set(State::Idle);
                        self.buffer.take().map_or_else(
                            || panic!("No buffer to return"),
                            move |buffer| Err((return_code.unwrap_err(), buffer)),
                        )
                    }
                }
            }
            None => Err((ErrorCode::RESERVE, buffer)),
        }
    }

    /// Sync log to storage.
    /// Result<(), ErrorCode>s used:
    ///     * Ok(()): flush started successfully.
    ///     * FAIL: flash driver not configured.
    ///     * BUSY: log or flash driver busy, try again later.
    ///     * RESERVE: no log client set.
    /// Result<(), ErrorCode>s used in sync_done callback:
    ///     * Ok(()): append succeeded.
    ///     * FAIL: write failed due to flash error.
    fn sync(&self) -> Result<(), ErrorCode> {
        if self.append_entry_id.get() % self.page_size == PAGE_HEADER_SIZE {
            // Pagebuffer empty, don't need to flush.
            return Ok(());
        } else if self.state.get() != State::Idle {
            // Log busy, try appending again later.
            return Err(ErrorCode::BUSY);
        }

        self.pagebuffer
            .take()
            .map_or(Err(ErrorCode::RESERVE), move |pagebuffer| {
                self.state.set(State::Sync);
                let return_code = self.flush_pagebuffer(pagebuffer);
                if return_code != Ok(()) {
                    self.state.set(State::Idle);
                }
                return_code
            })
    }

    /// Erase the entire log.
    /// Result<(), ErrorCode>s used:
    ///     * Ok(()): flush started successfully.
    ///     * BUSY: log busy, try again later.
    /// Result<(), ErrorCode>s used in erase_done callback:
    ///     * Ok(()): erase succeeded.
    ///     * BUSY: erase interrupted by busy flash driver. Call erase again to resume.
    fn erase(&self) -> Result<(), ErrorCode> {
        if self.state.get() != State::Idle {
            // Log busy, try appending again later.
            return Err(ErrorCode::BUSY);
        }

        self.state.set(State::Erase);
        self.erase_page()
    }
}

impl<'a, F: Flash + 'static> flash::Client<F> for Log<'a, F> {
    fn read_complete(&self, _read_buffer: &'static mut F::Page, _result: Result<(), flash::Error>) {
        // Reads are made directly from the storage volume, not through the flash interface.
        unreachable!();
    }

    /// If in the middle of a write operation, reset pagebuffer and finish write. If syncing, make
    /// successful client callback.
    fn write_complete(&self, pagebuffer: &'static mut F::Page, result: Result<(), flash::Error>) {
        match result.is_ok() {
            true => {
                match self.state.get() {
                    State::Append => {
                        // Reset pagebuffer and finish writing on the new page.
                        if self.reset_pagebuffer(pagebuffer) {
                            self.buffer
                                .take()
                                .map(move |buffer| {
                                    self.append_entry(buffer, self.length.get(), pagebuffer);
                                })
                                .unwrap();
                        } else {
                            self.pagebuffer.replace(pagebuffer);
                            self.length.set(0);
                            self.records_lost.set(false);
                            self.error.set(Err(ErrorCode::CANCEL));
                            self.client_callback();
                        }
                    }
                    State::Sync => {
                        // Reset pagebuffer if synced page was full.
                        if self.append_entry_id.get() % self.page_size == 0 {
                            self.reset_pagebuffer(pagebuffer);
                        }

                        self.pagebuffer.replace(pagebuffer);
                        self.error.set(Ok(()));
                        self.client_callback();
                    }
                    _ => unreachable!(),
                }
            }
            false => {
                match result.unwrap_err() {
                    flash::Error::FlashError | flash::Error::FlashMemoryProtectionError => {
                        // Make client callback with FAIL return code.
                        self.pagebuffer.replace(pagebuffer);
                        match self.state.get() {
                            State::Append => {
                                self.length.set(0);
                                self.records_lost.set(false);
                                self.error.set(Err(ErrorCode::FAIL));
                                self.client_callback();
                            }
                            State::Sync => {
                                self.error.set(Err(ErrorCode::FAIL));
                                self.client_callback();
                            }
                            _ => unreachable!(),
                        }
                    }
                }
            }
        }
    }

    /// Erase next page if log erase complete, else make client callback. Fails with BUSY if flash
    /// is busy and erase cannot be completed.
    fn erase_complete(&self, result: Result<(), flash::Error>) {
        match result.is_ok() {
            true => {
                let oldest_entry_id = self.oldest_entry_id.get();
                if oldest_entry_id >= self.append_entry_id.get() - self.page_size {
                    // Erased all pages. Reset state and callback client.
                    if self.reset() {
                        self.error.set(Ok(()));
                    } else {
                        self.error.set(Err(ErrorCode::RESERVE));
                    }
                    self.client_callback();
                } else {
                    // Not done, erase next page.
                    self.oldest_entry_id.set(oldest_entry_id + self.page_size);
                    let status = self.erase_page();

                    // Abort and alert client if flash driver is busy.
                    if status == Err(ErrorCode::BUSY) {
                        self.read_entry_id
                            .set(core::cmp::max(self.read_entry_id.get(), oldest_entry_id));
                        self.error.set(Err(ErrorCode::BUSY));
                        self.client_callback();
                    }
                }
            }
            false => match result.unwrap_err() {
                flash::Error::FlashError | flash::Error::FlashMemoryProtectionError => {
                    self.error.set(Err(ErrorCode::FAIL));
                    self.client_callback();
                }
            },
        }
    }
}

impl<'a, F: Flash + 'static> DeferredCallClient for Log<'a, F> {
    fn handle_deferred_call(&self) {
        self.client_callback();
    }

    fn register(&'static self) {
        self.deferred_call.register(self);
    }
}