efaacac4b9c41de2bf3c50aa420ca0136be9e81f
[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         unsigned int oneshot_checkpoint = (yaffs_auto_checkpoint & 4);
1941
1942         T(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, 
1943                 ("yaffs_do_sync_fs: %s %s%s\n",
1944                 sb->s_dirt ? "dirty" : "clean",
1945                 do_checkpoint ? "with checkpoint" : "no checkpoint",
1946                 oneshot_checkpoint ? " one-shot" : "" ));
1947
1948         if (sb->s_dirt || oneshot_checkpoint) {
1949                 yaffs_GrossLock(dev);
1950                 yaffs_FlushSuperBlock(sb,do_checkpoint);
1951                 yaffs_GrossUnlock(dev);
1952
1953                 sb->s_dirt = 0;
1954
1955                 if(oneshot_checkpoint)
1956                         yaffs_auto_checkpoint &= ~4;
1957         }
1958         return 0;
1959 }
1960
1961 /*
1962  * yaffs background thread functions .
1963  * yaffs_BackgroundThread() the thread function
1964  * yaffs_BackgroundStart() launches the background thread.
1965  * yaffs_BackgroundStop() cleans up the background thread.
1966  *
1967  * NB: 
1968  * The thread should only run after the yaffs is initialised
1969  * The thread should be stopped before yaffs is unmounted.
1970  * The thread should not do any writing while the fs is in read only.
1971  */
1972
1973 #ifdef YAFFS_COMPILE_BACKGROUND
1974 static int yaffs_BackgroundThread(void *data)
1975 {
1976         yaffs_Device *dev = (yaffs_Device *)data;
1977         struct yaffs_LinuxContext *context = yaffs_DeviceToContext(dev);
1978
1979         T(YAFFS_TRACE_BACKGROUND,
1980                 ("yaffs_background starting for dev %p\n",
1981                 (void *)dev));
1982         
1983         while(context->bgRunning){
1984                 T(YAFFS_TRACE_BACKGROUND,
1985                         ("yaffs_background\n"));
1986
1987                 if(kthread_should_stop())
1988                         break;
1989                 yaffs_GrossLock(dev);
1990                 yaffs_UpdateDirtyDirectories(dev);
1991                 yaffs_GrossUnlock(dev);
1992                 msleep(500);
1993         }
1994         return 0;
1995 }
1996
1997 static int yaffs_BackgroundStart(yaffs_Device *dev)
1998 {
1999         int retval = 0;
2000
2001         struct yaffs_LinuxContext *context = yaffs_DeviceToContext(dev);
2002
2003         context->bgRunning = 1;
2004
2005         context->bgThread = kthread_run(yaffs_BackgroundThread,(void *)dev,"yaffs_%x",(unsigned)dev);
2006
2007         if(IS_ERR(context->bgThread)){
2008                 retval = PTR_ERR(context->bgThread);
2009                 context->bgThread = NULL;
2010                 context->bgRunning = 0;
2011         }
2012         return retval;
2013 }
2014
2015 static void yaffs_BackgroundStop(yaffs_Device *dev)
2016 {
2017         struct yaffs_LinuxContext *ctxt = yaffs_DeviceToContext(dev);
2018
2019         ctxt->bgRunning = 0;
2020
2021         if( ctxt->bgThread){
2022                 kthread_stop(ctxt->bgThread);
2023                 ctxt->bgThread = NULL;
2024         }
2025 }
2026 #else
2027 static int yaffs_BackgroundThread(void *data)
2028 {
2029         return 0;
2030 }
2031
2032 static int yaffs_BackgroundStart(yaffs_Device *dev)
2033 {
2034         return 0;
2035 }
2036
2037 static void yaffs_BackgroundStop(yaffs_Device *dev)
2038 {
2039 }
2040 #endif
2041
2042
2043 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2044 static void yaffs_write_super(struct super_block *sb)
2045 #else
2046 static int yaffs_write_super(struct super_block *sb)
2047 #endif
2048 {
2049
2050         T(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, ("yaffs_write_super\n"));
2051         yaffs_do_sync_fs(sb, yaffs_auto_checkpoint >= 2);
2052
2053 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 18))
2054         return 0;
2055 #endif
2056 }
2057
2058
2059 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2060 static int yaffs_sync_fs(struct super_block *sb, int wait)
2061 #else
2062 static int yaffs_sync_fs(struct super_block *sb)
2063 #endif
2064 {
2065         T(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, ("yaffs_sync_fs\n"));
2066
2067         yaffs_do_sync_fs(sb,yaffs_auto_checkpoint >= 1);
2068
2069         return 0;
2070 }
2071
2072 #ifdef YAFFS_USE_OWN_IGET
2073
2074 static struct inode *yaffs_iget(struct super_block *sb, unsigned long ino)
2075 {
2076         struct inode *inode;
2077         yaffs_Object *obj;
2078         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2079
2080         T(YAFFS_TRACE_OS,
2081                 ("yaffs_iget for %lu\n", ino));
2082
2083         inode = iget_locked(sb, ino);
2084         if (!inode)
2085                 return ERR_PTR(-ENOMEM);
2086         if (!(inode->i_state & I_NEW))
2087                 return inode;
2088
2089         /* NB This is called as a side effect of other functions, but
2090          * we had to release the lock to prevent deadlocks, so
2091          * need to lock again.
2092          */
2093
2094         yaffs_GrossLock(dev);
2095
2096         obj = yaffs_FindObjectByNumber(dev, inode->i_ino);
2097
2098         yaffs_FillInodeFromObject(inode, obj);
2099
2100         yaffs_GrossUnlock(dev);
2101
2102         unlock_new_inode(inode);
2103         return inode;
2104 }
2105
2106 #else
2107
2108 static void yaffs_read_inode(struct inode *inode)
2109 {
2110         /* NB This is called as a side effect of other functions, but
2111          * we had to release the lock to prevent deadlocks, so
2112          * need to lock again.
2113          */
2114
2115         yaffs_Object *obj;
2116         yaffs_Device *dev = yaffs_SuperToDevice(inode->i_sb);
2117
2118         T(YAFFS_TRACE_OS,
2119                 ("yaffs_read_inode for %d\n", (int)inode->i_ino));
2120
2121         if(current != yaffs_DeviceToContext(dev)->readdirProcess)
2122                 yaffs_GrossLock(dev);
2123
2124         obj = yaffs_FindObjectByNumber(dev, inode->i_ino);
2125
2126         yaffs_FillInodeFromObject(inode, obj);
2127
2128         if(current != yaffs_DeviceToContext(dev)->readdirProcess)
2129                 yaffs_GrossUnlock(dev);
2130 }
2131
2132 #endif
2133
2134 static YLIST_HEAD(yaffs_context_list);
2135 struct semaphore yaffs_context_lock;
2136
2137 #if 0 /* not used */
2138 static int yaffs_remount_fs(struct super_block *sb, int *flags, char *data)
2139 {
2140         yaffs_Device    *dev = yaffs_SuperToDevice(sb);
2141
2142         if (*flags & MS_RDONLY) {
2143                 struct mtd_info *mtd = yaffs_SuperToDevice(sb)->genericDevice;
2144
2145                 T(YAFFS_TRACE_OS,
2146                         ("yaffs_remount_fs: %s: RO\n", dev->name));
2147
2148                 yaffs_GrossLock(dev);
2149
2150                 yaffs_FlushSuperBlock(sb,1);
2151
2152                 if (mtd->sync)
2153                         mtd->sync(mtd);
2154
2155                 yaffs_GrossUnlock(dev);
2156         } else {
2157                 T(YAFFS_TRACE_OS,
2158                         ("yaffs_remount_fs: %s: RW\n", dev->name));
2159         }
2160
2161         return 0;
2162 }
2163 #endif
2164
2165 static void yaffs_put_super(struct super_block *sb)
2166 {
2167         yaffs_Device *dev = yaffs_SuperToDevice(sb);
2168
2169         T(YAFFS_TRACE_OS, ("yaffs_put_super\n"));
2170
2171         yaffs_GrossLock(dev);
2172
2173         yaffs_FlushSuperBlock(sb,1);
2174
2175         if (yaffs_DeviceToContext(dev)->putSuperFunc)
2176                 yaffs_DeviceToContext(dev)->putSuperFunc(sb);
2177
2178         yaffs_BackgroundStop(dev);
2179
2180         yaffs_Deinitialise(dev);
2181
2182         yaffs_GrossUnlock(dev);
2183
2184         down(&yaffs_context_lock);
2185         ylist_del_init(&(yaffs_DeviceToContext(dev)->contextList));
2186         up(&yaffs_context_lock);
2187
2188         if (yaffs_DeviceToContext(dev)->spareBuffer) {
2189                 YFREE(yaffs_DeviceToContext(dev)->spareBuffer);
2190                 yaffs_DeviceToContext(dev)->spareBuffer = NULL;
2191         }
2192
2193         kfree(dev);
2194 }
2195
2196
2197 static void yaffs_MTDPutSuper(struct super_block *sb)
2198 {
2199         struct mtd_info *mtd = yaffs_DeviceToContext(yaffs_SuperToDevice(sb))->mtd;
2200
2201         if (mtd->sync)
2202                 mtd->sync(mtd);
2203
2204         put_mtd_device(mtd);
2205 }
2206
2207
2208 static void yaffs_MarkSuperBlockDirty(yaffs_Device *dev)
2209 {
2210         struct super_block *sb = yaffs_DeviceToContext(dev)->superBlock;
2211
2212         T(YAFFS_TRACE_OS, ("yaffs_MarkSuperBlockDirty() sb = %p\n", sb));
2213         if (sb)
2214                 sb->s_dirt = 1;
2215 }
2216
2217 typedef struct {
2218         int inband_tags;
2219         int skip_checkpoint_read;
2220         int skip_checkpoint_write;
2221         int no_cache;
2222         int tags_ecc_on;
2223         int tags_ecc_overridden;
2224         int lazy_loading_enabled;
2225         int lazy_loading_overridden;
2226         int empty_lost_and_found;
2227         int empty_lost_and_found_overridden;
2228 } yaffs_options;
2229
2230 #define MAX_OPT_LEN 30
2231 static int yaffs_parse_options(yaffs_options *options, const char *options_str)
2232 {
2233         char cur_opt[MAX_OPT_LEN + 1];
2234         int p;
2235         int error = 0;
2236
2237         /* Parse through the options which is a comma seperated list */
2238
2239         while (options_str && *options_str && !error) {
2240                 memset(cur_opt, 0, MAX_OPT_LEN + 1);
2241                 p = 0;
2242
2243                 while(*options_str == ',')
2244                         options_str++;
2245
2246                 while (*options_str && *options_str != ',') {
2247                         if (p < MAX_OPT_LEN) {
2248                                 cur_opt[p] = *options_str;
2249                                 p++;
2250                         }
2251                         options_str++;
2252                 }
2253
2254                 if (!strcmp(cur_opt, "inband-tags"))
2255                         options->inband_tags = 1;
2256                 else if (!strcmp(cur_opt, "tags-ecc-off")){
2257                         options->tags_ecc_on = 0;
2258                         options->tags_ecc_overridden=1;
2259                 } else if (!strcmp(cur_opt, "tags-ecc-on")){
2260                         options->tags_ecc_on = 1;
2261                         options->tags_ecc_overridden = 1;
2262                 } else if (!strcmp(cur_opt, "lazy-loading-off")){
2263                         options->lazy_loading_enabled = 0;
2264                         options->lazy_loading_overridden=1;
2265                 } else if (!strcmp(cur_opt, "lazy-loading-on")){
2266                         options->lazy_loading_enabled = 1;
2267                         options->lazy_loading_overridden = 1;
2268                 } else if (!strcmp(cur_opt, "empty-lost-and-found-off")){
2269                         options->empty_lost_and_found = 0;
2270                         options->empty_lost_and_found_overridden=1;
2271                 } else if (!strcmp(cur_opt, "empty-lost-and-found-on")){
2272                         options->empty_lost_and_found = 1;
2273                         options->empty_lost_and_found_overridden=1;
2274                 } else if (!strcmp(cur_opt, "no-cache"))
2275                         options->no_cache = 1;
2276                 else if (!strcmp(cur_opt, "no-checkpoint-read"))
2277                         options->skip_checkpoint_read = 1;
2278                 else if (!strcmp(cur_opt, "no-checkpoint-write"))
2279                         options->skip_checkpoint_write = 1;
2280                 else if (!strcmp(cur_opt, "no-checkpoint")) {
2281                         options->skip_checkpoint_read = 1;
2282                         options->skip_checkpoint_write = 1;
2283                 } else {
2284                         printk(KERN_INFO "yaffs: Bad mount option \"%s\"\n",
2285                                         cur_opt);
2286                         error = 1;
2287                 }
2288         }
2289
2290         return error;
2291 }
2292
2293 static struct super_block *yaffs_internal_read_super(int yaffsVersion,
2294                                                 struct super_block *sb,
2295                                                 void *data, int silent)
2296 {
2297         int nBlocks;
2298         struct inode *inode = NULL;
2299         struct dentry *root;
2300         yaffs_Device *dev = 0;
2301         char devname_buf[BDEVNAME_SIZE + 1];
2302         struct mtd_info *mtd;
2303         int err;
2304         char *data_str = (char *)data;
2305         struct yaffs_LinuxContext *context = NULL;
2306         yaffs_DeviceParam *param;
2307
2308         yaffs_options options;
2309
2310         sb->s_magic = YAFFS_MAGIC;
2311         sb->s_op = &yaffs_super_ops;
2312         sb->s_flags |= MS_NOATIME;
2313
2314 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,9))
2315         sb->s_export_op = &yaffs_export_ops;
2316 #endif
2317
2318         if (!sb)
2319                 printk(KERN_INFO "yaffs: sb is NULL\n");
2320         else if (!sb->s_dev)
2321                 printk(KERN_INFO "yaffs: sb->s_dev is NULL\n");
2322         else if (!yaffs_devname(sb, devname_buf))
2323                 printk(KERN_INFO "yaffs: devname is NULL\n");
2324         else
2325                 printk(KERN_INFO "yaffs: dev is %d name is \"%s\"\n",
2326                        sb->s_dev,
2327                        yaffs_devname(sb, devname_buf));
2328
2329         if (!data_str)
2330                 data_str = "";
2331
2332         printk(KERN_INFO "yaffs: passed flags \"%s\"\n", data_str);
2333
2334         memset(&options, 0, sizeof(options));
2335
2336         if (yaffs_parse_options(&options, data_str)) {
2337                 /* Option parsing failed */
2338                 return NULL;
2339         }
2340
2341
2342         sb->s_blocksize = PAGE_CACHE_SIZE;
2343         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
2344         T(YAFFS_TRACE_OS, ("yaffs_read_super: Using yaffs%d\n", yaffsVersion));
2345         T(YAFFS_TRACE_OS,
2346           ("yaffs_read_super: block size %d\n", (int)(sb->s_blocksize)));
2347
2348 #ifdef CONFIG_YAFFS_DISABLE_WRITE_VERIFY
2349         T(YAFFS_TRACE_OS,
2350           ("yaffs: Write verification disabled. All guarantees "
2351            "null and void\n"));
2352 #endif
2353
2354         T(YAFFS_TRACE_ALWAYS, ("yaffs: Attempting MTD mount on %u.%u, "
2355                                "\"%s\"\n",
2356                                MAJOR(sb->s_dev), MINOR(sb->s_dev),
2357                                yaffs_devname(sb, devname_buf)));
2358
2359         /* Check it's an mtd device..... */
2360         if (MAJOR(sb->s_dev) != MTD_BLOCK_MAJOR)
2361                 return NULL;    /* This isn't an mtd device */
2362
2363         /* Get the device */
2364         mtd = get_mtd_device(NULL, MINOR(sb->s_dev));
2365         if (!mtd) {
2366                 T(YAFFS_TRACE_ALWAYS,
2367                   ("yaffs: MTD device #%u doesn't appear to exist\n",
2368                    MINOR(sb->s_dev)));
2369                 return NULL;
2370         }
2371         /* Check it's NAND */
2372         if (mtd->type != MTD_NANDFLASH) {
2373                 T(YAFFS_TRACE_ALWAYS,
2374                   ("yaffs: MTD device is not NAND it's type %d\n", mtd->type));
2375                 return NULL;
2376         }
2377
2378         T(YAFFS_TRACE_OS, (" erase %p\n", mtd->erase));
2379         T(YAFFS_TRACE_OS, (" read %p\n", mtd->read));
2380         T(YAFFS_TRACE_OS, (" write %p\n", mtd->write));
2381         T(YAFFS_TRACE_OS, (" readoob %p\n", mtd->read_oob));
2382         T(YAFFS_TRACE_OS, (" writeoob %p\n", mtd->write_oob));
2383         T(YAFFS_TRACE_OS, (" block_isbad %p\n", mtd->block_isbad));
2384         T(YAFFS_TRACE_OS, (" block_markbad %p\n", mtd->block_markbad));
2385         T(YAFFS_TRACE_OS, (" %s %d\n", WRITE_SIZE_STR, WRITE_SIZE(mtd)));
2386         T(YAFFS_TRACE_OS, (" oobsize %d\n", mtd->oobsize));
2387         T(YAFFS_TRACE_OS, (" erasesize %d\n", mtd->erasesize));
2388 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 29)
2389         T(YAFFS_TRACE_OS, (" size %u\n", mtd->size));
2390 #else
2391         T(YAFFS_TRACE_OS, (" size %lld\n", mtd->size));
2392 #endif
2393
2394 #ifdef CONFIG_YAFFS_AUTO_YAFFS2
2395
2396         if (yaffsVersion == 1 && WRITE_SIZE(mtd) >= 2048) {
2397                 T(YAFFS_TRACE_ALWAYS, ("yaffs: auto selecting yaffs2\n"));
2398                 yaffsVersion = 2;
2399         }
2400
2401         /* Added NCB 26/5/2006 for completeness */
2402         if (yaffsVersion == 2 && !options.inband_tags && WRITE_SIZE(mtd) == 512) {
2403                 T(YAFFS_TRACE_ALWAYS, ("yaffs: auto selecting yaffs1\n"));
2404                 yaffsVersion = 1;
2405         }
2406
2407 #endif
2408
2409         if (yaffsVersion == 2) {
2410                 /* Check for version 2 style functions */
2411                 if (!mtd->erase ||
2412                     !mtd->block_isbad ||
2413                     !mtd->block_markbad ||
2414                     !mtd->read ||
2415                     !mtd->write ||
2416 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2417                     !mtd->read_oob || !mtd->write_oob) {
2418 #else
2419                     !mtd->write_ecc ||
2420                     !mtd->read_ecc || !mtd->read_oob || !mtd->write_oob) {
2421 #endif
2422                         T(YAFFS_TRACE_ALWAYS,
2423                           ("yaffs: MTD device does not support required "
2424                            "functions\n"));;
2425                         return NULL;
2426                 }
2427
2428                 if ((WRITE_SIZE(mtd) < YAFFS_MIN_YAFFS2_CHUNK_SIZE ||
2429                     mtd->oobsize < YAFFS_MIN_YAFFS2_SPARE_SIZE) &&
2430                     !options.inband_tags) {
2431                         T(YAFFS_TRACE_ALWAYS,
2432                           ("yaffs: MTD device does not have the "
2433                            "right page sizes\n"));
2434                         return NULL;
2435                 }
2436         } else {
2437                 /* Check for V1 style functions */
2438                 if (!mtd->erase ||
2439                     !mtd->read ||
2440                     !mtd->write ||
2441 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2442                     !mtd->read_oob || !mtd->write_oob) {
2443 #else
2444                     !mtd->write_ecc ||
2445                     !mtd->read_ecc || !mtd->read_oob || !mtd->write_oob) {
2446 #endif
2447                         T(YAFFS_TRACE_ALWAYS,
2448                           ("yaffs: MTD device does not support required "
2449                            "functions\n"));;
2450                         return NULL;
2451                 }
2452
2453                 if (WRITE_SIZE(mtd) < YAFFS_BYTES_PER_CHUNK ||
2454                     mtd->oobsize != YAFFS_BYTES_PER_SPARE) {
2455                         T(YAFFS_TRACE_ALWAYS,
2456                           ("yaffs: MTD device does not support have the "
2457                            "right page sizes\n"));
2458                         return NULL;
2459                 }
2460         }
2461
2462         /* OK, so if we got here, we have an MTD that's NAND and looks
2463          * like it has the right capabilities
2464          * Set the yaffs_Device up for mtd
2465          */
2466
2467         dev = kmalloc(sizeof(yaffs_Device), GFP_KERNEL);
2468         context = kmalloc(sizeof(struct yaffs_LinuxContext),GFP_KERNEL);
2469         
2470         if(!dev || !context ){
2471                 if(dev)
2472                         kfree(dev);
2473                 if(context)
2474                         kfree(context);
2475                 dev = NULL;
2476                 context = NULL;
2477         }
2478
2479         if (!dev) {
2480                 /* Deep shit could not allocate device structure */
2481                 T(YAFFS_TRACE_ALWAYS,
2482                   ("yaffs_read_super: Failed trying to allocate "
2483                    "yaffs_Device. \n"));
2484                 return NULL;
2485         }
2486         memset(dev, 0, sizeof(yaffs_Device));
2487         param = &(dev->param);
2488
2489         memset(context,0,sizeof(struct yaffs_LinuxContext));
2490         dev->context = context;
2491         YINIT_LIST_HEAD(&(context->contextList));
2492         context->dev = dev;
2493         context->superBlock = sb;
2494
2495         
2496
2497 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2498         sb->s_fs_info = dev;
2499 #else
2500         sb->u.generic_sbp = dev;
2501 #endif
2502         
2503         yaffs_DeviceToContext(dev)->mtd = mtd;
2504         param->name = mtd->name;
2505
2506         /* Set up the memory size parameters.... */
2507
2508         nBlocks = YCALCBLOCKS(mtd->size, (YAFFS_CHUNKS_PER_BLOCK * YAFFS_BYTES_PER_CHUNK));
2509
2510         param->startBlock = 0;
2511         param->endBlock = nBlocks - 1;
2512         param->nChunksPerBlock = YAFFS_CHUNKS_PER_BLOCK;
2513         param->totalBytesPerChunk = YAFFS_BYTES_PER_CHUNK;
2514         param->nReservedBlocks = 5;
2515         param->nShortOpCaches = (options.no_cache) ? 0 : 10;
2516         param->inbandTags = options.inband_tags;
2517
2518 #ifdef CONFIG_YAFFS_DISABLE_LAZY_LOAD
2519         param->disableLazyLoad = 1;
2520 #endif
2521         if(options.lazy_loading_overridden)
2522                 param->disableLazyLoad = !options.lazy_loading_enabled;
2523
2524 #ifdef CONFIG_YAFFS_DISABLE_TAGS_ECC
2525         param->noTagsECC = 1;
2526 #endif
2527
2528 #ifdef CONFIG_YAFFS_DISABLE_BACKGROUND
2529 #else
2530         param->deferDirectoryUpdate = 1;
2531 #endif
2532
2533         if(options.tags_ecc_overridden)
2534                 param->noTagsECC = !options.tags_ecc_on;
2535
2536 #ifdef CONFIG_YAFFS_EMPTY_LOST_AND_FOUND
2537         param->emptyLostAndFound = 1;
2538 #endif
2539
2540 #ifdef CONFIG_YAFFS_DISABLE_BLOCK_REFRESHING
2541         param->refreshPeriod = 0;
2542 #else
2543         param->refreshPeriod = 10000;
2544 #endif
2545
2546         if(options.empty_lost_and_found_overridden)
2547                 param->emptyLostAndFound = options.empty_lost_and_found;
2548
2549         /* ... and the functions. */
2550         if (yaffsVersion == 2) {
2551                 param->writeChunkWithTagsToNAND =
2552                     nandmtd2_WriteChunkWithTagsToNAND;
2553                 param->readChunkWithTagsFromNAND =
2554                     nandmtd2_ReadChunkWithTagsFromNAND;
2555                 param->markNANDBlockBad = nandmtd2_MarkNANDBlockBad;
2556                 param->queryNANDBlock = nandmtd2_QueryNANDBlock;
2557                 yaffs_DeviceToContext(dev)->spareBuffer = YMALLOC(mtd->oobsize);
2558                 param->isYaffs2 = 1;
2559 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2560                 param->totalBytesPerChunk = mtd->writesize;
2561                 param->nChunksPerBlock = mtd->erasesize / mtd->writesize;
2562 #else
2563                 param->totalBytesPerChunk = mtd->oobblock;
2564                 param->nChunksPerBlock = mtd->erasesize / mtd->oobblock;
2565 #endif
2566                 nBlocks = YCALCBLOCKS(mtd->size, mtd->erasesize);
2567
2568                 param->startBlock = 0;
2569                 param->endBlock = nBlocks - 1;
2570         } else {
2571 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2572                 /* use the MTD interface in yaffs_mtdif1.c */
2573                 param->writeChunkWithTagsToNAND =
2574                         nandmtd1_WriteChunkWithTagsToNAND;
2575                 param->readChunkWithTagsFromNAND =
2576                         nandmtd1_ReadChunkWithTagsFromNAND;
2577                 param->markNANDBlockBad = nandmtd1_MarkNANDBlockBad;
2578                 param->queryNANDBlock = nandmtd1_QueryNANDBlock;
2579 #else
2580                 param->writeChunkToNAND = nandmtd_WriteChunkToNAND;
2581                 param->readChunkFromNAND = nandmtd_ReadChunkFromNAND;
2582 #endif
2583                 param->isYaffs2 = 0;
2584         }
2585         /* ... and common functions */
2586         param->eraseBlockInNAND = nandmtd_EraseBlockInNAND;
2587         param->initialiseNAND = nandmtd_InitialiseNAND;
2588
2589         yaffs_DeviceToContext(dev)->putSuperFunc = yaffs_MTDPutSuper;
2590
2591         param->markSuperBlockDirty = yaffs_MarkSuperBlockDirty;
2592         param->gcControl = yaffs_gc_control_callback;
2593
2594         yaffs_DeviceToContext(dev)->superBlock= sb;
2595         
2596
2597 #ifndef CONFIG_YAFFS_DOES_ECC
2598         param->useNANDECC = 1;
2599 #endif
2600
2601 #ifdef CONFIG_YAFFS_DISABLE_WIDE_TNODES
2602         param->wideTnodesDisabled = 1;
2603 #endif
2604
2605         param->skipCheckpointRead = options.skip_checkpoint_read;
2606         param->skipCheckpointWrite = options.skip_checkpoint_write;
2607
2608         /* we assume this is protected by lock_kernel() in mount/umount */
2609         down(&yaffs_context_lock);
2610         ylist_add_tail(&(yaffs_DeviceToContext(dev)->contextList), &yaffs_context_list);
2611         up(&yaffs_context_lock);
2612
2613         /* Directory search handling...*/
2614         YINIT_LIST_HEAD(&(yaffs_DeviceToContext(dev)->searchContexts));
2615         param->removeObjectCallback = yaffs_RemoveObjectCallback;
2616
2617         init_MUTEX(&(yaffs_DeviceToContext(dev)->grossLock));
2618
2619         yaffs_GrossLock(dev);
2620
2621         err = yaffs_GutsInitialise(dev);
2622
2623         T(YAFFS_TRACE_OS,
2624           ("yaffs_read_super: guts initialised %s\n",
2625            (err == YAFFS_OK) ? "OK" : "FAILED"));
2626            
2627         if(err == YAFFS_OK)
2628                 yaffs_BackgroundStart(dev);
2629                 
2630         if(!context->bgThread)
2631                 param->deferDirectoryUpdate = 0;
2632
2633
2634         /* Release lock before yaffs_get_inode() */
2635         yaffs_GrossUnlock(dev);
2636
2637         /* Create root inode */
2638         if (err == YAFFS_OK)
2639                 inode = yaffs_get_inode(sb, S_IFDIR | 0755, 0,
2640                                         yaffs_Root(dev));
2641
2642         if (!inode)
2643                 return NULL;
2644
2645         inode->i_op = &yaffs_dir_inode_operations;
2646         inode->i_fop = &yaffs_dir_operations;
2647
2648         T(YAFFS_TRACE_OS, ("yaffs_read_super: got root inode\n"));
2649
2650         root = d_alloc_root(inode);
2651
2652         T(YAFFS_TRACE_OS, ("yaffs_read_super: d_alloc_root done\n"));
2653
2654         if (!root) {
2655                 iput(inode);
2656                 return NULL;
2657         }
2658         sb->s_root = root;
2659         sb->s_dirt = !dev->isCheckpointed;
2660         T(YAFFS_TRACE_ALWAYS,
2661           ("yaffs_read_super: isCheckpointed %d\n", dev->isCheckpointed));
2662
2663         T(YAFFS_TRACE_OS, ("yaffs_read_super: done\n"));
2664         return sb;
2665 }
2666
2667
2668 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2669 static int yaffs_internal_read_super_mtd(struct super_block *sb, void *data,
2670                                          int silent)
2671 {
2672         return yaffs_internal_read_super(1, sb, data, silent) ? 0 : -EINVAL;
2673 }
2674
2675 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2676 static int yaffs_read_super(struct file_system_type *fs,
2677                             int flags, const char *dev_name,
2678                             void *data, struct vfsmount *mnt)
2679 {
2680
2681         return get_sb_bdev(fs, flags, dev_name, data,
2682                            yaffs_internal_read_super_mtd, mnt);
2683 }
2684 #else
2685 static struct super_block *yaffs_read_super(struct file_system_type *fs,
2686                                             int flags, const char *dev_name,
2687                                             void *data)
2688 {
2689
2690         return get_sb_bdev(fs, flags, dev_name, data,
2691                            yaffs_internal_read_super_mtd);
2692 }
2693 #endif
2694
2695 static struct file_system_type yaffs_fs_type = {
2696         .owner = THIS_MODULE,
2697         .name = "yaffs",
2698         .get_sb = yaffs_read_super,
2699         .kill_sb = kill_block_super,
2700         .fs_flags = FS_REQUIRES_DEV,
2701 };
2702 #else
2703 static struct super_block *yaffs_read_super(struct super_block *sb, void *data,
2704                                             int silent)
2705 {
2706         return yaffs_internal_read_super(1, sb, data, silent);
2707 }
2708
2709 static DECLARE_FSTYPE(yaffs_fs_type, "yaffs", yaffs_read_super,
2710                       FS_REQUIRES_DEV);
2711 #endif
2712
2713
2714 #ifdef CONFIG_YAFFS_YAFFS2
2715
2716 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 5, 0))
2717 static int yaffs2_internal_read_super_mtd(struct super_block *sb, void *data,
2718                                           int silent)
2719 {
2720         return yaffs_internal_read_super(2, sb, data, silent) ? 0 : -EINVAL;
2721 }
2722
2723 #if (LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 17))
2724 static int yaffs2_read_super(struct file_system_type *fs,
2725                         int flags, const char *dev_name, void *data,
2726                         struct vfsmount *mnt)
2727 {
2728         return get_sb_bdev(fs, flags, dev_name, data,
2729                         yaffs2_internal_read_super_mtd, mnt);
2730 }
2731 #else
2732 static struct super_block *yaffs2_read_super(struct file_system_type *fs,
2733                                              int flags, const char *dev_name,
2734                                              void *data)
2735 {
2736
2737         return get_sb_bdev(fs, flags, dev_name, data,
2738                            yaffs2_internal_read_super_mtd);
2739 }
2740 #endif
2741
2742 static struct file_system_type yaffs2_fs_type = {
2743         .owner = THIS_MODULE,
2744         .name = "yaffs2",
2745         .get_sb = yaffs2_read_super,
2746         .kill_sb = kill_block_super,
2747         .fs_flags = FS_REQUIRES_DEV,
2748 };
2749 #else
2750 static struct super_block *yaffs2_read_super(struct super_block *sb,
2751                                              void *data, int silent)
2752 {
2753         return yaffs_internal_read_super(2, sb, data, silent);
2754 }
2755
2756 static DECLARE_FSTYPE(yaffs2_fs_type, "yaffs2", yaffs2_read_super,
2757                       FS_REQUIRES_DEV);
2758 #endif
2759
2760 #endif                          /* CONFIG_YAFFS_YAFFS2 */
2761
2762 static struct proc_dir_entry *my_proc_entry;
2763 static struct proc_dir_entry *debug_proc_entry;
2764
2765 static char *yaffs_dump_dev_part0(char *buf, yaffs_Device * dev)
2766 {
2767         buf += sprintf(buf, "startBlock......... %d\n", dev->param.startBlock);
2768         buf += sprintf(buf, "endBlock........... %d\n", dev->param.endBlock);
2769         buf += sprintf(buf, "totalBytesPerChunk. %d\n", dev->param.totalBytesPerChunk);
2770         buf += sprintf(buf, "useNANDECC......... %d\n", dev->param.useNANDECC);
2771         buf += sprintf(buf, "noTagsECC.......... %d\n", dev->param.noTagsECC);
2772         buf += sprintf(buf, "isYaffs2........... %d\n", dev->param.isYaffs2);
2773         buf += sprintf(buf, "inbandTags......... %d\n", dev->param.inbandTags);
2774         buf += sprintf(buf, "emptyLostAndFound.. %d\n", dev->param.emptyLostAndFound);
2775         buf += sprintf(buf, "disableLazyLoad.... %d\n", dev->param.disableLazyLoad);
2776         buf += sprintf(buf, "refreshPeriod...... %d\n", dev->param.refreshPeriod);
2777         buf += sprintf(buf, "nShortOpCaches..... %d\n", dev->param.nShortOpCaches);
2778         buf += sprintf(buf, "nReservedBlocks.... %d\n", dev->param.nReservedBlocks);
2779
2780         buf += sprintf(buf, "\n");
2781
2782         return buf;
2783 }
2784
2785
2786 static char *yaffs_dump_dev_part1(char *buf, yaffs_Device * dev)
2787 {
2788         buf += sprintf(buf, "nDataBytesPerChunk. %d\n", dev->nDataBytesPerChunk);
2789         buf += sprintf(buf, "chunkGroupBits..... %d\n", dev->chunkGroupBits);
2790         buf += sprintf(buf, "chunkGroupSize..... %d\n", dev->chunkGroupSize);
2791         buf += sprintf(buf, "nErasedBlocks...... %d\n", dev->nErasedBlocks);
2792         buf += sprintf(buf, "blocksInCheckpoint. %d\n", dev->blocksInCheckpoint);
2793         buf += sprintf(buf, "\n");
2794         buf += sprintf(buf, "nTnodesCreated..... %d\n", dev->nTnodesCreated);
2795         buf += sprintf(buf, "nFreeTnodes........ %d\n", dev->nFreeTnodes);
2796         buf += sprintf(buf, "nObjectsCreated.... %d\n", dev->nObjectsCreated);
2797         buf += sprintf(buf, "nFreeObjects....... %d\n", dev->nFreeObjects);
2798         buf += sprintf(buf, "nFreeChunks........ %d\n", dev->nFreeChunks);
2799         buf += sprintf(buf, "\n");
2800         buf += sprintf(buf, "nPageWrites........ %u\n", dev->nPageWrites);
2801         buf += sprintf(buf, "nPageReads......... %u\n", dev->nPageReads);
2802         buf += sprintf(buf, "nBlockErasures..... %u\n", dev->nBlockErasures);
2803         buf += sprintf(buf, "nGCCopies.......... %u\n", dev->nGCCopies);
2804         buf += sprintf(buf, "garbageCollections. %u\n", dev->garbageCollections);
2805         buf += sprintf(buf, "passiveGCs......... %u\n", dev->passiveGarbageCollections);
2806         buf += sprintf(buf, "nRetriedWrites..... %u\n", dev->nRetriedWrites);
2807         buf += sprintf(buf, "nRetireBlocks...... %u\n", dev->nRetiredBlocks);
2808         buf += sprintf(buf, "eccFixed........... %u\n", dev->eccFixed);
2809         buf += sprintf(buf, "eccUnfixed......... %u\n", dev->eccUnfixed);
2810         buf += sprintf(buf, "tagsEccFixed....... %u\n", dev->tagsEccFixed);
2811         buf += sprintf(buf, "tagsEccUnfixed..... %u\n", dev->tagsEccUnfixed);
2812         buf += sprintf(buf, "cacheHits.......... %u\n", dev->cacheHits);
2813         buf += sprintf(buf, "nDeletedFiles...... %u\n", dev->nDeletedFiles);
2814         buf += sprintf(buf, "nUnlinkedFiles..... %u\n", dev->nUnlinkedFiles);
2815         buf += sprintf(buf, "refreshCount....... %u\n", dev->refreshCount);
2816         buf +=
2817             sprintf(buf, "nBackgroudDeletions %u\n", dev->nBackgroundDeletions);
2818
2819         return buf;
2820 }
2821
2822 static int yaffs_proc_read(char *page,
2823                            char **start,
2824                            off_t offset, int count, int *eof, void *data)
2825 {
2826         struct ylist_head *item;
2827         char *buf = page;
2828         int step = offset;
2829         int n = 0;
2830
2831         /* Get proc_file_read() to step 'offset' by one on each sucessive call.
2832          * We use 'offset' (*ppos) to indicate where we are in devList.
2833          * This also assumes the user has posted a read buffer large
2834          * enough to hold the complete output; but that's life in /proc.
2835          */
2836
2837         *(int *)start = 1;
2838
2839         /* Print header first */
2840         if (step == 0)
2841                 buf += sprintf(buf, "YAFFS built:" __DATE__ " " __TIME__
2842                                "\n%s\n%s\n", yaffs_fs_c_version,
2843                                yaffs_guts_c_version);
2844         else if (step == 1)
2845                 buf += sprintf(buf,"\n");
2846         else {
2847                 step-=2;
2848                 
2849                 down(&yaffs_context_lock);
2850
2851                 /* Locate and print the Nth entry.  Order N-squared but N is small. */
2852                 ylist_for_each(item, &yaffs_context_list) {
2853                         struct yaffs_LinuxContext *dc = ylist_entry(item, struct yaffs_LinuxContext, contextList);
2854                         yaffs_Device *dev = dc->dev;
2855
2856                         if (n < (step & ~1)) {
2857                                 n+=2;
2858                                 continue;
2859                         }
2860                         if((step & 1)==0){
2861                                 buf += sprintf(buf, "\nDevice %d \"%s\"\n", n, dev->param.name);
2862                                 buf = yaffs_dump_dev_part0(buf, dev);
2863                         } else
2864                                 buf = yaffs_dump_dev_part1(buf, dev);
2865                         
2866                         break;
2867                 }
2868                 up(&yaffs_context_lock);
2869         }
2870
2871         return buf - page < count ? buf - page : count;
2872 }
2873
2874 static int yaffs_debug_proc_read(char *page,
2875                                 char **start,
2876                                 off_t offset, int count, int *eof, void *data)
2877 {
2878         struct ylist_head *item;
2879         char *buf = page;
2880         int n = 0;
2881
2882         down(&yaffs_context_lock);
2883
2884         /* Locate and print the Nth entry.  Order N-squared but N is small. */
2885         ylist_for_each(item, &yaffs_context_list) {
2886                 struct yaffs_LinuxContext *dc = ylist_entry(item, struct yaffs_LinuxContext, contextList);
2887                 yaffs_Device *dev = dc->dev;
2888
2889                 int erasedChunks;
2890                 int nObjects;
2891                 int nTnodes;
2892
2893                 erasedChunks = dev->nErasedBlocks * dev->param.nChunksPerBlock;
2894                 nObjects = dev->nObjectsCreated -dev->nFreeObjects;
2895                 nTnodes = dev->nTnodesCreated - dev->nFreeTnodes;
2896                 
2897                 
2898                 buf += sprintf(buf,"%d, %d, %d, %d, %d\n", 
2899                                 n, dev->nFreeChunks, erasedChunks,
2900                                 nObjects, nTnodes);
2901         }
2902         up(&yaffs_context_lock);
2903
2904
2905         return buf - page < count ? buf - page : count;
2906 }
2907
2908 /**
2909  * Set the verbosity of the warnings and error messages.
2910  *
2911  * Note that the names can only be a..z or _ with the current code.
2912  */
2913
2914 static struct {
2915         char *mask_name;
2916         unsigned mask_bitfield;
2917 } mask_flags[] = {
2918         {"allocate", YAFFS_TRACE_ALLOCATE},
2919         {"always", YAFFS_TRACE_ALWAYS},
2920         {"bad_blocks", YAFFS_TRACE_BAD_BLOCKS},
2921         {"buffers", YAFFS_TRACE_BUFFERS},
2922         {"bug", YAFFS_TRACE_BUG},
2923         {"checkpt", YAFFS_TRACE_CHECKPOINT},
2924         {"deletion", YAFFS_TRACE_DELETION},
2925         {"erase", YAFFS_TRACE_ERASE},
2926         {"error", YAFFS_TRACE_ERROR},
2927         {"gc_detail", YAFFS_TRACE_GC_DETAIL},
2928         {"gc", YAFFS_TRACE_GC},
2929         {"mtd", YAFFS_TRACE_MTD},
2930         {"nandaccess", YAFFS_TRACE_NANDACCESS},
2931         {"os", YAFFS_TRACE_OS},
2932         {"scan_debug", YAFFS_TRACE_SCAN_DEBUG},
2933         {"scan", YAFFS_TRACE_SCAN},
2934         {"tracing", YAFFS_TRACE_TRACING},
2935         {"sync", YAFFS_TRACE_SYNC},
2936
2937         {"background", YAFFS_TRACE_BACKGROUND},
2938
2939         {"verify", YAFFS_TRACE_VERIFY},
2940         {"verify_nand", YAFFS_TRACE_VERIFY_NAND},
2941         {"verify_full", YAFFS_TRACE_VERIFY_FULL},
2942         {"verify_all", YAFFS_TRACE_VERIFY_ALL},
2943
2944         {"write", YAFFS_TRACE_WRITE},
2945         {"all", 0xffffffff},
2946         {"none", 0},
2947         {NULL, 0},
2948 };
2949
2950 #define MAX_MASK_NAME_LENGTH 40
2951 static int yaffs_proc_write_trace_options(struct file *file, const char *buf,
2952                                          unsigned long count, void *data)
2953 {
2954         unsigned rg = 0, mask_bitfield;
2955         char *end;
2956         char *mask_name;
2957         const char *x;
2958         char substring[MAX_MASK_NAME_LENGTH + 1];
2959         int i;
2960         int done = 0;
2961         int add, len = 0;
2962         int pos = 0;
2963
2964         rg = yaffs_traceMask;
2965
2966         while (!done && (pos < count)) {
2967                 done = 1;
2968                 while ((pos < count) && isspace(buf[pos]))
2969                         pos++;
2970
2971                 switch (buf[pos]) {
2972                 case '+':
2973                 case '-':
2974                 case '=':
2975                         add = buf[pos];
2976                         pos++;
2977                         break;
2978
2979                 default:
2980                         add = ' ';
2981                         break;
2982                 }
2983                 mask_name = NULL;
2984
2985                 mask_bitfield = simple_strtoul(buf + pos, &end, 0);
2986
2987                 if (end > buf + pos) {
2988                         mask_name = "numeral";
2989                         len = end - (buf + pos);
2990                         pos += len;
2991                         done = 0;
2992                 } else {
2993                         for (x = buf + pos, i = 0;
2994                             (*x == '_' || (*x >= 'a' && *x <= 'z')) &&
2995                             i < MAX_MASK_NAME_LENGTH; x++, i++, pos++)
2996                                 substring[i] = *x;
2997                         substring[i] = '\0';
2998
2999                         for (i = 0; mask_flags[i].mask_name != NULL; i++) {
3000                                 if (strcmp(substring, mask_flags[i].mask_name) == 0) {
3001                                         mask_name = mask_flags[i].mask_name;
3002                                         mask_bitfield = mask_flags[i].mask_bitfield;
3003                                         done = 0;
3004                                         break;
3005                                 }
3006                         }
3007                 }
3008
3009                 if (mask_name != NULL) {
3010                         done = 0;
3011                         switch (add) {
3012                         case '-':
3013                                 rg &= ~mask_bitfield;
3014                                 break;
3015                         case '+':
3016                                 rg |= mask_bitfield;
3017                                 break;
3018                         case '=':
3019                                 rg = mask_bitfield;
3020                                 break;
3021                         default:
3022                                 rg |= mask_bitfield;
3023                                 break;
3024                         }
3025                 }
3026         }
3027
3028         yaffs_traceMask = rg | YAFFS_TRACE_ALWAYS;
3029
3030         printk(KERN_DEBUG "new trace = 0x%08X\n", yaffs_traceMask);
3031
3032         if (rg & YAFFS_TRACE_ALWAYS) {
3033                 for (i = 0; mask_flags[i].mask_name != NULL; i++) {
3034                         char flag;
3035                         flag = ((rg & mask_flags[i].mask_bitfield) == mask_flags[i].mask_bitfield) ? '+' : '-';
3036                         printk(KERN_DEBUG "%c%s\n", flag, mask_flags[i].mask_name);
3037                 }
3038         }
3039
3040         return count;
3041 }
3042
3043
3044 static int yaffs_proc_write(struct file *file, const char *buf,
3045                                          unsigned long count, void *data)
3046 {
3047         return yaffs_proc_write_trace_options(file, buf, count, data);
3048 }
3049
3050 /* Stuff to handle installation of file systems */
3051 struct file_system_to_install {
3052         struct file_system_type *fst;
3053         int installed;
3054 };
3055
3056 static struct file_system_to_install fs_to_install[] = {
3057         {&yaffs_fs_type, 0},
3058         {&yaffs2_fs_type, 0},
3059         {NULL, 0}
3060 };
3061
3062 static int __init init_yaffs_fs(void)
3063 {
3064         int error = 0;
3065         struct file_system_to_install *fsinst;
3066
3067         T(YAFFS_TRACE_ALWAYS,
3068           ("yaffs " __DATE__ " " __TIME__ " Installing. \n"));
3069
3070         init_MUTEX(&yaffs_context_lock);
3071
3072         /* Install the proc_fs entries */
3073         my_proc_entry = create_proc_entry("yaffs",
3074                                                S_IRUGO | S_IFREG,
3075                                                YPROC_ROOT);
3076
3077         if (my_proc_entry) {
3078                 my_proc_entry->write_proc = yaffs_proc_write;
3079                 my_proc_entry->read_proc = yaffs_proc_read;
3080                 my_proc_entry->data = NULL;
3081         } else
3082                 return -ENOMEM;
3083
3084         debug_proc_entry = create_proc_entry("yaffs_debug",
3085                                                S_IRUGO | S_IFREG,
3086                                                YPROC_ROOT);
3087
3088         if (debug_proc_entry) {
3089                 debug_proc_entry->write_proc = NULL;
3090                 debug_proc_entry->read_proc = yaffs_debug_proc_read;
3091                 debug_proc_entry->data = NULL;
3092         } else
3093                 return -ENOMEM;
3094
3095         /* Now add the file system entries */
3096
3097         fsinst = fs_to_install;
3098
3099         while (fsinst->fst && !error) {
3100                 error = register_filesystem(fsinst->fst);
3101                 if (!error)
3102                         fsinst->installed = 1;
3103                 fsinst++;
3104         }
3105
3106         /* Any errors? uninstall  */
3107         if (error) {
3108                 fsinst = fs_to_install;
3109
3110                 while (fsinst->fst) {
3111                         if (fsinst->installed) {
3112                                 unregister_filesystem(fsinst->fst);
3113                                 fsinst->installed = 0;
3114                         }
3115                         fsinst++;
3116                 }
3117         }
3118
3119         return error;
3120 }
3121
3122 static void __exit exit_yaffs_fs(void)
3123 {
3124
3125         struct file_system_to_install *fsinst;
3126
3127         T(YAFFS_TRACE_ALWAYS, ("yaffs " __DATE__ " " __TIME__
3128                                " removing. \n"));
3129
3130         remove_proc_entry("yaffs", YPROC_ROOT);
3131
3132         fsinst = fs_to_install;
3133
3134         while (fsinst->fst) {
3135                 if (fsinst->installed) {
3136                         unregister_filesystem(fsinst->fst);
3137                         fsinst->installed = 0;
3138                 }
3139                 fsinst++;
3140         }
3141 }
3142
3143 module_init(init_yaffs_fs)
3144 module_exit(exit_yaffs_fs)
3145
3146 MODULE_DESCRIPTION("YAFFS2 - a NAND specific flash file system");
3147 MODULE_AUTHOR("Charles Manning, Aleph One Ltd., 2002-2006");
3148 MODULE_LICENSE("GPL");