aboutsummaryrefslogtreecommitdiff
path: root/ks_flash.c
blob: 37c2563ff16597a8aeb29ecd8cbc29f7596a73c6 (plain) (blame)
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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
/*
 * ks_flash.c
 * ----------
 * Keystore implementation in flash memory.
 *
 * Authors: Rob Austein, Fredrik Thulin
 * Copyright (c) 2015-2016, NORDUnet A/S All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in the
 *   documentation and/or other materials provided with the distribution.
 *
 * - Neither the name of the NORDUnet nor the names of its contributors may
 *   be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stddef.h>
#include <string.h>
#include <assert.h>

#include "hal.h"
#include "hal_internal.h"

#include "last_gasp_pin_internal.h"

#define HAL_OK CMIS_HAL_OK
#include "stm-keystore.h"
#undef HAL_OK

/*
 * Revised flash keystore database.  Work in progress.
 *
 * General consideration:
 *
 * - bits can only be cleared, not set, unless one wants to erase the
 *   (sub)sector.  This has some odd knock on effects in terms of
 *   things like values of enumerated constants used here.
 *
 * - At the moment, all of the the low-level flash code deals with
 *   sectors, not sub-sectors, so for the moment we only use the first
 *   sub-sector of each sector.  Fixing this should not involve any
 *   major changes to the code, just redefinition of some constants
 *   here once we figure out what effect this will have on the rest of
 *   the code that shares the same low-level flash code.  In either
 *   case we're dealing with "blocks", where a block is a sector now
 *   and will be a sub-sector later.
 *
 * - This code assumes we're using ks_index.c, including its notion
 *   of a free list and its attempt at light-weight wear leveling.
 *
 * - This version takes a simplistic approach to updating existing
 *   blocks: write the modified contents to a new block regardless of
 *   whether they could have been made in-place.  The only in-place
 *   modifications we make are things like zeroing a block to mark it
 *   as having been used recently, so that it will go near the end of
 *   the free list.  We could allow many kinds of updates in place by
 *   making the crc field in the block header an array with some kind
 *   of counter (probably encoded as a mask given the constraints),
 *   but the code would be more complicated and it's not immediately
 *   obvious that it's worth it.  Maybe add that as a wear reduction
 *   feature later, but let's get the simpler version working first.
 *
 * Current theory for update logic:
 *
 * 1) Update-in-place of old block to deprecate;
 * 2) Write new block, including updating index;
 * 3) Update-in-place of old block to zero.
 */

/*
 * Known block states.
 *
 * Might want an additional state 0xDEADDEAD to mark blocks which
 * are known to be unusable, but the current hardware is NOR flash
 * so that may not be as important as it would be with NAND flash.
 *
 * C does not guarantee any particular representation for enums, so
 * including an enum directly in the block header isn't safe.
 */

typedef enum {
  FLASH_ERASED  = 0xFFFFFFFF, /* Pristine erased block (candidate for reuse) */
  FLASH_ZEROED  = 0x00000000, /* Zeroed block (recently used) */
  FLASH_KEYBLK  = 0x55555555, /* Block contains key material */
  FLASH_KEYOLD  = 0x41411414, /* Deprecated key block */
  FLASH_PINBLK  = 0xAAAAAAAA, /* Block contains PINs */
  FLASH_PINOLD  = 0x82822828, /* Deprecated PIN block */
  FLASH_UNKNOWN = 0x12345678, /* Internal code for "I have no clue what this is" */
} flash_block_type_t;

/*
 * Common header for all flash block types.  The crc fields should
 * remain at the end of the header to simplify the CRC calculation.
 */

typedef struct {
  uint32_t              block_type;
  hal_crc32_t           crc1, crc2;
} flash_block_header_t;

/*
 * We probably want some kind of TLV format for optional attributes
 * in key objects, and might want to put the DER key itself there to
 * save space.
 */

typedef struct {
  flash_block_header_t  header;
  hal_uuid_t            name;
  hal_key_type_t        type;
  hal_curve_name_t      curve;
  hal_key_flags_t       flags;
  size_t                der_len;
  uint8_t               der[HAL_KS_WRAPPED_KEYSIZE];
} flash_key_block_t;

