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