[Feature]add MT2731_MP2_MR2_SVN388 baseline version

Change-Id: Ief04314834b31e27effab435d3ca8ba33b499059
diff --git a/src/bsp/lk/lib/fs/debug.c b/src/bsp/lk/lib/fs/debug.c
new file mode 100644
index 0000000..729f96c
--- /dev/null
+++ b/src/bsp/lk/lib/fs/debug.c
@@ -0,0 +1,254 @@
+/*
+ * Copyright (c) 2009 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#include <debug.h>
+#include <string.h>
+#include <lib/console.h>
+#include <lib/fs.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <platform.h>
+#include <err.h>
+
+static void test_normalize(const char *in)
+{
+    char path[1024];
+
+    strlcpy(path, in, sizeof(path));
+    fs_normalize_path(path);
+    printf("'%s' -> '%s'\n", in, path);
+}
+
+#if 0
+test_normalize("/");
+test_normalize("/test");
+test_normalize("/test/");
+test_normalize("test/");
+test_normalize("test");
+test_normalize("/test//");
+test_normalize("/test/foo");
+test_normalize("/test/foo/");
+test_normalize("/test/foo/bar");
+test_normalize("/test/foo/bar//");
+test_normalize("/test//foo/bar//");
+test_normalize("/test//./foo/bar//");
+test_normalize("/test//./.foo/bar//");
+test_normalize("/test//./..foo/bar//");
+test_normalize("/test//./../foo/bar//");
+test_normalize("/test/../foo");
+test_normalize("/test/bar/../foo");
+test_normalize("../foo");
+test_normalize("../foo/");
+test_normalize("/../foo");
+test_normalize("/../foo/");
+test_normalize("/../../foo");
+test_normalize("/bleh/../../foo");
+test_normalize("/bleh/bar/../../foo");
+test_normalize("/bleh/bar/../../foo/..");
+test_normalize("/bleh/bar/../../foo/../meh");
+#endif
+
+#if defined(WITH_LIB_CONSOLE)
+
+#if LK_DEBUGLEVEL > 1
+static int cmd_fs(int argc, const cmd_args *argv);
+
+STATIC_COMMAND_START
+STATIC_COMMAND("fs", "fs debug commands", &cmd_fs)
+STATIC_COMMAND_END(fs);
+
+extern int fs_mount_type(const char *path, const char *device, const char *name);
+
+static int cmd_fs_ioctl(int argc, const cmd_args *argv)
+{
+    if (argc < 3) {
+        printf("not enough arguments\n");
+        return ERR_INVALID_ARGS;
+    }
+
+    int request = argv[2].u;
+
+    switch (request) {
+        case FS_IOCTL_GET_FILE_ADDR: {
+            if (argc < 4) {
+                printf("%s %s %lu <path>\n", argv[0].str, argv[1].str,
+                       argv[2].u);
+                return ERR_INVALID_ARGS;
+            }
+
+            int err;
+            filehandle *handle;
+            err = fs_open_file(argv[3].str, &handle);
+            if (err != NO_ERROR) {
+                printf("error %d opening file\n", err);
+                return err;
+            }
+
+            void *file_addr;
+            err = fs_file_ioctl(handle, request, &file_addr);
+            if (err != NO_ERROR) {
+                fs_close_file(handle);
+                return err;
+            }
+
+            printf("%s is mapped at %p\n", argv[3].str, file_addr);
+
+            return fs_close_file(handle);
+            break;
+        }
+        default: {
+            printf("error, unsupported ioctl: %d\n", request);
+        }
+    }
+
+    return ERR_NOT_SUPPORTED;
+}
+
+static int cmd_fs(int argc, const cmd_args *argv)
+{
+    int rc = 0;
+
+    if (argc < 2) {
+notenoughargs:
+        printf("not enough arguments:\n");
+usage:
+        printf("%s mount <path> <type> [device]\n", argv[0].str);
+        printf("%s unmount <path>\n", argv[0].str);
+        printf("%s write <path> <string> [<offset>]\n", argv[0].str);
+        printf("%s format <type> [device]\n", argv[0].str);
+        printf("%s stat <path>\n", argv[0].str);
+        printf("%s ioctl <request> [args...]\n", argv[0].str);
+        return -1;
+    }
+
+    if (!strcmp(argv[1].str, "mount")) {
+        int err;
+
+        if (argc < 4)
+            goto notenoughargs;
+
+        err = fs_mount(argv[2].str, argv[3].str,
+                       (argc >= 5) ? argv[4].str : NULL);
+
+        if (err < 0) {
+            printf("error %d mounting device\n", err);
+            return err;
+        }
+    } else if (!strcmp(argv[1].str, "unmount")) {
+        int err;
+
+        if (argc < 3)
+            goto notenoughargs;
+
+        err = fs_unmount(argv[2].str);
+        if (err < 0) {
+            printf("error %d unmounting device\n", err);
+            return err;
+        }
+    } else if (!strcmp(argv[1].str, "format")) {
+        int err;
+
+        if (argc < 3) {
+            goto notenoughargs;
+        }
+
+        err = fs_format_device(
+                  argv[2].str,
+                  (argc >= 4) ? argv[3].str : NULL,
+                  NULL
+              );
+
+        if (err != NO_ERROR) {
+            printf("error %d formatting device\n", err);
+            return err;
+        }
+
+    } else if (!strcmp(argv[1].str, "stat")) {
+        int err;
+
+        if (argc < 3) {
+            goto notenoughargs;
+        }
+
+        struct fs_stat stat;
+        err = fs_stat_fs(argv[2].str, &stat);
+
+        if (err != NO_ERROR) {
+            printf("error %d statting filesystem\n", err);
+            return err;
+        }
+
+        printf("\ttotal bytes: %llu\n", stat.total_space);
+        printf("\tfree bytes: %llu\n", stat.free_space);
+        printf("\n");
+        printf("\ttotal inodes: %d\n", stat.total_inodes);
+        printf("\tfree inodes: %d\n", stat.free_inodes);
+
+    } else if (!strcmp(argv[1].str, "ioctl")) {
+        return cmd_fs_ioctl(argc, argv);
+    } else if (!strcmp(argv[1].str, "write")) {
+        int err;
+        off_t off;
+        filehandle *handle;
+        struct file_stat stat;
+
+        if (argc < 3)
+            goto notenoughargs;
+
+        err = fs_open_file(argv[2].str, &handle);
+        if (err < 0) {
+            printf("error %d opening file\n", err);
+            return err;
+        }
+
+        err = fs_stat_file(handle, &stat);
+        if (err < 0) {
+            printf("error %d stat'ing file\n", err);
+            fs_close_file(handle);
+            return err;
+        }
+
+        if (argc < 5)
+            off = stat.size;
+        else
+            off = argv[4].u;
+
+        err = fs_write_file(handle, argv[3].str, off, strlen(argv[3].str));
+        if (err < 0) {
+            printf("error %d writing file\n", err);
+            fs_close_file(handle);
+            return err;
+        }
+
+        fs_close_file(handle);
+    } else {
+        printf("unrecognized subcommand\n");
+        goto usage;
+    }
+
+    return rc;
+}
+
+#endif
+
+#endif
+
diff --git a/src/bsp/lk/lib/fs/ext2/dir.c b/src/bsp/lk/lib/fs/ext2/dir.c
new file mode 100644
index 0000000..6a48c50
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/dir.c
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 2007 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#include <string.h>
+#include <stdlib.h>
+#include <debug.h>
+#include <trace.h>
+#include <err.h>
+#include "ext2_priv.h"
+
+#define LOCAL_TRACE 0
+
+/* read in the dir, look for the entry */
+static int ext2_dir_lookup(ext2_t *ext2, struct ext2_inode *dir_inode, const char *name, inodenum_t *inum)
+{
+    uint file_blocknum;
+    int err;
+    uint8_t *buf;
+    size_t namelen = strlen(name);
+
+    if (!S_ISDIR(dir_inode->i_mode))
+        return ERR_NOT_DIR;
+
+    buf = malloc(EXT2_BLOCK_SIZE(ext2->sb));
+
+    file_blocknum = 0;
+    for (;;) {
+        /* read in the offset */
+        err = ext2_read_inode(ext2, dir_inode, buf, file_blocknum * EXT2_BLOCK_SIZE(ext2->sb), EXT2_BLOCK_SIZE(ext2->sb));
+        if (err <= 0) {
+            free(buf);
+            return -1;
+        }
+
+        /* walk through the directory entries, looking for the one that matches */
+        struct ext2_dir_entry_2 *ent;
+        uint pos = 0;
+        while (pos < EXT2_BLOCK_SIZE(ext2->sb)) {
+            ent = (struct ext2_dir_entry_2 *)&buf[pos];
+
+            LTRACEF("ent %d:%d: inode 0x%x, reclen %d, namelen %d\n",
+                    file_blocknum, pos, LE32(ent->inode), LE16(ent->rec_len), ent->name_len/* , ent->name*/);
+
+            /* sanity check the record length */
+            if (LE16(ent->rec_len) == 0)
+                break;
+
+            if (ent->name_len == namelen && memcmp(name, ent->name, ent->name_len) == 0) {
+                // match
+                *inum = LE32(ent->inode);
+                LTRACEF("match: inode %d\n", *inum);
+                free(buf);
+                return 1;
+            }
+
+            pos += ROUNDUP(LE16(ent->rec_len), 4);
+        }
+
+        file_blocknum++;
+
+        /* sanity check the directory. 4MB should be enough */
+        if (file_blocknum > 1024) {
+            free(buf);
+            return -1;
+        }
+    }
+}
+
+/* note, trashes path */
+static int ext2_walk(ext2_t *ext2, char *path, struct ext2_inode *start_inode, inodenum_t *inum, int recurse)
+{
+    char *ptr;
+    struct ext2_inode inode;
+    struct ext2_inode dir_inode;
+    int err;
+    bool done;
+
+    LTRACEF("path '%s', start_inode %p, inum %p, recurse %d\n", path, start_inode, inum, recurse);
+
+    if (recurse > 4)
+        return ERR_RECURSE_TOO_DEEP;
+
+    /* chew up leading slashes */
+    ptr = &path[0];
+    while (*ptr == '/')
+        ptr++;
+
+    done = false;
+    memcpy(&dir_inode, start_inode, sizeof(struct ext2_inode));
+    while (!done) {
+        /* process the first component */
+        char *next_sep = strchr(ptr, '/');
+        if (next_sep) {
+            /* terminate the next component, giving us a substring */
+            *next_sep = 0;
+        } else {
+            /* this is the last component */
+            done = true;
+        }
+
+        LTRACEF("component '%s', done %d\n", ptr, done);
+
+        /* do the lookup on this component */
+        err = ext2_dir_lookup(ext2, &dir_inode, ptr, inum);
+        if (err < 0)
+            return err;
+
+nextcomponent:
+        LTRACEF("inum %u\n", *inum);
+
+        /* load the next inode */
+        err = ext2_load_inode(ext2, *inum, &inode);
+        if (err < 0)
+            return err;
+
+        /* is it a symlink? */
+        if (S_ISLNK(inode.i_mode)) {
+            char link[512];
+
+            LTRACEF("hit symlink\n");
+
+            err = ext2_read_link(ext2, &inode, link, sizeof(link));
+            if (err < 0)
+                return err;
+
+            LTRACEF("symlink read returns %d '%s'\n", err, link);
+
+            /* recurse, parsing the link */
+            if (link[0] == '/') {
+                /* link starts with '/', so start over again at the rootfs */
+                err = ext2_walk(ext2, link, &ext2->root_inode, inum, recurse + 1);
+            } else {
+                err = ext2_walk(ext2, link, &dir_inode, inum, recurse + 1);
+            }
+
+            LTRACEF("recursive walk returns %d\n", err);
+
+            if (err < 0)
+                return err;
+
+            /* if we weren't done with our path parsing, start again with the result of this recurse */
+            if (!done) {
+                goto nextcomponent;
+            }
+        } else if (S_ISDIR(inode.i_mode)) {
+            /* for the next cycle, point the dir inode at our new directory */
+            memcpy(&dir_inode, &inode, sizeof(struct ext2_inode));
+        } else {
+            if (!done) {
+                /* we aren't done and this walked over a nondir, abort */
+                LTRACEF("not finished and component is nondir\n");
+                return ERR_NOT_FOUND;
+            }
+        }
+
+        if (!done) {
+            /* move to the next seperator */
+            ptr = next_sep + 1;
+
+            /* consume multiple seperators */
+            while (*ptr == '/')
+                ptr++;
+        }
+    }
+
+    return 0;
+}
+
+/* do a path parse, looking up each component */
+int ext2_lookup(ext2_t *ext2, const char *_path, inodenum_t *inum)
+{
+    LTRACEF("path '%s', inum %p\n", _path, inum);
+
+    char path[512];
+    strlcpy(path, _path, sizeof(path));
+
+    return ext2_walk(ext2, path, &ext2->root_inode, inum, 1);
+}
+
diff --git a/src/bsp/lk/lib/fs/ext2/ext2.c b/src/bsp/lk/lib/fs/ext2/ext2.c
new file mode 100644
index 0000000..5c0261b
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/ext2.c
@@ -0,0 +1,275 @@
+/*
+ * Copyright (c) 2007-2015 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <debug.h>
+#include <err.h>
+#include <trace.h>
+#include <lk/init.h>
+#include <lib/fs.h>
+#include "ext2_priv.h"
+
+#define LOCAL_TRACE 0
+
+static void endian_swap_superblock(struct ext2_super_block *sb)
+{
+    LE32SWAP(sb->s_inodes_count);
+    LE32SWAP(sb->s_blocks_count);
+    LE32SWAP(sb->s_r_blocks_count);
+    LE32SWAP(sb->s_free_blocks_count);
+    LE32SWAP(sb->s_free_inodes_count);
+    LE32SWAP(sb->s_first_data_block);
+    LE32SWAP(sb->s_log_block_size);
+    LE32SWAP(sb->s_log_frag_size);
+    LE32SWAP(sb->s_blocks_per_group);
+    LE32SWAP(sb->s_frags_per_group);
+    LE32SWAP(sb->s_inodes_per_group);
+    LE32SWAP(sb->s_mtime);
+    LE32SWAP(sb->s_wtime);
+    LE16SWAP(sb->s_mnt_count);
+    LE16SWAP(sb->s_max_mnt_count);
+    LE16SWAP(sb->s_magic);
+    LE16SWAP(sb->s_state);
+    LE16SWAP(sb->s_errors);
+    LE16SWAP(sb->s_minor_rev_level);
+    LE32SWAP(sb->s_lastcheck);
+    LE32SWAP(sb->s_checkinterval);
+    LE32SWAP(sb->s_creator_os);
+    LE32SWAP(sb->s_rev_level);
+    LE16SWAP(sb->s_def_resuid);
+    LE16SWAP(sb->s_def_resgid);
+    LE32SWAP(sb->s_first_ino);
+    LE16SWAP(sb->s_inode_size);
+    LE16SWAP(sb->s_block_group_nr);
+    LE32SWAP(sb->s_feature_compat);
+    LE32SWAP(sb->s_feature_incompat);
+    LE32SWAP(sb->s_feature_ro_compat);
+    LE32SWAP(sb->s_algorithm_usage_bitmap);
+
+    /* ext3 journal stuff */
+    LE32SWAP(sb->s_journal_inum);
+    LE32SWAP(sb->s_journal_dev);
+    LE32SWAP(sb->s_last_orphan);
+    LE32SWAP(sb->s_default_mount_opts);
+    LE32SWAP(sb->s_first_meta_bg);
+}
+
+static void endian_swap_inode(struct ext2_inode *inode)
+{
+    LE16SWAP(inode->i_mode);
+    LE16SWAP(inode->i_uid_low);
+    LE32SWAP(inode->i_size);
+    LE32SWAP(inode->i_atime);
+    LE32SWAP(inode->i_ctime);
+    LE32SWAP(inode->i_mtime);
+    LE32SWAP(inode->i_dtime);
+    LE16SWAP(inode->i_gid_low);
+    LE16SWAP(inode->i_links_count);
+    LE32SWAP(inode->i_blocks);
+    LE32SWAP(inode->i_flags);
+
+    // leave block pointers/symlink data alone
+
+    LE32SWAP(inode->i_generation);
+    LE32SWAP(inode->i_file_acl);
+    LE32SWAP(inode->i_dir_acl);
+    LE32SWAP(inode->i_faddr);
+
+    LE16SWAP(inode->i_uid_high);
+    LE16SWAP(inode->i_gid_high);
+}
+
+static void endian_swap_group_desc(struct ext2_group_desc *gd)
+{
+    LE32SWAP(gd->bg_block_bitmap);
+    LE32SWAP(gd->bg_inode_bitmap);
+    LE32SWAP(gd->bg_inode_table);
+    LE16SWAP(gd->bg_free_blocks_count);
+    LE16SWAP(gd->bg_free_inodes_count);
+    LE16SWAP(gd->bg_used_dirs_count);
+}
+
+status_t ext2_mount(bdev_t *dev, fscookie **cookie)
+{
+    int err;
+
+    LTRACEF("dev %p\n", dev);
+
+    if (!dev)
+        return ERR_NOT_FOUND;
+
+    ext2_t *ext2 = malloc(sizeof(ext2_t));
+    ext2->dev = dev;
+
+    err = bio_read(dev, &ext2->sb, 1024, sizeof(struct ext2_super_block));
+    if (err < 0)
+        goto err;
+
+    endian_swap_superblock(&ext2->sb);
+
+    /* see if the superblock is good */
+    if (ext2->sb.s_magic != EXT2_SUPER_MAGIC) {
+        err = -1;
+        return err;
+    }
+
+    /* calculate group count, rounded up */
+    ext2->s_group_count = (ext2->sb.s_blocks_count + ext2->sb.s_blocks_per_group - 1) / ext2->sb.s_blocks_per_group;
+
+    /* print some info */
+    LTRACEF("rev level %d\n", ext2->sb.s_rev_level);
+    LTRACEF("compat features 0x%x\n", ext2->sb.s_feature_compat);
+    LTRACEF("incompat features 0x%x\n", ext2->sb.s_feature_incompat);
+    LTRACEF("ro compat features 0x%x\n", ext2->sb.s_feature_ro_compat);
+    LTRACEF("block size %d\n", EXT2_BLOCK_SIZE(ext2->sb));
+    LTRACEF("inode size %d\n", EXT2_INODE_SIZE(ext2->sb));
+    LTRACEF("block count %d\n", ext2->sb.s_blocks_count);
+    LTRACEF("blocks per group %d\n", ext2->sb.s_blocks_per_group);
+    LTRACEF("group count %d\n", ext2->s_group_count);
+    LTRACEF("inodes per group %d\n", ext2->sb.s_inodes_per_group);
+
+    /* we only support dynamic revs */
+    if (ext2->sb.s_rev_level > EXT2_DYNAMIC_REV) {
+        err = -2;
+        return err;
+    }
+
+    /* make sure it doesn't have any ro features we don't support */
+    if (ext2->sb.s_feature_ro_compat & ~(EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER|EXT2_FEATURE_RO_COMPAT_LARGE_FILE)) {
+        err = -3;
+        return err;
+    }
+
+    /* read in all the group descriptors */
+    ext2->gd = malloc(sizeof(struct ext2_group_desc) * ext2->s_group_count);
+    err = bio_read(ext2->dev, (void *)ext2->gd,
+                   (EXT2_BLOCK_SIZE(ext2->sb) == 4096) ? 4096 : 2048,
+                   sizeof(struct ext2_group_desc) * ext2->s_group_count);
+    if (err < 0) {
+        err = -4;
+        return err;
+    }
+
+    int i;
+    for (i=0; i < ext2->s_group_count; i++) {
+        endian_swap_group_desc(&ext2->gd[i]);
+        LTRACEF("group %d:\n", i);
+        LTRACEF("\tblock bitmap %d\n", ext2->gd[i].bg_block_bitmap);
+        LTRACEF("\tinode bitmap %d\n", ext2->gd[i].bg_inode_bitmap);
+        LTRACEF("\tinode table %d\n", ext2->gd[i].bg_inode_table);
+        LTRACEF("\tfree blocks %d\n", ext2->gd[i].bg_free_blocks_count);
+        LTRACEF("\tfree inodes %d\n", ext2->gd[i].bg_free_inodes_count);
+        LTRACEF("\tused dirs %d\n", ext2->gd[i].bg_used_dirs_count);
+    }
+
+    /* initialize the block cache */
+    ext2->cache = bcache_create(ext2->dev, EXT2_BLOCK_SIZE(ext2->sb), 4);
+
+    /* load the first inode */
+    err = ext2_load_inode(ext2, EXT2_ROOT_INO, &ext2->root_inode);
+    if (err < 0)
+        goto err;
+
+//  TRACE("successfully mounted volume\n");
+
+    *cookie = (fscookie *)ext2;
+
+    return 0;
+
+err:
+    LTRACEF("exiting with err code %d\n", err);
+
+    free(ext2);
+    return err;
+}
+
+status_t ext2_unmount(fscookie *cookie)
+{
+    // free it up
+    ext2_t *ext2 = (ext2_t *)cookie;
+
+    bcache_destroy(ext2->cache);
+    free(ext2->gd);
+    free(ext2);
+
+    return 0;
+}
+
+static void get_inode_addr(ext2_t *ext2, inodenum_t num, blocknum_t *block, size_t *block_offset)
+{
+    num--;
+
+    uint32_t group = num / ext2->sb.s_inodes_per_group;
+
+    // calculate the start of the inode table for the group it's in
+    *block = ext2->gd[group].bg_inode_table;
+
+    // add the offset of the inode within the group
+    size_t offset = (num % EXT2_INODES_PER_GROUP(ext2->sb)) * EXT2_INODE_SIZE(ext2->sb);
+    *block_offset = offset % EXT2_BLOCK_SIZE(ext2->sb);
+    *block += offset / EXT2_BLOCK_SIZE(ext2->sb);
+}
+
+int ext2_load_inode(ext2_t *ext2, inodenum_t num, struct ext2_inode *inode)
+{
+    int err;
+
+    LTRACEF("num %d, inode %p\n", num, inode);
+
+    blocknum_t bnum;
+    size_t block_offset;
+    get_inode_addr(ext2, num, &bnum, &block_offset);
+
+    LTRACEF("bnum %u, offset %zd\n", bnum, block_offset);
+
+    /* get a pointer to the cache block */
+    void *cache_ptr;
+    err = bcache_get_block(ext2->cache, &cache_ptr, bnum);
+    if (err < 0)
+        return err;
+
+    /* copy the inode out */
+    memcpy(inode, (uint8_t *)cache_ptr + block_offset, sizeof(struct ext2_inode));
+
+    /* put the cache block */
+    bcache_put_block(ext2->cache, bnum);
+
+    /* endian swap it */
+    endian_swap_inode(inode);
+
+    LTRACEF("read inode: mode 0x%x, size %d\n", inode->i_mode, inode->i_size);
+
+    return 0;
+}
+
+static const struct fs_api ext2_api = {
+    .mount = ext2_mount,
+    .unmount = ext2_unmount,
+    .open = ext2_open_file,
+    .stat = ext2_stat_file,
+    .read = ext2_read_file,
+    .close = ext2_close_file,
+};
+
+STATIC_FS_IMPL(ext2, &ext2_api);
diff --git a/src/bsp/lk/lib/fs/ext2/ext2_fs.h b/src/bsp/lk/lib/fs/ext2/ext2_fs.h
new file mode 100644
index 0000000..c06f456
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/ext2_fs.h
@@ -0,0 +1,435 @@
+/*
+ *  linux/include/linux/ext2_fs.h
+ *
+ * Copyright (C) 1992, 1993, 1994, 1995
+ * Remy Card (card@masi.ibp.fr)
+ * Laboratoire MASI - Institut Blaise Pascal
+ * Universite Pierre et Marie Curie (Paris VI)
+ *
+ *  from
+ *
+ *  linux/include/linux/minix_fs.h
+ *
+ *  Copyright (C) 1991, 1992  Linus Torvalds
+ */
+
+#ifndef _LINUX_EXT2_FS_H
+#define _LINUX_EXT2_FS_H
+
+#include <sys/types.h>
+#include <stdint.h>
+
+//#include <linux/types.h>
+//#include <linux/magic.h>
+
+/*
+ * The second extended filesystem constants/structures
+ */
+
+/*
+ * Special inode numbers
+ */
+#define EXT2_BAD_INO         1  /* Bad blocks inode */
+#define EXT2_ROOT_INO        2  /* Root inode */
+#define EXT2_BOOT_LOADER_INO     5  /* Boot loader inode */
+#define EXT2_UNDEL_DIR_INO   6  /* Undelete directory inode */
+
+/* First non-reserved inode for old ext2 filesystems */
+#define EXT2_GOOD_OLD_FIRST_INO 11
+
+/*
+ * Maximal count of links to a file
+ */
+#define EXT2_LINK_MAX       32000
+
+/*
+ * Macro-instructions used to manage several block sizes
+ */
+#define EXT2_MIN_BLOCK_SIZE     1024
+#define EXT2_MAX_BLOCK_SIZE     4096
+#define EXT2_MIN_BLOCK_LOG_SIZE       10
+#define EXT2_BLOCK_SIZE(s)      ((uint32_t)EXT2_MIN_BLOCK_SIZE << (s).s_log_block_size)
+#define EXT2_ADDR_PER_BLOCK(s)      (EXT2_BLOCK_SIZE(s) / sizeof (uint32_t))
+#define EXT2_BLOCK_SIZE_BITS(s) ((s).s_log_block_size + 10)
+#define EXT2_INODE_SIZE(s)  (((s).s_rev_level == EXT2_GOOD_OLD_REV) ? \
+                 EXT2_GOOD_OLD_INODE_SIZE : \
+                 (s).s_inode_size)
+#define EXT2_FIRST_INO(s)   (((s).s_rev_level == EXT2_GOOD_OLD_REV) ? \
+                 EXT2_GOOD_OLD_FIRST_INO : \
+                 (s).s_first_ino)
+
+/*
+ * Macro-instructions used to manage fragments
+ */
+#define EXT2_MIN_FRAG_SIZE      1024
+#define EXT2_MAX_FRAG_SIZE      4096
+#define EXT2_MIN_FRAG_LOG_SIZE        10
+#define EXT2_FRAG_SIZE(s)       (EXT2_MIN_FRAG_SIZE << (s).s_log_frag_size)
+#define EXT2_FRAGS_PER_BLOCK(s) (EXT2_BLOCK_SIZE(s) / EXT2_FRAG_SIZE(s))
+
+/*
+ * Structure of a blocks group descriptor
+ */
+struct ext2_group_desc {
+    uint32_t    bg_block_bitmap;        /* Blocks bitmap block */
+    uint32_t    bg_inode_bitmap;        /* Inodes bitmap block */
+    uint32_t    bg_inode_table;     /* Inodes table block */
+    uint16_t    bg_free_blocks_count;   /* Free blocks count */
+    uint16_t    bg_free_inodes_count;   /* Free inodes count */
+    uint16_t    bg_used_dirs_count; /* Directories count */
+    uint16_t    bg_pad;
+    uint32_t    bg_reserved[3];
+};
+
+/*
+ * Macro-instructions used to manage group descriptors
+ */
+#define EXT2_BLOCKS_PER_GROUP(s)    ((s).s_blocks_per_group)
+#define EXT2_DESC_PER_BLOCK(s)      (EXT2_BLOCK_SIZE(s) / sizeof (struct ext2_group_desc))
+#define EXT2_INODES_PER_GROUP(s)    ((s).s_inodes_per_group)
+
+/*
+ * Constants relative to the data blocks
+ */
+#define EXT2_NDIR_BLOCKS        12
+#define EXT2_IND_BLOCK          EXT2_NDIR_BLOCKS
+#define EXT2_DIND_BLOCK         (EXT2_IND_BLOCK + 1)
+#define EXT2_TIND_BLOCK         (EXT2_DIND_BLOCK + 1)
+#define EXT2_N_BLOCKS           (EXT2_TIND_BLOCK + 1)
+
+/*
+ * Structure of an inode on the disk
+ */
+struct ext2_inode {
+    uint16_t    i_mode;     /* File mode */
+    uint16_t    i_uid;      /* Low 16 bits of Owner Uid */
+    uint32_t    i_size;     /* Size in bytes */
+    uint32_t    i_atime;    /* Access time */
+    uint32_t    i_ctime;    /* Creation time */
+    uint32_t    i_mtime;    /* Modification time */
+    uint32_t    i_dtime;    /* Deletion Time */
+    uint16_t    i_gid;      /* Low 16 bits of Group Id */
+    uint16_t    i_links_count;  /* Links count */
+    uint32_t    i_blocks;   /* Blocks count */
+    uint32_t    i_flags;    /* File flags */
+    union {
+        struct {
+            uint32_t  l_i_reserved1;
+        } linux1;
+        struct {
+            uint32_t  h_i_translator;
+        } hurd1;
+        struct {
+            uint32_t  m_i_reserved1;
+        } masix1;
+    } osd1;             /* OS dependent 1 */
+    uint32_t    i_block[EXT2_N_BLOCKS];/* Pointers to blocks */
+    uint32_t    i_generation;   /* File version (for NFS) */
+    uint32_t    i_file_acl; /* File ACL */
+    uint32_t    i_dir_acl;  /* Directory ACL */
+    uint32_t    i_faddr;    /* Fragment address */
+    union {
+        struct {
+            uint8_t l_i_frag;   /* Fragment number */
+            uint8_t l_i_fsize;  /* Fragment size */
+            uint16_t    i_pad1;
+            uint16_t    l_i_uid_high;   /* these 2 fields    */
+            uint16_t    l_i_gid_high;   /* were reserved2[0] */
+            uint32_t    l_i_reserved2;
+        } linux2;
+        struct {
+            uint8_t h_i_frag;   /* Fragment number */
+            uint8_t h_i_fsize;  /* Fragment size */
+            uint16_t    h_i_mode_high;
+            uint16_t    h_i_uid_high;
+            uint16_t    h_i_gid_high;
+            uint32_t    h_i_author;
+        } hurd2;
+        struct {
+            uint8_t m_i_frag;   /* Fragment number */
+            uint8_t m_i_fsize;  /* Fragment size */
+            uint16_t    m_pad1;
+            uint32_t    m_i_reserved2[2];
+        } masix2;
+    } osd2;             /* OS dependent 2 */
+};
+
+#define i_size_high i_dir_acl
+
+#define i_reserved1 osd1.linux1.l_i_reserved1
+#define i_frag      osd2.linux2.l_i_frag
+#define i_fsize     osd2.linux2.l_i_fsize
+#define i_uid_low   i_uid
+#define i_gid_low   i_gid
+#define i_uid_high  osd2.linux2.l_i_uid_high
+#define i_gid_high  osd2.linux2.l_i_gid_high
+#define i_reserved2 osd2.linux2.l_i_reserved2
+
+/*
+ * File system states
+ */
+#define EXT2_VALID_FS           0x0001  /* Unmounted cleanly */
+#define EXT2_ERROR_FS           0x0002  /* Errors detected */
+
+/*
+ * Mount flags
+ */
+#define EXT2_MOUNT_CHECK        0x000001  /* Do mount-time checks */
+#define EXT2_MOUNT_OLDALLOC     0x000002  /* Don't use the new Orlov allocator */
+#define EXT2_MOUNT_GRPID        0x000004  /* Create files with directory's group */
+#define EXT2_MOUNT_DEBUG        0x000008  /* Some debugging messages */
+#define EXT2_MOUNT_ERRORS_CONT      0x000010  /* Continue on errors */
+#define EXT2_MOUNT_ERRORS_RO        0x000020  /* Remount fs ro on errors */
+#define EXT2_MOUNT_ERRORS_PANIC     0x000040  /* Panic on errors */
+#define EXT2_MOUNT_MINIX_DF     0x000080  /* Mimics the Minix statfs */
+#define EXT2_MOUNT_NOBH         0x000100  /* No buffer_heads */
+#define EXT2_MOUNT_NO_UID32     0x000200  /* Disable 32-bit UIDs */
+#define EXT2_MOUNT_XATTR_USER       0x004000  /* Extended user attributes */
+#define EXT2_MOUNT_POSIX_ACL        0x008000  /* POSIX Access Control Lists */
+#define EXT2_MOUNT_XIP          0x010000  /* Execute in place */
+#define EXT2_MOUNT_USRQUOTA     0x020000 /* user quota */
+#define EXT2_MOUNT_GRPQUOTA     0x040000 /* group quota */
+
+
+#define clear_opt(o, opt)       o &= ~EXT2_MOUNT_##opt
+#define set_opt(o, opt)         o |= EXT2_MOUNT_##opt
+#define test_opt(sb, opt)       (EXT2_SB(sb)->s_mount_opt & \
+                     EXT2_MOUNT_##opt)
+/*
+ * Maximal mount counts between two filesystem checks
+ */
+#define EXT2_DFL_MAX_MNT_COUNT      20  /* Allow 20 mounts */
+#define EXT2_DFL_CHECKINTERVAL      0   /* Don't use interval check */
+
+/*
+ * Behaviour when detecting errors
+ */
+#define EXT2_ERRORS_CONTINUE        1   /* Continue execution */
+#define EXT2_ERRORS_RO          2   /* Remount fs read-only */
+#define EXT2_ERRORS_PANIC       3   /* Panic */
+#define EXT2_ERRORS_DEFAULT     EXT2_ERRORS_CONTINUE
+
+#define EXT2_SUPER_MAGIC    0xEF53
+#define EXT3_SUPER_MAGIC    0xEF53
+#define EXT4_SUPER_MAGIC    0xEF53
+
+/*
+ * Structure of the super block
+ */
+struct ext2_super_block {
+    uint32_t    s_inodes_count;     /* Inodes count */
+    uint32_t    s_blocks_count;     /* Blocks count */
+    uint32_t    s_r_blocks_count;   /* Reserved blocks count */
+    uint32_t    s_free_blocks_count;    /* Free blocks count */
+    uint32_t    s_free_inodes_count;    /* Free inodes count */
+    uint32_t    s_first_data_block; /* First Data Block */
+    uint32_t    s_log_block_size;   /* Block size */
+    uint32_t    s_log_frag_size;    /* Fragment size */
+    uint32_t    s_blocks_per_group; /* # Blocks per group */
+    uint32_t    s_frags_per_group;  /* # Fragments per group */
+    uint32_t    s_inodes_per_group; /* # Inodes per group */
+    uint32_t    s_mtime;        /* Mount time */
+    uint32_t    s_wtime;        /* Write time */
+    uint16_t    s_mnt_count;        /* Mount count */
+    uint16_t    s_max_mnt_count;    /* Maximal mount count */
+    uint16_t    s_magic;        /* Magic signature */
+    uint16_t    s_state;        /* File system state */
+    uint16_t    s_errors;       /* Behaviour when detecting errors */
+    uint16_t    s_minor_rev_level;  /* minor revision level */
+    uint32_t    s_lastcheck;        /* time of last check */
+    uint32_t    s_checkinterval;    /* max. time between checks */
+    uint32_t    s_creator_os;       /* OS */
+    uint32_t    s_rev_level;        /* Revision level */
+    uint16_t    s_def_resuid;       /* Default uid for reserved blocks */
+    uint16_t    s_def_resgid;       /* Default gid for reserved blocks */
+    /*
+     * These fields are for EXT2_DYNAMIC_REV superblocks only.
+     *
+     * Note: the difference between the compatible feature set and
+     * the incompatible feature set is that if there is a bit set
+     * in the incompatible feature set that the kernel doesn't
+     * know about, it should refuse to mount the filesystem.
+     *
+     * e2fsck's requirements are more strict; if it doesn't know
+     * about a feature in either the compatible or incompatible
+     * feature set, it must abort and not try to meddle with
+     * things it doesn't understand...
+     */
+    uint32_t    s_first_ino;        /* First non-reserved inode */
+    uint16_t   s_inode_size;        /* size of inode structure */
+    uint16_t    s_block_group_nr;   /* block group # of this superblock */
+    uint32_t    s_feature_compat;   /* compatible feature set */
+    uint32_t    s_feature_incompat;     /* incompatible feature set */
+    uint32_t    s_feature_ro_compat;    /* readonly-compatible feature set */
+    uint8_t s_uuid[16];     /* 128-bit uuid for volume */
+    char    s_volume_name[16];  /* volume name */
+    char    s_last_mounted[64];     /* directory where last mounted */
+    uint32_t    s_algorithm_usage_bitmap; /* For compression */
+    /*
+     * Performance hints.  Directory preallocation should only
+     * happen if the EXT2_COMPAT_PREALLOC flag is on.
+     */
+    uint8_t s_prealloc_blocks;  /* Nr of blocks to try to preallocate*/
+    uint8_t s_prealloc_dir_blocks;  /* Nr to preallocate for dirs */
+    uint16_t    s_padding1;
+    /*
+     * Journaling support valid if EXT3_FEATURE_COMPAT_HAS_JOURNAL set.
+     */
+    uint8_t s_journal_uuid[16]; /* uuid of journal superblock */
+    uint32_t    s_journal_inum;     /* inode number of journal file */
+    uint32_t    s_journal_dev;      /* device number of journal file */
+    uint32_t    s_last_orphan;      /* start of list of inodes to delete */
+    uint32_t    s_hash_seed[4];     /* HTREE hash seed */
+    uint8_t s_def_hash_version; /* Default hash version to use */
+    uint8_t s_reserved_char_pad;
+    uint16_t    s_reserved_word_pad;
+    uint32_t    s_default_mount_opts;
+    uint32_t    s_first_meta_bg;    /* First metablock block group */
+    uint32_t    s_reserved[190];    /* Padding to the end of the block */
+};
+
+/*
+ * Codes for operating systems
+ */
+#define EXT2_OS_LINUX       0
+#define EXT2_OS_HURD        1
+#define EXT2_OS_MASIX       2
+#define EXT2_OS_FREEBSD     3
+#define EXT2_OS_LITES       4
+
+/*
+ * Revision levels
+ */
+#define EXT2_GOOD_OLD_REV   0   /* The good old (original) format */
+#define EXT2_DYNAMIC_REV    1   /* V2 format w/ dynamic inode sizes */
+
+#define EXT2_CURRENT_REV    EXT2_GOOD_OLD_REV
+#define EXT2_MAX_SUPP_REV   EXT2_DYNAMIC_REV
+
+#define EXT2_GOOD_OLD_INODE_SIZE 128
+
+/*
+ * Feature set definitions
+ */
+
+#define EXT2_HAS_COMPAT_FEATURE(sb,mask)            \
+    ( (sb).s_feature_compat & cpu_to_le32(mask) )
+#define EXT2_HAS_RO_COMPAT_FEATURE(sb,mask)         \
+    ( (sb).s_feature_ro_compat & cpu_to_le32(mask) )
+#define EXT2_HAS_INCOMPAT_FEATURE(sb,mask)          \
+    ( (sb).s_feature_incompat & cpu_to_le32(mask) )
+#define EXT2_SET_COMPAT_FEATURE(sb,mask)            \
+    (sb).s_feature_compat |= cpu_to_le32(mask)
+#define EXT2_SET_RO_COMPAT_FEATURE(sb,mask)         \
+    (sb).s_feature_ro_compat |= cpu_to_le32(mask)
+#define EXT2_SET_INCOMPAT_FEATURE(sb,mask)          \
+    (sb).s_feature_incompat |= cpu_to_le32(mask)
+#define EXT2_CLEAR_COMPAT_FEATURE(sb,mask)          \
+    (sb).s_feature_compat &= ~cpu_to_le32(mask)
+#define EXT2_CLEAR_RO_COMPAT_FEATURE(sb,mask)           \
+    (sb).s_feature_ro_compat &= ~cpu_to_le32(mask)
+#define EXT2_CLEAR_INCOMPAT_FEATURE(sb,mask)            \
+    (sb).s_feature_incompat &= ~cpu_to_le32(mask)
+
+#define EXT2_FEATURE_COMPAT_DIR_PREALLOC    0x0001
+#define EXT2_FEATURE_COMPAT_IMAGIC_INODES   0x0002
+#define EXT3_FEATURE_COMPAT_HAS_JOURNAL     0x0004
+#define EXT2_FEATURE_COMPAT_EXT_ATTR        0x0008
+#define EXT2_FEATURE_COMPAT_RESIZE_INO      0x0010
+#define EXT2_FEATURE_COMPAT_DIR_INDEX       0x0020
+#define EXT2_FEATURE_COMPAT_ANY         0xffffffff
+
+#define EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER 0x0001
+#define EXT2_FEATURE_RO_COMPAT_LARGE_FILE   0x0002
+#define EXT2_FEATURE_RO_COMPAT_BTREE_DIR    0x0004
+#define EXT2_FEATURE_RO_COMPAT_ANY      0xffffffff
+
+#define EXT2_FEATURE_INCOMPAT_COMPRESSION   0x0001
+#define EXT2_FEATURE_INCOMPAT_FILETYPE      0x0002
+#define EXT3_FEATURE_INCOMPAT_RECOVER       0x0004
+#define EXT3_FEATURE_INCOMPAT_JOURNAL_DEV   0x0008
+#define EXT2_FEATURE_INCOMPAT_META_BG       0x0010
+#define EXT2_FEATURE_INCOMPAT_ANY       0xffffffff
+
+#define EXT2_FEATURE_COMPAT_SUPP    EXT2_FEATURE_COMPAT_EXT_ATTR
+#define EXT2_FEATURE_INCOMPAT_SUPP  (EXT2_FEATURE_INCOMPAT_FILETYPE| \
+                     EXT2_FEATURE_INCOMPAT_META_BG)
+#define EXT2_FEATURE_RO_COMPAT_SUPP (EXT2_FEATURE_RO_COMPAT_SPARSE_SUPER| \
+                     EXT2_FEATURE_RO_COMPAT_LARGE_FILE| \
+                     EXT2_FEATURE_RO_COMPAT_BTREE_DIR)
+#define EXT2_FEATURE_RO_COMPAT_UNSUPPORTED  ~EXT2_FEATURE_RO_COMPAT_SUPP
+#define EXT2_FEATURE_INCOMPAT_UNSUPPORTED   ~EXT2_FEATURE_INCOMPAT_SUPP
+
+/*
+ * Default values for user and/or group using reserved blocks
+ */
+#define EXT2_DEF_RESUID     0
+#define EXT2_DEF_RESGID     0
+
+/*
+ * Default mount options
+ */
+#define EXT2_DEFM_DEBUG     0x0001
+#define EXT2_DEFM_BSDGROUPS 0x0002
+#define EXT2_DEFM_XATTR_USER    0x0004
+#define EXT2_DEFM_ACL       0x0008
+#define EXT2_DEFM_UID16     0x0010
+/* Not used by ext2, but reserved for use by ext3 */
+#define EXT3_DEFM_JMODE     0x0060
+#define EXT3_DEFM_JMODE_DATA    0x0020
+#define EXT3_DEFM_JMODE_ORDERED 0x0040
+#define EXT3_DEFM_JMODE_WBACK   0x0060
+
+/*
+ * Structure of a directory entry
+ */
+#define EXT2_NAME_LEN 255
+
+struct ext2_dir_entry {
+    uint32_t    inode;          /* Inode number */
+    uint16_t    rec_len;        /* Directory entry length */
+    uint16_t    name_len;       /* Name length */
+    char    name[EXT2_NAME_LEN];    /* File name */
+};
+
+/*
+ * The new version of the directory entry.  Since EXT2 structures are
+ * stored in intel byte order, and the name_len field could never be
+ * bigger than 255 chars, it's safe to reclaim the extra byte for the
+ * file_type field.
+ */
+struct ext2_dir_entry_2 {
+    uint32_t    inode;          /* Inode number */
+    uint16_t    rec_len;        /* Directory entry length */
+    uint8_t name_len;       /* Name length */
+    uint8_t file_type;
+    char    name[EXT2_NAME_LEN];    /* File name */
+};
+
+/*
+ * Ext2 directory file types.  Only the low 3 bits are used.  The
+ * other bits are reserved for now.
+ */
+enum {
+    EXT2_FT_UNKNOWN,
+    EXT2_FT_REG_FILE,
+    EXT2_FT_DIR,
+    EXT2_FT_CHRDEV,
+    EXT2_FT_BLKDEV,
+    EXT2_FT_FIFO,
+    EXT2_FT_SOCK,
+    EXT2_FT_SYMLINK,
+    EXT2_FT_MAX
+};
+
+/*
+ * EXT2_DIR_PAD defines the directory entries boundaries
+ *
+ * NOTE: It must be a multiple of 4
+ */
+#define EXT2_DIR_PAD            4
+#define EXT2_DIR_ROUND          (EXT2_DIR_PAD - 1)
+#define EXT2_DIR_REC_LEN(name_len)  (((name_len) + 8 + EXT2_DIR_ROUND) & \
+                     ~EXT2_DIR_ROUND)
+
+#endif  /* _LINUX_EXT2_FS_H */
diff --git a/src/bsp/lk/lib/fs/ext2/ext2_priv.h b/src/bsp/lk/lib/fs/ext2/ext2_priv.h
new file mode 100644
index 0000000..ef37e54
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/ext2_priv.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2007-2015 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef __EXT2_PRIV_H
+#define __EXT2_PRIV_H
+
+#include <lib/bio.h>
+#include <lib/bcache.h>
+#include <lib/fs.h>
+#include "ext2_fs.h"
+
+typedef uint32_t blocknum_t;
+typedef uint32_t inodenum_t;
+typedef uint32_t groupnum_t;
+
+typedef struct {
+    bdev_t *dev;
+    bcache_t cache;
+
+    struct ext2_super_block sb;
+    int s_group_count;
+    struct ext2_group_desc *gd;
+    struct ext2_inode root_inode;
+} ext2_t;
+
+struct cache_block {
+    blocknum_t num;
+    void *ptr;
+};
+
+/* open file handle */
+typedef struct {
+    ext2_t *ext2;
+
+    struct cache_block ind_cache[3]; // cache of indirect blocks as they're scanned
+    struct ext2_inode inode;
+} ext2_file_t;
+
+/* internal routines */
+int ext2_load_inode(ext2_t *ext2, inodenum_t num, struct ext2_inode *inode);
+int ext2_lookup(ext2_t *ext2, const char *path, inodenum_t *inum); // path to inode
+
+/* io */
+int ext2_read_block(ext2_t *ext2, void *buf, blocknum_t bnum);
+int ext2_get_block(ext2_t *ext2, void **ptr, blocknum_t bnum);
+int ext2_put_block(ext2_t *ext2, blocknum_t bnum);
+
+off_t ext2_file_len(ext2_t *ext2, struct ext2_inode *inode);
+ssize_t ext2_read_inode(ext2_t *ext2, struct ext2_inode *inode, void *buf, off_t offset, size_t len);
+int ext2_read_link(ext2_t *ext2, struct ext2_inode *inode, char *str, size_t len);
+
+/* fs api */
+status_t ext2_mount(bdev_t *dev, fscookie **cookie);
+status_t ext2_unmount(fscookie *cookie);
+status_t ext2_open_file(fscookie *cookie, const char *path, filecookie **fcookie);
+ssize_t ext2_read_file(filecookie *fcookie, void *buf, off_t offset, size_t len);
+status_t ext2_close_file(filecookie *fcookie);
+status_t ext2_stat_file(filecookie *fcookie, struct file_stat *);
+
+/* mode stuff */
+#define S_IFMT      0170000
+#define S_IFIFO     0010000
+#define S_IFCHR     0020000
+#define S_IFDIR     0040000
+#define S_IFBLK     0060000
+#define S_IFREG     0100000
+#define S_IFLNK     0120000
+#define S_IFSOCK    0140000
+
+#define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO)
+#define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR)
+#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
+#define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK)
+#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)
+#define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK)
+#define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK)
+
+#endif
+
diff --git a/src/bsp/lk/lib/fs/ext2/ext3_fs.h b/src/bsp/lk/lib/fs/ext2/ext3_fs.h
new file mode 100644
index 0000000..3a366d6
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/ext3_fs.h
@@ -0,0 +1,883 @@
+/*
+ *  linux/include/linux/ext3_fs.h
+ *
+ * Copyright (C) 1992, 1993, 1994, 1995
+ * Remy Card (card@masi.ibp.fr)
+ * Laboratoire MASI - Institut Blaise Pascal
+ * Universite Pierre et Marie Curie (Paris VI)
+ *
+ *  from
+ *
+ *  linux/include/linux/minix_fs.h
+ *
+ *  Copyright (C) 1991, 1992  Linus Torvalds
+ */
+
+#ifndef _LINUX_EXT3_FS_H
+#define _LINUX_EXT3_FS_H
+
+#include <linux/types.h>
+#include <linux/magic.h>
+
+/*
+ * The second extended filesystem constants/structures
+ */
+
+/*
+ * Define EXT3FS_DEBUG to produce debug messages
+ */
+#undef EXT3FS_DEBUG
+
+/*
+ * Define EXT3_RESERVATION to reserve data blocks for expanding files
+ */
+#define EXT3_DEFAULT_RESERVE_BLOCKS     8
+/*max window size: 1024(direct blocks) + 3([t,d]indirect blocks) */
+#define EXT3_MAX_RESERVE_BLOCKS         1027
+#define EXT3_RESERVE_WINDOW_NOT_ALLOCATED 0
+/*
+ * Always enable hashed directories
+ */
+#define CONFIG_EXT3_INDEX
+
+/*
+ * Debug code
+ */
+#ifdef EXT3FS_DEBUG
+#define ext3_debug(f, a...)                     \
+    do {                                \
+        printk (KERN_DEBUG "EXT3-fs DEBUG (%s, %d): %s:",   \
+            __FILE__, __LINE__, __FUNCTION__);      \
+        printk (KERN_DEBUG f, ## a);                \
+    } while (0)
+#else
+#define ext3_debug(f, a...) do {} while (0)
+#endif
+
+/*
+ * Special inodes numbers
+ */
+#define EXT3_BAD_INO         1  /* Bad blocks inode */
+#define EXT3_ROOT_INO        2  /* Root inode */
+#define EXT3_BOOT_LOADER_INO     5  /* Boot loader inode */
+#define EXT3_UNDEL_DIR_INO   6  /* Undelete directory inode */
+#define EXT3_RESIZE_INO      7  /* Reserved group descriptors inode */
+#define EXT3_JOURNAL_INO     8  /* Journal inode */
+
+/* First non-reserved inode for old ext3 filesystems */
+#define EXT3_GOOD_OLD_FIRST_INO 11
+
+/*
+ * Maximal count of links to a file
+ */
+#define EXT3_LINK_MAX       32000
+
+/*
+ * Macro-instructions used to manage several block sizes
+ */
+#define EXT3_MIN_BLOCK_SIZE     1024
+#define EXT3_MAX_BLOCK_SIZE     4096
+#define EXT3_MIN_BLOCK_LOG_SIZE       10
+#ifdef __KERNEL__
+# define EXT3_BLOCK_SIZE(s)     ((s)->s_blocksize)
+#else
+# define EXT3_BLOCK_SIZE(s)     (EXT3_MIN_BLOCK_SIZE << (s)->s_log_block_size)
+#endif
+#define EXT3_ADDR_PER_BLOCK(s)      (EXT3_BLOCK_SIZE(s) / sizeof (__u32))
+#ifdef __KERNEL__
+# define EXT3_BLOCK_SIZE_BITS(s)    ((s)->s_blocksize_bits)
+#else
+# define EXT3_BLOCK_SIZE_BITS(s)    ((s)->s_log_block_size + 10)
+#endif
+#ifdef __KERNEL__
+#define EXT3_ADDR_PER_BLOCK_BITS(s) (EXT3_SB(s)->s_addr_per_block_bits)
+#define EXT3_INODE_SIZE(s)      (EXT3_SB(s)->s_inode_size)
+#define EXT3_FIRST_INO(s)       (EXT3_SB(s)->s_first_ino)
+#else
+#define EXT3_INODE_SIZE(s)  (((s)->s_rev_level == EXT3_GOOD_OLD_REV) ? \
+                 EXT3_GOOD_OLD_INODE_SIZE : \
+                 (s)->s_inode_size)
+#define EXT3_FIRST_INO(s)   (((s)->s_rev_level == EXT3_GOOD_OLD_REV) ? \
+                 EXT3_GOOD_OLD_FIRST_INO : \
+                 (s)->s_first_ino)
+#endif
+
+/*
+ * Macro-instructions used to manage fragments
+ */
+#define EXT3_MIN_FRAG_SIZE      1024
+#define EXT3_MAX_FRAG_SIZE      4096
+#define EXT3_MIN_FRAG_LOG_SIZE        10
+#ifdef __KERNEL__
+# define EXT3_FRAG_SIZE(s)      (EXT3_SB(s)->s_frag_size)
+# define EXT3_FRAGS_PER_BLOCK(s)    (EXT3_SB(s)->s_frags_per_block)
+#else
+# define EXT3_FRAG_SIZE(s)      (EXT3_MIN_FRAG_SIZE << (s)->s_log_frag_size)
+# define EXT3_FRAGS_PER_BLOCK(s)    (EXT3_BLOCK_SIZE(s) / EXT3_FRAG_SIZE(s))
+#endif
+
+/*
+ * Structure of a blocks group descriptor
+ */
+struct ext3_group_desc {
+    __le32  bg_block_bitmap;        /* Blocks bitmap block */
+    __le32  bg_inode_bitmap;        /* Inodes bitmap block */
+    __le32  bg_inode_table;     /* Inodes table block */
+    __le16  bg_free_blocks_count;   /* Free blocks count */
+    __le16  bg_free_inodes_count;   /* Free inodes count */
+    __le16  bg_used_dirs_count; /* Directories count */
+    __u16   bg_pad;
+    __le32  bg_reserved[3];
+};
+
+/*
+ * Macro-instructions used to manage group descriptors
+ */
+#ifdef __KERNEL__
+# define EXT3_BLOCKS_PER_GROUP(s)   (EXT3_SB(s)->s_blocks_per_group)
+# define EXT3_DESC_PER_BLOCK(s)     (EXT3_SB(s)->s_desc_per_block)
+# define EXT3_INODES_PER_GROUP(s)   (EXT3_SB(s)->s_inodes_per_group)
+# define EXT3_DESC_PER_BLOCK_BITS(s)    (EXT3_SB(s)->s_desc_per_block_bits)
+#else
+# define EXT3_BLOCKS_PER_GROUP(s)   ((s)->s_blocks_per_group)
+# define EXT3_DESC_PER_BLOCK(s)     (EXT3_BLOCK_SIZE(s) / sizeof (struct ext3_group_desc))
+# define EXT3_INODES_PER_GROUP(s)   ((s)->s_inodes_per_group)
+#endif
+
+/*
+ * Constants relative to the data blocks
+ */
+#define EXT3_NDIR_BLOCKS        12
+#define EXT3_IND_BLOCK          EXT3_NDIR_BLOCKS
+#define EXT3_DIND_BLOCK         (EXT3_IND_BLOCK + 1)
+#define EXT3_TIND_BLOCK         (EXT3_DIND_BLOCK + 1)
+#define EXT3_N_BLOCKS           (EXT3_TIND_BLOCK + 1)
+
+/*
+ * Inode flags
+ */
+#define EXT3_SECRM_FL           0x00000001 /* Secure deletion */
+#define EXT3_UNRM_FL            0x00000002 /* Undelete */
+#define EXT3_COMPR_FL           0x00000004 /* Compress file */
+#define EXT3_SYNC_FL            0x00000008 /* Synchronous updates */
+#define EXT3_IMMUTABLE_FL       0x00000010 /* Immutable file */
+#define EXT3_APPEND_FL          0x00000020 /* writes to file may only append */
+#define EXT3_NODUMP_FL          0x00000040 /* do not dump file */
+#define EXT3_NOATIME_FL         0x00000080 /* do not update atime */
+/* Reserved for compression usage... */
+#define EXT3_DIRTY_FL           0x00000100
+#define EXT3_COMPRBLK_FL        0x00000200 /* One or more compressed clusters */
+#define EXT3_NOCOMPR_FL         0x00000400 /* Don't compress */
+#define EXT3_ECOMPR_FL          0x00000800 /* Compression error */
+/* End compression flags --- maybe not all used */
+#define EXT3_INDEX_FL           0x00001000 /* hash-indexed directory */
+#define EXT3_IMAGIC_FL          0x00002000 /* AFS directory */
+#define EXT3_JOURNAL_DATA_FL        0x00004000 /* file data should be journaled */
+#define EXT3_NOTAIL_FL          0x00008000 /* file tail should not be merged */
+#define EXT3_DIRSYNC_FL         0x00010000 /* dirsync behaviour (directories only) */
+#define EXT3_TOPDIR_FL          0x00020000 /* Top of directory hierarchies*/
+#define EXT3_RESERVED_FL        0x80000000 /* reserved for ext3 lib */
+
+#define EXT3_FL_USER_VISIBLE        0x0003DFFF /* User visible flags */
+#define EXT3_FL_USER_MODIFIABLE     0x000380FF /* User modifiable flags */
+
+/*
+ * Inode dynamic state flags
+ */
+#define EXT3_STATE_JDATA        0x00000001 /* journaled data exists */
+#define EXT3_STATE_NEW          0x00000002 /* inode is newly created */
+#define EXT3_STATE_XATTR        0x00000004 /* has in-inode xattrs */
+
+/* Used to pass group descriptor data when online resize is done */
+struct ext3_new_group_input {
+    __u32 group;            /* Group number for this data */
+    __u32 block_bitmap;     /* Absolute block number of block bitmap */
+    __u32 inode_bitmap;     /* Absolute block number of inode bitmap */
+    __u32 inode_table;      /* Absolute block number of inode table start */
+    __u32 blocks_count;     /* Total number of blocks in this group */
+    __u16 reserved_blocks;  /* Number of reserved blocks in this group */
+    __u16 unused;
+};
+
+/* The struct ext3_new_group_input in kernel space, with free_blocks_count */
+struct ext3_new_group_data {
+    __u32 group;
+    __u32 block_bitmap;
+    __u32 inode_bitmap;
+    __u32 inode_table;
+    __u32 blocks_count;
+    __u16 reserved_blocks;
+    __u16 unused;
+    __u32 free_blocks_count;
+};
+
+
+/*
+ * ioctl commands
+ */
+#define EXT3_IOC_GETFLAGS       FS_IOC_GETFLAGS
+#define EXT3_IOC_SETFLAGS       FS_IOC_SETFLAGS
+#define EXT3_IOC_GETVERSION     _IOR('f', 3, long)
+#define EXT3_IOC_SETVERSION     _IOW('f', 4, long)
+#define EXT3_IOC_GROUP_EXTEND       _IOW('f', 7, unsigned long)
+#define EXT3_IOC_GROUP_ADD      _IOW('f', 8,struct ext3_new_group_input)
+#define EXT3_IOC_GETVERSION_OLD     FS_IOC_GETVERSION
+#define EXT3_IOC_SETVERSION_OLD     FS_IOC_SETVERSION
+#ifdef CONFIG_JBD_DEBUG
+#define EXT3_IOC_WAIT_FOR_READONLY  _IOR('f', 99, long)
+#endif
+#define EXT3_IOC_GETRSVSZ       _IOR('f', 5, long)
+#define EXT3_IOC_SETRSVSZ       _IOW('f', 6, long)
+
+/*
+ * ioctl commands in 32 bit emulation
+ */
+#define EXT3_IOC32_GETFLAGS     FS_IOC32_GETFLAGS
+#define EXT3_IOC32_SETFLAGS     FS_IOC32_SETFLAGS
+#define EXT3_IOC32_GETVERSION       _IOR('f', 3, int)
+#define EXT3_IOC32_SETVERSION       _IOW('f', 4, int)
+#define EXT3_IOC32_GETRSVSZ     _IOR('f', 5, int)
+#define EXT3_IOC32_SETRSVSZ     _IOW('f', 6, int)
+#define EXT3_IOC32_GROUP_EXTEND     _IOW('f', 7, unsigned int)
+#ifdef CONFIG_JBD_DEBUG
+#define EXT3_IOC32_WAIT_FOR_READONLY    _IOR('f', 99, int)
+#endif
+#define EXT3_IOC32_GETVERSION_OLD   FS_IOC32_GETVERSION
+#define EXT3_IOC32_SETVERSION_OLD   FS_IOC32_SETVERSION
+
+
+/*
+ *  Mount options
+ */
+struct ext3_mount_options {
+    unsigned long s_mount_opt;
+    uid_t s_resuid;
+    gid_t s_resgid;
+    unsigned long s_commit_interval;
+#ifdef CONFIG_QUOTA
+    int s_jquota_fmt;
+    char *s_qf_names[MAXQUOTAS];
+#endif
+};
+
+/*
+ * Structure of an inode on the disk
+ */
+struct ext3_inode {
+    __le16  i_mode;     /* File mode */
+    __le16  i_uid;      /* Low 16 bits of Owner Uid */
+    __le32  i_size;     /* Size in bytes */
+    __le32  i_atime;    /* Access time */
+    __le32  i_ctime;    /* Creation time */
+    __le32  i_mtime;    /* Modification time */
+    __le32  i_dtime;    /* Deletion Time */
+    __le16  i_gid;      /* Low 16 bits of Group Id */
+    __le16  i_links_count;  /* Links count */
+    __le32  i_blocks;   /* Blocks count */
+    __le32  i_flags;    /* File flags */
+    union {
+        struct {
+            __u32  l_i_reserved1;
+        } linux1;
+        struct {
+            __u32  h_i_translator;
+        } hurd1;
+        struct {
+            __u32  m_i_reserved1;
+        } masix1;
+    } osd1;             /* OS dependent 1 */
+    __le32  i_block[EXT3_N_BLOCKS];/* Pointers to blocks */
+    __le32  i_generation;   /* File version (for NFS) */
+    __le32  i_file_acl; /* File ACL */
+    __le32  i_dir_acl;  /* Directory ACL */
+    __le32  i_faddr;    /* Fragment address */
+    union {
+        struct {
+            __u8    l_i_frag;   /* Fragment number */
+            __u8    l_i_fsize;  /* Fragment size */
+            __u16   i_pad1;
+            __le16  l_i_uid_high;   /* these 2 fields    */
+            __le16  l_i_gid_high;   /* were reserved2[0] */
+            __u32   l_i_reserved2;
+        } linux2;
+        struct {
+            __u8    h_i_frag;   /* Fragment number */
+            __u8    h_i_fsize;  /* Fragment size */
+            __u16   h_i_mode_high;
+            __u16   h_i_uid_high;
+            __u16   h_i_gid_high;
+            __u32   h_i_author;
+        } hurd2;
+        struct {
+            __u8    m_i_frag;   /* Fragment number */
+            __u8    m_i_fsize;  /* Fragment size */
+            __u16   m_pad1;
+            __u32   m_i_reserved2[2];
+        } masix2;
+    } osd2;             /* OS dependent 2 */
+    __le16  i_extra_isize;
+    __le16  i_pad1;
+};
+
+#define i_size_high i_dir_acl
+
+#if defined(__KERNEL__) || defined(__linux__)
+#define i_reserved1 osd1.linux1.l_i_reserved1
+#define i_frag      osd2.linux2.l_i_frag
+#define i_fsize     osd2.linux2.l_i_fsize
+#define i_uid_low   i_uid
+#define i_gid_low   i_gid
+#define i_uid_high  osd2.linux2.l_i_uid_high
+#define i_gid_high  osd2.linux2.l_i_gid_high
+#define i_reserved2 osd2.linux2.l_i_reserved2
+
+#elif defined(__GNU__)
+
+#define i_translator    osd1.hurd1.h_i_translator
+#define i_frag      osd2.hurd2.h_i_frag;
+#define i_fsize     osd2.hurd2.h_i_fsize;
+#define i_uid_high  osd2.hurd2.h_i_uid_high
+#define i_gid_high  osd2.hurd2.h_i_gid_high
+#define i_author    osd2.hurd2.h_i_author
+
+#elif defined(__masix__)
+
+#define i_reserved1 osd1.masix1.m_i_reserved1
+#define i_frag      osd2.masix2.m_i_frag
+#define i_fsize     osd2.masix2.m_i_fsize
+#define i_reserved2 osd2.masix2.m_i_reserved2
+
+#endif /* defined(__KERNEL__) || defined(__linux__) */
+
+/*
+ * File system states
+ */
+#define EXT3_VALID_FS           0x0001  /* Unmounted cleanly */
+#define EXT3_ERROR_FS           0x0002  /* Errors detected */
+#define EXT3_ORPHAN_FS          0x0004  /* Orphans being recovered */
+
+/*
+ * Mount flags
+ */
+#define EXT3_MOUNT_CHECK        0x00001 /* Do mount-time checks */
+#define EXT3_MOUNT_OLDALLOC     0x00002  /* Don't use the new Orlov allocator */
+#define EXT3_MOUNT_GRPID        0x00004 /* Create files with directory's group */
+#define EXT3_MOUNT_DEBUG        0x00008 /* Some debugging messages */
+#define EXT3_MOUNT_ERRORS_CONT      0x00010 /* Continue on errors */
+#define EXT3_MOUNT_ERRORS_RO        0x00020 /* Remount fs ro on errors */
+#define EXT3_MOUNT_ERRORS_PANIC     0x00040 /* Panic on errors */
+#define EXT3_MOUNT_MINIX_DF     0x00080 /* Mimics the Minix statfs */
+#define EXT3_MOUNT_NOLOAD       0x00100 /* Don't use existing journal*/
+#define EXT3_MOUNT_ABORT        0x00200 /* Fatal error detected */
+#define EXT3_MOUNT_DATA_FLAGS       0x00C00 /* Mode for data writes: */
+#define EXT3_MOUNT_JOURNAL_DATA     0x00400 /* Write data to journal */
+#define EXT3_MOUNT_ORDERED_DATA     0x00800 /* Flush data before commit */
+#define EXT3_MOUNT_WRITEBACK_DATA   0x00C00 /* No data ordering */
+#define EXT3_MOUNT_UPDATE_JOURNAL   0x01000 /* Update the journal format */
+#define EXT3_MOUNT_NO_UID32     0x02000  /* Disable 32-bit UIDs */
+#define EXT3_MOUNT_XATTR_USER       0x04000 /* Extended user attributes */
+#define EXT3_MOUNT_POSIX_ACL        0x08000 /* POSIX Access Control Lists */
+#define EXT3_MOUNT_RESERVATION      0x10000 /* Preallocation */
+#define EXT3_MOUNT_BARRIER      0x20000 /* Use block barriers */
+#define EXT3_MOUNT_NOBH         0x40000 /* No bufferheads */
+#define EXT3_MOUNT_QUOTA        0x80000 /* Some quota option set */
+#define EXT3_MOUNT_USRQUOTA     0x100000 /* "old" user quota */
+#define EXT3_MOUNT_GRPQUOTA     0x200000 /* "old" group quota */
+
+/* Compatibility, for having both ext2_fs.h and ext3_fs.h included at once */
+#ifndef _LINUX_EXT2_FS_H
+#define clear_opt(o, opt)       o &= ~EXT3_MOUNT_##opt
+#define set_opt(o, opt)         o |= EXT3_MOUNT_##opt
+#define test_opt(sb, opt)       (EXT3_SB(sb)->s_mount_opt & \
+                     EXT3_MOUNT_##opt)
+#else
+#define EXT2_MOUNT_NOLOAD       EXT3_MOUNT_NOLOAD
+#define EXT2_MOUNT_ABORT        EXT3_MOUNT_ABORT
+#define EXT2_MOUNT_DATA_FLAGS       EXT3_MOUNT_DATA_FLAGS
+#endif
+
+#define ext3_set_bit            ext2_set_bit
+#define ext3_set_bit_atomic     ext2_set_bit_atomic
+#define ext3_clear_bit          ext2_clear_bit
+#define ext3_clear_bit_atomic       ext2_clear_bit_atomic
+#define ext3_test_bit           ext2_test_bit
+#define ext3_find_first_zero_bit    ext2_find_first_zero_bit
+#define ext3_find_next_zero_bit     ext2_find_next_zero_bit
+
+/*
+ * Maximal mount counts between two filesystem checks
+ */
+#define EXT3_DFL_MAX_MNT_COUNT      20  /* Allow 20 mounts */
+#define EXT3_DFL_CHECKINTERVAL      0   /* Don't use interval check */
+
+/*
+ * Behaviour when detecting errors
+ */
+#define EXT3_ERRORS_CONTINUE        1   /* Continue execution */
+#define EXT3_ERRORS_RO          2   /* Remount fs read-only */
+#define EXT3_ERRORS_PANIC       3   /* Panic */
+#define EXT3_ERRORS_DEFAULT     EXT3_ERRORS_CONTINUE
+
+/*
+ * Structure of the super block
+ */
+struct ext3_super_block {
+    /*00*/  __le32  s_inodes_count;     /* Inodes count */
+    __le32  s_blocks_count;     /* Blocks count */
+    __le32  s_r_blocks_count;   /* Reserved blocks count */
+    __le32  s_free_blocks_count;    /* Free blocks count */
+    /*10*/  __le32  s_free_inodes_count;    /* Free inodes count */
+    __le32  s_first_data_block; /* First Data Block */
+    __le32  s_log_block_size;   /* Block size */
+    __le32  s_log_frag_size;    /* Fragment size */
+    /*20*/  __le32  s_blocks_per_group; /* # Blocks per group */
+    __le32  s_frags_per_group;  /* # Fragments per group */
+    __le32  s_inodes_per_group; /* # Inodes per group */
+    __le32  s_mtime;        /* Mount time */
+    /*30*/  __le32  s_wtime;        /* Write time */
+    __le16  s_mnt_count;        /* Mount count */
+    __le16  s_max_mnt_count;    /* Maximal mount count */
+    __le16  s_magic;        /* Magic signature */
+    __le16  s_state;        /* File system state */
+    __le16  s_errors;       /* Behaviour when detecting errors */
+    __le16  s_minor_rev_level;  /* minor revision level */
+    /*40*/  __le32  s_lastcheck;        /* time of last check */
+    __le32  s_checkinterval;    /* max. time between checks */
+    __le32  s_creator_os;       /* OS */
+    __le32  s_rev_level;        /* Revision level */
+    /*50*/  __le16  s_def_resuid;       /* Default uid for reserved blocks */
+    __le16  s_def_resgid;       /* Default gid for reserved blocks */
+    /*
+     * These fields are for EXT3_DYNAMIC_REV superblocks only.
+     *
+     * Note: the difference between the compatible feature set and
+     * the incompatible feature set is that if there is a bit set
+     * in the incompatible feature set that the kernel doesn't
+     * know about, it should refuse to mount the filesystem.
+     *
+     * e2fsck's requirements are more strict; if it doesn't know
+     * about a feature in either the compatible or incompatible
+     * feature set, it must abort and not try to meddle with
+     * things it doesn't understand...
+     */
+    __le32  s_first_ino;        /* First non-reserved inode */
+    __le16   s_inode_size;      /* size of inode structure */
+    __le16  s_block_group_nr;   /* block group # of this superblock */
+    __le32  s_feature_compat;   /* compatible feature set */
+    /*60*/  __le32  s_feature_incompat; /* incompatible feature set */
+    __le32  s_feature_ro_compat;    /* readonly-compatible feature set */
+    /*68*/  __u8    s_uuid[16];     /* 128-bit uuid for volume */
+    /*78*/  char    s_volume_name[16];  /* volume name */
+    /*88*/  char    s_last_mounted[64]; /* directory where last mounted */
+    /*C8*/  __le32  s_algorithm_usage_bitmap; /* For compression */
+    /*
+     * Performance hints.  Directory preallocation should only
+     * happen if the EXT3_FEATURE_COMPAT_DIR_PREALLOC flag is on.
+     */
+    __u8    s_prealloc_blocks;  /* Nr of blocks to try to preallocate*/
+    __u8    s_prealloc_dir_blocks;  /* Nr to preallocate for dirs */
+    __le16  s_reserved_gdt_blocks;  /* Per group desc for online growth */
+    /*
+     * Journaling support valid if EXT3_FEATURE_COMPAT_HAS_JOURNAL set.
+     */
+    /*D0*/  __u8    s_journal_uuid[16]; /* uuid of journal superblock */
+    /*E0*/  __le32  s_journal_inum;     /* inode number of journal file */
+    __le32  s_journal_dev;      /* device number of journal file */
+    __le32  s_last_orphan;      /* start of list of inodes to delete */
+    __le32  s_hash_seed[4];     /* HTREE hash seed */
+    __u8    s_def_hash_version; /* Default hash version to use */
+    __u8    s_reserved_char_pad;
+    __u16   s_reserved_word_pad;
+    __le32  s_default_mount_opts;
+    __le32  s_first_meta_bg;    /* First metablock block group */
+    __u32   s_reserved[190];    /* Padding to the end of the block */
+};
+
+#ifdef __KERNEL__
+#include <linux/ext3_fs_i.h>
+#include <linux/ext3_fs_sb.h>
+static inline struct ext3_sb_info * EXT3_SB(struct super_block *sb)
+{
+    return sb->s_fs_info;
+}
+static inline struct ext3_inode_info *EXT3_I(struct inode *inode)
+{
+    return container_of(inode, struct ext3_inode_info, vfs_inode);
+}
+
+static inline int ext3_valid_inum(struct super_block *sb, unsigned long ino)
+{
+    return ino == EXT3_ROOT_INO ||
+           ino == EXT3_JOURNAL_INO ||
+           ino == EXT3_RESIZE_INO ||
+           (ino >= EXT3_FIRST_INO(sb) &&
+            ino <= le32_to_cpu(EXT3_SB(sb)->s_es->s_inodes_count));
+}
+#else
+/* Assume that user mode programs are passing in an ext3fs superblock, not
+ * a kernel struct super_block.  This will allow us to call the feature-test
+ * macros from user land. */
+#define EXT3_SB(sb) (sb)
+#endif
+
+#define NEXT_ORPHAN(inode) EXT3_I(inode)->i_dtime
+
+/*
+ * Codes for operating systems
+ */
+#define EXT3_OS_LINUX       0
+#define EXT3_OS_HURD        1
+#define EXT3_OS_MASIX       2
+#define EXT3_OS_FREEBSD     3
+#define EXT3_OS_LITES       4
+
+/*
+ * Revision levels
+ */
+#define EXT3_GOOD_OLD_REV   0   /* The good old (original) format */
+#define EXT3_DYNAMIC_REV    1   /* V2 format w/ dynamic inode sizes */
+
+#define EXT3_CURRENT_REV    EXT3_GOOD_OLD_REV
+#define EXT3_MAX_SUPP_REV   EXT3_DYNAMIC_REV
+
+#define EXT3_GOOD_OLD_INODE_SIZE 128
+
+/*
+ * Feature set definitions
+ */
+
+#define EXT3_HAS_COMPAT_FEATURE(sb,mask)            \
+    ( EXT3_SB(sb)->s_es->s_feature_compat & cpu_to_le32(mask) )
+#define EXT3_HAS_RO_COMPAT_FEATURE(sb,mask)         \
+    ( EXT3_SB(sb)->s_es->s_feature_ro_compat & cpu_to_le32(mask) )
+#define EXT3_HAS_INCOMPAT_FEATURE(sb,mask)          \
+    ( EXT3_SB(sb)->s_es->s_feature_incompat & cpu_to_le32(mask) )
+#define EXT3_SET_COMPAT_FEATURE(sb,mask)            \
+    EXT3_SB(sb)->s_es->s_feature_compat |= cpu_to_le32(mask)
+#define EXT3_SET_RO_COMPAT_FEATURE(sb,mask)         \
+    EXT3_SB(sb)->s_es->s_feature_ro_compat |= cpu_to_le32(mask)
+#define EXT3_SET_INCOMPAT_FEATURE(sb,mask)          \
+    EXT3_SB(sb)->s_es->s_feature_incompat |= cpu_to_le32(mask)
+#define EXT3_CLEAR_COMPAT_FEATURE(sb,mask)          \
+    EXT3_SB(sb)->s_es->s_feature_compat &= ~cpu_to_le32(mask)
+#define EXT3_CLEAR_RO_COMPAT_FEATURE(sb,mask)           \
+    EXT3_SB(sb)->s_es->s_feature_ro_compat &= ~cpu_to_le32(mask)
+#define EXT3_CLEAR_INCOMPAT_FEATURE(sb,mask)            \
+    EXT3_SB(sb)->s_es->s_feature_incompat &= ~cpu_to_le32(mask)
+
+#define EXT3_FEATURE_COMPAT_DIR_PREALLOC    0x0001
+#define EXT3_FEATURE_COMPAT_IMAGIC_INODES   0x0002
+#define EXT3_FEATURE_COMPAT_HAS_JOURNAL     0x0004
+#define EXT3_FEATURE_COMPAT_EXT_ATTR        0x0008
+#define EXT3_FEATURE_COMPAT_RESIZE_INODE    0x0010
+#define EXT3_FEATURE_COMPAT_DIR_INDEX       0x0020
+
+#define EXT3_FEATURE_RO_COMPAT_SPARSE_SUPER 0x0001
+#define EXT3_FEATURE_RO_COMPAT_LARGE_FILE   0x0002
+#define EXT3_FEATURE_RO_COMPAT_BTREE_DIR    0x0004
+
+#define EXT3_FEATURE_INCOMPAT_COMPRESSION   0x0001
+#define EXT3_FEATURE_INCOMPAT_FILETYPE      0x0002
+#define EXT3_FEATURE_INCOMPAT_RECOVER       0x0004 /* Needs recovery */
+#define EXT3_FEATURE_INCOMPAT_JOURNAL_DEV   0x0008 /* Journal device */
+#define EXT3_FEATURE_INCOMPAT_META_BG       0x0010
+
+#define EXT3_FEATURE_COMPAT_SUPP    EXT2_FEATURE_COMPAT_EXT_ATTR
+#define EXT3_FEATURE_INCOMPAT_SUPP  (EXT3_FEATURE_INCOMPAT_FILETYPE| \
+                     EXT3_FEATURE_INCOMPAT_RECOVER| \
+                     EXT3_FEATURE_INCOMPAT_META_BG)
+#define EXT3_FEATURE_RO_COMPAT_SUPP (EXT3_FEATURE_RO_COMPAT_SPARSE_SUPER| \
+                     EXT3_FEATURE_RO_COMPAT_LARGE_FILE| \
+                     EXT3_FEATURE_RO_COMPAT_BTREE_DIR)
+
+/*
+ * Default values for user and/or group using reserved blocks
+ */
+#define EXT3_DEF_RESUID     0
+#define EXT3_DEF_RESGID     0
+
+/*
+ * Default mount options
+ */
+#define EXT3_DEFM_DEBUG     0x0001
+#define EXT3_DEFM_BSDGROUPS 0x0002
+#define EXT3_DEFM_XATTR_USER    0x0004
+#define EXT3_DEFM_ACL       0x0008
+#define EXT3_DEFM_UID16     0x0010
+#define EXT3_DEFM_JMODE     0x0060
+#define EXT3_DEFM_JMODE_DATA    0x0020
+#define EXT3_DEFM_JMODE_ORDERED 0x0040
+#define EXT3_DEFM_JMODE_WBACK   0x0060
+
+/*
+ * Structure of a directory entry
+ */
+#define EXT3_NAME_LEN 255
+
+struct ext3_dir_entry {
+    __le32  inode;          /* Inode number */
+    __le16  rec_len;        /* Directory entry length */
+    __le16  name_len;       /* Name length */
+    char    name[EXT3_NAME_LEN];    /* File name */
+};
+
+/*
+ * The new version of the directory entry.  Since EXT3 structures are
+ * stored in intel byte order, and the name_len field could never be
+ * bigger than 255 chars, it's safe to reclaim the extra byte for the
+ * file_type field.
+ */
+struct ext3_dir_entry_2 {
+    __le32  inode;          /* Inode number */
+    __le16  rec_len;        /* Directory entry length */
+    __u8    name_len;       /* Name length */
+    __u8    file_type;
+    char    name[EXT3_NAME_LEN];    /* File name */
+};
+
+/*
+ * Ext3 directory file types.  Only the low 3 bits are used.  The
+ * other bits are reserved for now.
+ */
+#define EXT3_FT_UNKNOWN     0
+#define EXT3_FT_REG_FILE    1
+#define EXT3_FT_DIR     2
+#define EXT3_FT_CHRDEV      3
+#define EXT3_FT_BLKDEV      4
+#define EXT3_FT_FIFO        5
+#define EXT3_FT_SOCK        6
+#define EXT3_FT_SYMLINK     7
+
+#define EXT3_FT_MAX     8
+
+/*
+ * EXT3_DIR_PAD defines the directory entries boundaries
+ *
+ * NOTE: It must be a multiple of 4
+ */
+#define EXT3_DIR_PAD            4
+#define EXT3_DIR_ROUND          (EXT3_DIR_PAD - 1)
+#define EXT3_DIR_REC_LEN(name_len)  (((name_len) + 8 + EXT3_DIR_ROUND) & \
+                     ~EXT3_DIR_ROUND)
+/*
+ * Hash Tree Directory indexing
+ * (c) Daniel Phillips, 2001
+ */
+
+#ifdef CONFIG_EXT3_INDEX
+#define is_dx(dir) (EXT3_HAS_COMPAT_FEATURE(dir->i_sb, \
+                          EXT3_FEATURE_COMPAT_DIR_INDEX) && \
+              (EXT3_I(dir)->i_flags & EXT3_INDEX_FL))
+#define EXT3_DIR_LINK_MAX(dir) (!is_dx(dir) && (dir)->i_nlink >= EXT3_LINK_MAX)
+#define EXT3_DIR_LINK_EMPTY(dir) ((dir)->i_nlink == 2 || (dir)->i_nlink == 1)
+#else
+#define is_dx(dir) 0
+#define EXT3_DIR_LINK_MAX(dir) ((dir)->i_nlink >= EXT3_LINK_MAX)
+#define EXT3_DIR_LINK_EMPTY(dir) ((dir)->i_nlink == 2)
+#endif
+
+/* Legal values for the dx_root hash_version field: */
+
+#define DX_HASH_LEGACY      0
+#define DX_HASH_HALF_MD4    1
+#define DX_HASH_TEA     2
+
+#ifdef __KERNEL__
+
+/* hash info structure used by the directory hash */
+struct dx_hash_info {
+    u32     hash;
+    u32     minor_hash;
+    int     hash_version;
+    u32     *seed;
+};
+
+#define EXT3_HTREE_EOF  0x7fffffff
+
+/*
+ * Control parameters used by ext3_htree_next_block
+ */
+#define HASH_NB_ALWAYS      1
+
+
+/*
+ * Describe an inode's exact location on disk and in memory
+ */
+struct ext3_iloc {
+    struct buffer_head *bh;
+    unsigned long offset;
+    unsigned long block_group;
+};
+
+static inline struct ext3_inode *ext3_raw_inode(struct ext3_iloc *iloc)
+{
+    return (struct ext3_inode *) (iloc->bh->b_data + iloc->offset);
+}
+
+/*
+ * This structure is stuffed into the struct file's private_data field
+ * for directories.  It is where we put information so that we can do
+ * readdir operations in hash tree order.
+ */
+struct dir_private_info {
+    struct rb_root  root;
+    struct rb_node  *curr_node;
+    struct fname    *extra_fname;
+    loff_t      last_pos;
+    __u32       curr_hash;
+    __u32       curr_minor_hash;
+    __u32       next_hash;
+};
+
+/* calculate the first block number of the group */
+static inline ext3_fsblk_t
+ext3_group_first_block_no(struct super_block *sb, unsigned long group_no)
+{
+    return group_no * (ext3_fsblk_t)EXT3_BLOCKS_PER_GROUP(sb) +
+           le32_to_cpu(EXT3_SB(sb)->s_es->s_first_data_block);
+}
+
+/*
+ * Special error return code only used by dx_probe() and its callers.
+ */
+#define ERR_BAD_DX_DIR  -75000
+
+/*
+ * Function prototypes
+ */
+
+/*
+ * Ok, these declarations are also in <linux/kernel.h> but none of the
+ * ext3 source programs needs to include it so they are duplicated here.
+ */
+# define NORET_TYPE    /**/
+# define ATTRIB_NORET  __attribute__((noreturn))
+# define NORET_AND     noreturn,
+
+/* balloc.c */
+extern int ext3_bg_has_super(struct super_block *sb, int group);
+extern unsigned long ext3_bg_num_gdb(struct super_block *sb, int group);
+extern ext3_fsblk_t ext3_new_block (handle_t *handle, struct inode *inode,
+                                    ext3_fsblk_t goal, int *errp);
+extern ext3_fsblk_t ext3_new_blocks (handle_t *handle, struct inode *inode,
+                                     ext3_fsblk_t goal, unsigned long *count, int *errp);
+extern void ext3_free_blocks (handle_t *handle, struct inode *inode,
+                              ext3_fsblk_t block, unsigned long count);
+extern void ext3_free_blocks_sb (handle_t *handle, struct super_block *sb,
+                                 ext3_fsblk_t block, unsigned long count,
+                                 unsigned long *pdquot_freed_blocks);
+extern ext3_fsblk_t ext3_count_free_blocks (struct super_block *);
+extern void ext3_check_blocks_bitmap (struct super_block *);
+extern struct ext3_group_desc * ext3_get_group_desc(struct super_block * sb,
+        unsigned int block_group,
+        struct buffer_head ** bh);
+extern int ext3_should_retry_alloc(struct super_block *sb, int *retries);
+extern void ext3_init_block_alloc_info(struct inode *);
+extern void ext3_rsv_window_add(struct super_block *sb, struct ext3_reserve_window_node *rsv);
+
+/* dir.c */
+extern int ext3_check_dir_entry(const char *, struct inode *,
+                                struct ext3_dir_entry_2 *,
+                                struct buffer_head *, unsigned long);
+extern int ext3_htree_store_dirent(struct file *dir_file, __u32 hash,
+                                   __u32 minor_hash,
+                                   struct ext3_dir_entry_2 *dirent);
+extern void ext3_htree_free_dir_info(struct dir_private_info *p);
+
+/* fsync.c */
+extern int ext3_sync_file (struct file *, struct dentry *, int);
+
+/* hash.c */
+extern int ext3fs_dirhash(const char *name, int len, struct
+                          dx_hash_info *hinfo);
+
+/* ialloc.c */
+extern struct inode * ext3_new_inode (handle_t *, struct inode *, int);
+extern void ext3_free_inode (handle_t *, struct inode *);
+extern struct inode * ext3_orphan_get (struct super_block *, unsigned long);
+extern unsigned long ext3_count_free_inodes (struct super_block *);
+extern unsigned long ext3_count_dirs (struct super_block *);
+extern void ext3_check_inodes_bitmap (struct super_block *);
+extern unsigned long ext3_count_free (struct buffer_head *, unsigned);
+
+
+/* inode.c */
+int ext3_forget(handle_t *handle, int is_metadata, struct inode *inode,
+                struct buffer_head *bh, ext3_fsblk_t blocknr);
+struct buffer_head * ext3_getblk (handle_t *, struct inode *, long, int, int *);
+struct buffer_head * ext3_bread (handle_t *, struct inode *, int, int, int *);
+int ext3_get_blocks_handle(handle_t *handle, struct inode *inode,
+                           sector_t iblock, unsigned long maxblocks, struct buffer_head *bh_result,
+                           int create, int extend_disksize);
+
+extern void ext3_read_inode (struct inode *);
+extern int  ext3_write_inode (struct inode *, int);
+extern int  ext3_setattr (struct dentry *, struct iattr *);
+extern void ext3_delete_inode (struct inode *);
+extern int  ext3_sync_inode (handle_t *, struct inode *);
+extern void ext3_discard_reservation (struct inode *);
+extern void ext3_dirty_inode(struct inode *);
+extern int ext3_change_inode_journal_flag(struct inode *, int);
+extern int ext3_get_inode_loc(struct inode *, struct ext3_iloc *);
+extern void ext3_truncate (struct inode *);
+extern void ext3_set_inode_flags(struct inode *);
+extern void ext3_get_inode_flags(struct ext3_inode_info *);
+extern void ext3_set_aops(struct inode *inode);
+
+/* ioctl.c */
+extern int ext3_ioctl (struct inode *, struct file *, unsigned int,
+                       unsigned long);
+extern long ext3_compat_ioctl (struct file *, unsigned int, unsigned long);
+
+/* namei.c */
+extern int ext3_orphan_add(handle_t *, struct inode *);
+extern int ext3_orphan_del(handle_t *, struct inode *);
+extern int ext3_htree_fill_tree(struct file *dir_file, __u32 start_hash,
+                                __u32 start_minor_hash, __u32 *next_hash);
+
+/* resize.c */
+extern int ext3_group_add(struct super_block *sb,
+                          struct ext3_new_group_data *input);
+extern int ext3_group_extend(struct super_block *sb,
+                             struct ext3_super_block *es,
+                             ext3_fsblk_t n_blocks_count);
+
+/* super.c */
+extern void ext3_error (struct super_block *, const char *, const char *, ...)
+__attribute__ ((format (printf, 3, 4)));
+extern void __ext3_std_error (struct super_block *, const char *, int);
+extern void ext3_abort (struct super_block *, const char *, const char *, ...)
+__attribute__ ((format (printf, 3, 4)));
+extern void ext3_warning (struct super_block *, const char *, const char *, ...)
+__attribute__ ((format (printf, 3, 4)));
+extern void ext3_update_dynamic_rev (struct super_block *sb);
+
+#define ext3_std_error(sb, errno)               \
+do {                                \
+    if ((errno))                        \
+        __ext3_std_error((sb), __FUNCTION__, (errno));  \
+} while (0)
+
+/*
+ * Inodes and files operations
+ */
+
+/* dir.c */
+extern const struct file_operations ext3_dir_operations;
+
+/* file.c */
+extern const struct inode_operations ext3_file_inode_operations;
+extern const struct file_operations ext3_file_operations;
+
+/* namei.c */
+extern const struct inode_operations ext3_dir_inode_operations;
+extern const struct inode_operations ext3_special_inode_operations;
+
+/* symlink.c */
+extern const struct inode_operations ext3_symlink_inode_operations;
+extern const struct inode_operations ext3_fast_symlink_inode_operations;
+
+
+#endif  /* __KERNEL__ */
+
+#endif  /* _LINUX_EXT3_FS_H */
diff --git a/src/bsp/lk/lib/fs/ext2/file.c b/src/bsp/lk/lib/fs/ext2/file.c
new file mode 100644
index 0000000..94b0ad0
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/file.c
@@ -0,0 +1,145 @@
+/*
+ * Copyright (c) 2007 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdlib.h>
+#include <err.h>
+#include <debug.h>
+#include <trace.h>
+#include "ext2_priv.h"
+
+#define LOCAL_TRACE 0
+
+int ext2_open_file(fscookie *cookie, const char *path, filecookie **fcookie)
+{
+    ext2_t *ext2 = (ext2_t *)cookie;
+    int err;
+
+    /* do a path lookup */
+    inodenum_t inum;
+    err = ext2_lookup(ext2, path, &inum);
+    if (err < 0)
+        return err;
+
+    /* create the file object */
+    ext2_file_t *file = malloc(sizeof(ext2_file_t));
+    memset(file, 0, sizeof(ext2_file_t));
+
+    /* read in the inode */
+    err = ext2_load_inode(ext2, inum, &file->inode);
+    if (err < 0) {
+        free(file);
+        return err;
+    }
+
+    file->ext2 = ext2;
+    *fcookie = (filecookie *)file;
+
+    return 0;
+}
+
+ssize_t ext2_read_file(filecookie *fcookie, void *buf, off_t offset, size_t len)
+{
+    ext2_file_t *file = (ext2_file_t *)fcookie;
+    int err;
+
+    // test that it's a file
+    if (!S_ISREG(file->inode.i_mode)) {
+        dprintf(INFO, "ext2_read_file: not a file\n");
+        return -1;
+    }
+
+    // read from the inode
+    err = ext2_read_inode(file->ext2, &file->inode, buf, offset, len);
+
+    return err;
+}
+
+int ext2_close_file(filecookie *fcookie)
+{
+    ext2_file_t *file = (ext2_file_t *)fcookie;
+
+    // see if we need to free any of the cache blocks
+    int i;
+    for (i=0; i < 3; i++) {
+        if (file->ind_cache[i].num != 0) {
+            free(file->ind_cache[i].ptr);
+        }
+    }
+
+    free(file);
+
+    return 0;
+}
+
+off_t ext2_file_len(ext2_t *ext2, struct ext2_inode *inode)
+{
+    /* calculate the file size */
+    off_t len = inode->i_size;
+    if ((ext2->sb.s_feature_ro_compat & EXT2_FEATURE_RO_COMPAT_LARGE_FILE) && (S_ISREG(inode->i_mode))) {
+        /* can potentially be a large file */
+        len |= (off_t)inode->i_size_high << 32;
+    }
+
+    return len;
+}
+
+int ext2_stat_file(filecookie *fcookie, struct file_stat *stat)
+{
+    ext2_file_t *file = (ext2_file_t *)fcookie;
+
+    stat->size = ext2_file_len(file->ext2, &file->inode);
+
+    /* is it a dir? */
+    stat->is_dir = false;
+    if (S_ISDIR(file->inode.i_mode))
+        stat->is_dir = true;
+
+    return 0;
+}
+
+int ext2_read_link(ext2_t *ext2, struct ext2_inode *inode, char *str, size_t len)
+{
+    LTRACEF("inode %p, str %p, len %zu\n", inode, str, len);
+
+    off_t linklen = ext2_file_len(ext2, inode);
+
+    if ((linklen < 0) || (linklen + 1 > len))
+        return ERR_NO_MEMORY;
+
+    if (linklen > 60) {
+        int err = ext2_read_inode(ext2, inode, str, 0, linklen);
+        if (err < 0)
+            return err;
+        str[linklen] = 0;
+    } else {
+        memcpy(str, &inode->i_block[0], linklen);
+        str[linklen] = 0;
+    }
+
+    LTRACEF("read link '%s'\n", str);
+
+    return linklen;
+}
+
diff --git a/src/bsp/lk/lib/fs/ext2/io.c b/src/bsp/lk/lib/fs/ext2/io.c
new file mode 100644
index 0000000..5b96ea2
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/io.c
@@ -0,0 +1,269 @@
+/*
+ * Copyright (c) 2007 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <debug.h>
+#include <trace.h>
+#include "ext2_priv.h"
+
+#define LOCAL_TRACE 0
+
+int ext2_read_block(ext2_t *ext2, void *buf, blocknum_t bnum)
+{
+    return bcache_read_block(ext2->cache, buf, bnum);
+}
+
+int ext2_get_block(ext2_t *ext2, void **ptr, blocknum_t bnum)
+{
+    return bcache_get_block(ext2->cache, ptr, bnum);
+}
+
+int ext2_put_block(ext2_t *ext2, blocknum_t bnum)
+{
+    return bcache_put_block(ext2->cache, bnum);
+}
+
+static int ext2_calculate_block_pointer_pos(ext2_t *ext2, blocknum_t block_to_find, uint32_t *level, uint32_t pos[])
+{
+    uint32_t block_ptr_per_block, block_ptr_per_2nd_block;
+
+    // XXX optimize this
+
+    // See if it's in the direct blocks
+    if (block_to_find < EXT2_NDIR_BLOCKS) {
+        *level = 0;
+        pos[0] = block_to_find;
+        return 0;
+    }
+
+    block_ptr_per_block = EXT2_ADDR_PER_BLOCK(ext2->sb);
+    block_to_find -= EXT2_NDIR_BLOCKS;
+    // See if it's in the first indirect block
+    if (block_to_find < block_ptr_per_block) {
+        *level = 1;
+        pos[0] = EXT2_IND_BLOCK;
+        pos[1] = block_to_find;
+        return 0;
+    }
+
+    block_to_find -= block_ptr_per_block;
+    block_ptr_per_2nd_block = block_ptr_per_block * block_ptr_per_block;
+    // See if it's in the second indirect block
+    if (block_to_find < (block_ptr_per_2nd_block)) {
+        *level = 2;
+        pos[0] = EXT2_DIND_BLOCK;
+        pos[1] = block_to_find / block_ptr_per_block;
+        pos[2] = block_to_find % block_ptr_per_block;
+        return 0;
+    }
+
+    block_to_find -= block_ptr_per_2nd_block;
+    // See if it's in the third indirect block
+    if (block_to_find < (block_ptr_per_2nd_block * block_ptr_per_block)) {
+        *level = 3;
+        pos[0] = EXT2_TIND_BLOCK;
+        pos[1] = block_to_find / block_ptr_per_2nd_block;
+        pos[2] = (block_to_find % block_ptr_per_2nd_block) / block_ptr_per_block;
+        pos[3] = (block_to_find % block_ptr_per_2nd_block) % block_ptr_per_block;
+        return 0;
+    }
+
+    // The block requested must be too big.
+    return -1;
+}
+
+// This function returns a pointer to the cache block that corresponds to the indirect block pointer.
+int ext2_get_indirect_block_pointer_cache_block(ext2_t *ext2, struct ext2_inode *inode, blocknum_t **cache_block, uint32_t level, uint32_t pos[], uint *block_loaded)
+{
+    uint32_t current_level = 0;
+    uint current_block = 0, last_block;
+    blocknum_t *block = NULL;
+    int err;
+
+    if ((level > 3) || (level == 0)) {
+        err = -1;
+        goto error;
+    }
+
+    // Dig down into the indirect blocks. When done, current_block should point to the target.
+    while (current_level < level) {
+        if (current_level == 0) {
+            // read the direct block, simulates a prior loop
+            current_block = LE32(inode->i_block[pos[0]]);
+        }
+
+        if (current_block == 0) {
+            err = -1;
+            goto error;
+        }
+
+        last_block = current_block;
+        current_level++;
+        *block_loaded = current_block;
+
+        err = ext2_get_block(ext2, (void **)(void *)&block, current_block);
+        if (err < 0) {
+            goto error;
+        }
+
+        if (current_level < level) {
+            current_block = LE32(block[pos[current_level]]);
+            ext2_put_block(ext2, last_block);
+        }
+    }
+
+    *cache_block = block;
+    return 0;
+
+error:
+    *cache_block = NULL;
+    *block_loaded = 0;
+    return err;
+}
+
+/* translate a file block to a physical block */
+static blocknum_t file_block_to_fs_block(ext2_t *ext2, struct ext2_inode *inode, uint fileblock)
+{
+    int err;
+    blocknum_t block;
+
+    LTRACEF("inode %p, fileblock %u\n", inode, fileblock);
+
+    uint32_t pos[4];
+    uint32_t level = 0;
+    ext2_calculate_block_pointer_pos(ext2, fileblock, &level, pos);
+
+    LTRACEF("level %d, pos 0x%x 0x%x 0x%x 0x%x\n", level, pos[0], pos[1], pos[2], pos[3]);
+
+    if (level == 0) {
+        /* direct block, just return it directly */
+        block = LE32(inode->i_block[fileblock]);
+    } else {
+        /* at least one level of indirection, get a pointer to the final indirect block table and dereference it */
+        blocknum_t *ind_table;
+        blocknum_t phys_block;
+        err = ext2_get_indirect_block_pointer_cache_block(ext2, inode, &ind_table, level, pos, &phys_block);
+        if (err < 0)
+            return 0;
+
+        /* dereference the final entry in the final table */
+        block = LE32(ind_table[pos[level]]);
+        LTRACEF("block %u, indirect_block %u\n", block, phys_block);
+
+        /* release the ref on the cache block */
+        ext2_put_block(ext2, phys_block);
+    }
+
+    LTRACEF("returning %u\n", block);
+
+    return block;
+}
+
+ssize_t ext2_read_inode(ext2_t *ext2, struct ext2_inode *inode, void *_buf, off_t offset, size_t len)
+{
+    int err = 0;
+    size_t bytes_read = 0;
+    uint8_t *buf = _buf;
+
+    /* calculate the file size */
+    off_t file_size = ext2_file_len(ext2, inode);
+
+    LTRACEF("inode %p, offset %lld, len %zd, file_size %lld\n", inode, offset, len, file_size);
+
+    /* trim the read */
+    if (offset > file_size)
+        return 0;
+    if (offset + len >= file_size)
+        len = file_size - offset;
+    if (len == 0)
+        return 0;
+
+    /* calculate the starting file block */
+    uint file_block = offset / EXT2_BLOCK_SIZE(ext2->sb);
+
+    /* handle partial first block */
+    if ((offset % EXT2_BLOCK_SIZE(ext2->sb)) != 0) {
+        uint8_t temp[EXT2_BLOCK_SIZE(ext2->sb)];
+
+        /* calculate the block and read it */
+        blocknum_t phys_block = file_block_to_fs_block(ext2, inode, file_block);
+        if (phys_block == 0) {
+            memset(temp, 0, EXT2_BLOCK_SIZE(ext2->sb));
+        } else {
+            ext2_read_block(ext2, temp, phys_block);
+        }
+
+        /* copy out what we need */
+        size_t block_offset = offset % EXT2_BLOCK_SIZE(ext2->sb);
+        size_t tocopy = MIN(len, EXT2_BLOCK_SIZE(ext2->sb) - block_offset);
+        memcpy(buf, temp + block_offset, tocopy);
+
+        /* increment our stuff */
+        file_block++;
+        len -= tocopy;
+        bytes_read += tocopy;
+        buf += tocopy;
+    }
+
+    /* handle middle blocks */
+    while (len >= EXT2_BLOCK_SIZE(ext2->sb)) {
+        /* calculate the block and read it */
+        blocknum_t phys_block = file_block_to_fs_block(ext2, inode, file_block);
+        if (phys_block == 0) {
+            memset(buf, 0, EXT2_BLOCK_SIZE(ext2->sb));
+        } else {
+            ext2_read_block(ext2, buf, phys_block);
+        }
+
+        /* increment our stuff */
+        file_block++;
+        len -= EXT2_BLOCK_SIZE(ext2->sb);
+        bytes_read += EXT2_BLOCK_SIZE(ext2->sb);
+        buf += EXT2_BLOCK_SIZE(ext2->sb);
+    }
+
+    /* handle partial last block */
+    if (len > 0) {
+        uint8_t temp[EXT2_BLOCK_SIZE(ext2->sb)];
+
+        /* calculate the block and read it */
+        blocknum_t phys_block = file_block_to_fs_block(ext2, inode, file_block);
+        if (phys_block == 0) {
+            memset(temp, 0, EXT2_BLOCK_SIZE(ext2->sb));
+        } else {
+            ext2_read_block(ext2, temp, phys_block);
+        }
+
+        /* copy out what we need */
+        memcpy(buf, temp, len);
+
+        /* increment our stuff */
+        bytes_read += len;
+    }
+
+    LTRACEF("err %d, bytes_read %zu\n", err, bytes_read);
+
+    return (err < 0) ? err : (ssize_t)bytes_read;
+}
+
diff --git a/src/bsp/lk/lib/fs/ext2/rules.mk b/src/bsp/lk/lib/fs/ext2/rules.mk
new file mode 100644
index 0000000..2167847
--- /dev/null
+++ b/src/bsp/lk/lib/fs/ext2/rules.mk
@@ -0,0 +1,16 @@
+LOCAL_DIR := $(GET_LOCAL_DIR)
+
+MODULE := $(LOCAL_DIR)
+
+MODULE_DEPS += \
+	lib/fs \
+	lib/bcache \
+	lib/bio
+
+MODULE_SRCS += \
+	$(LOCAL_DIR)/ext2.c \
+	$(LOCAL_DIR)/dir.c \
+	$(LOCAL_DIR)/io.c \
+	$(LOCAL_DIR)/file.c
+
+include make/module.mk
diff --git a/src/bsp/lk/lib/fs/fs.c b/src/bsp/lk/lib/fs/fs.c
new file mode 100644
index 0000000..378e824
--- /dev/null
+++ b/src/bsp/lk/lib/fs/fs.c
@@ -0,0 +1,622 @@
+/*
+ * Copyright (c) 2009-2015 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#include <debug.h>
+#include <trace.h>
+#include <list.h>
+#include <err.h>
+#include <string.h>
+#include <stdlib.h>
+#include <lib/fs.h>
+#include <lib/bio.h>
+#include <lk/init.h>
+#include <kernel/mutex.h>
+
+#define LOCAL_TRACE 0
+
+struct fs_mount {
+    struct list_node node;
+
+    char *path;
+    bdev_t *dev;
+    fscookie *cookie;
+    int ref;
+    const struct fs_api *api;
+};
+
+struct filehandle {
+    filecookie *cookie;
+    struct fs_mount *mount;
+};
+
+struct dirhandle {
+    dircookie *cookie;
+    struct fs_mount *mount;
+};
+
+static mutex_t mount_lock = MUTEX_INITIAL_VALUE(mount_lock);
+static struct list_node mounts = LIST_INITIAL_VALUE(mounts);
+static struct list_node fses = LIST_INITIAL_VALUE(fses);
+
+// defined in the linker script
+extern const struct fs_impl __fs_impl_start;
+extern const struct fs_impl __fs_impl_end;
+
+static const struct fs_impl *find_fs(const char *name)
+{
+    for (const struct fs_impl *fs = &__fs_impl_start; fs != &__fs_impl_end; fs++) {
+        if (!strcmp(name, fs->name))
+            return fs;
+    }
+    return NULL;
+}
+
+
+// find a mount structure based on the prefix of this path
+// bump the ref to the mount structure before returning
+static struct fs_mount *find_mount(const char *path, const char **trimmed_path)
+{
+    struct fs_mount *mount;
+    size_t pathlen = strlen(path);
+
+    mutex_acquire(&mount_lock);
+    list_for_every_entry(&mounts, mount, struct fs_mount, node) {
+        size_t mountpathlen = strlen(mount->path);
+        if (pathlen < mountpathlen)
+            continue;
+
+        LTRACEF("comparing %s with %s\n", path, mount->path);
+
+        if (memcmp(path, mount->path, mountpathlen) == 0) {
+            if (trimmed_path)
+                *trimmed_path = &path[mountpathlen];
+
+            mount->ref++;
+
+            mutex_release(&mount_lock);
+            return mount;
+        }
+    }
+
+    mutex_release(&mount_lock);
+    return NULL;
+}
+
+// decrement the ref to the mount structure, which may
+// cause an unmount operation
+static void put_mount(struct fs_mount *mount)
+{
+    mutex_acquire(&mount_lock);
+    if ((--mount->ref) == 0) {
+        list_delete(&mount->node);
+        mount->api->unmount(mount->cookie);
+        free(mount->path);
+        if (mount->dev)
+            bio_close(mount->dev);
+        free(mount);
+    }
+    mutex_release(&mount_lock);
+}
+
+static status_t mount(const char *path, const char *device, const struct fs_api *api)
+{
+    struct fs_mount *mount;
+    char temppath[FS_MAX_PATH_LEN];
+
+    strlcpy(temppath, path, sizeof(temppath));
+    fs_normalize_path(temppath);
+
+    if (temppath[0] != '/')
+        return ERR_BAD_PATH;
+
+    /* see if there's already something at this path, abort if there is */
+    mount = find_mount(temppath, NULL);
+    if (mount) {
+        put_mount(mount);
+        return ERR_ALREADY_MOUNTED;
+    }
+
+    /* open a bio device if the string is nonnull */
+    bdev_t *dev = NULL;
+    if (device && device[0] != '\0') {
+        dev = bio_open(device);
+        if (!dev)
+            return ERR_NOT_FOUND;
+    }
+
+    /* call into the fs implementation */
+    fscookie *cookie;
+    status_t err = api->mount(dev, &cookie);
+    if (err < 0) {
+        if (dev) bio_close(dev);
+        return err;
+    }
+
+    /* create the mount structure and add it to the list */
+    mount = malloc(sizeof(struct fs_mount));
+    mount->path = strdup(temppath);
+    mount->dev = dev;
+    mount->cookie = cookie;
+    mount->ref = 1;
+    mount->api = api;
+
+    list_add_head(&mounts, &mount->node);
+
+    return 0;
+
+}
+
+status_t fs_format_device(const char *fsname, const char *device, const void *args)
+{
+    const struct fs_impl *fs = find_fs(fsname);
+    if (!fs) {
+        return ERR_NOT_FOUND;
+    }
+
+    if (fs->api->format == NULL) {
+        return ERR_NOT_SUPPORTED;
+    }
+
+    bdev_t *dev = NULL;
+    if (device && device[0] != '\0') {
+        dev = bio_open(device);
+        if (!dev)
+            return ERR_NOT_FOUND;
+    }
+
+    return fs->api->format(dev, args);
+}
+
+status_t fs_mount(const char *path, const char *fsname, const char *device)
+{
+    const struct fs_impl *fs = find_fs(fsname);
+    if (!fs)
+        return ERR_NOT_FOUND;
+
+    return mount(path, device, fs->api);
+}
+
+status_t fs_unmount(const char *path)
+{
+    char temppath[FS_MAX_PATH_LEN];
+
+    strlcpy(temppath, path, sizeof(temppath));
+    fs_normalize_path(temppath);
+
+    struct fs_mount *mount = find_mount(temppath, NULL);
+    if (!mount)
+        return ERR_NOT_FOUND;
+
+    // return the ref that find_mount added and one extra
+    put_mount(mount);
+    put_mount(mount);
+
+    return 0;
+}
+
+
+status_t fs_open_file(const char *path, filehandle **handle)
+{
+    char temppath[FS_MAX_PATH_LEN];
+
+    strlcpy(temppath, path, sizeof(temppath));
+    fs_normalize_path(temppath);
+
+    LTRACEF("path %s temppath %s\n", path, temppath);
+
+    const char *newpath;
+    struct fs_mount *mount = find_mount(temppath, &newpath);
+    if (!mount)
+        return ERR_NOT_FOUND;
+
+    LTRACEF("path %s temppath %s newpath %s\n", path, temppath, newpath);
+
+    filecookie *cookie;
+    status_t err = mount->api->open(mount->cookie, newpath, &cookie);
+    if (err < 0) {
+        put_mount(mount);
+        return err;
+    }
+
+    filehandle *f = malloc(sizeof(*f));
+    f->cookie = cookie;
+    f->mount = mount;
+    *handle = f;
+
+    return 0;
+}
+
+status_t fs_file_ioctl(filehandle *handle, int request, void *argp)
+{
+    LTRACEF("filehandle %p, request %d, argp, %p\n", handle, request, argp);
+
+    if (unlikely(!handle || !handle->mount ||
+                 !handle->mount->api || !handle->mount->api->file_ioctl)) {
+        return ERR_INVALID_ARGS;
+    }
+
+    return handle->mount->api->file_ioctl(handle->cookie, request, argp);
+}
+
+status_t fs_create_file(const char *path, filehandle **handle, uint64_t len)
+{
+    char temppath[FS_MAX_PATH_LEN];
+
+    strlcpy(temppath, path, sizeof(temppath));
+    fs_normalize_path(temppath);
+
+    const char *newpath;
+    struct fs_mount *mount = find_mount(temppath, &newpath);
+    if (!mount)
+        return ERR_NOT_FOUND;
+
+    if (!mount->api->create) {
+        put_mount(mount);
+        return ERR_NOT_SUPPORTED;
+    }
+
+    filecookie *cookie;
+    status_t err = mount->api->create(mount->cookie, newpath, &cookie, len);
+    if (err < 0) {
+        put_mount(mount);
+        return err;
+    }
+
+    filehandle *f = malloc(sizeof(*f));
+    f->cookie = cookie;
+    f->mount = mount;
+    *handle = f;
+
+    return 0;
+}
+
+status_t fs_remove_file(const char *path)
+{
+    char temppath[FS_MAX_PATH_LEN];
+
+    strlcpy(temppath, path, sizeof(temppath));
+    fs_normalize_path(temppath);
+
+    const char *newpath;
+    struct fs_mount *mount = find_mount(temppath, &newpath);
+    if (!mount)
+        return ERR_NOT_FOUND;
+
+    if (!mount->api->remove) {
+        put_mount(mount);
+        return ERR_NOT_SUPPORTED;
+    }
+
+    status_t err = mount->api->remove(mount->cookie, newpath);
+
+    put_mount(mount);
+
+    return err;
+}
+
+ssize_t fs_read_file(filehandle *handle, void *buf, off_t offset, size_t len)
+{
+    return handle->mount->api->read(handle->cookie, buf, offset, len);
+}
+
+ssize_t fs_write_file(filehandle *handle, const void *buf, off_t offset, size_t len)
+{
+    if (!handle->mount->api->write)
+        return ERR_NOT_SUPPORTED;
+
+    return handle->mount->api->write(handle->cookie, buf, offset, len);
+}
+
+status_t fs_close_file(filehandle *handle)
+{
+    status_t err = handle->mount->api->close(handle->cookie);
+    if (err < 0)
+        return err;
+
+    put_mount(handle->mount);
+    free(handle);
+    return 0;
+}
+
+status_t fs_stat_file(filehandle *handle, struct file_stat *stat)
+{
+    return handle->mount->api->stat(handle->cookie, stat);
+}
+
+status_t fs_make_dir(const char *path)
+{
+    char temppath[FS_MAX_PATH_LEN];
+
+    strlcpy(temppath, path, sizeof(temppath));
+    fs_normalize_path(temppath);
+
+    const char *newpath;
+    struct fs_mount *mount = find_mount(temppath, &newpath);
+    if (!mount)
+        return ERR_NOT_FOUND;
+
+    if (!mount->api->mkdir) {
+        put_mount(mount);
+        return ERR_NOT_SUPPORTED;
+    }
+
+    status_t err = mount->api->mkdir(mount->cookie, newpath);
+
+    put_mount(mount);
+
+    return err;
+}
+
+status_t fs_open_dir(const char *path, dirhandle **handle)
+{
+    char temppath[FS_MAX_PATH_LEN];
+
+    strlcpy(temppath, path, sizeof(temppath));
+    fs_normalize_path(temppath);
+
+    LTRACEF("path %s temppath %s\n", path, temppath);
+
+    const char *newpath;
+    struct fs_mount *mount = find_mount(temppath, &newpath);
+    if (!mount)
+        return ERR_NOT_FOUND;
+
+    LTRACEF("path %s temppath %s newpath %s\n", path, temppath, newpath);
+
+    if (!mount->api->opendir) {
+        put_mount(mount);
+        return ERR_NOT_SUPPORTED;
+    }
+
+    dircookie *cookie;
+    status_t err = mount->api->opendir(mount->cookie, newpath, &cookie);
+    if (err < 0) {
+        put_mount(mount);
+        return err;
+    }
+
+    dirhandle *d = malloc(sizeof(*d));
+    d->cookie = cookie;
+    d->mount = mount;
+    *handle = d;
+
+    return 0;
+}
+
+status_t fs_read_dir(dirhandle *handle, struct dirent *ent)
+{
+    if (!handle->mount->api->readdir)
+        return ERR_NOT_SUPPORTED;
+
+    return handle->mount->api->readdir(handle->cookie, ent);
+}
+
+status_t fs_close_dir(dirhandle *handle)
+{
+    if (!handle->mount->api->closedir)
+        return ERR_NOT_SUPPORTED;
+
+    status_t err = handle->mount->api->closedir(handle->cookie);
+    if (err < 0)
+        return err;
+
+    put_mount(handle->mount);
+    free(handle);
+    return 0;
+}
+
+status_t fs_stat_fs(const char *mountpoint, struct fs_stat *stat)
+{
+    LTRACEF("mountpoint %s stat %p\n", mountpoint, stat);
+
+    if (!stat) {
+        return ERR_INVALID_ARGS;
+    }
+
+    const char *newpath;
+    struct fs_mount *mount = find_mount(mountpoint, &newpath);
+    if (!mount) {
+        return ERR_NOT_FOUND;
+    }
+
+    if (!mount->api->fs_stat) {
+        put_mount(mount);
+        return ERR_NOT_SUPPORTED;
+    }
+
+    status_t result = mount->api->fs_stat(mount->cookie, stat);
+
+    put_mount(mount);
+
+    return result;
+}
+
+
+ssize_t fs_load_file(const char *path, void *ptr, size_t maxlen)
+{
+    filehandle *handle;
+
+    /* open the file */
+    status_t err = fs_open_file(path, &handle);
+    if (err < 0)
+        return err;
+
+    /* stat it for size, see how much we need to read */
+    struct file_stat stat;
+    fs_stat_file(handle, &stat);
+
+    ssize_t read_bytes = fs_read_file(handle, ptr, 0, MIN(maxlen, stat.size));
+
+    fs_close_file(handle);
+
+    return read_bytes;
+}
+
+const char *trim_name(const char *_name)
+{
+    const char *name = &_name[0];
+    // chew up leading spaces
+    while (*name == ' ')
+        name++;
+
+    // chew up leading slashes
+    while (*name == '/')
+        name++;
+
+    return name;
+}
+
+
+void fs_normalize_path(char *path)
+{
+    int outpos;
+    int pos;
+    char c;
+    bool done;
+    enum {
+        INITIAL,
+        FIELD_START,
+        IN_FIELD,
+        SEP,
+        SEEN_SEP,
+        DOT,
+        SEEN_DOT,
+        DOTDOT,
+        SEEN_DOTDOT,
+    } state;
+
+    state = INITIAL;
+    pos = 0;
+    outpos = 0;
+    done = false;
+
+    /* remove duplicate path seperators, flatten empty fields (only composed of .), backtrack fields with .., remove trailing slashes */
+    while (!done) {
+        c = path[pos];
+        switch (state) {
+            case INITIAL:
+                if (c == '/') {
+                    state = SEP;
+                } else if (c == '.') {
+                    state = DOT;
+                } else {
+                    state = FIELD_START;
+                }
+                break;
+            case FIELD_START:
+                if (c == '.') {
+                    state = DOT;
+                } else if (c == 0) {
+                    done = true;
+                } else {
+                    state = IN_FIELD;
+                }
+                break;
+            case IN_FIELD:
+                if (c == '/') {
+                    state = SEP;
+                } else if (c == 0) {
+                    done = true;
+                } else {
+                    path[outpos++] = c;
+                    pos++;
+                }
+                break;
+            case SEP:
+                pos++;
+                path[outpos++] = '/';
+                state = SEEN_SEP;
+                break;
+            case SEEN_SEP:
+                if (c == '/') {
+                    // eat it
+                    pos++;
+                } else if (c == 0) {
+                    done = true;
+                } else {
+                    state = FIELD_START;
+                }
+                break;
+            case DOT:
+                pos++; // consume the dot
+                state = SEEN_DOT;
+                break;
+            case SEEN_DOT:
+                if (c == '.') {
+                    // dotdot now
+                    state = DOTDOT;
+                } else if (c == '/') {
+                    // a field composed entirely of a .
+                    // consume the / and move directly to the SEEN_SEP state
+                    pos++;
+                    state = SEEN_SEP;
+                } else if (c == 0) {
+                    done = true;
+                } else {
+                    // a field prefixed with a .
+                    // emit a . and move directly into the IN_FIELD state
+                    path[outpos++] = '.';
+                    state = IN_FIELD;
+                }
+                break;
+            case DOTDOT:
+                pos++; // consume the dot
+                state = SEEN_DOTDOT;
+                break;
+            case SEEN_DOTDOT:
+                if (c == '/' || c == 0) {
+                    // a field composed entirely of '..'
+                    // search back and consume a field we've already emitted
+                    if (outpos > 0) {
+                        // we have already consumed at least one field
+                        outpos--;
+
+                        // walk backwards until we find the next field boundary
+                        while (outpos > 0) {
+                            if (path[outpos - 1] == '/') {
+                                break;
+                            }
+                            outpos--;
+                        }
+                    }
+                    pos++;
+                    state = SEEN_SEP;
+                    if (c == 0)
+                        done = true;
+                } else {
+                    // a field prefixed with ..
+                    // emit the .. and move directly to the IN_FIELD state
+                    path[outpos++] = '.';
+                    path[outpos++] = '.';
+                    state = IN_FIELD;
+                }
+                break;
+        }
+    }
+
+    /* dont end with trailing slashes */
+    if (outpos > 0 && path[outpos - 1] == '/')
+        outpos--;
+
+    path[outpos++] = 0;
+}
+
diff --git a/src/bsp/lk/lib/fs/fs.ld b/src/bsp/lk/lib/fs/fs.ld
new file mode 100644
index 0000000..7106291
--- /dev/null
+++ b/src/bsp/lk/lib/fs/fs.ld
@@ -0,0 +1,8 @@
+SECTIONS {
+    .fs_impls : {
+        __fs_impl_start = .;
+        KEEP (*(.fs_impl))
+        __fs_impl_end = .;
+    }
+}
+INSERT AFTER .rodata;
diff --git a/src/bsp/lk/lib/fs/include/lib/fs.h b/src/bsp/lk/lib/fs/include/lib/fs.h
new file mode 100644
index 0000000..a3d39ad
--- /dev/null
+++ b/src/bsp/lk/lib/fs/include/lib/fs.h
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2009-2015 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+#pragma once
+
+#include <stdbool.h>
+#include <sys/types.h>
+#include <compiler.h>
+
+#define FS_MAX_PATH_LEN 128
+#define FS_MAX_FILE_LEN 64
+
+// Generic FS ioctls
+enum fs_ioctl_num {
+    FS_IOCTL_NULL = 0,
+    FS_IOCTL_GET_FILE_ADDR,
+};
+
+struct file_stat {
+    bool is_dir;
+    uint64_t size;
+    uint64_t capacity;
+};
+
+struct fs_stat {
+    uint64_t free_space;
+    uint64_t total_space;
+
+    uint32_t free_inodes;
+    uint32_t total_inodes;
+};
+
+struct dirent {
+    char name[FS_MAX_FILE_LEN];
+};
+
+typedef struct filehandle filehandle;
+typedef struct dirhandle dirhandle;
+
+
+status_t fs_format_device(const char *fsname, const char *device, const void *args) __NONNULL((1));
+status_t fs_mount(const char *path, const char *fs, const char *device) __NONNULL((1)) __NONNULL((2));
+status_t fs_unmount(const char *path) __NONNULL();
+status_t fs_file_ioctl(filehandle *handle, int request, void *argp) __NONNULL((1)) __NONNULL((3));
+
+/* file api */
+status_t fs_create_file(const char *path, filehandle **handle, uint64_t len) __NONNULL();
+status_t fs_open_file(const char *path, filehandle **handle) __NONNULL();
+status_t fs_remove_file(const char *path) __NONNULL();
+ssize_t fs_read_file(filehandle *handle, void *buf, off_t offset, size_t len) __NONNULL();
+ssize_t fs_write_file(filehandle *handle, const void *buf, off_t offset, size_t len) __NONNULL();
+status_t fs_close_file(filehandle *handle) __NONNULL();
+status_t fs_stat_file(filehandle *handle, struct file_stat *) __NONNULL((1));
+
+/* dir api */
+status_t fs_make_dir(const char *path) __NONNULL();
+status_t fs_open_dir(const char *path, dirhandle **handle) __NONNULL();
+status_t fs_read_dir(dirhandle *handle, struct dirent *ent) __NONNULL();
+status_t fs_close_dir(dirhandle *handle) __NONNULL();
+
+status_t fs_stat_fs(const char *mountpoint, struct fs_stat *stat) __NONNULL((1)) __NONNULL((2));
+
+/* convenience routines */
+ssize_t fs_load_file(const char *path, void *ptr, size_t maxlen) __NONNULL();
+
+/* walk through a path string, removing duplicate path seperators, flattening . and .. references */
+void fs_normalize_path(char *path) __NONNULL();
+
+/* Remove any leading spaces or slashes */
+const char *trim_name(const char *_name);
+
+/* file system api */
+typedef struct fscookie fscookie;
+typedef struct filecookie filecookie;
+typedef struct dircookie dircookie;
+struct bdev;
+
+struct fs_api {
+    status_t (*format)(struct bdev *, const void *);
+    status_t (*fs_stat)(fscookie *, struct fs_stat *);
+
+    status_t (*mount)(struct bdev *, fscookie **);
+    status_t (*unmount)(fscookie *);
+    status_t (*open)(fscookie *, const char *, filecookie **);
+    status_t (*create)(fscookie *, const char *, filecookie **, uint64_t);
+    status_t (*remove)(fscookie *, const char *);
+    status_t (*stat)(filecookie *, struct file_stat *);
+    ssize_t (*read)(filecookie *, void *, off_t, size_t);
+    ssize_t (*write)(filecookie *, const void *, off_t, size_t);
+    status_t (*close)(filecookie *);
+
+    status_t (*mkdir)(fscookie *, const char *);
+    status_t (*opendir)(fscookie *, const char *, dircookie **) __NONNULL();
+    status_t (*readdir)(dircookie *, struct dirent *) __NONNULL();
+    status_t (*closedir)(dircookie *) __NONNULL();
+
+    status_t (*file_ioctl)(filecookie *, int, void *);
+};
+
+struct fs_impl {
+    const char *name;
+    const struct fs_api *api;
+};
+
+/* define in your fs implementation to register your api with the fs layer */
+#define STATIC_FS_IMPL(_name, _api) const struct fs_impl __fs_impl_##_name __ALIGNED(sizeof(void *)) __SECTION(".fs_impl") = \
+    { .name = #_name, .api = _api }
+
diff --git a/src/bsp/lk/lib/fs/include/lib/fs/spifs.h b/src/bsp/lk/lib/fs/include/lib/fs/spifs.h
new file mode 100644
index 0000000..c7d31b0
--- /dev/null
+++ b/src/bsp/lk/lib/fs/include/lib/fs/spifs.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2015 Gurjant Kalsi <me@gurjantkalsi.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef LIB_FS_SPIFS_H_
+#define LIB_FS_SPIFS_H_
+
+#include <lib/fs.h>
+
+typedef struct {
+    uint32_t toc_pages;
+} spifs_format_args_t;
+
+#endif  // LIB_FS_SPIFS_H_
diff --git a/src/bsp/lk/lib/fs/memfs/memfs.c b/src/bsp/lk/lib/fs/memfs/memfs.c
new file mode 100644
index 0000000..6d5ad12
--- /dev/null
+++ b/src/bsp/lk/lib/fs/memfs/memfs.c
@@ -0,0 +1,396 @@
+/*
+ * Copyright (c) 2015 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <string.h>
+#include <stdlib.h>
+#include <debug.h>
+#include <err.h>
+#include <trace.h>
+#include <list.h>
+#include <lk/init.h>
+#include <lib/fs.h>
+#include <kernel/mutex.h>
+
+#define LOCAL_TRACE 0
+
+typedef struct {
+    struct list_node files;
+    struct list_node dcookies;
+
+    mutex_t lock;
+} memfs_t;
+
+typedef struct {
+    struct list_node node;
+    memfs_t *fs;
+
+    // name
+    char *name;
+
+    // main data area
+    uint8_t *ptr;
+    size_t len;
+} memfs_file_t;
+
+struct dircookie {
+    struct list_node node;
+    memfs_t *fs;
+
+    // next entry that will be returned
+    memfs_file_t *next_file;
+};
+
+static memfs_file_t *find_file(memfs_t *mem, const char *name)
+{
+    memfs_file_t *file;
+    list_for_every_entry(&mem->files, file, memfs_file_t, node) {
+        if (!strcmp(name, file->name))
+            return file;
+    }
+
+    return NULL;
+}
+
+static status_t memfs_mount(struct bdev *dev, fscookie **cookie)
+{
+    LTRACEF("dev %p, cookie %p\n", dev, cookie);
+
+    memfs_t *mem = malloc(sizeof(*mem));
+    if (!mem)
+        return ERR_NO_MEMORY;
+
+    list_initialize(&mem->files);
+    list_initialize(&mem->dcookies);
+    mutex_init(&mem->lock);
+
+    *cookie = (fscookie *)mem;
+
+    return NO_ERROR;
+}
+
+static void free_file(memfs_file_t *file)
+{
+    free(file->ptr);
+    free(file->name);
+    free(file);
+}
+
+static status_t memfs_unmount(fscookie *cookie)
+{
+    LTRACEF("cookie %p\n", cookie);
+
+    memfs_t *mem = (memfs_t *)cookie;
+
+    mutex_acquire(&mem->lock);
+
+    // free all the files
+    memfs_file_t *file;
+    while ((file = list_remove_head_type(&mem->files, memfs_file_t, node))) {
+        free_file(file);
+    }
+
+    mutex_release(&mem->lock);
+
+    free(mem);
+
+    return NO_ERROR;
+}
+
+static status_t memfs_create(fscookie *cookie, const char *name, filecookie **fcookie, uint64_t len)
+{
+    status_t err;
+
+    LTRACEF("cookie %p name '%s' filecookie %p len %llu\n", cookie, name, fcookie, len);
+
+    memfs_t *mem = (memfs_t *)cookie;
+
+    if (len >= ULONG_MAX)
+        return ERR_NO_MEMORY;
+
+    // make sure we strip out any leading /
+    name = trim_name(name);
+
+    // we can't handle directories right now, so fail if the file has a / in its name
+    if (strchr(name, '/'))
+        return ERR_NOT_SUPPORTED;
+
+    mutex_acquire(&mem->lock);
+
+    // see if the file already exists
+    if (find_file(mem, name)) {
+        err = ERR_ALREADY_EXISTS;
+        goto out;
+    }
+
+    // allocate a new file
+    memfs_file_t *file = malloc(sizeof(*file));
+    if (!file) {
+        err = ERR_NO_MEMORY;
+        goto out;
+    }
+
+    // allocate the space for it
+    file->ptr = calloc(1, len);
+    if (!file->ptr) {
+        free(file);
+        err = ERR_NO_MEMORY;
+        goto out;
+    }
+    file->len = len;
+
+    // fill in some metadata and stuff it in the file list
+    file->name = strdup(name);
+    file->fs = mem;
+
+    list_add_tail(&mem->files, &file->node);
+
+    *fcookie = (filecookie *)file;
+
+    err = NO_ERROR;
+
+out:
+    mutex_release(&mem->lock);
+
+    return err;
+}
+
+static status_t memfs_open(fscookie *cookie, const char *name, filecookie **fcookie)
+{
+    LTRACEF("cookie %p name '%s' filecookie %p\n", cookie, name, fcookie);
+
+    memfs_t *mem = (memfs_t *)cookie;
+
+    // make sure we strip out any leading /
+    name = trim_name(name);
+
+    mutex_acquire(&mem->lock);
+    memfs_file_t *file = find_file(mem, name);
+    mutex_release(&mem->lock);
+
+    if (!file)
+        return ERR_NOT_FOUND;
+
+    *fcookie = (filecookie *)file;
+
+    return NO_ERROR;
+}
+
+static status_t memfs_remove(fscookie *cookie, const char *name)
+{
+    LTRACEF("cookie %p name '%s'\n", cookie, name);
+
+    memfs_t *mem = (memfs_t *)cookie;
+
+    // make sure we strip out any leading /
+    name = trim_name(name);
+
+    mutex_acquire(&mem->lock);
+    memfs_file_t *file = find_file(mem, name);
+    if (file)
+        list_delete(&file->node);
+    mutex_release(&mem->lock);
+
+    if (!file)
+        return ERR_NOT_FOUND;
+
+    // XXX make sure there are no open file handles
+    free_file(file);
+
+    return NO_ERROR;
+}
+
+static status_t memfs_close(filecookie *fcookie)
+{
+    memfs_file_t *file = (memfs_file_t *)fcookie;
+
+    LTRACEF("cookie %p name '%s'\n", fcookie, file->name);
+
+    return NO_ERROR;
+}
+
+static ssize_t memfs_read(filecookie *fcookie, void *buf, off_t off, size_t len)
+{
+    LTRACEF("filecookie %p buf %p offset %lld len %zu\n", fcookie, buf, off, len);
+
+    memfs_file_t *file = (memfs_file_t *)fcookie;
+
+    if (off < 0)
+        return ERR_INVALID_ARGS;
+
+    mutex_acquire(&file->fs->lock);
+
+    if (off >= file->len) {
+        len = 0;
+    } else if (off + len > file->len) {
+        len = file->len - off;
+    }
+
+    // copy that floppy
+    memcpy(buf, file->ptr + off, len);
+
+    mutex_release(&file->fs->lock);
+
+    return len;
+}
+
+static ssize_t memfs_write(filecookie *fcookie, const void *buf, off_t off, size_t len)
+{
+    LTRACEF("filecookie %p buf %p offset %lld len %zu\n", fcookie, buf, off, len);
+
+    memfs_file_t *file = (memfs_file_t *)fcookie;
+
+    if (off < 0)
+        return ERR_INVALID_ARGS;
+
+    mutex_acquire(&file->fs->lock);
+
+    // see if this write will extend the file
+    if (off + len > file->len) {
+        void *ptr = realloc(file->ptr, off + len);
+        if (!ptr) {
+            mutex_release(&file->fs->lock);
+            return ERR_NO_MEMORY;
+        }
+
+        file->ptr = ptr;
+        file->len = off + len;
+    }
+
+    memcpy(file->ptr + off, buf, len);
+
+    mutex_release(&file->fs->lock);
+
+    return len;
+}
+
+static status_t memfs_stat(filecookie *fcookie, struct file_stat *stat)
+{
+    LTRACEF("filecookie %p stat %p\n", fcookie, stat);
+
+    memfs_file_t *file = (memfs_file_t *)fcookie;
+
+    mutex_acquire(&file->fs->lock);
+
+    if (stat) {
+        stat->is_dir = false;
+        stat->size = file->len;
+    }
+
+    mutex_release(&file->fs->lock);
+
+    return NO_ERROR;
+}
+
+static status_t memfs_opendir(fscookie *cookie, const char *name, dircookie **dcookie)
+{
+    LTRACEF("cookie %p name '%s' dircookie %p\n", cookie, name, dcookie);
+
+    memfs_t *mem = (memfs_t *)cookie;
+
+    // make sure we strip out any leading /
+    name = trim_name(name);
+
+    // at the moment, we only support opening "" (with / stripped)
+    if (strcmp("", name))
+        return ERR_NOT_FOUND;
+
+    // allocate a dir cookie, point it at the first file, and stuff it in the dircookie jar
+    dircookie *dir = malloc(sizeof(*dir));
+    if (!dir)
+        return ERR_NO_MEMORY;
+
+    dir->fs = mem;
+
+    mutex_acquire(&mem->lock);
+    dir->next_file = list_peek_head_type(&mem->files, memfs_file_t, node);
+    list_add_head(&mem->dcookies, &dir->node);
+    mutex_release(&mem->lock);
+
+    *dcookie = dir;
+
+    return NO_ERROR;
+}
+
+static status_t memfs_readdir(dircookie *dcookie, struct dirent *ent)
+{
+    status_t err;
+
+    LTRACEF("dircookie %p ent %p\n", dcookie, ent);
+
+    if (!ent)
+        return ERR_INVALID_ARGS;
+
+    mutex_acquire(&dcookie->fs->lock);
+
+    // return the next file in the list and bump the cursor
+    if (dcookie->next_file) {
+        strlcpy(ent->name, dcookie->next_file->name, sizeof(ent->name));
+        dcookie->next_file = list_next_type(&dcookie->fs->files, &dcookie->next_file->node, memfs_file_t, node);
+        err = NO_ERROR;
+    } else {
+        err = ERR_NOT_FOUND;
+    }
+
+    mutex_release(&dcookie->fs->lock);
+
+    return err;
+}
+
+static status_t memfs_closedir(dircookie *dcookie)
+{
+    LTRACEF("dircookie %p\n", dcookie);
+
+    // free the dircookie
+    mutex_acquire(&dcookie->fs->lock);
+    list_delete(&dcookie->node);
+    mutex_release(&dcookie->fs->lock);
+
+    free(dcookie);
+
+    return NO_ERROR;
+}
+
+static const struct fs_api memfs_api = {
+    .mount = memfs_mount,
+    .unmount = memfs_unmount,
+
+    .create = memfs_create,
+    .open = memfs_open,
+    .remove = memfs_remove,
+    .close = memfs_close,
+
+    .read = memfs_read,
+    .write = memfs_write,
+
+    .stat = memfs_stat,
+
+#if 0
+    status_t (*mkdir)(fscookie *, const char *);
+#endif
+    .opendir = memfs_opendir,
+    .readdir = memfs_readdir,
+    .closedir = memfs_closedir,
+
+};
+
+STATIC_FS_IMPL(memfs, &memfs_api);
diff --git a/src/bsp/lk/lib/fs/memfs/rules.mk b/src/bsp/lk/lib/fs/memfs/rules.mk
new file mode 100644
index 0000000..2cab84b
--- /dev/null
+++ b/src/bsp/lk/lib/fs/memfs/rules.mk
@@ -0,0 +1,10 @@
+LOCAL_DIR := $(GET_LOCAL_DIR)
+
+MODULE := $(LOCAL_DIR)
+
+MODULE_DEPS := lib/fs
+
+MODULE_SRCS += \
+	$(LOCAL_DIR)/memfs.c
+
+include make/module.mk
diff --git a/src/bsp/lk/lib/fs/rules.mk b/src/bsp/lk/lib/fs/rules.mk
new file mode 100644
index 0000000..10be693
--- /dev/null
+++ b/src/bsp/lk/lib/fs/rules.mk
@@ -0,0 +1,12 @@
+LOCAL_DIR := $(GET_LOCAL_DIR)
+
+MODULE := $(LOCAL_DIR)
+
+MODULE_SRCS += \
+	$(LOCAL_DIR)/fs.c \
+	$(LOCAL_DIR)/debug.c \
+	$(LOCAL_DIR)/shell.c
+
+EXTRA_LINKER_SCRIPTS += $(LOCAL_DIR)/fs.ld
+
+include make/module.mk
diff --git a/src/bsp/lk/lib/fs/shell.c b/src/bsp/lk/lib/fs/shell.c
new file mode 100644
index 0000000..1dbd6de
--- /dev/null
+++ b/src/bsp/lk/lib/fs/shell.c
@@ -0,0 +1,316 @@
+/*
+ * Copyright (c) 2015 Travis Geiselbrecht
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <err.h>
+#include <debug.h>
+#include <string.h>
+#include <stdio.h>
+#include <trace.h>
+#include <stdlib.h>
+#include <platform.h>
+#include <lib/console.h>
+#include <lib/fs.h>
+
+/* shell console hooks for manipulating the file system */
+
+#if WITH_LIB_CONSOLE
+
+static char *cwd = NULL;
+
+static void set_cwd(const char *path)
+{
+    if (!path) {
+        free(cwd);
+        cwd = NULL;
+        return;
+    }
+
+    size_t len = strlen(path) + 1;
+    char *new_cwd = realloc(cwd, len);
+    if (new_cwd) {
+        cwd = new_cwd;
+        memcpy(cwd, path, len);
+    }
+}
+
+static const char *get_cwd(void)
+{
+    if (!cwd)
+        return "/";
+    return cwd;
+}
+
+static char *prepend_cwd(char *path, size_t len, const char *arg)
+{
+    path[0] = '\0';
+
+    if (!arg || arg[0] != '/') {
+        strlcat(path, get_cwd(), len);
+        if (arg && path[strlen(path) - 1] != '/')
+            strlcat(path, "/", len);
+    }
+    if (arg) {
+        strlcat(path, arg, len);
+    }
+
+    return path;
+}
+
+static int cmd_ls(int argc, const cmd_args *argv)
+{
+    status_t status = NO_ERROR;
+
+    // construct the path
+    char *path = malloc(FS_MAX_PATH_LEN);
+    prepend_cwd(path, FS_MAX_PATH_LEN, (argc >= 2) ? argv[1].str : NULL);
+
+    dirhandle *dhandle;
+    status = fs_open_dir(path, &dhandle);
+    if (status < 0) {
+        printf("error %d opening dir '%s'\n", status, path);
+        goto err;
+    }
+
+    size_t pathlen = strlen(path);
+
+    status_t err;
+    struct dirent ent;
+    while ((err = fs_read_dir(dhandle, &ent)) >= 0) {
+        struct file_stat stat;
+        filehandle *handle;
+
+        // append our filename to the path
+        strlcat(path, "/", FS_MAX_PATH_LEN);
+        strlcat(path, ent.name, FS_MAX_PATH_LEN);
+
+        err = fs_open_file(path, &handle);
+
+        // restore the old path
+        path[pathlen] = '\0';
+
+        if (err < 0) {
+            printf("error %d opening file '%s'\n", err, path);
+            continue;
+        }
+
+        // stat the file
+        err = fs_stat_file(handle, &stat);
+        fs_close_file(handle);
+        if (err < 0) {
+            printf("error %d statting file\n", err);
+            continue;
+        }
+
+        printf("%c %16llu %s\n", stat.is_dir ? 'd' : ' ', stat.size, ent.name);
+    }
+
+    fs_close_dir(dhandle);
+
+err:
+    free(path);
+    return status;;
+}
+
+static int cmd_cd(int argc, const cmd_args *argv)
+{
+    if (argc < 2) {
+        set_cwd(NULL);
+    } else {
+        char *path = malloc(FS_MAX_PATH_LEN);
+        prepend_cwd(path, FS_MAX_PATH_LEN, (argc >= 2) ? argv[1].str : NULL);
+        fs_normalize_path(path);
+
+        if (strlen(path) == 0) {
+            set_cwd(NULL);
+        } else {
+            set_cwd(path);
+        }
+        free(path);
+    }
+    puts(get_cwd());
+
+    return 0;
+}
+
+static int cmd_pwd(int argc, const cmd_args *argv)
+{
+    puts(get_cwd());
+
+    return 0;
+}
+
+static int cmd_mkdir(int argc, const cmd_args *argv)
+{
+    if (argc < 2) {
+        printf("not enough arguments\n");
+        printf("usage: %s <path>\n", argv[0].str);
+        return -1;
+    }
+
+    char *path = malloc(FS_MAX_PATH_LEN);
+
+    int status = fs_make_dir(prepend_cwd(path, FS_MAX_PATH_LEN, argv[1].str));
+    if (status < 0) {
+        printf("error %d making directory '%s'\n", status, path);
+    }
+
+    free(path);
+    return status;
+}
+
+static int cmd_mkfile(int argc, const cmd_args *argv)
+{
+    if (argc < 2) {
+        printf("not enough arguments\n");
+        printf("usage: %s <path> [length]\n", argv[0].str);
+        return -1;
+    }
+
+    char *path = malloc(FS_MAX_PATH_LEN);
+    prepend_cwd(path, FS_MAX_PATH_LEN, argv[1].str);
+
+    filehandle *handle;
+    status_t status = fs_create_file(path, &handle, (argc >= 2) ? argv[2].u : 0);
+    if (status < 0) {
+        printf("error %d making file '%s'\n", status, path);
+        goto err;
+    }
+
+    fs_close_file(handle);
+
+err:
+    free(path);
+    return status;
+}
+
+static int cmd_rm(int argc, const cmd_args *argv)
+{
+    if (argc < 2) {
+        printf("not enough arguments\n");
+        printf("usage: %s <path>\n", argv[0].str);
+        return -1;
+    }
+
+    char *path = malloc(FS_MAX_PATH_LEN);
+    prepend_cwd(path, FS_MAX_PATH_LEN, argv[1].str);
+
+    status_t err = fs_remove_file(path);
+    if (err < 0) {
+        printf("error %d removing file '%s'\n", err, path);
+        return err;
+    }
+
+    return 0;
+}
+
+static int cmd_stat(int argc, const cmd_args *argv)
+{
+    if (argc < 2) {
+        printf("not enough arguments\n");
+        printf("usage: %s <path>\n", argv[0].str);
+        return -1;
+    }
+
+    int status;
+    struct file_stat stat;
+    filehandle *handle;
+
+    char *path = malloc(FS_MAX_PATH_LEN);
+    prepend_cwd(path, FS_MAX_PATH_LEN, argv[1].str);
+
+    status = fs_open_file(path, &handle);
+    if (status < 0) {
+        printf("error %d opening file '%s'\n", status, path);
+        goto err;
+    }
+
+    status = fs_stat_file(handle, &stat);
+
+    fs_close_file(handle);
+
+    if (status < 0) {
+        printf("error %d statting file\n", status);
+        goto err;
+    }
+
+    printf("stat successful:\n");
+    printf("\tis_dir: %d\n", stat.is_dir ? 1 : 0);
+    printf("\tsize: %lld\n", stat.size);
+
+
+err:
+    free(path);
+    return status;
+}
+
+static int cmd_cat(int argc, const cmd_args *argv)
+{
+    status_t status = NO_ERROR;
+
+    if (argc < 2) {
+        printf("not enough arguments\n");
+        printf("usage: %s <path>\n", argv[0].str);
+        return -1;
+    }
+
+    char *path = malloc(FS_MAX_PATH_LEN);
+    prepend_cwd(path, FS_MAX_PATH_LEN, argv[1].str);
+
+    filehandle *handle;
+    status = fs_open_file(path, &handle);
+    if (status < 0) {
+        printf("error %d opening file '%s'\n", status, path);
+        goto err;
+    }
+
+    char buf[64];
+    ssize_t read_len;
+    off_t offset = 0;
+    while ((read_len = fs_read_file(handle, buf, offset, sizeof(buf))) > 0) {
+        for (int i = 0; i < read_len; i++) {
+            putchar(buf[i]);
+        }
+
+        offset += read_len;
+    }
+
+    fs_close_file(handle);
+
+err:
+    free(path);
+    return status;
+}
+
+STATIC_COMMAND_START
+STATIC_COMMAND("ls", "dir listing", &cmd_ls)
+STATIC_COMMAND("cd", "change dir", &cmd_cd)
+STATIC_COMMAND("pwd", "print working dir", &cmd_pwd)
+STATIC_COMMAND("mkdir", "make dir", &cmd_mkdir)
+STATIC_COMMAND("mkfile", "make file", &cmd_mkfile)
+STATIC_COMMAND("rm", "remove file", &cmd_rm)
+STATIC_COMMAND("stat", "stat file", &cmd_stat)
+STATIC_COMMAND("cat", "cat file", &cmd_cat)
+STATIC_COMMAND_END(fs_shell);
+
+#endif
+
diff --git a/src/bsp/lk/lib/fs/spifs/rules.mk b/src/bsp/lk/lib/fs/spifs/rules.mk
new file mode 100644
index 0000000..b313d2b
--- /dev/null
+++ b/src/bsp/lk/lib/fs/spifs/rules.mk
@@ -0,0 +1,13 @@
+LOCAL_DIR := $(GET_LOCAL_DIR)
+
+MODULE := $(LOCAL_DIR)
+
+MODULE_SRCS += \
+	$(LOCAL_DIR)/spifs.c \
+
+MODULE_DEPS += \
+	lib/fs \
+	lib/cksum \
+	lib/bio
+
+include make/module.mk
diff --git a/src/bsp/lk/lib/fs/spifs/spifs.c b/src/bsp/lk/lib/fs/spifs/spifs.c
new file mode 100644
index 0000000..6700651
--- /dev/null
+++ b/src/bsp/lk/lib/fs/spifs/spifs.c
@@ -0,0 +1,1209 @@
+/*
+ * Copyright (c) 2015 Gurjant Kalsi <me@gurjantkalsi.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#include <debug.h>
+#include <err.h>
+#include <pow2.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <trace.h>
+
+#include <kernel/mutex.h>
+#include <lib/bio.h>
+#include <lib/cksum.h>
+#include <lib/console.h>
+#include <lib/fs.h>
+#include <lib/fs/spifs.h>
+#include <list.h>
+#include <lk/init.h>
+
+#define LOCAL_TRACE 0
+
+#define FS_VERSION 1
+#define FS_MAGIC 0x53504653  // SPFS
+
+#define SPIFS_ENTRY_LENGTH 32
+
+#define TOC_HEADER_RESERVED_BYTES 16
+#define TOC_FOOTER_RESERVED_BYTES 28
+#define MAX_FILENAME_LENGTH 20
+
+#define CORRUPT_TOC 0
+#define NO_OPEN_RUNS 0
+
+#define FRONT_TOC (1)
+#define BACK_TOC  (-1)
+
+#define FRONT_TOC_LABEL "front-toc"
+#define BACK_TOC_LABEL "back-toc"
+
+typedef int32_t toc_position_t;
+
+typedef struct {
+    uint8_t *page;
+    uint32_t page_size;
+    uint32_t page_count;
+    uint32_t blocks_per_page;
+
+    uint32_t generation;
+    uint32_t num_entries;
+    toc_position_t toc_position;
+
+    struct list_node files;
+    struct list_node dcookies;
+
+    bdev_t *dev;
+
+    mutex_t lock;
+} spifs_t;
+
+typedef struct {
+    uint32_t magic;
+    uint32_t version;
+    uint32_t num_entries;
+    uint32_t generation;
+
+    uint8_t _reserved[TOC_HEADER_RESERVED_BYTES];
+} toc_header_t;
+
+typedef struct {
+    uint32_t page_idx;
+    uint32_t length;
+    uint32_t capacity;
+    char filename[MAX_FILENAME_LENGTH];
+} toc_file_t;
+
+typedef struct {
+    uint8_t _reserved[TOC_FOOTER_RESERVED_BYTES];
+    uint32_t checksum;
+} toc_footer_t;
+
+typedef struct {
+    struct list_node node;
+    spifs_t *fs_handle;
+    toc_file_t metadata;
+} spifs_file_t;
+
+struct dircookie {
+    struct list_node node;
+    spifs_t *fs;
+
+    spifs_file_t *next_file;
+};
+
+typedef struct {
+    uint32_t page_id;
+    int32_t direction;
+    uint32_t entry_length;
+    uint8_t *data;
+    uint8_t *page;
+    spifs_t *spifs;
+} cursor_t;
+
+static status_t spifs_read_page(spifs_t *spifs, uint32_t page_addr);
+static status_t spifs_write_page(spifs_t *spifs, uint32_t page_addr);
+
+static status_t get_device_page_info(bdev_t *dev, uint32_t *page_size,
+                                     uint32_t *page_count);
+
+
+static status_t cursor_init(
+    cursor_t *cursor, spifs_t *spifs, int32_t direction, uint32_t page_id,
+    uint32_t entry_length
+)
+{
+    // Make sure the cursor can only be advanced an integer number of times
+    // per page.
+    DEBUG_ASSERT(ispow2(entry_length));
+    DEBUG_ASSERT(spifs->page_size % entry_length == 0);
+    DEBUG_ASSERT(spifs->page);
+
+    cursor->page_id = page_id;
+    cursor->direction = direction;
+    cursor->entry_length = entry_length;
+    cursor->data = spifs->page;
+    cursor->spifs = spifs;
+
+
+    return spifs_read_page(spifs, page_id);
+}
+
+static uint8_t *cursor_get(cursor_t *cursor)
+{
+    spifs_t *spifs = cursor->spifs;
+
+    uint8_t *page_end = spifs->page + spifs->page_size;
+    DEBUG_ASSERT(cursor->data < page_end);
+
+    return cursor->data;
+}
+
+static status_t cursor_advance(cursor_t *cursor)
+{
+    spifs_t *spifs = cursor->spifs;
+
+    uint8_t *page_end = spifs->page + spifs->page_size;
+
+    cursor->data += cursor->entry_length;
+
+    // We have walked past the end of our buffer.
+    DEBUG_ASSERT(page_end >= cursor->data);
+
+    // If we're at the end of this page, read the next page and move the cursor
+    // to the beginning of it.
+    if (cursor->data == page_end) {
+        cursor->page_id += cursor->direction;
+        cursor->data = spifs->page;
+
+        return spifs_read_page(spifs, cursor->page_id);
+    }
+
+    return NO_ERROR;
+}
+
+static spifs_file_t *find_file(spifs_t *spifs, const char *name)
+{
+    spifs_file_t *file;
+
+    list_for_every_entry(&spifs->files, file, spifs_file_t, node) {
+        // Skip the ToC Entries
+        if (file == list_peek_head_type(&spifs->files, spifs_file_t, node) ||
+                file == list_peek_tail_type(&spifs->files, spifs_file_t, node)) {
+            continue;
+        }
+
+        if (!strncmp(name, file->metadata.filename, MAX_FILENAME_LENGTH)) {
+            return file;
+        }
+    }
+
+    return NULL;
+}
+
+static uint32_t find_open_run(spifs_t *spifs, uint32_t requested_length)
+{
+    spifs_file_t *file;
+    list_for_every_entry(&spifs->files, file, spifs_file_t, node) {
+        // Number of pages that this file occupies
+        uint32_t page_size_shift = log2_uint(file->fs_handle->page_size);
+
+        uint32_t file_page_length =
+            divpow2(file->metadata.capacity, page_size_shift);
+
+        // Index of the page immediately following the last page of this file.
+        uint32_t file_end_page = file->metadata.page_idx + file_page_length;
+
+        // Determine the page that the next file starts at.
+        spifs_file_t *next =
+            list_next_type(&spifs->files, &file->node, spifs_file_t, node);
+
+        // End of list?
+        if (next == NULL) {
+            return NO_OPEN_RUNS;
+        }
+
+        uint32_t available_pages = next->metadata.page_idx - file_end_page;
+        uint32_t available_bytes = available_pages * file->fs_handle->page_size;
+        if (available_bytes >= requested_length) {
+            return file_end_page;
+        }
+    }
+    return NO_OPEN_RUNS;
+}
+
+static uint64_t used_space(spifs_t *spifs)
+{
+    uint64_t result = 0;
+
+    spifs_file_t *file;
+    list_for_every_entry(&spifs->files, file, spifs_file_t, node) {
+        result += file->metadata.capacity;
+    }
+
+    return result;
+}
+
+static bool consistency_check(spifs_t *spifs)
+{
+    /* Return true iff the ToC is in a consistent state. */
+    spifs_file_t *file;
+    list_for_every_entry(&spifs->files, file, spifs_file_t, node) {
+        // Number of pages that this file occupies
+        uint32_t file_page_length =
+            file->metadata.capacity / file->fs_handle->page_size;
+
+        // Index of the last page of this file.
+        uint32_t file_end_page = file->metadata.page_idx + file_page_length - 1;
+
+        // Determine the page that the next file starts at.
+        spifs_file_t *next =
+            list_next_type(&spifs->files, &file->node, spifs_file_t, node);
+
+        // End of list?
+        if (next == NULL) {
+            continue;
+        }
+
+        if (next->metadata.page_idx <= file_end_page) {
+            return false;
+        }
+    }
+
+    return true;
+}
+
+static status_t spifs_commit_toc(spifs_t *spifs)
+{
+    status_t err;
+
+    // Get the next logical ToC.
+    toc_position_t target_toc =
+        spifs->toc_position == FRONT_TOC ? BACK_TOC : FRONT_TOC;
+
+    // Bump the generation counter.
+    uint32_t target_generation = spifs->generation + 1;
+
+    uint32_t crc = 0;
+    uint8_t *cursor = spifs->page;
+    uint32_t toc_page_addr = target_toc == FRONT_TOC ?
+                             0 : spifs->page_count - 1;
+
+    // Setup the ToC Header.
+    toc_header_t header = {
+        .magic       = FS_MAGIC,
+        .version     = FS_VERSION,
+        .num_entries = spifs->num_entries,
+        .generation  = target_generation,
+    };
+    memset(header._reserved, 0, TOC_HEADER_RESERVED_BYTES);
+
+    crc = crc32(crc, (uint8_t *)&header, SPIFS_ENTRY_LENGTH);
+
+    memcpy(cursor, (uint8_t *)&header, SPIFS_ENTRY_LENGTH);
+    cursor += SPIFS_ENTRY_LENGTH;
+
+    // Create an empty file to copy into the empty spots in the ToC
+    toc_file_t empty;
+    memset(&empty, 0, SPIFS_ENTRY_LENGTH);
+
+    spifs_file_t *file = list_peek_head_type(&spifs->files, spifs_file_t, node);
+    for (uint32_t i = 0; i < spifs->num_entries; i++) {
+        uint8_t *page_end = spifs->page + spifs->page_size;
+        DEBUG_ASSERT(cursor <= page_end);
+
+        if (cursor == page_end) {
+            err = spifs_write_page(spifs, toc_page_addr);
+            if (err != NO_ERROR) {
+                return err;
+            }
+
+            toc_page_addr += target_toc;
+            cursor = spifs->page;
+        }
+
+        if (file) {
+            crc = crc32(crc, (uint8_t *)&file->metadata, SPIFS_ENTRY_LENGTH);
+            memcpy(cursor, (uint8_t *)&file->metadata, SPIFS_ENTRY_LENGTH);
+            file = list_next_type(&spifs->files, &file->node, spifs_file_t, node);
+        } else {
+            crc = crc32(crc, (uint8_t *)&empty, SPIFS_ENTRY_LENGTH);
+            memcpy(cursor, (uint8_t *)&empty, SPIFS_ENTRY_LENGTH);
+        }
+
+        cursor += SPIFS_ENTRY_LENGTH;
+    }
+
+    // Sanity check. The cursor should be at the last position in this page
+    // at this point.
+    uint8_t *expected_cursor_location =
+        (spifs->page + spifs->page_size) - SPIFS_ENTRY_LENGTH;
+    DEBUG_ASSERT(cursor == expected_cursor_location);
+
+    toc_footer_t footer;
+    memset(&footer, 0, SPIFS_ENTRY_LENGTH);
+    footer.checksum = crc;
+    memcpy(cursor, (uint8_t *)&footer, SPIFS_ENTRY_LENGTH);
+
+    err = spifs_write_page(spifs, toc_page_addr);
+    if (err != NO_ERROR)
+        return err;
+
+    // Only update this once we're sure that the write went through.
+    // This way, if the write failed, we'll try writing over the bad ToC again
+    // rather than potentially corrupting both ToCs.
+    spifs->generation = target_generation;
+    spifs->toc_position = target_toc;
+
+    return NO_ERROR;
+}
+
+static void spifs_add_ascending(spifs_t *spifs, spifs_file_t *target)
+{
+    spifs_file_t *file;
+    list_for_every_entry(&spifs->files, file, spifs_file_t, node) {
+        if (file->metadata.page_idx > target->metadata.page_idx) {
+            list_add_before(&file->node, &target->node);
+            return;
+        }
+    }
+
+    list_add_tail(&spifs->files, &target->node);
+}
+
+
+static status_t spifs_read_page(spifs_t *spifs, uint32_t page_addr)
+{
+    off_t block_addr = page_addr * spifs->blocks_per_page;
+
+    ssize_t bytes = bio_read_block(spifs->dev, spifs->page, block_addr,
+                                   spifs->blocks_per_page);
+
+    if ((uint32_t)bytes != spifs->page_size) {
+        return ERR_IO;
+    }
+
+    return NO_ERROR;
+}
+
+static status_t spifs_write_page(spifs_t *spifs, uint32_t page_addr)
+{
+    off_t block_addr = page_addr * spifs->blocks_per_page;
+    off_t device_addr = block_addr * spifs->dev->block_size;
+
+    // Device requires erase before write?
+    if (spifs->dev->geometry_count != 0) {
+        ssize_t bytes = bio_erase(spifs->dev, device_addr, spifs->page_size);
+        if ((uint32_t)bytes != spifs->page_size) {
+            return ERR_IO;
+        }
+    }
+
+    ssize_t bytes = bio_write_block(spifs->dev, spifs->page, block_addr,
+                                    spifs->blocks_per_page);
+
+    if ((uint32_t)bytes != spifs->page_size) {
+        return ERR_IO;
+    }
+
+    return NO_ERROR;
+}
+
+static uint32_t get_toc_generation(spifs_t *spifs, toc_position_t toc_pos)
+{
+    LTRACEF("spifs %p\n", spifs);
+
+    uint32_t candidate_generation;
+
+    DEBUG_ASSERT(spifs);
+
+    DEBUG_ASSERT(toc_pos == FRONT_TOC || toc_pos == BACK_TOC);
+    uint32_t toc_page = toc_pos == FRONT_TOC ?
+                        0 : (spifs->page_count - 1);
+
+
+    cursor_t cursor;
+    if (cursor_init(&cursor, spifs, toc_pos, toc_page, SPIFS_ENTRY_LENGTH) !=
+            NO_ERROR) {
+        return CORRUPT_TOC;
+    }
+
+    toc_header_t *header = (toc_header_t *)cursor_get(&cursor);
+
+    if (header->magic != FS_MAGIC) {
+        return CORRUPT_TOC;
+    }
+
+    if (header->version != FS_VERSION) {
+        return CORRUPT_TOC;
+    }
+
+    candidate_generation = header->generation;
+    uint32_t num_toc_entries = header->num_entries;
+
+    uint32_t crc = 0;
+    crc = crc32(crc, (uint8_t *)header, SPIFS_ENTRY_LENGTH);
+
+    header = NULL;
+
+    for (size_t i = 0; i < num_toc_entries; i++) {
+        if (cursor_advance(&cursor) != NO_ERROR)
+            return CORRUPT_TOC;
+
+        crc = crc32(crc, cursor_get(&cursor), SPIFS_ENTRY_LENGTH);
+    }
+
+    if (cursor_advance(&cursor) != NO_ERROR)
+        return CORRUPT_TOC;
+
+    toc_footer_t *footer = (toc_footer_t *)cursor_get(&cursor);
+    if (footer->checksum != crc) {
+        return CORRUPT_TOC;
+    }
+
+    return candidate_generation;
+}
+
+// page_size will be populated with the device's page size if this function
+// returns NO_ERROR, otherwise the contents of page_size are undefined.
+static status_t get_device_page_info(bdev_t *dev, uint32_t *page_size, uint32_t *page_count)
+{
+    LTRACEF("dev %p, page_size %p\n", dev, page_size);
+
+    switch (dev->geometry_count) {
+        case 0: {
+            // Device has no erase geometry; overwriting is supported.
+            *page_size = dev->block_size;
+            *page_count = dev->total_size / (*page_size);
+            return NO_ERROR;
+        }
+        case 1: {
+            // Device has erase geometry.
+            size_t erase_size = valpow2(dev->geometry->erase_size);
+            size_t block_size = dev->block_size;
+
+            if (erase_size % block_size != 0) {
+                // erase_size must be a multiple of the block size.
+                return ERR_NOT_SUPPORTED;
+            }
+
+            *page_size = erase_size;
+            *page_count = dev->total_size / (*page_size);
+            return NO_ERROR;
+        }
+        default: {
+            // We don't support non-uniform erase geometry.
+            return ERR_NOT_SUPPORTED;
+        }
+    }
+}
+
+static status_t spifs_format(bdev_t *dev, const void *args)
+{
+    status_t err = NO_ERROR;
+
+    LTRACEF("dev %p, args %p\n", dev, args);
+
+    if (!dev) {
+        return ERR_INVALID_ARGS;
+    }
+
+    spifs_format_args_t *spifs_args;
+    spifs_format_args_t default_args = {
+        .toc_pages = 1,
+    };
+
+    if (!args) {
+        spifs_args = &default_args;
+    } else {
+        spifs_args = (spifs_format_args_t *)args;
+    }
+
+    // Make sure that each of the three data structures are the same size.
+    STATIC_ASSERT(sizeof(toc_header_t) == SPIFS_ENTRY_LENGTH);
+    STATIC_ASSERT(sizeof(toc_file_t) == SPIFS_ENTRY_LENGTH);
+    STATIC_ASSERT(sizeof(toc_footer_t) == SPIFS_ENTRY_LENGTH);
+
+    uint32_t page_size;
+    uint32_t page_count;
+    err = get_device_page_info(dev, &page_size, &page_count);
+    if (err != NO_ERROR)
+        return err;
+
+    // Make sure entries can be exactly packed into pages.
+    if (page_size % SPIFS_ENTRY_LENGTH != 0) {
+        return ERR_NOT_SUPPORTED;
+    }
+
+    // Make sure the device size is some multiple of the page size;
+    // we don't want a partial page at the end of the device.
+    if (dev->total_size % page_size != 0) {
+        return ERR_NOT_SUPPORTED;
+    }
+
+    uint32_t entires_per_page = page_size / SPIFS_ENTRY_LENGTH;
+
+    // Number of ToC entrries is the total number of entries less 2 for the
+    // header/footer
+    uint32_t num_entries = spifs_args->toc_pages * entires_per_page;
+    uint32_t num_toc_entries = num_entries - 2;
+
+    // Four entries will be consumed by metadata: Header, Front ToC entry,
+    // Back ToC entry, footer. If there are only four entries, there will be
+    // no room for files.
+    if (num_entries <= 4) {
+        return ERR_TOO_BIG;
+    }
+
+    // Create a mock spifs_t for the purposes of formatting the fs.
+    spifs_t spifs = {
+        .page_size = page_size,
+        .page_count = page_count,
+        .blocks_per_page = divpow2(page_size, dev->block_shift),
+        .generation = 1,
+        .num_entries = num_toc_entries,
+        .toc_position = FRONT_TOC,
+        .dev = dev,
+    };
+    spifs.page = memalign(CACHE_LINE, page_size);
+    list_initialize(&spifs.files);
+    list_initialize(&spifs.dcookies);
+    mutex_init(&spifs.lock);
+
+    spifs_file_t f_toc;
+    f_toc.metadata.page_idx = 0;
+    f_toc.metadata.length = spifs_args->toc_pages * page_size;
+    f_toc.metadata.capacity = spifs_args->toc_pages * page_size;
+    f_toc.fs_handle = &spifs;
+    memset(f_toc.metadata.filename, 0, MAX_FILENAME_LENGTH);
+    strlcpy(f_toc.metadata.filename, FRONT_TOC_LABEL, MAX_FILENAME_LENGTH);
+
+    spifs_file_t b_toc;
+    b_toc.metadata.page_idx = page_count - spifs_args->toc_pages;
+    b_toc.metadata.length = spifs_args->toc_pages * page_size;
+    b_toc.metadata.capacity = spifs_args->toc_pages * page_size;
+    b_toc.fs_handle = &spifs;
+    memset(b_toc.metadata.filename, 0, MAX_FILENAME_LENGTH);
+    strlcpy(b_toc.metadata.filename, BACK_TOC_LABEL, MAX_FILENAME_LENGTH);
+
+    spifs_add_ascending(&spifs, &f_toc);
+    spifs_add_ascending(&spifs, &b_toc);
+
+    // Commit the first toc.
+    err = spifs_commit_toc(&spifs);
+    if (err != NO_ERROR)
+        goto err;
+
+    // Commit the other toc.
+    err = spifs_commit_toc(&spifs);
+    if (err != NO_ERROR)
+        goto err;
+
+err:
+    free(spifs.page);
+
+    return err;
+}
+
+static status_t spifs_mount(bdev_t *dev, fscookie **cookie)
+{
+    status_t status;
+
+    LTRACEF("dev %p, cookie %p\n", dev, cookie);
+
+    spifs_t *spifs = malloc(sizeof(*spifs));
+    if (!spifs) {
+        return ERR_NO_MEMORY;
+    }
+
+    status = get_device_page_info(dev, &spifs->page_size, &spifs->page_count);
+    if (status != NO_ERROR) {
+        free(spifs);
+        return status;
+    }
+
+    spifs->blocks_per_page = divpow2(spifs->page_size, dev->block_shift);
+
+    spifs->page = memalign(CACHE_LINE, spifs->page_size);
+    if (!spifs->page) {
+        free(spifs);
+        return ERR_NO_MEMORY;
+    }
+
+    spifs->dev = dev;
+
+    list_initialize(&spifs->files);
+    list_initialize(&spifs->dcookies);
+    mutex_init(&spifs->lock);
+
+    // Determine which of the two Table of Contents we should use.
+    uint32_t f_toc_generation = get_toc_generation(spifs, FRONT_TOC);
+    uint32_t b_toc_generation = get_toc_generation(spifs, BACK_TOC);
+
+    if (f_toc_generation == CORRUPT_TOC && b_toc_generation == CORRUPT_TOC) {
+        // Both ToCs are corrupt.
+        status = ERR_CRC_FAIL;
+        goto err;
+    }
+
+    spifs->toc_position =
+        f_toc_generation > b_toc_generation ? FRONT_TOC : BACK_TOC;
+    spifs->generation = MAX(f_toc_generation, b_toc_generation);
+
+    uint32_t toc_page_addr = spifs->toc_position == FRONT_TOC ?
+                             0 : spifs->page_count - 1;
+
+    cursor_t cursor;
+    status = cursor_init(&cursor, spifs, spifs->toc_position, toc_page_addr,
+                         SPIFS_ENTRY_LENGTH);
+    if (status != NO_ERROR)
+        goto err;
+
+    toc_header_t *header = (toc_header_t *)cursor_get(&cursor);
+    spifs->num_entries = header->num_entries;
+    header = NULL;
+
+    // Create in-memory versions of metadata for files.
+    spifs_file_t *file;
+    for (size_t i = 0; i < spifs->num_entries; i++) {
+        status = cursor_advance(&cursor);
+        if (status != NO_ERROR)
+            goto err;
+
+        toc_file_t *file_entry = (toc_file_t *)cursor_get(&cursor);
+        if (file_entry->capacity == 0) {
+            continue;
+        }
+
+        file = malloc(sizeof(*file));
+        if (!file) {
+            status = ERR_NO_MEMORY;
+            goto err;
+        }
+
+        memcpy(&file->metadata, file_entry, SPIFS_ENTRY_LENGTH);
+
+        file->fs_handle = spifs;
+
+        list_add_tail(&spifs->files, &file->node);
+    }
+
+    if (!consistency_check(spifs)) {
+        status = ERR_BAD_STATE;
+        goto err;
+    }
+
+    *cookie = (fscookie *)spifs;
+
+    return NO_ERROR;
+
+err:
+    while ((file = list_remove_head_type(&spifs->files, spifs_file_t, node))) {
+        free(file);
+    }
+
+    free(spifs->page);
+    free(spifs);
+    return status;
+}
+
+static status_t spifs_unmount(fscookie *cookie)
+{
+    LTRACEF("cookie %p\n", cookie);
+
+    spifs_t *spifs = (spifs_t *)cookie;
+
+    mutex_acquire(&spifs->lock);
+
+    spifs_file_t *file;
+    while ((file = list_remove_head_type(&spifs->files, spifs_file_t, node))) {
+        free(file);
+    }
+
+    free(spifs->page);
+
+    mutex_release(&spifs->lock);
+
+    free(spifs);
+
+    return NO_ERROR;
+}
+
+static status_t spifs_create(fscookie *cookie, const char *name, filecookie **fcookie, uint64_t len)
+{
+    status_t status = NO_ERROR;
+
+    LTRACEF("cookie %p name '%s' filecookie %p len %llu\n", cookie, name, fcookie, len);
+
+    spifs_t *spifs = (spifs_t *)cookie;
+
+    // Strip leading fwd-slashes
+    name = trim_name(name);
+
+    // File system is flat, directories not supported.
+    if (strchr(name, '/'))
+        return ERR_NOT_SUPPORTED;
+
+    // Check that filename is not too long.
+    if (strnlen(name, MAX_FILENAME_LENGTH) == MAX_FILENAME_LENGTH)
+        return ERR_BAD_PATH;
+
+    // Length is bigger than 4GB?
+    if (len > 0xFFFFFFFF)
+        return ERR_TOO_BIG;
+
+    mutex_acquire(&spifs->lock);
+
+    if (find_file(spifs, name)) {
+        status = ERR_ALREADY_EXISTS;
+        goto err;
+    }
+
+    // Is the ToC full? Have we reached the limit on the number of files?
+    size_t num_files_in_toc = list_length(&spifs->files);
+    DEBUG_ASSERT(num_files_in_toc <= spifs->num_entries);
+    if (num_files_in_toc >= spifs->num_entries) {
+        status = ERR_TOO_BIG;
+        goto err;
+    }
+
+    uint32_t capacity;
+    if (len == 0) {
+        capacity = spifs->page_size;
+    } else {
+        capacity = ROUNDUP(len, spifs->page_size);
+    }
+
+    uint32_t open_run = find_open_run(spifs, capacity);
+    if (open_run == NO_OPEN_RUNS) {
+        status = ERR_TOO_BIG;
+        goto err;
+    }
+
+    spifs_file_t *file = malloc(sizeof(*file));
+    if (!file) {
+        status = ERR_NO_MEMORY;
+        goto err;
+    }
+
+    file->fs_handle = spifs;
+    file->metadata.page_idx = open_run;
+    file->metadata.length = len;
+    file->metadata.capacity = capacity;
+    memset(file->metadata.filename, 0, MAX_FILENAME_LENGTH);
+    strlcpy(file->metadata.filename, name, MAX_FILENAME_LENGTH);
+
+    // Erase the memory allocated to the file.
+    if (bio_erase(spifs->dev, open_run * spifs->page_size, capacity) !=
+            (ssize_t)capacity) {
+
+        free(file);
+
+        status = ERR_IO;
+        goto err;
+    }
+
+    spifs_add_ascending(spifs, file);
+
+    if (spifs_commit_toc(spifs) != NO_ERROR) {
+        // If the commit fails, make sure we don't leave any residue of the file
+        // lying around.
+        list_delete(&file->node);
+        free(file);
+        *fcookie = NULL;
+
+        status = ERR_IO;
+        goto err;
+    }
+
+    *fcookie = (filecookie *) file;
+
+err:
+    mutex_release(&spifs->lock);
+
+    return status;
+}
+
+static status_t spifs_open(fscookie *cookie, const char *name, filecookie **fcookie)
+{
+    LTRACEF("cookie %p name '%s' filecookie %p\n", cookie, name, fcookie);
+
+    spifs_t *spifs = (spifs_t *)cookie;
+
+    name = trim_name(name);
+
+    mutex_acquire(&spifs->lock);
+
+    spifs_file_t *file = find_file(spifs, name);
+
+    mutex_release(&spifs->lock);
+
+    if (!file)
+        return ERR_NOT_FOUND;
+
+    *fcookie = (filecookie *)file;
+
+    return NO_ERROR;
+}
+
+static status_t spifs_close(filecookie *fcookie)
+{
+    spifs_file_t *file = (spifs_file_t *)fcookie;
+
+    LTRACEF("cookie %p name '%s'\n", fcookie, file->metadata.filename);
+
+    return NO_ERROR;
+}
+
+static status_t spifs_remove(fscookie *cookie, const char *name)
+{
+    status_t status;
+
+    LTRACEF("cookie %p name '%s'\n", cookie, name);
+
+    spifs_t *spifs = (spifs_t *)cookie;
+
+    // make sure we strip out any leading /
+    name = trim_name(name);
+
+    mutex_acquire(&spifs->lock);
+
+    spifs_file_t *file = find_file(spifs, name);
+
+    if (!file) {
+        status = ERR_NOT_FOUND;
+        goto err;
+    }
+
+    // Make sure there are no dirents open that point to the file that we're
+    // deleting.
+    dircookie *dcookie;
+    list_for_every_entry(&spifs->dcookies, dcookie, dircookie, node) {
+        if (dcookie->next_file == file) {
+            dcookie->next_file = list_next_type(&dcookie->fs->files,
+                                                &dcookie->next_file->node,
+                                                spifs_file_t, node);
+        }
+    }
+
+    list_delete(&file->node);
+    free(file);
+
+    status = spifs_commit_toc(spifs);
+
+err:
+    mutex_release(&spifs->lock);
+
+    return status;
+}
+
+static ssize_t spifs_read(filecookie *fcookie, void *buf, off_t off, size_t len)
+{
+    LTRACEF("filecookie %p buf %p offset %lld len %zu\n", fcookie, buf, off, len);
+
+    spifs_file_t *file = (spifs_file_t *)fcookie;
+    spifs_t *spifs = file->fs_handle;
+
+    if (off < 0)
+        return ERR_INVALID_ARGS;
+
+    mutex_acquire(&spifs->lock);
+
+    uint32_t file_start = file->fs_handle->page_size * file->metadata.page_idx;
+    uint32_t file_end = file_start + file->metadata.length;
+
+    uint32_t read_start = file_start + off;
+    uint32_t read_end = read_start + len;
+
+    if (read_start >= file_end) {
+        len = 0;
+    } else if (read_end > file_end) {
+        len = file_end - read_start;
+    }
+
+    DEBUG_ASSERT(file->fs_handle->dev);
+
+    ssize_t result = bio_read(file->fs_handle->dev, buf, read_start, len);
+
+    mutex_release(&spifs->lock);
+
+    return result;
+}
+
+static ssize_t spifs_write(filecookie *fcookie, const void *buf, off_t off, size_t size)
+{
+    status_t err = NO_ERROR;
+    size_t len = size;
+
+    LTRACEF("filecookie %p buf %p offset %lld len %zu\n", fcookie, buf, off, len);
+
+    spifs_file_t *file = (spifs_file_t *)fcookie;
+    spifs_t *spifs = (spifs_t *)(file->fs_handle);
+
+    if (off < 0)
+        return ERR_INVALID_ARGS;
+
+    mutex_acquire(&spifs->lock);
+
+    if (off + len > file->metadata.capacity) {
+        err = ERR_OUT_OF_RANGE;
+        goto err;
+    }
+
+    bool dirty_toc = false;
+
+    uint32_t start_addr =
+        off + (file->metadata.page_idx * spifs->page_size);
+
+    uint32_t page_shift = log2_uint(spifs->page_size);
+    uint32_t target_page_id = divpow2(start_addr, page_shift);
+
+    // Are we growing the file?
+    if (off + len > file->metadata.length) {
+        file->metadata.length = off + len;
+        dirty_toc = true;
+    }
+
+    // Leading Partial Page.
+    uint32_t page_offset = start_addr % spifs->page_size;
+    if (page_offset) {
+        uint32_t page_end = ROUNDUP(start_addr, spifs->page_size);
+
+        uint32_t n_bytes = MIN(len, page_end - start_addr);
+
+        // read..
+        err = spifs_read_page(spifs, target_page_id);
+        if (err != NO_ERROR) {
+            goto err;
+        }
+
+        // modify..
+        memcpy(spifs->page + page_offset, buf, n_bytes);
+
+        // write..
+        err = spifs_write_page(spifs, target_page_id);
+        if (err != NO_ERROR) {
+            goto err;
+        }
+
+        len -= n_bytes;
+        buf += n_bytes;
+        target_page_id++;
+    }
+
+    // Internal Full Pages.
+    while (len >= spifs->page_size) {
+        memcpy(spifs->page, buf, spifs->page_size);
+        err = spifs_write_page(spifs, target_page_id);
+        if (err != NO_ERROR) {
+            goto err;
+        }
+
+        len -= spifs->page_size;
+        buf += spifs->page_size;
+        target_page_id++;
+    }
+
+    // Trailing Partial Page.
+    if (len) { // Bytes remaining?
+        // read..
+        err = spifs_read_page(spifs, target_page_id);
+        if (err != NO_ERROR) {
+            goto err;
+        }
+
+        // modify..
+        memcpy(spifs->page, buf, len);
+
+        // write..
+        err = spifs_write_page(spifs, target_page_id);
+        if (err != NO_ERROR) {
+            goto err;
+        } else {
+            len = 0;
+        }
+    }
+
+    if (dirty_toc) {
+        err = spifs_commit_toc(spifs);
+    }
+
+err:
+    mutex_release(&spifs->lock);
+    return len == 0 ? (ssize_t)size : err;
+}
+
+static status_t spifs_stat(filecookie *fcookie, struct file_stat *stat)
+{
+    LTRACEF("filecookie %p stat %p\n", fcookie, stat);
+
+    spifs_file_t *file = (spifs_file_t *)fcookie;
+
+    mutex_acquire(&file->fs_handle->lock);
+
+    if (stat) {
+        stat->is_dir = false;
+        stat->size = file->metadata.length;
+        stat->capacity = file->metadata.capacity;
+    }
+
+    mutex_release(&file->fs_handle->lock);
+
+    return NO_ERROR;
+}
+
+static status_t spifs_opendir(fscookie *cookie, const char *name, dircookie **dcookie)
+{
+    LTRACEF("cookie %p name '%s' dircookie %p\n", cookie, name, dcookie);
+
+    spifs_t *spifs = (spifs_t *)cookie;
+
+    name = trim_name(name);
+
+    if (strcmp("", name))
+        return ERR_NOT_FOUND;
+
+    dircookie *dir = malloc(sizeof(*dir));
+    if (!dir)
+        return ERR_NO_MEMORY;
+
+    dir->fs = spifs;
+
+    mutex_acquire(&spifs->lock);
+
+    spifs_file_t *front_toc_file =
+        list_peek_head_type(&spifs->files, spifs_file_t, node);
+    dir->next_file = list_next_type(&spifs->files, &front_toc_file->node,
+                                    spifs_file_t, node);
+    list_add_head(&spifs->dcookies, &dir->node);
+
+    mutex_release(&spifs->lock);
+
+    *dcookie = dir;
+
+    return NO_ERROR;
+}
+
+static status_t spifs_readdir(dircookie *dcookie, struct dirent *ent)
+{
+    status_t err;
+
+    LTRACEF("dircookie %p ent %p\n", dcookie, ent);
+
+    mutex_acquire(&dcookie->fs->lock);
+
+    spifs_file_t *back_toc_file =
+        list_peek_tail_type(&dcookie->fs->files, spifs_file_t, node);
+
+    if (dcookie->next_file != back_toc_file) {
+        strlcpy(ent->name, dcookie->next_file->metadata.filename, sizeof(ent->name));
+        dcookie->next_file =
+            list_next_type(&dcookie->fs->files, &dcookie->next_file->node,
+                           spifs_file_t, node);
+        err = NO_ERROR;
+    } else {
+        err = ERR_NOT_FOUND;
+    }
+
+    mutex_release(&dcookie->fs->lock);
+
+    return err;
+}
+
+static status_t spifs_closedir(dircookie *dcookie)
+{
+    LTRACEF("dircookie %p\n", dcookie);
+
+    mutex_acquire(&dcookie->fs->lock);
+    list_delete(&dcookie->node);
+    mutex_release(&dcookie->fs->lock);
+
+    free(dcookie);
+
+    return NO_ERROR;
+}
+
+static status_t spifs_fs_stat(fscookie *cookie, struct fs_stat *stat)
+{
+    LTRACEF("cookie %p, stat %p\n", cookie, stat);
+
+    spifs_t *spifs = (spifs_t *)cookie;
+
+    stat->total_space = (uint64_t)spifs->dev->total_size;
+    stat->free_space  = stat->total_space - used_space(spifs);
+
+    stat->total_inodes = spifs->num_entries;
+    stat->free_inodes  = stat->total_inodes - list_length(&spifs->files);
+
+    return NO_ERROR;
+}
+
+static status_t spifs_ioctl_get_file_addr(filecookie *cookie, void **argp)
+{
+    LTRACEF("cookie %p, argp %p\n", cookie, argp);
+
+    if (unlikely(!argp)) {
+        return ERR_INVALID_ARGS;
+    }
+
+    status_t result;
+
+    spifs_file_t *file = (spifs_file_t *)cookie;
+    spifs_t *spifs = file->fs_handle;
+    bdev_t *dev = spifs->dev;
+
+    // Get the base address of the underlying BIO device.
+    void *result_addr;
+    result = bio_ioctl(dev, BIO_IOCTL_GET_MAP_ADDR, &result_addr);
+    if (result != NO_ERROR) {
+        return result;
+    }
+
+    // Get the offset of the file.
+    result_addr += file->metadata.page_idx * spifs->page_size;
+    *argp = result_addr;
+
+    return NO_ERROR;
+}
+
+static status_t spifs_file_ioctl(filecookie *cookie, int request, void *argp)
+{
+    LTRACEF("request %d, argp %p\n", request, argp);
+
+    switch (request) {
+        case FS_IOCTL_GET_FILE_ADDR: {
+            return spifs_ioctl_get_file_addr(cookie, (void **)argp);
+        }
+        default: {
+            return ERR_NOT_SUPPORTED;
+        }
+    }
+    return ERR_NOT_SUPPORTED;
+}
+
+static const struct fs_api spifs_api = {
+    .format = spifs_format,
+    .fs_stat = spifs_fs_stat,
+
+    .mount = spifs_mount,
+    .unmount = spifs_unmount,
+
+    .create = spifs_create,
+    .open = spifs_open,
+    .remove = spifs_remove,
+    .close = spifs_close,
+
+    .read = spifs_read,
+    .write = spifs_write,
+
+    .stat = spifs_stat,
+
+    .file_ioctl = spifs_file_ioctl,
+
+    .opendir = spifs_opendir,
+    .readdir = spifs_readdir,
+    .closedir = spifs_closedir,
+};
+
+STATIC_FS_IMPL(spifs, &spifs_api);
diff --git a/src/bsp/lk/lib/fs/spifs/test/rules.mk b/src/bsp/lk/lib/fs/spifs/test/rules.mk
new file mode 100644
index 0000000..344c7b5
--- /dev/null
+++ b/src/bsp/lk/lib/fs/spifs/test/rules.mk
@@ -0,0 +1,8 @@
+LOCAL_DIR := $(GET_LOCAL_DIR)
+
+MODULE := $(LOCAL_DIR)
+
+MODULE_SRCS += \
+	$(LOCAL_DIR)/spifstest.c
+
+include make/module.mk
diff --git a/src/bsp/lk/lib/fs/spifs/test/spifstest.c b/src/bsp/lk/lib/fs/spifs/test/spifstest.c
new file mode 100644
index 0000000..d2de090
--- /dev/null
+++ b/src/bsp/lk/lib/fs/spifs/test/spifstest.c
@@ -0,0 +1,684 @@
+/*
+ * Copyright (c) 2015 Gurjant Kalsi <me@gurjantkalsi.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files
+ * (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#if LK_DEBUGLEVEL > 1
+
+#include <string.h>
+#include <err.h>
+#include <stdlib.h>
+
+#include <lib/bio.h>
+#include <lib/console.h>
+#include <lib/fs/spifs.h>
+
+#define FS_NAME "spifs"
+#define MNT_PATH "/s"
+#define TEST_FILE_PATH "/s/test"
+#define TEST_PATH_MAX_SIZE 16
+
+typedef bool(*test_func)(const char *);
+
+typedef struct {
+    test_func func;
+    const char* name;
+    uint32_t toc_pages;
+} test;
+
+static bool test_empty_after_format(const char *);
+static bool test_double_create_file(const char *);
+static bool test_write_read_normal(const char *);
+static bool test_write_past_eof(const char *);
+static bool test_full_toc(const char *);
+static bool test_full_fs(const char *);
+static bool test_write_past_end_of_capacity(const char *);
+static bool test_rm_reclaim(const char *);
+static bool test_corrupt_toc(const char *);
+static bool test_write_with_offset(const char *);
+static bool test_read_write_big(const char *);
+static bool test_rm_active_dirent(const char *);
+
+static test tests[] = {
+    {&test_empty_after_format, "Test no files in ToC after format.", 1},
+    {&test_write_read_normal, "Test the normal read/write file paths.", 1},
+    {&test_double_create_file, "Test file cannot be created if it already exists.", 1},
+    {&test_write_past_eof, "Test that file can grow up to capacity.", 1},
+    {&test_full_toc, "Test that files cannot be created once the ToC is full.", 2},
+    {&test_full_fs, "Test that files cannot be created once the device is full.", 1},
+    {&test_rm_reclaim, "Test that files can be deleted and that used space is reclaimed.", 1},
+    {&test_write_past_end_of_capacity, "Test that we cannot write past the capacity of a file.", 1},
+    {&test_corrupt_toc, "Test that FS can be mounted with one corrupt ToC.", 1},
+    {&test_write_with_offset, "Test that files can be written to at an offset.", 1},
+    {&test_read_write_big, "Test that an unaligned ~10kb buffer can be written and read.", 1},
+    {&test_rm_active_dirent, "Test that we can remove a file with an open dirent.", 1},
+};
+
+bool test_setup(const char *dev_name, uint32_t toc_pages)
+{
+    spifs_format_args_t args = {
+        .toc_pages = toc_pages,
+    };
+
+    status_t res = fs_format_device(FS_NAME, dev_name, (void*)&args);
+    if (res != NO_ERROR) {
+        printf("spifs_format failed dev = %s, toc_pages = %u, retcode = %d\n",
+               dev_name, toc_pages, res);
+        return false;
+    }
+
+    res = fs_mount(MNT_PATH, FS_NAME, dev_name);
+    if (res != NO_ERROR) {
+        printf("fs_mount failed path = %s, fs name = %s, dev name = %s,"
+               " retcode = %d\n", MNT_PATH, FS_NAME, dev_name, res);
+        return false;
+    }
+
+    return true;
+}
+
+bool test_teardown(void)
+{
+    if (fs_unmount(MNT_PATH) != NO_ERROR) {
+        printf("Unmount failed\n");
+        return false;
+    }
+
+    return true;;
+}
+
+static bool test_empty_after_format(const char *dev_name)
+{
+    dirhandle *dhandle;
+    status_t err = fs_open_dir(MNT_PATH, &dhandle);
+    if (err != NO_ERROR) {
+        return false;
+    }
+
+    struct dirent ent;
+    if (fs_read_dir(dhandle, &ent) >= 0) {
+        fs_close_dir(dhandle);
+        return false;
+    }
+
+    fs_close_dir(dhandle);
+    return true;
+}
+
+static bool test_double_create_file(const char *dev_name)
+{
+    status_t status;
+
+    struct dirent *ent = malloc(sizeof(*ent));
+    size_t num_files = 0;
+
+    filehandle *handle;
+    status = fs_create_file(TEST_FILE_PATH, &handle, 10);
+    if (status != NO_ERROR) {
+        goto err;
+    }
+    fs_close_file(handle);
+
+    filehandle *duphandle;
+    status = fs_create_file(TEST_FILE_PATH, &duphandle, 20);
+    if (status != ERR_ALREADY_EXISTS) {
+        goto err;
+    }
+
+    dirhandle *dhandle;
+    status = fs_open_dir(MNT_PATH, &dhandle);
+    if (status != NO_ERROR) {
+        goto err;
+    }
+
+    while ((status = fs_read_dir(dhandle, ent)) >= 0) {
+        num_files++;
+    }
+
+    status = NO_ERROR;
+
+    fs_close_dir(dhandle);
+
+
+err:
+    free(ent);
+
+    return status == NO_ERROR ? num_files == 1 : false;
+}
+
+static bool test_write_read_normal(const char *dev_name)
+{
+    char test_message[] = "spifs test";
+    char test_buf[sizeof(test_message)];
+
+    bdev_t *dev = bio_open(dev_name);
+    if (!dev) {
+        return false;
+    }
+    uint8_t erase_byte = dev->erase_byte;
+    bio_close(dev);
+
+    filehandle *handle;
+    status_t status =
+        fs_create_file(TEST_FILE_PATH, &handle, sizeof(test_message));
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    ssize_t bytes;
+
+    // New files should be initialized to 'erase_byte'
+    bytes = fs_read_file(handle, test_buf, 0, sizeof(test_buf));
+    if (bytes != sizeof(test_buf)) {
+        return false;
+    }
+
+    for (size_t i = 0; i < sizeof(test_buf); i++) {
+        if (test_buf[i] != erase_byte) {
+            return false;
+        }
+    }
+
+    bytes = fs_write_file(handle, test_message, 0, sizeof(test_message));
+    if (bytes != sizeof(test_message)) {
+        return false;
+    }
+
+    bytes = fs_read_file(handle, test_buf, 0, sizeof(test_buf));
+    if (bytes != sizeof(test_buf)) {
+        return false;
+    }
+
+    status = fs_close_file(handle);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    return strncmp(test_message, test_buf, sizeof(test_message)) == 0;
+}
+
+static bool test_write_past_eof(const char *dev_name)
+{
+    char test_message[] = "spifs test";
+
+    // Create a 0 length file.
+    filehandle *handle;
+    status_t status =
+        fs_create_file(TEST_FILE_PATH, &handle, 0);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    ssize_t bytes = fs_write_file(handle, test_message, 0, sizeof(test_message));
+    if (bytes != sizeof(test_message)) {
+        return false;
+    }
+
+    // Make sure the file grows.
+    struct file_stat stat;
+    fs_stat_file(handle, &stat);
+    if (stat.is_dir != false && stat.size != sizeof(test_message)) {
+        return false;
+    }
+
+    fs_close_file(handle);
+
+    return true;
+}
+
+static bool test_full_toc(const char *dev_name)
+{
+    struct fs_stat stat;
+
+    fs_stat_fs(MNT_PATH, &stat);
+
+    char test_file_name[TEST_PATH_MAX_SIZE];
+
+    filehandle *handle;
+    for (size_t i = 0; i < stat.free_inodes; i++) {
+        memset(test_file_name, 0, TEST_PATH_MAX_SIZE);
+
+        char filenum[] = "000";
+        filenum[0] += i / 100;
+        filenum[1] += (i / 10) % 10;
+        filenum[2] += i % 10;
+
+        strlcat(test_file_name, MNT_PATH, sizeof(test_file_name));
+        strlcat(test_file_name, "/", sizeof(test_file_name));
+        strlcat(test_file_name, filenum, sizeof(test_file_name));
+
+        status_t status =
+            fs_create_file(test_file_name, &handle, 1);
+
+        if (status != NO_ERROR) {
+            return false;
+        }
+
+        fs_close_file(handle);
+    }
+
+    // There shouldn't be enough space for this file since we've exhausted all
+    // the inodes.
+
+    status_t status = fs_create_file(TEST_FILE_PATH, &handle, 1);
+    if (status != ERR_TOO_BIG) {
+        return false;
+    }
+
+    return true;
+}
+
+static bool test_rm_reclaim(const char *dev_name)
+{
+    // Create some number of files that's a power of 2;
+    size_t n_files = 4;
+
+    struct fs_stat stat;
+
+    fs_stat_fs(MNT_PATH, &stat);
+
+    size_t file_size = stat.free_space / (n_files + 1);
+
+    char test_file_name[TEST_PATH_MAX_SIZE];
+
+    filehandle *handle;
+    for (size_t i = 0; i < n_files; i++) {
+        memset(test_file_name, 0, TEST_PATH_MAX_SIZE);
+
+        char filenum[] = "000";
+        filenum[0] += i / 100;
+        filenum[1] += (i / 10) % 10;
+        filenum[2] += i % 10;
+
+        strcat(test_file_name, MNT_PATH);
+        strcat(test_file_name, filenum);
+
+        status_t status =
+            fs_create_file(test_file_name, &handle, file_size);
+
+        if (status != NO_ERROR) {
+            return false;
+        }
+
+        fs_close_file(handle);
+    }
+
+    // Try to create a new Big file.
+    char filename[] = "BIGFILE";
+    memset(test_file_name, 0, TEST_PATH_MAX_SIZE);
+    strcat(test_file_name, MNT_PATH);
+    strcat(test_file_name, filename);
+
+    status_t status;
+
+    // This should fail because there's no more space.
+    fs_stat_fs(MNT_PATH, &stat);
+    status = fs_create_file(test_file_name, &handle, stat.free_space + 1);
+    if (status != ERR_TOO_BIG) {
+        return false;
+    }
+
+    // Delete an existing file to make space for the new file.
+    char existing_filename[] = "001";
+    memset(test_file_name, 0, TEST_PATH_MAX_SIZE);
+    strcat(test_file_name, MNT_PATH);
+    strcat(test_file_name, existing_filename);
+
+    status = fs_remove_file(test_file_name);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+
+    // Now this should go through because we've reclaimed the space.
+    status = fs_create_file(test_file_name, &handle, stat.free_space + 1);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    fs_close_file(handle);
+    return true;
+}
+
+static bool test_full_fs(const char *dev_name)
+{
+    struct fs_stat stat;
+
+    fs_stat_fs(MNT_PATH, &stat);
+
+    char second_file_path[TEST_PATH_MAX_SIZE];
+    memset(second_file_path, 0, TEST_PATH_MAX_SIZE);
+    strcpy(second_file_path, MNT_PATH);
+    strcat(second_file_path, "/fail");
+
+    filehandle *handle;
+    status_t status = fs_create_file(TEST_FILE_PATH, &handle, stat.free_space);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    fs_close_file(handle);
+
+    // There shouldn't be enough space for this file since we've used all the
+    // space.
+    status = fs_create_file(second_file_path, &handle, 1);
+    if (status != ERR_TOO_BIG) {
+        return false;
+    }
+
+    return true;
+}
+
+static bool test_write_past_end_of_capacity(const char *dev_name)
+{
+    filehandle *handle;
+    status_t status = fs_create_file(TEST_FILE_PATH, &handle, 0);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    struct file_stat stat;
+    status = fs_stat_file(handle, &stat);
+    if (status != NO_ERROR) {
+        goto finish;
+    }
+
+    // We shouldn't be able to write past the capacity of a file.
+    char buf[1];
+    status = fs_write_file(handle, buf, stat.capacity, 1);
+    if (status == ERR_OUT_OF_RANGE) {
+        status = NO_ERROR;
+    } else {
+        status = ERR_IO;
+    }
+
+finish:
+    fs_close_file(handle);
+    return status == NO_ERROR;
+}
+
+static bool test_corrupt_toc(const char *dev_name)
+{
+    // Create a zero byte file.
+    filehandle *handle;
+    status_t status = fs_create_file(TEST_FILE_PATH, &handle, 0);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    // Grow the file to one byte. This should trigger a ToC flush. Now the
+    // ToC record for this file should exist in both ToCs. Therefore corrupting
+    // either of the ToCs will still yield this file readable.
+    char buf[1] = { 'a' };
+    status = fs_write_file(handle, buf, 0, 1);
+    if (status != 1) {
+        return false;
+    }
+
+    status = fs_close_file(handle);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    status = fs_unmount(MNT_PATH);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    // Now we're going to manually corrupt one of the ToCs
+    bdev_t *dev = bio_open(dev_name);
+    if (!dev) {
+        return false;
+    }
+
+    // Directly write 0s to the block that contains the front-ToC.
+    size_t block_size = dev->block_size;
+    uint8_t *block_buf = memalign(CACHE_LINE, block_size);
+    if (!block_buf) {
+        return false;
+    }
+    memset(block_buf, 0, block_size);
+
+    ssize_t bytes = bio_write_block(dev, block_buf, 0, 1);
+
+    free(block_buf);
+
+    bio_close(dev);
+
+    if (bytes != (ssize_t)block_size) {
+        return false;
+    }
+
+    // Mount the FS again and make sure that the file we created is still there.
+    status = fs_mount(MNT_PATH, FS_NAME, dev_name);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    status = fs_open_file(TEST_FILE_PATH, &handle);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    struct file_stat stat;
+    status = fs_stat_file(handle, &stat);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    status = fs_close_file(handle);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    return true;
+}
+
+static bool test_write_with_offset(const char *dev_name)
+{
+    size_t repeats = 3;
+    char test_message[] = "test";
+    size_t msg_len = strnlen(test_message, sizeof(test_message));
+    char test_buf[msg_len * repeats];
+
+    filehandle *handle;
+    status_t status = fs_create_file(TEST_FILE_PATH, &handle, msg_len);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    ssize_t bytes;
+    for (size_t pos = 0; pos < repeats; pos++) {
+        bytes = fs_write_file(handle, test_message, pos * msg_len, msg_len);
+        if ((size_t)bytes != msg_len) {
+            return false;
+        }
+    }
+
+    bytes = fs_read_file(handle, test_buf, 0, msg_len * repeats);
+    if ((size_t)bytes != msg_len * repeats) {
+        return false;
+    }
+
+    status = fs_close_file(handle);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    bool success = true;
+    for (size_t i = 0; i < repeats; i++) {
+        success &= (memcmp(test_message,
+                           test_buf + i * msg_len,
+                           msg_len) == 0);
+    }
+    return success;
+}
+
+static bool test_read_write_big(const char *dev_name)
+{
+    bool success = true;
+
+    size_t buflen = 10013;
+
+    uint8_t *rbuf = malloc(buflen);
+    if (!rbuf) {
+        return false;
+    }
+
+    uint8_t *wbuf = malloc(buflen);
+    if (!wbuf) {
+        free(rbuf);
+        return false;
+    }
+
+    for (size_t i = 0; i < buflen; i++) {
+        wbuf[i] = rand() % sizeof(uint8_t);
+    }
+
+    filehandle *handle;
+    status_t status = fs_create_file(TEST_FILE_PATH, &handle, buflen);
+    if (status != NO_ERROR) {
+        success = false;
+        goto err;
+    }
+
+    ssize_t bytes = fs_write_file(handle, wbuf, 0, buflen);
+    if ((size_t)bytes != buflen) {
+        success = false;
+        goto err;
+    }
+
+    bytes = fs_read_file(handle, rbuf, 0, buflen);
+    if ((size_t)bytes != buflen) {
+        success = false;
+        goto err;
+    }
+
+    for (size_t i = 0; i < buflen; i++) {
+        if (wbuf[i] != rbuf[i]) {
+            success = false;
+            break;
+        }
+    }
+
+err:
+    success &= fs_close_file(handle) == NO_ERROR;
+
+    free(rbuf);
+    free(wbuf);
+    return success;
+}
+
+static bool test_rm_active_dirent(const char *dev_name)
+{
+    filehandle *handle;
+    status_t status = fs_create_file(TEST_FILE_PATH, &handle, 0);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    status = fs_close_file(handle);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    dirhandle *dhandle;
+    status = fs_open_dir(MNT_PATH, &dhandle);
+    if (status != NO_ERROR) {
+        return false;
+    }
+
+    // Dir handle should now be pointing to the only file in our FS.
+    status = fs_remove_file(TEST_FILE_PATH);
+    if (status != NO_ERROR) {
+        fs_close_dir(dhandle);
+        return false;
+    }
+
+    bool success = true;
+    struct dirent *ent = malloc(sizeof(*ent));
+    if (fs_read_dir(dhandle, ent) >= 0) {
+        success = false;
+    }
+
+    success &= fs_close_dir(dhandle) == NO_ERROR;
+    free(ent);
+
+    return success;
+}
+
+static int cmd_spifs(int argc, const cmd_args *argv)
+{
+    if (argc < 3) {
+notenoughargs:
+        printf("not enough arguments:\n");
+usage:
+        printf("%s test <device>\n", argv[0].str);
+        return -1;
+    }
+
+    if (strcmp(argv[1].str, "test")) {
+        goto usage;
+    }
+
+    // Make sure this block device is legit.
+    bdev_t *dev = bio_open(argv[2].str);
+    if (!dev) {
+        printf("error: could not open block device %s\n", argv[2].str);
+        return -1;
+    }
+    bio_close(dev);
+
+    size_t passed = 0;
+    size_t attempted = 0;
+    for (size_t i = 0; i < countof(tests); i++) {
+        ++attempted;
+        if (!test_setup(argv[2].str, tests[i].toc_pages)) {
+            printf("Test Setup failed before %s. Exiting.\n", tests[i].name);
+            break;
+        }
+
+        if (tests[i].func(argv[2].str)) {
+            printf(" [Passed] %s\n", tests[i].name);
+            ++passed;
+        } else {
+            printf(" [Failed] %s\n", tests[i].name);
+        }
+
+        if (!test_teardown()) {
+            printf("Test teardown failed after %s. Exiting.\n", tests[i].name);
+            break;
+        }
+    }
+    printf("\nPassed %u of %u tests.\n", passed, attempted);
+
+    if (attempted != countof(tests)) {
+        printf("(Skipped %u)\n", countof(tests) - attempted);
+    }
+
+    return countof(tests) - passed;
+}
+
+STATIC_COMMAND_START
+STATIC_COMMAND("spifs", "commands related to the spifs implementation.", &cmd_spifs)
+STATIC_COMMAND_END(spifs);
+
+#endif  // LK_DEBUGLEVEL > 1
\ No newline at end of file