summaryrefslogtreecommitdiff
path: root/nuttx/fs/nxffs/nxffs_pack.c
blob: 7577aa66cac5dc6a2bc4ea763124f5d415bf1a7e (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
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
/****************************************************************************
 * fs/nxffs/nxffs_pack.c
 *
 *   Copyright (C) 2011, 2013 Gregory Nutt. All rights reserved.
 *   Author: Gregory Nutt <gnutt@nuttx.org>
 *
 * References: Linux/Documentation/filesystems/romfs.txt
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 * 3. Neither the name NuttX 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 OWNER 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.
 *
 ****************************************************************************/

/****************************************************************************
 * Included Files
 ****************************************************************************/

#include <nuttx/config.h>

#include <string.h>
#include <errno.h>
#include <assert.h>
#include <crc32.h>
#include <debug.h>

#include <nuttx/kmalloc.h>

#include "nxffs.h"

/****************************************************************************
 * Pre-processor Definitions
 ****************************************************************************/

/****************************************************************************
 * Public Types
 ****************************************************************************/
/* This structure supports access to one inode data stream */

struct nxffs_packstream_s
{
  struct nxffs_entry_s entry;      /* Describes the inode header */
  off_t                fpos;       /* Current file position */
  off_t                blkoffset;  /* Offset to the current data block */
  uint16_t             blklen;     /* Size of this block */
  uint16_t             blkpos;     /* Position in block corresponding to fpos */
};

/* The structure supports the overall packing operation */

struct nxffs_pack_s
{
  /* These describe the source and destination streams */

  struct nxffs_packstream_s src;
  struct nxffs_packstream_s dest;

  /* These describe the state of the current contents of the (destination)
   * volume->pack buffer.
   */

  FAR uint8_t         *iobuffer;   /* I/O block start position */
  off_t                ioblock;    /* I/O block number */
  off_t                block0;     /* First I/O block number in the erase block */
  uint16_t             iooffset;   /* I/O block offset */
};

/****************************************************************************
 * Public Variables
 ****************************************************************************/

/****************************************************************************
 * Private Functions
 ****************************************************************************/

/****************************************************************************
 * Name: nxffs_getblock
 *
 * Description:
 *   Return the I/O block number that includes the provided offset.
 *
 * Input Parameters:
 *   volume - Describes the NXFFS volume
 *   offset - FLASH offset
 *
 * Returned Value:
 *   The I/O block number.
 *
 ****************************************************************************/

static off_t nxffs_getblock(FAR struct nxffs_volume_s *volume, off_t offset)
{
  return offset / volume->geo.blocksize;
}

/****************************************************************************
 * Name: nxffs_getoffset
 *
 * Description:
 *   Given an I/O block number return the block offset corresponding to the
 *   FLASH offset;
 *
 * Input Parameters:
 *   volume - Describes the NXFFS volume
 *   offset - FLASH offset
 *
 * Returned Value:
 *   The I/O block number.
 *
 ****************************************************************************/

static off_t nxffs_getoffset(FAR struct nxffs_volume_s *volume,
                             off_t offset, off_t block)
{
  return offset - block * volume->geo.blocksize;
}

/****************************************************************************
 * Name: nxffs_packtell
 *
 * Description:
 *   Report the current destination position in the pack buffer.
 *
 * Input Parameters:
 *   volume - Describes the NXFFS volume
 *   pack   - The volume packing state structure.
 *
 * Returned Value:
 *   The offset from the beginning of FLASH to the current seek position.
 *
 ****************************************************************************/

static off_t nxffs_packtell(FAR struct nxffs_volume_s *volume,
                            FAR struct nxffs_pack_s *pack)
{
  return pack->ioblock * volume->geo.blocksize + pack->iooffset;
}

/****************************************************************************
 * Name: nxffs_packvalid
 *
 * Description:
 *   Check if the current destination block is valid.
 *
 * Input Parameters:
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   None
 *
 ****************************************************************************/

static inline bool nxffs_packvalid(FAR struct nxffs_pack_s *pack)
{
  FAR struct nxffs_block_s *blkhdr;

  blkhdr = (FAR struct nxffs_block_s *)pack->iobuffer;
  return (memcmp(blkhdr->magic, g_blockmagic, NXFFS_MAGICSIZE) == 0 &&
          blkhdr->state == BLOCK_STATE_GOOD);
}

/****************************************************************************
 * Name: nxffs_mediacheck
 *
 * Description:
 *   Verify that there is at least one valid block and at least one valid
 *   inode header on the media.  On successful return, the volume packing
 *   structure is initialized and contains the offset to the first valid
 *   inode header is returned.
 *
 * Input Parameters:
 *   volume - The volume to be packed.
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   The offset to the data area on the first valid block.  Zero is return
 *   if there are no valid blocks or if there are no valid inode headers
 *   after the first valid block.
 *
 ****************************************************************************/

static inline off_t nxffs_mediacheck(FAR struct nxffs_volume_s *volume,
                                     FAR struct nxffs_pack_s *pack)
{
  off_t froffset;
  int ret;

  /* Initialize the packing structure to all zero */

  memset(pack, 0, sizeof(struct nxffs_pack_s));

  /* Find the FLASH offset to the first valid block */

  volume->ioblock = 0;
  ret = nxffs_validblock(volume, &volume->ioblock);
  if (ret < 0)
   {
     /* No valid blocks?  Return offset zero. */

     return 0;
   }

  /* The offset to the free location to pack is then just after the block
   * header in this block.
   */

  volume->iooffset = SIZEOF_NXFFS_BLOCK_HDR;
  froffset         = nxffs_iotell(volume);

  /* Get the offset to the first valid inode entry after this free offset */

  ret = nxffs_nextentry(volume, froffset, &pack->src.entry);
  if (ret < 0)
    {
      /* No valid entries on the media -- Return offset zero */

     return 0;
    }

  /* Okay.. the start block and first entry have been found */

  return froffset;
}

/****************************************************************************
 * Name: nxffs_startpos
 *
 * Description:
 *   Find the position in FLASH memory where we should begin packing.  That
 *   position is the place where there is a gap between the last and the next
 *   valid inode.  On entry, the volume packing structure should be as it
 *   was initialized by nxffx_mediacheck.  on successful return, the volume
 *   packing state structure will be updated to begin the packing operation.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *   froffset - On input, this is the location where we should be searching
 *     for the location to begin packing.  On successful return, froffset
 *     will be set to the offset in FLASH where the first inode should be
 *     copied to.  If -ENOSPC is returned -- meaning that the FLASH is full
 *     --  then no packing can be performed. In this case, then the free
 *     flash offset is returned through this location.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.  If -ENOSPC is returned then the
 *   free FLASH offset is also returned.
 *
 ****************************************************************************/

static inline int nxffs_startpos(FAR struct nxffs_volume_s *volume,
                                 FAR struct nxffs_pack_s *pack,
                                 off_t *froffset)
{
  struct nxffs_blkentry_s blkentry;
  off_t offset = *froffset;
  off_t wasted;
  off_t nbytes;
  int ret;

  /* Loop until we find a gap of unused FLASH large enough to warrant
   * compacting.
   */

  for(;;)
    {
      /* Is there wasted space between the offset where the we could have
       * valid data and the offset to the beginning of the first valid
       * inode header?  NOTE:  The threshold check is not accurate, there
       * may or may not be intervening block headers making the separation
       * seem larger than it is.
       */

      DEBUGASSERT(pack->src.entry.hoffset >= offset);
      wasted = pack->src.entry.hoffset - offset;
      if (wasted > CONFIG_NXFFS_PACKTHRESHOLD)
        {
          /* This is where we must begin packing.  Describe the destination
           * inode header (only non-zero entries need to be initialized).
           */

          pack->dest.entry.name    = pack->src.entry.name;
          pack->dest.entry.utc     = pack->src.entry.utc;
          pack->dest.entry.datlen  = pack->src.entry.datlen;

          /* The destination entry now "owns" the name string */

          pack->src.entry.name     = NULL;

          /* Return the FLASH offset to the destination inode header */

          *froffset = offset;
          return OK;
        }

      /* Free the allocated memory in the entry */

      nxffs_freeentry(&pack->src.entry);

      /* Update the offset to the first byte at the end of the last data
       * block.
       */

      nbytes = 0;
      offset = pack->src.entry.doffset;

      while (nbytes < pack->src.entry.datlen)
        {
          /* Read the next data block header */

          ret = nxffs_nextblock(volume, offset, &blkentry);
          if (ret < 0)
            {
              fdbg("ERROR: Failed to find next data block: %d\n", -ret);
              return ret;
            }

          /* Get the number of blocks and pointer to where the next
           * data block might lie.
           */

          nbytes += blkentry.datlen;
          offset  = blkentry.hoffset + SIZEOF_NXFFS_DATA_HDR + blkentry.datlen;
        }

      /* Make sure there is space at this location for an inode header */

      nxffs_ioseek(volume, offset);
      if (volume->iooffset + SIZEOF_NXFFS_INODE_HDR > volume->geo.blocksize)
        {
          /* No.. not enough space here. Find the next valid block */

          volume->ioblock++;
          ret = nxffs_validblock(volume, &volume->ioblock);
          if (ret < 0)
            {
               /* No valid blocks? Then there is nothing we can do.  Return
                * the end-of-flash indication.
                */

               *froffset = volume->froffset;
               return -ENOSPC;
            }

          volume->iooffset = SIZEOF_NXFFS_BLOCK_HDR;
          offset = nxffs_iotell(volume);
        }

      /* Get the offset to the next valid inode entry */

      ret = nxffs_nextentry(volume, offset, &pack->src.entry);
      if (ret < 0)
        {
          /* No more valid inode entries.  Just return an end-of-flash error
           * indication.  However, there could be many deleted inodes; set
           * volume->froffset to indicate the true free FLASH position.
           */

          *froffset = offset;
          return -ENOSPC;
        }
    }

  /* We won't get here */

  return -ENOSYS;
}

/****************************************************************************
 * Name: nxffs_srcsetup
 *
 * Description:
 *   Given a valid src inode, configure the src data stream.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *   offset - FLASH offset to the data block header (will be zero for zero-
 *     files.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.
 *
 ****************************************************************************/

static int nxffs_srcsetup(FAR struct nxffs_volume_s *volume,
                          FAR struct nxffs_pack_s *pack, off_t offset)
{
  /* Start with the first data block */

  pack->src.blkoffset = offset;
  pack->src.blkpos    = 0;

  /* Zero-length files have no valid data block offset */

  if (offset > 0)
    {
      /* Seek to the data block header, read and verify the block header */

      int ret = nxffs_rdblkhdr(volume, offset, &pack->src.blklen);
      if (ret < 0)
        {
          fdbg("ERROR: Failed to verify the data block header: %d\n", -ret);
        }

      return ret;
    }

  DEBUGASSERT(pack->src.entry.datlen == 0);
  return OK;
}

/****************************************************************************
 * Name: nxffs_destsetup
 *
 * Description:
 *   Given a valid dest inode, configure the dest data stream.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.
 *
 ****************************************************************************/

static int nxffs_destsetup(FAR struct nxffs_volume_s *volume,
                           FAR struct nxffs_pack_s *pack)
{
  size_t mindata;
  int    namlen;
  int    ret;

  /* The destination can be in one of three of states:
   *
   * State 1: The inode position was not yet been found.  This condition can
   * only occur on initial entry into nxffs_packblock() when there we no space
   * for the inode header at the end of the previous block.  We must now be
   * at the beginning of a shiny new I/O block, so we should always have
   * space for a new inode header right here.
   */

  if (pack->dest.entry.hoffset == 0)
    {
      /* Is there room for an inode structure in this block?  */

      if (pack->iooffset + SIZEOF_NXFFS_INODE_HDR > volume->geo.blocksize)
        {
          /* No.. that inode name will not fit in this block. Return an
           * indication that we are at the end of the block and try again
           * later.
           */

          return -ENOSPC;
        }

      /* The inode header will be placed at this position (but not until
       * we are finished.
       */

      pack->dest.entry.hoffset = nxffs_packtell(volume, pack);

      /* Make sure that the initialize state of the inode header memory is
       * erased.  This is important because we may not write to inode header
       * until it has already been written to FLASH.
       */

      memset(&pack->iobuffer[pack->iooffset], CONFIG_NXFFS_ERASEDSTATE,
             SIZEOF_NXFFS_INODE_HDR);

      /* Then set the new FLASH offset */

      pack->iooffset += SIZEOF_NXFFS_INODE_HDR;
    }

  /* State 2: inode position found, inode header not written, inode name
   * position not determined.
   */

  if (pack->dest.entry.noffset == 0)
    {
      /* Find the offset to the string memory.  Will if fit in this block?
       * Note: iooffset has already been incremented to account for the
       * size of the inode header.
       */

      namlen = strlen(pack->dest.entry.name);
      if (pack->iooffset + namlen > volume->geo.blocksize)
        {
          /* No.. that inode name will not fit in this block. Return an
           * indication that we are at the end of the block and try again
           * later.
           */

          return -ENOSPC;
        }

      /* Yes.. Write the inode name to the volume packing buffer now, but do
       * not free the name string memory yet; it will be needed later to\
       * calculate the header CRC.
       */

      memcpy(&pack->iobuffer[pack->iooffset], pack->dest.entry.name, namlen);

      /* Reserve space for the inode name  */

      pack->dest.entry.noffset = nxffs_packtell(volume, pack);
      pack->iooffset += namlen;
    }

  /* State 3: Inode header not-written, inode name written.  Still need the position
   * of the first data block.
   *
   * Deal with the special case where the source inode is a zero length file
   * with no data blocks to be transferred.
   */

  if (pack->src.entry.doffset > 0)
    {
      if (pack->dest.entry.doffset == 0)
        {
          /* Will the data block header plus a minimal amount of data fit in this
           * block? (or the whole file if the file is very small).
           */

          mindata = MIN(NXFFS_MINDATA, pack->dest.entry.datlen);
          if (pack->iooffset + SIZEOF_NXFFS_DATA_HDR + mindata > volume->geo.blocksize)
            {
              /* No.. return an indication that we are at the end of the block
               * and try again later.
               */

              ret = -ENOSPC;
              goto errout;
           }

          /* Yes.. reserve space for the data block header */

          pack->dest.entry.doffset = nxffs_packtell(volume, pack);
          pack->iooffset          += SIZEOF_NXFFS_DATA_HDR;

          /* Initialize the output data stream to start with the first data block */

          pack->dest.blkoffset     = pack->dest.entry.doffset;
          pack->dest.blklen        = 0;
          pack->dest.blkpos        = 0;
        }

      /* State 4:  Starting a new block.  Verify that there is space in the current
       * block for another (minimal sized) block
       */

      if (pack->dest.blkoffset == 0)
        {
          /* Will the data block header plus a minimal amount of data fit in this
           * block? (or the whole file if the file is very small).
           */

          mindata = MIN(NXFFS_MINDATA, pack->dest.entry.datlen);
          if (pack->iooffset + SIZEOF_NXFFS_DATA_HDR + mindata > volume->geo.blocksize)
            {
              /* No.. return an indication that we are at the end of the block
               * and try again later.
               */

              ret = -ENOSPC;
              goto errout;
           }

          /* Yes.. reserve space for the data block header */

          pack->dest.blkoffset = nxffs_packtell(volume, pack);
          pack->iooffset      += SIZEOF_NXFFS_DATA_HDR;
          pack->dest.blklen    = 0;
          pack->dest.blkpos    = 0;
        }
    }

  ret = OK;

errout:
  volume->froffset = nxffs_packtell(volume, pack);
  return ret;
}

/****************************************************************************
 * Name: nxffs_wrinodehdr
 *
 * Description:
 *   Write the destination inode header (only) to FLASH.  Note that the inode
 *   name has already been written to FLASH (thus greatly simplifying the
 *   the complexity of this operation).
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure (not used).
 *
 ****************************************************************************/

static int nxffs_wrinodehdr(FAR struct nxffs_volume_s *volume,
                            FAR struct nxffs_pack_s *pack)
{
  FAR struct nxffs_inode_s *inode;
  off_t ioblock;
  uint16_t iooffset;
  uint32_t crc;
  int namlen;
  int ret;

  /* Get seek positions corresponding to the inode header location */

  ioblock   = nxffs_getblock(volume, pack->dest.entry.hoffset);
  iooffset  = nxffs_getoffset(volume, pack->dest.entry.hoffset, ioblock);

  /* The inode header is not written until all of the inode data has been
   * packed into its new location.  As a result, there are two possibilities:
   *
   * 1. The inode header lies in the current, unwritten erase block,
   * 2. The inode header resides in an earlier erase block and has already
   *    been written to FLASH.
   *
   * Recall that the inode name has already been written to FLASH.  If that
   * were not the case, then there would be other complex possibilities.
   *
   * Case 2: Does the inode header reside in a block before the beginning
   * of the current erase block?
   */

  if (ioblock < pack->block0)
    {
      /* Case 2:  The inode header lies in an earlier erase block that has
       * already been written to FLASH.  In this case, if we are very
       * careful, we can just use the standard routine to write the inode
       * header that is called during the normal file close operation:
       */

      ret = nxffs_wrinode(volume, &pack->dest.entry);
    }
  else
    {
      /* Cases 1:  Both the inode header and name are in the unwritten cache
       * memory.
       *
       * Initialize the inode header.
       */

      iooffset += (ioblock - pack->block0) * volume->geo.blocksize;
      inode     = (FAR struct nxffs_inode_s *)&volume->pack[iooffset];
      memcpy(inode->magic, g_inodemagic, NXFFS_MAGICSIZE);

      nxffs_wrle32(inode->noffs,  pack->dest.entry.noffset);
      nxffs_wrle32(inode->doffs,  pack->dest.entry.doffset);
      nxffs_wrle32(inode->utc,    pack->dest.entry.utc);
      nxffs_wrle32(inode->crc,    0);
      nxffs_wrle32(inode->datlen, pack->dest.entry.datlen);

      /* Get the length of the inode name */

      namlen = strlen(pack->dest.entry.name);
      DEBUGASSERT(namlen < CONFIG_NXFFS_MAXNAMLEN);

      inode->state  = CONFIG_NXFFS_ERASEDSTATE;
      inode->namlen = namlen;

      /* Calculate the CRC */

      crc = crc32((FAR const uint8_t *)inode, SIZEOF_NXFFS_INODE_HDR);
      crc = crc32part((FAR const uint8_t *)pack->dest.entry.name, namlen, crc);

      /* Finish the inode header */

      inode->state = INODE_STATE_FILE;
      nxffs_wrle32(inode->crc, crc);

      /* If any open files reference this inode, then update the open file
       * state.
       */

      ret = nxffs_updateinode(volume, &pack->dest.entry);
      if (ret < 0)
        {
          fdbg("ERROR: Failed to update inode info: %s\n", -ret);
        }
    }

  /* Reset the dest inode information */

  nxffs_freeentry(&pack->dest.entry);
  memset(&pack->dest, 0, sizeof(struct nxffs_packstream_s));
  return ret;
}

/****************************************************************************
 * Name: nxffs_wrdatthdr
 *
 * Description:
 *   Write the destination data block header to FLASH.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.
 *
 ****************************************************************************/

static void nxffs_wrdathdr(FAR struct nxffs_volume_s *volume,
                           FAR struct nxffs_pack_s *pack)
{
  FAR struct nxffs_data_s *dathdr;
  off_t    ioblock;
  uint16_t iooffset;
  uint32_t crc;

  if (pack->dest.blklen > 0)
    {
      /* Get the offset in the block corresponding to the location of the data
       * block header.  NOTE:  This must lie in the same block as we currently have
       * buffered.
       */

      ioblock  = nxffs_getblock(volume, pack->dest.blkoffset);
      iooffset = nxffs_getoffset(volume, pack->dest.blkoffset, ioblock);
      DEBUGASSERT(pack->dest.blkoffset && ioblock == pack->ioblock);

      /* Write the data block header to memory */

      dathdr = (FAR struct nxffs_data_s *)&pack->iobuffer[iooffset];
      memcpy(dathdr->magic, g_datamagic, NXFFS_MAGICSIZE);
      nxffs_wrle32(dathdr->crc, 0);
      nxffs_wrle16(dathdr->datlen, pack->dest.blklen);

      /* Update the entire data block CRC (including the header) */

      crc = crc32(&pack->iobuffer[iooffset], pack->dest.blklen + SIZEOF_NXFFS_DATA_HDR);
      nxffs_wrle32(dathdr->crc, crc);
    }

  /* Setup state to allocate the next data block */

  pack->dest.blkoffset = 0;
  pack->dest.blklen    = 0;
  pack->dest.blkpos    = 0;
}

/****************************************************************************
 * Name: nxffs_packtransfer
 *
 * Description:
 *   Transfer data from the source to the destination buffer.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   None.
 *
 ****************************************************************************/

static void nxffs_packtransfer(FAR struct nxffs_volume_s *volume,
                               FAR struct nxffs_pack_s *pack)
{
   /* Determine how much data is available in the dest pack buffer */

   uint16_t destlen = volume->geo.blocksize - pack->iooffset;

   /* Dermined how much data is available in the src data block */

   uint16_t srclen = pack->src.blklen - pack->src.blkpos;

   /* Transfer the smaller of the two amounts data */

   uint16_t xfrlen = MIN(srclen, destlen);
   if (xfrlen > 0)
     {
       nxffs_ioseek(volume, pack->src.blkoffset + SIZEOF_NXFFS_DATA_HDR + pack->src.blkpos);
       memcpy(&pack->iobuffer[pack->iooffset], &volume->cache[volume->iooffset], xfrlen);

       /* Increment counts and offset for this data transfer */

       pack->src.fpos    += xfrlen; /* Source data offsets */
       pack->src.blkpos  += xfrlen;
       pack->dest.fpos   += xfrlen; /* Destination data offsets */
       pack->dest.blkpos += xfrlen;
       pack->dest.blklen += xfrlen; /* Destination data block size */
       pack->iooffset    += xfrlen; /* Destination I/O block offset */
       volume->iooffset  += xfrlen; /* Source I/O block offset */
       volume->froffset  += xfrlen; /* Free FLASH offset */
     }
}

/****************************************************************************
 * Name: nxffs_endsrcblock
 *
 * Description:
 *   The end of a source data block has been encountered.  Locate the next
 *   source block and setup to continue the transfer.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.
 *
 ****************************************************************************/

static int nxffs_endsrcblock(FAR struct nxffs_volume_s *volume,
                             FAR struct nxffs_pack_s *pack)
{
  struct nxffs_blkentry_s blkentry;
  off_t offset;
  int ret;

  /* Yes.. find the next data block in the source input stream. */

  offset = pack->src.blkoffset + SIZEOF_NXFFS_DATA_HDR + pack->src.blklen;
  ret    = nxffs_nextblock(volume, offset, &blkentry);
  if (ret < 0)
    {
      fdbg("ERROR: Failed to find next data block: %d\n", -ret);
      return ret;
    }

  /* Set up the source stream */

  pack->src.blkoffset = blkentry.hoffset;
  pack->src.blklen    = blkentry.datlen;
  pack->src.blkpos    = 0;
  return OK;
}

/****************************************************************************
 * Name: nxffs_packblock
 *
 * Description:
 *   Resume packing from the source stream into the newly identified
 *   destination block.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.
 *
 ****************************************************************************/

static inline int nxffs_packblock(FAR struct nxffs_volume_s *volume,
                                  FAR struct nxffs_pack_s *pack)
{
  off_t offset;
  int ret;

  /* Are we currently processing a block from the source stream? */

  if (pack->src.blkoffset == 0)
    {
      /* No.. setup the source stream */

      ret = nxffs_srcsetup(volume, pack, pack->src.entry.doffset);
      if (ret < 0)
        {
          fdbg("ERROR: Failed to configure the src stream: %d\n", -ret);
          return ret;
        }
    }

  /* We enter here on a new block every time, so we always have to setup
   * the dest data stream.  There should never be data block allocated at
   * this point in time.
   */

  DEBUGASSERT(pack->dest.blkoffset == 0 && pack->dest.blkpos == 0);

  ret = nxffs_destsetup(volume, pack);
  if (ret < 0)
    {
      /* -ENOSPC is a special return value which simply means that all of
       * the FLASH has been used up to the end of the current.  We need to
       * return OK in this case and resume at the next block.
       */

      if (ret == -ENOSPC)
        {
          return OK;
        }
      else
        {
          fdbg("ERROR: Failed to configure the dest stream: %d\n", -ret);
          return ret;
        }
    }

  /* Loop, transferring data from the source block to the destination pack
   * buffer until either (1) the source stream is exhausted, (2) the destination
   * block is full, or (3) an error occurs.
   */

  for (;;)
    {
      /* Transfer data from the source buffer to the destination buffer */

      nxffs_packtransfer(volume, pack);

      /* Now, either the (1) src block has been fully transferred, (2) all
       * of the source data has been transferred, or (3) the destination
       * block is full, .. or all three.
       *
       * Check if all of the bytes in the source inode have been transferred.
       */

      if (pack->src.fpos >= pack->src.entry.datlen)
        {
          /* Write the final destination data block header and inode
           * headers.
           */

          nxffs_wrdathdr(volume, pack);
          nxffs_wrinodehdr(volume, pack);

          /* Find the next valid source inode */

          offset = pack->src.blkoffset + pack->src.blklen;
          memset(&pack->src, 0, sizeof(struct nxffs_packstream_s));

          ret = nxffs_nextentry(volume, offset, &pack->src.entry);
          if (ret < 0)
            {
              /* No more valid inode entries.  Just return an end-of-flash error
               * indication.
               */

              return -ENOSPC;
            }

          /* Setup the new source stream */

          ret = nxffs_srcsetup(volume, pack, pack->src.entry.doffset);
          if (ret < 0)
            {
              return ret;
            }

          /* Setup the dest stream */

          memset(&pack->dest, 0, sizeof(struct nxffs_packstream_s));
          pack->dest.entry.name   = pack->src.entry.name;
          pack->dest.entry.utc    = pack->src.entry.utc;
          pack->dest.entry.datlen = pack->src.entry.datlen;
          pack->src.entry.name    = NULL;

          /* Is there sufficient space at the end of the I/O block to hold
           * the inode header?
           */

          if (pack->iooffset + SIZEOF_NXFFS_INODE_HDR > volume->geo.blocksize)
            {
              /* No, just return success... we will handle this condition when
               * this function is called on the next I/O block.
               */

              return OK;
            }

          /* Configure the destination stream */

          ret = nxffs_destsetup(volume, pack);
          if (ret < 0)
            {
              /* -ENOSPC is a special return value which simply means that all of the
               * has been used up to the end.  We need to return OK in this case and
               * resume at the next block.
               */

              if (ret == -ENOSPC)
                {
                  return OK;
                }
              else
                {
                  fdbg("ERROR: Failed to configure the dest stream: %d\n", -ret);
                  return ret;
                }
            }
        }

      /* Not at the end of the source data stream.  Check if we are at the
       * end of the current source data block.
       */

      else if (pack->src.blkpos >= pack->src.blklen)
        {
          ret = nxffs_endsrcblock(volume, pack);
          if (ret < 0)
            {
              return ret;
            }
        }

     /* Check if the destination block is full */

     if (pack->iooffset >= volume->geo.blocksize)
       {
         /* Yes.. Write the destination data block header and return success */

         nxffs_wrdathdr(volume, pack);
         return OK;
       }
    }

  return -ENOSYS;
}

/****************************************************************************
 * Name: nxffs_setupwriter
 *
 * Description:
 *   Writing is performed at the end of the free FLASH region.  When we
 *   finish packing the other inodes, we still need to pack the partially
 *   written file at the end of FLASH.  This function performs the setup
 *   necessary to perform that packing phase.
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   If there is an active writer of the volume, its open file instance is
 *   returned.  NULL is returned otherwise.
 *
 ****************************************************************************/

static FAR struct nxffs_wrfile_s *
nxffs_setupwriter(FAR struct nxffs_volume_s *volume,
                  FAR struct nxffs_pack_s *pack)
{
  FAR struct nxffs_wrfile_s *wrfile;

  /* Is there a writer? */

  wrfile = nxffs_findwriter(volume);
  if (wrfile)
    {
      /* Yes...  It is the activity of this write that probably initiated
       * this packing activity.  The writer may have failed in one of several
       * different stages:
       *
       *   hoffset == 0: The write failed early before even FLASH for the inode
       *     header was set aside.
       *   noffset == 0: The write failed after the inode header was set aside,
       *     but before the inode name was written.
       *   doffset == 0: The write failed after writing the inode name, bue
       *     before any data blocks were written to FLASH.
       *
       * If no FLASH has been set aside for the write, then we don't need to
       * do anything here.
       */

      if (wrfile->ofile.entry.hoffset > 0)
        {
          /* Initialize for the packing operation. */

           memset(&pack->dest, 0, sizeof(struct nxffs_packstream_s));
           pack->dest.entry.name   = strdup(wrfile->ofile.entry.name);
           pack->dest.entry.utc    = wrfile->ofile.entry.utc;
           pack->dest.entry.datlen = wrfile->ofile.entry.datlen;

           memset(&pack->src, 0, sizeof(struct nxffs_packstream_s));
           memcpy(&pack->src.entry, &wrfile->ofile.entry, sizeof(struct nxffs_entry_s));
           pack->src.entry.name    = NULL;
           return wrfile;
        }
    }

  return NULL;
}

/****************************************************************************
 * Name: nxffs_packwriter
 *
 * Description:
 *   There is a write in progress at the time that the volume is packed.
 *   This is the normal case because it is the write failures that trigger
 *   the packing operation to begin with.
 *
 *   Writing is performed at the end of the free FLASH region and this
 *   implemenation is restricted to a single writer.  The new inode is not
 *   written to FLASH until the writer is closed and so will not be
 *   found by nxffs_packblock().
 *
 * Input Parameters:
 *   volume - The volume to be packed
 *   pack   - The volume packing state structure.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.
 *
 ****************************************************************************/

static inline int nxffs_packwriter(FAR struct nxffs_volume_s *volume,
                                   FAR struct nxffs_pack_s *pack,
                                   FAR struct nxffs_wrfile_s *wrfile)
{
  int ret;

  /* Are we currently processing a block from the source stream? */

  if (pack->src.blkoffset == 0)
    {
      /* No.. setup the source stream */

      ret = nxffs_srcsetup(volume, pack, pack->src.entry.doffset);
      if (ret < 0)
        {
          fdbg("ERROR: Failed to configure the src stream: %d\n", -ret);
          return ret;
        }
    }

  /* We enter here on a new block every time, so we always have to setup
   * the dest data stream.  There should never be data block allocated at
   * this point in time.
   */

  DEBUGASSERT(pack->dest.blkoffset == 0 && pack->dest.blkpos == 0);

  ret = nxffs_destsetup(volume, pack);
  if (ret < 0)
    {
      /* -ENOSPC is a special return value which simply means that all of the
       * has been used up to the end.  We need to return OK in this case and
       * resume at the next block.
       */

      if (ret == -ENOSPC)
        {
          return OK;
        }
      else
        {
          fdbg("ERROR: Failed to configure the dest stream: %d\n", -ret);
          return ret;
        }
    }

  /* Loop, transferring data from the source block to the destination pack
   * buffer until either (1) the source stream is exhausted, (2) the destination
   * block is full, or (3) an error occurs.
   */

  for (;;)
    {
       /* Transfer data from the source buffer to the destination buffer */

       nxffs_packtransfer(volume, pack);

       /* Now, either the (1) src block has been fully transferred, (2) all
        * of the source data has been transferred, or (3) the destination
        * block is full, .. or all three.
        *
        * Check if all of the bytes in the source inode have been transferred.
        */

       if (pack->src.fpos >= pack->src.entry.datlen)
         {
           /* Write the final destination data block header and inode
            * headers.
            */

           nxffs_wrdathdr(volume, pack);

           /* Set the new offsets in the open file instance. */

           wrfile->ofile.entry.hoffset = pack->dest.entry.hoffset;
           wrfile->ofile.entry.noffset = pack->dest.entry.noffset;
           wrfile->ofile.entry.doffset = pack->dest.entry.doffset;

           /* Return an end-of-flash error to indicate that all of the write
            * data has been transferred.
            */

           return -ENOSPC;
         }

      /* Not at the end of the source data stream.  Check if we are at the
       * end of the current source data block.
       */

      else if (pack->src.blkpos >= pack->src.blklen)
        {
          ret = nxffs_endsrcblock(volume, pack);
          if (ret < 0)
            {
              return ret;
            }
        }

     /* Check if the destination block is full */

     if (pack->iooffset >= volume->geo.blocksize)
       {
         /* Yes.. Write the destination data block header and return success */

         nxffs_wrdathdr(volume, pack);
         return OK;
       }
    }

  return -ENOSYS;
}

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: nxffs_pack
 *
 * Description:
 *   Pack and re-write the filesystem in order to free up memory at the end
 *   of FLASH.
 *
 * Input Parameters:
 *   volume - The volume to be packed.
 *
 * Returned Values:
 *   Zero on success; Otherwise, a negated errno value is returned to
 *   indicate the nature of the failure.
 *
 ****************************************************************************/

int nxffs_pack(FAR struct nxffs_volume_s *volume)
{
  struct nxffs_pack_s pack;
  FAR struct nxffs_wrfile_s *wrfile;
  off_t iooffset;
  off_t eblock;
  off_t block;
  bool packed;
  int i;
  int ret = OK;

  /* Get the offset to the first valid inode entry */

  wrfile = NULL;
  packed = false;

  iooffset = nxffs_mediacheck(volume, &pack);
  if (iooffset == 0)
    {
      /* Offset zero is only returned if no valid blocks were found on the
       * FLASH media or if there are no valid inode entries on the FLASH after
       * the first valid block.  There are two possibilities:  (1) there
       * really is nothing on the FLASH, or (2) there is a file being written
       * to the FLASH now.
       */

      /* Is there a writer? */

      wrfile = nxffs_setupwriter(volume, &pack);
      if (wrfile)
        {
          /* If there is a write, just set ioffset to the offset of data in
           * first block. Setting 'packed' to true will supress normal inode
           * packing operation.  Then we can start compacting the FLASH.
           */

          iooffset = SIZEOF_NXFFS_BLOCK_HDR;
          packed   = true;
          goto start_pack;
        }
      else
        {
          /* No, there is no write in progress.  We just have an empty flash
           * full of deleted files.  In this case, the media needs to be re-
           * formatted.
            */

          ret = nxffs_reformat(volume);
          if (ret == OK)
            {
              /* The free flash offset will be in the first valid block of
               * the FLASH.
               */

              block = 0;
              ret = nxffs_validblock(volume, &block);
              if (ret == OK)
                {
                  /* Set to the offset past the block header in the first
                   * valid block
                   */

                  volume->froffset =
                    block * volume->geo.blocksize + SIZEOF_NXFFS_BLOCK_HDR;
                }
            }

          return ret;
        }
    }

  /* There is a valid format and valid inodes on the media.. setup up to
   * begin the packing operation.
   */

  ret = nxffs_startpos(volume, &pack, &iooffset);
  if (ret < 0)
    {
      /* This is a normal situation if the volume is full */

      if (ret == -ENOSPC)
        {
          /* In the case where the volume is full, nxffs_startpos() will
           * recalculate the free FLASH offset and store it in iooffset.  There
           * may be deleted files at the end of FLASH.  In this case, we don't
           * have to pack any files, we simply have to erase FLASH at the end.
           * But don't do this unless there is some particularly big FLASH
           * savings (otherwise, we risk wearing out these final blocks).
           */

          if (iooffset + CONFIG_NXFFS_TAILTHRESHOLD < volume->froffset)
            {
               /* Setting 'packed' to true will supress normal inode packing
                * operation.
                */

               packed = true;

               /* Writing is performed at the end of the free FLASH region.
                * If we are not packing files, we could still need to pack
                * the partially written file at the end of FLASH.
                */

               wrfile = nxffs_setupwriter(volume, &pack);
             }

          /* Otherwise return OK.. meaning that there is nothing more we can
           * do to recover FLASH space.
           */

          else
            {
              return OK;
            }
        }
      else
        {
          fdbg("ERROR: Failed to find a packing position: %d\n", -ret);
          return ret;
        }
    }

  /* Otherwise, begin pack at this src/dest block combination.  Initialize
   * ioblock and iooffset with the position of the first inode header.  In
   * this case, the FLASH offset to the first inode header is return in
   * iooffset.
   */

start_pack:

  pack.ioblock     = nxffs_getblock(volume, iooffset);
  pack.iooffset    = nxffs_getoffset(volume, iooffset, pack.ioblock);
  volume->froffset = iooffset;

  /* Then pack all erase blocks starting with the erase block that contains
   * the ioblock and through the final erase block on the FLASH.
   */

  for (eblock = pack.ioblock / volume->blkper;
       eblock < volume->geo.neraseblocks;
       eblock++)
    {
      /* Get the starting block number of the erase block */

      pack.block0 = eblock * volume->blkper;

#ifndef CONFIG_NXFFS_NAND
      /* Read the erase block into the pack buffer.  We need to do this even
       * if we are overwriting the entire block so that we skip over
       * previously marked bad blocks.
       */

      ret = MTD_BREAD(volume->mtd, pack.block0, volume->blkper, volume->pack);
      if (ret < 0)
        {
          fdbg("ERROR: Failed to read erase block %d: %d\n", eblock,-ret);
          goto errout_with_pack;
        }

#else
      /* Read the entire erase block into the pack buffer, one-block-at-a-
       * time.  We need to do this even if we are overwriting the entire
       * block so that (1) we skip over previously marked bad blocks, and
       * (2) we can handle individual block read failures.
       *
       * For most FLASH, a read failure indicates a fatal hardware failure.
       * But for NAND FLASH, the read failure probably indicates a block
       * with uncorrectable bit errors.
       */

      /* Read each I/O block */

      for (i = 0, block = pack.block0, pack.iobuffer = volume->pack;
           i < volume->blkper;
           i++, block++, pack.iobuffer += volume->geo.blocksize)
        {
          /* Read the next block in the erase block */

          ret = MTD_BREAD(volume->mtd, block, 1, pack.iobuffer);
          if (ret < 0)
            {
              /* Force a the block to be an NXFFS bad block */

              fdbg("ERROR: Failed to read block %d: %d\n", block, ret);
              nxffs_blkinit(volume, pack.iobuffer, BLOCK_STATE_BAD);
            }
        }
#endif

      /* Now pack each I/O block */

      for (i = 0, block = pack.block0, pack.iobuffer = volume->pack;
           i < volume->blkper;
           i++, block++, pack.iobuffer += volume->geo.blocksize)
        {
           /* The first time here, the ioblock may point to an offset into
            * the erase block.  We just need to skip over those cases.
            */

           if (block >= pack.ioblock)
              {
                /* Set the I/O position.  Note on the first time we get
                 * pack.iooffset will hold the offset in the first I/O block
                 * to the first inode header.  After that, it will always
                 * refer to the first byte after the block header.
                 */

                pack.ioblock = block;

                /* If this is not a valid block or if we have already
                 * finished packing the valid inode entries, then just fall
                 * through, reset the FLASH memory to the erase state, and
                 * write the reset values to FLASH.  (The first block that
                 * we want to process will always be valid -- we have
                 * already verified that).
                 */

                if (nxffs_packvalid(&pack))
                  {
                    /* Have we finished packing inodes? */

                    if (!packed)
                      {
                         DEBUGASSERT(wrfile == NULL);

                         /* Pack inode data into this block */

                         ret = nxffs_packblock(volume, &pack);
                         if (ret < 0)
                           {
                             /* The error -ENOSPC is a special value that simply
                              * means that there is nothing further to be packed.
                              */

                             if (ret == -ENOSPC)
                               {
                                 packed = true;

                                 /* Writing is performed at the end of the free
                                  * FLASH region and this implemenation is restricted
                                  * to a single writer.  The new inode is not
                                  * written to FLASH until the writer is closed
                                  * and so will not be found by nxffs_packblock().
                                  */

                                 wrfile = nxffs_setupwriter(volume, &pack);
                               }
                             else
                               {
                                 /* Otherwise, something really bad happened */

                                 fdbg("ERROR: Failed to pack into block %d: %d\n",
                                      block, ret);
                                 goto errout_with_pack;
                               }
                           }
                       }

                     /* If all of the "normal" inodes have been packed, then check if
                      * we need to pack the current, in-progress write operation.
                      */

                     if (wrfile)
                       {
                         DEBUGASSERT(packed == true);

                         /* Pack write data into this block */

                         ret = nxffs_packwriter(volume, &pack, wrfile);
                         if (ret < 0)
                           {
                             /* The error -ENOSPC is a special value that simply
                              * means that there is nothing further to be packed.
                              */

                             if (ret == -ENOSPC)
                               {
                                 wrfile = NULL;
                               }
                             else
                               {
                                 /* Otherwise, something really bad happened */

                                 fdbg("ERROR: Failed to pack into block %d: %d\n",
                                      block, ret);
                                 goto errout_with_pack;
                               }
                           }
                       }
                   }

                 /* Set any unused portion at the end of the block to the
                  * erased state.
                  */

                 if (pack.iooffset < volume->geo.blocksize)
                   {
                     memset(&pack.iobuffer[pack.iooffset],
                            CONFIG_NXFFS_ERASEDSTATE,
                            volume->geo.blocksize - pack.iooffset);
                   }

                 /* Next time through the loop, pack.iooffset will point to the
                  * first byte after the block header.
                  */

                 pack.iooffset = SIZEOF_NXFFS_BLOCK_HDR;
              }
         }

      /* We now have an in-memory image of how we want this erase block to
       * appear. Now it is safe to erase the block.
       */

      ret = MTD_ERASE(volume->mtd, eblock, 1);
      if (ret < 0)
        {
          fdbg("ERROR: Failed to erase block %d [%d]: %d\n",
               eblock, pack.block0, -ret);
          goto errout_with_pack;
        }

      /* Write the packed I/O block to FLASH */

      ret = MTD_BWRITE(volume->mtd, pack.block0, volume->blkper, volume->pack);
      if (ret < 0)
        {
          fdbg("ERROR: Failed to write erase block %d [%d]: %d\n",
               eblock, pack.block0, -ret);
          goto errout_with_pack;
        }
    }

errout_with_pack:
  nxffs_freeentry(&pack.src.entry);
  nxffs_freeentry(&pack.dest.entry);
  return ret;
}