fs/fat: fix case for FAT shortnames

Noticed when comparing our output to linux.  There are some lcase bits
which control whether filename and/or extension should be downcase'd.

Signed-off-by: Rob Clark <robdclark@gmail.com>
Reviewed-by: Ɓukasz Majewski <lukma@denx.de>
Reviewed-by: Simon Glass <sjg@chromium.org>
diff --git a/fs/fat/fat.c b/fs/fat/fat.c
index c951d84..65873a2 100644
--- a/fs/fat/fat.c
+++ b/fs/fat/fat.c
@@ -29,11 +29,13 @@
 #endif
 
 /*
- * Convert a string to lowercase.
+ * Convert a string to lowercase.  Converts at most 'len' characters,
+ * 'len' may be larger than the length of 'str' if 'str' is NULL
+ * terminated.
  */
-static void downcase(char *str)
+static void downcase(char *str, size_t len)
 {
-	while (*str != '\0') {
+	while (*str != '\0' && len--) {
 		*str = tolower(*str);
 		str++;
 	}
@@ -131,10 +133,13 @@
 	ptr = s_name;
 	while (*ptr && *ptr != ' ')
 		ptr++;
+	if (dirent->lcase & CASE_LOWER_BASE)
+		downcase(s_name, (unsigned)(ptr - s_name));
 	if (dirent->ext[0] && dirent->ext[0] != ' ') {
-		*ptr = '.';
-		ptr++;
+		*ptr++ = '.';
 		memcpy(ptr, dirent->ext, 3);
+		if (dirent->lcase & CASE_LOWER_EXT)
+			downcase(ptr, 3);
 		ptr[3] = '\0';
 		while (*ptr && *ptr != ' ')
 			ptr++;
@@ -144,7 +149,6 @@
 		*s_name = '\0';
 	else if (*s_name == aRING)
 		*s_name = DELETED_FLAG;
-	downcase(s_name);
 }
 
 static int flush_dirty_fat_buffer(fsdata *mydata);
diff --git a/fs/fat/fat_write.c b/fs/fat/fat_write.c
index 4ca024c..d0468ba 100644
--- a/fs/fat/fat_write.c
+++ b/fs/fat/fat_write.c
@@ -345,7 +345,7 @@
 		*l_name = '\0';
 	else if (*l_name == aRING)
 		*l_name = DELETED_FLAG;
-	downcase(l_name);
+	downcase(l_name, INT_MAX);
 
 	/* Return the real directory entry */
 	*retdent = realdent;
@@ -981,7 +981,7 @@
 
 	memcpy(l_filename, filename, name_len);
 	l_filename[name_len] = 0; /* terminate the string */
-	downcase(l_filename);
+	downcase(l_filename, INT_MAX);
 
 	startsect = mydata->rootdir_sect;
 	retdent = find_directory_entry(mydata, startsect,