/*
 * PIN block.  Also includes space for backing up the KEK when
 * HAL_MKM_FLASH_BACKUP_KLUDGE is enabled.
 */

typedef struct {
  flash_block_header_t  header;
  hal_ks_pin_t          wheel_pin;
  hal_ks_pin_t          so_pin;
  hal_ks_pin_t          user_pin;
#if HAL_MKM_FLASH_BACKUP_KLUDGE
  uint32_t              kek_set;
  uint8_t               kek[KEK_LENGTH];
#endif
} flash_pin_block_t;

#define FLASH_KEK_SET   0x33333333

/*
 * One flash block.
 */

typedef union {
  uint8_t               bytes[KEYSTORE_SUBSECTOR_SIZE];
  flash_block_header_t  header;
  flash_key_block_t     key;
  flash_pin_block_t     pin;
} flash_block_t;

/*
 * In-memory index, cache, etc.
 *
 * Some or all of this probably ought to be allocated out of external
 * SDRAM, but try it as a plain static variable initially.
 *
 * NUM_FLASH_BLOCKS should be KEYSTORE_NUM_SUBSECTORS, but all the
 * current flash code uses sectors rather than subsectors, so use
 * KEYSTORE_NUM_SECTORS until we have subsector erase code.
 */

#ifndef KS_FLASH_CACHE_SIZE
#define KS_FLASH_CACHE_SIZE 4
#endif

#define NUM_FLASH_BLOCKS        KEYSTORE_NUM_SECTORS

typedef struct {
  hal_ks_t              ks;                  /* Must be first (C "subclassing") */
  hal_ks_index_t        ksi;
  hal_ks_pin_t          wheel_pin;
  hal_ks_pin_t          so_pin;
  hal_ks_pin_t          user_pin;
  uint32_t              cache_lru;
  struct {
    unsigned            blockno;
    uint32_t            lru;
    flash_block_t       block;
  }                     cache[KS_FLASH_CACHE_SIZE];
  uint16_t              _index[NUM_FLASH_BLOCKS];
  hal_uuid_t            _names[NUM_FLASH_BLOCKS];
} db_t;

/*
 * PIN block gets the all-zeros UUID, which will never be returned by
 * the UUID generation code (by definition -- it's not a version 4 UUID).
 */

const static hal_uuid_t pin_uuid = {{0}};

/*
 * The in-memory database almost certainly should be a pointer to
 * allocated SDRAM rather than compile-time data space.  Well,
 * the arrays should be, anyway, it might be reasonable to keep
 * the top level structure here.  Worry about that later.
 */

static db_t db;

/*
 * Type safe cast.
 */

static inline flash_block_type_t block_get_type(const flash_block_t * const block)
{
  assert(block != NULL);
  return (flash_block_type_t) block->header.block_type;
}

/*
 * Pick unused or least-recently-used slot in our in-memory cache.
 *
 * Updating lru values is caller's problem: if caller is using cache
 * slot as a temporary buffer and there's no point in caching the
 * result, leave the lru values alone and the right thing will happen.
 */

static inline flash_block_t *cache_pick_lru(void)
{
  uint32_t best_delta = 0;
  int      best_index = 0;

  for (int i = 0; i < sizeof(db.cache)/sizeof(*db.cache); i++) {

    if (db.cache[i].blockno == ~0)
      return &db.cache[i].block;

    const uint32_t delta = db.cache_lru - db.cache[i].lru;
    if (delta > best_delta) {
      best_delta = delta;
      best_index = i;
    }

  }

  db.cache[best_index].blockno = ~0;
  return &db.cache[best_index].block;
}

/*
 * Find a block in our in-memory cache; return block or NULL if not present.
 */

static inline flash_block_t *cache_find_block(const unsigned blockno)
{
  for (int i = 0; i < sizeof(db.cache)/sizeof(*db.cache); i++)
    if (db.cache[i].blockno == blockno)
      return &db.cache[i].block;
  return NULL;
}

/*
 * Mark a block in our in-memory cache as being in current use.
 */

static inline void cache_mark_used(const flash_block_t * const block, const unsigned blockno)
{
  for (int i = 0; i < sizeof(db.cache)/sizeof(*db.cache); i++) {
    if (&db.cache[i].block == block) {
      db.cache[i].blockno = blockno;
      db.cache[i].lru = ++db.cache_lru;
      return;
    }
  }
}

