Merge branch 'master' of git://cadel.mutabah.net/acess2
[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  int    Ext2_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX]);
17 tVFS_Node       *Ext2_FindDir(tVFS_Node *Node, const char *FileName, Uint Flags);
18 tVFS_Node       *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
22 // === GLOBALS ===
23 tVFS_NodeType   gExt2_DirType = {
24         .TypeName = "ext2-dir",
25         .ReadDir = Ext2_ReadDir,
26         .FindDir = Ext2_FindDir,
27         .MkNod = Ext2_MkNod,
28         .Unlink = Ext2_Unlink,
29         .Link = Ext2_Link,
30         .Close = Ext2_CloseFile
31         };
32 tVFS_NodeType   gExt2_FileType = {
33         .TypeName = "ext2-file",
34         .Read = Ext2_Read,
35         .Write = Ext2_Write,
36         .Close = Ext2_CloseFile
37         };
38
39 // === CODE ===
40 /**
41  * \brief Reads a directory entry
42  * \param Node  Directory node
43  * \param Pos   Position of desired element
44  */
45 int Ext2_ReadDir(tVFS_Node *Node, int Pos, char Dest[FILENAME_MAX])
46 {
47         tExt2_Inode     *inode = (void*)(Node+1);
48         tExt2_DirEnt    dirent;
49         Uint64  Base;   // Block's Base Address
50          int    block = 0;
51         Uint    ofs = 0;
52          int    entNum = 0;
53         tExt2_Disk      *disk = Node->ImplPtr;
54         Uint    size;
55         
56         ENTER("pNode iPos", Node, Pos);
57         
58         // Read directory's inode
59         size = inode->i_size;
60         
61         LOG("inode={.i_block[0]= 0x%x, .i_size=0x%x}", inode->i_block[0], inode->i_size);
62         
63         // Find Entry
64         // Get First Block
65         // - Do this ourselves as it is a simple operation
66         Base = inode->i_block[0] * disk->BlockSize;
67         // Scan directory
68         while(Pos -- && size > 0 && size <= inode->i_size)
69         {
70                 VFS_ReadAt( disk->FD, Base+ofs, sizeof(tExt2_DirEnt), &dirent);
71                 ofs += dirent.rec_len;
72                 size -= dirent.rec_len;
73                 entNum ++;
74                 
75                 if(ofs >= disk->BlockSize) {
76                         block ++;
77                         if( ofs > disk->BlockSize ) {
78                                 Log_Warning("EXT2", "Directory Entry %i of inode %i extends over a block boundary, ignoring",
79                                         entNum-1, Node->Inode);
80                         }
81                         ofs = 0;
82                         Base = Ext2_int_GetBlockAddr( disk, inode->i_block, block );
83                         if( Base == 0 ) {
84                                 size = 0;
85                                 break;
86                         }
87                 }
88         }
89         
90         // Check for the end of the list
91         if(size <= 0 || size > inode->i_size) {
92                 LEAVE('i', -ENOENT);
93                 return -ENOENT;
94         }
95         
96         // Read Entry
97         VFS_ReadAt( disk->FD, Base+ofs, sizeof(tExt2_DirEnt), &dirent );
98         LOG("dirent={.rec_len=%i,.inode=0x%x,.name_len=%i}",
99                 dirent.rec_len, dirent.inode, dirent.name_len);
100         dirent.name[ dirent.name_len ] = '\0';  // Cap off string
101         
102         if( dirent.name_len == 0 ) {
103                 LEAVE('i', 1);
104                 return 1;
105         }
106         
107         // Ignore . and .. (these are done in the VFS)
108         if( (dirent.name[0] == '.' && dirent.name[1] == '\0')
109         ||  (dirent.name[0] == '.' && dirent.name[1] == '.' && dirent.name[2]=='\0')) {
110                 LEAVE('i', 1);
111                 return 1;       // Skip
112         }
113         
114         LOG("Name '%s'", dirent.name);
115         strncpy(Dest, dirent.name, FILENAME_MAX);
116         LEAVE('i', 0);
117         return 0;
118 }
119
120 /**
121  * \brief Gets information about a file
122  * \param Node  Parent Node
123  * \param Filename      Name of wanted file
124  * \return VFS Node of file
125  */
126 tVFS_Node *Ext2_FindDir(tVFS_Node *Node, const char *Filename, Uint Flags)
127 {
128         tExt2_Disk      *disk = Node->ImplPtr;
129         tExt2_Inode     *inode = (void*)(Node+1);
130         tExt2_DirEnt    dirent;
131         Uint64  Base;   // Block's Base Address
132          int    block = 0;
133         Uint    ofs = 0;
134          int    entNum = 0;
135         Uint    size;
136          int    filenameLen = strlen(Filename);
137         
138         // Read directory's inode
139         size = inode->i_size;
140         
141         // Get First Block
142         // - Do this ourselves as it is a simple operation
143         Base = inode->i_block[0] * disk->BlockSize;
144         // Find File
145         while(size > 0)
146         {
147                 VFS_ReadAt( disk->FD, Base+ofs, sizeof(tExt2_DirEnt), &dirent);
148                 // If it matches, create a node and return it
149                 if(dirent.name_len == filenameLen && strncmp(dirent.name, Filename, filenameLen) == 0)
150                         return Ext2_int_CreateNode( disk, dirent.inode );
151                 // Increment pointers
152                 ofs += dirent.rec_len;
153                 size -= dirent.rec_len;
154                 entNum ++;
155                 
156                 // Check for end of block
157                 if(ofs >= disk->BlockSize) {
158                         block ++;
159                         if( ofs > disk->BlockSize ) {
160                                 Log_Warning("EXT2", "Directory Entry %i of inode %i extends over a block boundary, ignoring",
161                                         entNum-1, Node->Inode);
162                         }
163                         ofs = 0;
164                         Base = Ext2_int_GetBlockAddr( disk, inode->i_block, block );
165                 }
166         }
167         
168         return NULL;
169 }
170
171 /**
172  * \fn int Ext2_MkNod(tVFS_Node *Parent, const char *Name, Uint Flags)
173  * \brief Create a new node
174  */
175 tVFS_Node *Ext2_MkNod(tVFS_Node *Parent, const char *Name, Uint Flags)
176 {
177         ENTER("pParent sName xFlags", Parent, Name, Flags);
178         
179         Uint64 inodeNum = Ext2_int_AllocateInode(Parent->ImplPtr, Parent->Inode);
180         if( inodeNum == 0 ) {
181                 LOG("Inode allocation failed");
182                 LEAVE_RET('n', NULL);
183         }
184         tVFS_Node *child = Ext2_int_CreateNode(Parent->ImplPtr, inodeNum);
185         if( !child ) {
186                 Ext2_int_DereferenceInode(Parent->ImplPtr, inodeNum);
187                 Log_Warning("Ext2", "Ext2_MkNod - Node creation failed");
188                 LEAVE_RET('n', NULL);
189         }
190
191         child->Flags = Flags & (VFS_FFLAG_DIRECTORY|VFS_FFLAG_SYMLINK|VFS_FFLAG_READONLY);
192         child->UID = Threads_GetUID();
193         child->GID = Threads_GetGID();
194         child->CTime =
195                 child->MTime =
196                 child->ATime =
197                 now();
198         child->ImplInt = 0;     // ImplInt is the link count
199         // TODO: Set up ACLs
200
201         int rv = Ext2_Link(Parent, Name, child);
202         if( rv ) {
203                 Ext2_CloseFile(child);
204                 return NULL;
205         }
206         LEAVE_RET('p', child);
207 }
208
209 /**
210  * \brief Rename a file
211  * \param Node  This (directory) node
212  * \param OldName       Old name of file
213  * \param NewName       New name for file
214  * \return Boolean Failure - See ::tVFS_Node.Unlink for info
215  */
216 int Ext2_Unlink(tVFS_Node *Node, const char *OldName)
217 {
218         Log_Warning("Ext2", "TODO: Impliment Ext2_Unlink");
219         return 1;
220 }
221
222 /**
223  * \brief Links an existing node to a new name
224  * \param Parent        Parent (directory) node
225  * \param Name  New name for the node
226  * \param Node  Node to link
227  * \return Boolean Failure - See ::tVFS_Node.Link for info
228  */
229 int Ext2_Link(tVFS_Node *Node, const char *Name, tVFS_Node *Child)
230 {       
231         tExt2_Disk      *disk = Node->ImplPtr;
232         tExt2_Inode     *inode = (void*)(Node+1);
233         tExt2_DirEnt    *dirent;
234         tExt2_DirEnt    newEntry;
235         Uint64  base;   // Block's Base Address
236          int    block = 0, ofs = 0;
237         Uint    size;
238          int    bestMatch = -1;
239          int    bestSize=0, bestBlock=0, bestOfs=0, bestNeedsSplit=0;
240          int    nEntries;
241
242         ENTER("pNode sName pChild",
243                 Node, Name, Child);
244         
245         void *blockData = malloc(disk->BlockSize);
246         
247         // Create a stub entry
248         newEntry.inode = Child->Inode;
249         newEntry.name_len = strlen(Name);
250         newEntry.rec_len = ((newEntry.name_len+3)&~3) + EXT2_DIRENT_SIZE;
251         newEntry.type = inode->i_mode >> 12;
252         memcpy(newEntry.name, Name, newEntry.name_len);
253         
254         // Read directory's inode
255         size = inode->i_size;
256         
257         // Get a lock on the inode
258         //Ext2_int_LockInode(disk, Node->Inode);
259         Mutex_Acquire(&Node->Lock);
260
261 //      if( !Node->Data ) {
262 //      }
263
264         // Get First Block
265         // - Do this ourselves as it is a simple operation
266         base = inode->i_block[0] * disk->BlockSize;
267         VFS_ReadAt( disk->FD, base, disk->BlockSize, blockData );
268         block = 0;
269         nEntries = 0;
270         // Find File
271         while(size > 0)
272         {
273                 dirent = blockData + ofs;
274                 // Sanity Check the entry
275                 if(ofs + dirent->rec_len > disk->BlockSize) {
276                         Log_Warning("EXT2",
277                                 "Directory entry %i of inode 0x%x extends over a block boundary",
278                                 nEntries, (Uint)Node->Inode);
279                 }
280                 else
281                 {
282                         LOG("Entry %i: %x %i bytes", nEntries, dirent->type, dirent->rec_len);
283                         // Free entry
284                         if(dirent->type == 0)
285                         {
286                                 if( dirent->rec_len >= newEntry.rec_len
287                                  && (bestMatch == -1 || bestSize > dirent->rec_len) )
288                                 {
289                                         bestMatch = nEntries;
290                                         bestSize = dirent->rec_len;
291                                         bestBlock = block;
292                                         bestOfs = ofs;
293                                         bestNeedsSplit = 0;
294                                 }
295                         }
296                         // Non free - check name to avoid duplicates
297                         else
298                         {
299                                 LOG(" name='%.*s'", dirent->name_len, dirent->name);
300                                 if(strncmp(Name, dirent->name, dirent->name_len) == 0) {
301                                         //Ext2_int_UnlockInode(disk, Node->Inode);
302                                         goto _err;
303                                 }
304                                 
305                                  int    spare_space = dirent->rec_len - (dirent->name_len + EXT2_DIRENT_SIZE);
306                                 if( spare_space > newEntry.rec_len
307                                  && (bestMatch == -1 || bestSize > spare_space) )
308                                 {
309                                         bestMatch = nEntries;
310                                         bestSize = spare_space;
311                                         bestBlock = block;
312                                         bestOfs = ofs;
313                                         bestNeedsSplit = 1;
314                                 }
315                         }
316                 }
317                 
318                 // Increment the pointer
319                 nEntries ++;
320                 ofs += dirent->rec_len;
321                 size -= dirent->rec_len;
322                 if( size > 0 && ofs >= disk->BlockSize ) {
323                         // Read the next block if needed
324                 //      BLOCK_DIR_OFS(Node->Data, block) = nEntries;
325                         block ++;
326                         ofs = 0;
327                         base = Ext2_int_GetBlockAddr(disk, inode->i_block, block);
328                         VFS_ReadAt( disk->FD, base, disk->BlockSize, blockData );
329                 }
330         }
331         
332         LOG("bestMatch = %i", bestMatch);
333         // If EOF was reached with no space, check if we can fit one on the end
334         if( bestMatch < 0 && ofs + newEntry.rec_len < disk->BlockSize ) {
335                 Node->Size += newEntry.rec_len;
336                 Node->Flags |= VFS_FFLAG_DIRTY;
337                 bestBlock = block;
338                 bestOfs = ofs;
339                 bestSize = newEntry.rec_len;
340                 bestNeedsSplit = 0;
341         }
342         // Check if a free slot was found
343         if( bestMatch >= 0 )
344         {
345                 // Read-Modify-Write
346                 base = Ext2_int_GetBlockAddr(disk, inode->i_block, bestBlock);
347                 VFS_ReadAt( disk->FD, base, disk->BlockSize, blockData );
348                 dirent = blockData + bestOfs;
349                 // Shorten a pre-existing entry
350                 if(bestNeedsSplit)
351                 {
352                         dirent->rec_len = EXT2_DIRENT_SIZE + dirent->name_len;
353                         bestOfs += dirent->rec_len;
354                         //bestSize -= dirent->rec_len; // (not needed, bestSize is the spare space after)
355                         dirent = blockData + bestOfs;
356                 }
357                 // Insert new file entry
358                 memcpy(dirent, &newEntry, newEntry.rec_len);
359                 // Create a new blank entry
360                 if( bestSize != newEntry.rec_len )
361                 {
362                         bestOfs += newEntry.rec_len;
363                         dirent = blockData + bestOfs;
364
365                         dirent->rec_len = bestSize - newEntry.rec_len;                  
366                         dirent->type = 0;
367                 }
368                 // Save changes
369                 VFS_WriteAt( disk->FD, base, disk->BlockSize, blockData );
370         }
371         else {
372                 // Allocate block, Write
373                 Uint32 newblock = Ext2_int_AllocateBlock(disk, base / disk->BlockSize);
374                 Ext2_int_AppendBlock(Node, inode, newblock);
375                 base = newblock * disk->BlockSize;
376                 Node->Size += newEntry.rec_len;
377                 Node->Flags |= VFS_FFLAG_DIRTY;
378                 memcpy(blockData, &newEntry, newEntry.rec_len);
379                 memset(blockData + newEntry.rec_len, 0, disk->BlockSize - newEntry.rec_len);
380                 VFS_WriteAt( disk->FD, base, disk->BlockSize, blockData );
381         }
382
383         Child->ImplInt ++;
384         Child->Flags |= VFS_FFLAG_DIRTY;
385
386         //Ext2_int_UnlockInode(disk, Node->Inode);
387         free(blockData);
388         Mutex_Release(&Node->Lock);
389         LEAVE('i', 0);
390         return 0;
391 _err:
392         free(blockData);
393         Mutex_Release(&Node->Lock);
394         LEAVE('i', 1);
395         return 1;       // ERR_???
396 }
397

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