Modules/FAT - Slight cleanup
[tpg/acess2.git] / KernelLand / Modules / Filesystems / FAT / dir.c
index f639a0b..f5445fd 100644 (file)
@@ -5,14 +5,14 @@
  * dir.c
  * - Directory access/manipulation code
  */
-#define DEBUG  1
+#define DEBUG  0
 #include <acess.h>
 #include <vfs.h>
 #include "common.h"
 
 // === PROTOTYPES ===
 void   FAT_int_ProperFilename(char *dest, const char *src);
-char   *FAT_int_CreateName(fat_filetable *ft, const Uint16 *LongFileName);
+ int   FAT_int_CreateName(fat_filetable *ft, const Uint16 *LongFileName, char *Dest);
  int   FAT_int_ConvertUTF16_to_UTF8(Uint8 *Dest, const Uint16 *Source);
  int   FAT_int_ConvertUTF8_to_UTF16(Uint16 *Dest, const Uint8 *Source);
 
@@ -26,11 +26,11 @@ char        *FAT_int_CreateName(fat_filetable *ft, const Uint16 *LongFileName);
 Uint16 *FAT_int_GetLFN(tVFS_Node *Node, int ID);
 void   FAT_int_DelLFN(tVFS_Node *Node, int ID);
 #endif
-char   *FAT_ReadDir(tVFS_Node *Node, int ID);
-tVFS_Node      *FAT_FindDir(tVFS_Node *Node, const char *Name);
+ int   FAT_ReadDir(tVFS_Node *Node, int ID, char Dest[FILENAME_MAX]);
+tVFS_Node      *FAT_FindDir(tVFS_Node *Node, const char *Name, Uint Flags);
 tVFS_Node      *FAT_GetNodeFromINode(tVFS_Node *Root, Uint64 Inode);
 #if SUPPORT_WRITE
- int   FAT_Mknod(tVFS_Node *Node, const char *Name, Uint Flags);
+tVFS_Node      *FAT_Mknod(tVFS_Node *Node, const char *Name, Uint Flags);
  int   FAT_int_IsValid83Filename(const char *Name);
  int   FAT_Link(tVFS_Node *DirNode, const char *NewName, tVFS_Node *Node);
  int   FAT_Relink(tVFS_Node *node, const char *OldName, const char *NewName);
@@ -75,32 +75,28 @@ void FAT_int_ProperFilename(char *dest, const char *src)
  * \param LongFileName Long file name pointer
  * \return Filename as a heap string
  */
-char *FAT_int_CreateName(fat_filetable *ft, const Uint16 *LongFileName)
+int FAT_int_CreateName(fat_filetable *ft, const Uint16 *LongFileName, char *Dest)
 {
-       char    *ret;
        ENTER("pft sLongFileName", ft, LongFileName);
-       //Log_Debug("FAT", "FAT_int_CreateName(ft=%p, LongFileName=%p'%s')", ft, LongFileName);
        #if USE_LFN
        if(LongFileName && LongFileName[0] != 0)
        {
                 int    len = FAT_int_ConvertUTF16_to_UTF8(NULL, LongFileName);
-               ret = malloc( len + 1 );
-               FAT_int_ConvertUTF16_to_UTF8((Uint8*)ret, LongFileName);
+               if( len > FILENAME_MAX ) {
+                       LEAVE('i', -1);
+                       return -1;
+               }
+               FAT_int_ConvertUTF16_to_UTF8((Uint8*)Dest, LongFileName);
        }
        else
        {
        #endif
-               ret = (char*) malloc(13);
-               if( !ret ) {
-                       Log_Warning("FAT", "FAT_int_CreateName: malloc(13) failed");
-                       return NULL;
-               }
-               FAT_int_ProperFilename(ret, ft->name);
+               FAT_int_ProperFilename(Dest, ft->name);
        #if USE_LFN
        }
        #endif
-       LEAVE('s', ret);
-       return ret;
+       LEAVE('i', 0);
+       return 0;
 }
 
 #if USE_LFN
