]> cloudbase.mooo.com Git - z180-stamp.git/blobdiff - avr/cmd_fat.c
Merge branch 'fatfs-integration' into fatcommands
[z180-stamp.git] / avr / cmd_fat.c
index 20d1da9f01e921c26425c65c6d26d0a69746127b..33d60510b575e84ff95983cef5d78a2ce874d971 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * (C) Copyright 2014,2016 Leo C. <erbl259-lmu@yahoo.de>
+ * (C) Copyright 2014,2016,2018 Leo C. <erbl259-lmu@yahoo.de>
  *
  * SPDX-License-Identifier:    GPL-2.0
  */
@@ -8,11 +8,9 @@
  * FAT filesystem commands
  */
 
-#include "common.h"
-#include <string.h>
-#include <stdbool.h>
+#include "cmd_fat.h"
+#include <util/delay.h>
 
-#include "command.h"
 #include "ff.h"
 #include "z80-if.h"
 #include "eval_arg.h"
 #include "time.h"
 #include "timer.h"
 #include "debug.h"
+#include "env.h"
+#include "getopt-min.h"
 
-/* TODO: use memory size test function (cmd_mem.c) */
-#define MAX_MEMORY     (1ul << 19)
+
+#define DEBUG_CP               1       /* set to 1 to debug */
+#define DEBUG_LS               1       /* set to 1 to debug */
+#define DEBUG_RM               1       /* set to 1 to debug */
+#define DEBUG_FA               1       /* set to 1 to debug */
+
+#define debug_cp(fmt, args...)                                                        \
+       debug_cond(DEBUG_CP, fmt, ##args)
+#define debug_ls(fmt, args...)                                                        \
+       debug_cond(DEBUG_LS, fmt, ##args)
+#define debug_rm(fmt, args...)                                                        \
+       debug_cond(DEBUG_RM, fmt, ##args)
+#define debug_fa(fmt, args...)                                                        \
+       debug_cond(DEBUG_FA, fmt, ##args)
+
+
+
+/* TODO: use memory size test function (detect_ramsize() in cmd_loadihex.c) */
+/* TODO: detect_ramsize() should be moved to z80-if.c */
+#define MAX_MEMORY     CONFIG_SYS_RAMSIZE_MAX
 #define BUFFER_SIZE    512
+#define MAX_PATHLEN CONFIG_SYS_MAX_PATHLEN
+
+
+typedef struct {
+       char *p_end;                    /* pointer to NULL at end of path */
+       char p_path[MAX_PATHLEN + 1];   /* pointer to the start of a path */
+} PATH_T;
+
+/*
+ * Multible (fat) partitions per physical drive are not supported,
+ * but we have up to 2 sdcard slots.
+ */
+FATFS FatFs0;
+FATFS FatFs1;
+
+uint8_t *blockbuf;
+int blockbuf_size;
+PATH_T from;
+PATH_T to;
+command_ret_t command_ret;
+char *cmdname;
+
+static uint8_t flags;
+#define F_FLAG (1<<3)  // overwrite existing file ignoring write protection
+#define I_FLAG (1<<1)  // prompt before overwrite (overrides a previous -n option)
+#define N_FLAG (1<<2)  // do not overwrite an existing file (overrides a previous -i option)
+#define P_FLAG (1<<4)  // preserve attributes and timestamps
+#define R_FLAG (1<<0)  // copy directories recursively
+#define V_FLAG (1<<5)  // explain what is being done
+
+
 
+void setup_fatfs(void)
+{
+       f_mount(&FatFs0, "0:", 0);
+       f_mount(&FatFs1, "1:", 0);
+}
 
 DWORD get_fattime (void)
 {
@@ -50,6 +104,29 @@ static bool check_abort(void)
 }
 
 
+static const FLASH char * const FLASH rc_strings[] = {
+                       FSTR("OK"),
+                       FSTR("disk error"),
+                       FSTR("internal error"),
+                       FSTR("not ready"),
+                       FSTR("no file"),
+                       FSTR("no path"),
+                       FSTR("invalid name"),
+                       FSTR("denied"),
+                       FSTR("exist"),
+                       FSTR("invalid object"),
+                       FSTR("write protected"),
+                       FSTR("invalid drive"),
+                       FSTR("not enabled"),
+                       FSTR("no file system"),
+                       FSTR("mkfs aborted"),
+                       FSTR("timeout"),
+                       FSTR("locked"),
+                       FSTR("not enough core"),
+                       FSTR("too many open files"),
+                       FSTR("invalid parameter")
+               };
+
 static const FLASH char * const FLASH rc_names[] = {
                        FSTR("OK"),
                        FSTR("DISK_ERR"),
@@ -86,6 +163,217 @@ void put_rc (FRESULT rc)
 #endif
 }
 
+const FLASH char * rctostr(FRESULT rc)
+{
+       return  rc < ARRAY_SIZE(rc_strings) ? rc_strings[rc] : PSTR(" Unknown Error");
+}
+
+void err(const char *fmt, ...)
+{
+       va_list ap;
+       va_start(ap, fmt);
+       printf_P(PSTR("fat %s: "), cmdname);
+       vfprintf_P(stdout, fmt, ap);
+       va_end(ap);
+       printf_P(PSTR("\n"));
+       _delay_ms(20);
+       command_ret = CMD_RET_FAILURE;
+}
+
+/******************************************************************************/
+
+/*
+ * These functions manipulate paths in PATH_T structures.
+ *
+ * They eliminate multiple slashes in paths when they notice them,
+ * and keep the path non-slash terminated.
+ *
+ * Both path_set() and path_append() return 0 if the requested name
+ * would be too long.
+ */
+
+
+static void path_init(void)
+{
+       from.p_path[0] = '\0'; from.p_end = from.p_path;
+       to.p_path[0] = '\0';   to.p_end = to.p_path;
+}
+
+static char *path_skip_heading(char *p)
+{
+       if ((p[0] & 0x38) == '0' &&  p[1] == ':') {
+               p += 2;
+       } else {
+               char *q = p;
+               if (*q++ == '.') {
+                       if (*q == '.')
+                               ++q;
+                       if (*q == '\0' || *q == '/')
+                               p = q;
+               }
+               return p;
+       }
+       if (*p == '/')
+               ++p;
+
+       return p;
+}
+
+static void strip_trailing_slash(PATH_T *p)
+{
+       char *beg = path_skip_heading(p->p_path);
+       char *end = p->p_end;
+
+       while (end > beg && end[-1] == '/')
+               *--end = '\0';
+
+       p->p_end =end;
+}
+
+/*
+ * Move specified string into path.  Convert "" to "." to handle BSD
+ * semantics for a null path.  Strip trailing slashes.
+ */
+int
+path_set(PATH_T *p, char *string)
+{
+       if (strlen(string) > MAX_PATHLEN) {
+               err(PSTR("set: '%s': name too long"), string);
+               return 0;
+       }
+
+       (void)strcpy(p->p_path, string);
+       p->p_end = p->p_path + strlen(p->p_path);
+
+       if (p->p_path == p->p_end) {
+               *p->p_end++ = '.';
+               *p->p_end = '\0';
+       }
+
+       strip_trailing_slash(p);
+       return 1;
+}
+
+/*
+ * Append specified string to path, inserting '/' if necessary.  Return a
+ * pointer to the old end of path for restoration.
+ */
+char *
+path_append(PATH_T *p, char *name)
+{
+       char *old = p->p_end;
+       int len = strlen(name);
+
+       /* The "+ 1" accounts for the '/' between old path and name. */
+       if ((len + p->p_end - p->p_path + 1) > MAX_PATHLEN) {
+               err(PSTR("append: '%s/%s': name too long"), p->p_path, name);
+               return NULL;
+       }
+
+       /*
+        * This code should always be executed, since paths shouldn't
+        * end in '/'.
+        */
+       if (p->p_end[-1] != '/') {
+               *p->p_end++ = '/';
+               *p->p_end = '\0';
+       }
+
+       strncat(p->p_end, name, len);
+       p->p_end += len;
+       *p->p_end = '\0';
+
+       strip_trailing_slash(p);
+       return old;
+}
+
+/*
+ * Restore path to previous value.  (As returned by path_append.)
+ */
+void
+path_restore(PATH_T *p, char *old)
+{
+       p->p_end = old;
+       *p->p_end = '\0';
+}
+
+/*
+ * Return basename of path.
+ */
+char *path_basename(PATH_T *p)
+{
+       char *basename = strrchr(p->p_path, '/');
+
+       if (basename) {
+               ++basename;
+       } else {
+               basename = p->p_path;
+               if ((basename[0] & 0x38) == '0' &&  basename[1] == ':')
+                       basename += 2;
+       }
+
+       return basename;
+}
+
+#if 0
+char *path_basename_pattern(PATH_T *p)
+{
+       char *pattern = path_basename(p);
+       if (strpbrk_P(pattern, PSTR("*?"))) {
+               memmove(pattern+1, pattern, strlen(pattern)+1);
+               *pattern++ = '\0';
+       } else {
+               //p->p_pattern = p->p_end + 1;
+               pattern = p->p_end + 1;
+               pattern[0] = '*';
+               pattern[1] = '\0';
+       }
+       return pattern;
+}
+#endif
+
+/*
+ * Split path
+ * Return basename/pattern of path.
+ */
+
+char *path_split_pattern(PATH_T *p)
+{
+       char *pp = path_skip_heading(p->p_path);
+       char *pattern = strrchr(pp, '/');
+
+       if (pattern == NULL) {
+               pattern = pp;
+               p->p_end = pattern;
+       } else {
+               p->p_end = pattern;
+               pattern++;
+       }
+       memmove(pattern+2, pattern, strlen(pattern)+1);
+       pattern += 2;
+       *p->p_end = '\0' ;
+
+       return pattern;
+}
+
+void path_fix(PATH_T *p)
+{
+       char *pp = path_skip_heading(p->p_path);
+
+       if (pp != p->p_end) {
+               *p->p_end++ = '/';
+               *p->p_end = '\0' ;
+       }
+}
+
+void path_unfix(PATH_T *p)
+{
+       char *pp = path_skip_heading(p->p_path);
+
+       if (pp != p->p_end) {
+               *--p->p_end = '\0' ;
+       }
+}
 
 static void swirl(void)
 {
@@ -100,7 +388,744 @@ static void swirl(void)
        }
 }
 
-/* Work register for fs command */
+/*
+ * pwd - Print current directory of the current drive.
+ *
+ */
+command_ret_t do_pwd(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc UNUSED, char * const argv[] UNUSED)
+{
+       FRESULT res;
+
+       cmdname = argv[0];
+       command_ret = CMD_RET_SUCCESS;
+
+       res = f_getcwd(from.p_path, MAX_PATHLEN);  /* Get current directory path */
+
+       if (res == FR_OK)
+               puts(from.p_path);
+       else
+               err(PSTR("Error: %S"), rctostr(res));
+
+       return command_ret;
+}
+
+
+/*
+ * cd - Change the current/working directory.
+ *
+ */
+command_ret_t do_cd(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
+{
+       char *arg;
+       FRESULT res = FR_OK;
+
+       cmdname = argv[0];
+       command_ret = CMD_RET_SUCCESS;
+
+       if (argc < 2) {
+               arg = getenv_str(PSTR(ENV_HOME));
+               if (arg == NULL) {
+                       err(PSTR("'%S' is not set"), PSTR(ENV_HOME));
+                       return command_ret;
+               }
+       } else
+               arg = argv[1];
+
+       if (arg[1] == ':')
+               res = f_chdrive(arg);
+       if (res == FR_OK)
+               res = f_chdir(arg);
+       if (res != FR_OK)
+               err(PSTR("'%s': %S"), arg, rctostr(res));
+
+       return command_ret;
+}
+
+
+static int decode_arg(const char *arg)
+{
+       BYTE attr = 0;
+       char c;
+
+       while ((c = *++arg) != '\0') {
+               switch (c) {
+                       case 'a':
+                               attr |= AM_ARC;         /* Archive   */
+                               break;
+                       case 'h':
+                               attr |= AM_HID;         /* Hidden    */
+                               break;
+                       case 'r':
+                               attr |= AM_RDO;         /* Read only */
+                               break;
+                       case 's':
+                               attr |= AM_SYS;         /* System    */
+                               break;
+                       default:
+                               err(PSTR("unknown attribute: '%c'"), c);
+                               return -1;
+               }
+       }
+       return attr;
+}
+
+static void print_attrib(char *path, FILINFO *f)
+{
+       printf_P(PSTR("%c%c%c%c%c %s%s\n"),
+                               (f->fattrib & AM_DIR) ? 'D' : '-',
+                               (f->fattrib & AM_RDO) ? 'R' : '-',
+                               (f->fattrib & AM_HID) ? 'H' : '-',
+                               (f->fattrib & AM_SYS) ? 'S' : '-',
+                               (f->fattrib & AM_ARC) ? 'A' : '-',
+                               path, f->fname);
+}
+
+command_ret_t do_attrib(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, UNUSED char * const argv[])
+{
+       DIR Dir;                                        /* Directory object */
+       FILINFO Finfo;
+       FRESULT res;
+       BYTE set_mask = 0;
+       BYTE clear_mask = 0;
+
+       cmdname = argv[0];
+       command_ret = CMD_RET_SUCCESS;
+
+
+       for (;;) {
+               int attr;
+               char *arg = *++argv;
+
+               if (!arg)
+                       return CMD_RET_USAGE;
+               if (arg[0] != '-' && arg[0] != '+')
+                       break;
+               attr = decode_arg(arg);
+               if (attr < 0)
+                       return CMD_RET_FAILURE;
+               if (arg[0] == '+')
+                       set_mask |= attr;
+               else
+                       clear_mask |= attr;
+       }
+
+       do {
+               if (!path_set(&from, *argv)) {
+                       /* TODO: error out*/
+               }
+               char *pattern = path_split_pattern(&from);
+               if (*pattern == '\0')
+                       pattern = "*";
+               debug_fa("==== path: '%s', pattern: '%s'\n", from.p_path ? from.p_path : "<NULL>", pattern ? pattern : "<NULL>");
+               res = f_findfirst(&Dir, &Finfo, from.p_path, pattern);
+               debug_fa("==== findfirst %d\n", res);
+               if (res != FR_OK || !Finfo.fname[0]) {
+                       path_fix(&from);
+                       err(PSTR("'%s%s': No such file or directory"), from.p_path, pattern);
+               } else {
+                       do {
+                               if (set_mask | clear_mask) {
+                                       if ((res = f_chmod(Finfo.fname, set_mask, set_mask | clear_mask)) != FR_OK) {
+                                               path_fix(&from);
+                                               err(PSTR("'%s%s': %S"), from.p_path, Finfo.fname, rctostr(res));
+                                               path_unfix(&from);
+                                       }
+                               } else {
+                                       path_fix(&from);
+                                       print_attrib(from.p_path, &Finfo);
+                                       path_unfix(&from);
+                               }
+
+                               res = f_findnext(&Dir, &Finfo);
+                               //debug_fa("==== findnext %d\n", res);
+                       } while (res == FR_OK && Finfo.fname[0]);
+               }
+               f_closedir(&Dir);
+       } while (*++argv);
+
+       return command_ret;
+}
+
+command_ret_t do_rm(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
+{
+       DIR Dir;                                        /* Directory object */
+       FILINFO Finfo;
+       FRESULT res;
+
+       cmdname = argv[0];
+       command_ret = CMD_RET_SUCCESS;
+
+       /* reset getopt() */
+       optind = 0;
+       flags = 0;
+
+       int opt;
+       while ((opt = getopt(argc, argv, PSTR("nv"))) != -1) {
+               switch (opt) {
+                       case 'n':
+                               flags |=  N_FLAG;
+                               break;
+                       case 'v':
+                               flags |=  V_FLAG;
+                               break;
+                       default:
+                               return CMD_RET_USAGE;
+                               break;
+               }
+       }
+       argc -= optind;
+       argv += optind;
+
+       if (argc < 1) {
+               err(PSTR("missing operand"));
+       } else {
+               for (int i = 0; i < argc; i++) {
+                       if (!path_set(&from, argv[i])) {
+                               /* TODO: error out*/
+                       }
+                       char *pattern = path_split_pattern(&from);
+
+                       debug_rm("==== path: '%s', pattern: '%s'\n", from.p_path ? from.p_path : "<NULL>", pattern ? pattern : "<NULL>");
+
+                       res = f_findfirst(&Dir, &Finfo, from.p_path, pattern);
+                       debug_rm("==== findfirst %d\n", res);
+
+                       if (res != FR_OK || !Finfo.fname[0]) {
+                               path_fix(&from);
+                               err(PSTR("cannot remove '%s%s': No such file or directory"), from.p_path, pattern);
+                       } else {
+                               do {
+                                       if (Finfo.fattrib & AM_DIR) {
+                                               path_fix(&from);
+                                               err(PSTR("cannot remove '%s%s': Is a directory"), from.p_path, Finfo.fname);
+                                       } else {
+                                               if (!(flags & N_FLAG)) {
+                                                       if ((res = f_unlink(Finfo.fname)) == FR_OK) {
+                                                               if (flags & V_FLAG)
+                                                                       path_fix(&from);
+                                                                       printf_P(PSTR("removed '%s%s'\n"), from.p_path, Finfo.fname);
+                                                                       path_unfix(&from);
+                                                       } else {
+                                                               path_fix(&from);
+                                                               err(PSTR("cannot remove '%s%s': %S"), from.p_path, Finfo.fname, rctostr(res));
+                                                       }
+                                               } else {
+                                                       path_fix(&from);
+                                                       printf_P(PSTR("not removed '%s%s'\n"), from.p_path, Finfo.fname);
+                                                       path_unfix(&from);
+                                               }
+                                       }
+                                       res = f_findnext(&Dir, &Finfo);
+                                       //debug_rm("==== findnext %d\n", res);
+                               } while (res == FR_OK && Finfo.fname[0]);
+                       }
+                       f_closedir(&Dir);
+               }
+
+               /* TODO */
+               if (res) {
+                       put_rc(res);
+                       return CMD_RET_FAILURE;
+               }
+       }
+       return command_ret;
+}
+
+command_ret_t do_rmdir(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
+{
+       cmdname = argv[0];
+       command_ret = CMD_RET_SUCCESS;
+
+       return command_ret;
+}
+
+command_ret_t do_mkdir(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
+{
+       cmdname = argv[0];
+       command_ret = CMD_RET_SUCCESS;
+
+       return command_ret;
+}
+
+
+static void print_dirent(FILINFO *f)
+{
+       printf_P(PSTR("%c%c%c%c%c %u/%02u/%02u %02u:%02u %9lu  %s\n"),
+                               (f->fattrib & AM_DIR) ? 'D' : '-',
+                               (f->fattrib & AM_RDO) ? 'R' : '-',
+                               (f->fattrib & AM_HID) ? 'H' : '-',
+                               (f->fattrib & AM_SYS) ? 'S' : '-',
+                               (f->fattrib & AM_ARC) ? 'A' : '-',
+                               (f->fdate >> 9) + 1980, (f->fdate >> 5) & 15, f->fdate & 31,
+                               (f->ftime >> 11), (f->ftime >> 5) & 63,
+                               f->fsize, f->fname);
+}
+
+/*
+ * ls path - Directory listing
+ *
+ */
+command_ret_t do_ls(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
+{
+       FATFS *fs;
+       DIR Dir;                                        /* Directory object */
+       FILINFO Finfo;
+       unsigned long p1;
+       unsigned int s1, s2;
+       FRESULT res;
+
+       cmdname = argv[0];
+       command_ret = CMD_RET_SUCCESS;
+
+       path_init();
+       if (argc > 1)
+               if (!path_set(&from, argv[1])) {
+                       /* TODO: error out*/
+               }
+
+#if 0
+       char *pattern = path_basename_pattern(&from);
+#else
+       char *pattern = path_split_pattern(&from);
+       if (*pattern == '\0')
+               pattern = "*";
+#endif
+       debug_ls("==== path: '%s', pattern: '%s'\n", from.p_path ? from.p_path : "<NULL>", pattern ? pattern : "<NULL>");
+
+       p1 = s1 = s2 = 0;
+       res = f_findfirst(&Dir, &Finfo, from.p_path, pattern);  /* Start to search for files */
+       if (res != FR_OK || !Finfo.fname[0]) {
+               path_fix(&from);
+               err(PSTR("'%s%s': No such file or directory"), from.p_path, pattern);
+       } else {
+               do {
+                       if (Finfo.fattrib & AM_DIR) {
+                               s2++;
+                       } else {
+                               s1++; p1 += Finfo.fsize;
+                       }
+                       print_dirent(&Finfo);
+                       if (check_abort())
+                               break;
+                       res = f_findnext(&Dir, &Finfo);
+               } while (res == FR_OK && Finfo.fname[0]);
+       }
+       f_closedir(&Dir);
+
+       if (res == FR_OK && command_ret == CMD_RET_SUCCESS) {
+               printf_P(PSTR("%4u File(s),%10lu bytes total\n%4u Dir(s)"), s1, p1, s2);
+               if (f_getfree(from.p_path, (DWORD*)&p1, &fs) == FR_OK)
+                       printf_P(PSTR(", %10luK bytes free\n"), p1 * fs->csize / 2);
+       }
+
+       if (res && command_ret == CMD_RET_SUCCESS) {
+               put_rc(res);
+               return CMD_RET_FAILURE;
+       }
+
+       return command_ret;
+}
+
+/*
+ * tst path - for debugging: test access with different functions
+ *
+ */
+command_ret_t do_tst(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
+{
+       DIR Dir;                                        /* Directory object */
+       FILINFO Finfo;
+       FRESULT res = FR_OK;
+       char *path = "";
+       char *pattern = "*";
+
+       printf_P(PSTR("sizeof DIR: %u, sizeof FIL: %u\n"), sizeof (DIR), sizeof (FILINFO));
+
+       char * buf = (char *) malloc(BUFFER_SIZE);
+       if (buf == NULL) {
+               printf_P(PSTR("tst: Out of Memory!\n"));
+               return CMD_RET_FAILURE;
+       }
+       res = f_getcwd(buf, BUFFER_SIZE);  /* Get current directory path */
+
+       if (!res) {
+               printf_P(PSTR("cwd: '%s'\n"), buf);
+       }
+       free(buf);
+       if (res) {
+               put_rc(res);
+               return CMD_RET_FAILURE;
+       }
+
+       if (argc > 1)
+               path = argv[1];
+       if (argc > 2)
+               pattern = argv[2];
+
+       printf_P(PSTR("arg: '%s' '%s'\n"), path, pattern);
+       printf_P(PSTR("==== f_stat:      "));
+       res = f_stat(path, &Finfo);
+       put_rc(res);
+       if (res == FR_OK) {
+               print_dirent(&Finfo);
+       }
+
+       printf_P(PSTR("==== f_findfirst: "));
+       res = f_findfirst(&Dir, &Finfo, path, pattern);  /* Start to search for files */
+       put_rc(res);
+       if (res == FR_OK) {
+               print_dirent(&Finfo);
+       }
+       f_closedir(&Dir);
+
+       printf_P(PSTR("==== f_opendir:   "));
+       res = f_opendir(&Dir, path);
+       put_rc(res);
+       f_closedir(&Dir);
+
+       return CMD_RET_SUCCESS;
+}
+
+/******************************************************************************/
+
+static void
+setfile(FILINFO *fs)
+{
+       FRESULT fr;
+
+       fr = f_utime(to.p_path, fs);
+       if (fr != FR_OK)
+               err(PSTR("f_utime: %s: %S"), to.p_path, rctostr(fr));
+       fr = f_chmod(to.p_path, fs->fattrib, AM_RDO|AM_ARC|AM_SYS|AM_HID);
+       if (fr != FR_OK)
+               err(PSTR("f_chmod: %s: %S"), to.p_path, rctostr(fr));
+
+}
+
+void copy_file(FILINFO *fs, uint_fast8_t dne)
+{
+       FIL from_fd, to_fd;
+       UINT rcount, wcount;
+       FRESULT fr;
+       BYTE open_mode;
+
+       if (blockbuf == NULL) {
+               blockbuf_size = get_freemem() / 512 * 512;
+               if (blockbuf_size != 0)
+                       blockbuf = (uint8_t *) malloc(blockbuf_size);
+               if (blockbuf == NULL) {
+                       err(PSTR("Not enough memory!\n"));
+                       return;
+               }
+       }
+
+debug_cp("==== copy_file(): dne: %u, blockbuf_size: %d, freemem: %u\n", dne, blockbuf_size, get_freemem());
+debug_cp("     from:'%s'  to:'%s'\n", from.p_path, to.p_path);
+
+
+       if ((fr = f_open(&from_fd, from.p_path, FA_READ)) != FR_OK) {
+               err(PSTR("%s: %S"), from.p_path, rctostr(fr));
+               return;
+       }
+
+       /*
+        * If the file exists and we're interactive, verify with the user.
+        */
+       if (!dne) {
+               if (flags & N_FLAG) {
+                       if (flags & V_FLAG)
+                               printf_P(PSTR("%s not overwritten\n"), to.p_path);
+                       f_close(&from_fd);
+                       return;
+               } if (flags & I_FLAG) {
+                       printf_P(PSTR("overwrite '%s'? "), to.p_path);
+                       if (!confirm_yes()) {
+                               f_close(&from_fd);
+                               return;
+                       }
+               }
+               if (flags & F_FLAG) {
+                       /* Remove existing destination file name create a new file. */
+                       f_chmod(to.p_path,0, AM_RDO);
+                       f_unlink(to.p_path);
+                       open_mode = FA_WRITE|FA_CREATE_NEW;
+               } else {
+                       /* Overwrite existing destination file name. */
+                       open_mode = FA_WRITE|FA_CREATE_ALWAYS;
+               }
+       } else {
+               open_mode = FA_WRITE|FA_CREATE_NEW;
+       }
+       fr = f_open(&to_fd, to.p_path, open_mode);
+
+       if (fr != FR_OK) {
+               err(PSTR("%s: %S"), to.p_path, rctostr(fr));
+               f_close(&from_fd);
+               return;
+       }
+
+       while ((fr = f_read(&from_fd, blockbuf, blockbuf_size, &rcount)) == FR_OK &&
+                                                                                       rcount > 0) {
+               fr = f_write(&to_fd, blockbuf, rcount, &wcount);
+               if (fr || wcount < rcount) {
+                       err(PSTR("%s: %S"), to.p_path, rctostr(fr));
+                       break;
+               }
+       }
+       if (fr != FR_OK)
+               err(PSTR("%s: S"), from.p_path, rctostr(fr));
+
+       f_close(&from_fd);
+       if ((fr = f_close(&to_fd)) != FR_OK)
+               err(PSTR("%s: %S"), to.p_path, rctostr(fr));
+
+       if (flags & P_FLAG)
+               setfile(fs);
+}
+
+static void copy();
+
+static void copy_dir(void)
+{
+       DIR Dir;                                        /* Directory object */
+       FILINFO Finfo;
+       char *old_from, *old_to;
+       FRESULT res;
+       char *pattern = {"*"};
+
+debug_cp("==== copy_dir(): freemem: %u\n", get_freemem());
+debug_cp("     from:'%s'  to:'%s'\n", from.p_path, to.p_path);
+
+#if 0
+
+       printf_P(PSTR("directory copy not supported, ommitting dir '%s'\n"),
+               from->p_path);
+       command_ret = CMD_RET_FAILURE;
+
+#else
+
+       for (res = f_findfirst(&Dir, &Finfo, from.p_path, pattern);
+                res == FR_OK && Finfo.fname[0];
+                res = f_findnext(&Dir, &Finfo)) {
+
+               if (!(Finfo.fattrib & AM_DIR) &&
+                               (old_from = path_append(&from, Finfo.fname))) {
+                       if ((old_to = path_append(&to, Finfo.fname))) {
+                               copy();
+                               path_restore(&to, old_to);
+                       }
+                       path_restore(&from, old_from);
+               }
+       }
+
+       for (res = f_findfirst(&Dir, &Finfo, from.p_path, pattern);
+                res == FR_OK && Finfo.fname[0];
+                res = f_findnext(&Dir, &Finfo)) {
+
+               if ((Finfo.fattrib & AM_DIR) &&
+                               (old_from = path_append(&from, Finfo.fname))) {
+                       if ((old_to = path_append(&to, Finfo.fname))) {
+                               copy();
+                               path_restore(&to, old_to);
+                       }
+                       path_restore(&from, old_from);
+               }
+       }
+}
+#endif
+
+/*
+ * copy file or directory at "from" to "to".
+ */
+static void copy()
+{
+       FILINFO from_stat, to_stat;
+       uint_fast8_t dne;
+       FRESULT fr;
+
+debug_cp("==== copy(); freemem: %u\n", get_freemem());
+debug_cp("     from:'%s'  to:'%s'\n", from.p_path, to.p_path);
+
+       fr = f_stat(from.p_path, &from_stat);
+       if (fr != FR_OK) {
+               err(PSTR("%s: %S"), from.p_path, rctostr(fr));
+               return;
+       }
+
+       /* not an error, but need to remember it happened */
+       if (f_stat(to.p_path, &to_stat) != FR_OK)
+               dne = 1;
+       else {
+               if (strcmp(to.p_path, from.p_path) == 0) {
+                       (void)printf_P(PSTR("%s and %s are identical (not copied).\n"),
+                                       to.p_path, from.p_path);
+                       command_ret = CMD_RET_FAILURE;
+                       return;
+               }
+               dne = 0;
+       }
+
+       if(from_stat.fattrib & AM_DIR) {
+               if (!(flags & R_FLAG)) {
+                       (void)printf_P(PSTR("-r not specified; ommitting dir '%s'\n"),
+                           from.p_path);
+                       command_ret = CMD_RET_FAILURE;
+                       return;
+               }
+               if (dne) {
+                       /*
+                        * If the directory doesn't exist, create the new one.
+                        */
+                       if ((fr = f_mkdir(to.p_path)) != FR_OK) {
+                               err(PSTR("%s: %S"), to.p_path, rctostr(fr));
+                               return;
+                       }
+               } else if (!(to_stat.fattrib & AM_DIR)) {
+                       (void)printf_P(PSTR("%s: not a directory.\n"), to.p_path);
+                       return;
+               }
+               copy_dir();
+               if (flags & P_FLAG)
+                       setfile(&from_stat);
+
+               return;
+       }
+       copy_file(&from_stat, dne);
+}
+
+command_ret_t do_cp(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
+{
+
+    FRESULT fr;        /* Return value */
+    //DIR dj;                  /* Directory search object */
+    FILINFO to_stat;    /* File information */
+    char *old_to;
+
+
+       cmdname = argv[0];
+       uint8_t tflags = 0;
+       command_ret = CMD_RET_SUCCESS;
+
+       /* reset getopt() */
+       optind = 0;
+
+       int opt;
+       while ((opt = getopt(argc, argv, PSTR("finprv"))) != -1) {
+               switch (opt) {
+                       case 'f':
+                               tflags &= ~(I_FLAG | N_FLAG);
+                               tflags |=  F_FLAG;
+                               break;
+                       case 'i':
+                               tflags &= ~(F_FLAG | N_FLAG);
+                               tflags |=  I_FLAG;
+                               break;
+                       case 'n':
+                               tflags &= ~(F_FLAG | I_FLAG);
+                               tflags |=  N_FLAG;
+                               break;
+                       case 'p':
+                               tflags |= P_FLAG;
+                               break;
+                       case 'r':
+                               tflags |= R_FLAG;
+                               break;
+                       case 'v':
+                               tflags |= V_FLAG;
+                               break;
+                       default:
+                               return CMD_RET_USAGE;
+                               break;
+               }
+       }
+       flags = tflags;
+       argc -= optind;
+       argv += optind;
+
+       if (argc < 2)
+               return CMD_RET_USAGE;
+
+       path_init();
+
+       /* last argument is destination */
+       if (!path_set(&to, argv[--argc]))
+               goto cleanup;
+
+       /*
+        * Cp has two distinct cases:
+        *
+        * % cp [-rip] source target
+        * % cp [-rip] source1 ... directory
+        *
+        * In both cases, source can be either a file or a directory.
+        *
+        * In (1), the target becomes a copy of the source. That is, if the
+        * source is a file, the target will be a file, and likewise for
+        * directories.
+        *
+        * In (2), the real target is not directory, but "directory/source".
+        */
+
+       fr = f_stat(to.p_path, &to_stat);
+debug_cp("==== main, stat to: fr: %d, attr: %02x, flags:%02x, freemem: %u\n",
+                                               fr, to_stat.fattrib, flags, get_freemem());
+debug_cp("     from:'%s'  to:'%s'\n", from.p_path, to.p_path);
+
+       if (fr != FR_OK && fr != FR_NO_FILE && fr != FR_NO_PATH) {
+               err(PSTR("Test1: %s: %S"), to.p_path, rctostr(fr));
+               command_ret = CMD_RET_FAILURE;
+               goto cleanup;
+       }
+       if (!(fr == FR_OK && (to_stat.fattrib & AM_DIR))) {
+               /*
+                * Case (1).  Target is not a directory.
+                */
+               if (argc > 1) {
+                       err(PSTR("target '%s' is not a directory"), to.p_path);
+                       //command_ret = CMD_RET_USAGE;
+                       goto cleanup;
+               }
+               if (!path_set(&from, *argv)) {
+                       command_ret = CMD_RET_FAILURE;
+                       goto cleanup;
+               }
+               copy();
+       }
+       else {
+               /*
+                * Case (2).  Target is a directory.
+                */
+               for (;; ++argv) {
+                       if (!path_set(&from, *argv))
+                               continue;
+                       if (!(old_to = path_append(&to, path_basename(&from))))
+                               continue;
+                       copy();
+                       if (!--argc)
+                               break;
+                       path_restore(&to, old_to);
+               }
+       }
+
+cleanup:
+       free(blockbuf);
+       blockbuf = NULL;
+       blockbuf_size = 0;
+
+       return command_ret;
+}
+
+#if 0
+               if (flags & V_FLAG)
+                       printf_P((PSTR("%s  %s -> %s\n", badcp ? : "ERR:" : "    ", curr->fts_path, to.p_path)));
+
+#endif
+
+
+/******************************************************************************/
+
+/*
+ * Work register for stat command
+ */
 struct stat_dat_s {
        DWORD AccSize;
        WORD  AccFiles, AccDirs;
@@ -155,24 +1180,24 @@ FRESULT scan_files (
  * fatstat path - Show logical drive status
  *
  */
-command_ret_t do_fat_stat(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+command_ret_t do_stat(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
 {
        FATFS *fs;
        DWORD nfreeclst;
        FRESULT res;
-       char *path;
+       char *buf;
+       char *path = "";
        struct stat_dat_s statp;
 
-       (void) cmdtp; (void) flag; (void) argc;
-
-       path = (char *) malloc(BUFFER_SIZE);
-       if (path == NULL) {
-               printf_P(PSTR("fatstat: Out of Memory!\n"));
-               free(path);
+       buf = (char *) malloc(BUFFER_SIZE);
+       if (buf == NULL) {
+               printf_P(PSTR("fat stat: Out of Memory!\n"));
                return CMD_RET_FAILURE;
        }
 
-       res = f_getfree(argv[1], &nfreeclst, &fs);
+       if (argc > 1)
+               path = argv[1];
+       res = f_getfree(path, &nfreeclst, &fs);
        if (!res) {
                printf_P(PSTR(
                                        "FAT type:                %u\n"
@@ -189,22 +1214,21 @@ command_ret_t do_fat_stat(cmd_tbl_t *cmdtp, int flag, int argc, char * const arg
                                fs->fatbase, fs->dirbase, fs->database);
 
 #if _USE_LABEL
-               TCHAR label[12];
                DWORD serial;
-               res = f_getlabel(argv[1], label, &serial);
+               res = f_getlabel(path, buf, &serial);
                if (!res) {
                        printf_P(PSTR(
                                                "Volume name:             %s\n"
                                                "Volume S/N:              %04X-%04X\n"),
-                                       label, (WORD)(serial >> 16), (WORD)(serial & 0xFFFF));
+                                       buf, (WORD)(serial >> 16), (WORD)(serial & 0xFFFF));
                }
 #endif
                if (!res) {
                        my_puts_P(PSTR("\nCounting...  "));
                        statp.AccSize = statp.AccFiles = statp.AccDirs = 0;
-                       strcpy(path, argv[1]);
+                       strcpy(buf, path);
 
-                       res = scan_files(path, &statp);
+                       res = scan_files(buf, &statp);
                }
                if (!res) {
                        printf_P(PSTR("\r%u files, %lu bytes.\n%u folders.\n"
@@ -215,108 +1239,20 @@ command_ret_t do_fat_stat(cmd_tbl_t *cmdtp, int flag, int argc, char * const arg
                }
        }
 
-       free(path);
-       if (res) {
-               put_rc(res);
-               return CMD_RET_FAILURE;
-       }
-       return CMD_RET_SUCCESS;
-}
-
-
-/*
- * fatls path - Directory listing
- *
- */
-command_ret_t do_fat_ls(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
-{
-       FATFS *fs;
-       DIR Dir;                                        /* Directory object */
-       FILINFO Finfo;
-       unsigned long p1;
-       unsigned int s1, s2;
-       FRESULT res;
-
-       (void) cmdtp; (void) flag; (void) argc;
-
-       res = f_opendir(&Dir, argv[1]);
-       if (res) {
-               put_rc(res);
-               return CMD_RET_FAILURE;
-       }
-
-       p1 = s1 = s2 = 0;
-       for(;;) {
-               res = f_readdir(&Dir, &Finfo);
-               if ((res != FR_OK) || !Finfo.fname[0])
-                       break;
-               if (Finfo.fattrib & AM_DIR) {
-                       s2++;
-               } else {
-                       s1++; p1 += Finfo.fsize;
-               }
-               printf_P(PSTR("%c%c%c%c%c %u/%02u/%02u %02u:%02u %9lu  %s\n"),
-                                       (Finfo.fattrib & AM_DIR) ? 'D' : '-',
-                                       (Finfo.fattrib & AM_RDO) ? 'R' : '-',
-                                       (Finfo.fattrib & AM_HID) ? 'H' : '-',
-                                       (Finfo.fattrib & AM_SYS) ? 'S' : '-',
-                                       (Finfo.fattrib & AM_ARC) ? 'A' : '-',
-                                       (Finfo.fdate >> 9) + 1980, (Finfo.fdate >> 5) & 15, Finfo.fdate & 31,
-                                       (Finfo.ftime >> 11), (Finfo.ftime >> 5) & 63,
-                                       Finfo.fsize, Finfo.fname);
-               if (check_abort())
-                       break;
-       }
-
-       if (res == FR_OK) {
-               printf_P(PSTR("%4u File(s),%10lu bytes total\n%4u Dir(s)"), s1, p1, s2);
-               if (f_getfree(argv[1], (DWORD*)&p1, &fs) == FR_OK)
-                       printf_P(PSTR(", %10luK bytes free\n"), p1 * fs->csize / 2);
-       }
-
+       free(buf);
        if (res) {
                put_rc(res);
                return CMD_RET_FAILURE;
        }
-
        return CMD_RET_SUCCESS;
 }
 
-static
-FRESULT mkpath(TCHAR *path)
-{
-       /* TODO: */
-       (void) path;
-#if 0
-       FILINFO fd
-       TCHAR *p, *q;
-       FRESULT ret;
-
-       res = f_stat (path, &fd)
-
-       p = strchr(path, ':');
-       if (p == NULL || *++p == '\0' || *p++ != '/')
-               return FR_OK;
-
-       while ((q = strchr(p, '/')) != NULL) {
-               *q = '\0';
-               ret = f_mkdir(path);
-               *q = '/';
-                       if (ret != FR_OK && ret != FR_EXIST)
-                               return ret;
-               p = q + 1;
-       }
-#endif
-
-       return FR_OK;
-}
-
 /*
  * fatread/write - load binary file to/from a dos filesystem
  *             read  <d:/path/filename> <addr> [bytes [pos]]
  *             write <d:/path/filename> <addr> <bytes>
  */
-command_ret_t do_fat_rw(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
+command_ret_t do_rw(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc, char * const argv[])
 {
        FIL File;
        uint32_t addr;
@@ -324,14 +1260,12 @@ command_ret_t do_fat_rw(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[
        unsigned long pos;
        unsigned long bytes_rw;
 
-       bool dowrite = (argv[0][3] == 'w');
+       bool dowrite = (argv[0][0] == 'w');
        FRESULT res = FR_OK;
        bool buserr = 0;
        uint32_t timer;
        uint8_t *buffer;
 
-       (void) cmdtp; (void) flag;
-
        if (argc < (dowrite ? 4 : 3))
                return CMD_RET_USAGE;
 
@@ -359,9 +1293,6 @@ command_ret_t do_fat_rw(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[
                return CMD_RET_FAILURE;
        }
 
-       if (dowrite) {
-               res = mkpath(argv[1]);
-       }
        if (!res) {
                res = f_open(&File, argv[1], dowrite ? FA_WRITE | FA_CREATE_ALWAYS
                                                                                         : FA_READ );
@@ -434,3 +1365,133 @@ command_ret_t do_fat_rw(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[
 
        return CMD_RET_SUCCESS;
 }
+
+/*
+ * command table for fat subcommands
+ */
+
+cmd_tbl_t cmd_tbl_fat[] = {
+CMD_TBL_ITEM(
+       stat,   2,      CTBL_RPT,       do_stat,
+       "Show logical drive status",
+       "dev"
+),
+CMD_TBL_ITEM(
+       pwd,    1,      CTBL_RPT,       do_pwd,
+       "Print name of current/working directory",
+       ""
+),
+CMD_TBL_ITEM(
+       attrib, CONFIG_SYS_MAXARGS,     0,                      do_attrib,
+    "Display or change attributes on a FAT filesystem",
+    "[+-ahrs] files...\n"
+    "\n"
+    "    -    Clear attributes\n"
+    "    +    Set attributes\n"
+    "    a    Archive\n"
+    "    h    Hidden\n"
+    "    r    Read only\n"
+    "    s    System\n"
+    "Display only:\n"
+    "    v    Volume label\n"
+    "    d    Directory\n"
+),
+CMD_TBL_ITEM(
+       cd,             2,      0,                      do_cd,
+       "Change the current/working directory.",
+       "path"
+),
+CMD_TBL_ITEM(
+       rm,             CONFIG_SYS_MAXARGS,     0,                      do_rm,
+       "Remove FILE(s)",
+       "[OPTION]... [FILE]...\n"
+       //"    -i prompt before removal\n"
+       "    -v explain what is being done\n"
+       "\n"
+       "rm does not remove directories."
+),
+CMD_TBL_ITEM(
+       rmdir,          CONFIG_SYS_MAXARGS,     0,                      do_rmdir,
+       "Remove the DIRECTORY(ies), if they are empty",
+       "[OPTION]... DIRECTORY..."
+),
+CMD_TBL_ITEM(
+       mkdir,          CONFIG_SYS_MAXARGS,     0,                      do_mkdir,
+       "Create the DIRECTORY(ies), if they do not already exist.",
+       "[OPTION]... DIRECTORY..."
+),
+CMD_TBL_ITEM(
+       ls,             2,      CTBL_RPT,       do_ls,
+       "Directory listing",
+       "path"
+),
+CMD_TBL_ITEM(
+       tst,    3,      CTBL_DBG|CTBL_RPT,      do_tst,
+       "FatFS test function",
+       "path"
+),
+CMD_TBL_ITEM(
+       load,   5,      0,                      do_rw,
+       "load binary file from a dos filesystem",
+       "<d:/path/filename> <addr> [bytes [pos]]\n"
+       "    - Load binary file 'path/filename' on logical drive 'd'\n"
+       "      to address 'addr' from dos filesystem.\n"
+       "      'pos' gives the file position to start loading from.\n"
+       "      If 'pos' is omitted, 0 is used. 'pos' requires 'bytes'.\n"
+       "      'bytes' gives the size to load. If 'bytes' is 0 or omitted,\n"
+       "      the load stops on end of file."
+),
+CMD_TBL_ITEM(
+       write,  4,      0,                      do_rw,
+       "write file into a dos filesystem",
+       "<d:/path/filename> <addr> <bytes>\n"
+       "    - Write file to 'path/filename' on logical drive 'd' from RAM\n"
+       "      starting at address 'addr'.\n"
+),
+
+CMD_TBL_ITEM(
+       cp,     CONFIG_SYS_MAXARGS,     CTBL_DBG,       do_cp,
+       "copy files",
+       "[-f | -i | -n] [-prv] source_file target_file\n"
+//     "[-f | -i | -n] [-prv] source_file target_file\n"
+//     "cp [-f | -i | -n] [-prv] source_file ... target_dir\n"
+       "    -f overwrite existing file ignoring write protection\n"
+       "       this option is ignored when the -n option is also used\n"
+       "    -i prompt before overwrite (overrides a previous -n option)\n"
+       "    -n do not overwrite an existing file (overrides a previous -i option)\n"
+       "    -p preserve attributes and timestamps\n"
+       "    -r copy directories recursively\n"
+       "    -v explain what is being done\n"
+),
+
+CMD_TBL_ITEM(
+       help,   CONFIG_SYS_MAXARGS,     CTBL_RPT,       do_help,
+       "Print sub command description/usage",
+       "\n"
+       "       - print brief description of all sub commands\n"
+       "fat help command ...\n"
+       "       - print detailed usage of sub cmd 'command'"
+),
+
+/* This does not use the CMD_TBL_ITEM macro as ? can't be used in symbol names */
+       {FSTR("?"),   CONFIG_SYS_MAXARGS, 1, do_help,
+        FSTR("Alias for 'help'"),
+#ifdef  CONFIG_SYS_LONGHELP
+       FSTR(""),
+#endif /* CONFIG_SYS_LONGHELP */
+       NULL,
+#ifdef CONFIG_AUTO_COMPLETE
+       NULL,
+#endif
+},
+/* Mark end of table */
+CMD_TBL_END(cmd_tbl_fat)
+};
+
+
+command_ret_t do_fat(cmd_tbl_t *cmdtp UNUSED, uint_fast8_t flag UNUSED, int argc UNUSED, char * const argv[] UNUSED)
+{
+       puts_P(PSTR("Huch?"));
+
+       return CMD_RET_USAGE;
+}