9ac08abb15be867cd69da6e466cd54523cfbf57a
[yaffs2.git] / direct / yaffsfs.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2010 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 "yportenv.h"
18 #include "yaffs_trace.h"
19
20 #include <string.h> /* for memset */
21
22 #define YAFFSFS_MAX_SYMLINK_DEREFERENCES 5
23
24 #ifndef NULL
25 #define NULL ((void *)0)
26 #endif
27
28
29 /* YAFFSFS_RW_SIZE must be a power of 2 */
30 #define YAFFSFS_RW_SHIFT (13)
31 #define YAFFSFS_RW_SIZE  (1<<YAFFSFS_RW_SHIFT)
32
33 /* Some forward references */
34 static yaffs_Object *yaffsfs_FindObject(yaffs_Object *relativeDirectory, const YCHAR *path, int symDepth);
35 static void yaffsfs_RemoveObjectCallback(yaffs_Object *obj);
36
37 unsigned int yaffs_wr_attempts;
38
39 /*
40  * Handle management.
41  * There are open inodes in yaffsfs_Inode.
42  * There are open handles in yaffsfs_Handle.
43  *
44  * Things are structured this way to be like the Linux VFS model
45  * so that interactions with the yaffs guts calls are similar.
46  * That means more common code paths and less special code.
47  * That means better testing etc.
48  */
49
50 typedef struct {
51         int count;      /* Number of handles accessing this inode */
52         yaffs_Object *iObj;
53 } yaffsfs_Inode;
54
55 typedef struct{
56         __u8    readOnly:1;
57         __u8    append:1;
58         int     inodeId:13;     /* Index to corresponding yaffsfs_Inode */
59         int     useCount:16;    /* Use count for this handle */
60         __u32 position;         /* current position in file */
61 }yaffsfs_Handle;
62
63 static yaffsfs_Inode yaffsfs_inode[YAFFSFS_N_HANDLES];
64 static yaffsfs_Handle yaffsfs_handle[YAFFSFS_N_HANDLES];
65
66 /*
67  * yaffsfs_InitHandle
68  * Inilitalise handle management on start-up.
69  */
70
71 static int yaffsfs_InitHandles(void)
72 {
73         int i;
74         memset(yaffsfs_inode,0,sizeof(yaffsfs_inode));
75         memset(yaffsfs_handle,0,sizeof(yaffsfs_handle));
76         for(i = 0; i < YAFFSFS_N_HANDLES; i++)
77                 yaffsfs_handle[i].inodeId = -1;
78
79         return 0;
80 }
81
82 yaffsfs_Handle *yaffsfs_GetHandlePointer(int h)
83 {
84         if(h < 0 || h >= YAFFSFS_N_HANDLES)
85                 return NULL;
86
87         return &yaffsfs_handle[h];
88 }
89
90 yaffsfs_Inode *yaffsfs_GetInodePointer(int handle)
91 {
92         yaffsfs_Handle *h = yaffsfs_GetHandlePointer(handle);
93
94         if(h && h->useCount > 0 && h->inodeId >= 0 && h->inodeId < YAFFSFS_N_HANDLES)
95                 return  &yaffsfs_inode[h->inodeId];
96
97         return NULL;
98 }
99
100 yaffs_Object *yaffsfs_GetHandleObject(int handle)
101 {
102         yaffsfs_Inode *in = yaffsfs_GetInodePointer(handle);
103
104         if(in)
105                 return in->iObj;
106
107         return NULL;
108 }
109
110 /*
111  * yaffsfs_GetInodeIdForObject
112  * Grab an inode entry when opening a new inode.
113  */
114
115 static int yaffsfs_GetInodeIdForObject(yaffs_Object *obj)
116 {
117         int i;
118         int ret = -1;
119         yaffsfs_Inode *in = NULL;
120         
121         if(obj)
122                 obj = yaffs_GetEquivalentObject(obj);
123
124         /* Look for it. If we can't find it then make one */
125         for(i = 0; i < YAFFSFS_N_HANDLES && ret < 0; i++){
126                 if(yaffsfs_inode[i].iObj == obj)
127                         ret = i;
128         }
129
130         for(i = 0; i < YAFFSFS_N_HANDLES && ret < 0; i++){
131                 if(!yaffsfs_inode[i].iObj)
132                         ret = i;
133         }
134         
135         
136         if(ret>=0){
137                 in = &yaffsfs_inode[ret];
138                 if(!in->iObj)
139                         in->count = 0;
140                 in->iObj = obj;
141                 in->count++;
142         }
143         
144         
145         return ret;
146 }
147
148 static void yaffsfs_ReleaseInode(yaffsfs_Inode *in)
149 {
150         yaffs_Object *obj;
151         
152         obj = in->iObj;
153
154         if(obj->unlinked)
155                 yaffs_DeleteObject(obj);
156         
157         obj->myInode = NULL;
158         in->iObj = NULL;
159
160 }
161
162 static void yaffsfs_PutInode(int inodeId)
163 {
164         if(inodeId >= 0 && inodeId < YAFFSFS_N_HANDLES){
165                 yaffsfs_Inode *in = & yaffsfs_inode[inodeId];
166                 in->count--;
167                 if(in->count <= 0)
168                         yaffsfs_ReleaseInode(in);
169         }       
170 }
171
172
173 /*
174  * yaffsfs_GetHandle
175  * Grab a handle (when opening a file)
176  */
177
178 static int yaffsfs_GetNewHandle(void)
179 {
180         int i;
181         yaffsfs_Handle *h;
182
183         for(i = 0; i < YAFFSFS_N_HANDLES; i++){
184                 h = yaffsfs_GetHandlePointer(i);
185                 if(!h){
186                         /* todo bug: should never happen */
187                 }
188                 if(h->useCount < 1){
189                         memset(h,0,sizeof(yaffsfs_Handle));
190                         h->inodeId=-1;
191                         h->useCount=1;
192                         return i;
193                 }
194         }
195         return -1;
196 }
197
198 /*
199  * yaffs_GetHandle
200  * Increase use of handle when reading/writing a file
201  */
202 static int yaffsfs_GetHandle(int handle)
203 {
204         yaffsfs_Handle *h = yaffsfs_GetHandlePointer(handle);
205
206         if(h && h->useCount > 0){       
207                 h->useCount++;
208         }
209         return 0;
210 }
211
212 /*
213  * yaffs_PutHandle
214  * Let go of a handle when closing a file or aborting an open or
215  * ending a read or write.
216  */
217 static int yaffsfs_PutHandle(int handle)
218 {
219         yaffsfs_Handle *h = yaffsfs_GetHandlePointer(handle);
220
221         if(h && h->useCount > 0){       
222                 h->useCount--;
223                 if(h->useCount < 1){
224                         if(h->inodeId >= 0){
225                                 yaffsfs_PutInode(h->inodeId);
226                                 h->inodeId = -1;
227                         }
228                 }
229         }
230         return 0;
231 }
232
233
234
235
236 /*
237  *  Stuff to search for a directory from a path
238  */
239
240
241 int yaffsfs_Match(YCHAR a, YCHAR b)
242 {
243         /* case sensitive */
244         return (a == b);
245 }
246
247 int yaffsfs_IsPathDivider(YCHAR ch)
248 {
249         YCHAR *str = YAFFS_PATH_DIVIDERS;
250
251         while(*str){
252                 if(*str == ch)
253                         return 1;
254                 str++;
255         }
256
257         return 0;
258 }
259
260
261
262 YLIST_HEAD(yaffsfs_deviceList);
263
264 /*
265  * yaffsfs_FindDevice
266  * yaffsfs_FindRoot
267  * Scan the configuration list to find the root.
268  * Curveballs: Should match paths that end in '/' too
269  * Curveball2 Might have "/x/ and "/x/y". Need to return the longest match
270  */
271 static yaffs_Device *yaffsfs_FindDevice(const YCHAR *path, YCHAR **restOfPath)
272 {
273         struct ylist_head *cfg;
274         const YCHAR *leftOver;
275         const YCHAR *p;
276         yaffs_Device *retval = NULL;
277         yaffs_Device *dev = NULL;
278         int thisMatchLength;
279         int longestMatch = -1;
280         int matching;
281
282         /*
283          * Check all configs, choose the one that:
284          * 1) Actually matches a prefix (ie /a amd /abc will not match
285          * 2) Matches the longest.
286          */
287         ylist_for_each(cfg, &yaffsfs_deviceList){
288                 dev = ylist_entry(cfg, yaffs_Device, devList);
289                 leftOver = path;
290                 p = dev->param.name;
291                 thisMatchLength = 0;
292                 matching = 1;
293
294
295                 while(matching && *p && *leftOver){
296                         /* Skip over any /s */
297                         while(yaffsfs_IsPathDivider(*p))
298                               p++;
299
300                         /* Skip over any /s */
301                         while(yaffsfs_IsPathDivider(*leftOver))
302                               leftOver++;
303
304                         /* Now match the text part */
305                         while(matching &&
306                               *p && !yaffsfs_IsPathDivider(*p) &&
307                               *leftOver && !yaffsfs_IsPathDivider(*leftOver)){
308                                 if(yaffsfs_Match(*p,*leftOver)){
309                                         p++;
310                                         leftOver++;
311                                         thisMatchLength++;
312                                 } else {
313                                         matching = 0;
314                                 }
315                         }
316                 }
317
318                 /* Skip over any /s in leftOver */
319                 while(yaffsfs_IsPathDivider(*leftOver))
320                       leftOver++;
321
322                 // Skip over any /s in p
323                 while(yaffsfs_IsPathDivider(*p))
324                       p++;
325
326                 // p should now be at the end of the string (ie. fully matched)
327                 if(*p)
328                         matching = 0;
329
330                 if( matching && (thisMatchLength > longestMatch))
331                 {
332                         // Matched prefix
333                         *restOfPath = (YCHAR *)leftOver;
334                         retval = dev;
335                         longestMatch = thisMatchLength;
336                 }
337
338         }
339         return retval;
340 }
341
342 #if 0
343 static yaffs_Device *yaffsfs_FindDevice(const YCHAR *path, YCHAR **restOfPath)
344 {
345         yaffsfs_DeviceConfiguration *cfg = yaffsfs_configurationList;
346         const YCHAR *leftOver;
347         const YCHAR *p;
348         yaffs_Device *retval = NULL;
349         int thisMatchLength;
350         int longestMatch = -1;
351
352         /*
353          * Check all configs, choose the one that:
354          * 1) Actually matches a prefix (ie /a amd /abc will not match
355          * 2) Matches the longest.
356          */
357         while(cfg && cfg->prefix && cfg->dev){
358                 leftOver = path;
359                 p = cfg->prefix;
360                 thisMatchLength = 0;
361
362                 while(*p &&  /* unmatched part of prefix */
363                       !(yaffsfs_IsPathDivider(*p) && (p[1] == 0)) &&
364                       *leftOver && yaffsfs_Match(*p,*leftOver)){
365                         p++;
366                         leftOver++;
367                         thisMatchLength++;
368                 }
369
370
371                 if((!*p || (yaffsfs_IsPathDivider(*p) && (p[1] == 0))) &&  /* end of prefix */
372                    (!*leftOver || yaffsfs_IsPathDivider(*leftOver)) && /* no more in this path name part */
373                    (thisMatchLength > longestMatch)){
374                         /* Matched prefix */
375                         *restOfPath = (YCHAR *)leftOver;
376                         retval = cfg->dev;
377                         longestMatch = thisMatchLength;
378                 }
379                 cfg++;
380         }
381         return retval;
382 }
383 #endif
384
385 static yaffs_Object *yaffsfs_FindRoot(const YCHAR *path, YCHAR **restOfPath)
386 {
387
388         yaffs_Device *dev;
389
390         dev= yaffsfs_FindDevice(path,restOfPath);
391         if(dev && dev->isMounted){
392                 return dev->rootDir;
393         }
394         return NULL;
395 }
396
397 static yaffs_Object *yaffsfs_FollowLink(yaffs_Object *obj,int symDepth)
398 {
399
400         while(obj && obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK){
401                 YCHAR *alias = obj->variant.symLinkVariant.alias;
402
403                 if(yaffsfs_IsPathDivider(*alias))
404                         /* Starts with a /, need to scan from root up */
405                         obj = yaffsfs_FindObject(NULL,alias,symDepth++);
406                 else
407                         /* Relative to here, so use the parent of the symlink as a start */
408                         obj = yaffsfs_FindObject(obj->parent,alias,symDepth++);
409         }
410         return obj;
411 }
412
413
414 /*
415  * yaffsfs_FindDirectory
416  * Parse a path to determine the directory and the name within the directory.
417  *
418  * eg. "/data/xx/ff" --> puts name="ff" and returns the directory "/data/xx"
419  */
420 static yaffs_Object *yaffsfs_DoFindDirectory(yaffs_Object *startDir,
421                                 const YCHAR *path, YCHAR **name, int symDepth)
422 {
423         yaffs_Object *dir;
424         YCHAR *restOfPath;
425         YCHAR str[YAFFS_MAX_NAME_LENGTH+1];
426         int i;
427
428         if(symDepth > YAFFSFS_MAX_SYMLINK_DEREFERENCES)
429                 return NULL;
430
431         if(startDir){
432                 dir = startDir;
433                 restOfPath = (YCHAR *)path;
434         }
435         else
436                 dir = yaffsfs_FindRoot(path,&restOfPath);
437
438         while(dir){
439                 /*
440                  * parse off /.
441                  * curve ball: also throw away surplus '/'
442                  * eg. "/ram/x////ff" gets treated the same as "/ram/x/ff"
443                  */
444                 while(yaffsfs_IsPathDivider(*restOfPath))
445                         restOfPath++; /* get rid of '/' */
446
447                 *name = restOfPath;
448                 i = 0;
449
450                 while(*restOfPath && !yaffsfs_IsPathDivider(*restOfPath)){
451                         if (i < YAFFS_MAX_NAME_LENGTH){
452                                 str[i] = *restOfPath;
453                                 str[i+1] = '\0';
454                                 i++;
455                         }
456                         restOfPath++;
457                 }
458
459                 if(!*restOfPath)
460                         /* got to the end of the string */
461                         return dir;
462                 else{
463                         if(yaffs_strcmp(str,_Y(".")) == 0)
464                         {
465                                 /* Do nothing */
466                         }
467                         else if(yaffs_strcmp(str,_Y("..")) == 0)
468                                 dir = dir->parent;
469                         else{
470                                 dir = yaffs_FindObjectByName(dir,str);
471
472                                 while(dir && dir->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
473                                         dir = yaffsfs_FollowLink(dir,symDepth);
474
475
476                                 if(dir && dir->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
477                                         dir = NULL;
478                         }
479                 }
480         }
481         /* directory did not exist. */
482         return NULL;
483 }
484
485 static yaffs_Object *yaffsfs_FindDirectory(yaffs_Object *relativeDirectory,
486                                         const YCHAR *path,YCHAR **name,int symDepth)
487 {
488         return yaffsfs_DoFindDirectory(relativeDirectory,path,name,symDepth);
489 }
490
491 /*
492  * yaffsfs_FindObject turns a path for an existing object into the object
493  */
494 static yaffs_Object *yaffsfs_FindObject(yaffs_Object *relativeDirectory, const YCHAR *path,int symDepth)
495 {
496         yaffs_Object *dir;
497         YCHAR *name;
498
499         dir = yaffsfs_FindDirectory(relativeDirectory,path,&name,symDepth);
500
501         if(dir && *name)
502                 return yaffs_FindObjectByName(dir,name);
503
504         return dir;
505 }
506
507
508 int yaffs_dup(int fd)
509 {
510         int newHandle = -1;
511         yaffsfs_Handle *oldPtr = NULL;
512         yaffsfs_Handle *newPtr = NULL;
513
514         yaffsfs_Lock();
515
516         oldPtr = yaffsfs_GetHandlePointer(fd);
517         if(oldPtr && oldPtr->useCount > 0)
518                 newHandle = yaffsfs_GetNewHandle();
519         if(newHandle >= 0)
520                 newPtr = yaffsfs_GetHandlePointer(newHandle);
521
522         if(newPtr){
523                 *newPtr = *oldPtr;
524                 return newHandle;
525         }
526
527         if(!oldPtr)
528                 yaffsfs_SetError(-EBADF);
529         else
530                 yaffsfs_SetError(-ENOMEM);
531
532         return -1;
533
534 }
535
536 int yaffs_open(const YCHAR *path, int oflag, int mode)
537 {
538         yaffs_Object *obj = NULL;
539         yaffs_Object *dir = NULL;
540         YCHAR *name;
541         int handle = -1;
542         yaffsfs_Handle *h = NULL;
543         int openDenied = 0;
544         int symDepth = 0;
545         int errorReported = 0;
546
547         /* O_EXCL only has meaning if O_CREAT is specified */
548         if(!(oflag & O_CREAT))
549                 oflag &= ~(O_EXCL);
550
551         /* O_TRUNC has no meaning if (O_CREAT | O_EXCL) is specified */
552         if( (oflag & O_CREAT) & (oflag & O_EXCL))
553                 oflag &= ~(O_TRUNC);
554
555         /* Todo: Are there any more flag combos to sanitise ? */
556
557
558         yaffsfs_Lock();
559
560         handle = yaffsfs_GetNewHandle();
561
562         if(handle >= 0){
563
564                 h = yaffsfs_GetHandlePointer(handle);
565
566
567                 /* try to find the exisiting object */
568                 obj = yaffsfs_FindObject(NULL,path,0);
569
570                 if(obj && obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
571                         obj = yaffsfs_FollowLink(obj,symDepth++);
572
573                 if(obj)
574                         obj = yaffs_GetEquivalentObject(obj);
575
576                 if(obj &&
577                         obj->variantType != YAFFS_OBJECT_TYPE_FILE &&
578                         obj->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
579                         obj = NULL;
580
581                 if(obj){
582
583                         /* The file already exists or it might be a directory */
584
585                         /* If it is a directory then we can't open it as a file */
586                         if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
587                                 openDenied = 1;
588                                 yaffsfs_SetError(-EISDIR);
589                                 errorReported = 1;
590                         }
591
592                         /* Open should fail if O_CREAT and O_EXCL are specified since
593                          * the file exists
594                          */
595                         if((oflag & O_EXCL) && (oflag & O_CREAT)){
596                                 openDenied = 1;
597                                 yaffsfs_SetError(-EEXIST);
598                                 errorReported = 1;
599                         }
600
601                         /* Check file permissions */
602                         if( (oflag & (O_RDWR | O_WRONLY)) == 0 &&     /* ie O_RDONLY */
603                            !(obj->yst_mode & S_IREAD))
604                                 openDenied = 1;
605
606                         if( (oflag & O_RDWR) &&
607                            !(obj->yst_mode & S_IREAD))
608                                 openDenied = 1;
609
610                         if( (oflag & (O_RDWR | O_WRONLY)) &&
611                            !(obj->yst_mode & S_IWRITE))
612                                 openDenied = 1;
613
614                 } else if((oflag & O_CREAT)) {
615                         /* Let's see if we can create this file */
616                         dir = yaffsfs_FindDirectory(NULL,path,&name,0);
617                         if(dir  && dir->myDev->readOnly){
618                                 yaffsfs_SetError(-EINVAL);
619                                 errorReported = 1;
620                         } else if(dir)
621                                 obj = yaffs_MknodFile(dir,name,mode,0,0);
622                         else {
623                                 yaffsfs_SetError(-ENOTDIR);
624                                 errorReported = 1;
625                         }
626                 }
627
628                 if(obj && !openDenied) {
629                         int inodeId = yaffsfs_GetInodeIdForObject(obj);
630
631                         if(inodeId<0) {
632                                 /*
633                                  * Todo: Fix any problem if inodes run out, though that
634                                  * can't happen if the number of inode items >= number of handles. 
635                                  */
636                         }
637                         
638                         h->inodeId = inodeId;
639                         h->readOnly = (oflag & (O_WRONLY | O_RDWR)) ? 0 : 1;
640                         h->append =  (oflag & O_APPEND) ? 1 : 0;
641                         h->position = 0;
642
643                         /* Hook inode to object */
644                         obj->myInode = (void*) &yaffsfs_inode[inodeId];
645
646                         if((oflag & O_TRUNC) && !h->readOnly)
647                                 yaffs_ResizeFile(obj,0);
648                 } else {
649                         yaffsfs_PutHandle(handle);
650                         if(!errorReported) {
651                                 yaffsfs_SetError(-EACCES);
652                                 errorReported = 1;
653                         }
654                         handle = -1;
655                 }
656         }
657
658         yaffsfs_Unlock();
659
660         return handle;
661 }
662
663 int yaffs_Dofsync(int fd,int datasync)
664 {
665         yaffsfs_Handle *h = NULL;
666         int retVal = 0;
667
668         yaffsfs_Lock();
669
670         h = yaffsfs_GetHandlePointer(fd);
671
672         if(h && h->useCount > 0)
673                 /* flush the file */
674                 yaffs_FlushFile(yaffsfs_inode[h->inodeId].iObj,1,datasync);
675         else {
676                 /* bad handle */
677                 yaffsfs_SetError(-EBADF);
678                 retVal = -1;
679         }
680
681         yaffsfs_Unlock();
682
683         return retVal;
684 }
685
686 int yaffs_fsync(int fd)
687 {
688         return yaffs_Dofsync(fd,0);
689 }
690
691 int yaffs_flush(int fd)
692 {
693         return yaffs_fsync(fd);
694 }
695
696 int yaffs_fdatasync(int fd)
697 {
698         return yaffs_Dofsync(fd,1);
699 }
700
701 int yaffs_close(int fd)
702 {
703         yaffsfs_Handle *h = NULL;
704         int retVal = 0;
705
706         yaffsfs_Lock();
707
708         h = yaffsfs_GetHandlePointer(fd);
709
710         if(h && h->useCount > 0) {
711                 /* clean up */
712                 yaffs_FlushFile(yaffsfs_inode[h->inodeId].iObj,1,0);
713                 yaffsfs_PutHandle(fd);
714                 retVal = 0;
715         } else {
716                 /* bad handle */
717                 yaffsfs_SetError(-EBADF);
718                 retVal = -1;
719         }
720
721         yaffsfs_Unlock();
722
723         return retVal;
724 }
725
726
727
728 int yaffsfs_do_read(int fd, void *vbuf, unsigned int nbyte, int isPread, int offset)
729 {
730         yaffsfs_Handle *h = NULL;
731         yaffs_Object *obj = NULL;
732         int pos = 0;
733         int startPos = 0;
734         int nRead = 0;
735         int nToRead = 0;
736         int totalRead = 0;
737         unsigned int maxRead;
738         __u8 *buf = (__u8 *)vbuf;
739
740         yaffsfs_Lock();
741         h = yaffsfs_GetHandlePointer(fd);
742         obj = yaffsfs_GetHandleObject(fd);
743
744         if(!h || !obj){
745                 /* bad handle */
746                 yaffsfs_SetError(-EBADF);
747                 totalRead = -1;
748         } else if( h && obj){
749                 if(isPread)
750                         startPos = offset;
751                 else
752                         startPos = h->position;
753
754                 pos = startPos;
755                                         
756                 if(yaffs_GetObjectFileLength(obj) > pos)
757                         maxRead = yaffs_GetObjectFileLength(obj) - pos;
758                 else
759                         maxRead = 0;
760
761                 if(nbyte > maxRead)
762                         nbyte = maxRead;
763
764
765                 yaffsfs_GetHandle(fd);
766
767                 while(nbyte > 0) {
768                         nToRead = YAFFSFS_RW_SIZE - (pos & (YAFFSFS_RW_SIZE -1));
769                         if(nToRead > nbyte)
770                                 nToRead = nbyte;
771                         nRead = yaffs_ReadDataFromFile(obj,buf,pos,nToRead);
772
773                         if(nRead > 0){
774                                 totalRead += nRead;
775                                 pos += nRead;
776                                 buf += nRead;
777                         }
778
779                         if(nRead == nToRead)
780                                 nbyte-=nRead;
781                         else
782                                 nbyte = 0; /* no more to read */
783                                         
784                                         
785                         if(nbyte > 0){
786                                 yaffsfs_Unlock();
787                                 yaffsfs_Lock();
788                         }
789
790                 }
791
792                 yaffsfs_PutHandle(fd);
793
794                 if(!isPread) {
795                         if(totalRead >= 0)
796                                 h->position = startPos + totalRead;
797                         else {
798                                         /* todo error */
799                         }
800                 }
801
802         }
803
804         yaffsfs_Unlock();
805
806         return (totalRead >= 0) ? totalRead : -1;
807
808 }
809
810 int yaffs_read(int fd, void *buf, unsigned int nbyte)
811 {
812         return yaffsfs_do_read(fd, buf, nbyte, 0, 0);
813 }
814
815 int yaffs_pread(int fd, void *buf, unsigned int nbyte, unsigned int offset)
816 {
817         return yaffsfs_do_read(fd, buf, nbyte, 1, offset);
818 }
819
820 int yaffsfs_do_write(int fd, const void *vbuf, unsigned int nbyte, int isPwrite, int offset)
821 {
822         yaffsfs_Handle *h = NULL;
823         yaffs_Object *obj = NULL;
824         int pos = 0;
825         int startPos = 0;
826         int nWritten = 0;
827         int totalWritten = 0;
828         int writeThrough = 0;
829         int nToWrite = 0;
830         const __u8 *buf = (const __u8 *)vbuf;
831
832         yaffsfs_Lock();
833         h = yaffsfs_GetHandlePointer(fd);
834         obj = yaffsfs_GetHandleObject(fd);
835
836         if(!h || !obj){
837                 /* bad handle */
838                 yaffsfs_SetError(-EBADF);
839                 totalWritten = -1;
840         } else if( h && obj && (h->readOnly || obj->myDev->readOnly)){
841                 yaffsfs_SetError(-EINVAL);
842                 totalWritten=-1;
843         } else if( h && obj){
844                 if(h->append)
845                         startPos = yaffs_GetObjectFileLength(obj);
846                 else if(isPwrite)
847                         startPos = offset;
848                 else
849                         startPos = h->position;
850
851                 yaffsfs_GetHandle(fd);
852                 pos = startPos;
853                 while(nbyte > 0) {
854                         nToWrite = YAFFSFS_RW_SIZE - (pos & (YAFFSFS_RW_SIZE -1));
855                         if(nToWrite > nbyte)
856                                 nToWrite = nbyte;
857
858                         nWritten = yaffs_WriteDataToFile(obj,buf,pos,nToWrite,writeThrough);
859                         if(nWritten > 0){
860                                 totalWritten += nWritten;
861                                 pos += nWritten;
862                                 buf += nWritten;
863                         }
864
865                         if(nWritten == nToWrite)
866                                 nbyte -= nToWrite;
867                         else
868                                 nbyte = 0;
869
870                         if(nWritten < 1 && totalWritten < 1){
871                                 yaffsfs_SetError(-ENOSPC);
872                                 totalWritten = -1;
873                         }
874
875                         if(nbyte > 0){
876                                 yaffsfs_Unlock();
877                                 yaffsfs_Lock();
878                         }
879                 }
880
881                 yaffsfs_PutHandle(fd);
882
883                 if(!isPwrite){
884                         if(totalWritten > 0)
885                                 h->position = startPos + totalWritten;
886                         else {
887                                 /* todo error */
888                         }
889                 }
890         }
891
892         yaffsfs_Unlock();
893
894         return (totalWritten >= 0) ? totalWritten : -1;
895 }
896
897 int yaffs_write(int fd, const void *buf, unsigned int nbyte)
898 {
899         return yaffsfs_do_write(fd, buf, nbyte, 0, 0);
900 }
901
902 int yaffs_pwrite(int fd, const void *buf, unsigned int nbyte, unsigned int offset)
903 {
904         return yaffsfs_do_write(fd, buf, nbyte, 1, offset);
905 }
906
907
908 int yaffs_truncate(const YCHAR *path,off_t newSize)
909 {
910         yaffs_Object *obj = NULL;
911         int result = YAFFS_FAIL;
912
913         yaffsfs_Lock();
914
915         obj = yaffsfs_FindObject(NULL,path,0);
916         if(obj)
917                 obj = yaffs_GetEquivalentObject(obj);
918
919         if(!obj)
920                 yaffsfs_SetError(-ENOENT);
921         else if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
922                 yaffsfs_SetError(-EISDIR);
923         else if(obj->myDev->readOnly)
924                 yaffsfs_SetError(-EINVAL);
925         else
926                 result = yaffs_ResizeFile(obj,newSize);
927
928         yaffsfs_Unlock();
929
930
931         return (result) ? 0 : -1;
932 }
933
934 int yaffs_ftruncate(int fd, off_t newSize)
935 {
936         yaffsfs_Handle *h = NULL;
937         yaffs_Object *obj = NULL;
938         int result = 0;
939
940         yaffsfs_Lock();
941         h = yaffsfs_GetHandlePointer(fd);
942         obj = yaffsfs_GetHandleObject(fd);
943
944         if(!h || !obj)
945                 /* bad handle */
946                 yaffsfs_SetError(-EBADF);
947         else if(obj->myDev->readOnly)
948                 yaffsfs_SetError(-EINVAL);
949         else
950                 /* resize the file */
951                 result = yaffs_ResizeFile(obj,newSize);
952         yaffsfs_Unlock();
953
954
955         return (result) ? 0 : -1;
956
957 }
958
959 off_t yaffs_lseek(int fd, off_t offset, int whence)
960 {
961         yaffsfs_Handle *h = NULL;
962         yaffs_Object *obj = NULL;
963         int pos = -1;
964         int fSize = -1;
965
966         yaffsfs_Lock();
967         h = yaffsfs_GetHandlePointer(fd);
968         obj = yaffsfs_GetHandleObject(fd);
969
970         if(!h || !obj)
971                 /* bad handle */
972                 yaffsfs_SetError(-EBADF);
973         else if(whence == SEEK_SET){
974                 if(offset >= 0)
975                         pos = offset;
976         }
977         else if(whence == SEEK_CUR) {
978                 if( (h->position + offset) >= 0)
979                         pos = (h->position + offset);
980         }
981         else if(whence == SEEK_END) {
982                 fSize = yaffs_GetObjectFileLength(obj);
983                 if(fSize >= 0 && (fSize + offset) >= 0)
984                         pos = fSize + offset;
985         }
986
987         if(pos >= 0)
988                 h->position = pos;
989         else {
990                 /* todo error */
991         }
992
993
994         yaffsfs_Unlock();
995
996         return pos;
997 }
998
999
1000 int yaffsfs_DoUnlink(const YCHAR *path,int isDirectory)
1001 {
1002         yaffs_Object *dir = NULL;
1003         yaffs_Object *obj = NULL;
1004         YCHAR *name;
1005         int result = YAFFS_FAIL;
1006
1007         yaffsfs_Lock();
1008
1009         obj = yaffsfs_FindObject(NULL,path,0);
1010         dir = yaffsfs_FindDirectory(NULL,path,&name,0);
1011         if(!dir)
1012                 yaffsfs_SetError(-ENOTDIR);
1013         else if(!obj)
1014                 yaffsfs_SetError(-ENOENT);
1015         else if(obj->myDev->readOnly)
1016                 yaffsfs_SetError(-EINVAL);
1017         else if(!isDirectory && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1018                 yaffsfs_SetError(-EISDIR);
1019         else if(isDirectory && obj->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
1020                 yaffsfs_SetError(-ENOTDIR);
1021         else {
1022                 result = yaffs_Unlink(dir,name);
1023
1024                 if(result == YAFFS_FAIL && isDirectory)
1025                         yaffsfs_SetError(-ENOTEMPTY);
1026         }
1027
1028         yaffsfs_Unlock();
1029
1030         /* todo error */
1031
1032         return (result == YAFFS_FAIL) ? -1 : 0;
1033 }
1034
1035
1036 int yaffs_rmdir(const YCHAR *path)
1037 {
1038         return yaffsfs_DoUnlink(path,1);
1039 }
1040
1041 int yaffs_unlink(const YCHAR *path)
1042 {
1043         return yaffsfs_DoUnlink(path,0);
1044 }
1045
1046 int yaffs_rename(const YCHAR *oldPath, const YCHAR *newPath)
1047 {
1048         yaffs_Object *olddir = NULL;
1049         yaffs_Object *newdir = NULL;
1050         yaffs_Object *obj = NULL;
1051         YCHAR *oldname;
1052         YCHAR *newname;
1053         int result= YAFFS_FAIL;
1054         int renameAllowed = 1;
1055
1056         yaffsfs_Lock();
1057
1058         olddir = yaffsfs_FindDirectory(NULL,oldPath,&oldname,0);
1059         newdir = yaffsfs_FindDirectory(NULL,newPath,&newname,0);
1060         obj = yaffsfs_FindObject(NULL,oldPath,0);
1061
1062         if(!olddir || !newdir || !obj) {
1063                 /* bad file */
1064                 yaffsfs_SetError(-EBADF);
1065                 renameAllowed = 0;
1066         } else if(obj->myDev->readOnly){
1067                 yaffsfs_SetError(-EINVAL);
1068                 renameAllowed = 0;
1069         } else if(olddir->myDev != newdir->myDev) {
1070                 /* oops must be on same device */
1071                 /* todo error */
1072                 yaffsfs_SetError(-EXDEV);
1073                 renameAllowed = 0;
1074         } else if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1075                 /*
1076                  * It is a directory, check that it is not being renamed to
1077                  * being its own decendent.
1078                  * Do this by tracing from the new directory back to the root, checking for obj
1079                  */
1080
1081                 yaffs_Object *xx = newdir;
1082
1083                 while( renameAllowed && xx){
1084                         if(xx == obj)
1085                                 renameAllowed = 0;
1086                         xx = xx->parent;
1087                 }
1088                 if(!renameAllowed)
1089                         yaffsfs_SetError(-EACCES);
1090         }
1091
1092         if(renameAllowed)
1093                 result = yaffs_RenameObject(olddir,oldname,newdir,newname);
1094
1095         yaffsfs_Unlock();
1096
1097         return (result == YAFFS_FAIL) ? -1 : 0;
1098 }
1099
1100
1101 static int yaffsfs_DoStat(yaffs_Object *obj,struct yaffs_stat *buf)
1102 {
1103         int retVal = -1;
1104
1105         if(obj)
1106                 obj = yaffs_GetEquivalentObject(obj);
1107
1108         if(obj && buf){
1109                 buf->st_dev = (int)obj->myDev->osContext;
1110                 buf->st_ino = obj->objectId;
1111                 buf->st_mode = obj->yst_mode & ~S_IFMT; /* clear out file type bits */
1112
1113                 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1114                         buf->st_mode |= S_IFDIR;
1115                 else if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
1116                         buf->st_mode |= S_IFLNK;
1117                 else if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
1118                         buf->st_mode |= S_IFREG;
1119
1120                 buf->st_nlink = yaffs_GetObjectLinkCount(obj);
1121                 buf->st_uid = 0;
1122                 buf->st_gid = 0;;
1123                 buf->st_rdev = obj->yst_rdev;
1124                 buf->st_size = yaffs_GetObjectFileLength(obj);
1125                 buf->st_blksize = obj->myDev->nDataBytesPerChunk;
1126                 buf->st_blocks = (buf->st_size + buf->st_blksize -1)/buf->st_blksize;
1127 #if CONFIG_YAFFS_WINCE
1128                 buf->yst_wince_atime[0] = obj->win_atime[0];
1129                 buf->yst_wince_atime[1] = obj->win_atime[1];
1130                 buf->yst_wince_ctime[0] = obj->win_ctime[0];
1131                 buf->yst_wince_ctime[1] = obj->win_ctime[1];
1132                 buf->yst_wince_mtime[0] = obj->win_mtime[0];
1133                 buf->yst_wince_mtime[1] = obj->win_mtime[1];
1134 #else
1135                 buf->yst_atime = obj->yst_atime;
1136                 buf->yst_ctime = obj->yst_ctime;
1137                 buf->yst_mtime = obj->yst_mtime;
1138 #endif
1139                 retVal = 0;
1140         }
1141         return retVal;
1142 }
1143
1144 static int yaffsfs_DoStatOrLStat(const YCHAR *path, struct yaffs_stat *buf,int doLStat)
1145 {
1146         yaffs_Object *obj;
1147
1148         int retVal = -1;
1149
1150         yaffsfs_Lock();
1151         obj = yaffsfs_FindObject(NULL,path,0);
1152
1153         if(!doLStat && obj)
1154                 obj = yaffsfs_FollowLink(obj,0);
1155
1156         if(obj)
1157                 retVal = yaffsfs_DoStat(obj,buf);
1158         else
1159                 /* todo error not found */
1160                 yaffsfs_SetError(-ENOENT);
1161
1162         yaffsfs_Unlock();
1163
1164         return retVal;
1165
1166 }
1167
1168 int yaffs_stat(const YCHAR *path, struct yaffs_stat *buf)
1169 {
1170         return yaffsfs_DoStatOrLStat(path,buf,0);
1171 }
1172
1173 int yaffs_lstat(const YCHAR *path, struct yaffs_stat *buf)
1174 {
1175         return yaffsfs_DoStatOrLStat(path,buf,1);
1176 }
1177
1178 int yaffs_fstat(int fd, struct yaffs_stat *buf)
1179 {
1180         yaffs_Object *obj;
1181
1182         int retVal = -1;
1183
1184         yaffsfs_Lock();
1185         obj = yaffsfs_GetHandleObject(fd);
1186
1187         if(obj)
1188                 retVal = yaffsfs_DoStat(obj,buf);
1189         else
1190                 /* bad handle */
1191                 yaffsfs_SetError(-EBADF);
1192
1193         yaffsfs_Unlock();
1194
1195         return retVal;
1196 }
1197
1198 #ifndef CONFIG_YAFFS_WINCE
1199 /* xattrib functions */
1200
1201
1202 static int yaffs_do_setxattr(const YCHAR *path, const char *name, const void *data, int size, int flags, int follow)
1203 {
1204         yaffs_Object *obj;
1205
1206         int retVal = -1;
1207
1208         yaffsfs_Lock();
1209         obj = yaffsfs_FindObject(NULL,path,0);
1210
1211         if(follow)
1212                 obj = yaffsfs_FollowLink(obj,0);
1213
1214         if(obj) {
1215                 retVal = yaffs_SetXAttribute(obj,name,data,size,flags);
1216                 if(retVal< 0){
1217                         yaffsfs_SetError(retVal);
1218                         retVal = -1;
1219                 }
1220         } else
1221                 /* todo error not found */
1222                 yaffsfs_SetError(-ENOENT);
1223
1224         yaffsfs_Unlock();
1225
1226         return retVal;
1227
1228 }
1229
1230 int yaffs_setxattr(const YCHAR *path, const char *name, const void *data, int size, int flags)
1231 {
1232         return yaffs_do_setxattr(path, name, data, size, flags, 1);
1233 }
1234
1235 int yaffs_lsetxattr(const YCHAR *path, const char *name, const void *data, int size, int flags)
1236 {
1237         return yaffs_do_setxattr(path, name, data, size, flags, 0);
1238 }
1239
1240
1241
1242 int yaffs_fsetxattr(int fd, const char *name, const void *data, int size, int flags)
1243 {
1244         yaffs_Object *obj;
1245
1246         int retVal = -1;
1247
1248         yaffsfs_Lock();
1249         obj = yaffsfs_GetHandleObject(fd);
1250
1251         if(obj) {
1252                 retVal = yaffs_SetXAttribute(obj,name,data,size,flags);
1253                 if(retVal< 0){
1254                         yaffsfs_SetError(retVal);
1255                         retVal = -1;
1256                 }
1257         } else
1258                 /* bad handle */
1259                 yaffsfs_SetError(-EBADF);
1260
1261         yaffsfs_Unlock();
1262
1263         return retVal;
1264 }
1265
1266 static int yaffs_do_getxattr(const YCHAR *path, const char *name, void *data, int size, int follow)
1267 {
1268         yaffs_Object *obj;
1269
1270         int retVal = -1;
1271
1272         yaffsfs_Lock();
1273         obj = yaffsfs_FindObject(NULL,path,0);
1274
1275         if(follow)
1276                 obj = yaffsfs_FollowLink(obj,0);
1277
1278         if(obj) {
1279                 retVal = yaffs_GetXAttribute(obj,name,data,size);
1280                 if(retVal< 0){
1281                         yaffsfs_SetError(retVal);
1282                         retVal = -1;
1283                 }
1284         } else
1285                 /* todo error not found */
1286                 yaffsfs_SetError(-ENOENT);
1287
1288         yaffsfs_Unlock();
1289
1290         return retVal;
1291
1292 }
1293
1294 int yaffs_getxattr(const YCHAR *path, const char *name, void *data, int size)
1295 {
1296         return yaffs_do_getxattr( path, name, data, size, 1);
1297 }
1298 int yaffs_lgetxattr(const YCHAR *path, const char *name, void *data, int size)
1299 {
1300         return yaffs_do_getxattr( path, name, data, size, 0);
1301 }
1302
1303
1304
1305 int yaffs_fgetxattr(int fd, const char *name, void *data, int size)
1306 {
1307         yaffs_Object *obj;
1308
1309         int retVal = -1;
1310
1311         yaffsfs_Lock();
1312         obj = yaffsfs_GetHandleObject(fd);
1313
1314         if(obj) {
1315                 retVal = yaffs_GetXAttribute(obj,name,data,size);
1316                 if(retVal< 0){
1317                         yaffsfs_SetError(retVal);
1318                         retVal = -1;
1319                 }
1320         } else
1321                 /* bad handle */
1322                 yaffsfs_SetError(-EBADF);
1323
1324         yaffsfs_Unlock();
1325
1326         return retVal;
1327 }
1328
1329 static int yaffs_do_listxattr(const YCHAR *path, char *data, int size, int follow)
1330 {
1331         yaffs_Object *obj;
1332
1333         int retVal = -1;
1334
1335         yaffsfs_Lock();
1336         obj = yaffsfs_FindObject(NULL,path,0);
1337
1338         if(follow)
1339                 obj = yaffsfs_FollowLink(obj,0);
1340
1341         if(obj) {
1342                 retVal = yaffs_ListXAttributes(obj, data,size);
1343                 if(retVal< 0){
1344                         yaffsfs_SetError(retVal);
1345                         retVal = -1;
1346                 }
1347         } else
1348                 /* todo error not found */
1349                 yaffsfs_SetError(-ENOENT);
1350
1351         yaffsfs_Unlock();
1352
1353         return retVal;
1354
1355 }
1356
1357 int yaffs_listxattr(const YCHAR *path, char *data, int size)
1358 {
1359         return yaffs_do_listxattr(path, data, size, 1);
1360 }
1361
1362 int yaffs_llistxattr(const YCHAR *path, char *data, int size)
1363 {
1364         return yaffs_do_listxattr(path, data, size, 0);
1365 }
1366
1367 int yaffs_flistxattr(int fd, char *data, int size)
1368 {
1369         yaffs_Object *obj;
1370
1371         int retVal = -1;
1372
1373         yaffsfs_Lock();
1374         obj = yaffsfs_GetHandleObject(fd);
1375
1376         if(obj) {
1377                 retVal = yaffs_ListXAttributes(obj,data,size);
1378                 if(retVal< 0){
1379                         yaffsfs_SetError(retVal);
1380                         retVal = -1;
1381                 }
1382         } else
1383                 /* bad handle */
1384                 yaffsfs_SetError(-EBADF);
1385
1386         yaffsfs_Unlock();
1387
1388         return retVal;
1389 }
1390
1391 static int yaffs_do_removexattr(const YCHAR *path, const char *name, int follow)
1392 {
1393         yaffs_Object *obj;
1394
1395         int retVal = -1;
1396
1397         yaffsfs_Lock();
1398         obj = yaffsfs_FindObject(NULL,path,0);
1399
1400         if(follow)
1401                 obj = yaffsfs_FollowLink(obj,0);
1402
1403         if(obj) {
1404                 retVal = yaffs_RemoveXAttribute(obj,name);
1405                 if(retVal< 0){
1406                         yaffsfs_SetError(retVal);
1407                         retVal = -1;
1408                 }
1409         } else
1410                 /* todo error not found */
1411                 yaffsfs_SetError(-ENOENT);
1412
1413         yaffsfs_Unlock();
1414
1415         return retVal;
1416
1417 }
1418
1419 int yaffs_removexattr(const YCHAR *path, const char *name)
1420 {
1421         return yaffs_do_removexattr(path, name, 1);
1422 }
1423
1424 int yaffs_lremovexattr(const YCHAR *path, const char *name)
1425 {
1426         return yaffs_do_removexattr(path, name, 0);
1427 }
1428
1429 int yaffs_fremovexattr(int fd, const char *name)
1430 {
1431         yaffs_Object *obj;
1432
1433         int retVal = -1;
1434
1435         yaffsfs_Lock();
1436         obj = yaffsfs_GetHandleObject(fd);
1437
1438         if(obj){
1439                 retVal = yaffs_RemoveXAttribute(obj,name);
1440                 if(retVal< 0){
1441                         yaffsfs_SetError(retVal);
1442                         retVal = -1;
1443                 }
1444         }else
1445                 /* bad handle */
1446                 yaffsfs_SetError(-EBADF);
1447
1448         yaffsfs_Unlock();
1449
1450         return retVal;
1451 }
1452 #endif
1453
1454 #ifdef CONFIG_YAFFS_WINCE
1455 int yaffs_get_wince_times(int fd, unsigned *wctime, unsigned *watime, unsigned *wmtime)
1456 {
1457         yaffs_Object *obj;
1458
1459         int retVal = -1;
1460
1461         yaffsfs_Lock();
1462         obj = yaffsfs_GetHandleObject(fd);
1463
1464         if(obj){
1465
1466                 if(wctime){
1467                         wctime[0] = obj->win_ctime[0];
1468                         wctime[1] = obj->win_ctime[1];
1469                 }
1470                 if(watime){
1471                         watime[0] = obj->win_atime[0];
1472                         watime[1] = obj->win_atime[1];
1473                 }
1474                 if(wmtime){
1475                         wmtime[0] = obj->win_mtime[0];
1476                         wmtime[1] = obj->win_mtime[1];
1477                 }
1478
1479
1480                 retVal = 0;
1481         } else
1482                 /*  bad handle */
1483                 yaffsfs_SetError(-EBADF);               
1484         
1485         yaffsfs_Unlock();
1486         
1487         return retVal;
1488 }
1489
1490
1491 int yaffs_set_wince_times(int fd, 
1492                                                   const unsigned *wctime, 
1493                                                   const unsigned *watime, 
1494                                                   const unsigned *wmtime)
1495 {
1496         yaffs_Object *obj;
1497         int result;
1498         int retVal = -1;
1499
1500         yaffsfs_Lock();
1501         obj = yaffsfs_GetHandleObject(fd);
1502
1503         if(obj){
1504
1505                 if(wctime){
1506                         obj->win_ctime[0] = wctime[0];
1507                         obj->win_ctime[1] = wctime[1];
1508                 }
1509                 if(watime){
1510                         obj->win_atime[0] = watime[0];
1511                         obj->win_atime[1] = watime[1];
1512                 }
1513                 if(wmtime){
1514                         obj->win_mtime[0] = wmtime[0];
1515                         obj->win_mtime[1] = wmtime[1];
1516                 }
1517
1518                 obj->dirty = 1;
1519                 result = yaffs_FlushFile(obj,0,0);
1520                 retVal = 0;
1521         } else
1522                 /* bad handle */
1523                 yaffsfs_SetError(-EBADF);
1524
1525         yaffsfs_Unlock();
1526
1527         return retVal;
1528 }
1529
1530 #endif
1531
1532
1533 static int yaffsfs_DoChMod(yaffs_Object *obj,mode_t mode)
1534 {
1535         int result = -1;
1536
1537         if(obj)
1538                 obj = yaffs_GetEquivalentObject(obj);
1539
1540         if(obj) {
1541                 obj->yst_mode = mode;
1542                 obj->dirty = 1;
1543                 result = yaffs_FlushFile(obj,0,0);
1544         }
1545
1546         return result == YAFFS_OK ? 0 : -1;
1547 }
1548
1549
1550 int yaffs_access(const YCHAR *path, int amode)
1551 {
1552         yaffs_Object *obj;
1553
1554         int retval = 0;
1555
1556         yaffsfs_Lock();
1557         obj = yaffsfs_FindObject(NULL,path,0);
1558
1559         if(obj) {
1560                 int access_ok = 1;
1561
1562                 if((amode & R_OK) && !(obj->yst_mode & S_IREAD))
1563                         access_ok = 0;
1564                 if((amode & W_OK) && !(obj->yst_mode & S_IWRITE))
1565                         access_ok = 0;
1566                 if((amode & X_OK) && !(obj->yst_mode & S_IEXEC))
1567                         access_ok = 0;
1568
1569                 if(!access_ok) {
1570                         yaffsfs_SetError(-EACCES);
1571                         retval = -1;
1572                 }
1573         } else {
1574                 /* todo error not found */
1575                 yaffsfs_SetError(-ENOENT);
1576                 retval = -1;
1577         }
1578
1579         yaffsfs_Unlock();
1580
1581         return retval;
1582
1583 }
1584
1585
1586 int yaffs_chmod(const YCHAR *path, mode_t mode)
1587 {
1588         yaffs_Object *obj;
1589
1590         int retVal = -1;
1591
1592         yaffsfs_Lock();
1593         obj = yaffsfs_FindObject(NULL,path,0);
1594
1595         if(!obj)
1596                 yaffsfs_SetError(-ENOENT);
1597         else if(obj->myDev->readOnly)
1598                 yaffsfs_SetError(-EINVAL);
1599         else
1600                 retVal = yaffsfs_DoChMod(obj,mode);
1601
1602         yaffsfs_Unlock();
1603
1604         return retVal;
1605
1606 }
1607
1608
1609 int yaffs_fchmod(int fd, mode_t mode)
1610 {
1611         yaffs_Object *obj;
1612
1613         int retVal = -1;
1614
1615         yaffsfs_Lock();
1616         obj = yaffsfs_GetHandleObject(fd);
1617
1618         if(!obj)
1619                 yaffsfs_SetError(-ENOENT);
1620         else if(obj->myDev->readOnly)
1621                 yaffsfs_SetError(-EINVAL);
1622         else
1623                 retVal = yaffsfs_DoChMod(obj,mode);
1624
1625         yaffsfs_Unlock();
1626
1627         return retVal;
1628 }
1629
1630
1631 int yaffs_mkdir(const YCHAR *path, mode_t mode)
1632 {
1633         yaffs_Object *parent = NULL;
1634         yaffs_Object *dir = NULL;
1635         YCHAR *name;
1636         int retVal= -1;
1637
1638         yaffsfs_Lock();
1639         parent = yaffsfs_FindDirectory(NULL,path,&name,0);
1640         if(parent && yaffs_strnlen(name,5) == 0){
1641                 /* Trying to make the root itself */
1642                 yaffsfs_SetError(-EEXIST);
1643         } else if(parent && parent->myDev->readOnly){
1644                 yaffsfs_SetError(-EINVAL);
1645         } else {
1646                 if(parent)
1647                         dir = yaffs_MknodDirectory(parent,name,mode,0,0);
1648                 if(dir)
1649                         retVal = 0;
1650                 else {
1651                         if(!parent)
1652                                 yaffsfs_SetError(-ENOENT); /* missing path */
1653                         else if (yaffs_FindObjectByName(parent,name))
1654                                 yaffsfs_SetError(-EEXIST); /* the name already exists */
1655                         else
1656                                 yaffsfs_SetError(-ENOSPC); /* just assume no space */
1657                         retVal = -1;
1658                 }
1659         }
1660
1661         yaffsfs_Unlock();
1662
1663         return retVal;
1664 }
1665
1666 void * yaffs_getdev(const YCHAR *path)
1667 {
1668         yaffs_Device *dev=NULL;
1669         YCHAR *dummy;
1670         dev = yaffsfs_FindDevice(path,&dummy);
1671         return (void *)dev;
1672 }
1673
1674 int yaffs_mount2(const YCHAR *path,int readOnly)
1675 {
1676         int retVal=-1;
1677         int result=YAFFS_FAIL;
1678         yaffs_Device *dev=NULL;
1679         YCHAR *dummy;
1680
1681         T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Mounting %s" TENDSTR),path));
1682
1683         yaffsfs_Lock();
1684         dev = yaffsfs_FindDevice(path,&dummy);
1685         if(dev){
1686                 if(!dev->isMounted){
1687                         dev->readOnly = readOnly ? 1 : 0;
1688                         result = yaffs_GutsInitialise(dev);
1689                         if(result == YAFFS_FAIL)
1690                                 /* todo error - mount failed */
1691                                 yaffsfs_SetError(-ENOMEM);
1692                         retVal = result ? 0 : -1;
1693
1694                 }
1695                 else
1696                         /* todo error - already mounted. */
1697                         yaffsfs_SetError(-EBUSY);
1698         } else
1699                 /* todo error - no device */
1700                 yaffsfs_SetError(-ENODEV);
1701
1702         yaffsfs_Unlock();
1703         return retVal;
1704
1705 }
1706
1707 int yaffs_mount(const YCHAR *path)
1708 {
1709         return yaffs_mount2(path,0);
1710 }
1711
1712 int yaffs_sync(const YCHAR *path)
1713 {
1714         int retVal=-1;
1715         yaffs_Device *dev=NULL;
1716         YCHAR *dummy;
1717         
1718         yaffsfs_Lock();
1719         dev = yaffsfs_FindDevice(path,&dummy);
1720         if(dev){
1721                 if(dev->isMounted){
1722                         
1723                         yaffs_FlushEntireDeviceCache(dev);
1724                         yaffs_CheckpointSave(dev);
1725                         retVal = 0;
1726                         
1727                 } else
1728                         /* todo error - not mounted. */
1729                         yaffsfs_SetError(-EINVAL);
1730                         
1731         }else
1732                 /* todo error - no device */
1733                 yaffsfs_SetError(-ENODEV);
1734
1735         yaffsfs_Unlock();
1736         return retVal;  
1737 }
1738
1739
1740 int yaffs_remount(const YCHAR *path, int force, int readOnly)
1741 {
1742         int retVal=-1;
1743         yaffs_Device *dev=NULL;
1744         YCHAR *dummy;
1745
1746         yaffsfs_Lock();
1747         dev = yaffsfs_FindDevice(path,&dummy);
1748         if(dev){
1749                 if(dev->isMounted){
1750                         int i;
1751                         int inUse;
1752
1753                         yaffs_FlushEntireDeviceCache(dev);
1754
1755                         for(i = inUse = 0; i < YAFFSFS_N_HANDLES && !inUse && !force; i++){
1756                                 if(yaffsfs_handle[i].useCount>0 && yaffsfs_inode[yaffsfs_handle[i].inodeId].iObj->myDev == dev)
1757                                         inUse = 1; /* the device is in use, can't unmount */
1758                         }
1759
1760                         if(!inUse || force){
1761                                 if(readOnly)
1762                                         yaffs_CheckpointSave(dev);
1763                                 dev->readOnly =  readOnly ? 1 : 0;
1764                                 retVal = 0;
1765                         } else
1766                                 yaffsfs_SetError(-EBUSY);
1767
1768                 } else
1769                         yaffsfs_SetError(-EINVAL);
1770
1771         }
1772         else
1773                 yaffsfs_SetError(-ENODEV);
1774
1775         yaffsfs_Unlock();
1776         return retVal;
1777
1778 }
1779
1780 int yaffs_unmount2(const YCHAR *path, int force)
1781 {
1782         int retVal=-1;
1783         yaffs_Device *dev=NULL;
1784         YCHAR *dummy;
1785
1786         yaffsfs_Lock();
1787         dev = yaffsfs_FindDevice(path,&dummy);
1788         if(dev){
1789                 if(dev->isMounted){
1790                         int i;
1791                         int inUse;
1792
1793                         yaffs_FlushEntireDeviceCache(dev);
1794                         yaffs_CheckpointSave(dev);
1795
1796                         for(i = inUse = 0; i < YAFFSFS_N_HANDLES && !inUse; i++){
1797                                 if(yaffsfs_handle[i].useCount > 0 && yaffsfs_inode[yaffsfs_handle[i].inodeId].iObj->myDev == dev)
1798                                         inUse = 1; /* the device is in use, can't unmount */
1799                         }
1800
1801                         if(!inUse || force){
1802                                 yaffs_Deinitialise(dev);
1803
1804                                 retVal = 0;
1805                         } else
1806                                 /* todo error can't unmount as files are open */
1807                                 yaffsfs_SetError(-EBUSY);
1808
1809                 } else
1810                         /* todo error - not mounted. */
1811                         yaffsfs_SetError(-EINVAL);
1812
1813         }
1814         else
1815                 /* todo error - no device */
1816                 yaffsfs_SetError(-ENODEV);
1817
1818         yaffsfs_Unlock();
1819         return retVal;
1820
1821 }
1822
1823 int yaffs_unmount(const YCHAR *path)
1824 {
1825         return yaffs_unmount2(path,0);
1826 }
1827
1828 loff_t yaffs_freespace(const YCHAR *path)
1829 {
1830         loff_t retVal=-1;
1831         yaffs_Device *dev=NULL;
1832         YCHAR *dummy;
1833
1834         yaffsfs_Lock();
1835         dev = yaffsfs_FindDevice(path,&dummy);
1836         if(dev  && dev->isMounted){
1837                 retVal = yaffs_GetNumberOfFreeChunks(dev);
1838                 retVal *= dev->nDataBytesPerChunk;
1839
1840         } else
1841                 yaffsfs_SetError(-EINVAL);
1842
1843         yaffsfs_Unlock();
1844         return retVal;
1845 }
1846
1847 loff_t yaffs_totalspace(const YCHAR *path)
1848 {
1849         loff_t retVal=-1;
1850         yaffs_Device *dev=NULL;
1851         YCHAR *dummy;
1852
1853         yaffsfs_Lock();
1854         dev = yaffsfs_FindDevice(path,&dummy);
1855         if(dev  && dev->isMounted){
1856                 retVal = (dev->param.endBlock - dev->param.startBlock + 1) - dev->param.nReservedBlocks;
1857                 retVal *= dev->param.nChunksPerBlock;
1858                 retVal *= dev->nDataBytesPerChunk;
1859
1860         } else
1861                 yaffsfs_SetError(-EINVAL);
1862
1863         yaffsfs_Unlock();
1864         return retVal;
1865 }
1866
1867 int yaffs_inodecount(const YCHAR *path)
1868 {
1869         loff_t retVal= -1;
1870         yaffs_Device *dev=NULL;
1871         YCHAR *dummy;
1872
1873         yaffsfs_Lock();
1874         dev = yaffsfs_FindDevice(path,&dummy);
1875         if(dev  && dev->isMounted) {
1876            int nObjects = dev->nObjects;
1877            if(nObjects > dev->nHardLinks)
1878                 retVal = nObjects - dev->nHardLinks;
1879         }
1880         
1881         if(retVal < 0)
1882                 yaffsfs_SetError(-EINVAL);
1883         
1884         yaffsfs_Unlock();
1885         return retVal;  
1886 }
1887
1888
1889 void yaffs_AddDevice(yaffs_Device *dev)
1890 {
1891         dev->isMounted = 0;
1892         dev->param.removeObjectCallback = yaffsfs_RemoveObjectCallback;
1893
1894         if(!dev->devList.next)
1895                 YINIT_LIST_HEAD(&dev->devList);
1896
1897         ylist_add(&dev->devList,&yaffsfs_deviceList);
1898 }
1899
1900 void yaffs_RemoveDevice(yaffs_Device *dev)
1901 {
1902         ylist_del_init(&dev->devList);
1903 }
1904
1905
1906
1907
1908 /* Directory search stuff. */
1909
1910 /*
1911  * Directory search context
1912  *
1913  * NB this is an opaque structure.
1914  */
1915
1916
1917 typedef struct
1918 {
1919         __u32 magic;
1920         yaffs_dirent de;                /* directory entry being used by this dsc */
1921         YCHAR name[NAME_MAX+1];         /* name of directory being searched */
1922         yaffs_Object *dirObj;           /* ptr to directory being searched */
1923         yaffs_Object *nextReturn;       /* obj to be returned by next readddir */
1924         int offset;
1925         struct ylist_head others;       
1926 } yaffsfs_DirectorySearchContext;
1927
1928
1929
1930 static struct ylist_head search_contexts;
1931
1932
1933 static void yaffsfs_SetDirRewound(yaffsfs_DirectorySearchContext *dsc)
1934 {
1935         if(dsc &&
1936            dsc->dirObj &&
1937            dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
1938
1939            dsc->offset = 0;
1940
1941            if( ylist_empty(&dsc->dirObj->variant.directoryVariant.children))
1942                 dsc->nextReturn = NULL;
1943            else
1944                 dsc->nextReturn = ylist_entry(dsc->dirObj->variant.directoryVariant.children.next,
1945                                                 yaffs_Object,siblings);
1946         } else {
1947                 /* Hey someone isn't playing nice! */
1948         }
1949 }
1950
1951 static void yaffsfs_DirAdvance(yaffsfs_DirectorySearchContext *dsc)
1952 {
1953         if(dsc &&
1954            dsc->dirObj &&
1955            dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
1956
1957            if( dsc->nextReturn == NULL ||
1958                ylist_empty(&dsc->dirObj->variant.directoryVariant.children))
1959                 dsc->nextReturn = NULL;
1960            else {
1961                    struct ylist_head *next = dsc->nextReturn->siblings.next;
1962
1963                    if( next == &dsc->dirObj->variant.directoryVariant.children)
1964                         dsc->nextReturn = NULL; /* end of list */
1965                    else
1966                         dsc->nextReturn = ylist_entry(next,yaffs_Object,siblings);
1967            }
1968         } else {
1969                 /* Hey someone isn't playing nice! */
1970         }
1971 }
1972
1973 static void yaffsfs_RemoveObjectCallback(yaffs_Object *obj)
1974 {
1975
1976         struct ylist_head *i;
1977         yaffsfs_DirectorySearchContext *dsc;
1978
1979         /* if search contexts not initilised then skip */
1980         if(!search_contexts.next)
1981                 return;
1982
1983         /* Iterate through the directory search contexts.
1984          * If any are the one being removed, then advance the dsc to
1985          * the next one to prevent a hanging ptr.
1986          */
1987          ylist_for_each(i, &search_contexts) {
1988                 if (i) {
1989                         dsc = ylist_entry(i, yaffsfs_DirectorySearchContext,others);
1990                         if(dsc->nextReturn == obj)
1991                                 yaffsfs_DirAdvance(dsc);
1992                 }
1993         }
1994
1995 }
1996
1997 yaffs_DIR *yaffs_opendir(const YCHAR *dirname)
1998 {
1999         yaffs_DIR *dir = NULL;
2000         yaffs_Object *obj = NULL;
2001         yaffsfs_DirectorySearchContext *dsc = NULL;
2002
2003         yaffsfs_Lock();
2004
2005         obj = yaffsfs_FindObject(NULL,dirname,0);
2006
2007         if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
2008
2009                 dsc = YMALLOC(sizeof(yaffsfs_DirectorySearchContext));
2010                 dir = (yaffs_DIR *)dsc;
2011
2012                 if(dsc){
2013                         memset(dsc,0,sizeof(yaffsfs_DirectorySearchContext));
2014                         dsc->magic = YAFFS_MAGIC;
2015                         dsc->dirObj = obj;
2016                         yaffs_strncpy(dsc->name,dirname,NAME_MAX);
2017                         YINIT_LIST_HEAD(&dsc->others);
2018
2019                         if(!search_contexts.next)
2020                                 YINIT_LIST_HEAD(&search_contexts);
2021
2022                         ylist_add(&dsc->others,&search_contexts);       
2023                         yaffsfs_SetDirRewound(dsc);
2024                 }
2025
2026         }
2027
2028         yaffsfs_Unlock();
2029
2030         return dir;
2031 }
2032
2033 struct yaffs_dirent *yaffs_readdir(yaffs_DIR *dirp)
2034 {
2035         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
2036         struct yaffs_dirent *retVal = NULL;
2037
2038         yaffsfs_Lock();
2039
2040         if(dsc && dsc->magic == YAFFS_MAGIC){
2041                 yaffsfs_SetError(0);
2042                 if(dsc->nextReturn){
2043                         dsc->de.d_ino = yaffs_GetEquivalentObject(dsc->nextReturn)->objectId;
2044                         dsc->de.d_dont_use = (unsigned)dsc->nextReturn;
2045                         dsc->de.d_off = dsc->offset++;
2046                         yaffs_GetObjectName(dsc->nextReturn,dsc->de.d_name,NAME_MAX);
2047                         if(yaffs_strnlen(dsc->de.d_name,NAME_MAX+1) == 0)
2048                         {
2049                                 /* this should not happen! */
2050                                 yaffs_strcpy(dsc->de.d_name,_Y("zz"));
2051                         }
2052                         dsc->de.d_reclen = sizeof(struct yaffs_dirent);
2053                         retVal = &dsc->de;
2054                         yaffsfs_DirAdvance(dsc);
2055                 } else
2056                         retVal = NULL;
2057         } else
2058                 yaffsfs_SetError(-EBADF);
2059
2060         yaffsfs_Unlock();
2061
2062         return retVal;
2063
2064 }
2065
2066
2067 void yaffs_rewinddir(yaffs_DIR *dirp)
2068 {
2069         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
2070
2071         yaffsfs_Lock();
2072
2073         yaffsfs_SetDirRewound(dsc);
2074
2075         yaffsfs_Unlock();
2076 }
2077
2078
2079 int yaffs_closedir(yaffs_DIR *dirp)
2080 {
2081         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
2082
2083         yaffsfs_Lock();
2084         dsc->magic = 0;
2085         ylist_del(&dsc->others); /* unhook from list */
2086         YFREE(dsc);
2087         yaffsfs_Unlock();
2088         return 0;
2089 }
2090
2091 /* End of directory stuff */
2092
2093
2094 int yaffs_symlink(const YCHAR *oldpath, const YCHAR *newpath)
2095 {
2096         yaffs_Object *parent = NULL;
2097         yaffs_Object *obj;
2098         YCHAR *name;
2099         int retVal= -1;
2100         int mode = 0; /* ignore for now */
2101
2102         yaffsfs_Lock();
2103         parent = yaffsfs_FindDirectory(NULL,newpath,&name,0);
2104         if(parent && parent->myDev->readOnly)
2105                 yaffsfs_SetError(-EINVAL);
2106         else if(parent){
2107                 obj = yaffs_MknodSymLink(parent,name,mode,0,0,oldpath);
2108                 if(obj)
2109                         retVal = 0;
2110                 else{
2111                         yaffsfs_SetError(-ENOSPC); /* just assume no space for now */
2112                         retVal = -1;
2113                 }
2114         } else {
2115                 yaffsfs_SetError(-EINVAL);
2116                 retVal = -1;
2117         }
2118
2119         yaffsfs_Unlock();
2120
2121         return retVal;
2122
2123 }
2124
2125 int yaffs_readlink(const YCHAR *path, YCHAR *buf, int bufsiz)
2126 {
2127         yaffs_Object *obj = NULL;
2128         int retVal;
2129
2130
2131         yaffsfs_Lock();
2132
2133         obj = yaffsfs_FindObject(NULL,path,0);
2134
2135         if(!obj) {
2136                 yaffsfs_SetError(-ENOENT);
2137                 retVal = -1;
2138         } else if(obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK) {
2139                 yaffsfs_SetError(-EINVAL);
2140                 retVal = -1;
2141         } else {
2142                 YCHAR *alias = obj->variant.symLinkVariant.alias;
2143                 memset(buf,0,bufsiz);
2144                 yaffs_strncpy(buf,alias,bufsiz - 1);
2145                 retVal = 0;
2146         }
2147         yaffsfs_Unlock();
2148         return retVal;
2149 }
2150
2151 int yaffs_link(const YCHAR *oldpath, const YCHAR *newpath)
2152 {
2153         /* Creates a link called newpath to existing oldpath */
2154         yaffs_Object *obj = NULL;
2155         yaffs_Object *target = NULL;
2156         int retVal = 0;
2157         int newNameLength = 0;
2158
2159
2160         yaffsfs_Lock();
2161
2162         obj = yaffsfs_FindObject(NULL,oldpath,0);
2163         target = yaffsfs_FindObject(NULL,newpath,0);
2164
2165         if(!obj) {
2166                 yaffsfs_SetError(-ENOENT);
2167                 retVal = -1;
2168         } else if(obj->myDev->readOnly){
2169                 yaffsfs_SetError(-EINVAL);
2170                 retVal= -1;
2171         } else if(target) {
2172                 yaffsfs_SetError(-EEXIST);
2173                 retVal = -1;
2174         } else {
2175                 yaffs_Object *newdir = NULL;
2176                 yaffs_Object *link = NULL;
2177
2178                 YCHAR *newname;
2179
2180                 newdir = yaffsfs_FindDirectory(NULL,newpath,&newname,0);
2181
2182                 if(!newdir){
2183                         yaffsfs_SetError(-ENOTDIR);
2184                         retVal = -1;
2185                 }else if(newdir->myDev != obj->myDev){
2186                         yaffsfs_SetError(-EXDEV);
2187                         retVal = -1;
2188                 }
2189                 
2190                 newNameLength = yaffs_strnlen(newname,YAFFS_MAX_NAME_LENGTH+1);
2191                 
2192                 if(newNameLength == 0){
2193                         yaffsfs_SetError(-ENOENT);
2194                         retVal = -1;
2195                 } else if (newNameLength > YAFFS_MAX_NAME_LENGTH){
2196                         yaffsfs_SetError(-ENAMETOOLONG);
2197                         retVal = -1;
2198                 }
2199                 
2200                 if(retVal == 0) {
2201                         link = yaffs_Link(newdir,newname,obj);
2202                         if(link)
2203                                 retVal = 0;
2204                         else{
2205                                 yaffsfs_SetError(-ENOSPC);
2206                                 retVal = -1;
2207                         }
2208
2209                 }
2210         }
2211         yaffsfs_Unlock();
2212
2213         return retVal;
2214 }
2215
2216 int yaffs_mknod(const YCHAR *pathname, mode_t mode, dev_t dev)
2217 {
2218         return -1;
2219 }
2220
2221 int yaffs_DumpDevStruct(const YCHAR *path)
2222 {
2223 #if 0
2224         YCHAR *rest;
2225
2226         yaffs_Object *obj = yaffsfs_FindRoot(path,&rest);
2227
2228         if(obj){
2229                 yaffs_Device *dev = obj->myDev;
2230
2231                 printf("\n"
2232                            "nPageWrites.......... %d\n"
2233                            "nPageReads........... %d\n"
2234                            "nBlockErasures....... %d\n"
2235                            "nGCCopies............ %d\n"
2236                            "garbageCollections... %d\n"
2237                            "passiveGarbageColl'ns %d\n"
2238                            "\n",
2239                                 dev->nPageWrites,
2240                                 dev->nPageReads,
2241                                 dev->nBlockErasures,
2242                                 dev->nGCCopies,
2243                                 dev->garbageCollections,
2244                                 dev->passiveGarbageCollections
2245                 );
2246
2247         }
2248
2249 #endif
2250         return 0;
2251 }
2252