@@ -114,6 +110,7 @@ int FAT_int_CompareUTF16_UTF8(const Uint16 *Str16, const char *Str8)
                Uint32  cp8, cp16;
                if( Str16[pos16] & 0x8000 ) {
                        // Do something!
+                       cp16 = 0;
                }
                else {
                        cp16 = Str16[pos16];
@@ -154,7 +151,7 @@ int FAT_int_ConvertUTF16_to_UTF8(Uint8 *Dest, const Uint16 *Source)
 int FAT_int_ConvertUTF8_to_UTF16(Uint16 *Dest, const Uint8 *Source)
 {
         int    len = 0;
-       for( ; *Source; Source ++ )
+       while( *Source )
        {
                Uint32  cp;
                int cpl;
@@ -211,6 +208,8 @@ int FAT_int_GetEntryByName(tVFS_Node *DirNode, const char *Name, fat_filetable *
         int    lfnId = -1;
        #endif
 
+       ENTER("pDirNode sName pEntry", DirNode, Name, Entry);
+
        for( int i = 0; ; i++ )
        {
                if((i & 0xF) == 0) {
@@ -281,7 +280,10 @@ int FAT_int_GetEntryByCluster(tVFS_Node *DirNode, Uint32 Cluster, fat_filetable
        fat_filetable   fileinfo[ents_per_sector];
         int    i, sector;
 
-       Mutex_Acquire(&DirNode->Lock);
+       if( Mutex_Acquire(&DirNode->Lock) ) {
+               return -EINTR;
+       }
+       
        sector = 0;
        for( i = 0; ; i ++ )
        {
@@ -302,7 +304,7 @@ int FAT_int_GetEntryByCluster(tVFS_Node *DirNode, Uint32 Cluster, fat_filetable
                
                if(fileinfo[i].attrib == ATTR_LFN)      continue;
 
-               LOG("fileinfo[i].cluster = %x %04x", fileinfo[i].clusterHi, fileinfo[i].cluster);
+               LOG("fileinfo[i].cluster = %x:%04x", fileinfo[i].clusterHi, fileinfo[i].cluster);
                #if DEBUG
                {
                        char    tmpName[13];
@@ -321,7 +323,7 @@ int FAT_int_GetEntryByCluster(tVFS_Node *DirNode, Uint32 Cluster, fat_filetable
        }
        
        Mutex_Release(&DirNode->Lock);
-       return -1;
+       return -ENOENT;
 }
 
 /* 
@@ -363,6 +365,37 @@ int FAT_int_ReadDirSector(tVFS_Node *Node, int Sector, fat_filetable *Buffer)
 }
 
 #if SUPPORT_WRITE
+/**
+ * \brief Write a sector to the disk
+ * \param Node Directory node to write
+ * \param Sector       Sector number in the directory to write
+ * \param Buffer       Source data
+ */
+int FAT_int_WriteDirSector(tVFS_Node *Node, int Sector, const fat_filetable *Buffer)
+{
+       Uint64  addr;
+       tFAT_VolInfo    *disk = Node->ImplPtr;
+       
+       ENTER("pNode iSector pEntry", Node, Sector, Buffer);
+       
+       // Parse address
+       if(FAT_int_GetAddress(Node, Sector * 512, &addr, NULL))
+       {
+               LEAVE('i', 1);
+               return 1;
+       }
+       
+       // Read Sector
+       if(VFS_WriteAt(disk->fileHandle, addr, 512, Buffer) != 512)
+       {
+               LEAVE('i', 1);
+               return 1;
+       }
+       
+       LEAVE('i', 0);
+       return 0;
+}
+
 /**
  * \brief Writes an entry to the disk
  * \todo Support expanding a directory
@@ -396,8 +429,8 @@ int FAT_int_WriteDirEntry(tVFS_Node *Node, int ID, fat_filetable *Entry)
 
        LOG("addr = 0x%llx", addr);
        
-       // Read Sector
-       VFS_WriteAt(disk->fileHandle, addr, sizeof(fat_filetable), Entry);      // Read Dir Data
+       // Wriet data to disk
+       VFS_WriteAt(disk->fileHandle, addr, sizeof(fat_filetable), Entry);
        
        LEAVE('i', 0);
        return 0;
@@ -414,13 +447,12 @@ int FAT_int_WriteDirEntry(tVFS_Node *Node, int ID, fat_filetable *Entry)
  */
 Uint16 *FAT_int_GetLFN(tVFS_Node *Node, int ID)
 {
-       tFAT_LFNCache   *cache;
-        int    i, firstFree;
-       
-       Mutex_Acquire( &Node->Lock );
+       if( Mutex_Acquire( &Node->Lock ) ) {
+               return NULL;
+       }
        
        // TODO: Thread Safety (Lock things)
-       cache = Node->Data;
+       tFAT_LFNCache   *cache = Node->Data;
        
        // Create a cache if it isn't there
        if(!cache) {
@@ -434,8 +466,8 @@ Uint16 *FAT_int_GetLFN(tVFS_Node *Node, int ID)
        }
        
        // Scan for this entry
-       firstFree = -1;
-       for( i = 0; i < cache->NumEntries; i++ )
+       int firstFree = -1;
+       for( int i = 0; i < cache->NumEntries; i++ )
        {
                if( cache->Entries[i].ID == ID ) {
                        Mutex_Release( &Node->Lock );
@@ -446,31 +478,35 @@ Uint16 *FAT_int_GetLFN(tVFS_Node *Node, int ID)
                        firstFree = i;
        }
        
-       if(firstFree == -1) {
-               // Use `i` for temp length
-               i = sizeof(tFAT_LFNCache) + (cache->NumEntries+1)*sizeof(tFAT_LFNCacheEnt);
-               Node->Data = realloc( Node->Data, i );
-               if( !Node->Data ) {
-                       Log_Error("FAT", "realloc() fail, unable to allocate %i for LFN cache", i);
+        int    cache_entry = firstFree;
+       
+       if(firstFree == -1)
+       {
+               size_t newsize = offsetof(tFAT_LFNCache, Entries[cache->NumEntries+1]);
+               tFAT_LFNCache *new_alloc = realloc( Node->Data, newsize );
+               if( !new_alloc ) {
+                       Log_Error("FAT", "realloc() fail, unable to allocate %zi for LFN cache", newsize);
                        Mutex_Release( &Node->Lock );
                        return NULL;
                }
+               Node->Data = new_alloc;
                //Log_Debug("FAT", "Realloc (%i)\n", i);
                cache = Node->Data;
-               i = cache->NumEntries;
+               cache_entry = cache->NumEntries;
                cache->NumEntries ++;
        }
-       else {
-               i = firstFree;
+       else
+       {
+               cache_entry = firstFree;
        }
        
        // Create new entry
-       cache->Entries[ i ].ID = ID;
-       cache->Entries[ i ].Data[0] = '\0';
+       cache->Entries[ cache_entry ].ID = ID;
+       cache->Entries[ cache_entry ].Data[0] = '\0';
        
        Mutex_Release( &Node->Lock );
        //Log_Debug("FAT", "Return = %p (firstFree, i = %i)", cache->Entries[i].Data, i);
-       return cache->Entries[ i ].Data;
+       return cache->Entries[ cache_entry ].Data;
 }
 
 /**
@@ -503,11 +539,10 @@ void FAT_int_DelLFN(tVFS_Node *Node, int ID)
  * \param ID   Directory position
  * \return Filename as a heap string, NULL or VFS_SKIP
  */
-char *FAT_ReadDir(tVFS_Node *Node, int ID)
+int FAT_ReadDir(tVFS_Node *Node, int ID, char Dest[FILENAME_MAX])
 {
        fat_filetable   fileinfo[16];   // sizeof(fat_filetable)=32, so 16 per sector
         int    a;
-       char    *ret;
        #if USE_LFN
        Uint16  *lfn = NULL;
        #endif
@@ -517,8 +552,8 @@ char *FAT_ReadDir(tVFS_Node *Node, int ID)
        if(FAT_int_ReadDirSector(Node, ID/16, fileinfo))
        {
                LOG("End of chain, end of dir");
-               LEAVE('n');
-               return NULL;
+               LEAVE('i', -EIO);
+               return -EIO;
        }
        
        // Offset in sector
@@ -530,20 +565,14 @@ char *FAT_ReadDir(tVFS_Node *Node, int ID)
        if( fileinfo[a].name[0] == '\0' ) {
                Node->Size = ID;
                LOG("End of list");
-               LEAVE('n');
-               return NULL;    // break
+               LEAVE('i', -ENOENT);
+               return -ENOENT; // break
        }
        
        // Check for empty entry
        if( (Uint8)fileinfo[a].name[0] == 0xE5 ) {
                LOG("Empty Entry");
-               #if 0   // Stop on empty entry?
-               LEAVE('n');
-               return NULL;    // Stop
-               #else
-               LEAVE('p', VFS_SKIP);
-               return VFS_SKIP;        // Skip
-               #endif
+               LEAVE_RET('i', 1);      // Skip
        }
        
        #if USE_LFN
@@ -561,31 +590,24 @@ char *FAT_ReadDir(tVFS_Node *Node, int ID)
                a = FAT_int_ParseLFN(&fileinfo[a], lfn);
                if( a < 0 ) {
                        LOG("Invalid LFN, error");
-                       LEAVE('n');
-                       return NULL;
+                       LEAVE_RET('i', -EIO);
                }
 
-//             LOG("lfn = '%s'", lfn);
-               //Log_Debug("FAT", "lfn = '%s'", lfn);
-               LEAVE('p', VFS_SKIP);
-               return VFS_SKIP;
+               LEAVE_RET('i', 1);      // Skip
        }
        #endif
        
        // Check if it is a volume entry
        if(fileinfo[a].attrib & 0x08) {
-               LEAVE('p', VFS_SKIP);
-               return VFS_SKIP;
+               LEAVE_RET('i', 1);      // Skip
        }
        // Ignore .
        if(fileinfo[a].name[0] == '.' && fileinfo[a].name[1] == ' ') {
-               LEAVE('p', VFS_SKIP);
-               return VFS_SKIP;
+               LEAVE_RET('i', 1);      // Skip
        }
        // and ..
        if(fileinfo[a].name[0] == '.' && fileinfo[a].name[1] == '.' && fileinfo[a].name[2] == ' ') {
-               LEAVE('p', VFS_SKIP);
-               return VFS_SKIP;
+               LEAVE_RET('i', 1);      // Skip
        }
        
        LOG("name='%c%c%c%c%c%c%c%c.%c%c%c'",
@@ -596,20 +618,20 @@ char *FAT_ReadDir(tVFS_Node *Node, int ID)
        #if USE_LFN
        lfn = FAT_int_GetLFN(Node, ID);
        //Log_Debug("FAT", "lfn = %p'%s'", lfn, lfn);
-       ret = FAT_int_CreateName(&fileinfo[a], lfn);
+       FAT_int_CreateName(&fileinfo[a], lfn, Dest);
        #else
-       ret = FAT_int_CreateName(&fileinfo[a], NULL);
+       FAT_int_CreateName(&fileinfo[a], NULL, Dest);
        #endif
        
-       LEAVE('s', ret);
-       return ret;
+       LEAVE('i', 0);
+       return 0;
 }
 
 /**
  * \fn tVFS_Node *FAT_FindDir(tVFS_Node *node, char *name)
  * \brief Finds an entry in the current directory
  */
-tVFS_Node *FAT_FindDir(tVFS_Node *Node, const char *Name)
+tVFS_Node *FAT_FindDir(tVFS_Node *Node, const char *Name, Uint Flags)
 {
        fat_filetable   fileent;
        
@@ -645,6 +667,7 @@ tVFS_Node *FAT_GetNodeFromINode(tVFS_Node *Root, Uint64 Inode)
        if( ret ) {
                if( (ret->Inode >> 32) != 0 ) {
                        LOG("Node in cache, quick return");
+                       LEAVE('p', ret);
                        return ret;
                }
                else {
@@ -671,12 +694,14 @@ tVFS_Node *FAT_GetNodeFromINode(tVFS_Node *Root, Uint64 Inode)
 /**
  * \brief Create a new node
  */
-int FAT_Mknod(tVFS_Node *DirNode, const char *Name, Uint Flags)
+tVFS_Node *FAT_Mknod(tVFS_Node *DirNode, const char *Name, Uint Flags)
 {
        tFAT_VolInfo    *disk = DirNode->ImplPtr;
         int    rv;
        fat_filetable   ft;
        memset(&ft, 0, sizeof(ft));
+
+       ENTER("pDirNode sName xFlags", DirNode, Name, Flags);
        
        // Allocate a cluster
        Uint32 cluster = FAT_int_AllocateCluster(disk, -1);
@@ -693,17 +718,17 @@ int FAT_Mknod(tVFS_Node *DirNode, const char *Name, Uint Flags)
        
        tVFS_Node *newnode = FAT_int_CreateNode(DirNode, &ft);
        if( !newnode ) {
-               return -1;
+               errno = -EINTERNAL;
+               return NULL;
        }
        LOG("newnode = %p", newnode);
 
        // Call link
        if( (rv = FAT_Link(DirNode, Name, newnode)) ) {
-               newnode->Flags |= FAT_FLAG_DELETE;
+               newnode->ImplInt |= FAT_FLAG_DELETE;
        }
-       LOG("rv = %i", rv);
-       FAT_CloseFile(newnode);
-       return rv;
+       LEAVE('p', newnode);
+       return newnode;
 }
 
 /**
@@ -715,15 +740,36 @@ static inline int is_valid_83_char(char ch)
                return 1;
        if( 'A' <= ch && ch <= 'Z' )
                return 1;
+       if( 'a' <= ch && ch <= 'z' )
+               return 1;
+       if( strchr("$%'-_@~`#!(){}^#&", ch) )
+               return 1;
+       if( ch > 128 )
+               return 1;
        return 0;
 }
 
+Uint8 FAT_int_UnicodeTo83(Uint32 Input)
+{
+       Input = toupper(Input);
+       // Input = unicode_to_oem(Input);
+       if( Input > 256 )
+               Input = '_';
+       if(!is_valid_83_char(Input))
+               Input = '_';
+       return Input;
+}
+
 /**
  * \brief Internal - Determines if a filename is a valid 8.3 filename
  */
 int FAT_int_IsValid83Filename(const char *Name)
 {
         int    i, j;
+
+       if( !Name[0] || Name[0] == '.' )
+               return 0;
+
        // Check filename portion
        for( i = 0; Name[i] && i < 8; i ++ )
        {
@@ -744,12 +790,24 @@ int FAT_int_IsValid83Filename(const char *Name)
        }
        
        // After the extension must be the end
-       if( !Name[i+j] )
+       if( Name[i+j] )
                return 0;
        
        return 1;
 }
 
+Uint8 FAT_int_MakeLFNChecksum(const char *ShortName)
+{
+       Uint8 ret = 0;
+       for( int i = 0; i < 11; i++ )
+       {
+               // ret = (ret >>> 1) + ShortName[i]
+               // where >>> is rotate right
+               ret = ((ret & 1) ? 0x80 : 0x00) + (ret >> 1) + ShortName[i];
+       }
+       return ret;
+}
+
 /**
  * \brief Create a new name for a file
  * \note Since FAT doesn't support reference counting, this will cause double-references if
@@ -760,37 +818,284 @@ int FAT_Link(tVFS_Node *DirNode, const char *NewName, tVFS_Node *NewNode)
        Uint16  lfn[256];
        fat_filetable   ft;
         int    nLFNEnt = 0;
+       const int eps = 512 / sizeof(fat_filetable);
+       fat_filetable   fileinfo[eps];
+       
+       if( Mutex_Acquire( &DirNode->Lock ) ) {
+               return EINTR;
+       }
+
+       // -- Ensure duplicates aren't created --
+       if( FAT_int_GetEntryByName(DirNode, NewName, &ft) >= 0 ) {
+               Mutex_Release( &DirNode->Lock );
+               return EEXIST;
+       }
        
        // -- Create filetable entry --
+       #if 0
+       {
+                int    bDirty = 0;
+                int    inofs = 0;
+               while( NewName[inofs] && NewName[inofs] == '.' )
+                       inofs ++, bDirty = 1;
+               for( int i = 0; i < 8 && NewName[inofs] && NewName[inofs] != '.'; i ++ )
+               {
+                       Uint32  cp;
+                       inofs += ReadUTF8(NewName + inofs, &cp);
+                       // Spaces are silently skipped
+                       if(isspace(cp)) {
+                               i --, bDirty = 1;
+                               continue ;
+                       }
+                       ft.name[i] = FAT_int_UnicodeTo83(cp);
+                       if(ft.name[i] != cp)
+                               bDirty = 1;
+               }
+               while( NewName[inofs] && NewName[inofs] != '.' )
+                       inofs ++, bDirty = 1;
+               for( ; i < 8+3 && NewName[inofs]; i ++ )
+               {
+                       Uint32  cp;
+                       inofs += ReadUTF8(NewName + inofs, &cp);
+                       // Spaces are silently skipped
+                       if(isspace(cp)) {
+                               i --, bDirty = 1;
+                               continue ;
+                       }
+                       ft.name[i] = FAT_int_UnicodeTo83(cp);
+                       if(ft.name[i] != cp)
+                               bDirty = 1;
+               }
+               if( !NewName[inofs] )   bDirty = 1;
+               
+               if( bDirty )
+               {
+                       int lfnlen = FAT_int_ConvertUTF8_to_UTF16(lfn, (const Uint8*)NewName);
+                       lfn[lfnlen] = 0;
+                       nLFNEnt = DivUp(lfnlen, 13);
+               }
+       }
+       #endif
         int    bNeedsLFN = !FAT_int_IsValid83Filename(NewName);
        if( bNeedsLFN )
        {
                int lfnlen = FAT_int_ConvertUTF8_to_UTF16(lfn, (const Uint8*)NewName);
+               lfn[lfnlen] = 0;
                nLFNEnt = DivUp(lfnlen, 13);
        
-               // Create mangled filetable entry
-               // - Requires checking for duplicates
-               Log_Warning("FAT", "FAT_Link - LFN Mangling unimplimented");
+               // Create a base mangled filetable entry
+               int i, j = 0;
+               while(NewName[j] == '.')        j ++;   // Eat leading dots
+               for( i = 0; i < 6 && NewName[j] && NewName[j] != '.'; i ++, j ++ )
+               {
+                       if( !isalpha(NewName[j]) && !is_valid_83_char(NewName[j]) )
+                               ft.name[i] = '_';
+                       else
+                               ft.name[i] = toupper(NewName[j]);
+               }
+               ft.name[i++] = '~';
+               ft.name[i++] = '1';
+               while(i < 8)    ft.name[i++] = ' ';
+               while(NewName[j] && NewName[j] != '.')  j ++;
+               for( ; i < 8+3 && NewName[j]; i ++, j ++ )
+               {
+                       if( NewName[j] == '.' )
+                               i --;
+                       else if( !is_valid_83_char(NewName[j]) )
+                               ft.name[i] = '_';
+                       else
+                               ft.name[i] = toupper(NewName[j]);
+               }
+               while(i < 8+3)  ft.name[i++] = ' ';
+               
+               // - Ensure there isn't a duplicate short-name
+                int    bIsDuplicate = 1;
+               while( bIsDuplicate )
+               {
+                       bIsDuplicate = 0;       // Assume none                  
+
+                       // Scan directory
+                       for( int id = 0; ; id ++ )
+                       {
+                               if( id % eps == 0 )
+                               {
+                                       if(FAT_int_ReadDirSector(DirNode, id/eps, fileinfo))
+                                               break;  // end of cluster chain
+                               }
+                               
+                               // End of file list
+                               if( fileinfo[id%eps].name[0] == '\0' )  break;
+                               // Empty entry
+                               if( fileinfo[id%eps].name[0] == '\xE5' )        continue;
+                               // LFN entry
+                               if( fileinfo[id%eps].attrib == ATTR_LFN )       continue;
+                               
+                               // Is this a duplicate?
+                               if( memcmp(ft.name, fileinfo[id%eps].name, 8+3) == 0 ) {
+                                       bIsDuplicate = 1;
+                                       break;
+                               }
+                               
+                               // No - move a long
+                       }
+                       
+                       // If a duplicate was found, increment the suffix
+                       if( bIsDuplicate )
+                       {
+                               if( ft.name[7] == '9' ) {
+                                       // TODO: Expand into ~00
+                                       Log_Error("FAT", "TODO: Use two digit LFN suffixes");
+                                       Mutex_Release(&DirNode->Lock);
+                                       return ENOTIMPL;
+                               }
+                               
+                               ft.name[7] += 1;
+                       }
+               }
        }
        else
        {
                // Create pure filetable entry
-               Log_Warning("FAT", "FAT_Link - Filename translation unimplimented");
+                int    i;
+               // - Copy filename
+               for( i = 0; i < 8 && *NewName && *NewName != '.'; i ++, NewName++ )
+                       ft.name[i] = *NewName;
+               // - Pad with spaces
+               for( ; i < 8; i ++ )
+                       ft.name[i] = ' ';
+               // - Eat '.'
+               if(*NewName)
+                       NewName ++;
+               // - Copy extension
+               for( ; i < 8+3 && *NewName; i ++, NewName++ )
+                       ft.name[i] = *NewName;
+               // - Pad with spaces
+               for( ; i < 8+3; i ++ )
+                       ft.name[i] = ' ';
        }
-       
-       ft.size = NewNode->Size;
 
-       // -- Add entry to the directory --
-       Mutex_Acquire( &DirNode->Lock );
+       ft.attrib = 0;
+       if(NewNode->Flags & VFS_FFLAG_DIRECTORY )
+               ft.attrib |= ATTR_DIRECTORY;    
+       ft.ntres     = 0;
+       FAT_int_GetFATTimestamp(NewNode->CTime, &ft.cdate, &ft.ctime, &ft.ctimems);
+//     ft.ctimems   = ft.ctimems;
+       ft.ctime     = LittleEndian16(ft.ctime);
+       ft.cdate     = LittleEndian16(ft.cdate);
+       FAT_int_GetFATTimestamp(NewNode->MTime, &ft.mdate, &ft.mtime, NULL);
+       ft.mtime     = LittleEndian16(ft.mtime);
+       ft.mdate     = LittleEndian16(ft.mdate);
+       FAT_int_GetFATTimestamp(NewNode->ATime, &ft.adate, NULL, NULL);
+       ft.adate     = LittleEndian16(ft.adate);
+       ft.clusterHi = LittleEndian16((NewNode->Inode >> 16) & 0xFFFF);
+       ft.cluster   = LittleEndian16(NewNode->Inode & 0xFFFF);
+       ft.size      = LittleEndian32(NewNode->Size);
+
+       LOG("ft.name = '%.11s'", ft.name);
 
+       // -- Add entry to the directory --
        // Locate a range of nLFNEnt + 1 free entries
-       // - If there are none, defragment the directory?
-       // - Else, expand the directory
-       // - and if that fails, return an error
-       Log_Warning("FAT", "FAT_Link - Free entry scanning unimplimented");
+        int    end_id = -1;
+        int    range_first = 0, range_last = -1;
+       for( int id = 0; ; id ++ )
+       {
+               if( id % eps == 0 )
+               {
+                       if(FAT_int_ReadDirSector(DirNode, id/eps, fileinfo))
+                               break;  // end of cluster chain
+               }
+               
+               // End of file list, break out
+               if( fileinfo[id%eps].name[0] == '\0' ) {
+                       if( id - range_first == nLFNEnt )
+                               range_last = id;
+                       end_id = id;
+                       break;
+               }
+               
+               // If an entry is occupied, clear the range
+               if( fileinfo[id%eps].name[0] != '\xE5' ) {
+                       range_first = id + 1;
+                       continue ;
+               }
+               
+               // Free entry, check if we have enough
+               if( id - range_first == nLFNEnt ) {
+                       range_last = id;
+                       break;
+               }
+               // Check the next one
+       }
+       if( range_last == -1 )
+       {
+               // - If there are none, defragment the directory?
+               
+               // - Else, expand the directory
+               if( end_id == -1 ) {
+                       // End of cluster chain
+               }
+               else {
+                       // Just end of block
+               }
+               // - and if that fails, return an error
+               Log_Warning("FAT", "TODO: Impliment directory expansion / defragmenting");
+               Mutex_Release(&DirNode->Lock);
+               return ENOTIMPL;
+       }
+
+       // Calculate the checksum used for LFN
+       Uint8   lfn_checksum = 0;
+       if( nLFNEnt )
+       {
+               lfn_checksum = FAT_int_MakeLFNChecksum(ft.name);
+       }
+
+       // Insert entries       
+       if( range_first % eps != 0 )
+               FAT_int_ReadDirSector(DirNode, range_first/eps, fileinfo);
+       for( int id = range_first; id <= range_last; id ++ )
+       {
+               if( id % eps == 0 ) {
+                       if( id != range_first )
+                               FAT_int_WriteDirSector(DirNode, (id-1)/eps, fileinfo);
+                       FAT_int_ReadDirSector(DirNode, id/eps, fileinfo);
+               }
+               
+               if( id == range_last ) {
+                       // Actual entry
+                       memcpy(fileinfo + id % eps, &ft, sizeof(fat_filetable));
+               }
+               else {
+                       // Long filename
+                       int lfnid = (nLFNEnt - (id - range_first));
+                       int ofs = (lfnid-1) * 13;
+                        int    i=0, j=0;
+                       fat_longfilename *lfnent = (void*)( fileinfo + id%eps );
+                       
+                       lfnent->id = 0x40 | lfnid;
+                       lfnent->attrib = ATTR_LFN;
+                       lfnent->type = 0;
+                       lfnent->firstCluster = 0;
+                       lfnent->checksum = lfn_checksum;        // ???
+
+                       for( i = 0; i < 13; i ++ )
+                       {
+                               Uint16  wd;
+                               if( (wd = lfn[ofs+j]) ) j ++;
+                               wd = LittleEndian16(wd);
+                               if(i < 5)
+                                       lfnent->name1[i    ] = wd;
+                               else if( i < 5+6 )
+                                       lfnent->name2[i-5  ] = wd;
+                               else
+                                       lfnent->name3[i-5-6] = wd;
+                       }
+               }
+       }
+       FAT_int_WriteDirSector(DirNode, range_last/eps, fileinfo);
 
        Mutex_Release( &DirNode->Lock );
-       return ENOTIMPL;
+       return 0;
 }
 
 /**
@@ -802,7 +1107,9 @@ int FAT_Unlink(tVFS_Node *Node, const char *OldName)
        tVFS_Node       *child;
        fat_filetable   ft;
        
-       Mutex_Acquire(&Node->Lock);
+       if( Mutex_Acquire(&Node->Lock) ) {
+               return EINTR;
+       }
 
        int id = FAT_int_GetEntryByName(Node, OldName, &ft);
        if(id == -1) {
@@ -820,7 +1127,7 @@ int FAT_Unlink(tVFS_Node *Node, const char *OldName)
        // TODO: If it has a LFN, remove that too
 
        // Delete from the directory
-       ft.name[0] = '\xE9';
+       ft.name[0] = '\xE5';
        FAT_int_WriteDirEntry(Node, id, &ft);
 
        // Close child

UCC git Repository :: git.ucc.asn.au