Add more test code.
[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.35 2010-02-25 22:38:03 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  && dir->myDev->readOnly){
585                                 yaffsfs_SetError(-EINVAL);
586                                 errorReported = 1;
587                         } else if(dir)
588                                 obj = yaffs_MknodFile(dir,name,mode,0,0);
589                         else {
590                                 yaffsfs_SetError(-ENOTDIR);
591                                 errorReported = 1;
592                         }
593                 }
594
595                 if(obj && !openDenied) {
596                         int inodeId = yaffsfs_GetInodeIdForObject(obj);
597
598                         if(inodeId<0) {
599                                 /*
600                                  * Todo: Fix any problem if inodes run out, though that
601                                  * can't happen if the number of inode items >= number of handles. 
602                                  */
603                         }
604                         
605                         h->inodeId = inodeId;
606                         h->readOnly = (oflag & (O_WRONLY | O_RDWR)) ? 0 : 1;
607                         h->append =  (oflag & O_APPEND) ? 1 : 0;
608                         h->exclusive = (oflag & O_EXCL) ? 1 : 0;
609                         h->position = 0;
610
611                         /* Hook inode to object */
612                         obj->myInode = (void*) &yaffsfs_inode[inodeId];
613
614                         if((oflag & O_TRUNC) && !h->readOnly)
615                                 yaffs_ResizeFile(obj,0);
616                 } else {
617                         yaffsfs_PutHandle(handle);
618                         if(!errorReported) {
619                                 yaffsfs_SetError(-EACCES);
620                                 errorReported = 1;
621                         }
622                         handle = -1;
623                 }
624         }
625
626         yaffsfs_Unlock();
627
628         return handle;
629 }
630
631 int yaffs_Dofsync(int fd,int datasync)
632 {
633         yaffsfs_Handle *h = NULL;
634         int retVal = 0;
635
636         yaffsfs_Lock();
637
638         h = yaffsfs_GetHandlePointer(fd);
639
640         if(h && h->useCount > 0)
641                 // flush the file
642                 yaffs_FlushFile(yaffsfs_inode[h->inodeId].iObj,1,datasync);
643         else {
644                 // bad handle
645                 yaffsfs_SetError(-EBADF);
646                 retVal = -1;
647         }
648
649         yaffsfs_Unlock();
650
651         return retVal;
652 }
653
654 int yaffs_fsync(int fd)
655 {
656         return yaffs_Dofsync(fd,0);
657 }
658
659 int yaffs_flush(int fd)
660 {
661         return yaffs_fsync(fd);
662 }
663
664 int yaffs_fdatasync(int fd)
665 {
666         return yaffs_Dofsync(fd,1);
667 }
668
669 int yaffs_close(int fd)
670 {
671         yaffsfs_Handle *h = NULL;
672         int retVal = 0;
673
674         yaffsfs_Lock();
675
676         h = yaffsfs_GetHandlePointer(fd);
677
678         if(h && h->useCount > 0) {
679                 // clean up
680                 yaffs_FlushFile(yaffsfs_inode[h->inodeId].iObj,1,0);
681                 yaffsfs_PutHandle(fd);
682                 retVal = 0;
683         } else {
684                 // bad handle
685                 yaffsfs_SetError(-EBADF);
686                 retVal = -1;
687         }
688
689         yaffsfs_Unlock();
690
691         return retVal;
692 }
693
694
695
696 int yaffsfs_do_read(int fd, void *vbuf, unsigned int nbyte, int isPread, int offset)
697 {
698         yaffsfs_Handle *h = NULL;
699         yaffs_Object *obj = NULL;
700         int pos = 0;
701         int startPos = 0;
702         int nRead = 0;
703         int nToRead = 0;
704         int totalRead = 0;
705         unsigned int maxRead;
706         __u8 *buf = (__u8 *)vbuf;
707
708         yaffsfs_Lock();
709         h = yaffsfs_GetHandlePointer(fd);
710         obj = yaffsfs_GetHandleObject(fd);
711
712         if(!h || !obj){
713                 // bad handle
714                 yaffsfs_SetError(-EBADF);
715                 totalRead = -1;
716         } else if( h && obj){
717                 if(isPread)
718                         startPos = offset;
719                 else
720                         startPos = h->position;
721
722                 pos = startPos;
723                                         
724                 if(yaffs_GetObjectFileLength(obj) > pos)
725                         maxRead = yaffs_GetObjectFileLength(obj) - pos;
726                 else
727                         maxRead = 0;
728
729                 if(nbyte > maxRead)
730                         nbyte = maxRead;
731
732
733                 yaffsfs_GetHandle(fd);
734
735                 while(nbyte > 0) {
736                         nToRead = YAFFSFS_RW_SIZE - (pos & (YAFFSFS_RW_SIZE -1));
737                         if(nToRead > nbyte)
738                                 nToRead = nbyte;
739                         nRead = yaffs_ReadDataFromFile(obj,buf,pos,nToRead);
740
741                         if(nRead > 0){
742                                 totalRead += nRead;
743                                 pos += nRead;
744                                 buf += nRead;
745                         }
746
747                         if(nRead == nToRead)
748                                 nbyte-=nRead;
749                         else
750                                 nbyte = 0; /* no more to read */
751                                         
752                                         
753                         if(nbyte > 0){
754                                 yaffsfs_Unlock();
755                                 yaffsfs_Lock();
756                         }
757
758                 }
759
760                 yaffsfs_PutHandle(fd);
761
762                 if(!isPread) {
763                         if(totalRead >= 0)
764                                 h->position = startPos + totalRead;
765                         else {
766                                         //todo error
767                         }
768                 }
769
770         }
771
772         yaffsfs_Unlock();
773
774         return (totalRead >= 0) ? totalRead : -1;
775
776 }
777
778 int yaffs_read(int fd, void *buf, unsigned int nbyte)
779 {
780         return yaffsfs_do_read(fd, buf, nbyte, 0, 0);
781 }
782
783 int yaffs_pread(int fd, void *buf, unsigned int nbyte, unsigned int offset)
784 {
785         return yaffsfs_do_read(fd, buf, nbyte, 1, offset);
786 }
787
788 int yaffsfs_do_write(int fd, const void *vbuf, unsigned int nbyte, int isPwrite, int offset)
789 {
790         yaffsfs_Handle *h = NULL;
791         yaffs_Object *obj = NULL;
792         int pos = 0;
793         int startPos = 0;
794         int nWritten = 0;
795         int totalWritten = 0;
796         int writeThrough = 0;
797         int nToWrite = 0;
798         const __u8 *buf = (const __u8 *)vbuf;
799
800         yaffsfs_Lock();
801         h = yaffsfs_GetHandlePointer(fd);
802         obj = yaffsfs_GetHandleObject(fd);
803
804         if(!h || !obj){
805                 // bad handle
806                 yaffsfs_SetError(-EBADF);
807                 totalWritten = -1;
808         } else if( h && obj && (h->readOnly || obj->myDev->readOnly)){
809                 yaffsfs_SetError(-EINVAL);
810                 totalWritten=-1;
811         } else if( h && obj){
812                 if(isPwrite)
813                         startPos = offset;
814                 if(h->append)
815                         startPos = yaffs_GetObjectFileLength(obj);
816                 else
817                         startPos = h->position;
818
819                 yaffsfs_GetHandle(fd);
820                 pos = startPos;
821                 while(nbyte > 0) {
822                         nToWrite = YAFFSFS_RW_SIZE - (pos & (YAFFSFS_RW_SIZE -1));
823                         if(nToWrite > nbyte)
824                                 nToWrite = nbyte;
825
826                         nWritten = yaffs_WriteDataToFile(obj,buf,pos,nToWrite,writeThrough);
827                         if(nWritten > 0){
828                                 totalWritten += nWritten;
829                                 pos += nWritten;
830                                 buf += nWritten;
831                         }
832
833                         if(nWritten == nToWrite)
834                                 nbyte -= nToWrite;
835                         else
836                                 nbyte = 0;
837
838                         if(nWritten < 1 && totalWritten < 1){
839                                 yaffsfs_SetError(-ENOSPC);
840                                 totalWritten = -1;
841                         }
842
843                         if(nbyte > 0){
844                                 yaffsfs_Unlock();
845                                 yaffsfs_Lock();
846                         }
847                 }
848
849                 yaffsfs_PutHandle(fd);
850
851                 if(!isPwrite){
852                         if(totalWritten > 0)
853                                 h->position = startPos + totalWritten;
854                         else {
855                                 //todo error
856                         }
857                 }
858         }
859
860         yaffsfs_Unlock();
861
862         return (totalWritten >= 0) ? totalWritten : -1;
863 }
864
865 int yaffs_write(int fd, const void *buf, unsigned int nbyte)
866 {
867         return yaffsfs_do_write(fd, buf, nbyte, 0, 0);
868 }
869
870 int yaffs_pwrite(int fd, const void *buf, unsigned int nbyte, unsigned int offset)
871 {
872         return yaffsfs_do_write(fd, buf, nbyte, 1, offset);
873 }
874
875
876 int yaffs_truncate(const YCHAR *path,off_t newSize)
877 {
878         yaffs_Object *obj = NULL;
879         int result = YAFFS_FAIL;
880
881         yaffsfs_Lock();
882
883         obj = yaffsfs_FindObject(NULL,path,0);
884         if(obj)
885                 obj = yaffs_GetEquivalentObject(obj);
886
887         if(!obj)
888                 yaffsfs_SetError(-ENOENT);
889         else if(obj->variantType != YAFFS_OBJECT_TYPE_FILE)
890                 yaffsfs_SetError(-EISDIR);
891         else if(obj->myDev->readOnly)
892                 yaffsfs_SetError(-EINVAL);
893         else
894                 result = yaffs_ResizeFile(obj,newSize);
895
896         yaffsfs_Unlock();
897
898
899         return (result) ? 0 : -1;
900 }
901
902 int yaffs_ftruncate(int fd, off_t newSize)
903 {
904         yaffsfs_Handle *h = NULL;
905         yaffs_Object *obj = NULL;
906         int result = 0;
907
908         yaffsfs_Lock();
909         h = yaffsfs_GetHandlePointer(fd);
910         obj = yaffsfs_GetHandleObject(fd);
911
912         if(!h || !obj)
913                 // bad handle
914                 yaffsfs_SetError(-EBADF);
915         else if(obj->myDev->readOnly)
916                 yaffsfs_SetError(-EINVAL);
917         else
918                 // resize the file
919                 result = yaffs_ResizeFile(obj,newSize);
920         yaffsfs_Unlock();
921
922
923         return (result) ? 0 : -1;
924
925 }
926
927 off_t yaffs_lseek(int fd, off_t offset, int whence)
928 {
929         yaffsfs_Handle *h = NULL;
930         yaffs_Object *obj = NULL;
931         int pos = -1;
932         int fSize = -1;
933
934         yaffsfs_Lock();
935         h = yaffsfs_GetHandlePointer(fd);
936         obj = yaffsfs_GetHandleObject(fd);
937
938         if(!h || !obj)
939                 // bad handle
940                 yaffsfs_SetError(-EBADF);
941         else if(whence == SEEK_SET){
942                 if(offset >= 0)
943                         pos = offset;
944         }
945         else if(whence == SEEK_CUR) {
946                 if( (h->position + offset) >= 0)
947                         pos = (h->position + offset);
948         }
949         else if(whence == SEEK_END) {
950                 fSize = yaffs_GetObjectFileLength(obj);
951                 if(fSize >= 0 && (fSize + offset) >= 0)
952                         pos = fSize + offset;
953         }
954
955         if(pos >= 0)
956                 h->position = pos;
957         else {
958                 // todo error
959         }
960
961
962         yaffsfs_Unlock();
963
964         return pos;
965 }
966
967
968 int yaffsfs_DoUnlink(const YCHAR *path,int isDirectory)
969 {
970         yaffs_Object *dir = NULL;
971         yaffs_Object *obj = NULL;
972         YCHAR *name;
973         int result = YAFFS_FAIL;
974
975         yaffsfs_Lock();
976
977         obj = yaffsfs_FindObject(NULL,path,0);
978         dir = yaffsfs_FindDirectory(NULL,path,&name,0);
979         if(!dir)
980                 yaffsfs_SetError(-ENOTDIR);
981         else if(!obj)
982                 yaffsfs_SetError(-ENOENT);
983         else if(obj->myDev->readOnly)
984                 yaffsfs_SetError(-EINVAL);
985         else if(!isDirectory && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
986                 yaffsfs_SetError(-EISDIR);
987         else if(isDirectory && obj->variantType != YAFFS_OBJECT_TYPE_DIRECTORY)
988                 yaffsfs_SetError(-ENOTDIR);
989         else {
990                 result = yaffs_Unlink(dir,name);
991
992                 if(result == YAFFS_FAIL && isDirectory)
993                         yaffsfs_SetError(-ENOTEMPTY);
994         }
995
996         yaffsfs_Unlock();
997
998         // todo error
999
1000         return (result == YAFFS_FAIL) ? -1 : 0;
1001 }
1002
1003
1004 int yaffs_rmdir(const YCHAR *path)
1005 {
1006         return yaffsfs_DoUnlink(path,1);
1007 }
1008
1009 int yaffs_unlink(const YCHAR *path)
1010 {
1011         return yaffsfs_DoUnlink(path,0);
1012 }
1013
1014 int yaffs_rename(const YCHAR *oldPath, const YCHAR *newPath)
1015 {
1016         yaffs_Object *olddir = NULL;
1017         yaffs_Object *newdir = NULL;
1018         yaffs_Object *obj = NULL;
1019         YCHAR *oldname;
1020         YCHAR *newname;
1021         int result= YAFFS_FAIL;
1022         int renameAllowed = 1;
1023
1024         yaffsfs_Lock();
1025
1026         olddir = yaffsfs_FindDirectory(NULL,oldPath,&oldname,0);
1027         newdir = yaffsfs_FindDirectory(NULL,newPath,&newname,0);
1028         obj = yaffsfs_FindObject(NULL,oldPath,0);
1029
1030         if(!olddir || !newdir || !obj) {
1031                 // bad file
1032                 yaffsfs_SetError(-EBADF);
1033                 renameAllowed = 0;
1034         } else if(obj->myDev->readOnly){
1035                 yaffsfs_SetError(-EINVAL);
1036                 renameAllowed = 0;
1037         } else if(olddir->myDev != newdir->myDev) {
1038                 // oops must be on same device
1039                 // todo error
1040                 yaffsfs_SetError(-EXDEV);
1041                 renameAllowed = 0;
1042         } else if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY) {
1043                 // It is a directory, check that it is not being renamed to
1044                 // being its own decendent.
1045                 // Do this by tracing from the new directory back to the root, checking for obj
1046
1047                 yaffs_Object *xx = newdir;
1048
1049                 while( renameAllowed && xx){
1050                         if(xx == obj)
1051                                 renameAllowed = 0;
1052                         xx = xx->parent;
1053                 }
1054                 if(!renameAllowed)
1055                         yaffsfs_SetError(-EACCES);
1056         }
1057
1058         if(renameAllowed)
1059                 result = yaffs_RenameObject(olddir,oldname,newdir,newname);
1060
1061         yaffsfs_Unlock();
1062
1063         return (result == YAFFS_FAIL) ? -1 : 0;
1064 }
1065
1066
1067 static int yaffsfs_DoStat(yaffs_Object *obj,struct yaffs_stat *buf)
1068 {
1069         int retVal = -1;
1070
1071         if(obj)
1072                 obj = yaffs_GetEquivalentObject(obj);
1073
1074         if(obj && buf){
1075                 buf->st_dev = (int)obj->myDev->context;
1076                 buf->st_ino = obj->objectId;
1077                 buf->st_mode = obj->yst_mode & ~S_IFMT; // clear out file type bits
1078
1079                 if(obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY)
1080                         buf->st_mode |= S_IFDIR;
1081                 else if(obj->variantType == YAFFS_OBJECT_TYPE_SYMLINK)
1082                         buf->st_mode |= S_IFLNK;
1083                 else if(obj->variantType == YAFFS_OBJECT_TYPE_FILE)
1084                         buf->st_mode |= S_IFREG;
1085
1086                 buf->st_nlink = yaffs_GetObjectLinkCount(obj);
1087                 buf->st_uid = 0;
1088                 buf->st_gid = 0;;
1089                 buf->st_rdev = obj->yst_rdev;
1090                 buf->st_size = yaffs_GetObjectFileLength(obj);
1091                 buf->st_blksize = obj->myDev->nDataBytesPerChunk;
1092                 buf->st_blocks = (buf->st_size + buf->st_blksize -1)/buf->st_blksize;
1093 #if CONFIG_YAFFS_WINCE
1094                 buf->yst_wince_atime[0] = obj->win_atime[0];
1095                 buf->yst_wince_atime[1] = obj->win_atime[1];
1096                 buf->yst_wince_ctime[0] = obj->win_ctime[0];
1097                 buf->yst_wince_ctime[1] = obj->win_ctime[1];
1098                 buf->yst_wince_mtime[0] = obj->win_mtime[0];
1099                 buf->yst_wince_mtime[1] = obj->win_mtime[1];
1100 #else
1101                 buf->yst_atime = obj->yst_atime;
1102                 buf->yst_ctime = obj->yst_ctime;
1103                 buf->yst_mtime = obj->yst_mtime;
1104 #endif
1105                 retVal = 0;
1106         }
1107         return retVal;
1108 }
1109
1110 static int yaffsfs_DoStatOrLStat(const YCHAR *path, struct yaffs_stat *buf,int doLStat)
1111 {
1112         yaffs_Object *obj;
1113
1114         int retVal = -1;
1115
1116         yaffsfs_Lock();
1117         obj = yaffsfs_FindObject(NULL,path,0);
1118
1119         if(!doLStat && obj)
1120                 obj = yaffsfs_FollowLink(obj,0);
1121
1122         if(obj)
1123                 retVal = yaffsfs_DoStat(obj,buf);
1124         else
1125                 // todo error not found
1126                 yaffsfs_SetError(-ENOENT);
1127
1128         yaffsfs_Unlock();
1129
1130         return retVal;
1131
1132 }
1133
1134 int yaffs_stat(const YCHAR *path, struct yaffs_stat *buf)
1135 {
1136         return yaffsfs_DoStatOrLStat(path,buf,0);
1137 }
1138
1139 int yaffs_lstat(const YCHAR *path, struct yaffs_stat *buf)
1140 {
1141         return yaffsfs_DoStatOrLStat(path,buf,1);
1142 }
1143
1144 int yaffs_fstat(int fd, struct yaffs_stat *buf)
1145 {
1146         yaffs_Object *obj;
1147
1148         int retVal = -1;
1149
1150         yaffsfs_Lock();
1151         obj = yaffsfs_GetHandleObject(fd);
1152
1153         if(obj)
1154                 retVal = yaffsfs_DoStat(obj,buf);
1155         else
1156                 // bad handle
1157                 yaffsfs_SetError(-EBADF);
1158
1159         yaffsfs_Unlock();
1160
1161         return retVal;
1162 }
1163
1164 #ifdef CONFIG_YAFFS_WINCE
1165 int yaffs_get_wince_times(int fd, unsigned *wctime, unsigned *watime, unsigned *wmtime)
1166 {
1167         yaffs_Object *obj;
1168
1169         int retVal = -1;
1170
1171         yaffsfs_Lock();
1172         obj = yaffsfs_GetHandleObject(fd);
1173
1174         if(obj){
1175
1176                 if(wctime){
1177                         wctime[0] = obj->win_ctime[0];
1178                         wctime[1] = obj->win_ctime[1];
1179                 }
1180                 if(watime){
1181                         watime[0] = obj->win_atime[0];
1182                         watime[1] = obj->win_atime[1];
1183                 }
1184                 if(wmtime){
1185                         wmtime[0] = obj->win_mtime[0];
1186                         wmtime[1] = obj->win_mtime[1];
1187                 }
1188
1189
1190                 retVal = 0;
1191         } else
1192                 // bad handle
1193                 yaffsfs_SetError(-EBADF);               
1194         
1195         yaffsfs_Unlock();
1196         
1197         return retVal;
1198 }
1199
1200
1201 int yaffs_set_wince_times(int fd, 
1202                                                   const unsigned *wctime, 
1203                                                   const unsigned *watime, 
1204                                                   const unsigned *wmtime)
1205 {
1206         yaffs_Object *obj;
1207         int result;
1208         int retVal = -1;
1209
1210         yaffsfs_Lock();
1211         obj = yaffsfs_GetHandleObject(fd);
1212
1213         if(obj){
1214
1215                 if(wctime){
1216                         obj->win_ctime[0] = wctime[0];
1217                         obj->win_ctime[1] = wctime[1];
1218                 }
1219                 if(watime){
1220                         obj->win_atime[0] = watime[0];
1221                         obj->win_atime[1] = watime[1];
1222                 }
1223                 if(wmtime){
1224                         obj->win_mtime[0] = wmtime[0];
1225                         obj->win_mtime[1] = wmtime[1];
1226                 }
1227
1228                 obj->dirty = 1;
1229                 result = yaffs_FlushFile(obj,0,0);
1230                 retVal = 0;
1231         } else
1232                 // bad handle
1233                 yaffsfs_SetError(-EBADF);
1234
1235         yaffsfs_Unlock();
1236
1237         return retVal;
1238 }
1239
1240 #endif
1241
1242
1243 static int yaffsfs_DoChMod(yaffs_Object *obj,mode_t mode)
1244 {
1245         int result = -1;
1246
1247         if(obj)
1248                 obj = yaffs_GetEquivalentObject(obj);
1249
1250         if(obj) {
1251                 obj->yst_mode = mode;
1252                 obj->dirty = 1;
1253                 result = yaffs_FlushFile(obj,0,0);
1254         }
1255
1256         return result == YAFFS_OK ? 0 : -1;
1257 }
1258
1259
1260 int yaffs_access(const YCHAR *path, int amode)
1261 {
1262         yaffs_Object *obj;
1263
1264         int retval = 0;
1265
1266         yaffsfs_Lock();
1267         obj = yaffsfs_FindObject(NULL,path,0);
1268
1269         if(obj) {
1270                 int access_ok = 1;
1271
1272                 if((amode & R_OK) && !(obj->yst_mode & S_IREAD))
1273                         access_ok = 0;
1274                 if((amode & W_OK) && !(obj->yst_mode & S_IWRITE))
1275                         access_ok = 0;
1276                 if((amode & X_OK) && !(obj->yst_mode & S_IEXEC))
1277                         access_ok = 0;
1278
1279                 if(!access_ok) {
1280                         yaffsfs_SetError(-EACCES);
1281                         retval = -1;
1282                 }
1283         } else {
1284                 // todo error not found
1285                 yaffsfs_SetError(-ENOENT);
1286                 retval = -1;
1287         }
1288
1289         yaffsfs_Unlock();
1290
1291         return retval;
1292
1293 }
1294
1295
1296 int yaffs_chmod(const YCHAR *path, mode_t mode)
1297 {
1298         yaffs_Object *obj;
1299
1300         int retVal = -1;
1301
1302         yaffsfs_Lock();
1303         obj = yaffsfs_FindObject(NULL,path,0);
1304
1305         if(!obj)
1306                 yaffsfs_SetError(-ENOENT);
1307         else if(obj->myDev->readOnly)
1308                 yaffsfs_SetError(-EINVAL);
1309         else
1310                 retVal = yaffsfs_DoChMod(obj,mode);
1311
1312         yaffsfs_Unlock();
1313
1314         return retVal;
1315
1316 }
1317
1318
1319 int yaffs_fchmod(int fd, mode_t mode)
1320 {
1321         yaffs_Object *obj;
1322
1323         int retVal = -1;
1324
1325         yaffsfs_Lock();
1326         obj = yaffsfs_GetHandleObject(fd);
1327
1328         if(!obj)
1329                 yaffsfs_SetError(-ENOENT);
1330         else if(obj->myDev->readOnly)
1331                 yaffsfs_SetError(-EINVAL);
1332         else
1333                 retVal = yaffsfs_DoChMod(obj,mode);
1334
1335         yaffsfs_Unlock();
1336
1337         return retVal;
1338 }
1339
1340
1341 int yaffs_mkdir(const YCHAR *path, mode_t mode)
1342 {
1343         yaffs_Object *parent = NULL;
1344         yaffs_Object *dir = NULL;
1345         YCHAR *name;
1346         int retVal= -1;
1347
1348         yaffsfs_Lock();
1349         parent = yaffsfs_FindDirectory(NULL,path,&name,0);
1350         if(parent && parent->myDev->readOnly){
1351                 yaffsfs_SetError(-EINVAL);
1352         } else {
1353                 if(parent)
1354                         dir = yaffs_MknodDirectory(parent,name,mode,0,0);
1355                 if(dir)
1356                         retVal = 0;
1357                 else {
1358                         if(!parent)
1359                                 yaffsfs_SetError(-ENOENT); // missing path
1360                         else if (yaffs_FindObjectByName(parent,name))
1361                                 yaffsfs_SetError(-EEXIST); // the name already exists
1362                         else
1363                                 yaffsfs_SetError(-ENOSPC); // just assume no space
1364                         retVal = -1;
1365                 }
1366         }
1367
1368         yaffsfs_Unlock();
1369
1370         return retVal;
1371 }
1372
1373 int yaffs_mount2(const YCHAR *path,int readOnly)
1374 {
1375         int retVal=-1;
1376         int result=YAFFS_FAIL;
1377         yaffs_Device *dev=NULL;
1378         YCHAR *dummy;
1379
1380         T(YAFFS_TRACE_ALWAYS,(TSTR("yaffs: Mounting %s" TENDSTR),path));
1381
1382         yaffsfs_Lock();
1383         dev = yaffsfs_FindDevice(path,&dummy);
1384         if(dev){
1385                 if(!dev->isMounted){
1386                         dev->readOnly = readOnly ? 1 : 0;
1387                         result = yaffs_GutsInitialise(dev);
1388                         if(result == YAFFS_FAIL)
1389                                 // todo error - mount failed
1390                                 yaffsfs_SetError(-ENOMEM);
1391                         retVal = result ? 0 : -1;
1392
1393                 }
1394                 else
1395                         //todo error - already mounted.
1396                         yaffsfs_SetError(-EBUSY);
1397         } else
1398                 // todo error - no device
1399                 yaffsfs_SetError(-ENODEV);
1400
1401         yaffsfs_Unlock();
1402         return retVal;
1403
1404 }
1405
1406 int yaffs_mount(const YCHAR *path)
1407 {
1408         return yaffs_mount2(path,0);
1409 }
1410
1411 int yaffs_sync(const YCHAR *path)
1412 {
1413         int retVal=-1;
1414         yaffs_Device *dev=NULL;
1415         YCHAR *dummy;
1416         
1417         yaffsfs_Lock();
1418         dev = yaffsfs_FindDevice(path,&dummy);
1419         if(dev){
1420                 if(dev->isMounted){
1421                         
1422                         yaffs_FlushEntireDeviceCache(dev);
1423                         yaffs_CheckpointSave(dev);
1424                         
1425                         
1426                 } else
1427                         //todo error - not mounted.
1428                         yaffsfs_SetError(-EINVAL);
1429                         
1430         }else
1431                 // todo error - no device
1432                 yaffsfs_SetError(-ENODEV);
1433
1434         yaffsfs_Unlock();
1435         return retVal;  
1436 }
1437
1438
1439 int yaffs_remount(const YCHAR *path, int force, int readOnly)
1440 {
1441         int retVal=-1;
1442         yaffs_Device *dev=NULL;
1443         YCHAR *dummy;
1444
1445         yaffsfs_Lock();
1446         dev = yaffsfs_FindDevice(path,&dummy);
1447         if(dev){
1448                 if(dev->isMounted){
1449                         int i;
1450                         int inUse;
1451
1452                         yaffs_FlushEntireDeviceCache(dev);
1453
1454                         for(i = inUse = 0; i < YAFFSFS_N_HANDLES && !inUse && !force; i++){
1455                                 if(yaffsfs_handle[i].useCount>0 && yaffsfs_inode[yaffsfs_handle[i].inodeId].iObj->myDev == dev)
1456                                         inUse = 1; // the device is in use, can't unmount
1457                         }
1458
1459                         if(!inUse || force){
1460                                 if(readOnly)
1461                                         yaffs_CheckpointSave(dev);
1462                                 dev->readOnly =  readOnly ? 1 : 0;
1463                                 retVal = 0;
1464                         } else
1465                                 yaffsfs_SetError(-EBUSY);
1466
1467                 } else
1468                         yaffsfs_SetError(-EINVAL);
1469
1470         }
1471         else
1472                 yaffsfs_SetError(-ENODEV);
1473
1474         yaffsfs_Unlock();
1475         return retVal;
1476
1477 }
1478
1479 int yaffs_unmount2(const YCHAR *path, int force)
1480 {
1481         int retVal=-1;
1482         yaffs_Device *dev=NULL;
1483         YCHAR *dummy;
1484
1485         yaffsfs_Lock();
1486         dev = yaffsfs_FindDevice(path,&dummy);
1487         if(dev){
1488                 if(dev->isMounted){
1489                         int i;
1490                         int inUse;
1491
1492                         yaffs_FlushEntireDeviceCache(dev);
1493                         yaffs_CheckpointSave(dev);
1494
1495                         for(i = inUse = 0; i < YAFFSFS_N_HANDLES && !inUse; i++){
1496                                 if(yaffsfs_handle[i].useCount > 0 && yaffsfs_inode[yaffsfs_handle[i].inodeId].iObj->myDev == dev)
1497                                         inUse = 1; // the device is in use, can't unmount
1498                         }
1499
1500                         if(!inUse || force){
1501                                 yaffs_Deinitialise(dev);
1502
1503                                 retVal = 0;
1504                         } else
1505                                 // todo error can't unmount as files are open
1506                                 yaffsfs_SetError(-EBUSY);
1507
1508                 } else
1509                         //todo error - not mounted.
1510                         yaffsfs_SetError(-EINVAL);
1511
1512         }
1513         else
1514                 // todo error - no device
1515                 yaffsfs_SetError(-ENODEV);
1516
1517         yaffsfs_Unlock();
1518         return retVal;
1519
1520 }
1521
1522 int yaffs_unmount(const YCHAR *path)
1523 {
1524         return yaffs_unmount2(path,0);
1525 }
1526
1527 loff_t yaffs_freespace(const YCHAR *path)
1528 {
1529         loff_t retVal=-1;
1530         yaffs_Device *dev=NULL;
1531         YCHAR *dummy;
1532
1533         yaffsfs_Lock();
1534         dev = yaffsfs_FindDevice(path,&dummy);
1535         if(dev  && dev->isMounted){
1536                 retVal = yaffs_GetNumberOfFreeChunks(dev);
1537                 retVal *= dev->nDataBytesPerChunk;
1538
1539         } else
1540                 yaffsfs_SetError(-EINVAL);
1541
1542         yaffsfs_Unlock();
1543         return retVal;
1544 }
1545
1546 loff_t yaffs_totalspace(const YCHAR *path)
1547 {
1548         loff_t retVal=-1;
1549         yaffs_Device *dev=NULL;
1550         YCHAR *dummy;
1551
1552         yaffsfs_Lock();
1553         dev = yaffsfs_FindDevice(path,&dummy);
1554         if(dev  && dev->isMounted){
1555                 retVal = (dev->param.endBlock - dev->param.startBlock + 1) - dev->param.nReservedBlocks;
1556                 retVal *= dev->param.nChunksPerBlock;
1557                 retVal *= dev->nDataBytesPerChunk;
1558
1559         } else
1560                 yaffsfs_SetError(-EINVAL);
1561
1562         yaffsfs_Unlock();
1563         return retVal;
1564 }
1565
1566 int yaffs_inodecount(const YCHAR *path)
1567 {
1568         loff_t retVal= -1;
1569         yaffs_Device *dev=NULL;
1570         YCHAR *dummy;
1571
1572         yaffsfs_Lock();
1573         dev = yaffsfs_FindDevice(path,&dummy);
1574         if(dev  && dev->isMounted) {
1575            int nObjects = dev->nObjectsCreated - dev->nFreeObjects;
1576            if(nObjects > dev->nHardLinks)
1577                 retVal = nObjects - dev->nHardLinks;
1578         }
1579         
1580         if(retVal < 0)
1581                 yaffsfs_SetError(-EINVAL);
1582         
1583         yaffsfs_Unlock();
1584         return retVal;  
1585 }
1586
1587
1588
1589 void yaffs_initialise(yaffsfs_DeviceConfiguration *cfgList)
1590 {
1591
1592         yaffsfs_DeviceConfiguration *cfg;
1593
1594         yaffsfs_configurationList = cfgList;
1595
1596         yaffsfs_InitHandles();
1597
1598         cfg = yaffsfs_configurationList;
1599
1600         while(cfg && cfg->prefix && cfg->dev){
1601                 cfg->dev->isMounted = 0;
1602                 cfg->dev->param.removeObjectCallback = yaffsfs_RemoveObjectCallback;
1603                 cfg++;
1604         }
1605
1606
1607 }
1608
1609
1610 //
1611 // Directory search stuff.
1612
1613 //
1614 // Directory search context
1615 //
1616 // NB this is an opaque structure.
1617
1618
1619 typedef struct
1620 {
1621         __u32 magic;
1622         yaffs_dirent de;                /* directory entry being used by this dsc */
1623         YCHAR name[NAME_MAX+1];         /* name of directory being searched */
1624         yaffs_Object *dirObj;           /* ptr to directory being searched */
1625         yaffs_Object *nextReturn;       /* obj to be returned by next readddir */
1626         int offset;
1627         struct ylist_head others;       
1628 } yaffsfs_DirectorySearchContext;
1629
1630
1631
1632 static struct ylist_head search_contexts;
1633
1634
1635 static void yaffsfs_SetDirRewound(yaffsfs_DirectorySearchContext *dsc)
1636 {
1637         if(dsc &&
1638            dsc->dirObj &&
1639            dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
1640
1641            dsc->offset = 0;
1642
1643            if( ylist_empty(&dsc->dirObj->variant.directoryVariant.children))
1644                 dsc->nextReturn = NULL;
1645            else
1646                 dsc->nextReturn = ylist_entry(dsc->dirObj->variant.directoryVariant.children.next,
1647                                                 yaffs_Object,siblings);
1648         } else {
1649                 /* Hey someone isn't playing nice! */
1650         }
1651 }
1652
1653 static void yaffsfs_DirAdvance(yaffsfs_DirectorySearchContext *dsc)
1654 {
1655         if(dsc &&
1656            dsc->dirObj &&
1657            dsc->dirObj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
1658
1659            if( dsc->nextReturn == NULL ||
1660                ylist_empty(&dsc->dirObj->variant.directoryVariant.children))
1661                 dsc->nextReturn = NULL;
1662            else {
1663                    struct ylist_head *next = dsc->nextReturn->siblings.next;
1664
1665                    if( next == &dsc->dirObj->variant.directoryVariant.children)
1666                         dsc->nextReturn = NULL; /* end of list */
1667                    else
1668                         dsc->nextReturn = ylist_entry(next,yaffs_Object,siblings);
1669            }
1670         } else {
1671                 /* Hey someone isn't playing nice! */
1672         }
1673 }
1674
1675 static void yaffsfs_RemoveObjectCallback(yaffs_Object *obj)
1676 {
1677
1678         struct ylist_head *i;
1679         yaffsfs_DirectorySearchContext *dsc;
1680
1681         /* if search contexts not initilised then skip */
1682         if(!search_contexts.next)
1683                 return;
1684
1685         /* Iterate through the directory search contexts.
1686          * If any are the one being removed, then advance the dsc to
1687          * the next one to prevent a hanging ptr.
1688          */
1689          ylist_for_each(i, &search_contexts) {
1690                 if (i) {
1691                         dsc = ylist_entry(i, yaffsfs_DirectorySearchContext,others);
1692                         if(dsc->nextReturn == obj)
1693                                 yaffsfs_DirAdvance(dsc);
1694                 }
1695         }
1696
1697 }
1698
1699 yaffs_DIR *yaffs_opendir(const YCHAR *dirname)
1700 {
1701         yaffs_DIR *dir = NULL;
1702         yaffs_Object *obj = NULL;
1703         yaffsfs_DirectorySearchContext *dsc = NULL;
1704
1705         yaffsfs_Lock();
1706
1707         obj = yaffsfs_FindObject(NULL,dirname,0);
1708
1709         if(obj && obj->variantType == YAFFS_OBJECT_TYPE_DIRECTORY){
1710
1711                 dsc = YMALLOC(sizeof(yaffsfs_DirectorySearchContext));
1712                 dir = (yaffs_DIR *)dsc;
1713
1714                 if(dsc){
1715                         memset(dsc,0,sizeof(yaffsfs_DirectorySearchContext));
1716                         dsc->magic = YAFFS_MAGIC;
1717                         dsc->dirObj = obj;
1718                         yaffs_strncpy(dsc->name,dirname,NAME_MAX);
1719                         YINIT_LIST_HEAD(&dsc->others);
1720
1721                         if(!search_contexts.next)
1722                                 YINIT_LIST_HEAD(&search_contexts);
1723
1724                         ylist_add(&dsc->others,&search_contexts);       
1725                         yaffsfs_SetDirRewound(dsc);
1726                 }
1727
1728         }
1729
1730         yaffsfs_Unlock();
1731
1732         return dir;
1733 }
1734
1735 struct yaffs_dirent *yaffs_readdir(yaffs_DIR *dirp)
1736 {
1737         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
1738         struct yaffs_dirent *retVal = NULL;
1739
1740         yaffsfs_Lock();
1741
1742         if(dsc && dsc->magic == YAFFS_MAGIC){
1743                 yaffsfs_SetError(0);
1744                 if(dsc->nextReturn){
1745                         dsc->de.d_ino = yaffs_GetEquivalentObject(dsc->nextReturn)->objectId;
1746                         dsc->de.d_dont_use = (unsigned)dsc->nextReturn;
1747                         dsc->de.d_off = dsc->offset++;
1748                         yaffs_GetObjectName(dsc->nextReturn,dsc->de.d_name,NAME_MAX);
1749                         if(yaffs_strnlen(dsc->de.d_name,NAME_MAX+1) == 0)
1750                         {
1751                                 // this should not happen!
1752                                 yaffs_strcpy(dsc->de.d_name,_Y("zz"));
1753                         }
1754                         dsc->de.d_reclen = sizeof(struct yaffs_dirent);
1755                         retVal = &dsc->de;
1756                         yaffsfs_DirAdvance(dsc);
1757                 } else
1758                         retVal = NULL;
1759         } else
1760                 yaffsfs_SetError(-EBADF);
1761
1762         yaffsfs_Unlock();
1763
1764         return retVal;
1765
1766 }
1767
1768
1769 void yaffs_rewinddir(yaffs_DIR *dirp)
1770 {
1771         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
1772
1773         yaffsfs_Lock();
1774
1775         yaffsfs_SetDirRewound(dsc);
1776
1777         yaffsfs_Unlock();
1778 }
1779
1780
1781 int yaffs_closedir(yaffs_DIR *dirp)
1782 {
1783         yaffsfs_DirectorySearchContext *dsc = (yaffsfs_DirectorySearchContext *)dirp;
1784
1785         yaffsfs_Lock();
1786         dsc->magic = 0;
1787         ylist_del(&dsc->others); /* unhook from list */
1788         YFREE(dsc);
1789         yaffsfs_Unlock();
1790         return 0;
1791 }
1792
1793 // end of directory stuff
1794
1795
1796 int yaffs_symlink(const YCHAR *oldpath, const YCHAR *newpath)
1797 {
1798         yaffs_Object *parent = NULL;
1799         yaffs_Object *obj;
1800         YCHAR *name;
1801         int retVal= -1;
1802         int mode = 0; // ignore for now
1803
1804         yaffsfs_Lock();
1805         parent = yaffsfs_FindDirectory(NULL,newpath,&name,0);
1806         if(parent && parent->myDev->readOnly)
1807                 yaffsfs_SetError(-EINVAL);
1808         else if(parent){
1809                 obj = yaffs_MknodSymLink(parent,name,mode,0,0,oldpath);
1810                 if(obj)
1811                         retVal = 0;
1812                 else{
1813                         yaffsfs_SetError(-ENOSPC); // just assume no space for now
1814                         retVal = -1;
1815                 }
1816         } else {
1817                 yaffsfs_SetError(-EINVAL);
1818                 retVal = -1;
1819         }
1820
1821         yaffsfs_Unlock();
1822
1823         return retVal;
1824
1825 }
1826
1827 int yaffs_readlink(const YCHAR *path, YCHAR *buf, int bufsiz)
1828 {
1829         yaffs_Object *obj = NULL;
1830         int retVal;
1831
1832
1833         yaffsfs_Lock();
1834
1835         obj = yaffsfs_FindObject(NULL,path,0);
1836
1837         if(!obj) {
1838                 yaffsfs_SetError(-ENOENT);
1839                 retVal = -1;
1840         } else if(obj->variantType != YAFFS_OBJECT_TYPE_SYMLINK) {
1841                 yaffsfs_SetError(-EINVAL);
1842                 retVal = -1;
1843         } else {
1844                 YCHAR *alias = obj->variant.symLinkVariant.alias;
1845                 memset(buf,0,bufsiz);
1846                 yaffs_strncpy(buf,alias,bufsiz - 1);
1847                 retVal = 0;
1848         }
1849         yaffsfs_Unlock();
1850         return retVal;
1851 }
1852
1853 int yaffs_link(const YCHAR *oldpath, const YCHAR *newpath)
1854 {
1855         // Creates a link called newpath to existing oldpath
1856         yaffs_Object *obj = NULL;
1857         yaffs_Object *target = NULL;
1858         int retVal = 0;
1859         int newNameLength = 0;
1860
1861
1862         yaffsfs_Lock();
1863
1864         obj = yaffsfs_FindObject(NULL,oldpath,0);
1865         target = yaffsfs_FindObject(NULL,newpath,0);
1866
1867         if(!obj) {
1868                 yaffsfs_SetError(-ENOENT);
1869                 retVal = -1;
1870         } else if(obj->myDev->readOnly){
1871                 yaffsfs_SetError(-EINVAL);
1872                 retVal= -1;
1873         } else if(target) {
1874                 yaffsfs_SetError(-EEXIST);
1875                 retVal = -1;
1876         } else {
1877                 yaffs_Object *newdir = NULL;
1878                 yaffs_Object *link = NULL;
1879
1880                 YCHAR *newname;
1881
1882                 newdir = yaffsfs_FindDirectory(NULL,newpath,&newname,0);
1883
1884                 if(!newdir){
1885                         yaffsfs_SetError(-ENOTDIR);
1886                         retVal = -1;
1887                 }else if(newdir->myDev != obj->myDev){
1888                         yaffsfs_SetError(-EXDEV);
1889                         retVal = -1;
1890                 }
1891                 
1892                 newNameLength = yaffs_strnlen(newname,YAFFS_MAX_NAME_LENGTH+1);
1893                 
1894                 if(newNameLength == 0){
1895                         yaffsfs_SetError(-ENOENT);
1896                         retVal = -1;
1897                 } else if (newNameLength > YAFFS_MAX_NAME_LENGTH){
1898                         yaffsfs_SetError(-ENAMETOOLONG);
1899                         retVal = -1;
1900                 }
1901                 
1902                 if(retVal == 0) {
1903                         link = yaffs_Link(newdir,newname,obj);
1904                         if(link)
1905                                 retVal = 0;
1906                         else{
1907                                 yaffsfs_SetError(-ENOSPC);
1908                                 retVal = -1;
1909                         }
1910
1911                 }
1912         }
1913         yaffsfs_Unlock();
1914
1915         return retVal;
1916 }
1917
1918 int yaffs_mknod(const YCHAR *pathname, mode_t mode, dev_t dev)
1919 {
1920         return -1;
1921 }
1922
1923 int yaffs_DumpDevStruct(const YCHAR *path)
1924 {
1925 #if 0
1926         YCHAR *rest;
1927
1928         yaffs_Object *obj = yaffsfs_FindRoot(path,&rest);
1929
1930         if(obj){
1931                 yaffs_Device *dev = obj->myDev;
1932
1933                 printf("\n"
1934                            "nPageWrites.......... %d\n"
1935                            "nPageReads........... %d\n"
1936                            "nBlockErasures....... %d\n"
1937                            "nGCCopies............ %d\n"
1938                            "garbageCollections... %d\n"
1939                            "passiveGarbageColl'ns %d\n"
1940                            "\n",
1941                                 dev->nPageWrites,
1942                                 dev->nPageReads,
1943                                 dev->nBlockErasures,
1944                                 dev->nGCCopies,
1945                                 dev->garbageCollections,
1946                                 dev->passiveGarbageCollections
1947                 );
1948
1949         }
1950
1951 #endif
1952         return 0;
1953 }
1954