Updated headers so they really are the same
[yaffs2.git] / direct / yaffsfs.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2007 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  */
13  
14 #include "yaffsfs.h"
15 #include "yaffs_guts.h"
16 #include "yaffscfg.h"
17 #include <string.h> // for memset
18 #include "yportenv.h"
19
20 #define YAFFSFS_MAX_SYMLINK_DEREFERENCES 5
21
22 #ifndef NULL
23 #define NULL ((void *)0)
24 #endif
25
26
27 const char *yaffsfs_c_version="$Id: yaffsfs.c,v 1.17 2007-02-14 01:09:06 wookey Exp $";
28
29 // configurationList is the list of devices that are supported
30 static yaffsfs_DeviceConfiguration *yaffsfs_configurationList;
31
32
33 /* Some forward references */
34 static yaffs_Object *yaffsfs_FindObject(yaffs_Object *relativeDirectory, const char *path, int symDepth);
35 static void yaffsfs_RemoveObjectCallback(yaffs_Object *obj);
36
37
38 // Handle management.
39 // 
40
41 typedef struct
42 {
43         __u8  inUse:1;          // this handle is in use
44         __u8  readOnly:1;       // this handle is read only
45         __u8  append:1;         // append only
46         __u8  exclusive:1;      // exclusive
47         __u32 position;         // current position in file
48         yaffs_Object *obj;      // the object
49 }yaffsfs_Handle;
50
51
52 static yaffsfs_Handle yaffsfs_handle[YAFFSFS_N_HANDLES];
53
54 // yaffsfs_InitHandle
55 /// Inilitalise handles on start-up.
56 //
57 static int yaffsfs_InitHandles(void)
58 {
59         int i;
60         for(i = 0; i < YAFFSFS_N_HANDLES; i++)
61         {
62                 yaffsfs_handle[i].inUse = 0;
63                 yaffsfs_handle[i].obj = NULL;
64         }
65         return 0;
66 }
67
68 yaffsfs_Handle *yaffsfs_GetHandlePointer(int h)
69 {
70         if(h < 0 || h >= YAFFSFS_N_HANDLES)
71         {
72                 return NULL;
73         }
74         
75         return &yaffsfs_handle[h];
76 }
77
78 yaffs_Object *yaffsfs_GetHandleObject(int handle)
79 {
80         yaffsfs_Handle *h = yaffsfs_GetHandlePointer(handle);
81
82         if(h && h->inUse)
83         {
84                 return h->obj;
85         }
86         
87         return NULL;
88 }
89
90
91 //yaffsfs_GetHandle
92 // Grab a handle (when opening a file)
93 //
94
95 static int yaffsfs_GetHandle(void)
96 {
97         int i;
98         yaffsfs_Handle *h;
99         
100         for(i = 0; i < YAFFSFS_N_HANDLES; i++)
101         {
102                 h = yaffsfs_GetHandlePointer(i);
103                 if(!h)
104                 {
105                         // todo bug: should never happen
106                 }
107                 if(!h->inUse)
108                 {
109                         memset(h,0,sizeof(yaffsfs_Handle));
110                         h->inUse=1;
111                         return i;
112                 }
113         }
114         return -1;
115 }
116
117 // yaffs_PutHandle
118 // Let go of a handle (when closing a file)
119 //
120 static int yaffsfs_PutHandle(int handle)
121 {
122         yaffsfs_Handle *h = yaffsfs_GetHandlePointer(handle);
123         
124         if(h)
125         {
126                 h->inUse = 0;
127                 h->obj = NULL;
128         }
129         return 0;
130 }
131
132
133
134 // Stuff to search for a directory from a path
135
136
137 int yaffsfs_Match(char a, char b)
138 {
139         // case sensitive
140         return (a == b);
141 }
142
143 // yaffsfs_FindDevice
144 // yaffsfs_FindRoot
145 // Scan the configuration list to find the root.
146 // Curveballs: Should match paths that end in '/' too
147 // Curveball2 Might have "/x/ and "/x/y". Need to return the longest match
148 static yaffs_Device *yaffsfs_FindDevice(const char *path, char **restOfPath)
149 {
150         yaffsfs_DeviceConfiguration *cfg = yaffsfs_configurationList;
151         const char *leftOver;
152         const char *p;
153         yaffs_Device *retval = NULL;
154         int thisMatchLength;
155         int longestMatch = -1;
156         
157         // Check all configs, choose the one that:
158         // 1) Actually matches a prefix (ie /a amd /abc will not match
159         // 2) Matches the longest.
160         while(cfg && cfg->prefix && cfg->dev)
161         {
162                 leftOver = path;
163                 p = cfg->prefix;
164                 thisMatchLength = 0;
165                 
166                 while(*p &&  //unmatched part of prefix 
167                       strcmp(p,"/") && // the rest of the prefix is not / (to catch / at end)
168                       *leftOver && 
169                       yaffsfs_Match(*p,*leftOver))
170                 {
171                         p++;
172                         leftOver++;
173                         thisMatchLength++;
174                 }
175                 if((!*p || strcmp(p,"/") == 0) &&      // end of prefix
176                    (!*leftOver || *leftOver == '/') && // no more in this path name part
177                    (thisMatchLength > longestMatch))
178                 {
179                         // Matched prefix
180                         *restOfPath = (char *)leftOver;
181                         retval = cfg->dev;
182                         longestMatch = thisMatchLength;
183                 }
184                 cfg++;
185         }
186         return retval;
187 }
188
189 static yaffs_Object *yaffsfs_FindRoot(const char *path, char **restOfPath)
190 {
191
192         yaffs_Device *dev;
193         
194         dev= yaffsfs_FindDevice(path,restOfPath);
195         if(dev && dev->isMounted)
196         {
197                 return dev->rootDir;
198         }
199         return NULL;
200 }
201
202 static yaffs_Object *yaffsfs_FollowLink(yaffs_Object *obj,int symDepth)
203 {
204
205         while(obj && obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
206         {
207                 char *alias = obj->variant.symLinkVariant.alias;
208                                                 
209                 if(*alias == '/')
210                 {
211                         // Starts with a /, need to scan from root up
212                         obj = yaffsfs_FindObject(NULL,alias,symDepth++);
213                 }
214                 else
215                 {
216                         // Relative to here, so use the parent of the symlink as a start
217                         obj = yaffsfs_FindObject(obj->parent,alias,symDepth++);
218                 }
219         }
220         return obj;
221 }
222
223
224 // yaffsfs_FindDirectory
225 // Parse a path to determine the directory and the name within the directory.
226 //
227 // eg. "/data/xx/ff" --> puts name="ff" and returns the directory "/data/xx"
228 static yaffs_Object *yaffsfs_DoFindDirectory(yaffs_Object *startDir,const char *path,char **name,int symDepth)
229 {
230         yaffs_Object *dir;
231         char *restOfPath;
232         char str[YAFFS_MAX_NAME_LENGTH+1];
233         int i;
234         
235         if(symDepth > YAFFSFS_MAX_SYMLINK_DEREFERENCES)
236         {
237                 return NULL;
238         }
239         
240         if(startDir)
241         {
242                 dir = startDir;
243                 restOfPath = (char *)path;
244         }
245         else
246         {
247                 dir = yaffsfs_FindRoot(path,&restOfPath);
248         }
249         
250         while(dir)
251         {       
252                 // parse off /.
253                 // curve ball: also throw away surplus '/' 
254                 // eg. "/ram/x////ff" gets treated the same as "/ram/x/ff"
255                 while(*restOfPath == '/')
256                 {
257                         restOfPath++; // get rid of '/'
258                 }
259                 
260                 *name = restOfPath;
261                 i = 0;
262                 
263                 while(*restOfPath && *restOfPath != '/')
264                 {
265                         if (i < YAFFS_MAX_NAME_LENGTH)
266                         {
267                                 str[i] = *restOfPath;
268                                 str[i+1] = '\0';
269                                 i++;
270                         }
271                         restOfPath++;
272                 }
273                 
274                 if(!*restOfPath)
275                 {
276                         // got to the end of the string
277                         return dir;
278                 }
279                 else
280                 {
281                         if(strcmp(str,".") == 0)
282                         {
283                                 // Do nothing
284                         }
285                         else if(strcmp(str,"..") == 0)
286                         {
287                                 dir = dir->parent;
288                         }
289                         else
290                         {
291                                 dir = yaffs_FindObjectByName(dir,str);
292                                 
293                                 while(dir && dir->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
294                                 {
295                                 
296                                         dir = yaffsfs_FollowLink(dir,symDepth);
297                 
298                                 }
299                                 
300                                 if(dir && dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
301                                 {
302                                         dir = NULL;
303                                 }
304                         }
305                 }
306         }
307         // directory did not exist.
308         return NULL;
309 }
310
311 static yaffs_Object *yaffsfs_FindDirectory(yaffs_Object *relativeDirectory,const char *path,char **name,int symDepth)
312 {
313         return yaffsfs_DoFindDirectory(relativeDirectory,path,name,symDepth);
314 }
315
316 // yaffsfs_FindObject turns a path for an existing object into the object
317 // 
318 static yaffs_Object *yaffsfs_FindObject(yaffs_Object *relativeDirectory, const char *path,int symDepth)
319 {
320         yaffs_Object *dir;
321         char *name;
322         
323         dir = yaffsfs_FindDirectory(relativeDirectory,path,&name,symDepth);
324         
325         if(dir && *name)
326         {
327                 return yaffs_FindObjectByName(dir,name);
328         }
329         
330         return dir;
331 }
332
333
334
335 int yaffs_open(const char *path, int oflag, int mode)
336 {
337         yaffs_Object *obj = NULL;
338         yaffs_Object *dir = NULL;
339         char *name;
340         int handle = -1;
341         yaffsfs_Handle *h = NULL;
342         int alreadyOpen = 0;
343         int alreadyExclusive = 0;
344         int openDenied = 0;
345         int symDepth = 0;
346         int errorReported = 0;
347         
348         int i;
349         
350         
351         // todo sanity check oflag (eg. can't have O_TRUNC without WRONLY or RDWR
352         
353         
354         yaffsfs_Lock();
355         
356         handle = yaffsfs_GetHandle();
357         
358         if(handle >= 0)
359         {
360
361                 h = yaffsfs_GetHandlePointer(handle);
362         
363         
364                 // try to find the exisiting object
365                 obj = yaffsfs_FindObject(NULL,path,0);
366                 
367                 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
368                 {
369                 
370                         obj = yaffsfs_FollowLink(obj,symDepth++);
371                 }
372
373                 if(obj)
374                 {
375                         // Check if the object is already in use
376                         alreadyOpen = alreadyExclusive = 0;
377                         
378                         for(i = 0; i <= YAFFSFS_N_HANDLES; i++)
379                         {
380                                 
381                                 if(i != handle &&
382                                    yaffsfs_handle[i].inUse &&
383                                     obj == yaffsfs_handle[i].obj)
384                                  {
385                                         alreadyOpen = 1;
386                                         if(yaffsfs_handle[i].exclusive)
387                                         {
388                                                 alreadyExclusive = 1;
389                                         }
390                                  }
391                         }
392
393                         if(((oflag & O_EXCL) && alreadyOpen) || alreadyExclusive)
394                         {
395                                 openDenied = 1;
396                         }
397                         
398                         // Open should fail if O_CREAT and O_EXCL are specified
399                         if((oflag & O_EXCL) && (oflag & O_CREAT))
400                         {
401                                 openDenied = 1;
402                                 yaffsfs_SetError(-EEXIST);
403                                 errorReported = 1;
404                         }
405                         
406                         // Check file permissions
407                         if( (oflag & (O_RDWR | O_WRONLY)) == 0 &&     // ie O_RDONLY
408                            !(obj->yst_mode & S_IREAD))
409                         {
410                                 openDenied = 1;
411                         }
412
413                         if( (oflag & O_RDWR) && 
414                            !(obj->yst_mode & S_IREAD))
415                         {
416                                 openDenied = 1;
417                         }
418
419                         if( (oflag & (O_RDWR | O_WRONLY)) && 
420                            !(obj->yst_mode & S_IWRITE))
421                         {
422                                 openDenied = 1;
423                         }
424                         
425                 }
426                 
427                 else if((oflag & O_CREAT))
428                 {
429                         // Let's see if we can create this file
430                         dir = yaffsfs_FindDirectory(NULL,path,&name,0);
431                         if(dir)
432                         {
433                                 obj = yaffs_MknodFile(dir,name,mode,0,0);       
434                         }
435                         else
436                         {
437                                 yaffsfs_SetError(-ENOTDIR);
438                         }
439                 }
440                 
441                 if(obj && !openDenied)
442                 {
443                         h->obj = obj;
444                         h->inUse = 1;
445                 h->readOnly = (oflag & (O_WRONLY | O_RDWR)) ? 0 : 1;
446                         h->append =  (oflag & O_APPEND) ? 1 : 0;
447                         h->exclusive = (oflag & O_EXCL) ? 1 : 0;
448                         h->position = 0;
449                         
450                         obj->inUse++;
451                         if((oflag & O_TRUNC) && !h->readOnly)
452                         {
453                                 //todo truncate
454                                 yaffs_ResizeFile(obj,0);
455                         }
456                         
457                 }
458                 else
459                 {
460                         yaffsfs_PutHandle(handle);
461                         if(!errorReported)
462                         {
463                                 yaffsfs_SetError(-EACCESS);
464                                 errorReported = 1;
465                         }
466                         handle = -1;
467                 }
468                 
469         }
470         
471         yaffsfs_Unlock();
472         
473         return handle;          
474 }
475
476 int yaffs_close(int fd)
477 {
478         yaffsfs_Handle *h = NULL;
479         int retVal = 0;
480         
481         yaffsfs_Lock();
482
483         h = yaffsfs_GetHandlePointer(fd);
484         
485         if(h && h->inUse)
486         {
487                 // clean up
488                 yaffs_FlushFile(h->obj,1);
489                 h->obj->inUse--;
490                 if(h->obj->inUse <= 0 && h->obj->unlinked)
491                 {
492                         yaffs_DeleteFile(h->obj);
493                 }
494                 yaffsfs_PutHandle(fd);
495                 retVal = 0;
496         }
497         else
498         {
499                 // bad handle
500                 yaffsfs_SetError(-EBADF);               
501                 retVal = -1;
502         }
503         
504         yaffsfs_Unlock();
505         
506         return retVal;
507 }
508
509 int yaffs_read(int fd, void *buf, unsigned int nbyte)
510 {
511         yaffsfs_Handle *h = NULL;
512         yaffs_Object *obj = NULL;
513         int pos = 0;
514         int nRead = -1;
515         int maxRead;
516         
517         yaffsfs_Lock();
518         h = yaffsfs_GetHandlePointer(fd);
519         obj = yaffsfs_GetHandleObject(fd);
520         
521         if(!h || !obj)
522         {
523                 // bad handle
524                 yaffsfs_SetError(-EBADF);               
525         }
526         else if( h && obj)
527         {
528                 pos=  h->position;
529                 if(yaffs_GetObjectFileLength(obj) > pos)
530                 {
531                         maxRead = yaffs_GetObjectFileLength(obj) - pos;
532                 }
533                 else
534                 {
535                         maxRead = 0;
536                 }
537
538                 if(nbyte > maxRead)
539                 {
540                         nbyte = maxRead;
541                 }
542
543                 
544                 if(nbyte > 0)
545                 {
546                         nRead = yaffs_ReadDataFromFile(obj,buf,pos,nbyte);
547                         if(nRead >= 0)
548                         {
549                                 h->position = pos + nRead;
550                         }
551                         else
552                         {
553                                 //todo error
554                         }
555                 }
556                 else
557                 {
558                         nRead = 0;
559                 }
560                 
561         }
562         
563         yaffsfs_Unlock();
564         
565         
566         return (nRead >= 0) ? nRead : -1;
567                 
568 }
569
570 int yaffs_write(int fd, const void *buf, unsigned int nbyte)
571 {
572         yaffsfs_Handle *h = NULL;
573         yaffs_Object *obj = NULL;
574         int pos = 0;
575         int nWritten = -1;
576         int writeThrough = 0;
577         
578         yaffsfs_Lock();
579         h = yaffsfs_GetHandlePointer(fd);
580         obj = yaffsfs_GetHandleObject(fd);
581         
582         if(!h || !obj)
583         {
584                 // bad handle
585                 yaffsfs_SetError(-EBADF);               
586         }
587         else if( h && obj && h->readOnly)
588         {
589                 // todo error
590         }
591         else if( h && obj)
592         {
593                 if(h->append)
594                 {
595                         pos =  yaffs_GetObjectFileLength(obj);
596                 }
597                 else
598                 {
599                         pos = h->position;
600                 }
601                 
602                 nWritten = yaffs_WriteDataToFile(obj,buf,pos,nbyte,writeThrough);
603                 
604                 if(nWritten >= 0)
605                 {
606                         h->position = pos + nWritten;
607                 }
608                 else
609                 {
610                         //todo error
611                 }
612                 
613         }
614         
615         yaffsfs_Unlock();
616         
617         
618         return (nWritten >= 0) ? nWritten : -1;
619
620 }
621
622 int yaffs_truncate(int fd, off_t newSize)
623 {
624         yaffsfs_Handle *h = NULL;
625         yaffs_Object *obj = NULL;
626         int result = 0;
627         
628         yaffsfs_Lock();
629         h = yaffsfs_GetHandlePointer(fd);
630         obj = yaffsfs_GetHandleObject(fd);
631         
632         if(!h || !obj)
633         {
634                 // bad handle
635                 yaffsfs_SetError(-EBADF);               
636         }
637         else
638         {
639                 // resize the file
640                 result = yaffs_ResizeFile(obj,newSize);
641         }       
642         yaffsfs_Unlock();
643         
644         
645         return (result) ? 0 : -1;
646
647 }
648
649 off_t yaffs_lseek(int fd, off_t offset, int whence) 
650 {
651         yaffsfs_Handle *h = NULL;
652         yaffs_Object *obj = NULL;
653         int pos = -1;
654         int fSize = -1;
655         
656         yaffsfs_Lock();
657         h = yaffsfs_GetHandlePointer(fd);
658         obj = yaffsfs_GetHandleObject(fd);
659         
660         if(!h || !obj)
661         {
662                 // bad handle
663                 yaffsfs_SetError(-EBADF);               
664         }
665         else if(whence == SEEK_SET)
666         {
667                 if(offset >= 0)
668                 {
669                         pos = offset;
670                 }
671         }
672         else if(whence == SEEK_CUR)
673         {
674                 if( (h->position + offset) >= 0)
675                 {
676                         pos = (h->position + offset);
677                 }
678         }
679         else if(whence == SEEK_END)
680         {
681                 fSize = yaffs_GetObjectFileLength(obj);
682                 if(fSize >= 0 && (fSize + offset) >= 0)
683                 {
684                         pos = fSize + offset;
685                 }
686         }
687         
688         if(pos >= 0)
689         {
690                 h->position = pos;
691         }
692         else
693         {
694                 // todo error
695         }
696
697         
698         yaffsfs_Unlock();
699         
700         return pos;
701 }
702
703
704 int yaffsfs_DoUnlink(const char *path,int isDirectory) 
705 {
706         yaffs_Object *dir = NULL;
707         yaffs_Object *obj = NULL;
708         char *name;
709         int result = YAFFS_FAIL;
710         
711         yaffsfs_Lock();
712
713         obj = yaffsfs_FindObject(NULL,path,0);
714         dir = yaffsfs_FindDirectory(NULL,path,&name,0);
715         if(!dir)
716         {
717                 yaffsfs_SetError(-ENOTDIR);
718         }
719         else if(!obj)
720         {
721                 yaffsfs_SetError(-ENOENT);
722         }
723         else if(!isDirectory && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
724         {
725                 yaffsfs_SetError(-EISDIR);
726         }
727         else if(isDirectory && obj->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
728         {
729                 yaffsfs_SetError(-ENOTDIR);
730         }
731         else
732         {
733                 result = yaffs_Unlink(dir,name);
734                 
735                 if(result == YAFFS_FAIL && isDirectory)
736                 {
737                         yaffsfs_SetError(-ENOTEMPTY);
738                 }
739         }
740         
741         yaffsfs_Unlock();
742         
743         // todo error
744         
745         return (result == YAFFS_FAIL) ? -1 : 0;
746 }
747 int yaffs_rmdir(const char *path) 
748 {
749         return yaffsfs_DoUnlink(path,1);
750 }
751
752 int yaffs_unlink(const char *path) 
753 {
754         return yaffsfs_DoUnlink(path,0);
755 }
756
757 int yaffs_rename(const char *oldPath, const char *newPath)
758 {
759         yaffs_Object *olddir = NULL;
760         yaffs_Object *newdir = NULL;
761         yaffs_Object *obj = NULL;
762         char *oldname;
763         char *newname;
764         int result= YAFFS_FAIL;
765         int renameAllowed = 1;
766         
767         yaffsfs_Lock();
768         
769         olddir = yaffsfs_FindDirectory(NULL,oldPath,&oldname,0);
770         newdir = yaffsfs_FindDirectory(NULL,newPath,&newname,0);
771         obj = yaffsfs_FindObject(NULL,oldPath,0);
772         
773         if(!olddir || !newdir || !obj)
774         {
775                 // bad file
776                 yaffsfs_SetError(-EBADF);       
777                 renameAllowed = 0;      
778         }
779         else if(olddir->myDev != newdir->myDev)
780         {
781                 // oops must be on same device
782                 // todo error
783                 yaffsfs_SetError(-EXDEV);
784                 renameAllowed = 0;      
785         }
786         else if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
787         {
788                 // It is a directory, check that it is not being renamed to 
789                 // being its own decendent.
790                 // Do this by tracing from the new directory back to the root, checking for obj
791                 
792                 yaffs_Object *xx = newdir;
793                 
794                 while( renameAllowed && xx)
795                 {
796                         if(xx == obj)
797                         {
798                                 renameAllowed = 0;
799                         }
800                         xx = xx->parent;
801                 }
802                 if(!renameAllowed) yaffsfs_SetError(-EACCESS);
803         }
804         
805         if(renameAllowed)
806         {
807                 result = yaffs_RenameObject(olddir,oldname,newdir,newname);
808         }
809         
810         yaffsfs_Unlock();
811         
812         return (result == YAFFS_FAIL) ? -1 : 0; 
813 }
814
815
816 static int yaffsfs_DoStat(yaffs_Object *obj,struct yaffs_stat *buf)
817 {
818         int retVal = -1;
819
820         if(obj)
821         {
822                 obj = yaffs_GetEquivalentObject(obj);
823         }
824
825         if(obj && buf)
826         {
827         buf->st_dev = (int)obj->myDev->genericDevice;
828         buf->st_ino = obj->objectId;
829         buf->st_mode = obj->yst_mode & ~S_IFMT; // clear out file type bits
830         
831                 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) 
832                 {
833                         buf->st_mode |= S_IFDIR;
834                 }
835                 else if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK) 
836                 {
837                         buf->st_mode |= S_IFLNK;
838                 }
839                 else if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
840                 {
841                         buf->st_mode |= S_IFREG;
842                 }
843                 
844         buf->st_nlink = yaffs_GetObjectLinkCount(obj);
845         buf->st_uid = 0;    
846         buf->st_gid = 0;;     
847         buf->st_rdev = obj->yst_rdev;
848         buf->st_size = yaffs_GetObjectFileLength(obj);
849                 buf->st_blksize = obj->myDev->nDataBytesPerChunk;
850         buf->st_blocks = (buf->st_size + buf->st_blksize -1)/buf->st_blksize;
851         buf->yst_atime = obj->yst_atime; 
852         buf->yst_ctime = obj->yst_ctime; 
853         buf->yst_mtime = obj->yst_mtime; 
854                 retVal = 0;
855         }
856         return retVal;
857 }
858
859 static int yaffsfs_DoStatOrLStat(const char *path, struct yaffs_stat *buf,int doLStat)
860 {
861         yaffs_Object *obj;
862         
863         int retVal = -1;
864         
865         yaffsfs_Lock();
866         obj = yaffsfs_FindObject(NULL,path,0);
867         
868         if(!doLStat && obj)
869         {
870                 obj = yaffsfs_FollowLink(obj,0);
871         }
872         
873         if(obj)
874         {
875                 retVal = yaffsfs_DoStat(obj,buf);
876         }
877         else
878         {
879                 // todo error not found
880                 yaffsfs_SetError(-ENOENT);
881         }
882         
883         yaffsfs_Unlock();
884         
885         return retVal;
886         
887 }
888
889 int yaffs_stat(const char *path, struct yaffs_stat *buf)
890 {
891         return yaffsfs_DoStatOrLStat(path,buf,0);
892 }
893
894 int yaffs_lstat(const char *path, struct yaffs_stat *buf)
895 {
896         return yaffsfs_DoStatOrLStat(path,buf,1);
897 }
898
899 int yaffs_fstat(int fd, struct yaffs_stat *buf)
900 {
901         yaffs_Object *obj;
902         
903         int retVal = -1;
904         
905         yaffsfs_Lock();
906         obj = yaffsfs_GetHandleObject(fd);
907         
908         if(obj)
909         {
910                 retVal = yaffsfs_DoStat(obj,buf);
911         }
912         else
913         {
914                 // bad handle
915                 yaffsfs_SetError(-EBADF);               
916         }
917         
918         yaffsfs_Unlock();
919         
920         return retVal;
921 }
922
923 static int yaffsfs_DoChMod(yaffs_Object *obj,mode_t mode)
924 {
925         int result;
926
927         if(obj)
928         {
929                 obj = yaffs_GetEquivalentObject(obj);
930         }
931         
932         if(obj)
933         {
934                 obj->yst_mode = mode;
935                 obj->dirty = 1;
936                 result = yaffs_FlushFile(obj,0);
937         }
938         
939         return result == YAFFS_OK ? 0 : -1;
940 }
941
942
943 int yaffs_chmod(const char *path, mode_t mode)
944 {
945         yaffs_Object *obj;
946         
947         int retVal = -1;
948         
949         yaffsfs_Lock();
950         obj = yaffsfs_FindObject(NULL,path,0);
951         
952         if(obj)
953         {
954                 retVal = yaffsfs_DoChMod(obj,mode);
955         }
956         else
957         {
958                 // todo error not found
959                 yaffsfs_SetError(-ENOENT);
960         }
961         
962         yaffsfs_Unlock();
963         
964         return retVal;
965         
966 }
967
968
969 int yaffs_fchmod(int fd, mode_t mode)
970 {
971         yaffs_Object *obj;
972         
973         int retVal = -1;
974         
975         yaffsfs_Lock();
976         obj = yaffsfs_GetHandleObject(fd);
977         
978         if(obj)
979         {
980                 retVal = yaffsfs_DoChMod(obj,mode);
981         }
982         else
983         {
984                 // bad handle
985                 yaffsfs_SetError(-EBADF);               
986         }
987         
988         yaffsfs_Unlock();
989         
990         return retVal;
991 }
992
993
994 int yaffs_mkdir(const char *path, mode_t mode)
995 {
996         yaffs_Object *parent = NULL;
997         yaffs_Object *dir = NULL;
998         char *name;
999         int retVal= -1;
1000         
1001         yaffsfs_Lock();
1002         parent = yaffsfs_FindDirectory(NULL,path,&name,0);
1003         if(parent)
1004                 dir = yaffs_MknodDirectory(parent,name,mode,0,0);
1005         if(dir)
1006         {
1007                 retVal = 0;
1008         }
1009         else
1010         {
1011                 yaffsfs_SetError(-ENOSPC); // just assume no space for now
1012                 retVal = -1;
1013         }
1014         
1015         yaffsfs_Unlock();
1016         
1017         return retVal;
1018 }
1019
1020 int yaffs_mount(const char *path)
1021 {
1022         int retVal=-1;
1023         int result=YAFFS_FAIL;
1024         yaffs_Device *dev=NULL;
1025         char *dummy;
1026         
1027         T(YAFFS_TRACE_ALWAYS,("yaffs: Mounting %s\n",path));
1028         
1029         yaffsfs_Lock();
1030         dev = yaffsfs_FindDevice(path,&dummy);
1031         if(dev)
1032         {
1033                 if(!dev->isMounted)
1034                 {
1035                         result = yaffs_GutsInitialise(dev);
1036                         if(result == YAFFS_FAIL)
1037                         {
1038                                 // todo error - mount failed
1039                                 yaffsfs_SetError(-ENOMEM);
1040                         }
1041                         retVal = result ? 0 : -1;
1042                         
1043                 }
1044                 else
1045                 {
1046                         //todo error - already mounted.
1047                         yaffsfs_SetError(-EBUSY);
1048                 }
1049         }
1050         else
1051         {
1052                 // todo error - no device
1053                 yaffsfs_SetError(-ENODEV);
1054         }
1055         yaffsfs_Unlock();
1056         return retVal;
1057         
1058 }
1059
1060 int yaffs_unmount(const char *path)
1061 {
1062         int retVal=-1;
1063         yaffs_Device *dev=NULL;
1064         char *dummy;
1065         
1066         yaffsfs_Lock();
1067         dev = yaffsfs_FindDevice(path,&dummy);
1068         if(dev)
1069         {
1070                 if(dev->isMounted)
1071                 {
1072                         int i;
1073                         int inUse;
1074                         
1075                         yaffs_FlushEntireDeviceCache(dev);
1076                         yaffs_CheckpointSave(dev);
1077                         
1078                         for(i = inUse = 0; i < YAFFSFS_N_HANDLES && !inUse; i++)
1079                         {
1080                                 if(yaffsfs_handle[i].inUse && yaffsfs_handle[i].obj->myDev == dev)
1081                                 {
1082                                         inUse = 1; // the device is in use, can't unmount
1083                                 }
1084                         }
1085                         
1086                         if(!inUse)
1087                         {
1088                                 yaffs_Deinitialise(dev);
1089                                         
1090                                 retVal = 0;
1091                         }
1092                         else
1093                         {
1094                                 // todo error can't unmount as files are open
1095                                 yaffsfs_SetError(-EBUSY);
1096                         }
1097                         
1098                 }
1099                 else
1100                 {
1101                         //todo error - not mounted.
1102                         yaffsfs_SetError(-EINVAL);
1103                         
1104                 }
1105         }
1106         else
1107         {
1108                 // todo error - no device
1109                 yaffsfs_SetError(-ENODEV);
1110         }       
1111         yaffsfs_Unlock();
1112         return retVal;
1113         
1114 }
1115
1116 loff_t yaffs_freespace(const char *path)
1117 {
1118         loff_t retVal=-1;
1119         yaffs_Device *dev=NULL;
1120         char *dummy;
1121         
1122         yaffsfs_Lock();
1123         dev = yaffsfs_FindDevice(path,&dummy);
1124         if(dev  && dev->isMounted)
1125         {
1126                 retVal = yaffs_GetNumberOfFreeChunks(dev);
1127                 retVal *= dev->nDataBytesPerChunk;
1128                 
1129         }
1130         else
1131         {
1132                 yaffsfs_SetError(-EINVAL);
1133         }
1134         
1135         yaffsfs_Unlock();
1136         return retVal;  
1137 }
1138
1139
1140
1141 void yaffs_initialise(yaffsfs_DeviceConfiguration *cfgList)
1142 {
1143         
1144         yaffsfs_DeviceConfiguration *cfg;
1145         
1146         yaffsfs_configurationList = cfgList;
1147         
1148         yaffsfs_InitHandles();
1149         
1150         cfg = yaffsfs_configurationList;
1151         
1152         while(cfg && cfg->prefix && cfg->dev)
1153         {
1154                 cfg->dev->isMounted = 0;
1155                 cfg->dev->removeObjectCallback = yaffsfs_RemoveObjectCallback;
1156                 cfg++;
1157         }
1158         
1159         
1160 }
1161
1162
1163 //
1164 // Directory search stuff.
1165
1166 //
1167 // Directory search context
1168 //
1169 // NB this is an opaque structure.
1170
1171
1172 typedef struct
1173 {
1174         __u32 magic;
1175         yaffs_dirent de;                /* directory entry being used by this dsc */
1176         char name[NAME_MAX+1];          /* name of directory being searched */
1177         yaffs_Object *dirObj;           /* ptr to directory being searched */
1178         yaffs_Object *nextReturn;       /* obj to be returned by next readddir */
1179         int offset;
1180         struct list_head others;        
1181 } yaffsfs_DirectorySearchContext;
1182
1183
1184
1185 static struct list_head search_contexts;
1186
1187
1188 static void yaffsfs_SetDirRewound(yaffsfs_DirectorySearchContext *dsc)
1189 {
1190         if(dsc &&
1191            dsc->dirObj &&
1192            dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
1193            
1194            dsc->offset = 0;
1195            
1196            if( list_empty(&dsc->dirObj->variant.directoryVariant.children)){
1197                 dsc->nextReturn = NULL;
1198            } else {
1199                 dsc->nextReturn = list_entry(dsc->dirObj->variant.directoryVariant.children.next,
1200                                                 yaffs_Object,siblings);
1201            }
1202         } else {
1203                 /* Hey someone isn't playing nice! */
1204         }
1205 }
1206
1207 static void yaffsfs_DirAdvance(yaffsfs_DirectorySearchContext *dsc)
1208 {
1209         if(dsc &&
1210            dsc->dirObj &&
1211            dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
1212            
1213            if( dsc->nextReturn == NULL ||
1214                list_empty(&dsc->dirObj->variant.directoryVariant.children)){
1215                 dsc->nextReturn = NULL;
1216            } else {
1217                    struct list_head *next = dsc->nextReturn->siblings.next;
1218    
1219                    if( next == &dsc->dirObj->variant.directoryVariant.children)
1220                         dsc->nextReturn = NULL; /* end of list */
1221                    else 
1222                         dsc->nextReturn = list_entry(next,yaffs_Object,siblings);
1223            }
1224         } else {
1225                 /* Hey someone isn't playing nice! */
1226         }
1227 }
1228
1229 static void yaffsfs_RemoveObjectCallback(yaffs_Object *obj)
1230 {
1231
1232         struct list_head *i;
1233         yaffsfs_DirectorySearchContext *dsc;
1234         
1235         /* if search contexts not initilised then skip */
1236         if(!search_contexts.next)
1237                 return;
1238                 
1239         /* Iteratethrough the directory search contexts.
1240          * If any are the one being removed, then advance the dsc to
1241          * the next one to prevent a hanging ptr.
1242          */
1243          list_for_each(i, &search_contexts) {
1244                 if (i) {
1245                         dsc = list_entry(i, yaffsfs_DirectorySearchContext,others);
1246                         if(dsc->nextReturn == obj)
1247                                 yaffsfs_DirAdvance(dsc);
1248                 }
1249         }
1250                                 
1251 }
1252
1253 yaffs_DIR *yaffs_opendir(const char *dirname)
1254 {
1255         yaffs_DIR *dir = NULL;
1256         yaffs_Object *obj = NULL;
1257         yaffsfs_DirectorySearchContext *dsc = NULL;
1258         
1259         yaffsfs_Lock();
1260         
1261         obj = yaffsfs_FindObject(NULL,dirname,0);
1262         
1263         if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1264         {
1265                 
1266                 dsc = YMALLOC(sizeof(yaffsfs_DirectorySearchContext));
1267                 dir = (yaffs_DIR *)dsc;
1268                 if(dsc)
1269                 {
1270                         memset(dsc,0,sizeof(yaffsfs_DirectorySearchContext));
1271                         dsc->magic = YAFFS_MAGIC;
1272                         dsc->dirObj = obj;
1273                         strncpy(dsc->name,dirname,NAME_MAX);
1274                         INIT_LIST_HEAD(&dsc->others);
1275                         
1276                         if(!search_contexts.next)
1277                                 INIT_LIST_HEAD(&search_contexts);
1278                                 
1279                         list_add(&dsc->others,&search_contexts);        
1280                         yaffsfs_SetDirRewound(dsc);             }
1281         
1282         }
1283         
1284         yaffsfs_Unlock();
1285         
1286         return dir;
1287 }
1288
1289 struct yaffs_dirent *yaffs_readdir(yaffs_DIR *dirp)
1290 {
1291         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
1292         struct yaffs_dirent *retVal = NULL;
1293                 
1294         yaffsfs_Lock();
1295         
1296         if(dsc && dsc->magic == YAFFS_MAGIC){
1297                 yaffsfs_SetError(0);
1298                 if(dsc->nextReturn){
1299                         dsc->de.d_ino = yaffs_GetEquivalentObject(dsc->nextReturn)->objectId;
1300                         dsc->de.d_dont_use = (unsigned)dsc->nextReturn;
1301                         dsc->de.d_off = dsc->offset++;
1302                         yaffs_GetObjectName(dsc->nextReturn,dsc->de.d_name,NAME_MAX);
1303                         if(strlen(dsc->de.d_name) == 0)
1304                         {
1305                                 // this should not happen!
1306                                 strcpy(dsc->de.d_name,"zz");
1307                         }
1308                         dsc->de.d_reclen = sizeof(struct yaffs_dirent);
1309                         retVal = &dsc->de;
1310                         yaffsfs_DirAdvance(dsc);
1311                 } else
1312                         retVal = NULL;
1313         }
1314         else
1315         {
1316                 yaffsfs_SetError(-EBADF);
1317         }
1318         
1319         yaffsfs_Unlock();
1320         
1321         return retVal;
1322         
1323 }
1324
1325
1326 void yaffs_rewinddir(yaffs_DIR *dirp)
1327 {
1328         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
1329         
1330         yaffsfs_Lock();
1331         
1332         yaffsfs_SetDirRewound(dsc);
1333
1334         yaffsfs_Unlock();
1335 }
1336
1337
1338 int yaffs_closedir(yaffs_DIR *dirp)
1339 {
1340         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
1341                 
1342         yaffsfs_Lock();
1343         dsc->magic = 0;
1344         list_del(&dsc->others); /* unhook from list */
1345         YFREE(dsc);
1346         yaffsfs_Unlock();
1347         return 0;
1348 }
1349
1350 // end of directory stuff
1351
1352
1353 int yaffs_symlink(const char *oldpath, const char *newpath)
1354 {
1355         yaffs_Object *parent = NULL;
1356         yaffs_Object *obj;
1357         char *name;
1358         int retVal= -1;
1359         int mode = 0; // ignore for now
1360         
1361         yaffsfs_Lock();
1362         parent = yaffsfs_FindDirectory(NULL,newpath,&name,0);
1363         obj = yaffs_MknodSymLink(parent,name,mode,0,0,oldpath);
1364         if(obj)
1365         {
1366                 retVal = 0;
1367         }
1368         else
1369         {
1370                 yaffsfs_SetError(-ENOSPC); // just assume no space for now
1371                 retVal = -1;
1372         }
1373         
1374         yaffsfs_Unlock();
1375         
1376         return retVal;
1377         
1378 }
1379
1380 int yaffs_readlink(const char *path, char *buf, int bufsiz)
1381 {
1382         yaffs_Object *obj = NULL;
1383         int retVal;
1384
1385                 
1386         yaffsfs_Lock();
1387         
1388         obj = yaffsfs_FindObject(NULL,path,0);
1389         
1390         if(!obj)
1391         {
1392                 yaffsfs_SetError(-ENOENT);
1393                 retVal = -1;
1394         }
1395         else if(obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK)
1396         {
1397                 yaffsfs_SetError(-EINVAL);
1398                 retVal = -1;
1399         }
1400         else
1401         {
1402                 char *alias = obj->variant.symLinkVariant.alias;
1403                 memset(buf,0,bufsiz);
1404                 strncpy(buf,alias,bufsiz - 1);
1405                 retVal = 0;
1406         }
1407         yaffsfs_Unlock();
1408         return retVal;
1409 }
1410
1411 int yaffs_link(const char *oldpath, const char *newpath)
1412 {
1413         // Creates a link called newpath to existing oldpath
1414         yaffs_Object *obj = NULL;
1415         yaffs_Object *target = NULL;
1416         int retVal = 0;
1417
1418                 
1419         yaffsfs_Lock();
1420         
1421         obj = yaffsfs_FindObject(NULL,oldpath,0);
1422         target = yaffsfs_FindObject(NULL,newpath,0);
1423         
1424         if(!obj)
1425         {
1426                 yaffsfs_SetError(-ENOENT);
1427                 retVal = -1;
1428         }
1429         else if(target)
1430         {
1431                 yaffsfs_SetError(-EEXIST);
1432                 retVal = -1;
1433         }
1434         else    
1435         {
1436                 yaffs_Object *newdir = NULL;
1437                 yaffs_Object *link = NULL;
1438                 
1439                 char *newname;
1440                 
1441                 newdir = yaffsfs_FindDirectory(NULL,newpath,&newname,0);
1442                 
1443                 if(!newdir)
1444                 {
1445                         yaffsfs_SetError(-ENOTDIR);
1446                         retVal = -1;
1447                 }
1448                 else if(newdir->myDev != obj->myDev)
1449                 {
1450                         yaffsfs_SetError(-EXDEV);
1451                         retVal = -1;
1452                 }
1453                 if(newdir && strlen(newname) > 0)
1454                 {
1455                         link = yaffs_Link(newdir,newname,obj);
1456                         if(link)
1457                                 retVal = 0;
1458                         else
1459                         {
1460                                 yaffsfs_SetError(-ENOSPC);
1461                                 retVal = -1;
1462                         }
1463
1464                 }
1465         }
1466         yaffsfs_Unlock();
1467         
1468         return retVal;
1469 }
1470
1471 int yaffs_mknod(const char *pathname, mode_t mode, dev_t dev);
1472
1473 int yaffs_DumpDevStruct(const char *path)
1474 {
1475         char *rest;
1476         
1477         yaffs_Object *obj = yaffsfs_FindRoot(path,&rest);
1478         
1479         if(obj)
1480         {
1481                 yaffs_Device *dev = obj->myDev;
1482                 
1483                 printf("\n"
1484                            "nPageWrites.......... %d\n"
1485                            "nPageReads........... %d\n"
1486                            "nBlockErasures....... %d\n"
1487                            "nGCCopies............ %d\n"
1488                            "garbageCollections... %d\n"
1489                            "passiveGarbageColl'ns %d\n"
1490                            "\n",
1491                                 dev->nPageWrites,
1492                                 dev->nPageReads,
1493                                 dev->nBlockErasures,
1494                                 dev->nGCCopies,
1495                                 dev->garbageCollections,
1496                                 dev->passiveGarbageCollections
1497                 );
1498                 
1499         }
1500         return 0;
1501 }
1502