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