ef347ad075c8d176d3736f3e13215506dda582e8
[tpg/acess2.git] / KernelLand / Modules / Filesystems / Ext2 / dir.c
1 /*
2  * Acess2 Ext2 Driver
3  * - By John Hodge (thePowersGang)
4  *
5  * dir.c
6  * - Directory Handling
7  */
8 #define DEBUG   0
9 #define VERBOSE 0
10 #include "ext2_common.h"
11
12 // === MACROS ===
13 #define BLOCK_DIR_OFS(_data, _block)    (((Uint16*)(_data))[(_block)])
14
15 // === PROTOTYPES ===
16 char    *Ext2_ReadDir(tVFS_Node *Node, int Pos);
17 tVFS_Node       *Ext2_FindDir(tVFS_Node *Node, const char *FileName);
18  int    Ext2_MkNod(tVFS_Node *Node, const char *Name, Uint Flags);
19  int    Ext2_Unlink(tVFS_Node *Node, const char *OldName);
20  int    Ext2_Link(tVFS_Node *Parent, const char *Name, tVFS_Node *Node);
21 // --- Helpers ---
22 tVFS_Node       *Ext2_int_CreateNode(tExt2_Disk *Disk, Uint InodeId);
23
24 // === GLOBALS ===
25 tVFS_NodeType   gExt2_DirType = {
26         .TypeName = "ext2-dir",
27         .ReadDir = Ext2_ReadDir,
28         .FindDir = Ext2_FindDir,
29         .MkNod = Ext2_MkNod,
30         .Unlink = Ext2_Unlink,
31         .Link = Ext2_Link,
32         .Close = Ext2_CloseFile
33         };
34 tVFS_NodeType   gExt2_FileType = {
35         .TypeName = "ext2-file",
36         .Read = Ext2_Read,
37         .Write = Ext2_Write,
38         .Close = Ext2_CloseFile
39         };
40
41 // === CODE ===
42 /**
43  * \brief Reads a directory entry
44  * \param Node  Directory node
45  * \param Pos   Position of desired element
46  */
47 char *Ext2_ReadDir(tVFS_Node *Node, int Pos)
48 {
49         tExt2_Inode     inode;
50         tExt2_DirEnt    dirent;
51         Uint64  Base;   // Block's Base Address
52          int    block = 0;
53         Uint    ofs = 0;
54          int    entNum = 0;
55         tExt2_Disk      *disk = Node->ImplPtr;
56         Uint    size;
57         
58         ENTER("pNode iPos", Node, Pos);
59         
60         // Read directory's inode
61         Ext2_int_ReadInode(disk, Node->Inode, &inode);
62         size = inode.i_size;
63         
64         LOG("inode={.i_block[0]= 0x%x, .i_size=0x%x}", inode.i_block[0], inode.i_size);
65         
66         // Find Entry
67         // Get First Block
68         // - Do this ourselves as it is a simple operation
69         Base = inode.i_block[0] * disk->BlockSize;
70         // Scan directory
71         while(Pos -- && size > 0 && size <= inode.i_size)
72         {
73                 VFS_ReadAt( disk->FD, Base+ofs, sizeof(tExt2_DirEnt), &dirent);
74                 ofs += dirent.rec_len;
75                 size -= dirent.rec_len;
76                 entNum ++;
77                 
78                 if(ofs >= disk->BlockSize) {
79                         block ++;
80                         if( ofs > disk->BlockSize ) {
81                                 Log_Warning("EXT2", "Directory Entry %i of inode %i extends over a block boundary, ignoring",
82                                         entNum-1, Node->Inode);
83                         }
84                         ofs = 0;
85                         Base = Ext2_int_GetBlockAddr( disk, inode.i_block, block );
86                         if( Base == 0 ) {
87                                 size = 0;
88                                 break;
89                         }
90                 }
91         }
92         
93         // Check for the end of the list
94         if(size <= 0 || size > inode.i_size) {
95                 LEAVE('n');
96                 return NULL;
97         }
98         
99         // Read Entry
100         VFS_ReadAt( disk->FD, Base+ofs, sizeof(tExt2_DirEnt), &dirent );
101         LOG("dirent={.rec_len=%i,.inode=0x%x,.name_len=%i}",
102                 dirent.rec_len, dirent.inode, dirent.name_len);
103         dirent.name[ dirent.name_len ] = '\0';  // Cap off string
104         
105         if( dirent.name_len == 0 ) {
106                 LEAVE('p', VFS_SKIP);
107                 return VFS_SKIP;
108         }
109         
110         // Ignore . and .. (these are done in the VFS)
111         if( (dirent.name[0] == '.' && dirent.name[1] == '\0')
112         ||  (dirent.name[0] == '.' && dirent.name[1] == '.' && dirent.name[2]=='\0')) {
113                 LEAVE('p', VFS_SKIP);
114                 return VFS_SKIP;        // Skip
115         }
116         
117         LEAVE('s', dirent.name);
118         // Create new node
119         return strdup(dirent.name);
120 }
121
122 /**
123  * \brief Gets information about a file
124  * \param Node  Parent Node
125  * \param Filename      Name of wanted file
126  * \return VFS Node of file
127  */
128 tVFS_Node *Ext2_FindDir(tVFS_Node *Node, const char *Filename)
129 {
130         tExt2_Disk      *disk = Node->ImplPtr;
131         tExt2_Inode     inode;
132         tExt2_DirEnt    dirent;
133         Uint64  Base;   // Block's Base Address
134          int    block = 0;
135         Uint    ofs = 0;
136          int    entNum = 0;
137         Uint    size;
138          int    filenameLen = strlen(Filename);
139         
140         // Read directory's inode
141         Ext2_int_ReadInode(disk, Node->Inode, &inode);
142         size = inode.i_size;
143         
144         // Get First Block
145         // - Do this ourselves as it is a simple operation
146         Base = inode.i_block[0] * disk->BlockSize;
147         // Find File
148         while(size > 0)
149         {
150                 VFS_ReadAt( disk->FD, Base+ofs, sizeof(tExt2_DirEnt), &dirent);
151                 // TODO: Possible overrun if name_len == 255?
152                 dirent.name[ dirent.name_len ] = '\0';  // Cap off string
153                 // If it matches, create a node and return it
154                 if(dirent.name_len == filenameLen && strcmp(dirent.name, Filename) == 0)
155                         return Ext2_int_CreateNode( disk, dirent.inode );
156                 // Increment pointers
157                 ofs += dirent.rec_len;
158                 size -= dirent.rec_len;
159                 entNum ++;
160                 
161                 // Check for end of block
162                 if(ofs >= disk->BlockSize) {
163                         block ++;
164                         if( ofs > disk->BlockSize ) {
165                                 Log_Warning("EXT2", "Directory Entry %i of inode %i extends over a block boundary, ignoring",
166                                         entNum-1, Node->Inode);
167                         }
168                         ofs = 0;
169                         Base = Ext2_int_GetBlockAddr( disk, inode.i_block, block );
170                 }
171         }
172         
173         return NULL;
174 }
175
176 /**
177  * \fn int Ext2_MkNod(tVFS_Node *Parent, const char *Name, Uint Flags)
178  * \brief Create a new node
179  */
180 int Ext2_MkNod(tVFS_Node *Parent, const char *Name, Uint Flags)
181 {
182         ENTER("pParent sName xFlags", Parent, Name, Flags);
183         
184         Uint64 inodeNum = Ext2_int_AllocateInode(Parent->ImplPtr, Parent->Inode);
185         if( inodeNum == 0 ) {
186                 LOG("Inode allocation failed");
187                 LEAVE('i', -1);
188                 return -1;
189         }
190         tVFS_Node *child = Ext2_int_CreateNode(Parent->ImplPtr, inodeNum);
191         if( !child ) {
192                 Ext2_int_DereferenceInode(Parent->ImplPtr, inodeNum);
193                 Log_Warning("Ext2", "Ext2_MkNod - Node creation failed");
194                 LEAVE('i', -1);
195                 return -1;
196         }
197
198         child->Flags = Flags & (VFS_FFLAG_DIRECTORY|VFS_FFLAG_SYMLINK|VFS_FFLAG_READONLY);
199         child->UID = Threads_GetUID();
200         child->GID = Threads_GetGID();
201         child->CTime =
202                 child->MTime =
203                 child->ATime =
204                 now();
205         child->ImplInt = 0;     // ImplInt is the link count
206         // TODO: Set up ACLs
207
208         int rv = Ext2_Link(Parent, Name, child);
209         child->Type->Close(child);
210         LEAVE('i', rv);
211         return rv;
212 }
213
214 /**
215  * \brief Rename a file
216  * \param Node  This (directory) node
217  * \param OldName       Old name of file
218  * \param NewName       New name for file
219  * \return Boolean Failure - See ::tVFS_Node.Unlink for info
220  */
221 int Ext2_Unlink(tVFS_Node *Node, const char *OldName)
222 {
223         Log_Warning("Ext2", "TODO: Impliment Ext2_Unlink");
224         return 1;
225 }
226
227 /**
228  * \brief Links an existing node to a new name
229  * \param Parent        Parent (directory) node
230  * \param Name  New name for the node
231  * \param Node  Node to link
232  * \return Boolean Failure - See ::tVFS_Node.Link for info
233  */
234 int Ext2_Link(tVFS_Node *Node, const char *Name, tVFS_Node *Child)
235 {       
236         #if 1
237         tExt2_Disk      *disk = Node->ImplPtr;
238         tExt2_Inode     inode;
239         tExt2_DirEnt    *dirent;
240         tExt2_DirEnt    newEntry;
241         Uint64  base;   // Block's Base Address
242          int    block = 0, ofs = 0;
243         Uint    size;
244         void    *blockData;
245          int    bestMatch = -1, bestSize, bestBlock, bestOfs, bestNeedsSplit;
246          int    nEntries;
247
248         ENTER("pNode sName pChild",
249                 Node, Name, Child);
250         
251         blockData = malloc(disk->BlockSize);
252         
253         // Read child inode (get's the file type)
254         Ext2_int_ReadInode(disk, Child->Inode, &inode);
255         
256         // Create a stub entry
257         newEntry.inode = Child->Inode;
258         newEntry.name_len = strlen(Name);
259         newEntry.rec_len = ((newEntry.name_len+3)&~3) + EXT2_DIRENT_SIZE;
260         newEntry.type = inode.i_mode >> 12;
261         memcpy(newEntry.name, Name, newEntry.name_len);
262         
263         // Read directory's inode
264         Ext2_int_ReadInode(disk, Node->Inode, &inode);
265         size = inode.i_size;
266         
267         // Get a lock on the inode
268         //Ext2_int_LockInode(disk, Node->Inode);
269         Mutex_Acquire(&Node->Lock);
270
271 //      if( !Node->Data ) {
272 //      }
273
274         // Get First Block
275         // - Do this ourselves as it is a simple operation
276         base = inode.i_block[0] * disk->BlockSize;
277         VFS_ReadAt( disk->FD, base, disk->BlockSize, blockData );
278         block = 0;
279         // Find File
280         while(size > 0)
281         {
282                 dirent = blockData + ofs;
283                 // Sanity Check the entry
284                 if(ofs + dirent->rec_len > disk->BlockSize) {
285                         Log_Warning("EXT2",
286                                 "Directory entry %i of inode 0x%x extends over a block boundary",
287                                 nEntries, (Uint)Node->Inode);
288                 }
289                 else
290                 {
291                         LOG("Entry %i: %x %i bytes", nEntries, dirent->type, dirent->rec_len);
292                         // Free entry
293                         if(dirent->type == 0)
294                         {
295                                 if( dirent->rec_len >= newEntry.rec_len
296                                  && (bestMatch == -1 || bestSize > dirent->rec_len) )
297                                 {
298                                         bestMatch = nEntries;
299                                         bestSize = dirent->rec_len;
300                                         bestBlock = block;
301                                         bestOfs = ofs;
302                                         bestNeedsSplit = 0;
303                                 }
304                         }
305                         // Non free - check name to avoid duplicates
306                         else
307                         {
308                                 LOG(" name='%.*s'", dirent->name_len, dirent->name);
309                                 if(strncmp(Name, dirent->name, dirent->name_len) == 0) {
310                                         //Ext2_int_UnlockInode(disk, Node->Inode);
311                                         Mutex_Release(&Node->Lock);
312                                         LEAVE('i', 1);
313                                         return 1;       // ERR_???
314                                 }
315                                 
316                                  int    spare_space = dirent->rec_len - (dirent->name_len + EXT2_DIRENT_SIZE);
317                                 if( spare_space > newEntry.rec_len
318                                  && (bestMatch == -1 || bestSize > spare_space) )
319                                 {
320                                         bestMatch = nEntries;
321                                         bestSize = spare_space;
322                                         bestBlock = block;
323                                         bestOfs = ofs;
324                                         bestNeedsSplit = 1;
325                                 }
326                         }
327                 }
328                 
329                 // Increment the pointer
330                 nEntries ++;
331                 ofs += dirent->rec_len;
332                 size -= dirent->rec_len;
333                 if( size > 0 && ofs >= disk->BlockSize ) {
334                         // Read the next block if needed
335                 //      BLOCK_DIR_OFS(Node->Data, block) = nEntries;
336                         block ++;
337                         ofs = 0;
338                         base = Ext2_int_GetBlockAddr(disk, inode.i_block, block);
339                         VFS_ReadAt( disk->FD, base, disk->BlockSize, blockData );
340                 }
341         }
342         
343         LOG("bestMatch = %i", bestMatch);
344         // If EOF was reached with no space, check if we can fit one on the end
345         if( bestMatch < 0 && ofs + newEntry.rec_len < disk->BlockSize ) {
346                 Node->Size += newEntry.rec_len;
347                 Node->Flags |= VFS_FFLAG_DIRTY;
348                 bestBlock = block;
349                 bestOfs = ofs;
350                 bestSize = newEntry.rec_len;
351                 bestNeedsSplit = 0;
352         }
353         // Check if a free slot was found
354         if( bestMatch >= 0 )
355         {
356                 // Read-Modify-Write
357                 base = Ext2_int_GetBlockAddr(disk, inode.i_block, bestBlock);
358                 VFS_ReadAt( disk->FD, base, disk->BlockSize, blockData );
359                 dirent = blockData + bestOfs;
360                 // Shorten a pre-existing entry
361                 if(bestNeedsSplit)
362                 {
363                         dirent->rec_len = EXT2_DIRENT_SIZE + dirent->name_len;
364                         bestOfs += dirent->rec_len;
365                         //bestSize -= dirent->rec_len; // (not needed, bestSize is the spare space after)
366                         dirent = blockData + bestOfs;
367                 }
368                 // Insert new file entry
369                 memcpy(dirent, &newEntry, newEntry.rec_len);
370                 // Create a new blank entry
371                 if( bestSize != newEntry.rec_len )
372                 {
373                         bestOfs += newEntry.rec_len;
374                         dirent = blockData + bestOfs;
375
376                         dirent->rec_len = bestSize - newEntry.rec_len;                  
377                         dirent->type = 0;
378                 }
379                 // Save changes
380                 VFS_WriteAt( disk->FD, base, disk->BlockSize, blockData );
381         }
382         else {
383                 // Allocate block, Write
384                 Uint32 newblock = Ext2_int_AllocateBlock(disk, base / disk->BlockSize);
385                 Ext2_int_AppendBlock(disk, &inode, newblock);
386                 base = newblock * disk->BlockSize;
387                 Node->Size += newEntry.rec_len;
388                 Node->Flags |= VFS_FFLAG_DIRTY;
389                 memcpy(blockData, &newEntry, newEntry.rec_len);
390                 memset(blockData + newEntry.rec_len, 0, disk->BlockSize - newEntry.rec_len);
391                 VFS_WriteAt( disk->FD, base, disk->BlockSize, blockData );
392         }
393
394         Child->ImplInt ++;
395         Child->Flags |= VFS_FFLAG_DIRTY;
396
397         //Ext2_int_UnlockInode(disk, Node->Inode);
398         Mutex_Release(&Node->Lock);
399         LEAVE('i', 0);
400         return 0;
401         #else
402         Log_Warning("Ext2", "TODO: Impliment Ext2_Link");
403         return 1;
404         #endif
405 }
406
407 // ---- INTERNAL FUNCTIONS ----
408 /**
409  * \fn vfs_node *Ext2_int_CreateNode(tExt2_Disk *Disk, Uint InodeID)
410  * \brief Create a new VFS Node
411  */
412 tVFS_Node *Ext2_int_CreateNode(tExt2_Disk *Disk, Uint InodeID)
413 {
414         tExt2_Inode     inode;
415         tVFS_Node       retNode;
416         tVFS_Node       *tmpNode;
417         
418         if( !Ext2_int_ReadInode(Disk, InodeID, &inode) )
419                 return NULL;
420         
421         if( (tmpNode = Inode_GetCache(Disk->CacheID, InodeID)) )
422                 return tmpNode;
423
424         memset(&retNode, 0, sizeof(retNode));   
425         
426         // Set identifiers
427         retNode.Inode = InodeID;
428         retNode.ImplPtr = Disk;
429         retNode.ImplInt = inode.i_links_count;
430         
431         // Set file length
432         retNode.Size = inode.i_size;
433         
434         // Set Access Permissions
435         retNode.UID = inode.i_uid;
436         retNode.GID = inode.i_gid;
437         retNode.NumACLs = 3;
438         retNode.ACLs = VFS_UnixToAcessACL(inode.i_mode & 0777, inode.i_uid, inode.i_gid);
439         
440         //  Set Function Pointers
441         retNode.Type = &gExt2_FileType;
442         
443         switch(inode.i_mode & EXT2_S_IFMT)
444         {
445         // Symbolic Link
446         case EXT2_S_IFLNK:
447                 retNode.Flags = VFS_FFLAG_SYMLINK;
448                 break;
449         // Regular File
450         case EXT2_S_IFREG:
451                 retNode.Flags = 0;
452                 retNode.Size |= (Uint64)inode.i_dir_acl << 32;
453                 break;
454         // Directory
455         case EXT2_S_IFDIR:
456                 retNode.Type = &gExt2_DirType;
457                 retNode.Flags = VFS_FFLAG_DIRECTORY;
458                 retNode.Data = calloc( sizeof(Uint16), DivUp(retNode.Size, Disk->BlockSize) );
459                 break;
460         // Unknown, Write protect it to be safe 
461         default:
462                 retNode.Flags = VFS_FFLAG_READONLY;
463                 break;
464         }
465         
466         // Set Timestamps
467         retNode.ATime = inode.i_atime * 1000;
468         retNode.MTime = inode.i_mtime * 1000;
469         retNode.CTime = inode.i_ctime * 1000;
470         
471         // Save in node cache and return saved node
472         return Inode_CacheNode(Disk->CacheID, &retNode);
473 }
474
475 int Ext2_int_WritebackNode(tExt2_Disk *Disk, tVFS_Node *Node)
476 {
477         Log_Warning("Ext2","TODO: Impliment Ext2_int_WritebackNode");
478         return 0;
479 }
480

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