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