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