Add nfs support.
[yaffs2.git] / yaffs_fs.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2009 Aleph One Ltd.
5  *   for Toby Churchill Ltd and Brightstar Engineering
6  *
7  * Created by Charles Manning <charles@aleph1.co.uk>
8  * Acknowledgements:
9  * Luc van OostenRyck for numerous patches.
10  * Nick Bane for numerous patches.
11  * Nick Bane for 2.5/2.6 integration.
12  * Andras Toth for mknod rdev issue.
13  * Michael Fischer for finding the problem with inode inconsistency.
14  * Some code bodily lifted from JFFS
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License version 2 as
18  * published by the Free Software Foundation.
19  */
20
21 /*
22  *
23  * This is the file system front-end to YAFFS that hooks it up to
24  * the VFS.
25  *
26  * Special notes:
27  * >> 2.4: sb->u.generic_sbp points to the yaffs_Device associated with
28  *         this superblock
29  * >> 2.6: sb->s_fs_info  points to the yaffs_Device associated with this
30  *         superblock
31  * >> inode->u.generic_ip points to the associated yaffs_Object.
32  */
33
34 const char *yaffs_fs_c_version =
35     "$Id: yaffs_fs.c,v 1.102 2010-03-15 23:10:33 charles Exp $";
36 extern const char *yaffs_guts_c_version;
37
38 #include <linux/version.h>
39
40 #if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 10))
41 #define YAFFS_COMPILE_BACKGROUND
42 #endif
43
44 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19))
45 #include <linux/config.h>
46 #endif
47 #include <linux/kernel.h>
48 #include <linux/module.h>
49 #include <linux/slab.h>
50 #include <linux/init.h>
51 #include <linux/fs.h>
52 #include <linux/proc_fs.h>
53 #include <linux/smp_lock.h>
54 #include <linux/pagemap.h>
55 #include <linux/mtd/mtd.h>
56 #include <linux/interrupt.h>
57 #include <linux/string.h>
58 #include <linux/ctype.h>
59 #include <linux/exportfs.h>
60
61 #ifdef YAFFS_COMPILE_BACKGROUND
62 #include <linux/kthread.h>
63 #include <linux/delay.h>
64 #endif
65
66
67 #include "asm/div64.h"
68
69
70 #define LOCK_TRACE 0
71
72 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
73
74 #include <linux/statfs.h>       /* Added NCB 15-8-2003 */
75 #include <linux/statfs.h>
76 #define UnlockPage(p) unlock_page(p)
77 #define Page_Uptodate(page)     test_bit(PG_uptodate, &(page)->flags)
78
79 /* FIXME: use sb->s_id instead ? */
80 #define yaffs_devname(sb, buf)  bdevname(sb->s_bdev, buf)
81
82 #else
83
84 #include <linux/locks.h>
85 #define BDEVNAME_SIZE           0
86 #define yaffs_devname(sb, buf)  kdevname(sb->s_dev)
87
88 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 5, 0))
89 /* added NCB 26/5/2006 for 2.4.25-vrs2-tcl1 kernel */
90 #define __user
91 #endif
92
93 #endif
94
95 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 26))
96 #define YPROC_ROOT  (&proc_root)
97 #else
98 #define YPROC_ROOT  NULL
99 #endif
100
101 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
102 #define WRITE_SIZE_STR "writesize"
103 #define WRITE_SIZE(mtd) ((mtd)->writesize)
104 #else
105 #define WRITE_SIZE_STR "oobblock"
106 #define WRITE_SIZE(mtd) ((mtd)->oobblock)
107 #endif
108
109 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 27))
110 #define YAFFS_USE_WRITE_BEGIN_END 1
111 #else
112 #define YAFFS_USE_WRITE_BEGIN_END 0
113 #endif
114
115 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 28))
116 static uint32_t YCALCBLOCKS(uint64_t partition_size, uint32_t block_size)
117 {
118         uint64_t result = partition_size;
119         do_div(result, block_size);
120         return (uint32_t)result;
121 }
122 #else
123 #define YCALCBLOCKS(s, b) ((s)/(b))
124 #endif
125
126 #include <linux/uaccess.h>
127
128 #include "yportenv.h"
129 #include "yaffs_trace.h"
130 #include "yaffs_guts.h"
131
132 #include "yaffs_linux.h"
133
134 #include <linux/mtd/mtd.h>
135 #include "yaffs_mtdif.h"
136 #include "yaffs_mtdif1.h"
137 #include "yaffs_mtdif2.h"
138
139 unsigned int yaffs_traceMask = YAFFS_TRACE_BAD_BLOCKS | YAFFS_TRACE_ALWAYS;
140 unsigned int yaffs_wr_attempts = YAFFS_WR_ATTEMPTS;
141 unsigned int yaffs_auto_checkpoint = 1;
142 unsigned int yaffs_gc_control = 1;
143
144 /* Module Parameters */
145 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
146 module_param(yaffs_traceMask, uint, 0644);
147 module_param(yaffs_wr_attempts, uint, 0644);
148 module_param(yaffs_auto_checkpoint, uint, 0644);
149 module_param(yaffs_gc_control, uint, 0644);
150 #else
151 MODULE_PARM(yaffs_traceMask, "i");
152 MODULE_PARM(yaffs_wr_attempts, "i");
153 MODULE_PARM(yaffs_auto_checkpoint, "i");
154 MODULE_PARM(yaffs_gc_control, "i");
155 #endif
156
157 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 25))
158 /* use iget and read_inode */
159 #define Y_IGET(sb, inum) iget((sb), (inum))
160 static void yaffs_read_inode(struct inode *inode);
161
162 #else
163 /* Call local equivalent */
164 #define YAFFS_USE_OWN_IGET
165 #define Y_IGET(sb, inum) yaffs_iget((sb), (inum))
166
167 static struct inode *yaffs_iget(struct super_block *sb, unsigned long ino);
168 #endif
169
170 /*#define T(x) printk x */
171
172 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 18))
173 #define yaffs_InodeToObjectLV(iptr) ((iptr)->i_private)
174 #else
175 #define yaffs_InodeToObjectLV(iptr) ((iptr)->u.generic_ip)
176 #endif
177
178 #define yaffs_InodeToObject(iptr) ((yaffs_Object *)(yaffs_InodeToObjectLV(iptr)))
179 #define yaffs_DentryToObject(dptr) yaffs_InodeToObject((dptr)->d_inode)
180
181 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
182 #define yaffs_SuperToDevice(sb) ((yaffs_Device *)sb->s_fs_info)
183 #else
184 #define yaffs_SuperToDevice(sb) ((yaffs_Device *)sb->u.generic_sbp)
185 #endif
186
187
188 #define update_dir_time(dir) do {\
189                         (dir)->i_ctime = (dir)->i_mtime = CURRENT_TIME; \
190                 } while(0)
191                 
192 static void yaffs_put_super(struct super_block *sb);
193
194 static ssize_t yaffs_file_write(struct file *f, const char *buf, size_t n,
195                                 loff_t *pos);
196 static ssize_t yaffs_hold_space(struct file *f);
197 static void yaffs_release_space(struct file *f);
198
199 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
200 static int yaffs_file_flush(struct file *file, fl_owner_t id);
201 #else
202 static int yaffs_file_flush(struct file *file);
203 #endif
204
205 static int yaffs_sync_object(struct file *file, struct dentry *dentry,
206                                 int datasync);
207
208 static int yaffs_readdir(struct file *f, void *dirent, filldir_t filldir);
209
210 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
211 static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode,
212                         struct nameidata *n);
213 static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry,
214                                         struct nameidata *n);
215 #else
216 static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode);
217 static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry);
218 #endif
219 static int yaffs_link(struct dentry *old_dentry, struct inode *dir,
220                         struct dentry *dentry);
221 static int yaffs_unlink(struct inode *dir, struct dentry *dentry);
222 static int yaffs_symlink(struct inode *dir, struct dentry *dentry,
223                         const char *symname);
224 static int yaffs_mkdir(struct inode *dir, struct dentry *dentry, int mode);
225
226 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
227 static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
228                         dev_t dev);
229 #else
230 static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
231                         int dev);
232 #endif
233 static int yaffs_rename(struct inode *old_dir, struct dentry *old_dentry,
234                         struct inode *new_dir, struct dentry *new_dentry);
235 static int yaffs_setattr(struct dentry *dentry, struct iattr *attr);
236
237 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
238 static int yaffs_sync_fs(struct super_block *sb, int wait);
239 static void yaffs_write_super(struct super_block *sb);
240 #else
241 static int yaffs_sync_fs(struct super_block *sb);
242 static int yaffs_write_super(struct super_block *sb);
243 #endif
244
245 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
246 static int yaffs_statfs(struct dentry *dentry, struct kstatfs *buf);
247 #elif (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
248 static int yaffs_statfs(struct super_block *sb, struct kstatfs *buf);
249 #else
250 static int yaffs_statfs(struct super_block *sb, struct statfs *buf);
251 #endif
252
253 #ifdef YAFFS_HAS_PUT_INODE
254 static void yaffs_put_inode(struct inode *inode);
255 #endif
256
257 static void yaffs_delete_inode(struct inode *);
258 static void yaffs_clear_inode(struct inode *);
259
260 static int yaffs_readpage(struct file *file, struct page *page);
261 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
262 static int yaffs_writepage(struct page *page, struct writeback_control *wbc);
263 #else
264 static int yaffs_writepage(struct page *page);
265 #endif
266
267
268 #if (YAFFS_USE_WRITE_BEGIN_END != 0)
269 static int yaffs_write_begin(struct file *filp, struct address_space *mapping,
270                                 loff_t pos, unsigned len, unsigned flags,
271                                 struct page **pagep, void **fsdata);
272 static int yaffs_write_end(struct file *filp, struct address_space *mapping,
273                                 loff_t pos, unsigned len, unsigned copied,
274                                 struct page *pg, void *fsdadata);
275 #else
276 static int yaffs_prepare_write(struct file *f, struct page *pg,
277                                 unsigned offset, unsigned to);
278 static int yaffs_commit_write(struct file *f, struct page *pg, unsigned offset,
279                                 unsigned to);
280
281 #endif
282
283 static int yaffs_readlink(struct dentry *dentry, char __user *buffer,
284                                 int buflen);
285 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
286 static void *yaffs_follow_link(struct dentry *dentry, struct nameidata *nd);
287 #else
288 static int yaffs_follow_link(struct dentry *dentry, struct nameidata *nd);
289 #endif
290 static loff_t yaffs_dir_llseek(struct file *file, loff_t offset, int origin);
291
292 static struct address_space_operations yaffs_file_address_operations = {
293         .readpage = yaffs_readpage,
294         .writepage = yaffs_writepage,
295 #if (YAFFS_USE_WRITE_BEGIN_END > 0)
296         .write_begin = yaffs_write_begin,
297         .write_end = yaffs_write_end,
298 #else
299         .prepare_write = yaffs_prepare_write,
300         .commit_write = yaffs_commit_write,
301 #endif
302 };
303
304 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 22))
305 static const struct file_operations yaffs_file_operations = {
306         .read = do_sync_read,
307         .write = do_sync_write,
308         .aio_read = generic_file_aio_read,
309         .aio_write = generic_file_aio_write,
310         .mmap = generic_file_mmap,
311         .flush = yaffs_file_flush,
312         .fsync = yaffs_sync_object,
313         .splice_read = generic_file_splice_read,
314         .splice_write = generic_file_splice_write,
315         .llseek = generic_file_llseek,
316 };
317
318 #elif (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 18))
319
320 static const struct file_operations yaffs_file_operations = {
321         .read = do_sync_read,
322         .write = do_sync_write,
323         .aio_read = generic_file_aio_read,
324         .aio_write = generic_file_aio_write,
325         .mmap = generic_file_mmap,
326         .flush = yaffs_file_flush,
327         .fsync = yaffs_sync_object,
328         .sendfile = generic_file_sendfile,
329 };
330
331 #else
332
333 static const struct file_operations yaffs_file_operations = {
334         .read = generic_file_read,
335         .write = generic_file_write,
336         .mmap = generic_file_mmap,
337         .flush = yaffs_file_flush,
338         .fsync = yaffs_sync_object,
339 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
340         .sendfile = generic_file_sendfile,
341 #endif
342 };
343 #endif
344
345 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,25))
346 static void zero_user_segment(struct page *page, unsigned start, unsigned end)
347 {
348         void * kaddr = kmap_atomic(page, KM_USER0);
349         memset(kaddr + start, 0, end - start);
350         kunmap_atomic(kaddr, KM_USER0);
351         flush_dcache_page(page);
352 }
353 #endif
354
355
356 static const struct inode_operations yaffs_file_inode_operations = {
357         .setattr = yaffs_setattr,
358 };
359
360 static const struct inode_operations yaffs_symlink_inode_operations = {
361         .readlink = yaffs_readlink,
362         .follow_link = yaffs_follow_link,
363         .setattr = yaffs_setattr,
364 };
365
366 static const struct inode_operations yaffs_dir_inode_operations = {
367         .create = yaffs_create,
368         .lookup = yaffs_lookup,
369         .link = yaffs_link,
370         .unlink = yaffs_unlink,
371         .symlink = yaffs_symlink,
372         .mkdir = yaffs_mkdir,
373         .rmdir = yaffs_unlink,
374         .mknod = yaffs_mknod,
375         .rename = yaffs_rename,
376         .setattr = yaffs_setattr,
377 };
378
379 static const struct file_operations yaffs_dir_operations = {
380         .read = generic_read_dir,
381         .readdir = yaffs_readdir,
382         .fsync = yaffs_sync_object,
383         .llseek = yaffs_dir_llseek,
384 };
385
386 static const struct super_operations yaffs_super_ops = {
387         .statfs = yaffs_statfs,
388
389 #ifndef YAFFS_USE_OWN_IGET
390         .read_inode = yaffs_read_inode,
391 #endif
392 #ifdef YAFFS_HAS_PUT_INODE
393         .put_inode = yaffs_put_inode,
394 #endif
395         .put_super = yaffs_put_super,
396         .delete_inode = yaffs_delete_inode,
397         .clear_inode = yaffs_clear_inode,
398         .sync_fs = yaffs_sync_fs,
399         .write_super = yaffs_write_super,
400 };
401
402 static unsigned yaffs_gc_control_callback(yaffs_Device *dev)
403 {
404         return yaffs_gc_control;
405 }
406                                                                                                                         
407 static void yaffs_GrossLock(yaffs_Device *dev)
408 {
409         T(LOCK_TRACE && YAFFS_TRACE_OS, ("yaffs locking %p\n", current));
410         down(&(yaffs_DeviceToContext(dev)->grossLock));
411         T(LOCK_TRACE && YAFFS_TRACE_OS, ("yaffs locked %p\n", current));
412 }
413
414 static void yaffs_GrossUnlock(yaffs_Device *dev)
415 {
416         T(LOCK_TRACE && YAFFS_TRACE_OS, ("yaffs unlocking %p\n", current));
417         up(&(yaffs_DeviceToContext(dev)->grossLock));
418 }
419
420
421
422 static struct inode *
423 yaffs2_nfs_get_inode(struct super_block *sb, uint64_t ino, uint32_t generation)
424 {
425         return yaffs_iget(sb, ino);
426 }
427
428 static struct dentry *
429 yaffs2_fh_to_dentry(struct super_block *sb, struct fid *fid, int fh_len, int fh_type)
430 {
431         return generic_fh_to_dentry(sb, fid, fh_len, fh_type, yaffs2_nfs_get_inode) ;
432 }
433
434 static struct dentry *
435  yaffs2_fh_to_parent(struct super_block *sb, struct fid *fid, int fh_len, int fh_type)
436 {
437         return generic_fh_to_parent(sb, fid, fh_len, fh_type, yaffs2_nfs_get_inode);
438 }
439
440 struct dentry *yaffs2_get_parent(struct dentry *dentry)
441 {
442
443         struct super_block *sb = dentry->d_inode->i_sb;
444         struct dentry *parent = ERR_PTR(-ENOENT);
445         struct inode *inode;
446         unsigned long parent_ino;
447         yaffs_Object *d_obj;
448         yaffs_Object *parent_obj;
449
450         d_obj = yaffs_InodeToObject(dentry->d_inode);
451
452         if (d_obj) {
453                 parent_obj = d_obj->parent;
454                 if (parent_obj) {
455                         parent_ino = yaffs_GetObjectInode(parent_obj);
456                         inode = yaffs_iget(sb, parent_ino);
457
458                         if (IS_ERR(inode)) {
459                                 parent = ERR_CAST(inode);
460                         } else {
461                                 parent = d_obtain_alias(inode);
462                                 if (!IS_ERR(parent)) {
463                                         parent = ERR_PTR(-ENOMEM);
464                                         iput(inode);
465                                 }
466                         }
467                 }
468         }
469
470         return parent;
471 }
472
473 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,9))
474 /* Just declare a zero structure as a NULL value implies
475  * using the default functions of expfs.
476  */
477
478 static struct export_operations yaffs_export_ops =
479 {
480         .fh_to_dentry = yaffs2_fh_to_dentry,
481         .fh_to_parent = yaffs2_fh_to_parent,
482         .get_parent = yaffs2_get_parent,
483 } ;
484
485 #endif
486
487 /*-----------------------------------------------------------------*/
488 /* Directory search context allows us to unlock access to yaffs during
489  * filldir without causing problems with the directory being modified.
490  * This is similar to the tried and tested mechanism used in yaffs direct.
491  *
492  * A search context iterates along a doubly linked list of siblings in the
493  * directory. If the iterating object is deleted then this would corrupt
494  * the list iteration, likely causing a crash. The search context avoids
495  * this by using the removeObjectCallback to move the search context to the
496  * next object before the object is deleted.
497  *
498  * Many readdirs (and thus seach conexts) may be alive simulateously so
499  * each yaffs_Device has a list of these.
500  *
501  * A seach context lives for the duration of a readdir.
502  *
503  * All these functions must be called while yaffs is locked.
504  */
505
506 struct yaffs_SearchContext {
507         yaffs_Device *dev;
508         yaffs_Object *dirObj;
509         yaffs_Object *nextReturn;
510         struct ylist_head others;
511 };
512
513 /*
514  * yaffs_NewSearch() creates a new search context, initialises it and
515  * adds it to the device's search context list.
516  *
517  * Called at start of readdir.
518  */
519 static struct yaffs_SearchContext * yaffs_NewSearch(yaffs_Object *dir)
520 {
521         yaffs_Device *dev = dir->myDev;
522         struct yaffs_SearchContext *sc = YMALLOC(sizeof(struct yaffs_SearchContext));
523         if(sc){
524                 sc->dirObj = dir;
525                 sc->dev = dev;
526                 if( ylist_empty(&sc->dirObj->variant.directoryVariant.children))
527                         sc->nextReturn = NULL;
528                 else
529                         sc->nextReturn = ylist_entry(
530                                 dir->variant.directoryVariant.children.next,
531                                 yaffs_Object,siblings);
532                 YINIT_LIST_HEAD(&sc->others);
533                 ylist_add(&sc->others,&(yaffs_DeviceToContext(dev)->searchContexts));
534         }
535         return sc;
536 }
537
538 /*
539  * yaffs_EndSearch() disposes of a search context and cleans up.
540  */
541 static void yaffs_EndSearch(struct yaffs_SearchContext * sc)
542 {
543         if(sc){
544                 ylist_del(&sc->others);
545                 YFREE(sc);
546         }
547 }
548
549 /*
550  * yaffs_SearchAdvance() moves a search context to the next object.
551  * Called when the search iterates or when an object removal causes
552  * the search context to be moved to the next object.
553  */
554 static void yaffs_SearchAdvance(struct yaffs_SearchContext *sc)
555 {
556         if(!sc)
557                 return;
558
559         if( sc->nextReturn == NULL ||
560                 ylist_empty(&sc->dirObj->variant.directoryVariant.children))
561                 sc->nextReturn = NULL;
562         else {
563                 struct ylist_head *next = sc->nextReturn->siblings.next;
564
565                 if( next == &sc->dirObj->variant.directoryVariant.children)
566                         sc->nextReturn = NULL; /* end of list */
567                 else
568                         sc->nextReturn = ylist_entry(next,yaffs_Object,siblings);
569         }
570 }
571
572 /*
573  * yaffs_RemoveObjectCallback() is called when an object is unlinked.
574  * We check open search contexts and advance any which are currently
575  * on the object being iterated.
576  */
577 static void yaffs_RemoveObjectCallback(yaffs_Object *obj)
578 {
579
580         struct ylist_head *i;
581         struct yaffs_SearchContext *sc;
582         struct ylist_head *search_contexts = &(yaffs_DeviceToContext(obj->myDev)->searchContexts);
583
584
585         /* Iterate through the directory search contexts.
586          * If any are currently on the object being removed, then advance
587          * the search context to the next object to prevent a hanging pointer.
588          */
589          ylist_for_each(i, search_contexts) {
590                 if (i) {
591                         sc = ylist_entry(i, struct yaffs_SearchContext,others);
592                         if(sc->nextReturn == obj)
593                                 yaffs_SearchAdvance(sc);
594                 }
595         }
596
597 }
598
599
600 /*-----------------------------------------------------------------*/
601
602 static int yaffs_readlink(struct dentry *dentry, char __user *buffer,
603                         int buflen)
604 {
605         unsigned char *alias;
606         int ret;
607
608         yaffs_Device *dev = yaffs_DentryToObject(dentry)->myDev;
609
610         yaffs_GrossLock(dev);
611
612         alias = yaffs_GetSymlinkAlias(yaffs_DentryToObject(dentry));
613
614         yaffs_GrossUnlock(dev);
615
616         if (!alias)
617                 return -ENOMEM;
618
619         ret = vfs_readlink(dentry, buffer, buflen, alias);
620         kfree(alias);
621         return ret;
622 }
623
624 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
625 static void *yaffs_follow_link(struct dentry *dentry, struct nameidata *nd)
626 #else
627 static int yaffs_follow_link(struct dentry *dentry, struct nameidata *nd)
628 #endif
629 {
630         unsigned char *alias;
631         int ret;
632         yaffs_Device *dev = yaffs_DentryToObject(dentry)->myDev;
633
634         yaffs_GrossLock(dev);
635
636         alias = yaffs_GetSymlinkAlias(yaffs_DentryToObject(dentry));
637
638         yaffs_GrossUnlock(dev);
639
640         if (!alias) {
641                 ret = -ENOMEM;
642                 goto out;
643         }
644
645         ret = vfs_follow_link(nd, alias);
646         kfree(alias);
647 out:
648 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
649         return ERR_PTR(ret);
650 #else
651         return ret;
652 #endif
653 }
654
655 struct inode *yaffs_get_inode(struct super_block *sb, int mode, int dev,
656                                 yaffs_Object *obj);
657
658 /*
659  * Lookup is used to find objects in the fs
660  */
661 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
662
663 static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry,
664                                 struct nameidata *n)
665 #else
666 static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry)
667 #endif
668 {
669         yaffs_Object *obj;
670         struct inode *inode = NULL;     /* NCB 2.5/2.6 needs NULL here */
671
672         yaffs_Device *dev = yaffs_InodeToObject(dir)->myDev;
673
674         if(current != yaffs_DeviceToContext(dev)->readdirProcess)
675                 yaffs_GrossLock(dev);
676
677         T(YAFFS_TRACE_OS,
678                 ("yaffs_lookup for %d:%s\n",
679                 yaffs_InodeToObject(dir)->objectId, dentry->d_name.name));
680
681         obj = yaffs_FindObjectByName(yaffs_InodeToObject(dir),
682                                         dentry->d_name.name);
683
684         obj = yaffs_GetEquivalentObject(obj);   /* in case it was a hardlink */
685
686         /* Can't hold gross lock when calling yaffs_get_inode() */
687         if(current != yaffs_DeviceToContext(dev)->readdirProcess)
688                 yaffs_GrossUnlock(dev);
689
690         if (obj) {
691                 T(YAFFS_TRACE_OS,
692                         ("yaffs_lookup found %d\n", obj->objectId));
693
694                 inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
695
696                 if (inode) {
697                         T(YAFFS_TRACE_OS,
698                                 ("yaffs_loookup dentry \n"));
699 /* #if 0 asserted by NCB for 2.5/6 compatability - falls through to
700  * d_add even if NULL inode */
701 #if 0
702                         /*dget(dentry); // try to solve directory bug */
703                         d_add(dentry, inode);
704
705                         /* return dentry; */
706                         return NULL;
707 #endif
708                 }
709
710         } else {
711                 T(YAFFS_TRACE_OS, ("yaffs_lookup not found\n"));
712
713         }
714
715 /* added NCB for 2.5/6 compatability - forces add even if inode is
716  * NULL which creates dentry hash */
717         d_add(dentry, inode);
718
719         return NULL;
720 }
721
722
723 #ifdef YAFFS_HAS_PUT_INODE
724
725 /* For now put inode is just for debugging
726  * Put inode is called when the inode **structure** is put.
727  */
728 static void yaffs_put_inode(struct inode *inode)
729 {
730         T(YAFFS_TRACE_OS,
731                 ("yaffs_put_inode: ino %d, count %d\n", (int)inode->i_ino,
732                 atomic_read(&inode->i_count)));
733
734 }
735 #endif
736
737 /* clear is called to tell the fs to release any per-inode data it holds */
738 static void yaffs_clear_inode(struct inode *inode)
739 {
740         yaffs_Object *obj;
741         yaffs_Device *dev;
742
743         obj = yaffs_InodeToObject(inode);
744
745         T(YAFFS_TRACE_OS,
746                 ("yaffs_clear_inode: ino %d, count %d %s\n", (int)inode->i_ino,
747                 atomic_read(&inode->i_count),
748                 obj ? "object exists" : "null object"));
749
750         if (obj) {
751                 dev = obj->myDev;
752                 yaffs_GrossLock(dev);
753
754                 /* Clear the association between the inode and
755                  * the yaffs_Object.
756                  */
757                 obj->myInode = NULL;
758                 yaffs_InodeToObjectLV(inode) = NULL;
759
760                 /* If the object freeing was deferred, then the real
761                  * free happens now.
762                  * This should fix the inode inconsistency problem.
763                  */
764
765                 yaffs_HandleDeferedFree(obj);
766
767                 yaffs_GrossUnlock(dev);
768         }
769
770 }
771
772 /* delete is called when the link count is zero and the inode
773  * is put (ie. nobody wants to know about it anymore, time to
774  * delete the file).
775  * NB Must call clear_inode()
776  */
777 static void yaffs_delete_inode(struct inode *inode)
778 {
779         yaffs_Object *obj = yaffs_InodeToObject(inode);
780         yaffs_Device *dev;
781
782         T(YAFFS_TRACE_OS,
783                 ("yaffs_delete_inode: ino %d, count %d %s\n", (int)inode->i_ino,
784                 atomic_read(&inode->i_count),
785                 obj ? "object exists" : "null object"));
786
787         if (obj) {
788                 dev = obj->myDev;
789                 yaffs_GrossLock(dev);
790                 yaffs_DeleteObject(obj);
791                 yaffs_GrossUnlock(dev);
792         }
793 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 13))
794         truncate_inode_pages(&inode->i_data, 0);
795 #endif
796         clear_inode(inode);
797 }
798
799 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
800 static int yaffs_file_flush(struct file *file, fl_owner_t id)
801 #else
802 static int yaffs_file_flush(struct file *file)
803 #endif
804 {
805         yaffs_Object *obj = yaffs_DentryToObject(file->f_dentry);
806
807         yaffs_Device *dev = obj->myDev;
808
809         T(YAFFS_TRACE_OS,
810                 ("yaffs_file_flush object %d (%s)\n", obj->objectId,
811                 obj->dirty ? "dirty" : "clean"));
812
813         yaffs_GrossLock(dev);
814
815         yaffs_FlushFile(obj, 1, 0);
816
817         yaffs_GrossUnlock(dev);
818
819         return 0;
820 }
821
822 static int yaffs_readpage_nolock(struct file *f, struct page *pg)
823 {
824         /* Lifted from jffs2 */
825
826         yaffs_Object *obj;
827         unsigned char *pg_buf;
828         int ret;
829
830         yaffs_Device *dev;
831
832         T(YAFFS_TRACE_OS, ("yaffs_readpage_nolock at %08x, size %08x\n",
833                         (unsigned)(pg->index << PAGE_CACHE_SHIFT),
834                         (unsigned)PAGE_CACHE_SIZE));
835
836         obj = yaffs_DentryToObject(f->f_dentry);
837
838         dev = obj->myDev;
839
840 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
841         BUG_ON(!PageLocked(pg));
842 #else
843         if (!PageLocked(pg))
844                 PAGE_BUG(pg);
845 #endif
846
847         pg_buf = kmap(pg);
848         /* FIXME: Can kmap fail? */
849
850         yaffs_GrossLock(dev);
851
852         ret = yaffs_ReadDataFromFile(obj, pg_buf,
853                                 pg->index << PAGE_CACHE_SHIFT,
854                                 PAGE_CACHE_SIZE);
855
856         yaffs_GrossUnlock(dev);
857
858         if (ret >= 0)
859                 ret = 0;
860
861         if (ret) {
862                 ClearPageUptodate(pg);
863                 SetPageError(pg);
864         } else {
865                 SetPageUptodate(pg);
866                 ClearPageError(pg);
867         }
868
869         flush_dcache_page(pg);
870         kunmap(pg);
871
872         T(YAFFS_TRACE_OS, ("yaffs_readpage_nolock done\n"));
873         return ret;
874 }
875
876 static int yaffs_readpage_unlock(struct file *f, struct page *pg)
877 {
878         int ret = yaffs_readpage_nolock(f, pg);
879         UnlockPage(pg);
880         return ret;
881 }
882
883 static int yaffs_readpage(struct file *f, struct page *pg)
884 {
885         int ret;
886
887         T(YAFFS_TRACE_OS, ("yaffs_readpage\n"));
888         ret=yaffs_readpage_unlock(f, pg);
889         T(YAFFS_TRACE_OS, ("yaffs_readpage done\n"));
890         return ret;
891 }
892
893 /* writepage inspired by/stolen from smbfs */
894
895 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
896 static int yaffs_writepage(struct page *page, struct writeback_control *wbc)
897 #else
898 static int yaffs_writepage(struct page *page)
899 #endif
900 {
901         struct address_space *mapping = page->mapping;
902         struct inode *inode;
903         unsigned long end_index;
904         char *buffer;
905         yaffs_Object *obj;
906         int nWritten = 0;
907         unsigned nBytes;
908         loff_t i_size;
909
910         if (!mapping)
911                 BUG();
912         inode = mapping->host;
913         if (!inode)
914                 BUG();
915         i_size = i_size_read(inode);
916
917         end_index = i_size >> PAGE_CACHE_SHIFT;
918
919         if(page->index < end_index)
920                 nBytes = PAGE_CACHE_SIZE;
921         else {
922                 nBytes = i_size & (PAGE_CACHE_SIZE -1);
923
924                 if (page->index > end_index || !nBytes) {
925                         T(YAFFS_TRACE_OS,
926                                 ("yaffs_writepage at %08x, inode size = %08x!!!\n",
927                                 (unsigned)(page->index << PAGE_CACHE_SHIFT),
928                                 (unsigned)inode->i_size));
929                         T(YAFFS_TRACE_OS,
930                                 ("                -> don't care!!\n"));
931
932                         zero_user_segment(page,0,PAGE_CACHE_SIZE);
933                         set_page_writeback(page);
934                         unlock_page(page);
935                         end_page_writeback(page);
936                         return 0;
937                 }
938         }
939
940         if(nBytes != PAGE_CACHE_SIZE)
941                 zero_user_segment(page,nBytes,PAGE_CACHE_SIZE);
942
943         get_page(page);
944
945         buffer = kmap(page);
946
947         obj = yaffs_InodeToObject(inode);
948         yaffs_GrossLock(obj->myDev);
949
950         T(YAFFS_TRACE_OS,
951                 ("yaffs_writepage at %08x, size %08x\n",
952                 (unsigned)(page->index << PAGE_CACHE_SHIFT), nBytes));
953         T(YAFFS_TRACE_OS,
954                 ("writepag0: obj = %05x, ino = %05x\n",
955                 (int)obj->variant.fileVariant.fileSize, (int)inode->i_size));
956
957         nWritten = yaffs_WriteDataToFile(obj, buffer,
958                         page->index << PAGE_CACHE_SHIFT, nBytes, 0);
959
960         T(YAFFS_TRACE_OS,
961                 ("writepag1: obj = %05x, ino = %05x\n",
962                 (int)obj->variant.fileVariant.fileSize, (int)inode->i_size));
963
964         yaffs_GrossUnlock(obj->myDev);
965
966         kunmap(page);
967         set_page_writeback(page);
968         unlock_page(page);
969         end_page_writeback(page);
970         put_page(page);
971
972         return (nWritten == nBytes) ? 0 : -ENOSPC;
973 }
974
975
976 #if (YAFFS_USE_WRITE_BEGIN_END > 0)
977 static int yaffs_write_begin(struct file *filp, struct address_space *mapping,
978                                 loff_t pos, unsigned len, unsigned flags,
979                                 struct page **pagep, void **fsdata)
980 {
981         struct page *pg = NULL;
982         pgoff_t index = pos >> PAGE_CACHE_SHIFT;
983
984         int ret = 0;
985         int space_held = 0;
986
987         /* Get a page */
988 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)
989         pg = grab_cache_page_write_begin(mapping, index, flags);
990 #else
991         pg = __grab_cache_page(mapping, index);
992 #endif
993
994         *pagep = pg;
995         if (!pg) {
996                 ret =  -ENOMEM;
997                 goto out;
998         }
999         T(YAFFS_TRACE_OS, ("start yaffs_write_begin index %d(%x) uptodate %d\n",(int)index,(int)index,Page_Uptodate(pg) ? 1 : 0));
1000
1001         /* Get fs space */
1002         space_held = yaffs_hold_space(filp);
1003
1004         if (!space_held) {
1005                 ret = -ENOSPC;
1006                 goto out;
1007         }
1008
1009         /* Update page if required */
1010
1011         if (!Page_Uptodate(pg))
1012                 ret = yaffs_readpage_nolock(filp, pg);
1013
1014         if (ret)
1015                 goto out;
1016
1017         /* Happy path return */
1018         T(YAFFS_TRACE_OS, ("end yaffs_write_begin - ok\n"));
1019
1020         return 0;
1021
1022 out:
1023         T(YAFFS_TRACE_OS, ("end yaffs_write_begin fail returning %d\n", ret));
1024         if (space_held)
1025                 yaffs_release_space(filp);
1026         if (pg) {
1027                 unlock_page(pg);
1028                 page_cache_release(pg);
1029         }
1030         return ret;
1031 }
1032
1033 #else
1034
1035 static int yaffs_prepare_write(struct file *f, struct page *pg,
1036                                 unsigned offset, unsigned to)
1037 {
1038         T(YAFFS_TRACE_OS, ("yaffs_prepair_write\n"));
1039
1040         if (!Page_Uptodate(pg))
1041                 return yaffs_readpage_nolock(f, pg);
1042         return 0;
1043 }
1044 #endif
1045
1046 #if (YAFFS_USE_WRITE_BEGIN_END > 0)
1047 static int yaffs_write_end(struct file *filp, struct address_space *mapping,
1048                                 loff_t pos, unsigned len, unsigned copied,
1049                                 struct page *pg, void *fsdadata)
1050 {
1051         int ret = 0;
1052         void *addr, *kva;
1053         uint32_t offset_into_page = pos & (PAGE_CACHE_SIZE - 1);
1054
1055         kva = kmap(pg);
1056         addr = kva + offset_into_page;
1057
1058         T(YAFFS_TRACE_OS,
1059                 ("yaffs_write_end addr %x pos %x nBytes %d\n",
1060                 (unsigned) addr,
1061                 (int)pos, copied));
1062
1063         ret = yaffs_file_write(filp, addr, copied, &pos);
1064
1065         if (ret != copied) {
1066                 T(YAFFS_TRACE_OS,
1067                         ("yaffs_write_end not same size ret %d  copied %d\n",
1068                         ret, copied));
1069                 SetPageError(pg);
1070         } else {
1071                 /* Nothing */
1072         }
1073
1074         kunmap(pg);
1075
1076         yaffs_release_space(filp);
1077         unlock_page(pg);
1078         page_cache_release(pg);
1079         return ret;
1080 }
1081 #else
1082
1083 static int yaffs_commit_write(struct file *f, struct page *pg, unsigned offset,
1084                                 unsigned to)
1085 {
1086         void *addr, *kva;
1087
1088         loff_t pos = (((loff_t) pg->index) << PAGE_CACHE_SHIFT) + offset;
1089         int nBytes = to - offset;
1090         int nWritten;
1091
1092         unsigned spos = pos;
1093         unsigned saddr;
1094
1095         kva = kmap(pg);
1096         addr = kva + offset;
1097
1098         saddr = (unsigned) addr;
1099
1100         T(YAFFS_TRACE_OS,
1101                 ("yaffs_commit_write addr %x pos %x nBytes %d\n",
1102                 saddr, spos, nBytes));
1103
1104         nWritten = yaffs_file_write(f, addr, nBytes, &pos);
1105
1106         if (nWritten != nBytes) {
1107                 T(YAFFS_TRACE_OS,
1108                         ("yaffs_commit_write not same size nWritten %d  nBytes %d\n",
1109                         nWritten, nBytes));
1110                 SetPageError(pg);
1111         } else {
1112                 /* Nothing */
1113         }
1114
1115         kunmap(pg);
1116
1117         T(YAFFS_TRACE_OS,
1118                 ("yaffs_commit_write returning %d\n",
1119                 nWritten == nBytes ? 0 : nWritten));
1120
1121         return nWritten == nBytes ? 0 : nWritten;
1122 }
1123 #endif
1124
1125
1126 static void yaffs_FillInodeFromObject(struct inode *inode, yaffs_Object *obj)
1127 {
1128         if (inode && obj) {
1129
1130
1131                 /* Check mode against the variant type and attempt to repair if broken. */
1132                 __u32 mode = obj->yst_mode;
1133                 switch (obj->variantType) {
1134                 case YAFFS_OBJECT_TYPE_FILE:
1135                         if (!S_ISREG(mode)) {
1136                                 obj->yst_mode &= ~S_IFMT;
1137                                 obj->yst_mode |= S_IFREG;
1138                         }
1139
1140                         break;
1141                 case YAFFS_OBJECT_TYPE_SYMLINK:
1142                         if (!S_ISLNK(mode)) {
1143                                 obj->yst_mode &= ~S_IFMT;
1144                                 obj->yst_mode |= S_IFLNK;
1145                         }
1146
1147                         break;
1148                 case YAFFS_OBJECT_TYPE_DIRECTORY:
1149                         if (!S_ISDIR(mode)) {
1150                                 obj->yst_mode &= ~S_IFMT;
1151                                 obj->yst_mode |= S_IFDIR;
1152                         }
1153
1154                         break;
1155                 case YAFFS_OBJECT_TYPE_UNKNOWN:
1156                 case YAFFS_OBJECT_TYPE_HARDLINK:
1157                 case YAFFS_OBJECT_TYPE_SPECIAL:
1158                 default:
1159                         /* TODO? */
1160                         break;
1161                 }
1162
1163                 inode->i_flags |= S_NOATIME;
1164
1165                 inode->i_ino = obj->objectId;
1166                 inode->i_mode = obj->yst_mode;
1167                 inode->i_uid = obj->yst_uid;
1168                 inode->i_gid = obj->yst_gid;
1169 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19))
1170                 inode->i_blksize = inode->i_sb->s_blocksize;
1171 #endif
1172 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1173
1174                 inode->i_rdev = old_decode_dev(obj->yst_rdev);
1175                 inode->i_atime.tv_sec = (time_t) (obj->yst_atime);
1176                 inode->i_atime.tv_nsec = 0;
1177                 inode->i_mtime.tv_sec = (time_t) obj->yst_mtime;
1178                 inode->i_mtime.tv_nsec = 0;
1179                 inode->i_ctime.tv_sec = (time_t) obj->yst_ctime;
1180                 inode->i_ctime.tv_nsec = 0;
1181 #else
1182                 inode->i_rdev = obj->yst_rdev;
1183                 inode->i_atime = obj->yst_atime;
1184                 inode->i_mtime = obj->yst_mtime;
1185                 inode->i_ctime = obj->yst_ctime;
1186 #endif
1187                 inode->i_size = yaffs_GetObjectFileLength(obj);
1188                 inode->i_blocks = (inode->i_size + 511) >> 9;
1189
1190                 inode->i_nlink = yaffs_GetObjectLinkCount(obj);
1191
1192                 T(YAFFS_TRACE_OS,
1193                         ("yaffs_FillInode mode %x uid %d gid %d size %d count %d\n",
1194                         inode->i_mode, inode->i_uid, inode->i_gid,
1195                         (int)inode->i_size, atomic_read(&inode->i_count)));
1196
1197                 switch (obj->yst_mode & S_IFMT) {
1198                 default:        /* fifo, device or socket */
1199 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1200                         init_special_inode(inode, obj->yst_mode,
1201                                         old_decode_dev(obj->yst_rdev));
1202 #else
1203                         init_special_inode(inode, obj->yst_mode,
1204                                         (dev_t) (obj->yst_rdev));
1205 #endif
1206                         break;
1207                 case S_IFREG:   /* file */
1208                         inode->i_op = &yaffs_file_inode_operations;
1209                         inode->i_fop = &yaffs_file_operations;
1210                         inode->i_mapping->a_ops =
1211                                 &yaffs_file_address_operations;
1212                         break;
1213                 case S_IFDIR:   /* directory */
1214                         inode->i_op = &yaffs_dir_inode_operations;
1215                         inode->i_fop = &yaffs_dir_operations;
1216                         break;
1217                 case S_IFLNK:   /* symlink */
1218                         inode->i_op = &yaffs_symlink_inode_operations;
1219                         break;
1220                 }
1221
1222                 yaffs_InodeToObjectLV(inode) = obj;
1223
1224                 obj->myInode = inode;
1225
1226         } else {
1227                 T(YAFFS_TRACE_OS,
1228                         ("yaffs_FileInode invalid parameters\n"));
1229         }
1230
1231 }
1232
1233 struct inode *yaffs_get_inode(struct super_block *sb, int mode, int dev,
1234                                 yaffs_Object *obj)
1235 {
1236         struct inode *inode;
1237
1238         if (!sb) {
1239                 T(YAFFS_TRACE_OS,
1240                         ("yaffs_get_inode for NULL super_block!!\n"));
1241                 return NULL;
1242
1243         }
1244
1245         if (!obj) {
1246                 T(YAFFS_TRACE_OS,
1247                         ("yaffs_get_inode for NULL object!!\n"));
1248                 return NULL;
1249
1250         }
1251
1252         T(YAFFS_TRACE_OS,
1253                 ("yaffs_get_inode for object %d\n", obj->objectId));
1254
1255         inode = Y_IGET(sb, obj->objectId);
1256         if (IS_ERR(inode))
1257                 return NULL;
1258
1259         /* NB Side effect: iget calls back to yaffs_read_inode(). */
1260         /* iget also increments the inode's i_count */
1261         /* NB You can't be holding grossLock or deadlock will happen! */
1262
1263         return inode;
1264 }
1265
1266 static ssize_t yaffs_file_write(struct file *f, const char *buf, size_t n,
1267                                 loff_t *pos)
1268 {
1269         yaffs_Object *obj;
1270         int nWritten, ipos;
1271         struct inode *inode;
1272         yaffs_Device *dev;
1273
1274         obj = yaffs_DentryToObject(f->f_dentry);
1275
1276         dev = obj->myDev;
1277
1278         yaffs_GrossLock(dev);
1279
1280         inode = f->f_dentry->d_inode;
1281
1282         if (!S_ISBLK(inode->i_mode) && f->f_flags & O_APPEND)
1283                 ipos = inode->i_size;
1284         else
1285                 ipos = *pos;
1286
1287         if (!obj)
1288                 T(YAFFS_TRACE_OS,
1289                         ("yaffs_file_write: hey obj is null!\n"));
1290         else
1291                 T(YAFFS_TRACE_OS,
1292                         ("yaffs_file_write about to write writing %u(%x) bytes"
1293                         "to object %d at %d(%x)\n",
1294                         (unsigned) n, (unsigned) n, obj->objectId, ipos,ipos));
1295
1296         nWritten = yaffs_WriteDataToFile(obj, buf, ipos, n, 0);
1297
1298         T(YAFFS_TRACE_OS,
1299                 ("yaffs_file_write: %d(%x) bytes written\n",
1300                 (unsigned )n,(unsigned)n));
1301
1302         if (nWritten > 0) {
1303                 ipos += nWritten;
1304                 *pos = ipos;
1305                 if (ipos > inode->i_size) {
1306                         inode->i_size = ipos;
1307                         inode->i_blocks = (ipos + 511) >> 9;
1308
1309                         T(YAFFS_TRACE_OS,
1310                                 ("yaffs_file_write size updated to %d bytes, "
1311                                 "%d blocks\n",
1312                                 ipos, (int)(inode->i_blocks)));
1313                 }
1314
1315         }
1316         yaffs_GrossUnlock(dev);
1317         return (nWritten == 0) && (n > 0) ? -ENOSPC : nWritten;
1318 }
1319
1320 /* Space holding and freeing is done to ensure we have space available for write_begin/end */
1321 /* For now we just assume few parallel writes and check against a small number. */
1322 /* Todo: need to do this with a counter to handle parallel reads better */
1323
1324 static ssize_t yaffs_hold_space(struct file *f)
1325 {
1326         yaffs_Object *obj;
1327         yaffs_Device *dev;
1328
1329         int nFreeChunks;
1330
1331
1332         obj = yaffs_DentryToObject(f->f_dentry);
1333
1334         dev = obj->myDev;
1335
1336         yaffs_GrossLock(dev);
1337
1338         nFreeChunks = yaffs_GetNumberOfFreeChunks(dev);
1339
1340         yaffs_GrossUnlock(dev);
1341
1342         return (nFreeChunks > 20) ? 1 : 0;
1343 }
1344
1345 static void yaffs_release_space(struct file *f)
1346 {
1347         yaffs_Object *obj;
1348         yaffs_Device *dev;
1349
1350
1351         obj = yaffs_DentryToObject(f->f_dentry);
1352
1353         dev = obj->myDev;
1354
1355         yaffs_GrossLock(dev);
1356
1357
1358         yaffs_GrossUnlock(dev);
1359 }
1360
1361
1362 static loff_t yaffs_dir_llseek(struct file *file, loff_t offset, int origin)
1363 {
1364         long long retval;
1365
1366         lock_kernel();
1367
1368         switch (origin){
1369         case 2:
1370                 offset += i_size_read(file->f_path.dentry->d_inode);
1371                 break;
1372         case 1:
1373                 offset += file->f_pos;
1374         }
1375         retval = -EINVAL;
1376
1377         if (offset >= 0){
1378                 if (offset != file->f_pos)
1379                         file->f_pos = offset;
1380
1381                 retval = offset;
1382         }
1383         unlock_kernel();
1384         return retval;
1385 }
1386
1387
1388 static int yaffs_readdir(struct file *f, void *dirent, filldir_t filldir)
1389 {
1390         yaffs_Object *obj;
1391         yaffs_Device *dev;
1392         struct yaffs_SearchContext *sc;
1393         struct inode *inode = f->f_dentry->d_inode;
1394         unsigned long offset, curoffs;
1395         yaffs_Object *l;
1396         int retVal = 0;
1397
1398         char name[YAFFS_MAX_NAME_LENGTH + 1];
1399
1400         obj = yaffs_DentryToObject(f->f_dentry);
1401         dev = obj->myDev;
1402
1403         yaffs_GrossLock(dev);
1404
1405         yaffs_DeviceToContext(dev)->readdirProcess = current;
1406
1407         offset = f->f_pos;
1408
1409         sc = yaffs_NewSearch(obj);
1410         if(!sc){
1411                 retVal = -ENOMEM;
1412                 goto unlock_out;
1413         }
1414
1415         T(YAFFS_TRACE_OS, ("yaffs_readdir: starting at %d\n", (int)offset));
1416
1417         if (offset == 0) {
1418                 T(YAFFS_TRACE_OS,
1419                         ("yaffs_readdir: entry . ino %d \n",
1420                         (int)inode->i_ino));
1421                 yaffs_GrossUnlock(dev);
1422                 if (filldir(dirent, ".", 1, offset, inode->i_ino, DT_DIR) < 0)
1423                         goto out;
1424                 yaffs_GrossLock(dev);
1425                 offset++;
1426                 f->f_pos++;
1427         }
1428         if (offset == 1) {
1429                 T(YAFFS_TRACE_OS,
1430                         ("yaffs_readdir: entry .. ino %d \n",
1431                         (int)f->f_dentry->d_parent->d_inode->i_ino));
1432                 yaffs_GrossUnlock(dev);
1433                 if (filldir(dirent, "..", 2, offset,
1434                         f->f_dentry->d_parent->d_inode->i_ino, DT_DIR) < 0)
1435                         goto out;
1436                 yaffs_GrossLock(dev);
1437                 offset++;
1438                 f->f_pos++;
1439         }
1440
1441         curoffs = 1;
1442
1443         /* If the directory has changed since the open or last call to
1444            readdir, rewind to after the 2 canned entries. */
1445 #if 0 /* For exportfs patch */
1446         if (f->f_version != inode->i_version) {
1447                 offset = 2;
1448                 f->f_pos = offset;
1449                 f->f_version = inode->i_version;
1450         }
1451 #endif
1452
1453         while(sc->nextReturn){
1454                 curoffs++;
1455                 l = sc->nextReturn;
1456                 if (curoffs >= offset) {
1457                         int this_inode = yaffs_GetObjectInode(l);
1458                         int this_type = yaffs_GetObjectType(l);
1459
1460                         yaffs_GetObjectName(l, name,
1461                                             YAFFS_MAX_NAME_LENGTH + 1);
1462                         T(YAFFS_TRACE_OS,
1463                           ("yaffs_readdir: %s inode %d\n", name,
1464                            yaffs_GetObjectInode(l)));
1465
1466                         yaffs_GrossUnlock(dev);
1467
1468                         if (filldir(dirent,
1469                                         name,
1470                                         strlen(name),
1471                                         offset,
1472                                         this_inode,
1473                                         this_type) < 0)
1474                                 goto out;
1475
1476                         yaffs_GrossLock(dev);
1477
1478                         offset++;
1479                         f->f_pos++;
1480                 }
1481                 yaffs_SearchAdvance(sc);
1482         }
1483
1484 unlock_out:
1485         yaffs_DeviceToContext(dev)->readdirProcess = NULL;
1486
1487         yaffs_GrossUnlock(dev);
1488 out:
1489         yaffs_EndSearch(sc);
1490
1491         return retVal;
1492 }
1493
1494
1495
1496 /*
1497  * File creation. Allocate an inode, and we're done..
1498  */
1499
1500 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 29)
1501 #define YCRED(x) x
1502 #else
1503 #define YCRED(x) (x->cred)
1504 #endif
1505
1506 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1507 static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
1508                         dev_t rdev)
1509 #else
1510 static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
1511                         int rdev)
1512 #endif
1513 {
1514         struct inode *inode;
1515
1516         yaffs_Object *obj = NULL;
1517         yaffs_Device *dev;
1518
1519         yaffs_Object *parent = yaffs_InodeToObject(dir);
1520
1521         int error = -ENOSPC;
1522         uid_t uid = YCRED(current)->fsuid;
1523         gid_t gid = (dir->i_mode & S_ISGID) ? dir->i_gid : YCRED(current)->fsgid;
1524
1525         if ((dir->i_mode & S_ISGID) && S_ISDIR(mode))
1526                 mode |= S_ISGID;
1527
1528         if (parent) {
1529                 T(YAFFS_TRACE_OS,
1530                         ("yaffs_mknod: parent object %d type %d\n",
1531                         parent->objectId, parent->variantType));
1532         } else {
1533                 T(YAFFS_TRACE_OS,
1534                         ("yaffs_mknod: could not get parent object\n"));
1535                 return -EPERM;
1536         }
1537
1538         T(YAFFS_TRACE_OS, ("yaffs_mknod: making oject for %s, "
1539                         "mode %x dev %x\n",
1540                         dentry->d_name.name, mode, rdev));
1541
1542         dev = parent->myDev;
1543
1544         yaffs_GrossLock(dev);
1545
1546         switch (mode & S_IFMT) {
1547         default:
1548                 /* Special (socket, fifo, device...) */
1549                 T(YAFFS_TRACE_OS, ("yaffs_mknod: making special\n"));
1550 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1551                 obj = yaffs_MknodSpecial(parent, dentry->d_name.name, mode, uid,
1552                                 gid, old_encode_dev(rdev));
1553 #else
1554                 obj = yaffs_MknodSpecial(parent, dentry->d_name.name, mode, uid,
1555                                 gid, rdev);
1556 #endif
1557                 break;
1558         case S_IFREG:           /* file          */
1559                 T(YAFFS_TRACE_OS, ("yaffs_mknod: making file\n"));
1560                 obj = yaffs_MknodFile(parent, dentry->d_name.name, mode, uid,
1561                                 gid);
1562                 break;
1563         case S_IFDIR:           /* directory */
1564                 T(YAFFS_TRACE_OS,
1565                         ("yaffs_mknod: making directory\n"));
1566                 obj = yaffs_MknodDirectory(parent, dentry->d_name.name, mode,
1567                                         uid, gid);
1568                 break;
1569         case S_IFLNK:           /* symlink */
1570                 T(YAFFS_TRACE_OS, ("yaffs_mknod: making symlink\n"));
1571                 obj = NULL;     /* Do we ever get here? */
1572                 break;
1573         }
1574
1575         /* Can not call yaffs_get_inode() with gross lock held */
1576         yaffs_GrossUnlock(dev);
1577
1578         if (obj) {
1579                 inode = yaffs_get_inode(dir->i_sb, mode, rdev, obj);
1580                 d_instantiate(dentry, inode);
1581                 update_dir_time(dir);
1582                 T(YAFFS_TRACE_OS,
1583                         ("yaffs_mknod created object %d count = %d\n",
1584                         obj->objectId, atomic_read(&inode->i_count)));
1585                 error = 0;
1586                 yaffs_FillInodeFromObject(dir,parent);
1587         } else {
1588                 T(YAFFS_TRACE_OS,
1589                         ("yaffs_mknod failed making object\n"));
1590                 error = -ENOMEM;
1591         }
1592
1593         return error;
1594 }
1595
1596 static int yaffs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
1597 {
1598         int retVal;
1599         T(YAFFS_TRACE_OS, ("yaffs_mkdir\n"));
1600         retVal = yaffs_mknod(dir, dentry, mode | S_IFDIR, 0);
1601         return retVal;
1602 }
1603
1604 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1605 static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode,
1606                         struct nameidata *n)
1607 #else
1608 static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode)
1609 #endif
1610 {
1611         T(YAFFS_TRACE_OS, ("yaffs_create\n"));
1612         return yaffs_mknod(dir, dentry, mode | S_IFREG, 0);
1613 }
1614
1615 static int yaffs_unlink(struct inode *dir, struct dentry *dentry)
1616 {
1617         int retVal;
1618
1619         yaffs_Device *dev;
1620         yaffs_Object *obj;
1621
1622         T(YAFFS_TRACE_OS,
1623                 ("yaffs_unlink %d:%s\n", (int)(dir->i_ino),
1624                 dentry->d_name.name));
1625         obj = yaffs_InodeToObject(dir);
1626         dev = obj->myDev;
1627
1628         yaffs_GrossLock(dev);
1629
1630         retVal = yaffs_Unlink(obj, dentry->d_name.name);
1631
1632         if (retVal == YAFFS_OK) {
1633                 dentry->d_inode->i_nlink--;
1634                 dir->i_version++;
1635                 yaffs_GrossUnlock(dev);
1636                 mark_inode_dirty(dentry->d_inode);
1637                 update_dir_time(dir);
1638                 return 0;
1639         }
1640         yaffs_GrossUnlock(dev);
1641         return -ENOTEMPTY;
1642 }
1643
1644 /*
1645  * Create a link...
1646  */
1647 static int yaffs_link(struct dentry *old_dentry, struct inode *dir,
1648                         struct dentry *dentry)
1649 {
1650         struct inode *inode = old_dentry->d_inode;
1651         yaffs_Object *obj = NULL;
1652         yaffs_Object *link = NULL;
1653         yaffs_Device *dev;
1654
1655         T(YAFFS_TRACE_OS, ("yaffs_link\n"));
1656
1657         obj = yaffs_InodeToObject(inode);
1658         dev = obj->myDev;
1659
1660         yaffs_GrossLock(dev);
1661
1662         if (!S_ISDIR(inode->i_mode))            /* Don't link directories */
1663                 link = yaffs_Link(yaffs_InodeToObject(dir), dentry->d_name.name,
1664                         obj);
1665
1666         if (link) {
1667                 old_dentry->d_inode->i_nlink = yaffs_GetObjectLinkCount(obj);
1668                 d_instantiate(dentry, old_dentry->d_inode);
1669                 atomic_inc(&old_dentry->d_inode->i_count);
1670                 T(YAFFS_TRACE_OS,
1671                         ("yaffs_link link count %d i_count %d\n",
1672                         old_dentry->d_inode->i_nlink,
1673                         atomic_read(&old_dentry->d_inode->i_count)));
1674         }
1675
1676         yaffs_GrossUnlock(dev);
1677
1678         if (link){
1679                 update_dir_time(dir);
1680                 return 0;
1681         }
1682
1683         return -EPERM;
1684 }
1685
1686 static int yaffs_symlink(struct inode *dir, struct dentry *dentry,
1687                                 const char *symname)
1688 {
1689         yaffs_Object *obj;
1690         yaffs_Device *dev;
1691         uid_t uid = YCRED(current)->fsuid;
1692         gid_t gid = (dir->i_mode & S_ISGID) ? dir->i_gid : YCRED(current)->fsgid;
1693
1694         T(YAFFS_TRACE_OS, ("yaffs_symlink\n"));
1695
1696         dev = yaffs_InodeToObject(dir)->myDev;
1697         yaffs_GrossLock(dev);
1698         obj = yaffs_MknodSymLink(yaffs_InodeToObject(dir), dentry->d_name.name,
1699                                 S_IFLNK | S_IRWXUGO, uid, gid, symname);
1700         yaffs_GrossUnlock(dev);
1701
1702         if (obj) {
1703                 struct inode *inode;
1704
1705                 inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
1706                 d_instantiate(dentry, inode);
1707                 update_dir_time(dir);
1708                 T(YAFFS_TRACE_OS, ("symlink created OK\n"));
1709                 return 0;
1710         } else {
1711                 T(YAFFS_TRACE_OS, ("symlink not created\n"));
1712         }
1713
1714         return -ENOMEM;
1715 }
1716
1717 static int yaffs_sync_object(struct file *file, struct dentry *dentry,
1718                                 int datasync)
1719 {
1720
1721         yaffs_Object *obj;
1722         yaffs_Device *dev;
1723
1724         obj = yaffs_DentryToObject(dentry);
1725
1726         dev = obj->myDev;
1727
1728         T(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, ("yaffs_sync_object\n"));
1729         yaffs_GrossLock(dev);
1730         yaffs_FlushFile(obj, 1, datasync);
1731         yaffs_GrossUnlock(dev);
1732         return 0;
1733 }
1734
1735 /*
1736  * The VFS layer already does all the dentry stuff for rename.
1737  *
1738  * NB: POSIX says you can rename an object over an old object of the same name
1739  */
1740 static int yaffs_rename(struct inode *old_dir, struct dentry *old_dentry,
1741                         struct inode *new_dir, struct dentry *new_dentry)
1742 {
1743         yaffs_Device *dev;
1744         int retVal = YAFFS_FAIL;
1745         yaffs_Object *target;
1746
1747         T(YAFFS_TRACE_OS, ("yaffs_rename\n"));
1748         dev = yaffs_InodeToObject(old_dir)->myDev;
1749
1750         yaffs_GrossLock(dev);
1751
1752         /* Check if the target is an existing directory that is not empty. */
1753         target = yaffs_FindObjectByName(yaffs_InodeToObject(new_dir),
1754                                 new_dentry->d_name.name);
1755
1756
1757
1758         if (target && target->variantType == YAFFS_OBJECT_TYPE_DIRECTORY &&
1759                 !ylist_empty(&target->variant.directoryVariant.children)) {
1760
1761                 T(YAFFS_TRACE_OS, ("target is non-empty dir\n"));
1762
1763                 retVal = YAFFS_FAIL;
1764         } else {
1765                 /* Now does unlinking internally using shadowing mechanism */
1766                 T(YAFFS_TRACE_OS, ("calling yaffs_RenameObject\n"));
1767
1768                 retVal = yaffs_RenameObject(yaffs_InodeToObject(old_dir),
1769                                 old_dentry->d_name.name,
1770                                 yaffs_InodeToObject(new_dir),
1771                                 new_dentry->d_name.name);
1772         }
1773         yaffs_GrossUnlock(dev);
1774
1775         if (retVal == YAFFS_OK) {
1776                 if (target) {
1777                         new_dentry->d_inode->i_nlink--;
1778                         mark_inode_dirty(new_dentry->d_inode);
1779                 }
1780                 
1781                 update_dir_time(old_dir);
1782                 if(old_dir != new_dir)
1783                         update_dir_time(new_dir);
1784                 return 0;
1785         } else {
1786                 return -ENOTEMPTY;
1787         }
1788 }
1789
1790 static int yaffs_setattr(struct dentry *dentry, struct iattr *attr)
1791 {
1792         struct inode *inode = dentry->d_inode;
1793         int error = 0;
1794         yaffs_Device *dev;
1795
1796         T(YAFFS_TRACE_OS,
1797                 ("yaffs_setattr of object %d\n",
1798                 yaffs_InodeToObject(inode)->objectId));
1799
1800         /* Fail if a requested resize >= 2GB */         
1801         if (attr->ia_valid & ATTR_SIZE &&
1802                 (attr->ia_size >> 31))
1803                 error = -EINVAL;
1804
1805         if (error == 0)
1806                 error = inode_change_ok(inode, attr);
1807         if (error == 0) {
1808                 int result;
1809                 if (!error){
1810                         error = inode_setattr(inode, attr);
1811                         T(YAFFS_TRACE_OS,("inode_setattr called\n"));
1812                         if (attr->ia_valid & ATTR_SIZE)
1813                                 truncate_inode_pages(&inode->i_data,attr->ia_size);
1814                 }
1815                 dev = yaffs_InodeToObject(inode)->myDev;
1816                 if (attr->ia_valid & ATTR_SIZE){
1817                         T(YAFFS_TRACE_OS,("resize to %d(%x)\n",(int)(attr->ia_size),(int)(attr->ia_size)));
1818                 }
1819                 yaffs_GrossLock(dev);
1820                 result = yaffs_SetAttributes(yaffs_InodeToObject(inode), attr);
1821                 if(result == YAFFS_OK) {
1822                         error = 0;
1823                 } else {
1824                         error = -EPERM;
1825                 }
1826                 yaffs_GrossUnlock(dev);
1827
1828         }
1829
1830         T(YAFFS_TRACE_OS,
1831                 ("yaffs_setattr done returning %d\n",error));
1832
1833         return error;
1834 }
1835
1836 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
1837 static int yaffs_statfs(struct dentry *dentry, struct kstatfs *buf)
1838 {
1839         yaffs_Device *dev = yaffs_DentryToObject(dentry)->myDev;
1840         struct super_block *sb = dentry->d_sb;
1841 #elif (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
1842 static int yaffs_statfs(struct super_block *sb, struct kstatfs *buf)
1843 {
1844         yaffs_Device *dev = yaffs_SuperToDevice(sb);
1845 #else
1846 static int yaffs_statfs(struct super_block *sb, struct statfs *buf)
1847 {
1848         yaffs_Device *dev = yaffs_SuperToDevice(sb);
1849 #endif
1850
1851         T(YAFFS_TRACE_OS, ("yaffs_statfs\n"));
1852
1853         yaffs_GrossLock(dev);
1854
1855         buf->f_type = YAFFS_MAGIC;
1856         buf->f_bsize = sb->s_blocksize;
1857         buf->f_namelen = 255;
1858
1859         if (dev->nDataBytesPerChunk & (dev->nDataBytesPerChunk - 1)) {
1860                 /* Do this if chunk size is not a power of 2 */
1861
1862                 uint64_t bytesInDev;
1863                 uint64_t bytesFree;
1864
1865                 bytesInDev = ((uint64_t)((dev->param.endBlock - dev->param.startBlock + 1))) *
1866                         ((uint64_t)(dev->param.nChunksPerBlock * dev->nDataBytesPerChunk));
1867
1868                 do_div(bytesInDev, sb->s_blocksize); /* bytesInDev becomes the number of blocks */
1869                 buf->f_blocks = bytesInDev;
1870
1871                 bytesFree  = ((uint64_t)(yaffs_GetNumberOfFreeChunks(dev))) *
1872                         ((uint64_t)(dev->nDataBytesPerChunk));
1873
1874                 do_div(bytesFree, sb->s_blocksize);
1875
1876                 buf->f_bfree = bytesFree;
1877
1878         } else if (sb->s_blocksize > dev->nDataBytesPerChunk) {
1879
1880                 buf->f_blocks =
1881                         (dev->param.endBlock - dev->param.startBlock + 1) *
1882                         dev->param.nChunksPerBlock /
1883                         (sb->s_blocksize / dev->nDataBytesPerChunk);
1884                 buf->f_bfree =
1885                         yaffs_GetNumberOfFreeChunks(dev) /
1886                         (sb->s_blocksize / dev->nDataBytesPerChunk);
1887         } else {
1888                 buf->f_blocks =
1889                         (dev->param.endBlock - dev->param.startBlock + 1) *
1890                         dev->param.nChunksPerBlock *
1891                         (dev->nDataBytesPerChunk / sb->s_blocksize);
1892
1893                 buf->f_bfree =
1894                         yaffs_GetNumberOfFreeChunks(dev) *
1895                         (dev->nDataBytesPerChunk / sb->s_blocksize);
1896         }
1897
1898         buf->f_files = 0;
1899         buf->f_ffree = 0;
1900         buf->f_bavail = buf->f_bfree;
1901
1902         yaffs_GrossUnlock(dev);
1903         return 0;
1904 }
1905
1906
1907
1908 static void yaffs_FlushInodes(struct super_block *sb)
1909 {
1910         struct inode *iptr;
1911         yaffs_Object *obj;
1912         
1913         list_for_each_entry(iptr,&sb->s_inodes, i_sb_list){
1914                 obj = yaffs_InodeToObject(iptr);
1915                 if(obj){
1916                         T(YAFFS_TRACE_OS, ("flushing obj %d\n",obj->objectId));
1917                         yaffs_FlushFile(obj,1,0);
1918                 }
1919         }
1920 }
1921
1922
1923 static void yaffs_FlushSuperBlock(struct super_block *sb, int do_checkpoint)
1924 {
1925         yaffs_Device *dev = yaffs_SuperToDevice(sb);    
1926         if(!dev)
1927                 return;
1928         
1929         yaffs_FlushInodes(sb);
1930         yaffs_UpdateDirtyDirectories(dev);
1931         yaffs_FlushEntireDeviceCache(dev);
1932         if(do_checkpoint)
1933                 yaffs_CheckpointSave(dev);
1934 }
1935
1936 static int yaffs_do_sync_fs(struct super_block *sb, int do_checkpoint)
1937 {
1938
1939         yaffs_Device *dev = yaffs_SuperToDevice(sb);
1940         T(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, 
1941                 ("yaffs_do_sync_fs: %s %s\n", 
1942                 sb->s_dirt ? "dirty" : "clean",
1943                 do_checkpoint ? "with checkpoint" : "no checkpoint"));
1944
1945         if (sb->s_dirt) {
1946                 yaffs_GrossLock(dev);
1947                 yaffs_FlushSuperBlock(sb,do_checkpoint);
1948                 yaffs_GrossUnlock(dev);
1949
1950                 sb->s_dirt = 0;
1951         }
1952         return 0;
1953 }
1954
1955 /*
1956  * yaffs background thread functions .
1957  * yaffs_BackgroundThread() the thread function
1958  * yaffs_BackgroundStart() launches the background thread.
1959  * yaffs_BackgroundStop() cleans up the background thread.
1960  *
1961  * NB: 
1962  * The thread should only run after the yaffs is initialised
1963  * The thread should be stopped before yaffs is unmounted.
1964  * The thread should not do any writing while the fs is in read only.
1965  */
1966
1967 #ifdef YAFFS_COMPILE_BACKGROUND
1968 static int yaffs_BackgroundThread(void *data)
1969 {
1970         yaffs_Device *dev = (yaffs_Device *)data;
1971         struct yaffs_LinuxContext *context = yaffs_DeviceToContext(dev);
1972
1973         T(YAFFS_TRACE_BACKGROUND,
1974                 ("yaffs_background starting for dev %p\n",
1975                 (void *)dev));
1976         
1977         while(context->bgRunning){
1978                 T(YAFFS_TRACE_BACKGROUND,
1979                         ("yaffs_background\n"));
1980
1981                 if(kthread_should_stop())
1982                         break;
1983                 yaffs_GrossLock(dev);
1984                 yaffs_UpdateDirtyDirectories(dev);
1985                 yaffs_GrossUnlock(dev);
1986                 msleep(500);
1987         }
1988         return 0;
1989 }
1990
1991 static int yaffs_BackgroundStart(yaffs_Device *dev)
1992 {
1993         int retval = 0;
1994
1995         struct yaffs_LinuxContext *context = yaffs_DeviceToContext(dev);
1996
1997         context->bgRunning = 1;
1998
1999         context->bgThread = kthread_run(yaffs_BackgroundThread,(void *)dev,"yaffs_%x",(unsigned)dev);
2000
2001         if(IS_ERR(context->bgThread)){
2002                 retval = PTR_ERR(context->bgThread);
2003                 context->bgThread = NULL;
2004                 context->bgRunning = 0;
2005         }
2006         return retval;
2007 }
2008
2009 static void yaffs_BackgroundStop(yaffs_Device *dev)
2010 {
2011         struct yaffs_LinuxContext *ctxt = yaffs_DeviceToContext(dev);
2012
2013         ctxt->bgRunning = 0;
2014
2015         if( ctxt->bgThread){
2016                 kthread_stop(ctxt->bgThread);
2017                 ctxt->bgThread = NULL;
2018         }
2019 }
2020 #else
2021 static int yaffs_BackgroundThread(void *data)
2022 {
2023         return 0;
2024 }
2025
2026 static int yaffs_BackgroundStart(yaffs_Device *dev)
2027 {
2028         return 0;
2029 }
2030
2031 static void yaffs_BackgroundStop(yaffs_Device *dev)
2032 {
2033 }
2034 #endif
2035
2036
2037 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2038 static void yaffs_write_super(struct super_block *sb)
2039 #else
2040 static int yaffs_write_super(struct super_block *sb)
2041 #endif
2042 {
2043
2044         T(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, ("yaffs_write_super\n"));
2045         yaffs_do_sync_fs(sb, yaffs_auto_checkpoint >= 2);
2046
2047 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18))
2048         return 0;
2049 #endif
2050 }
2051
2052
2053 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2054 static int yaffs_sync_fs(struct super_block *sb, int wait)
2055 #else
2056 static int yaffs_sync_fs(struct super_block *sb)
2057 #endif
2058 {
2059         T(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, ("yaffs_sync_fs\n"));
2060
2061         yaffs_do_sync_fs(sb,yaffs_auto_checkpoint >= 1);
2062
2063         return 0;
2064 }
2065
2066 #ifdef YAFFS_USE_OWN_IGET
2067
2068 static struct inode *yaffs_iget(struct super_block *sb, unsigned long ino)
2069 {
2070         struct inode *inode;
2071         yaffs_Object *obj;
2072         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2073
2074         T(YAFFS_TRACE_OS,
2075                 ("yaffs_iget for %lu\n", ino));
2076
2077         inode = iget_locked(sb, ino);
2078         if (!inode)
2079                 return ERR_PTR(-ENOMEM);
2080         if (!(inode->i_state & I_NEW))
2081                 return inode;
2082
2083         /* NB This is called as a side effect of other functions, but
2084          * we had to release the lock to prevent deadlocks, so
2085          * need to lock again.
2086          */
2087
2088         yaffs_GrossLock(dev);
2089
2090         obj = yaffs_FindObjectByNumber(dev, inode->i_ino);
2091
2092         yaffs_FillInodeFromObject(inode, obj);
2093
2094         yaffs_GrossUnlock(dev);
2095
2096         unlock_new_inode(inode);
2097         return inode;
2098 }
2099
2100 #else
2101
2102 static void yaffs_read_inode(struct inode *inode)
2103 {
2104         /* NB This is called as a side effect of other functions, but
2105          * we had to release the lock to prevent deadlocks, so
2106          * need to lock again.
2107          */
2108
2109         yaffs_Object *obj;
2110         yaffs_Device *dev = yaffs_SuperToDevice(inode->i_sb);
2111
2112         T(YAFFS_TRACE_OS,
2113                 ("yaffs_read_inode for %d\n", (int)inode->i_ino));
2114
2115         if(current != yaffs_DeviceToContext(dev)->readdirProcess)
2116                 yaffs_GrossLock(dev);
2117
2118         obj = yaffs_FindObjectByNumber(dev, inode->i_ino);
2119
2120         yaffs_FillInodeFromObject(inode, obj);
2121
2122         if(current != yaffs_DeviceToContext(dev)->readdirProcess)
2123                 yaffs_GrossUnlock(dev);
2124 }
2125
2126 #endif
2127
2128 static YLIST_HEAD(yaffs_context_list);
2129 struct semaphore yaffs_context_lock;
2130
2131 #if 0 /* not used */
2132 static int yaffs_remount_fs(struct super_block *sb, int *flags, char *data)
2133 {
2134         yaffs_Device    *dev = yaffs_SuperToDevice(sb);
2135
2136         if (*flags & MS_RDONLY) {
2137                 struct mtd_info *mtd = yaffs_SuperToDevice(sb)->genericDevice;
2138
2139                 T(YAFFS_TRACE_OS,
2140                         ("yaffs_remount_fs: %s: RO\n", dev->name));
2141
2142                 yaffs_GrossLock(dev);
2143
2144                 yaffs_FlushSuperBlock(sb,1);
2145
2146                 if (mtd->sync)
2147                         mtd->sync(mtd);
2148
2149                 yaffs_GrossUnlock(dev);
2150         } else {
2151                 T(YAFFS_TRACE_OS,
2152                         ("yaffs_remount_fs: %s: RW\n", dev->name));
2153         }
2154
2155         return 0;
2156 }
2157 #endif
2158
2159 static void yaffs_put_super(struct super_block *sb)
2160 {
2161         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2162
2163         T(YAFFS_TRACE_OS, ("yaffs_put_super\n"));
2164
2165         yaffs_GrossLock(dev);
2166
2167         yaffs_FlushSuperBlock(sb,1);
2168
2169         if (yaffs_DeviceToContext(dev)->putSuperFunc)
2170                 yaffs_DeviceToContext(dev)->putSuperFunc(sb);
2171
2172         yaffs_BackgroundStop(dev);
2173
2174         yaffs_Deinitialise(dev);
2175
2176         yaffs_GrossUnlock(dev);
2177
2178         down(&yaffs_context_lock);
2179         ylist_del_init(&(yaffs_DeviceToContext(dev)->contextList));
2180         up(&yaffs_context_lock);
2181
2182         if (yaffs_DeviceToContext(dev)->spareBuffer) {
2183                 YFREE(yaffs_DeviceToContext(dev)->spareBuffer);
2184                 yaffs_DeviceToContext(dev)->spareBuffer = NULL;
2185         }
2186
2187         kfree(dev);
2188 }
2189
2190
2191 static void yaffs_MTDPutSuper(struct super_block *sb)
2192 {
2193         struct mtd_info *mtd = yaffs_DeviceToContext(yaffs_SuperToDevice(sb))->mtd;
2194
2195         if (mtd->sync)
2196                 mtd->sync(mtd);
2197
2198         put_mtd_device(mtd);
2199 }
2200
2201
2202 static void yaffs_MarkSuperBlockDirty(yaffs_Device *dev)
2203 {
2204         struct super_block *sb = yaffs_DeviceToContext(dev)->superBlock;
2205
2206         T(YAFFS_TRACE_OS, ("yaffs_MarkSuperBlockDirty() sb = %p\n", sb));
2207         if (sb)
2208                 sb->s_dirt = 1;
2209 }
2210
2211 typedef struct {
2212         int inband_tags;
2213         int skip_checkpoint_read;
2214         int skip_checkpoint_write;
2215         int no_cache;
2216         int tags_ecc_on;
2217         int tags_ecc_overridden;
2218         int lazy_loading_enabled;
2219         int lazy_loading_overridden;
2220         int empty_lost_and_found;
2221         int empty_lost_and_found_overridden;
2222 } yaffs_options;
2223
2224 #define MAX_OPT_LEN 30
2225 static int yaffs_parse_options(yaffs_options *options, const char *options_str)
2226 {
2227         char cur_opt[MAX_OPT_LEN + 1];
2228         int p;
2229         int error = 0;
2230
2231         /* Parse through the options which is a comma seperated list */
2232
2233         while (options_str && *options_str && !error) {
2234                 memset(cur_opt, 0, MAX_OPT_LEN + 1);
2235                 p = 0;
2236
2237                 while(*options_str == ',')
2238                         options_str++;
2239
2240                 while (*options_str && *options_str != ',') {
2241                         if (p < MAX_OPT_LEN) {
2242                                 cur_opt[p] = *options_str;
2243                                 p++;
2244                         }
2245                         options_str++;
2246                 }
2247
2248                 if (!strcmp(cur_opt, "inband-tags"))
2249                         options->inband_tags = 1;
2250                 else if (!strcmp(cur_opt, "tags-ecc-off")){
2251                         options->tags_ecc_on = 0;
2252                         options->tags_ecc_overridden=1;
2253                 } else if (!strcmp(cur_opt, "tags-ecc-on")){
2254                         options->tags_ecc_on = 1;
2255                         options->tags_ecc_overridden = 1;
2256                 } else if (!strcmp(cur_opt, "lazy-loading-off")){
2257                         options->lazy_loading_enabled = 0;
2258                         options->lazy_loading_overridden=1;
2259                 } else if (!strcmp(cur_opt, "lazy-loading-on")){
2260                         options->lazy_loading_enabled = 1;
2261                         options->lazy_loading_overridden = 1;
2262                 } else if (!strcmp(cur_opt, "empty-lost-and-found-off")){
2263                         options->empty_lost_and_found = 0;
2264                         options->empty_lost_and_found_overridden=1;
2265                 } else if (!strcmp(cur_opt, "empty-lost-and-found-on")){
2266                         options->empty_lost_and_found = 1;
2267                         options->empty_lost_and_found_overridden=1;
2268                 } else if (!strcmp(cur_opt, "no-cache"))
2269                         options->no_cache = 1;
2270                 else if (!strcmp(cur_opt, "no-checkpoint-read"))
2271                         options->skip_checkpoint_read = 1;
2272                 else if (!strcmp(cur_opt, "no-checkpoint-write"))
2273                         options->skip_checkpoint_write = 1;
2274                 else if (!strcmp(cur_opt, "no-checkpoint")) {
2275                         options->skip_checkpoint_read = 1;
2276                         options->skip_checkpoint_write = 1;
2277                 } else {
2278                         printk(KERN_INFO "yaffs: Bad mount option \"%s\"\n",
2279                                         cur_opt);
2280                         error = 1;
2281                 }
2282         }
2283
2284         return error;
2285 }
2286
2287 static struct super_block *yaffs_internal_read_super(int yaffsVersion,
2288                                                 struct super_block *sb,
2289                                                 void *data, int silent)
2290 {
2291         int nBlocks;
2292         struct inode *inode = NULL;
2293         struct dentry *root;
2294         yaffs_Device *dev = 0;
2295         char devname_buf[BDEVNAME_SIZE + 1];
2296         struct mtd_info *mtd;
2297         int err;
2298         char *data_str = (char *)data;
2299         struct yaffs_LinuxContext *context = NULL;
2300         yaffs_DeviceParam *param;
2301
2302         yaffs_options options;
2303
2304         sb->s_magic = YAFFS_MAGIC;
2305         sb->s_op = &yaffs_super_ops;
2306         sb->s_flags |= MS_NOATIME;
2307
2308 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,9))
2309         sb->s_export_op = &yaffs_export_ops;
2310 #endif
2311
2312         if (!sb)
2313                 printk(KERN_INFO "yaffs: sb is NULL\n");
2314         else if (!sb->s_dev)
2315                 printk(KERN_INFO "yaffs: sb->s_dev is NULL\n");
2316         else if (!yaffs_devname(sb, devname_buf))
2317                 printk(KERN_INFO "yaffs: devname is NULL\n");
2318         else
2319                 printk(KERN_INFO "yaffs: dev is %d name is \"%s\"\n",
2320                        sb->s_dev,
2321                        yaffs_devname(sb, devname_buf));
2322
2323         if (!data_str)
2324                 data_str = "";
2325
2326         printk(KERN_INFO "yaffs: passed flags \"%s\"\n", data_str);
2327
2328         memset(&options, 0, sizeof(options));
2329
2330         if (yaffs_parse_options(&options, data_str)) {
2331                 /* Option parsing failed */
2332                 return NULL;
2333         }
2334
2335
2336         sb->s_blocksize = PAGE_CACHE_SIZE;
2337         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
2338         T(YAFFS_TRACE_OS, ("yaffs_read_super: Using yaffs%d\n", yaffsVersion));
2339         T(YAFFS_TRACE_OS,
2340           ("yaffs_read_super: block size %d\n", (int)(sb->s_blocksize)));
2341
2342 #ifdef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
2343         T(YAFFS_TRACE_OS,
2344           ("yaffs: Write verification disabled. All guarantees "
2345            "null and void\n"));
2346 #endif
2347
2348         T(YAFFS_TRACE_ALWAYS, ("yaffs: Attempting MTD mount on %u.%u, "
2349                                "\"%s\"\n",
2350                                MAJOR(sb->s_dev), MINOR(sb->s_dev),
2351                                yaffs_devname(sb, devname_buf)));
2352
2353         /* Check it's an mtd device..... */
2354         if (MAJOR(sb->s_dev) != MTD_BLOCK_MAJOR)
2355                 return NULL;    /* This isn't an mtd device */
2356
2357         /* Get the device */
2358         mtd = get_mtd_device(NULL, MINOR(sb->s_dev));
2359         if (!mtd) {
2360                 T(YAFFS_TRACE_ALWAYS,
2361                   ("yaffs: MTD device #%u doesn't appear to exist\n",
2362                    MINOR(sb->s_dev)));
2363                 return NULL;
2364         }
2365         /* Check it's NAND */
2366         if (mtd->type != MTD_NANDFLASH) {
2367                 T(YAFFS_TRACE_ALWAYS,
2368                   ("yaffs: MTD device is not NAND it's type %d\n", mtd->type));
2369                 return NULL;
2370         }
2371
2372         T(YAFFS_TRACE_OS, (" erase %p\n", mtd->erase));
2373         T(YAFFS_TRACE_OS, (" read %p\n", mtd->read));
2374         T(YAFFS_TRACE_OS, (" write %p\n", mtd->write));
2375         T(YAFFS_TRACE_OS, (" readoob %p\n", mtd->read_oob));
2376         T(YAFFS_TRACE_OS, (" writeoob %p\n", mtd->write_oob));
2377         T(YAFFS_TRACE_OS, (" block_isbad %p\n", mtd->block_isbad));
2378         T(YAFFS_TRACE_OS, (" block_markbad %p\n", mtd->block_markbad));
2379         T(YAFFS_TRACE_OS, (" %s %d\n", WRITE_SIZE_STR, WRITE_SIZE(mtd)));
2380         T(YAFFS_TRACE_OS, (" oobsize %d\n", mtd->oobsize));
2381         T(YAFFS_TRACE_OS, (" erasesize %d\n", mtd->erasesize));
2382 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 29)
2383         T(YAFFS_TRACE_OS, (" size %u\n", mtd->size));
2384 #else
2385         T(YAFFS_TRACE_OS, (" size %lld\n", mtd->size));
2386 #endif
2387
2388 #ifdef CONFIG_YAFFS_AUTO_YAFFS2
2389
2390         if (yaffsVersion == 1 && WRITE_SIZE(mtd) >= 2048) {
2391                 T(YAFFS_TRACE_ALWAYS, ("yaffs: auto selecting yaffs2\n"));
2392                 yaffsVersion = 2;
2393         }
2394
2395         /* Added NCB 26/5/2006 for completeness */
2396         if (yaffsVersion == 2 && !options.inband_tags && WRITE_SIZE(mtd) == 512) {
2397                 T(YAFFS_TRACE_ALWAYS, ("yaffs: auto selecting yaffs1\n"));
2398                 yaffsVersion = 1;
2399         }
2400
2401 #endif
2402
2403         if (yaffsVersion == 2) {
2404                 /* Check for version 2 style functions */
2405                 if (!mtd->erase ||
2406                     !mtd->block_isbad ||
2407                     !mtd->block_markbad ||
2408                     !mtd->read ||
2409                     !mtd->write ||
2410 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2411                     !mtd->read_oob || !mtd->write_oob) {
2412 #else
2413                     !mtd->write_ecc ||
2414                     !mtd->read_ecc || !mtd->read_oob || !mtd->write_oob) {
2415 #endif
2416                         T(YAFFS_TRACE_ALWAYS,
2417                           ("yaffs: MTD device does not support required "
2418                            "functions\n"));;
2419                         return NULL;
2420                 }
2421
2422                 if ((WRITE_SIZE(mtd) < YAFFS_MIN_YAFFS2_CHUNK_SIZE ||
2423                     mtd->oobsize < YAFFS_MIN_YAFFS2_SPARE_SIZE) &&
2424                     !options.inband_tags) {
2425                         T(YAFFS_TRACE_ALWAYS,
2426                           ("yaffs: MTD device does not have the "
2427                            "right page sizes\n"));
2428                         return NULL;
2429                 }
2430         } else {
2431                 /* Check for V1 style functions */
2432                 if (!mtd->erase ||
2433                     !mtd->read ||
2434                     !mtd->write ||
2435 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2436                     !mtd->read_oob || !mtd->write_oob) {
2437 #else
2438                     !mtd->write_ecc ||
2439                     !mtd->read_ecc || !mtd->read_oob || !mtd->write_oob) {
2440 #endif
2441                         T(YAFFS_TRACE_ALWAYS,
2442                           ("yaffs: MTD device does not support required "
2443                            "functions\n"));;
2444                         return NULL;
2445                 }
2446
2447                 if (WRITE_SIZE(mtd) < YAFFS_BYTES_PER_CHUNK ||
2448                     mtd->oobsize != YAFFS_BYTES_PER_SPARE) {
2449                         T(YAFFS_TRACE_ALWAYS,
2450                           ("yaffs: MTD device does not support have the "
2451                            "right page sizes\n"));
2452                         return NULL;
2453                 }
2454         }
2455
2456         /* OK, so if we got here, we have an MTD that's NAND and looks
2457          * like it has the right capabilities
2458          * Set the yaffs_Device up for mtd
2459          */
2460
2461         dev = kmalloc(sizeof(yaffs_Device), GFP_KERNEL);
2462         context = kmalloc(sizeof(struct yaffs_LinuxContext),GFP_KERNEL);
2463         
2464         if(!dev || !context ){
2465                 if(dev)
2466                         kfree(dev);
2467                 if(context)
2468                         kfree(context);
2469                 dev = NULL;
2470                 context = NULL;
2471         }
2472
2473         if (!dev) {
2474                 /* Deep shit could not allocate device structure */
2475                 T(YAFFS_TRACE_ALWAYS,
2476                   ("yaffs_read_super: Failed trying to allocate "
2477                    "yaffs_Device. \n"));
2478                 return NULL;
2479         }
2480         memset(dev, 0, sizeof(yaffs_Device));
2481         param = &(dev->param);
2482
2483         memset(context,0,sizeof(struct yaffs_LinuxContext));
2484         dev->context = context;
2485         YINIT_LIST_HEAD(&(context->contextList));
2486         context->dev = dev;
2487         context->superBlock = sb;
2488
2489         
2490
2491 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2492         sb->s_fs_info = dev;
2493 #else
2494         sb->u.generic_sbp = dev;
2495 #endif
2496         
2497         yaffs_DeviceToContext(dev)->mtd = mtd;
2498         param->name = mtd->name;
2499
2500         /* Set up the memory size parameters.... */
2501
2502         nBlocks = YCALCBLOCKS(mtd->size, (YAFFS_CHUNKS_PER_BLOCK * YAFFS_BYTES_PER_CHUNK));
2503
2504         param->startBlock = 0;
2505         param->endBlock = nBlocks - 1;
2506         param->nChunksPerBlock = YAFFS_CHUNKS_PER_BLOCK;
2507         param->totalBytesPerChunk = YAFFS_BYTES_PER_CHUNK;
2508         param->nReservedBlocks = 5;
2509         param->nShortOpCaches = (options.no_cache) ? 0 : 10;
2510         param->inbandTags = options.inband_tags;
2511
2512 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
2513         param->disableLazyLoad = 1;
2514 #endif
2515         if(options.lazy_loading_overridden)
2516                 param->disableLazyLoad = !options.lazy_loading_enabled;
2517
2518 #ifdef CONFIG_YAFFS_DISABLE_TAGS_ECC
2519         param->noTagsECC = 1;
2520 #endif
2521
2522 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND
2523 #else
2524         param->deferDirectoryUpdate = 1;
2525 #endif
2526
2527         if(options.tags_ecc_overridden)
2528                 param->noTagsECC = !options.tags_ecc_on;
2529
2530 #ifdef CONFIG_YAFFS_EMPTY_LOST_AND_FOUND
2531         param->emptyLostAndFound = 1;
2532 #endif
2533
2534 #ifdef CONFIG_YAFFS_DISABLE_BLOCK_REFRESHING
2535         param->refreshPeriod = 0;
2536 #else
2537         param->refreshPeriod = 10000;
2538 #endif
2539
2540         if(options.empty_lost_and_found_overridden)
2541                 param->emptyLostAndFound = options.empty_lost_and_found;
2542
2543         /* ... and the functions. */
2544         if (yaffsVersion == 2) {
2545                 param->writeChunkWithTagsToNAND =
2546                     nandmtd2_WriteChunkWithTagsToNAND;
2547                 param->readChunkWithTagsFromNAND =
2548                     nandmtd2_ReadChunkWithTagsFromNAND;
2549                 param->markNANDBlockBad = nandmtd2_MarkNANDBlockBad;
2550                 param->queryNANDBlock = nandmtd2_QueryNANDBlock;
2551                 yaffs_DeviceToContext(dev)->spareBuffer = YMALLOC(mtd->oobsize);
2552                 param->isYaffs2 = 1;
2553 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2554                 param->totalBytesPerChunk = mtd->writesize;
2555                 param->nChunksPerBlock = mtd->erasesize / mtd->writesize;
2556 #else
2557                 param->totalBytesPerChunk = mtd->oobblock;
2558                 param->nChunksPerBlock = mtd->erasesize / mtd->oobblock;
2559 #endif
2560                 nBlocks = YCALCBLOCKS(mtd->size, mtd->erasesize);
2561
2562                 param->startBlock = 0;
2563                 param->endBlock = nBlocks - 1;
2564         } else {
2565 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2566                 /* use the MTD interface in yaffs_mtdif1.c */
2567                 param->writeChunkWithTagsToNAND =
2568                         nandmtd1_WriteChunkWithTagsToNAND;
2569                 param->readChunkWithTagsFromNAND =
2570                         nandmtd1_ReadChunkWithTagsFromNAND;
2571                 param->markNANDBlockBad = nandmtd1_MarkNANDBlockBad;
2572                 param->queryNANDBlock = nandmtd1_QueryNANDBlock;
2573 #else
2574                 param->writeChunkToNAND = nandmtd_WriteChunkToNAND;
2575                 param->readChunkFromNAND = nandmtd_ReadChunkFromNAND;
2576 #endif
2577                 param->isYaffs2 = 0;
2578         }
2579         /* ... and common functions */
2580         param->eraseBlockInNAND = nandmtd_EraseBlockInNAND;
2581         param->initialiseNAND = nandmtd_InitialiseNAND;
2582
2583         yaffs_DeviceToContext(dev)->putSuperFunc = yaffs_MTDPutSuper;
2584
2585         param->markSuperBlockDirty = yaffs_MarkSuperBlockDirty;
2586         param->gcControl = yaffs_gc_control_callback;
2587
2588         yaffs_DeviceToContext(dev)->superBlock= sb;
2589         
2590
2591 #ifndef CONFIG_YAFFS_DOES_ECC
2592         param->useNANDECC = 1;
2593 #endif
2594
2595 #ifdef CONFIG_YAFFS_DISABLE_WIDE_TNODES
2596         param->wideTnodesDisabled = 1;
2597 #endif
2598
2599         param->skipCheckpointRead = options.skip_checkpoint_read;
2600         param->skipCheckpointWrite = options.skip_checkpoint_write;
2601
2602         /* we assume this is protected by lock_kernel() in mount/umount */
2603         down(&yaffs_context_lock);
2604         ylist_add_tail(&(yaffs_DeviceToContext(dev)->contextList), &yaffs_context_list);
2605         up(&yaffs_context_lock);
2606
2607         /* Directory search handling...*/
2608         YINIT_LIST_HEAD(&(yaffs_DeviceToContext(dev)->searchContexts));
2609         param->removeObjectCallback = yaffs_RemoveObjectCallback;
2610
2611         init_MUTEX(&(yaffs_DeviceToContext(dev)->grossLock));
2612
2613         yaffs_GrossLock(dev);
2614
2615         err = yaffs_GutsInitialise(dev);
2616
2617         T(YAFFS_TRACE_OS,
2618           ("yaffs_read_super: guts initialised %s\n",
2619            (err == YAFFS_OK) ? "OK" : "FAILED"));
2620            
2621         if(err == YAFFS_OK)
2622                 yaffs_BackgroundStart(dev);
2623                 
2624         if(!context->bgThread)
2625                 param->deferDirectoryUpdate = 0;
2626
2627
2628         /* Release lock before yaffs_get_inode() */
2629         yaffs_GrossUnlock(dev);
2630
2631         /* Create root inode */
2632         if (err == YAFFS_OK)
2633                 inode = yaffs_get_inode(sb, S_IFDIR | 0755, 0,
2634                                         yaffs_Root(dev));
2635
2636         if (!inode)
2637                 return NULL;
2638
2639         inode->i_op = &yaffs_dir_inode_operations;
2640         inode->i_fop = &yaffs_dir_operations;
2641
2642         T(YAFFS_TRACE_OS, ("yaffs_read_super: got root inode\n"));
2643
2644         root = d_alloc_root(inode);
2645
2646         T(YAFFS_TRACE_OS, ("yaffs_read_super: d_alloc_root done\n"));
2647
2648         if (!root) {
2649                 iput(inode);
2650                 return NULL;
2651         }
2652         sb->s_root = root;
2653         sb->s_dirt = !dev->isCheckpointed;
2654         T(YAFFS_TRACE_ALWAYS,
2655           ("yaffs_read_super: isCheckpointed %d\n", dev->isCheckpointed));
2656
2657         T(YAFFS_TRACE_OS, ("yaffs_read_super: done\n"));
2658         return sb;
2659 }
2660
2661
2662 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2663 static int yaffs_internal_read_super_mtd(struct super_block *sb, void *data,
2664                                          int silent)
2665 {
2666         return yaffs_internal_read_super(1, sb, data, silent) ? 0 : -EINVAL;
2667 }
2668
2669 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2670 static int yaffs_read_super(struct file_system_type *fs,
2671                             int flags, const char *dev_name,
2672                             void *data, struct vfsmount *mnt)
2673 {
2674
2675         return get_sb_bdev(fs, flags, dev_name, data,
2676                            yaffs_internal_read_super_mtd, mnt);
2677 }
2678 #else
2679 static struct super_block *yaffs_read_super(struct file_system_type *fs,
2680                                             int flags, const char *dev_name,
2681                                             void *data)
2682 {
2683
2684         return get_sb_bdev(fs, flags, dev_name, data,
2685                            yaffs_internal_read_super_mtd);
2686 }
2687 #endif
2688
2689 static struct file_system_type yaffs_fs_type = {
2690         .owner = THIS_MODULE,
2691         .name = "yaffs",
2692         .get_sb = yaffs_read_super,
2693         .kill_sb = kill_block_super,
2694         .fs_flags = FS_REQUIRES_DEV,
2695 };
2696 #else
2697 static struct super_block *yaffs_read_super(struct super_block *sb, void *data,
2698                                             int silent)
2699 {
2700         return yaffs_internal_read_super(1, sb, data, silent);
2701 }
2702
2703 static DECLARE_FSTYPE(yaffs_fs_type, "yaffs", yaffs_read_super,
2704                       FS_REQUIRES_DEV);
2705 #endif
2706
2707
2708 #ifdef CONFIG_YAFFS_YAFFS2
2709
2710 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2711 static int yaffs2_internal_read_super_mtd(struct super_block *sb, void *data,
2712                                           int silent)
2713 {
2714         return yaffs_internal_read_super(2, sb, data, silent) ? 0 : -EINVAL;
2715 }
2716
2717 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2718 static int yaffs2_read_super(struct file_system_type *fs,
2719                         int flags, const char *dev_name, void *data,
2720                         struct vfsmount *mnt)
2721 {
2722         return get_sb_bdev(fs, flags, dev_name, data,
2723                         yaffs2_internal_read_super_mtd, mnt);
2724 }
2725 #else
2726 static struct super_block *yaffs2_read_super(struct file_system_type *fs,
2727                                              int flags, const char *dev_name,
2728                                              void *data)
2729 {
2730
2731         return get_sb_bdev(fs, flags, dev_name, data,
2732                            yaffs2_internal_read_super_mtd);
2733 }
2734 #endif
2735
2736 static struct file_system_type yaffs2_fs_type = {
2737         .owner = THIS_MODULE,
2738         .name = "yaffs2",
2739         .get_sb = yaffs2_read_super,
2740         .kill_sb = kill_block_super,
2741         .fs_flags = FS_REQUIRES_DEV,
2742 };
2743 #else
2744 static struct super_block *yaffs2_read_super(struct super_block *sb,
2745                                              void *data, int silent)
2746 {
2747         return yaffs_internal_read_super(2, sb, data, silent);
2748 }
2749
2750 static DECLARE_FSTYPE(yaffs2_fs_type, "yaffs2", yaffs2_read_super,
2751                       FS_REQUIRES_DEV);
2752 #endif
2753
2754 #endif                          /* CONFIG_YAFFS_YAFFS2 */
2755
2756 static struct proc_dir_entry *my_proc_entry;
2757 static struct proc_dir_entry *debug_proc_entry;
2758
2759 static char *yaffs_dump_dev_part0(char *buf, yaffs_Device * dev)
2760 {
2761         buf += sprintf(buf, "startBlock......... %d\n", dev->param.startBlock);
2762         buf += sprintf(buf, "endBlock........... %d\n", dev->param.endBlock);
2763         buf += sprintf(buf, "totalBytesPerChunk. %d\n", dev->param.totalBytesPerChunk);
2764         buf += sprintf(buf, "useNANDECC......... %d\n", dev->param.useNANDECC);
2765         buf += sprintf(buf, "noTagsECC.......... %d\n", dev->param.noTagsECC);
2766         buf += sprintf(buf, "isYaffs2........... %d\n", dev->param.isYaffs2);
2767         buf += sprintf(buf, "inbandTags......... %d\n", dev->param.inbandTags);
2768         buf += sprintf(buf, "emptyLostAndFound.. %d\n", dev->param.emptyLostAndFound);
2769         buf += sprintf(buf, "disableLazyLoad.... %d\n", dev->param.disableLazyLoad);
2770         buf += sprintf(buf, "refreshPeriod...... %d\n", dev->param.refreshPeriod);
2771         buf += sprintf(buf, "nShortOpCaches..... %d\n", dev->param.nShortOpCaches);
2772         buf += sprintf(buf, "nReservedBlocks.... %d\n", dev->param.nReservedBlocks);
2773
2774         buf += sprintf(buf, "\n");
2775
2776         return buf;
2777 }
2778
2779
2780 static char *yaffs_dump_dev_part1(char *buf, yaffs_Device * dev)
2781 {
2782         buf += sprintf(buf, "nDataBytesPerChunk. %d\n", dev->nDataBytesPerChunk);
2783         buf += sprintf(buf, "chunkGroupBits..... %d\n", dev->chunkGroupBits);
2784         buf += sprintf(buf, "chunkGroupSize..... %d\n", dev->chunkGroupSize);
2785         buf += sprintf(buf, "nErasedBlocks...... %d\n", dev->nErasedBlocks);
2786         buf += sprintf(buf, "blocksInCheckpoint. %d\n", dev->blocksInCheckpoint);
2787         buf += sprintf(buf, "\n");
2788         buf += sprintf(buf, "nTnodesCreated..... %d\n", dev->nTnodesCreated);
2789         buf += sprintf(buf, "nFreeTnodes........ %d\n", dev->nFreeTnodes);
2790         buf += sprintf(buf, "nObjectsCreated.... %d\n", dev->nObjectsCreated);
2791         buf += sprintf(buf, "nFreeObjects....... %d\n", dev->nFreeObjects);
2792         buf += sprintf(buf, "nFreeChunks........ %d\n", dev->nFreeChunks);
2793         buf += sprintf(buf, "\n");
2794         buf += sprintf(buf, "nPageWrites........ %u\n", dev->nPageWrites);
2795         buf += sprintf(buf, "nPageReads......... %u\n", dev->nPageReads);
2796         buf += sprintf(buf, "nBlockErasures..... %u\n", dev->nBlockErasures);
2797         buf += sprintf(buf, "nGCCopies.......... %u\n", dev->nGCCopies);
2798         buf += sprintf(buf, "garbageCollections. %u\n", dev->garbageCollections);
2799         buf += sprintf(buf, "passiveGCs......... %u\n", dev->passiveGarbageCollections);
2800         buf += sprintf(buf, "nRetriedWrites..... %u\n", dev->nRetriedWrites);
2801         buf += sprintf(buf, "nRetireBlocks...... %u\n", dev->nRetiredBlocks);
2802         buf += sprintf(buf, "eccFixed........... %u\n", dev->eccFixed);
2803         buf += sprintf(buf, "eccUnfixed......... %u\n", dev->eccUnfixed);
2804         buf += sprintf(buf, "tagsEccFixed....... %u\n", dev->tagsEccFixed);
2805         buf += sprintf(buf, "tagsEccUnfixed..... %u\n", dev->tagsEccUnfixed);
2806         buf += sprintf(buf, "cacheHits.......... %u\n", dev->cacheHits);
2807         buf += sprintf(buf, "nDeletedFiles...... %u\n", dev->nDeletedFiles);
2808         buf += sprintf(buf, "nUnlinkedFiles..... %u\n", dev->nUnlinkedFiles);
2809         buf += sprintf(buf, "refreshCount....... %u\n", dev->refreshCount);
2810         buf +=
2811             sprintf(buf, "nBackgroudDeletions %u\n", dev->nBackgroundDeletions);
2812
2813         return buf;
2814 }
2815
2816 static int yaffs_proc_read(char *page,
2817                            char **start,
2818                            off_t offset, int count, int *eof, void *data)
2819 {
2820         struct ylist_head *item;
2821         char *buf = page;
2822         int step = offset;
2823         int n = 0;
2824
2825         /* Get proc_file_read() to step 'offset' by one on each sucessive call.
2826          * We use 'offset' (*ppos) to indicate where we are in devList.
2827          * This also assumes the user has posted a read buffer large
2828          * enough to hold the complete output; but that's life in /proc.
2829          */
2830
2831         *(int *)start = 1;
2832
2833         /* Print header first */
2834         if (step == 0)
2835                 buf += sprintf(buf, "YAFFS built:" __DATE__ " " __TIME__
2836                                "\n%s\n%s\n", yaffs_fs_c_version,
2837                                yaffs_guts_c_version);
2838         else if (step == 1)
2839                 buf += sprintf(buf,"\n");
2840         else {
2841                 step-=2;
2842                 
2843                 down(&yaffs_context_lock);
2844
2845                 /* Locate and print the Nth entry.  Order N-squared but N is small. */
2846                 ylist_for_each(item, &yaffs_context_list) {
2847                         struct yaffs_LinuxContext *dc = ylist_entry(item, struct yaffs_LinuxContext, contextList);
2848                         yaffs_Device *dev = dc->dev;
2849
2850                         if (n < (step & ~1)) {
2851                                 n+=2;
2852                                 continue;
2853                         }
2854                         if((step & 1)==0){
2855                                 buf += sprintf(buf, "\nDevice %d \"%s\"\n", n, dev->param.name);
2856                                 buf = yaffs_dump_dev_part0(buf, dev);
2857                         } else
2858                                 buf = yaffs_dump_dev_part1(buf, dev);
2859                         
2860                         break;
2861                 }
2862                 up(&yaffs_context_lock);
2863         }
2864
2865         return buf - page < count ? buf - page : count;
2866 }
2867
2868 static int yaffs_debug_proc_read(char *page,
2869                                 char **start,
2870                                 off_t offset, int count, int *eof, void *data)
2871 {
2872         struct ylist_head *item;
2873         char *buf = page;
2874         int n = 0;
2875
2876         down(&yaffs_context_lock);
2877
2878         /* Locate and print the Nth entry.  Order N-squared but N is small. */
2879         ylist_for_each(item, &yaffs_context_list) {
2880                 struct yaffs_LinuxContext *dc = ylist_entry(item, struct yaffs_LinuxContext, contextList);
2881                 yaffs_Device *dev = dc->dev;
2882
2883                 int erasedChunks;
2884                 int nObjects;
2885                 int nTnodes;
2886
2887                 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2888                 nObjects = dev->nObjectsCreated -dev->nFreeObjects;
2889                 nTnodes = dev->nTnodesCreated - dev->nFreeTnodes;
2890                 
2891                 
2892                 buf += sprintf(buf,"%d, %d, %d, %d, %d\n", 
2893                                 n, dev->nFreeChunks, erasedChunks,
2894                                 nObjects, nTnodes);
2895         }
2896         up(&yaffs_context_lock);
2897
2898
2899         return buf - page < count ? buf - page : count;
2900 }
2901
2902 /**
2903  * Set the verbosity of the warnings and error messages.
2904  *
2905  * Note that the names can only be a..z or _ with the current code.
2906  */
2907
2908 static struct {
2909         char *mask_name;
2910         unsigned mask_bitfield;
2911 } mask_flags[] = {
2912         {"allocate", YAFFS_TRACE_ALLOCATE},
2913         {"always", YAFFS_TRACE_ALWAYS},
2914         {"bad_blocks", YAFFS_TRACE_BAD_BLOCKS},
2915         {"buffers", YAFFS_TRACE_BUFFERS},
2916         {"bug", YAFFS_TRACE_BUG},
2917         {"checkpt", YAFFS_TRACE_CHECKPOINT},
2918         {"deletion", YAFFS_TRACE_DELETION},
2919         {"erase", YAFFS_TRACE_ERASE},
2920         {"error", YAFFS_TRACE_ERROR},
2921         {"gc_detail", YAFFS_TRACE_GC_DETAIL},
2922         {"gc", YAFFS_TRACE_GC},
2923         {"mtd", YAFFS_TRACE_MTD},
2924         {"nandaccess", YAFFS_TRACE_NANDACCESS},
2925         {"os", YAFFS_TRACE_OS},
2926         {"scan_debug", YAFFS_TRACE_SCAN_DEBUG},
2927         {"scan", YAFFS_TRACE_SCAN},
2928         {"tracing", YAFFS_TRACE_TRACING},
2929         {"sync", YAFFS_TRACE_SYNC},
2930
2931         {"background", YAFFS_TRACE_BACKGROUND},
2932
2933         {"verify", YAFFS_TRACE_VERIFY},
2934         {"verify_nand", YAFFS_TRACE_VERIFY_NAND},
2935         {"verify_full", YAFFS_TRACE_VERIFY_FULL},
2936         {"verify_all", YAFFS_TRACE_VERIFY_ALL},
2937
2938         {"write", YAFFS_TRACE_WRITE},
2939         {"all", 0xffffffff},
2940         {"none", 0},
2941         {NULL, 0},
2942 };
2943
2944 #define MAX_MASK_NAME_LENGTH 40
2945 static int yaffs_proc_write_trace_options(struct file *file, const char *buf,
2946                                          unsigned long count, void *data)
2947 {
2948         unsigned rg = 0, mask_bitfield;
2949         char *end;
2950         char *mask_name;
2951         const char *x;
2952         char substring[MAX_MASK_NAME_LENGTH + 1];
2953         int i;
2954         int done = 0;
2955         int add, len = 0;
2956         int pos = 0;
2957
2958         rg = yaffs_traceMask;
2959
2960         while (!done && (pos < count)) {
2961                 done = 1;
2962                 while ((pos < count) && isspace(buf[pos]))
2963                         pos++;
2964
2965                 switch (buf[pos]) {
2966                 case '+':
2967                 case '-':
2968                 case '=':
2969                         add = buf[pos];
2970                         pos++;
2971                         break;
2972
2973                 default:
2974                         add = ' ';
2975                         break;
2976                 }
2977                 mask_name = NULL;
2978
2979                 mask_bitfield = simple_strtoul(buf + pos, &end, 0);
2980
2981                 if (end > buf + pos) {
2982                         mask_name = "numeral";
2983                         len = end - (buf + pos);
2984                         pos += len;
2985                         done = 0;
2986                 } else {
2987                         for (x = buf + pos, i = 0;
2988                             (*x == '_' || (*x >= 'a' && *x <= 'z')) &&
2989                             i < MAX_MASK_NAME_LENGTH; x++, i++, pos++)
2990                                 substring[i] = *x;
2991                         substring[i] = '\0';
2992
2993                         for (i = 0; mask_flags[i].mask_name != NULL; i++) {
2994                                 if (strcmp(substring, mask_flags[i].mask_name) == 0) {
2995                                         mask_name = mask_flags[i].mask_name;
2996                                         mask_bitfield = mask_flags[i].mask_bitfield;
2997                                         done = 0;
2998                                         break;
2999                                 }
3000                         }
3001                 }
3002
3003                 if (mask_name != NULL) {
3004                         done = 0;
3005                         switch (add) {
3006                         case '-':
3007                                 rg &= ~mask_bitfield;
3008                                 break;
3009                         case '+':
3010                                 rg |= mask_bitfield;
3011                                 break;
3012                         case '=':
3013                                 rg = mask_bitfield;
3014                                 break;
3015                         default:
3016                                 rg |= mask_bitfield;
3017                                 break;
3018                         }
3019                 }
3020         }
3021
3022         yaffs_traceMask = rg | YAFFS_TRACE_ALWAYS;
3023
3024         printk(KERN_DEBUG "new trace = 0x%08X\n", yaffs_traceMask);
3025
3026         if (rg & YAFFS_TRACE_ALWAYS) {
3027                 for (i = 0; mask_flags[i].mask_name != NULL; i++) {
3028                         char flag;
3029                         flag = ((rg & mask_flags[i].mask_bitfield) == mask_flags[i].mask_bitfield) ? '+' : '-';
3030                         printk(KERN_DEBUG "%c%s\n", flag, mask_flags[i].mask_name);
3031                 }
3032         }
3033
3034         return count;
3035 }
3036
3037
3038 static int yaffs_proc_write(struct file *file, const char *buf,
3039                                          unsigned long count, void *data)
3040 {
3041         return yaffs_proc_write_trace_options(file, buf, count, data);
3042 }
3043
3044 /* Stuff to handle installation of file systems */
3045 struct file_system_to_install {
3046         struct file_system_type *fst;
3047         int installed;
3048 };
3049
3050 static struct file_system_to_install fs_to_install[] = {
3051         {&yaffs_fs_type, 0},
3052         {&yaffs2_fs_type, 0},
3053         {NULL, 0}
3054 };
3055
3056 static int __init init_yaffs_fs(void)
3057 {
3058         int error = 0;
3059         struct file_system_to_install *fsinst;
3060
3061         T(YAFFS_TRACE_ALWAYS,
3062           ("yaffs " __DATE__ " " __TIME__ " Installing. \n"));
3063
3064         init_MUTEX(&yaffs_context_lock);
3065
3066         /* Install the proc_fs entries */
3067         my_proc_entry = create_proc_entry("yaffs",
3068                                                S_IRUGO | S_IFREG,
3069                                                YPROC_ROOT);
3070
3071         if (my_proc_entry) {
3072                 my_proc_entry->write_proc = yaffs_proc_write;
3073                 my_proc_entry->read_proc = yaffs_proc_read;
3074                 my_proc_entry->data = NULL;
3075         } else
3076                 return -ENOMEM;
3077
3078         debug_proc_entry = create_proc_entry("yaffs_debug",
3079                                                S_IRUGO | S_IFREG,
3080                                                YPROC_ROOT);
3081
3082         if (debug_proc_entry) {
3083                 debug_proc_entry->write_proc = NULL;
3084                 debug_proc_entry->read_proc = yaffs_debug_proc_read;
3085                 debug_proc_entry->data = NULL;
3086         } else
3087                 return -ENOMEM;
3088
3089         /* Now add the file system entries */
3090
3091         fsinst = fs_to_install;
3092
3093         while (fsinst->fst && !error) {
3094                 error = register_filesystem(fsinst->fst);
3095                 if (!error)
3096                         fsinst->installed = 1;
3097                 fsinst++;
3098         }
3099
3100         /* Any errors? uninstall  */
3101         if (error) {
3102                 fsinst = fs_to_install;
3103
3104                 while (fsinst->fst) {
3105                         if (fsinst->installed) {
3106                                 unregister_filesystem(fsinst->fst);
3107                                 fsinst->installed = 0;
3108                         }
3109                         fsinst++;
3110                 }
3111         }
3112
3113         return error;
3114 }
3115
3116 static void __exit exit_yaffs_fs(void)
3117 {
3118
3119         struct file_system_to_install *fsinst;
3120
3121         T(YAFFS_TRACE_ALWAYS, ("yaffs " __DATE__ " " __TIME__
3122                                " removing. \n"));
3123
3124         remove_proc_entry("yaffs", YPROC_ROOT);
3125
3126         fsinst = fs_to_install;
3127
3128         while (fsinst->fst) {
3129                 if (fsinst->installed) {
3130                         unregister_filesystem(fsinst->fst);
3131                         fsinst->installed = 0;
3132                 }
3133                 fsinst++;
3134         }
3135 }
3136
3137 module_init(init_yaffs_fs)
3138 module_exit(exit_yaffs_fs)
3139
3140 MODULE_DESCRIPTION("YAFFS2 - a NAND specific flash file system");
3141 MODULE_AUTHOR("Charles Manning, Aleph One Ltd., 2002-2006");
3142 MODULE_LICENSE("GPL");