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