summaryrefslogtreecommitdiff
path: root/nuttx/fs/smartfs/smartfs_smart.c
blob: 0b9a373b15091855e756c8fe9ec38fe0c19bb511 (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
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
/****************************************************************************
 * fs/smartfs/smartfs_smart.c
 *
 *   Copyright (C) 2013 Ken Pettit. All rights reserved.
 *   Author: Ken Pettit <pettitkd@gmail.com>
 *
 * 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 <sys/types.h>
#include <sys/stat.h>
#include <sys/statfs.h>

#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <semaphore.h>
#include <assert.h>
#include <fcntl.h>
#include <errno.h>
#include <debug.h>

#include <nuttx/kmalloc.h>
#include <nuttx/fs/fs.h>
#include <nuttx/fs/fat.h>
#include <nuttx/fs/dirent.h>
#include <nuttx/fs/ioctl.h>
#include <nuttx/mtd/mtd.h>
#include <nuttx/fs/smart.h>

#include "smartfs.h"

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

/****************************************************************************
 * Private Types
 ****************************************************************************/

/****************************************************************************
 * Private Function Prototypes
 ****************************************************************************/

static int     smartfs_open(FAR struct file *filep, const char *relpath,
                        int oflags, mode_t mode);
static int     smartfs_close(FAR struct file *filep);
static ssize_t smartfs_read(FAR struct file *filep, char *buffer, size_t buflen);
static ssize_t smartfs_write(FAR struct file *filep, const char *buffer,
                        size_t buflen);
static off_t   smartfs_seek(FAR struct file *filep, off_t offset, int whence);
static int     smartfs_ioctl(FAR struct file *filep, int cmd, unsigned long arg);

static int     smartfs_sync(FAR struct file *filep);
static int     smartfs_dup(FAR const struct file *oldp, FAR struct file *newp);

static int     smartfs_opendir(struct inode *mountpt, const char *relpath,
                        struct fs_dirent_s *dir);
static int     smartfs_readdir(struct inode *mountpt, struct fs_dirent_s *dir);
static int     smartfs_rewinddir(struct inode *mountpt, struct fs_dirent_s *dir);

static int     smartfs_bind(FAR struct inode *blkdriver, const void *data,
                        void **handle);
static int     smartfs_unbind(void *handle, FAR struct inode **blkdriver);
static int     smartfs_statfs(struct inode *mountpt, struct statfs *buf);

static int     smartfs_unlink(struct inode *mountpt, const char *relpath);
static int     smartfs_mkdir(struct inode *mountpt, const char *relpath,
                        mode_t mode);
static int     smartfs_rmdir(struct inode *mountpt, const char *relpath);
static int     smartfs_rename(struct inode *mountpt, const char *oldrelpath,
                        const char *newrelpath);
static int     smartfs_stat(struct inode *mountpt, const char *relpath, struct stat *buf);

static off_t smartfs_seek_internal(struct smartfs_mountpt_s *fs,
                        struct smartfs_ofile_s *sf,
                        off_t offset, int whence);

/****************************************************************************
 * Private Variables
 ****************************************************************************/

static uint8_t  g_seminitialized = FALSE;
static sem_t    g_sem;

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

/* See fs_mount.c -- this structure is explicitly externed there.
 * We use the old-fashioned kind of initializers so that this will compile
 * with any compiler.
 */

const struct mountpt_operations smartfs_operations =
{
  smartfs_open,          /* open */
  smartfs_close,         /* close */
  smartfs_read,          /* read */
  smartfs_write,         /* write */
  smartfs_seek,          /* seek */
  smartfs_ioctl,         /* ioctl */

  smartfs_sync,          /* sync */
  smartfs_dup,           /* dup */

  smartfs_opendir,       /* opendir */
  NULL,                  /* closedir */
  smartfs_readdir,       /* readdir */
  smartfs_rewinddir,     /* rewinddir */

  smartfs_bind,          /* bind */
  smartfs_unbind,        /* unbind */
  smartfs_statfs,        /* statfs */

  smartfs_unlink,        /* unlinke */
  smartfs_mkdir,         /* mkdir */
  smartfs_rmdir,         /* rmdir */
  smartfs_rename,        /* rename */
  smartfs_stat           /* stat */
};

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

/****************************************************************************
 * Name: smartfs_open
 ****************************************************************************/

static int smartfs_open(FAR struct file *filep, const char *relpath,
                        int oflags, mode_t mode)
{
  struct inode             *inode;
  struct smartfs_mountpt_s *fs;
  int                       ret;
  uint16_t                  parentdirsector;
  const char               *filename;
  struct smartfs_ofile_s   *sf;

  /* Sanity checks */

  DEBUGASSERT((filep->f_priv == NULL) && (filep->f_inode != NULL));

  /* Get the mountpoint inode reference from the file structure and the
   * mountpoint private data from the inode structure
   */

  inode = filep->f_inode;
  fs    = inode->i_private;

  DEBUGASSERT(fs != NULL);

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Locate the directory entry for this path */

  sf = (struct smartfs_ofile_s *) kmm_malloc(sizeof *sf);
  if (sf == NULL)
    {
      ret = -ENOMEM;
      goto errout_with_semaphore;
    }

  sf->entry.name = NULL;
  ret = smartfs_finddirentry(fs, &sf->entry, relpath, &parentdirsector,
                             &filename);

  /* Three possibililities: (1) a node exists for the relpath and
   * dirinfo describes the directory entry of the entity, (2) the
   * node does not exist, or (3) some error occurred.
   */

  if (ret == OK)
    {
      /* The name exists -- but is is a file or a directory ? */

      if (sf->entry.flags & SMARTFS_DIRENT_TYPE_DIR)
        {
          /* Can't open a dir as a file! */

          ret = -EISDIR;
          goto errout_with_buffer;
        }

      /* It would be an error if we are asked to create it exclusively */

      if ((oflags & (O_CREAT|O_EXCL)) == (O_CREAT|O_EXCL))
        {
          /* Already exists -- can't create it exclusively */

          ret = -EEXIST;
          goto errout_with_buffer;
        }

      /* TODO: Test open mode based on the file mode */

      /* The file exists.  Check if we are opening it for O_CREAT or
       * O_TRUNC mode and delete the sector chain if we are. */

      if ((oflags & (O_CREAT | O_TRUNC)) != 0)
        {
          /* Don't truncate if open for APPEND */

          if (!(oflags & O_APPEND))
            {
              /* Truncate the file as part of the open */

              ret = smartfs_truncatefile(fs, &sf->entry);
              if (ret < 0)
                {
                  goto errout_with_buffer;
                }
            }
        }
    }
  else if (ret == -ENOENT)
    {
      /* The file does not exist.  Were we asked to create it? */

      if ((oflags & O_CREAT) == 0)
        {
          /* No.. then we fail with -ENOENT */

          ret = -ENOENT;
          goto errout_with_buffer;
        }

      /* Yes... test if the parent directory is valid */

      if (parentdirsector != 0xFFFF)
        {
          /* We can create in the given parent directory */

          ret = smartfs_createentry(fs, parentdirsector, filename,
                                    SMARTFS_DIRENT_TYPE_FILE, mode,
                                    &sf->entry, 0xFFFF);
          if (ret != OK)
            {
              goto errout_with_buffer;
            }
        }
      else
        {
          /* Trying to create in a directory that doesn't exist */

          ret = -ENOENT;
          goto errout_with_buffer;
        }
    }
  else
    {
      goto errout_with_buffer;
    }

  /* Now perform the "open" on the file in direntry */

  sf->oflags = oflags;
  sf->crefs = 1;
  sf->filepos = 0;
  sf->curroffset = sizeof(struct smartfs_chain_header_s);
  sf->currsector = sf->entry.firstsector;
  sf->byteswritten = 0;

  /* Test if we opened for APPEND mode.  If we did, then seek to the
   * end of the file.
   */

  if (oflags & O_APPEND)
    {
      /* Perform the seek */

      smartfs_seek_internal(fs, sf, 0, SEEK_END);
    }

  /* Attach the private date to the struct file instance */

  filep->f_priv = sf;

  /* Then insert the new instance into the mountpoint structure.
   * It needs to be there (1) to handle error conditions that effect
   * all files, and (2) to inform the umount logic that we are busy
   * (but a simple reference count could have done that).
   */

  sf->fnext = fs->fs_head;
  fs->fs_head = sf;

  ret = OK;
  goto errout_with_semaphore;

errout_with_buffer:
  if (sf->entry.name != NULL)
    {
      /* Free the space for the name too */

      kmm_free(sf->entry.name);
      sf->entry.name = NULL;
    }

  kmm_free(sf);

errout_with_semaphore:
  smartfs_semgive(fs);
  if (ret == -EINVAL)
    {
      ret = -EIO;
    }

  return ret;
}

/****************************************************************************
 * Name: smartfs_close
 ****************************************************************************/

static int smartfs_close(FAR struct file *filep)
{
  struct inode             *inode;
  struct smartfs_mountpt_s *fs;
  struct smartfs_ofile_s   *sf;
  struct smartfs_ofile_s   *nextfile;
  struct smartfs_ofile_s   *prevfile;

  /* Sanity checks */

  DEBUGASSERT(filep->f_priv != NULL && filep->f_inode != NULL);

  /* Recover our private data from the struct file instance */

  inode = filep->f_inode;
  fs    = inode->i_private;
  sf    = filep->f_priv;

  /* Sync the file */

  smartfs_sync(filep);

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Check if we are the last one with a reference to the file and
   * only close if we are. */

  if (sf->crefs > 1)
    {
      /* The file is opened more than once.  Just decrement the
       * reference count and return. */

      sf->crefs--;
      goto okout;
    }

  /* Remove ourselves from the linked list */

  nextfile = fs->fs_head;
  prevfile = nextfile;
  while ((nextfile != sf) && (nextfile != NULL))
    {
      /* Save the previous file pointer too */

      prevfile = nextfile;
      nextfile = nextfile->fnext;
    }

  if (nextfile != NULL)
    {
      /* Test if we were the first entry */

      if (nextfile == fs->fs_head)
        {
          /* Assign a new head */

          fs->fs_head = nextfile->fnext;
        }
      else
        {
          /* Take ourselves out of the list */

          prevfile->fnext = nextfile->fnext;
        }
    }

  /* Now free the pointer */

  filep->f_priv = NULL;;
  if (sf->entry.name != NULL)
    {
      /* Free the space for the name too */

      kmm_free(sf->entry.name);
      sf->entry.name = NULL;
    }
  kmm_free(sf);

okout:
  smartfs_semgive(fs);
  return OK;
}

/****************************************************************************
 * Name: smartfs_read
 ****************************************************************************/

static ssize_t smartfs_read(FAR struct file *filep, char *buffer, size_t buflen)
{
  struct inode             *inode;
  struct smartfs_mountpt_s *fs;
  struct smartfs_ofile_s   *sf;
  struct smart_read_write_s readwrite;
  struct smartfs_chain_header_s *header;
  int                       ret = OK;
  uint32_t                  bytesread;
  uint16_t                  bytestoread;
  uint16_t                  bytesinsector;

  /* Sanity checks */

  DEBUGASSERT(filep->f_priv != NULL && filep->f_inode != NULL);

  /* Recover our private data from the struct file instance */

  sf    = filep->f_priv;
  inode = filep->f_inode;
  fs    = inode->i_private;

  DEBUGASSERT(fs != NULL);

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Loop until all byte read or error */

  bytesread = 0;
  while (bytesread != buflen)
    {
      /* Test if we are at the end of data */

      if (sf->currsector == SMARTFS_ERASEDSTATE_16BIT)
        {
          /* Break and return the number of bytes we read (may be zero) */

          break;
        }

      /* Read the curent sector into our buffer */

      readwrite.logsector = sf->currsector;
      readwrite.offset = 0;
      readwrite.buffer = (uint8_t *) fs->fs_rwbuffer;
      readwrite.count = fs->fs_llformat.availbytes;
      ret = FS_IOCTL(fs, BIOC_READSECT, (unsigned long) &readwrite);
      if (ret < 0)
        {
          fdbg("Error %d reading sector %d data\n", ret, sf->currsector);
          goto errout_with_semaphore;
        }

      /* Point header to the read data to get used byte count */

      header = (struct smartfs_chain_header_s *) fs->fs_rwbuffer;

      /* Get number of used bytes in this sector */

      bytesinsector = *((uint16_t *) header->used);
      if (bytesinsector == SMARTFS_ERASEDSTATE_16BIT)
        {
          /* No bytes to read from this sector */

          bytesinsector = 0;
        }

      /* Calculate the number of bytes to read into the buffer */

      bytestoread = bytesinsector - (sf->curroffset -
          sizeof(struct smartfs_chain_header_s));
      if (bytestoread + bytesread > buflen)
        {
          /* Truncate bytesto read based on buffer len */

          bytestoread = buflen - bytesread;
        }

      /* Copy data to the read buffer */

      if (bytestoread > 0)
        {
          /* Do incremental copy from this sector */

          memcpy(&buffer[bytesread], &fs->fs_rwbuffer[sf->curroffset], bytestoread);
          bytesread += bytestoread;
          sf->filepos += bytestoread;
          sf->curroffset += bytestoread;
        }

      /* Test if we are at the end of the data in this sector */

      if ((bytestoread == 0) || (sf->curroffset == fs->fs_llformat.availbytes))
        {
          /* Set the next sector as the current sector */

          sf->currsector = SMARTFS_NEXTSECTOR(header);
          sf->curroffset = sizeof(struct smartfs_chain_header_s);

          /* Test if at end of data */

          if (sf->currsector == SMARTFS_ERASEDSTATE_16BIT)
            {
              /* No more data!  Return what we have */

              break;
            }
        }
    }

  /* Return the number of bytes we read */

  ret = bytesread;

errout_with_semaphore:
  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_sync_internal
 *
 * Description: Synchronize the file state on disk to match internal, in-
 *   memory state.
 *
 ****************************************************************************/

static int smartfs_sync_internal(struct smartfs_mountpt_s *fs,
                                 struct smartfs_ofile_s *sf)
{
  struct smart_read_write_s readwrite;
  struct smartfs_chain_header_s *header;
  int ret = OK;

  /* Test if we have written bytes to the current sector that
   * need to be recorded in the chain header's used bytes field. */

  if (sf->byteswritten > 0)
    {
      fvdbg("Syncing sector %d\n", sf->currsector);

      /* Read the existing sector used bytes value */

      readwrite.logsector = sf->currsector;
      readwrite.offset = 0;
      readwrite.buffer = (uint8_t *) fs->fs_rwbuffer;
      readwrite.count = sizeof(struct smartfs_chain_header_s);
      ret = FS_IOCTL(fs, BIOC_READSECT, (unsigned long) &readwrite);
      if (ret < 0)
        {
          fdbg("Error %d reading sector %d data\n", ret, sf->currsector);
          goto errout;
        }

      /* Add new byteswritten to existing value */

      header = (struct smartfs_chain_header_s *) fs->fs_rwbuffer;
      if (*((uint16_t *) header->used) == SMARTFS_ERASEDSTATE_16BIT)
        {
          *((uint16_t *) header->used) = sf->byteswritten;
        }
      else
        {
          *((uint16_t *) header->used) += sf->byteswritten;
        }

      readwrite.offset = offsetof(struct smartfs_chain_header_s, used);
      readwrite.count = sizeof(uint16_t);
      readwrite.buffer = (uint8_t *) &fs->fs_rwbuffer[readwrite.offset];
      ret = FS_IOCTL(fs, BIOC_WRITESECT, (unsigned long) &readwrite);
      if (ret < 0)
        {
          fdbg("Error %d writing used bytes for sector %d\n", ret, sf->currsector);
          goto errout;
        }

      sf->byteswritten = 0;
    }

errout:
  return ret;
}

/****************************************************************************
 * Name: smartfs_write
 ****************************************************************************/

static ssize_t smartfs_write(FAR struct file *filep, const char *buffer,
                         size_t buflen)
{
  struct inode             *inode;
  struct smartfs_mountpt_s *fs;
  struct smartfs_ofile_s   *sf;
  struct smart_read_write_s readwrite;
  struct smartfs_chain_header_s *header;
  size_t                    byteswritten;
  int                       ret;

  /* Sanity checks.  I have seen the following assertion misfire if
   * CONFIG_DEBUG_MM is enabled while re-directing output to a
   * file.  In this case, the debug output can get generated while
   * the file is being opened,  FAT data structures are being allocated,
   * and things are generally in a perverse state.
   */

#ifdef CONFIG_DEBUG_MM
  if (filep->f_priv == NULL || filep->f_inode == NULL)
    {
      return -ENXIO;
    }
#else
  DEBUGASSERT(filep->f_priv != NULL && filep->f_inode != NULL);
#endif

  /* Recover our private data from the struct file instance */

  sf    = filep->f_priv;
  inode = filep->f_inode;
  fs    = inode->i_private;

  DEBUGASSERT(fs != NULL);

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Test the permissions.  Only allow write if the file was opened with
   * write flags.
   */

  if ((sf->oflags & O_WROK) == 0)
    {
      ret = -EACCES;
      goto errout_with_semaphore;
    }

  /* First test if we are overwriting an existing location or writing to
   * a new one. */

  header = (struct smartfs_chain_header_s *) fs->fs_rwbuffer;
  byteswritten = 0;
  while ((sf->filepos < sf->entry.datlen) && (buflen > 0))
    {
      /* Overwriting data caused by a seek, etc.  In this case, we need
       * to check if the write causes the file length to be extended
       * or not and update it accordingly.  We will write data up to
       * the current end-of-file and then break, allowing the next while
       * loop below to write the additional data to the end of the file.
       */

      readwrite.offset = sf->curroffset;
      readwrite.logsector = sf->currsector;
      readwrite.buffer = (uint8_t *) &buffer[byteswritten];
      readwrite.count = fs->fs_llformat.availbytes - sf->curroffset;

      /* Limit the write based on available data to write */

      if (readwrite.count > buflen)
        readwrite.count = buflen;

      /* Limit the write based on current file length */

      if (readwrite.count > sf->entry.datlen - sf->filepos)
        {
          /* Limit the write length so we write to the current EOF. */

          readwrite.count = sf->entry.datlen - sf->filepos;
        }

      /* Now perform the write. */

      if (readwrite.count > 0)
        {
          ret = FS_IOCTL(fs, BIOC_WRITESECT, (unsigned long) &readwrite);
          if (ret < 0)
            {
              fdbg("Error %d writing sector %d data\n", ret, sf->currsector);
              goto errout_with_semaphore;
            }

          /* Update our control variables */

          sf->filepos += readwrite.count;
          sf->curroffset += readwrite.count;
          buflen -= readwrite.count;
          byteswritten += readwrite.count;
        }

      /* Test if we wrote to the end of the current sector */

      if (sf->curroffset == fs->fs_llformat.availbytes)
        {
          /* Wrote to the end of the sector.  Update to point to the
           * next sector for additional writes.  First read the sector
           * header to get the sector chain info.
           */

          readwrite.offset = 0;
          readwrite.buffer = (uint8_t *) fs->fs_rwbuffer;
          readwrite.count = sizeof(struct smartfs_chain_header_s);
          ret = FS_IOCTL(fs, BIOC_READSECT, (unsigned long) &readwrite);
          if (ret < 0)
            {
              fdbg("Error %d reading sector %d header\n", ret, sf->currsector);
              goto errout_with_semaphore;
            }

          /* Now get the chained sector info and reset the offset */

          sf->curroffset = sizeof(struct smartfs_chain_header_s);
          sf->currsector = SMARTFS_NEXTSECTOR(header);
        }
    }

  /* Now append data to end of the file. */

  while (buflen > 0)
    {
      /* We will fill up the current sector. Write data to
       * the current sector first.
       */

      readwrite.offset = sf->curroffset;
      readwrite.logsector = sf->currsector;
      readwrite.buffer = (uint8_t *) &buffer[byteswritten];
      readwrite.count = fs->fs_llformat.availbytes - sf->curroffset;
      if (readwrite.count > buflen)
        {
          /* Limit the write base on remaining bytes to write */

          readwrite.count = buflen;
        }

      /* Perform the write */

      if (readwrite.count > 0)
        {
          ret = FS_IOCTL(fs, BIOC_WRITESECT, (unsigned long) &readwrite);
          if (ret < 0)
            {
              fdbg("Error %d writing sector %d data\n", ret, sf->currsector);
              goto errout_with_semaphore;
            }

          /* Update our control variables */

          sf->entry.datlen += readwrite.count;
          sf->byteswritten += readwrite.count;
          sf->filepos += readwrite.count;
          sf->curroffset += readwrite.count;
          buflen -= readwrite.count;
          byteswritten += readwrite.count;
        }

      /* Test if we wrote a full sector of data */

      if (sf->curroffset == fs->fs_llformat.availbytes)
        {
          /* Sync the file to write this sector out */

          smartfs_sync_internal(fs, sf);

          /* Allocate a new sector if needed */

          if (buflen > 0)
            {
              /* Allocate a new sector */

              ret = FS_IOCTL(fs, BIOC_ALLOCSECT, 0xFFFF);
              if (ret < 0)
                {
                  fdbg("Error %d allocating new sector\n", ret);
                  goto errout_with_semaphore;
                }

              /* Copy the new sector to the old one and chain it */

              header = (struct smartfs_chain_header_s *) fs->fs_rwbuffer;
              *((uint16_t *) header->nextsector) = (uint16_t) ret;
              readwrite.offset = offsetof(struct smartfs_chain_header_s,
                nextsector);
              readwrite.buffer = (uint8_t *) header->nextsector;
              readwrite.count = sizeof(uint16_t);
              ret = FS_IOCTL(fs, BIOC_WRITESECT, (unsigned long) &readwrite);
              if (ret < 0)
                {
                  fdbg("Error %d writing next sector\n", ret);
                  goto errout_with_semaphore;
                }

              /* Record the new sector in our tracking variables and
               * reset the offset to "zero".
               */

              sf->currsector = SMARTFS_NEXTSECTOR(header);
              sf->curroffset = sizeof(struct smartfs_chain_header_s);
            }
        }
    }

  ret = byteswritten;

errout_with_semaphore:
  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_seek_internal
 *
 * Description: Performs the logic of the seek function.  This is an internal
 *              function because it does not provide semaphore protection and
 *              therefore must be called from one of the other public
 *              interface routines (open, seek, etc.).
 *
 ****************************************************************************/

static off_t smartfs_seek_internal(struct smartfs_mountpt_s *fs,
                                   struct smartfs_ofile_s *sf,
                                   off_t offset, int whence)
{
  struct smart_read_write_s readwrite;
  struct smartfs_chain_header_s *header;
  int                       ret;
  off_t                     newpos;
  off_t                     sectorstartpos;

  /* Test if this is a seek to get the current file pos */

  if ((whence == SEEK_CUR) && (offset == 0))
    {
      return sf->filepos;
    }

  /* Test if we need to sync the file */

  if (sf->byteswritten > 0)
    {
      /* Perform a sync */

      smartfs_sync_internal(fs, sf);
    }

  /* Calculate the file position to seek to based on current position */

  switch (whence)
  {
    case SEEK_SET:
    default:
      newpos = offset;
      break;

    case SEEK_CUR:
      newpos = sf->filepos + offset;
      break;

    case SEEK_END:
      newpos = sf->entry.datlen - offset;
      break;
  }

  /* Ensure newpos is in range */

  if (newpos < 0)
    {
      newpos = 0;
    }

  if (newpos > sf->entry.datlen)
    {
      newpos = sf->entry.datlen;
    }

  /* Now perform the seek.  Test if we are seeking within the current
   * sector and can skip the search to save time.
   */

  sectorstartpos = sf->filepos - (sf->curroffset - sizeof(struct
        smartfs_chain_header_s));
  if (newpos >= sectorstartpos && newpos < sectorstartpos +
      fs->fs_llformat.availbytes - sizeof(struct smartfs_chain_header_s))
    {
      /* Seeking within the current sector.  Just update the offset */

      sf->curroffset = sizeof(struct smartfs_chain_header_s) + newpos-sectorstartpos;
      sf->filepos = newpos;

      return newpos;
    }

  /* Nope, we have to search for the sector and offset.  If the new pos is greater
   * than the current pos, then we can start from the beginning of the current
   * sector, otherwise we have to start from the beginning of the file.
   */

  if (newpos > sf->filepos)
    {
      sf->filepos = sectorstartpos;
    }
  else
    {
      sf->currsector = sf->entry.firstsector;
      sf->filepos = 0;
    }

  header = (struct smartfs_chain_header_s *) fs->fs_rwbuffer;
  while ((sf->currsector != SMARTFS_ERASEDSTATE_16BIT) &&
      (sf->filepos + fs->fs_llformat.availbytes -
      sizeof(struct smartfs_chain_header_s) < newpos))
    {
      /* Read the sector's header */

      readwrite.logsector = sf->currsector;
      readwrite.offset = 0;
      readwrite.count = sizeof(struct smartfs_chain_header_s);
      readwrite.buffer = (uint8_t *) fs->fs_rwbuffer;
      ret = FS_IOCTL(fs, BIOC_READSECT, (unsigned long) &readwrite);
      if (ret < 0)
        {
          fdbg("Error %d reading sector %d header\n", ret, sf->currsector);
          goto errout;
        }

      /* Point to next sector and update filepos */

      sf->currsector = SMARTFS_NEXTSECTOR(header);
      sf->filepos += SMARTFS_USED(header);
    }

  /* Now calculate the offset */

  sf->curroffset = sizeof(struct smartfs_chain_header_s) + newpos - sf->filepos;
  sf->filepos = newpos;
  return newpos;

errout:
  return ret;
}

/****************************************************************************
 * Name: smartfs_seek
 ****************************************************************************/

static off_t smartfs_seek(FAR struct file *filep, off_t offset, int whence)
{
  struct inode             *inode;
  struct smartfs_mountpt_s *fs;
  struct smartfs_ofile_s   *sf;
  int                       ret;

  /* Sanity checks */

  DEBUGASSERT(filep->f_priv != NULL && filep->f_inode != NULL);

  /* Recover our private data from the struct file instance */

  sf    = filep->f_priv;
  inode = filep->f_inode;
  fs    = inode->i_private;

  DEBUGASSERT(fs != NULL);

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Call our internal routine to perform the seek */

  ret = smartfs_seek_internal(fs, sf, offset, whence);

  if (ret >= 0)
    {
      filep->f_pos = ret;
    }

  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_ioctl
 ****************************************************************************/

static int smartfs_ioctl(FAR struct file *filep, int cmd, unsigned long arg)
{
  /* We don't use any ioctls */

  return -ENOSYS;
}

/****************************************************************************
 * Name: smartfs_sync
 *
 * Description: Synchronize the file state on disk to match internal, in-
 *   memory state.
 *
 ****************************************************************************/

static int smartfs_sync(FAR struct file *filep)
{
  struct inode             *inode;
  struct smartfs_mountpt_s *fs;
  struct smartfs_ofile_s   *sf;
  int                       ret;

  /* Sanity checks */

  DEBUGASSERT(filep->f_priv != NULL && filep->f_inode != NULL);

  /* Recover our private data from the struct file instance */

  sf    = filep->f_priv;
  inode = filep->f_inode;
  fs    = inode->i_private;

  DEBUGASSERT(fs != NULL);

  /* Take the semaphore */

  smartfs_semtake(fs);

  ret = smartfs_sync_internal(fs, sf);

  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smart_dup
 *
 * Description: Duplicate open file data in the new file structure.
 *
 ****************************************************************************/

static int smartfs_dup(FAR const struct file *oldp, FAR struct file *newp)
{
  struct smartfs_ofile_s   *sf;

  fvdbg("Dup %p->%p\n", oldp, newp);

  /* Sanity checks */

  DEBUGASSERT(oldp->f_priv != NULL &&
              newp->f_priv == NULL &&
              newp->f_inode != NULL);

  /* Recover our private data from the struct file instance */

  sf    = oldp->f_priv;

  DEBUGASSERT(sf != NULL);

  /* Just increment the reference count on the ofile */

  sf->crefs++;
  newp->f_priv = (FAR void *)sf;

  return OK;
}

/****************************************************************************
 * Name: smartfs_opendir
 *
 * Description: Open a directory for read access
 *
 ****************************************************************************/

static int smartfs_opendir(struct inode *mountpt, const char *relpath, struct fs_dirent_s *dir)
{
  struct smartfs_mountpt_s *fs;
  int                       ret;
  struct smartfs_entry_s    entry;
  uint16_t                  parentdirsector;
  const char               *filename;

  /* Sanity checks */

  DEBUGASSERT(mountpt != NULL && mountpt->i_private != NULL);

  /* Recover our private data from the inode instance */

  fs = mountpt->i_private;

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Search for the path on the volume */

  entry.name = NULL;
  ret = smartfs_finddirentry(fs, &entry, relpath, &parentdirsector,
                             &filename);
  if (ret < 0)
    {
      goto errout_with_semaphore;
    }

  /* Populate our private data in the fs_dirent_s struct */

  dir->u.smartfs.fs_firstsector = entry.firstsector;
  dir->u.smartfs.fs_currsector = entry.firstsector;
  dir->u.smartfs.fs_curroffset = sizeof(struct smartfs_chain_header_s);

  ret = OK;

errout_with_semaphore:
  /* If space for the entry name was allocated, then free it */

  if (entry.name != NULL)
    {
        kmm_free(entry.name);
        entry.name = NULL;
    }

  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_readdir
 *
 * Description: Read the next directory entry
 *
 ****************************************************************************/

static int smartfs_readdir(struct inode *mountpt, struct fs_dirent_s *dir)
{
  struct smartfs_mountpt_s *fs;
  int                   ret;
  uint16_t              entrysize;
  uint16_t              namelen;
  struct                smartfs_chain_header_s *header;
  struct                smart_read_write_s readwrite;
  struct                smartfs_entry_header_s *entry;

  /* Sanity checks */

  DEBUGASSERT(mountpt != NULL && mountpt->i_private != NULL);

  /* Recover our private data from the inode instance */

  fs = mountpt->i_private;

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Read sectors and search entries until one found or no more */

  entrysize = sizeof(struct smartfs_entry_header_s) +
    fs->fs_llformat.namesize;
  while (dir->u.smartfs.fs_currsector != SMARTFS_ERASEDSTATE_16BIT)
    {
      /* Read the logical sector */

      readwrite.logsector = dir->u.smartfs.fs_currsector;
      readwrite.count = fs->fs_llformat.availbytes;
      readwrite.buffer = (uint8_t *)fs->fs_rwbuffer;
      readwrite.offset = 0;
      ret = FS_IOCTL(fs, BIOC_READSECT, (unsigned long) &readwrite);
      if (ret < 0)
        {
          goto errout_with_semaphore;
        }

      /* Now search for entries, starting at curroffset */

      while (dir->u.smartfs.fs_curroffset < ret)
        {
          /* Point to next entry */

          entry = (struct smartfs_entry_header_s *) &fs->fs_rwbuffer[
            dir->u.smartfs.fs_curroffset];

          /* Test if this entry is valid and active */

          if (((entry->flags & SMARTFS_DIRENT_EMPTY) ==
              (SMARTFS_ERASEDSTATE_16BIT & SMARTFS_DIRENT_EMPTY)) ||
              ((entry->flags & SMARTFS_DIRENT_ACTIVE) !=
              (SMARTFS_ERASEDSTATE_16BIT & SMARTFS_DIRENT_ACTIVE)))
            {
              /* This entry isn't valid, skip it */

              dir->u.smartfs.fs_curroffset += entrysize;
              entry = (struct smartfs_entry_header_s *)
                &fs->fs_rwbuffer[dir->u.smartfs.fs_curroffset];

              continue;
            }

          /* Entry found!  Report it */

          if ((entry->flags & SMARTFS_DIRENT_TYPE) == SMARTFS_DIRENT_TYPE_DIR)
            {
              dir->fd_dir.d_type = DTYPE_DIRECTORY;
            }
          else
            {
              dir->fd_dir.d_type = DTYPE_FILE;
            }

          /* Copy the entry name to dirent */

          namelen = fs->fs_llformat.namesize;
          if (namelen > NAME_MAX)
            {
              namelen = NAME_MAX;
            }

          memset(dir->fd_dir.d_name, 0, namelen);
          strncpy(dir->fd_dir.d_name, entry->name, namelen);

          /* Now advance to the next entry */

          dir->u.smartfs.fs_curroffset += entrysize;
          if (dir->u.smartfs.fs_curroffset >= fs->fs_llformat.availbytes)
            {
              /* We advanced past the end of the sector.  Go to next sector */

              dir->u.smartfs.fs_curroffset = sizeof(struct smartfs_chain_header_s);
              header = (struct smartfs_chain_header_s *) fs->fs_rwbuffer;
              dir->u.smartfs.fs_currsector = SMARTFS_NEXTSECTOR(header);
            }

          /* Now exit */

          ret = OK;
          goto errout_with_semaphore;
        }

      /* No more entries in this sector.  Move on to next sector and
       * continue the search.  If no more sectors, then we are all
       * done and will report ENOENT.
       */

      header = (struct smartfs_chain_header_s *) fs->fs_rwbuffer;
      dir->u.smartfs.fs_curroffset = sizeof(struct smartfs_chain_header_s);
      dir->u.smartfs.fs_currsector = SMARTFS_NEXTSECTOR(header);
    }

  /* If we arrive here, then there are no more entries */

  ret = -ENOENT;

errout_with_semaphore:
  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_rewindir
 *
 * Description: Reset directory read to the first entry
 *
 ****************************************************************************/

static int smartfs_rewinddir(struct inode *mountpt, struct fs_dirent_s *dir)
{
  int ret = OK;

  /* Sanity checks */

  DEBUGASSERT(mountpt != NULL && mountpt->i_private != NULL);

  /* Reset the directory to the first entry */

  dir->u.smartfs.fs_currsector = dir->u.smartfs.fs_firstsector;
  dir->u.smartfs.fs_curroffset = sizeof(struct smartfs_chain_header_s);

  return ret;
}

/****************************************************************************
 * Name: smartfs_bind
 *
 * Description: This implements a portion of the mount operation. This
 *  function allocates and initializes the mountpoint private data and
 *  binds the blockdriver inode to the filesystem private data.  The final
 *  binding of the private data (containing the blockdriver) to the
 *  mountpoint is performed by mount().
 *
 ****************************************************************************/

static int smartfs_bind(FAR struct inode *blkdriver, const void *data,
                        void **handle)
{
  struct smartfs_mountpt_s *fs;
  int ret;

  /* Open the block driver */

  if (!blkdriver || !blkdriver->u.i_bops)
    {
      return -ENODEV;
    }

  if (blkdriver->u.i_bops->open &&
      blkdriver->u.i_bops->open(blkdriver) != OK)
    {
      return -ENODEV;
    }

  /* Create an instance of the mountpt state structure */

  fs = (struct smartfs_mountpt_s *)kmm_zalloc(sizeof(struct smartfs_mountpt_s));
  if (!fs)
    {
      return -ENOMEM;
    }

  /* If the global semaphore hasn't been initialized, then
   * initialized it now. */

  fs->fs_sem = &g_sem;
  if (!g_seminitialized)
    {
      sem_init(&g_sem, 0, 0);   /* Initialize the semaphore that controls access */
      g_seminitialized = TRUE;
    }
  else
    {
      /* Take the semaphore for the mount */

      smartfs_semtake(fs);
    }

  /* Initialize the allocated mountpt state structure.  The filesystem is
   * responsible for one reference ont the blkdriver inode and does not
   * have to addref() here (but does have to release in ubind().
   */

  fs->fs_blkdriver = blkdriver;  /* Save the block driver reference */
  fs->fs_head = NULL;

  /* Now perform the mount.  */

  ret = smartfs_mount(fs, true);
  if (ret != 0)
    {
      kmm_free(fs);
      smartfs_semgive(fs);
      return ret;
    }

  *handle = (void*)fs;
  smartfs_semgive(fs);
  return OK;
}

/****************************************************************************
 * Name: smartfs_unbind
 *
 * Description: This implements the filesystem portion of the umount
 *   operation.
 *
 ****************************************************************************/

static int smartfs_unbind(void *handle, FAR struct inode **blkdriver)
{
  struct smartfs_mountpt_s *fs = (struct smartfs_mountpt_s*)handle;
  int ret;

  if (!fs)
    {
      return -EINVAL;
    }

  /* Check if there are sill any files opened on the filesystem. */

  ret = OK; /* Assume success */
  smartfs_semtake(fs);
  if (fs->fs_head != NULL)
    {
      /* We cannot unmount now.. there are open files */

      smartfs_semgive(fs);

      ret = -EBUSY;
    }
  else
    {
       /* Unmount ... close the block driver */

      ret = smartfs_unmount(fs);
    }

  smartfs_semgive(fs);
  kmm_free(fs);

  return ret;
}

/****************************************************************************
 * Name: smartfs_statfs
 *
 * Description: Return filesystem statistics
 *
 ****************************************************************************/

static int smartfs_statfs(struct inode *mountpt, struct statfs *buf)
{
  struct smartfs_mountpt_s *fs;
  int ret;

  /* Sanity checks */

  DEBUGASSERT(mountpt && mountpt->i_private);

  /* Get the mountpoint private data from the inode structure */

  fs = mountpt->i_private;

  smartfs_semtake(fs);

  /* Implement the logic!! */

  memset(buf, 0, sizeof(struct statfs));
  buf->f_type = SMARTFS_MAGIC;

  /* Re-request the low-level format info to update free blocks */

  ret = FS_IOCTL(fs, BIOC_GETFORMAT, (unsigned long) &fs->fs_llformat);

  buf->f_namelen = fs->fs_llformat.namesize;
  buf->f_bsize = fs->fs_llformat.sectorsize;
  buf->f_blocks = fs->fs_llformat.nsectors;
  buf->f_bfree = fs->fs_llformat.nfreesectors;
  buf->f_bavail = fs->fs_llformat.nfreesectors;
  buf->f_files = 0;
  buf->f_ffree = fs->fs_llformat.nfreesectors;

  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_unlink
 *
 * Description: Remove a file
 *
 ****************************************************************************/

static int smartfs_unlink(struct inode *mountpt, const char *relpath)
{
  struct smartfs_mountpt_s *fs;
  int                       ret;
  struct smartfs_entry_s    entry;
  const char               *filename;
  uint16_t                  parentdirsector;

  /* Sanity checks */

  DEBUGASSERT(mountpt && mountpt->i_private);

  /* Get the mountpoint private data from the inode structure */

  fs = mountpt->i_private;

  smartfs_semtake(fs);

  /* Locate the directory entry for this path */

  entry.name = NULL;
  ret = smartfs_finddirentry(fs, &entry, relpath, &parentdirsector,
                             &filename);

  if (ret == OK)
    {
      /* The name exists -- validate it is a file, not a dir */

      if ((entry.flags & SMARTFS_DIRENT_TYPE) == SMARTFS_DIRENT_TYPE_DIR)
        {
          ret = -EISDIR;
          goto errout_with_semaphore;
        }

      /* TODO:  Need to check permissions?  */

      /* Okay, we are clear to delete the file.  Use the deleteentry routine. */

      smartfs_deleteentry(fs, &entry);

    }
  else
    {
      /* Just report the error */

      goto errout_with_semaphore;
    }

  ret = OK;

errout_with_semaphore:
  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_mkdir
 *
 * Description: Create a directory
 *
 ****************************************************************************/

static int smartfs_mkdir(struct inode *mountpt, const char *relpath, mode_t mode)
{
  struct smartfs_mountpt_s *fs;
  int                       ret;
  struct smartfs_entry_s    entry;
  uint16_t                  parentdirsector;
  const char               *filename;

  /* Sanity checks */

  DEBUGASSERT(mountpt && mountpt->i_private);

  /* Get the mountpoint private data from the inode structure */

  fs = mountpt->i_private;

  smartfs_semtake(fs);

  /* Locate the directory entry for this path */

  entry.name = NULL;
  ret = smartfs_finddirentry(fs, &entry, relpath, &parentdirsector,
                             &filename);

  /* Three possibililities: (1) a node exists for the relpath and
   * dirinfo describes the directory entry of the entity, (2) the
   * node does not exist, or (3) some error occurred.
   */

  if (ret == OK)
    {
      /* The name exists -- can't create */

      ret = -EEXIST;
      goto errout_with_semaphore;
    }
  else if (ret == -ENOENT)
    {
      /* It doesn't exist ... we can create it, but only if we have
       * the right permissions and if the parentdirsector is valid. */

      if (parentdirsector == 0xFFFF)
        {
          /* Invalid entry in the path (non-existant dir segment) */

          goto errout_with_semaphore;
        }

      /* Check mode */

      /* Create the directory */

      ret = smartfs_createentry(fs, parentdirsector, filename,
          SMARTFS_DIRENT_TYPE_DIR, mode, &entry, 0xFFFF);
      if (ret != OK)
        {
          goto errout_with_semaphore;
        }

      ret = OK;
    }

errout_with_semaphore:
  if (entry.name != NULL)
    {
      /* Free the filename space allocation */

      kmm_free(entry.name);
      entry.name = NULL;
    }

  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_rmdir
 *
 * Description: Remove a directory
 *
 ****************************************************************************/

int smartfs_rmdir(struct inode *mountpt, const char *relpath)
{
  struct smartfs_mountpt_s *fs;
  int                       ret;
  struct smartfs_entry_s    entry;
  const char               *filename;
  uint16_t                  parentdirsector;

  /* Sanity checks */

  DEBUGASSERT(mountpt && mountpt->i_private);

  /* Get the mountpoint private data from the inode structure */

  fs = mountpt->i_private;

  /* Take the semaphore */

  smartfs_semtake(fs);

  /* Locate the directory entry for this path */

  entry.name = NULL;
  ret = smartfs_finddirentry(fs, &entry, relpath, &parentdirsector,
                             &filename);

  if (ret == OK)
    {
      /* The name exists -- validate it is a dir, not a file */

      if ((entry.flags & SMARTFS_DIRENT_TYPE) == SMARTFS_DIRENT_TYPE_FILE)
        {
          ret = -ENOTDIR;
          goto errout_with_semaphore;
        }

      /* TODO:  Need to check permissions?  */

      /* Check if the directory is emtpy */

      ret = smartfs_countdirentries(fs, &entry);
      if (ret < 0)
        {
          goto errout_with_semaphore;
        }

      /* Only continue if there are zero entries in the directory */

      if (ret != 0)
        {
          ret = -ENOTEMPTY;
          goto errout_with_semaphore;
        }

      /* Okay, we are clear to delete the directory.  Use the deleteentry routine. */

      ret = smartfs_deleteentry(fs, &entry);
      if (ret < 0)
        {
          goto errout_with_semaphore;
        }
    }
  else
    {
      /* Just report the error */

      goto errout_with_semaphore;
    }

  ret = OK;

errout_with_semaphore:
  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_rename
 *
 * Description: Rename a file or directory
 *
 ****************************************************************************/

int smartfs_rename(struct inode *mountpt, const char *oldrelpath,
               const char *newrelpath)
{
  struct smartfs_mountpt_s *fs;
  int                       ret;
  struct smartfs_entry_s    oldentry;
  uint16_t                  oldparentdirsector;
  const char               *oldfilename;
  struct smartfs_entry_s    newentry;
  uint16_t                  newparentdirsector;
  const char               *newfilename;
  mode_t                    mode;
  uint16_t                  type;
  uint16_t                  sector;
  uint16_t                  offset;
  uint16_t                  entrysize;
  struct smartfs_entry_header_s *direntry;
  struct smart_read_write_s readwrite;

  /* Sanity checks */

  DEBUGASSERT(mountpt && mountpt->i_private);

  /* Get the mountpoint private data from the inode structure */

  fs = mountpt->i_private;

  smartfs_semtake(fs);

  /* Search for old entry to validate it exists */

  oldentry.name = NULL;
  newentry.name = NULL;
  ret = smartfs_finddirentry(fs, &oldentry, oldrelpath, &oldparentdirsector,
          &oldfilename);
  if (ret < 0)
    {
      goto errout_with_semaphore;
    }

  /* Search for the new entry and validate it DOESN'T exist, unless we
   * are copying to a directory and keeping the same filename, such as:
   *
   *    mv /mntpoint/somefile.txt /mntpoint/somedir
   *
   * in which case, we need to validate the /mntpoint/somedir/somefile.txt
   * doens't exsit.
   */

  ret = smartfs_finddirentry(fs, &newentry, newrelpath, &newparentdirsector,
          &newfilename);
  if (ret == OK)
    {
      /* Test if it's a file.  If it is, then it's an error */

      if ((newentry.flags & SMARTFS_DIRENT_TYPE) == SMARTFS_DIRENT_TYPE_FILE)
        {
          ret = -EEXIST;
          goto errout_with_semaphore;
        }

      /* Nope, it's a directory.  Now search the directory for oldfilename */

      sector = newentry.firstsector;
      while (sector != SMARTFS_ERASEDSTATE_16BIT)
        {
          /* Read the next sector of diretory entries */

          readwrite.logsector = sector;
          readwrite.offset = 0;
          readwrite.count = fs->fs_llformat.availbytes;
          readwrite.buffer = (uint8_t *) fs->fs_rwbuffer;
          ret = FS_IOCTL(fs, BIOC_READSECT, (unsigned long) &readwrite);
          if (ret < 0)
            {
              fdbg("Error %d reading sector %d data\n", ret, oldentry.dsector);
              goto errout_with_semaphore;
            }

          /* Search for newfilename in this sector */

          offset = sizeof(struct smartfs_chain_header_s);
          entrysize = sizeof(struct smartfs_entry_header_s) + fs->fs_llformat.namesize;
          while (offset + entrysize < fs->fs_llformat.availbytes)
            {
              /* Test the next entry */

              direntry = (struct smartfs_entry_header_s *) &fs->fs_rwbuffer[offset];
              if (((direntry->flags & SMARTFS_DIRENT_EMPTY) ==
                  (SMARTFS_ERASEDSTATE_16BIT & SMARTFS_DIRENT_EMPTY)) ||
                  ((direntry->flags & SMARTFS_DIRENT_ACTIVE) !=
                  (SMARTFS_ERASEDSTATE_16BIT & SMARTFS_DIRENT_ACTIVE)))
                {
                  /* This entry isn't valid, skip it */

                  offset += entrysize;
                  continue;
                }

              /* Test if this entry matches newfilename */

              if (strcmp(newfilename, direntry->name) == 0)
                {
                  /* Uh-oh, looks like the entry already exists */

                  ret = -EEXIST;
                  goto errout_with_semaphore;
                }

              offset += entrysize;
            }

          /* Chain to next sector */

          sector = SMARTFS_NEXTSECTOR(((struct smartfs_chain_header_s *)fs->fs_rwbuffer));
        }

      /* Okay, we will create newfilename in the newentry directory */

      newparentdirsector = newentry.firstsector;
      newfilename = oldfilename;
    }

  /* Test if the new parent directory is valid */

  if (newparentdirsector != 0xFFFF)
    {
      /* We can move to the given parent directory */

      mode = oldentry.flags & SMARTFS_DIRENT_MODE;
      type = oldentry.flags & SMARTFS_DIRENT_TYPE;
      ret = smartfs_createentry(fs, newparentdirsector, newfilename,
                                type, mode, &newentry, oldentry.firstsector);
      if (ret != OK)
        {
          goto errout_with_semaphore;
        }

      /* Now mark the old entry as inactive */

      readwrite.logsector = oldentry.dsector;
      readwrite.offset = 0;
      readwrite.count = fs->fs_llformat.availbytes;
      readwrite.buffer = (uint8_t *) fs->fs_rwbuffer;
      ret = FS_IOCTL(fs, BIOC_READSECT, (unsigned long) &readwrite);
      if (ret < 0)
        {
          fdbg("Error %d reading sector %d data\n", ret, oldentry.dsector);
          goto errout_with_semaphore;
        }

      direntry = (struct smartfs_entry_header_s *) &fs->fs_rwbuffer[oldentry.doffset];
#if CONFIG_SMARTFS_ERASEDSTATE == 0xFF
      direntry->flags &= ~SMARTFS_DIRENT_ACTIVE;
#else
      direntry->flags |= SMARTFS_DIRENT_ACTIVE;
#endif

      /* Now write the updated flags back to the device */

      readwrite.offset = oldentry.doffset;
      readwrite.count = sizeof(direntry->flags);
      readwrite.buffer = (uint8_t *) &direntry->flags;
      ret = FS_IOCTL(fs, BIOC_WRITESECT, (unsigned long) &readwrite);
      if (ret < 0)
        {
          fdbg("Error %d writing flag bytes for sector %d\n", ret, readwrite.logsector);
          goto errout_with_semaphore;
        }
    }
  else
    {
      /* Trying to create in a directory that doesn't exist */

      ret = -ENOENT;
      goto errout_with_semaphore;
    }

  ret = OK;

errout_with_semaphore:
  if (oldentry.name != NULL)
    {
      kmm_free(oldentry.name);
      oldentry.name = NULL;
    }

  if (newentry.name != NULL)
    {
      kmm_free(newentry.name);
      newentry.name = NULL;
    }

  smartfs_semgive(fs);
  return ret;
}

/****************************************************************************
 * Name: smartfs_stat
 *
 * Description: Return information about a file or directory
 *
 ****************************************************************************/

static int smartfs_stat(struct inode *mountpt, const char *relpath, struct stat *buf)
{
  struct smartfs_mountpt_s *fs;
  struct smartfs_entry_s    entry;
  int                       ret;
  uint16_t                  parentdirsector;
  const char               *filename;

  /* Sanity checks */

  DEBUGASSERT(mountpt && mountpt->i_private);

  /* Get the mountpoint private data from the inode structure */

  fs = mountpt->i_private;

  smartfs_semtake(fs);

  /* Find the directory entry corresponding to relpath */

  entry.name = NULL;
  ret = smartfs_finddirentry(fs, &entry, relpath, &parentdirsector,
                             &filename);
  if (ret < 0)
    {
      goto errout_with_semaphore;
    }

  /* Initialize the stat structure */

  memset(buf, 0, sizeof(struct stat));
  if (entry.firstsector == fs->fs_rootsector)
    {
      /* It's directory name of the mount point */

      buf->st_mode = S_IFDIR|S_IROTH|S_IRGRP|S_IRUSR|S_IWOTH|S_IWGRP|S_IWUSR;
      ret = OK;
      goto errout_with_semaphore;
    }

  buf->st_mode = entry.flags & 0xFFF;
  if ((entry.flags & SMARTFS_DIRENT_TYPE) == SMARTFS_DIRENT_TYPE_DIR)
    {
      buf->st_mode |= S_IFDIR;
    }
  else
    {
      buf->st_mode |= S_IFREG;
    }

  buf->st_size      = entry.datlen;
  buf->st_blksize   = fs->fs_llformat.availbytes;
  buf->st_blocks    = (buf->st_size + buf->st_blksize - 1) / buf->st_blksize;
  buf->st_atime     = 0;
  buf->st_ctime     = 0;

  ret = OK;

errout_with_semaphore:
  if (entry.name != NULL)
    {
      kmm_free(entry.name);
      entry.name = NULL;
    }

  smartfs_semgive(fs);
  return ret;
}

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