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