/*
 * Release a block from the in-memory cache.
 */

static inline void cache_release(const flash_block_t * const block)
{
  if (block != NULL)
    cache_mark_used(block, ~0);
}

/*
 * Generate CRC-32 for a block.
 *
 * This function needs to understand the structure of
 * flash_block_header_t, so that it can skip over the crc field.
 */

static hal_crc32_t calculate_block_crc(const flash_block_t * const block)
{
  assert(block != NULL);

  hal_crc32_t crc = hal_crc32_init();

  crc = hal_crc32_update(crc,
                         block->bytes,
                         offsetof(flash_block_header_t, crc1));

  crc = hal_crc32_update(crc,
                         block->bytes + sizeof(flash_block_header_t),
                         sizeof(block) - sizeof(flash_block_header_t));

  return hal_crc32_finalize(crc);
}

/*
 * Calculate block offset.  Once we have subsectors working this will
 * use subsector offsets, for the moment we have to use sector offsets.
 */

#if 0
#define BLOCK_OFFSET_SIZE       KEYSTORE_SUBSECTOR_SIZE
#else
#define BLOCK_OFFSET_SIZE       KEYSTORE_SECTOR_SIZE
#endif

static uint32_t block_offset(const unsigned blockno)
{
  return blockno * BLOCK_OFFSET_SIZE;
}

/*
 * Read a flash block.  In some cases we might be able to optimize by
 * reading just the first page, but NOR flash should be relatively
 * fast to read, and we need the whole block to check the CRC
 * anyway.
 */

static hal_error_t block_read(const unsigned blockno, flash_block_t *block)
{
  assert(block != NULL && blockno < NUM_FLASH_BLOCKS && sizeof(*block) == KEYSTORE_SUBSECTOR_SIZE);

  /* Sigh, magic numeric return codes */
  if (keystore_read_data(block_offset(blockno), block->bytes, sizeof(block)) != 1)
    return HAL_ERROR_KEYSTORE_ACCESS;

  switch (block_get_type(block)) {
  case FLASH_KEYBLK:
  case FLASH_PINBLK:
    if (calculate_block_crc(block) != block->header.crc1)
      return HAL_ERROR_KEYSTORE_BAD_CRC;
    break;
  case FLASH_KEYOLD:
  case FLASH_PINOLD:
    if (calculate_block_crc(block) != block->header.crc2)
      return HAL_ERROR_KEYSTORE_BAD_CRC;
    break;
  default:
    break;
  }

  return HAL_OK;
}

/*
 * Read a block using the cache.  Marking the block as used is left
 * for the caller, so we can avoid blowing out the cache when we
 * perform a ks_list() operation.
 */

static hal_error_t block_read_cached(const unsigned blockno, flash_block_t **block)
{
  if (block == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  if ((*block = cache_find_block(blockno)) != NULL)
    return HAL_OK;

  if ((*block = cache_pick_lru()) == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  return block_read(blockno, *block);
}

/*
 * Write a flash block, calculating CRC when appropriate.
 *
 * NB: This does NOT automatically erase the block prior to write,
 * because doing so would either mess up our wear leveling algorithm
 * (such as it is) or cause gratuitous erasures (increasing wear).
 */

static hal_error_t block_write(const unsigned blockno, flash_block_t *block)
{
  assert(block != NULL && blockno < NUM_FLASH_BLOCKS && sizeof(*block) == KEYSTORE_SUBSECTOR_SIZE);

  switch (block_get_type(block)) {
  case FLASH_KEYBLK:
  case FLASH_PINBLK:
    block->header.crc1 = calculate_block_crc(block);
    break;
  case FLASH_KEYOLD:
  case FLASH_PINOLD:
    block->header.crc2 = calculate_block_crc(block);
    break;
  default:
    break;
  }

  /* Sigh, magic numeric return codes */
  if (keystore_write_data(block_offset(blockno), block->bytes, sizeof(block)) != 1)
    return HAL_ERROR_KEYSTORE_ACCESS;

  return HAL_OK;
}

/*
 * Zero (not erase) a flash block.
 */

static hal_error_t block_zero(const unsigned blockno)
{
  flash_block_t *block = cache_pick_lru();

  if (block == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  memset(block, 0, sizeof(*block));

  /* Sigh, magic numeric return codes */
  if (keystore_write_data(block_offset(blockno), block->bytes, sizeof(*block)) != 1)
    return HAL_ERROR_KEYSTORE_ACCESS;

  return HAL_OK;
}

/*
 * Erase a flash block.
 *
 * At the moment this erases the whole sector, when we move to
 * subsector-based blocks that will need to change.
 */

static hal_error_t block_erase(const unsigned blockno)
{
  assert(blockno < NUM_FLASH_BLOCKS);

  /* Sigh, magic numeric return codes */
  if (keystore_erase_sectors(blockno, blockno) != 1)
    return HAL_ERROR_KEYSTORE_ACCESS;

  return HAL_OK;
}

/*
 * Erase a flash block if it hasn't already been erased.
 *
 * May not be necessary, trying to avoid unnecessary wear.
 */

static hal_error_t block_erase_maybe(const unsigned blockno)
{
  flash_block_t *block = cache_pick_lru();
  hal_error_t err;

  if (block == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  if ((err = block_read(blockno, block)) != HAL_OK)
    return err;

  for (int i = 0; i < sizeof(*block); i++)
    if (block->bytes[i] != 0xFF)
      return block_erase(blockno);

  return HAL_OK;
}

/*
 * Initialize keystore.  This includes some tricky bits that attempt
 * to preserve the free list ordering across reboots, to improve our
 * simplistic attempt at wear leveling.
 */

static hal_error_t ks_init(const hal_ks_driver_t * const driver)
{
  /*
   * Initialize the in-memory database.  In the long run this probably
   * needs to be using a block of SDRAM, which we would allocate here.
   */

  memset(&db, 0, sizeof(db));
  db.ksi.size  = NUM_FLASH_BLOCKS;
  db.ksi.used  = 0;
  db.ksi.index = db._index;
  db.ksi.names = db._names;

  for (int i = 0; i < sizeof(db.cache)/sizeof(*db.cache); i++)
    db.cache[i].blockno = ~0;

  /*
   * Scan existing content of flash to figure out what we've got.
   * This gets a bit involved due to the need to recover from things
   * like power failures at inconvenient times.
   */

  flash_block_type_t block_types[NUM_FLASH_BLOCKS];
  flash_block_t *block = cache_pick_lru();
  int first_erased = -1;
  int saw_pins = 0;
  hal_error_t err;
  uint16_t n = 0;

  if (block == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  for (int i = 0; i < NUM_FLASH_BLOCKS; i++) {

    /*
     * Read one block.  If the CRC is bad, it's old data we don't
     * understand, something we were writing when we crashed, or bad
     * flash; in any of these cases, we want the block to ends up near
     * the end of the free list.
     */

    if ((err = block_read(i, block)) == HAL_ERROR_KEYSTORE_BAD_CRC)
      block_types[i] = FLASH_UNKNOWN;

    else if (err == HAL_OK)
      block_types[i] = block_get_type(block);

    else
      return err;

    /*
     * First erased block we see is head of the free list.
     */

    if (block_types[i] == FLASH_ERASED && first_erased < 0)
      first_erased = i;

    /*
     * If it is or was a key block, remember its name.
     * PIN blocks get the all-zeros UUID for ks_index purposes.
     */

    if (block_types[i] == FLASH_KEYBLK || block_types[i] == FLASH_KEYOLD)
      db.ksi.names[i] = block->key.name;

    /*
     * If it is or was a PIN block, remember the PINs, but don't
     * overwrite PINs from a current PIN block with PINs from a
     * deprecated PIN block.
     */

    if (block_types[i] == FLASH_PINBLK || (block_types[i] == FLASH_PINOLD && !saw_pins)) {
      db.wheel_pin = block->pin.wheel_pin;
      db.so_pin    = block->pin.so_pin;
      db.user_pin  = block->pin.user_pin;
      saw_pins = 1;
    }

    /*
     * If it's a current block, include it in the index.
     */

    if (block_types[i] == FLASH_KEYBLK || block_types[i] == FLASH_PINBLK)
      db.ksi.index[n++] = i;
  }

  db.ksi.used = n;

  assert(db.ksi.used <= db.ksi.size);

  /*
   * At this point we've built the (unsorted) index from all the
   * current blocks.  Now we need to insert free, deprecated, and
   * unrecognized blocks into the free list in our preferred order.
   * There's probably a more efficient way to do this, but this is
   * just integer comparisons in a fairly small data set, so all of
   * these loops should be pretty fast.
   */

  if (n < db.ksi.size)
    for (int i = 0; i < NUM_FLASH_BLOCKS; i++)
      if (block_types[i] == FLASH_ERASED)
        db.ksi.index[n++] = i;

  if (n < db.ksi.size)
    for (int i = first_erased; i < NUM_FLASH_BLOCKS; i++)
      if (block_types[i] == FLASH_ZEROED)
        db.ksi.index[n++] = i;

  if (n < db.ksi.size)
    for (int i = 0; i < first_erased; i++)
      if (block_types[i] == FLASH_ZEROED)
        db.ksi.index[n++] = i;

  if (n < db.ksi.size)
    for (int i = 0; i < NUM_FLASH_BLOCKS; i++)
      if (block_types[i] == FLASH_KEYOLD || block_types[i] == FLASH_PINOLD)
        db.ksi.index[n++] = i;

  if (n < db.ksi.size)
    for (int i = 0; i < NUM_FLASH_BLOCKS; i++)
      if (block_types[i] == FLASH_UNKNOWN)
        db.ksi.index[n++] = i;

  assert(n == db.ksi.size);

  /*
   * Initialize the ks_index stuff.
   */

  if ((err = hal_ks_index_setup(&db.ksi)) != HAL_OK)
    return err;

  /*
   * Deal with deprecated blocks.  These are tombstones left behind
   * when something bad happened while we updating a block.  If write
   * of the updated block completed, we have nothing to do other than
   * cleaning up the tombstone, but if the write didn't complete, we
   * need to resurrect the data from the tombstone.
   */

  for (int i = 0; i < NUM_FLASH_BLOCKS; i++) {
    flash_block_type_t restore_type;

    switch (block_types[i]) {
    case FLASH_KEYOLD:  restore_type = FLASH_KEYBLK;    break;
    case FLASH_PINOLD:  restore_type = FLASH_PINBLK;    break;
    default:            continue;
    }

    err = hal_ks_index_find(&db.ksi, &db.ksi.names[i], NULL);

    if (err != HAL_OK && err != HAL_ERROR_KEY_NOT_FOUND)
      return err;

    unsigned b = ~0;

    if (err == HAL_ERROR_KEY_NOT_FOUND) {

      /*
       * Block did not exist, need to resurrect.
       */

      hal_uuid_t name = db.ksi.names[i]; /* Paranoia */

      if ((err = block_read(i, block)) != HAL_OK)
        return err;

      block->header.block_type = restore_type;

      if ((err = hal_ks_index_add(&db.ksi, &name, &b)) != HAL_OK ||
          (err = block_erase(b))                       != HAL_OK ||
          (err = block_write(b, block))                != HAL_OK)
        return err;

      if (restore_type == FLASH_PINBLK)
        saw_pins = 1;
    }

    /*
     * Done with the tombstone, zero it.
     */

    if ((unsigned) i != b && (err = block_zero(i)) != HAL_OK)
      return err;
  }

  /*
   * If we didn't see a PIN block, create one, with the user and so
   * PINs cleared and the wheel PIN set to the last-gasp value.  The
   * last-gasp WHEEL PIN is a terrible answer, but we need some kind
   * of bootstrapping mechanism when all else fails.  If you have a
   * better suggestion, we'd love to hear it.
   */

  if (!saw_pins) {
    unsigned b;

    memset(block, 0xFF, sizeof(*block));
    memset(&block->pin.so_pin,   0, sizeof(block->pin.so_pin));
    memset(&block->pin.user_pin, 0, sizeof(block->pin.user_pin));
    block->header.block_type = FLASH_PINBLK;
    block->pin.wheel_pin = hal_last_gasp_pin;

    if ((err = hal_ks_index_add(&db.ksi, &pin_uuid, &b)) != HAL_OK)
      return err;

    cache_mark_used(block, b);

    if ((err = block_erase_maybe(b)) == HAL_OK)
      err = block_write(b, block);

    cache_release(block);

    if (err != HAL_OK)
      return err;
  }

  /*
   * Erase first block on free list if it's not already erased.
   */

  if (db.ksi.used < db.ksi.size &&
      (err = block_erase_maybe(db.ksi.index[db.ksi.used])) != HAL_OK)
    return err;

  /*
   * And we're finally done.
   */

  db.ks.driver = driver;

  return HAL_OK;
}

static hal_error_t ks_shutdown(const hal_ks_driver_t * const driver)
{
  if (db.ks.driver != driver)
    return HAL_ERROR_KEYSTORE_ACCESS;
  memset(&db, 0, sizeof(db));
  return HAL_OK;
}

static hal_error_t ks_open(const hal_ks_driver_t * const driver,
                                    hal_ks_t **ks)
{
  if (driver != hal_ks_token_driver || ks == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  *ks = &db.ks;
  return HAL_OK;
}

static hal_error_t ks_close(hal_ks_t *ks)
{
  if (ks != NULL && ks != &db.ks)
    return HAL_ERROR_BAD_ARGUMENTS;

  return HAL_OK;
}

static inline int acceptable_key_type(const hal_key_type_t type)
{
  switch (type) {
  case HAL_KEY_TYPE_RSA_PRIVATE:
  case HAL_KEY_TYPE_EC_PRIVATE:
  case HAL_KEY_TYPE_RSA_PUBLIC:
  case HAL_KEY_TYPE_EC_PUBLIC:
    return 1;
  default:
    return 0;
  }
}

static hal_error_t ks_store(hal_ks_t *ks,
                            const hal_pkey_slot_t * const slot,
                            const uint8_t * const der, const size_t der_len)
{
  if (ks != &db.ks || slot == NULL || der == NULL || der_len == 0 || !acceptable_key_type(slot->type))
    return HAL_ERROR_BAD_ARGUMENTS;

  flash_block_t *block = cache_pick_lru();
  flash_key_block_t *k = &block->key;
  uint8_t kek[KEK_LENGTH];
  size_t kek_len;
  hal_error_t err;
  unsigned b;

  if (block == NULL)
    return HAL_ERROR_IMPOSSIBLE;

  if ((err = hal_ks_index_add(&db.ksi, &slot->name, &b)) != HAL_OK)
    return err;

  cache_mark_used(block, b);

  memset(block, 0xFF, sizeof(*block));
  block->header.block_type = FLASH_KEYBLK;
  k->name    = slot->name;
  k->type    = slot->type;
  k->curve   = slot->curve;
  k->flags   = slot->flags;
  k->der_len = sizeof(k->der);

  if ((err = hal_mkm_get_kek(kek, &kek_len, sizeof(kek))) == HAL_OK)
    err = hal_aes_keywrap(NULL, kek, kek_len, der, der_len, k->der, &k->der_len);

  memset(kek, 0, sizeof(kek));

  if (err == HAL_OK &&
      (err = block_erase_maybe(b)) == HAL_OK &&
      (err = block_write(b, block)) == HAL_OK)
    return HAL_OK;

  memset(block, 0, sizeof(*block));
  cache_release(block);
  (void) hal_ks_index_delete(&db.ksi, &slot->name, NULL);
  return err;
}

static hal_error_t ks_fetch(hal_ks_t *ks,
                            hal_pkey_slot_t *slot,
                            uint8_t *der, size_t *der_len, const size_t der_max)
{
  if (ks != &db.ks || slot == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  flash_block_t *block;
  hal_error_t err;
  unsigned b;

  if ((err = hal_ks_index_find(&db.ksi, &slot->name, &b)) != HAL_OK ||
      (err = block_read_cached(b, &block)) != HAL_OK)
    return err;

  cache_mark_used(block, b);

  flash_key_block_t *k = &block->key;

  slot->type  = k->type;
  slot->curve = k->curve;
  slot->flags = k->flags;

  if (der == NULL && der_len != NULL)
    *der_len = k->der_len;

  if (der != NULL) {

    uint8_t kek[KEK_LENGTH];
    size_t kek_len, der_len_;
    hal_error_t err;

    if (der_len == NULL)
      der_len = &der_len_;

    *der_len = der_max;

    if ((err = hal_mkm_get_kek(kek, &kek_len, sizeof(kek))) == HAL_OK)
      err = hal_aes_keyunwrap(NULL, kek, kek_len, k->der, k->der_len, der, der_len);

    memset(kek, 0, sizeof(kek));

    if (err != HAL_OK)
      return err;
  }

  return HAL_OK;
}

static hal_error_t ks_delete(hal_ks_t *ks,
                             const hal_pkey_slot_t * const slot)
{
  if (ks != &db.ks || slot == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  hal_error_t err;
  unsigned b;

  if ((err = hal_ks_index_delete(&db.ksi, &slot->name, &b)) != HAL_OK)
    return err;

  /*
   * If we wanted to double-check the flash block itself against what
   * we got from the index, this is where we'd do it.
   */

  cache_release(cache_find_block(b));

  if ((err = block_zero(b)) != HAL_OK ||
      (err = block_erase_maybe(db.ksi.index[db.ksi.used])) != HAL_OK)
    return err;

  return HAL_OK;
}

static hal_error_t ks_list(hal_ks_t *ks,
                           hal_pkey_info_t *result,
                           unsigned *result_len,
                           const unsigned result_max)
{
  if (ks != &db.ks || result == NULL || result_len == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  if (db.ksi.used > result_max)
    return HAL_ERROR_RESULT_TOO_LONG;

  flash_block_t *block;
  hal_error_t err;
  unsigned b;

  *result_len = 0;

  for (int i = 0; i < db.ksi.used; i++) {
    b = db.ksi.index[i];

    if ((err = block_read_cached(b, &block)) != HAL_OK)
      return err;

    if (block_get_type(block) != FLASH_KEYBLK)
      continue;

    result[*result_len].type  = block->key.type;
    result[*result_len].curve = block->key.curve;
    result[*result_len].flags = block->key.flags;
    result[*result_len].name  = block->key.name;
    ++ *result_len;
  }

  return HAL_OK;
}

const hal_ks_driver_t hal_ks_token_driver[1] = {{
  ks_init,
  ks_shutdown,
  ks_open,
  ks_close,
  ks_store,
  ks_fetch,
  ks_delete,
  ks_list
}};

/*
 * The remaining functions aren't really part of the keystore API per se,
 * but they all involve non-key data which we keep in the keystore
 * because it's the flash we've got.
 */

/*
 * Fetch PIN.  This is always cached, so just returned cached value.
 */

hal_error_t hal_get_pin(const hal_user_t user,
                        const hal_ks_pin_t **pin)
{
  if (pin == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  switch (user) {
  case HAL_USER_WHEEL:  *pin = &db.wheel_pin;  break;
  case HAL_USER_SO:     *pin = &db.so_pin;     break;
  case HAL_USER_NORMAL: *pin = &db.user_pin;   break;
  default:              return HAL_ERROR_BAD_ARGUMENTS;
  }

  return HAL_OK;
}

/*
 * Fetch PIN block.
 */

static hal_error_t fetch_pin_block(unsigned *b, flash_block_t **block)
{
  assert(b != NULL && block != NULL);

  hal_error_t err;

  if ((err = hal_ks_index_find(&db.ksi, &pin_uuid, b)) != HAL_OK ||
      (err = block_read_cached(*b, block))             != HAL_OK)
    return err;

  cache_mark_used(*block, *b);

  if (block_get_type(*block) != FLASH_PINBLK)
    return HAL_ERROR_IMPOSSIBLE;

  return HAL_OK;
}

/*
 * Update the PIN block.  This block should always be present, but we
 * have to dance a bit to make sure we write the new PIN block before
 * destroying the old one.
 */

static hal_error_t update_pin_block(const unsigned b1,
                                    flash_block_t *block,
                                    const flash_pin_block_t * const new_data)
{
  assert(block != NULL && new_data != NULL && block_get_type(block) == FLASH_PINBLK);

  hal_error_t err;
  unsigned b2;

  block->header.block_type = FLASH_PINOLD;

  err = block_write(b1, block);

  cache_release(block);

  if (err != HAL_OK)
    return err;

  /*
   * We could simplify and speed this up a bit by taking advantage of
   * knowing that the PIN block is always db.ksi->index[0] (because of
   * the all-zeros UUID).  Maybe later.
   */

  if ((err = hal_ks_index_delete(&db.ksi, &pin_uuid, &b2)) != HAL_OK)
    return err;

  if (b2 != b1)
    return HAL_ERROR_IMPOSSIBLE;

  block->pin = *new_data;

  err = hal_ks_index_add(&db.ksi, &pin_uuid, &b2);

  if (err == HAL_OK)
    cache_mark_used(block, b2);

  if (err == HAL_OK)
    err = block_erase_maybe(b2);

  if (err == HAL_OK)
    err = block_write(b2, block);

  if (err != HAL_OK)
    return err;

  if ((err = block_zero(b1)) != HAL_OK)
    return err;

  if (db.ksi.used < db.ksi.size)
    err = block_erase_maybe(db.ksi.index[db.ksi.used]);

  return err;
}

/*
 * Change a PIN.
 */

hal_error_t hal_set_pin(const hal_user_t user,
                        const hal_ks_pin_t * const pin)
{
  if (pin == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  flash_block_t *block;
  hal_error_t err;
  unsigned b;

  if ((err = fetch_pin_block(&b, &block)) != HAL_OK)
    return err;

  flash_pin_block_t new_data = block->pin;
  hal_ks_pin_t *dp, *bp;

  switch (user) {
  case HAL_USER_WHEEL:  bp = &new_data.wheel_pin; dp = &db.wheel_pin; break;
  case HAL_USER_SO:     bp = &new_data.so_pin;    dp = &db.so_pin;    break;
  case HAL_USER_NORMAL: bp = &new_data.user_pin;  dp = &db.user_pin;  break;
  default:              return HAL_ERROR_BAD_ARGUMENTS;
  }

  const hal_ks_pin_t old_pin = *dp;
  *dp = *bp = *pin;

  if ((err = update_pin_block(b, block, &new_data)) != HAL_OK)
    *dp = old_pin;

  return err;
}

#if HAL_MKM_FLASH_BACKUP_KLUDGE

hal_error_t hal_mkm_flash_read(uint8_t *buf, const size_t len)
{
  if (buf == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  if (len != KEK_LENGTH)
    return HAL_ERROR_MASTERKEY_BAD_LENGTH;

  flash_block_t *block;
  hal_error_t err;
  unsigned b;

  if ((err = fetch_pin_block(&b, &block)) != HAL_OK)
    return err;

  if (block->pin.kek_set != FLASH_KEK_SET)
    return HAL_ERROR_MASTERKEY_NOT_SET;

  memcpy(buf, block->pin.kek, len);
  return HAL_OK;
}

hal_error_t hal_mkm_flash_write(const uint8_t * const buf, const size_t len)
{
  if (buf == NULL)
    return HAL_ERROR_BAD_ARGUMENTS;

  if (len != KEK_LENGTH)
    return HAL_ERROR_MASTERKEY_BAD_LENGTH;

  flash_block_t *block;
  hal_error_t err;
  unsigned b;

  if ((err = fetch_pin_block(&b, &block)) != HAL_OK)
    return err;

  flash_pin_block_t new_data = block->pin;

  new_data.kek_set = FLASH_KEK_SET;
  memcpy(new_data.kek, buf, len);

  return update_pin_block(b, block, &new_data);
}

hal_error_t hal_mkm_flash_erase(const size_t len)
{
  if (len != KEK_LENGTH)
    return HAL_ERROR_MASTERKEY_BAD_LENGTH;

  flash_block_t *block;
  hal_error_t err;
  unsigned b;

  if ((err = fetch_pin_block(&b, &block)) != HAL_OK)
    return err;

  flash_pin_block_t new_data = block->pin;

  new_data.kek_set = FLASH_KEK_SET;
  memset(new_data.kek, 0, len);

  return update_pin_block(b, block, &new_data);
}

#endif /* HAL_MKM_FLASH_BACKUP_KLUDGE */


/*
 * Local variables:
 * indent-tabs-mode: nil
 * End:
 */