Fix vfs calls to yaffs_flush_file
[yaffs2.git] / yaffs_vfs_single.c
1 /*
2  * YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
3  *
4  * Copyright (C) 2002-2011 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 struct yaffs_dev associated with
28  *         this superblock
29  * >> 2.6: sb->s_fs_info  points to the struct yaffs_dev associated with this
30  *         superblock
31  * >> inode->u.generic_ip points to the associated struct yaffs_obj.
32  */
33
34 /*
35  * NB There are two variants of Linux VFS glue code. This variant supports
36  * a single version and should not include any multi-version code.
37  */
38 #include <linux/version.h>
39 #include <linux/kernel.h>
40 #include <linux/module.h>
41 #include <linux/slab.h>
42 #include <linux/init.h>
43 #include <linux/fs.h>
44 #include <linux/proc_fs.h>
45 #include <linux/pagemap.h>
46 #include <linux/mtd/mtd.h>
47 #include <linux/interrupt.h>
48 #include <linux/string.h>
49 #include <linux/ctype.h>
50 #include <linux/namei.h>
51 #include <linux/exportfs.h>
52 #include <linux/kthread.h>
53 #include <linux/delay.h>
54 #include <linux/freezer.h>
55 #include <asm/div64.h>
56 #include <linux/statfs.h>
57 #include <linux/uaccess.h>
58 #include <linux/mtd/mtd.h>
59
60 #include "yportenv.h"
61 #include "yaffs_trace.h"
62 #include "yaffs_guts.h"
63 #include "yaffs_attribs.h"
64 #include "yaffs_linux.h"
65 #include "yaffs_mtdif.h"
66 #include "yaffs_mtdif1.h"
67 #include "yaffs_mtdif2.h"
68
69 unsigned int yaffs_trace_mask = YAFFS_TRACE_BAD_BLOCKS | YAFFS_TRACE_ALWAYS;
70 unsigned int yaffs_wr_attempts = YAFFS_WR_ATTEMPTS;
71 unsigned int yaffs_auto_checkpoint = 1;
72 unsigned int yaffs_gc_control = 1;
73 unsigned int yaffs_bg_enable = 1;
74 unsigned int yaffs_auto_select = 1;
75
76 /* Module Parameters */
77 module_param(yaffs_trace_mask, uint, 0644);
78 module_param(yaffs_wr_attempts, uint, 0644);
79 module_param(yaffs_auto_checkpoint, uint, 0644);
80 module_param(yaffs_gc_control, uint, 0644);
81 module_param(yaffs_bg_enable, uint, 0644);
82 module_param(yaffs_auto_select, uint, 0644);
83
84 #define yaffs_devname(sb, buf)  bdevname(sb->s_bdev, buf)
85
86 static uint32_t YCALCBLOCKS(uint64_t partition_size, uint32_t block_size)
87 {
88         uint64_t result = partition_size;
89
90         do_div(result, block_size);
91         return (uint32_t) result;
92 }
93
94 #define yaffs_inode_to_obj_lv(iptr) ((iptr)->i_private)
95 #define yaffs_inode_to_obj(iptr)\
96         ((struct yaffs_obj *)(yaffs_inode_to_obj_lv(iptr)))
97 #define yaffs_dentry_to_obj(dptr) yaffs_inode_to_obj((dptr)->d_inode)
98 #define yaffs_super_to_dev(sb)  ((struct yaffs_dev *)sb->s_fs_info)
99
100 #define update_dir_time(dir) do {\
101                         (dir)->i_ctime = (dir)->i_mtime = CURRENT_TIME; \
102                 } while (0)
103
104
105 static unsigned yaffs_gc_control_callback(struct yaffs_dev *dev)
106 {
107         return yaffs_gc_control;
108 }
109
110 static void yaffs_gross_lock(struct yaffs_dev *dev)
111 {
112         yaffs_trace(YAFFS_TRACE_LOCK, "yaffs locking %p", current);
113         mutex_lock(&(yaffs_dev_to_lc(dev)->gross_lock));
114         yaffs_trace(YAFFS_TRACE_LOCK, "yaffs locked %p", current);
115 }
116
117 static void yaffs_gross_unlock(struct yaffs_dev *dev)
118 {
119         yaffs_trace(YAFFS_TRACE_LOCK, "yaffs unlocking %p", current);
120         mutex_unlock(&(yaffs_dev_to_lc(dev)->gross_lock));
121 }
122
123 static void yaffs_fill_inode_from_obj(struct inode *inode,
124                                       struct yaffs_obj *obj);
125
126 static struct inode *yaffs_iget(struct super_block *sb, unsigned long ino)
127 {
128         struct inode *inode;
129         struct yaffs_obj *obj;
130         struct yaffs_dev *dev = yaffs_super_to_dev(sb);
131
132         yaffs_trace(YAFFS_TRACE_OS, "yaffs_iget for %lu", ino);
133
134         inode = iget_locked(sb, ino);
135         if (!inode)
136                 return ERR_PTR(-ENOMEM);
137         if (!(inode->i_state & I_NEW))
138                 return inode;
139
140         /* NB This is called as a side effect of other functions, but
141          * we had to release the lock to prevent deadlocks, so
142          * need to lock again.
143          */
144
145         yaffs_gross_lock(dev);
146
147         obj = yaffs_find_by_number(dev, inode->i_ino);
148         yaffs_fill_inode_from_obj(inode, obj);
149
150         yaffs_gross_unlock(dev);
151
152         unlock_new_inode(inode);
153         return inode;
154 }
155
156 struct inode *yaffs_get_inode(struct super_block *sb, int mode, int dev,
157                               struct yaffs_obj *obj)
158 {
159         struct inode *inode;
160
161         if (!sb) {
162                 yaffs_trace(YAFFS_TRACE_OS,
163                         "yaffs_get_inode for NULL super_block!!");
164                 return NULL;
165
166         }
167
168         if (!obj) {
169                 yaffs_trace(YAFFS_TRACE_OS,
170                         "yaffs_get_inode for NULL object!!");
171                 return NULL;
172
173         }
174
175         yaffs_trace(YAFFS_TRACE_OS,
176                 "yaffs_get_inode for object %d",
177                 obj->obj_id);
178
179         inode = yaffs_iget(sb, obj->obj_id);
180         if (IS_ERR(inode))
181                 return NULL;
182
183         /* NB Side effect: iget calls back to yaffs_read_inode(). */
184         /* iget also increments the inode's i_count */
185         /* NB You can't be holding gross_lock or deadlock will happen! */
186
187         return inode;
188 }
189
190 static int yaffs_mknod(struct inode *dir, struct dentry *dentry, int mode,
191                        dev_t rdev)
192 {
193         struct inode *inode;
194         struct yaffs_obj *obj = NULL;
195         struct yaffs_dev *dev;
196         struct yaffs_obj *parent = yaffs_inode_to_obj(dir);
197         int error;
198         uid_t uid = current->cred->fsuid;
199         gid_t gid =
200             (dir->i_mode & S_ISGID) ? dir->i_gid : current->cred->fsgid;
201
202         if ((dir->i_mode & S_ISGID) && S_ISDIR(mode))
203                 mode |= S_ISGID;
204
205         if (!parent) {
206                 yaffs_trace(YAFFS_TRACE_OS,
207                         "yaffs_mknod: could not get parent object");
208                 return -EPERM;
209         }
210
211         yaffs_trace(YAFFS_TRACE_OS,
212                         "yaffs_mknod: parent object %d type %d",
213                         parent->obj_id, parent->variant_type);
214
215         yaffs_trace(YAFFS_TRACE_OS,
216                 "yaffs_mknod: making oject for %s, mode %x dev %x",
217                 dentry->d_name.name, mode, rdev);
218
219         dev = parent->my_dev;
220
221         yaffs_gross_lock(dev);
222
223         if (yaffs_get_n_free_chunks(dev) < 1) {
224                 error = -ENOSPC;
225                 goto err_out;
226         }
227
228         switch (mode & S_IFMT) {
229         default:
230                 /* Special (socket, fifo, device...) */
231                 yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making special");
232                 obj =
233                     yaffs_create_special(parent, dentry->d_name.name, mode, uid,
234                                          gid, old_encode_dev(rdev));
235                 break;
236         case S_IFREG:           /* file          */
237                 yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making file");
238                 obj = yaffs_create_file(parent, dentry->d_name.name, mode, uid,
239                                         gid);
240                 break;
241         case S_IFDIR:           /* directory */
242                 yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making directory");
243                 obj = yaffs_create_dir(parent, dentry->d_name.name, mode,
244                                        uid, gid);
245                 break;
246         case S_IFLNK:           /* symlink */
247                 yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod: making symlink");
248                 obj = NULL;     /* Do we ever get here? */
249                 break;
250         }
251
252         if (!obj) {
253                 error = -ENOMEM;
254                 goto err_out;
255         }
256
257         /* Can not call yaffs_get_inode() with gross lock held */
258         yaffs_gross_unlock(dev);
259
260
261         inode = yaffs_get_inode(dir->i_sb, mode, rdev, obj);
262         d_instantiate(dentry, inode);
263         update_dir_time(dir);
264         yaffs_trace(YAFFS_TRACE_OS,
265                 "yaffs_mknod created object %d count = %d",
266                 obj->obj_id, atomic_read(&inode->i_count));
267         yaffs_fill_inode_from_obj(dir, parent);
268         return 0;
269
270 err_out:
271         yaffs_gross_unlock(dev);
272         yaffs_trace(YAFFS_TRACE_OS, "yaffs_mknod error %d", error);
273         return error;
274
275 }
276
277 static int yaffs_mkdir(struct inode *dir, struct dentry *dentry, int mode)
278 {
279         return yaffs_mknod(dir, dentry, mode | S_IFDIR, 0);
280 }
281
282 static int yaffs_create(struct inode *dir, struct dentry *dentry, int mode,
283                         struct nameidata *n)
284 {
285         return yaffs_mknod(dir, dentry, mode | S_IFREG, 0);
286 }
287
288 static int yaffs_link(struct dentry *old_dentry, struct inode *dir,
289                       struct dentry *dentry)
290 {
291         struct inode *inode = old_dentry->d_inode;
292         struct yaffs_obj *obj = NULL;
293         struct yaffs_obj *link = NULL;
294         struct yaffs_dev *dev;
295
296         yaffs_trace(YAFFS_TRACE_OS, "yaffs_link");
297
298         obj = yaffs_inode_to_obj(inode);
299         dev = obj->my_dev;
300
301         yaffs_gross_lock(dev);
302
303         if (!S_ISDIR(inode->i_mode))    /* Don't link directories */
304                 link =
305                     yaffs_link_obj(yaffs_inode_to_obj(dir), dentry->d_name.name,
306                                    obj);
307
308         if (link) {
309                 set_nlink(old_dentry->d_inode, yaffs_get_obj_link_count(obj));
310                 d_instantiate(dentry, old_dentry->d_inode);
311                 atomic_inc(&old_dentry->d_inode->i_count);
312                 yaffs_trace(YAFFS_TRACE_OS,
313                         "yaffs_link link count %d i_count %d",
314                         old_dentry->d_inode->i_nlink,
315                         atomic_read(&old_dentry->d_inode->i_count));
316         }
317
318         yaffs_gross_unlock(dev);
319
320         if (link) {
321                 update_dir_time(dir);
322                 return 0;
323         }
324
325         return -EPERM;
326 }
327
328 static int yaffs_symlink(struct inode *dir, struct dentry *dentry,
329                          const char *symname)
330 {
331         struct yaffs_obj *obj;
332         struct yaffs_dev *dev;
333         struct inode *inode;
334         uid_t uid = current->cred->fsuid;
335         gid_t gid =
336             (dir->i_mode & S_ISGID) ? dir->i_gid : current->cred->fsgid;
337
338         yaffs_trace(YAFFS_TRACE_OS, "yaffs_symlink");
339
340         if (strnlen(dentry->d_name.name, YAFFS_MAX_NAME_LENGTH + 1) >
341                                 YAFFS_MAX_NAME_LENGTH)
342                 return -ENAMETOOLONG;
343
344         if (strnlen(symname, YAFFS_MAX_ALIAS_LENGTH + 1) >
345                                 YAFFS_MAX_ALIAS_LENGTH)
346                 return -ENAMETOOLONG;
347
348         dev = yaffs_inode_to_obj(dir)->my_dev;
349         yaffs_gross_lock(dev);
350         obj = yaffs_create_symlink(yaffs_inode_to_obj(dir), dentry->d_name.name,
351                                    S_IFLNK | S_IRWXUGO, uid, gid, symname);
352         yaffs_gross_unlock(dev);
353
354         if (!obj) {
355                 yaffs_trace(YAFFS_TRACE_OS, "symlink not created");
356                 return -ENOMEM;
357         }
358
359         inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
360         d_instantiate(dentry, inode);
361         update_dir_time(dir);
362         yaffs_trace(YAFFS_TRACE_OS, "symlink created OK");
363
364         return 0;
365 }
366
367 static struct dentry *yaffs_lookup(struct inode *dir, struct dentry *dentry,
368                                    struct nameidata *n)
369 {
370         struct yaffs_obj *obj;
371         struct inode *inode = NULL;
372         struct yaffs_dev *dev = yaffs_inode_to_obj(dir)->my_dev;
373
374         if (current != yaffs_dev_to_lc(dev)->readdir_process)
375                 yaffs_gross_lock(dev);
376
377         yaffs_trace(YAFFS_TRACE_OS,
378                 "yaffs_lookup for %d:%s",
379                 yaffs_inode_to_obj(dir)->obj_id, dentry->d_name.name);
380
381         obj = yaffs_find_by_name(yaffs_inode_to_obj(dir), dentry->d_name.name);
382
383         obj = yaffs_get_equivalent_obj(obj);    /* in case it was a hardlink */
384
385         /* Can't hold gross lock when calling yaffs_get_inode() */
386         if (current != yaffs_dev_to_lc(dev)->readdir_process)
387                 yaffs_gross_unlock(dev);
388
389         if (obj) {
390                 yaffs_trace(YAFFS_TRACE_OS,
391                         "yaffs_lookup found %d", obj->obj_id);
392
393                 inode = yaffs_get_inode(dir->i_sb, obj->yst_mode, 0, obj);
394
395                 if (inode) {
396                         yaffs_trace(YAFFS_TRACE_OS, "yaffs_loookup dentry");
397                         d_add(dentry, inode);
398                         /* return dentry; */
399                         return NULL;
400                 }
401
402         } else {
403                 yaffs_trace(YAFFS_TRACE_OS, "yaffs_lookup not found");
404
405         }
406
407         d_add(dentry, inode);
408
409         return NULL;
410 }
411
412 static int yaffs_unlink(struct inode *dir, struct dentry *dentry)
413 {
414         int ret_val;
415         struct yaffs_dev *dev;
416         struct yaffs_obj *obj;
417
418         yaffs_trace(YAFFS_TRACE_OS,
419                 "yaffs_unlink %d:%s",
420                 (int)(dir->i_ino), dentry->d_name.name);
421         obj = yaffs_inode_to_obj(dir);
422         dev = obj->my_dev;
423
424         yaffs_gross_lock(dev);
425
426         ret_val = yaffs_unlinker(obj, dentry->d_name.name);
427
428         if (ret_val == YAFFS_OK) {
429                 inode_dec_link_count(dentry->d_inode);
430                 dir->i_version++;
431                 yaffs_gross_unlock(dev);
432                 update_dir_time(dir);
433                 return 0;
434         }
435         yaffs_gross_unlock(dev);
436         return -ENOTEMPTY;
437 }
438
439 static int yaffs_sync_object(struct file *file,
440                                 loff_t start, loff_t end, int datasync)
441 {
442
443         struct yaffs_obj *obj;
444         struct yaffs_dev *dev;
445         struct dentry *dentry = file->f_path.dentry;
446
447         obj = yaffs_dentry_to_obj(dentry);
448
449         dev = obj->my_dev;
450
451         yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC, "yaffs_sync_object");
452         yaffs_gross_lock(dev);
453         yaffs_flush_file(obj, 1, datasync, 0);
454         yaffs_gross_unlock(dev);
455         return 0;
456 }
457 /*
458  * The VFS layer already does all the dentry stuff for rename.
459  *
460  * NB: POSIX says you can rename an object over an old object of the same name
461  */
462 static int yaffs_rename(struct inode *old_dir, struct dentry *old_dentry,
463                         struct inode *new_dir, struct dentry *new_dentry)
464 {
465         struct yaffs_dev *dev;
466         int ret_val = YAFFS_FAIL;
467         struct yaffs_obj *target;
468
469         yaffs_trace(YAFFS_TRACE_OS, "yaffs_rename");
470         dev = yaffs_inode_to_obj(old_dir)->my_dev;
471
472         yaffs_gross_lock(dev);
473
474         /* Check if the target is an existing directory that is not empty. */
475         target = yaffs_find_by_name(yaffs_inode_to_obj(new_dir),
476                                     new_dentry->d_name.name);
477
478         if (target && target->variant_type == YAFFS_OBJECT_TYPE_DIRECTORY &&
479             !list_empty(&target->variant.dir_variant.children)) {
480
481                 yaffs_trace(YAFFS_TRACE_OS, "target is non-empty dir");
482
483                 ret_val = YAFFS_FAIL;
484         } else {
485                 /* Now does unlinking internally using shadowing mechanism */
486                 yaffs_trace(YAFFS_TRACE_OS, "calling yaffs_rename_obj");
487
488                 ret_val = yaffs_rename_obj(yaffs_inode_to_obj(old_dir),
489                                            old_dentry->d_name.name,
490                                            yaffs_inode_to_obj(new_dir),
491                                            new_dentry->d_name.name);
492         }
493         yaffs_gross_unlock(dev);
494
495         if (ret_val == YAFFS_OK) {
496                 if (target)
497                         inode_dec_link_count(new_dentry->d_inode);
498
499                 update_dir_time(old_dir);
500                 if (old_dir != new_dir)
501                         update_dir_time(new_dir);
502                 return 0;
503         } else {
504                 return -ENOTEMPTY;
505         }
506 }
507
508 static int yaffs_setattr(struct dentry *dentry, struct iattr *attr)
509 {
510         struct inode *inode = dentry->d_inode;
511         int error = 0;
512         struct yaffs_dev *dev;
513         int result;
514
515         yaffs_trace(YAFFS_TRACE_OS,
516                 "yaffs_setattr of object %d",
517                 yaffs_inode_to_obj(inode)->obj_id);
518
519         /* Fail if a requested resize >= 2GB */
520         if (attr->ia_valid & ATTR_SIZE && (attr->ia_size >> 31))
521                 error = -EINVAL;
522
523         if (!error)
524                 error = inode_change_ok(inode, attr);
525
526         if (!error) {
527                 setattr_copy(inode, attr);
528                 yaffs_trace(YAFFS_TRACE_OS, "inode_setattr called");
529                 if (attr->ia_valid & ATTR_SIZE) {
530                         truncate_setsize(inode, attr->ia_size);
531                         inode->i_blocks = (inode->i_size + 511) >> 9;
532                 }
533                 dev = yaffs_inode_to_obj(inode)->my_dev;
534                 if (attr->ia_valid & ATTR_SIZE) {
535                         yaffs_trace(YAFFS_TRACE_OS, "resize to %d(%x)",
536                                            (int)(attr->ia_size),
537                                            (int)(attr->ia_size));
538                 }
539
540                 yaffs_gross_lock(dev);
541                 result = yaffs_set_attribs(yaffs_inode_to_obj(inode), attr);
542                 if (result != YAFFS_OK)
543                         error = -EPERM;
544                 yaffs_gross_unlock(dev);
545         }
546
547         yaffs_trace(YAFFS_TRACE_OS, "yaffs_setattr done returning %d", error);
548
549         return error;
550 }
551
552 static int yaffs_setxattr(struct dentry *dentry, const char *name,
553                    const void *value, size_t size, int flags)
554 {
555         struct inode *inode = dentry->d_inode;
556         int error;
557         struct yaffs_dev *dev;
558         struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
559
560         yaffs_trace(YAFFS_TRACE_OS, "yaffs_setxattr of object %d", obj->obj_id);
561
562         dev = obj->my_dev;
563         yaffs_gross_lock(dev);
564         error = yaffs_set_xattrib(obj, name, value, size, flags);
565         yaffs_gross_unlock(dev);
566
567         yaffs_trace(YAFFS_TRACE_OS, "yaffs_setxattr done returning %d", error);
568
569         return error;
570 }
571
572 static ssize_t yaffs_getxattr(struct dentry *dentry, const char *name,
573                                 void *buff, size_t size)
574 {
575         struct inode *inode = dentry->d_inode;
576         int error;
577         struct yaffs_dev *dev;
578         struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
579
580         yaffs_trace(YAFFS_TRACE_OS,
581                 "yaffs_getxattr \"%s\" from object %d",
582                 name, obj->obj_id);
583
584         dev = obj->my_dev;
585         yaffs_gross_lock(dev);
586         error = yaffs_get_xattrib(obj, name, buff, size);
587         yaffs_gross_unlock(dev);
588
589         yaffs_trace(YAFFS_TRACE_OS, "yaffs_getxattr done returning %d", error);
590
591         return error;
592 }
593
594 static int yaffs_removexattr(struct dentry *dentry, const char *name)
595 {
596         struct inode *inode = dentry->d_inode;
597         int error;
598         struct yaffs_dev *dev;
599         struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
600
601         yaffs_trace(YAFFS_TRACE_OS,
602                 "yaffs_removexattr of object %d", obj->obj_id);
603
604         dev = obj->my_dev;
605         yaffs_gross_lock(dev);
606         error = yaffs_remove_xattrib(obj, name);
607         yaffs_gross_unlock(dev);
608
609         yaffs_trace(YAFFS_TRACE_OS,
610                 "yaffs_removexattr done returning %d", error);
611
612         return error;
613 }
614
615 static ssize_t yaffs_listxattr(struct dentry *dentry, char *buff, size_t size)
616 {
617         struct inode *inode = dentry->d_inode;
618         int error;
619         struct yaffs_dev *dev;
620         struct yaffs_obj *obj = yaffs_inode_to_obj(inode);
621
622         yaffs_trace(YAFFS_TRACE_OS,
623                 "yaffs_listxattr of object %d", obj->obj_id);
624
625         dev = obj->my_dev;
626         yaffs_gross_lock(dev);
627         error = yaffs_list_xattrib(obj, buff, size);
628         yaffs_gross_unlock(dev);
629
630         yaffs_trace(YAFFS_TRACE_OS,
631                 "yaffs_listxattr done returning %d", error);
632
633         return error;
634 }
635
636 static const struct inode_operations yaffs_dir_inode_operations = {
637         .create = yaffs_create,
638         .lookup = yaffs_lookup,
639         .link = yaffs_link,
640         .unlink = yaffs_unlink,
641         .symlink = yaffs_symlink,
642         .mkdir = yaffs_mkdir,
643         .rmdir = yaffs_unlink,
644         .mknod = yaffs_mknod,
645         .rename = yaffs_rename,
646         .setattr = yaffs_setattr,
647         .setxattr = yaffs_setxattr,
648         .getxattr = yaffs_getxattr,
649         .listxattr = yaffs_listxattr,
650         .removexattr = yaffs_removexattr,
651 };
652 /*-----------------------------------------------------------------*/
653 /* Directory search context allows us to unlock access to yaffs during
654  * filldir without causing problems with the directory being modified.
655  * This is similar to the tried and tested mechanism used in yaffs direct.
656  *
657  * A search context iterates along a doubly linked list of siblings in the
658  * directory. If the iterating object is deleted then this would corrupt
659  * the list iteration, likely causing a crash. The search context avoids
660  * this by using the remove_obj_fn to move the search context to the
661  * next object before the object is deleted.
662  *
663  * Many readdirs (and thus seach conexts) may be alive simulateously so
664  * each struct yaffs_dev has a list of these.
665  *
666  * A seach context lives for the duration of a readdir.
667  *
668  * All these functions must be called while yaffs is locked.
669  */
670
671 struct yaffs_search_context {
672         struct yaffs_dev *dev;
673         struct yaffs_obj *dir_obj;
674         struct yaffs_obj *next_return;
675         struct list_head others;
676 };
677
678 /*
679  * yaffs_new_search() creates a new search context, initialises it and
680  * adds it to the device's search context list.
681  *
682  * Called at start of readdir.
683  */
684 static struct yaffs_search_context *yaffs_new_search(struct yaffs_obj *dir)
685 {
686         struct yaffs_dev *dev = dir->my_dev;
687         struct yaffs_search_context *sc =
688             kmalloc(sizeof(struct yaffs_search_context), GFP_NOFS);
689
690         if (!sc)
691                 return NULL;
692
693         sc->dir_obj = dir;
694         sc->dev = dev;
695         if (list_empty(&sc->dir_obj->variant.dir_variant.children))
696                 sc->next_return = NULL;
697         else
698                 sc->next_return =
699                     list_entry(dir->variant.dir_variant.children.next,
700                                struct yaffs_obj, siblings);
701         INIT_LIST_HEAD(&sc->others);
702         list_add(&sc->others, &(yaffs_dev_to_lc(dev)->search_contexts));
703
704         return sc;
705 }
706
707 /*
708  * yaffs_search_end() disposes of a search context and cleans up.
709  */
710 static void yaffs_search_end(struct yaffs_search_context *sc)
711 {
712         if (sc) {
713                 list_del(&sc->others);
714                 kfree(sc);
715         }
716 }
717
718 /*
719  * yaffs_search_advance() moves a search context to the next object.
720  * Called when the search iterates or when an object removal causes
721  * the search context to be moved to the next object.
722  */
723 static void yaffs_search_advance(struct yaffs_search_context *sc)
724 {
725         if (!sc)
726                 return;
727
728         if (sc->next_return == NULL ||
729             list_empty(&sc->dir_obj->variant.dir_variant.children))
730                 sc->next_return = NULL;
731         else {
732                 struct list_head *next = sc->next_return->siblings.next;
733
734                 if (next == &sc->dir_obj->variant.dir_variant.children)
735                         sc->next_return = NULL; /* end of list */
736                 else
737                         sc->next_return =
738                             list_entry(next, struct yaffs_obj, siblings);
739         }
740 }
741
742 /*
743  * yaffs_remove_obj_callback() is called when an object is unlinked.
744  * We check open search contexts and advance any which are currently
745  * on the object being iterated.
746  */
747 static void yaffs_remove_obj_callback(struct yaffs_obj *obj)
748 {
749
750         struct list_head *i;
751         struct yaffs_search_context *sc;
752         struct list_head *search_contexts =
753             &(yaffs_dev_to_lc(obj->my_dev)->search_contexts);
754
755         /* Iterate through the directory search contexts.
756          * If any are currently on the object being removed, then advance
757          * the search context to the next object to prevent a hanging pointer.
758          */
759         list_for_each(i, search_contexts) {
760                 sc = list_entry(i, struct yaffs_search_context, others);
761                 if (sc->next_return == obj)
762                         yaffs_search_advance(sc);
763         }
764
765 }
766
767 static int yaffs_readdir(struct file *f, void *dirent, filldir_t filldir)
768 {
769         struct yaffs_obj *obj;
770         struct yaffs_dev *dev;
771         struct yaffs_search_context *sc;
772         struct inode *inode = f->f_dentry->d_inode;
773         unsigned long offset, curoffs;
774         struct yaffs_obj *l;
775         int ret_val = 0;
776         char name[YAFFS_MAX_NAME_LENGTH + 1];
777
778         obj = yaffs_dentry_to_obj(f->f_dentry);
779         dev = obj->my_dev;
780
781         yaffs_gross_lock(dev);
782
783         yaffs_dev_to_lc(dev)->readdir_process = current;
784
785         offset = f->f_pos;
786
787         sc = yaffs_new_search(obj);
788         if (!sc) {
789                 ret_val = -ENOMEM;
790                 goto out;
791         }
792
793         yaffs_trace(YAFFS_TRACE_OS,
794                 "yaffs_readdir: starting at %d", (int)offset);
795
796         if (offset == 0) {
797                 yaffs_trace(YAFFS_TRACE_OS,
798                         "yaffs_readdir: entry . ino %d",
799                         (int)inode->i_ino);
800                 yaffs_gross_unlock(dev);
801                 if (filldir(dirent, ".", 1, offset, inode->i_ino, DT_DIR) < 0) {
802                         yaffs_gross_lock(dev);
803                         goto out;
804                 }
805                 yaffs_gross_lock(dev);
806                 offset++;
807                 f->f_pos++;
808         }
809         if (offset == 1) {
810                 yaffs_trace(YAFFS_TRACE_OS,
811                         "yaffs_readdir: entry .. ino %d",
812                         (int)f->f_dentry->d_parent->d_inode->i_ino);
813                 yaffs_gross_unlock(dev);
814                 if (filldir(dirent, "..", 2, offset,
815                             f->f_dentry->d_parent->d_inode->i_ino,
816                             DT_DIR) < 0) {
817                         yaffs_gross_lock(dev);
818                         goto out;
819                 }
820                 yaffs_gross_lock(dev);
821                 offset++;
822                 f->f_pos++;
823         }
824
825         curoffs = 1;
826
827         /* If the directory has changed since the open or last call to
828            readdir, rewind to after the 2 canned entries. */
829         if (f->f_version != inode->i_version) {
830                 offset = 2;
831                 f->f_pos = offset;
832                 f->f_version = inode->i_version;
833         }
834
835         while (sc->next_return) {
836                 curoffs++;
837                 l = sc->next_return;
838                 if (curoffs >= offset) {
839                         int this_inode = yaffs_get_obj_inode(l);
840                         int this_type = yaffs_get_obj_type(l);
841
842                         yaffs_get_obj_name(l, name, YAFFS_MAX_NAME_LENGTH + 1);
843                         yaffs_trace(YAFFS_TRACE_OS,
844                                 "yaffs_readdir: %s inode %d",
845                                 name, yaffs_get_obj_inode(l));
846
847                         yaffs_gross_unlock(dev);
848
849                         if (filldir(dirent,
850                                     name,
851                                     strlen(name),
852                                     offset, this_inode, this_type) < 0) {
853                                 yaffs_gross_lock(dev);
854                                 goto out;
855                         }
856
857                         yaffs_gross_lock(dev);
858
859                         offset++;
860                         f->f_pos++;
861                 }
862                 yaffs_search_advance(sc);
863         }
864
865 out:
866         yaffs_search_end(sc);
867         yaffs_dev_to_lc(dev)->readdir_process = NULL;
868         yaffs_gross_unlock(dev);
869
870         return ret_val;
871 }
872
873 static const struct file_operations yaffs_dir_operations = {
874         .read = generic_read_dir,
875         .readdir = yaffs_readdir,
876         .fsync = yaffs_sync_object,
877         .llseek = generic_file_llseek,
878 };
879
880
881
882 static int yaffs_file_flush(struct file *file, fl_owner_t id)
883 {
884         struct yaffs_obj *obj = yaffs_dentry_to_obj(file->f_dentry);
885         struct yaffs_dev *dev = obj->my_dev;
886
887         yaffs_trace(YAFFS_TRACE_OS,
888                 "yaffs_file_flush object %d (%s)",
889                 obj->obj_id, obj->dirty ? "dirty" : "clean");
890
891         yaffs_gross_lock(dev);
892
893         yaffs_flush_file(obj, 1, 0, 0);
894
895         yaffs_gross_unlock(dev);
896
897         return 0;
898 }
899
900 static const struct file_operations yaffs_file_operations = {
901         .read = do_sync_read,
902         .write = do_sync_write,
903         .aio_read = generic_file_aio_read,
904         .aio_write = generic_file_aio_write,
905         .mmap = generic_file_mmap,
906         .flush = yaffs_file_flush,
907         .fsync = yaffs_sync_object,
908         .splice_read = generic_file_splice_read,
909         .splice_write = generic_file_splice_write,
910         .llseek = generic_file_llseek,
911 };
912
913
914 /* ExportFS support */
915 static struct inode *yaffs2_nfs_get_inode(struct super_block *sb, uint64_t ino,
916                                           uint32_t generation)
917 {
918         return yaffs_iget(sb, ino);
919 }
920
921 static struct dentry *yaffs2_fh_to_dentry(struct super_block *sb,
922                                           struct fid *fid, int fh_len,
923                                           int fh_type)
924 {
925         return generic_fh_to_dentry(sb, fid, fh_len, fh_type,
926                                     yaffs2_nfs_get_inode);
927 }
928
929 static struct dentry *yaffs2_fh_to_parent(struct super_block *sb,
930                                           struct fid *fid, int fh_len,
931                                           int fh_type)
932 {
933         return generic_fh_to_parent(sb, fid, fh_len, fh_type,
934                                     yaffs2_nfs_get_inode);
935 }
936
937 struct dentry *yaffs2_get_parent(struct dentry *dentry)
938 {
939
940         struct super_block *sb = dentry->d_inode->i_sb;
941         struct dentry *parent = ERR_PTR(-ENOENT);
942         struct inode *inode;
943         unsigned long parent_ino;
944         struct yaffs_obj *d_obj;
945         struct yaffs_obj *parent_obj;
946
947         d_obj = yaffs_inode_to_obj(dentry->d_inode);
948
949         if (d_obj) {
950                 parent_obj = d_obj->parent;
951                 if (parent_obj) {
952                         parent_ino = yaffs_get_obj_inode(parent_obj);
953                         inode = yaffs_iget(sb, parent_ino);
954
955                         if (IS_ERR(inode)) {
956                                 parent = ERR_CAST(inode);
957                         } else {
958                                 parent = d_obtain_alias(inode);
959                                 if (!IS_ERR(parent)) {
960                                         parent = ERR_PTR(-ENOMEM);
961                                         iput(inode);
962                                 }
963                         }
964                 }
965         }
966         return parent;
967 }
968
969 /* Just declare a zero structure as a NULL value implies
970  * using the default functions of exportfs.
971  */
972
973 static struct export_operations yaffs_export_ops = {
974         .fh_to_dentry = yaffs2_fh_to_dentry,
975         .fh_to_parent = yaffs2_fh_to_parent,
976         .get_parent = yaffs2_get_parent,
977 };
978
979
980 /*-----------------------------------------------------------------*/
981
982 static int yaffs_readlink(struct dentry *dentry, char __user * buffer,
983                           int buflen)
984 {
985         unsigned char *alias;
986         int ret;
987         struct yaffs_dev *dev = yaffs_dentry_to_obj(dentry)->my_dev;
988
989         yaffs_gross_lock(dev);
990
991         alias = yaffs_get_symlink_alias(yaffs_dentry_to_obj(dentry));
992
993         yaffs_gross_unlock(dev);
994
995         if (!alias)
996                 return -ENOMEM;
997
998         ret = vfs_readlink(dentry, buffer, buflen, alias);
999         kfree(alias);
1000         return ret;
1001 }
1002
1003 static void *yaffs_follow_link(struct dentry *dentry, struct nameidata *nd)
1004 {
1005         unsigned char *alias;
1006         void *ret;
1007         struct yaffs_dev *dev = yaffs_dentry_to_obj(dentry)->my_dev;
1008
1009         yaffs_gross_lock(dev);
1010
1011         alias = yaffs_get_symlink_alias(yaffs_dentry_to_obj(dentry));
1012         yaffs_gross_unlock(dev);
1013
1014         if (!alias) {
1015                 ret = ERR_PTR(-ENOMEM);
1016                 goto out;
1017         }
1018
1019         nd_set_link(nd, alias);
1020         ret = (void *)alias;
1021 out:
1022         return ret;
1023 }
1024
1025 void yaffs_put_link(struct dentry *dentry, struct nameidata *nd, void *alias)
1026 {
1027         kfree(alias);
1028 }
1029
1030
1031 static void yaffs_unstitch_obj(struct inode *inode, struct yaffs_obj *obj)
1032 {
1033         /* Clear the association between the inode and
1034          * the struct yaffs_obj.
1035          */
1036         obj->my_inode = NULL;
1037         yaffs_inode_to_obj_lv(inode) = NULL;
1038
1039         /* If the object freeing was deferred, then the real
1040          * free happens now.
1041          * This should fix the inode inconsistency problem.
1042          */
1043         yaffs_handle_defered_free(obj);
1044 }
1045
1046 /* yaffs_evict_inode combines into one operation what was previously done in
1047  * yaffs_clear_inode() and yaffs_delete_inode()
1048  *
1049  */
1050 static void yaffs_evict_inode(struct inode *inode)
1051 {
1052         struct yaffs_obj *obj;
1053         struct yaffs_dev *dev;
1054         int deleteme = 0;
1055
1056         obj = yaffs_inode_to_obj(inode);
1057
1058         yaffs_trace(YAFFS_TRACE_OS,
1059                 "yaffs_evict_inode: ino %d, count %d %s",
1060                 (int)inode->i_ino,
1061                 atomic_read(&inode->i_count),
1062                 obj ? "object exists" : "null object");
1063
1064         if (!inode->i_nlink && !is_bad_inode(inode))
1065                 deleteme = 1;
1066         truncate_inode_pages(&inode->i_data, 0);
1067         end_writeback(inode);
1068
1069         if (deleteme && obj) {
1070                 dev = obj->my_dev;
1071                 yaffs_gross_lock(dev);
1072                 yaffs_del_obj(obj);
1073                 yaffs_gross_unlock(dev);
1074         }
1075         if (obj) {
1076                 dev = obj->my_dev;
1077                 yaffs_gross_lock(dev);
1078                 yaffs_unstitch_obj(inode, obj);
1079                 yaffs_gross_unlock(dev);
1080         }
1081
1082 }
1083
1084 static void yaffs_touch_super(struct yaffs_dev *dev)
1085 {
1086         struct super_block *sb = yaffs_dev_to_lc(dev)->super;
1087
1088         yaffs_trace(YAFFS_TRACE_OS, "yaffs_touch_super() sb = %p", sb);
1089         if (sb)
1090                 sb->s_dirt = 1;
1091 }
1092
1093 static int yaffs_readpage_nolock(struct file *f, struct page *pg)
1094 {
1095         /* Lifted from jffs2 */
1096
1097         struct yaffs_obj *obj;
1098         unsigned char *pg_buf;
1099         int ret;
1100         struct yaffs_dev *dev;
1101         loff_t pos = ((loff_t) pg->index) << PAGE_CACHE_SHIFT;
1102
1103         yaffs_trace(YAFFS_TRACE_OS,
1104                 "yaffs_readpage_nolock at %lld, size %08x",
1105                 (long long)pos,
1106                 (unsigned)PAGE_CACHE_SIZE);
1107
1108
1109         obj = yaffs_dentry_to_obj(f->f_dentry);
1110
1111         dev = obj->my_dev;
1112
1113         BUG_ON(!PageLocked(pg));
1114
1115         pg_buf = kmap(pg);
1116         /* FIXME: Can kmap fail? */
1117
1118         yaffs_gross_lock(dev);
1119
1120         ret = yaffs_file_rd(obj, pg_buf, pos, PAGE_CACHE_SIZE);
1121
1122         yaffs_gross_unlock(dev);
1123
1124         if (ret >= 0)
1125                 ret = 0;
1126
1127         if (ret) {
1128                 ClearPageUptodate(pg);
1129                 SetPageError(pg);
1130         } else {
1131                 SetPageUptodate(pg);
1132                 ClearPageError(pg);
1133         }
1134
1135         flush_dcache_page(pg);
1136         kunmap(pg);
1137
1138         yaffs_trace(YAFFS_TRACE_OS, "yaffs_readpage_nolock done");
1139         return ret;
1140 }
1141
1142 static int yaffs_readpage_unlock(struct file *f, struct page *pg)
1143 {
1144         int ret = yaffs_readpage_nolock(f, pg);
1145
1146         unlock_page(pg);
1147         return ret;
1148 }
1149
1150 static int yaffs_readpage(struct file *f, struct page *pg)
1151 {
1152         int ret;
1153
1154         yaffs_trace(YAFFS_TRACE_OS, "yaffs_readpage");
1155         ret = yaffs_readpage_unlock(f, pg);
1156         yaffs_trace(YAFFS_TRACE_OS, "yaffs_readpage done");
1157         return ret;
1158 }
1159
1160 /* writepage inspired by/stolen from smbfs */
1161
1162 static int yaffs_writepage(struct page *page, struct writeback_control *wbc)
1163 {
1164         struct yaffs_dev *dev;
1165         struct address_space *mapping = page->mapping;
1166         struct inode *inode;
1167         unsigned long end_index;
1168         char *buffer;
1169         struct yaffs_obj *obj;
1170         int n_written = 0;
1171         unsigned n_bytes;
1172         loff_t i_size;
1173
1174         if (!mapping)
1175                 BUG();
1176         inode = mapping->host;
1177         if (!inode)
1178                 BUG();
1179         i_size = i_size_read(inode);
1180
1181         end_index = i_size >> PAGE_CACHE_SHIFT;
1182
1183         if (page->index < end_index)
1184                 n_bytes = PAGE_CACHE_SIZE;
1185         else {
1186                 n_bytes = i_size & (PAGE_CACHE_SIZE - 1);
1187
1188                 if (page->index > end_index || !n_bytes) {
1189                         yaffs_trace(YAFFS_TRACE_OS,
1190                                 "yaffs_writepage at %08x, inode size = %08x!!!",
1191                                 (unsigned)(page->index << PAGE_CACHE_SHIFT),
1192                                 (unsigned)inode->i_size);
1193                         yaffs_trace(YAFFS_TRACE_OS,
1194                           "                -> don't care!!");
1195
1196                         zero_user_segment(page, 0, PAGE_CACHE_SIZE);
1197                         set_page_writeback(page);
1198                         unlock_page(page);
1199                         end_page_writeback(page);
1200                         return 0;
1201                 }
1202         }
1203
1204         if (n_bytes != PAGE_CACHE_SIZE)
1205                 zero_user_segment(page, n_bytes, PAGE_CACHE_SIZE);
1206
1207         get_page(page);
1208
1209         buffer = kmap(page);
1210
1211         obj = yaffs_inode_to_obj(inode);
1212         dev = obj->my_dev;
1213         yaffs_gross_lock(dev);
1214
1215         yaffs_trace(YAFFS_TRACE_OS,
1216                 "yaffs_writepage at %08x, size %08x",
1217                 (unsigned)(page->index << PAGE_CACHE_SHIFT), n_bytes);
1218         yaffs_trace(YAFFS_TRACE_OS,
1219                 "writepag0: obj = %05x, ino = %05x",
1220                 (int)obj->variant.file_variant.file_size, (int)inode->i_size);
1221
1222         n_written = yaffs_wr_file(obj, buffer,
1223                                   ((loff_t)page->index) << PAGE_CACHE_SHIFT,
1224                                   n_bytes, 0);
1225
1226         yaffs_touch_super(dev);
1227
1228         yaffs_trace(YAFFS_TRACE_OS,
1229                 "writepag1: obj = %05x, ino = %05x",
1230                 (int)obj->variant.file_variant.file_size, (int)inode->i_size);
1231
1232         yaffs_gross_unlock(dev);
1233
1234         kunmap(page);
1235         set_page_writeback(page);
1236         unlock_page(page);
1237         end_page_writeback(page);
1238         put_page(page);
1239
1240         return (n_written == n_bytes) ? 0 : -ENOSPC;
1241 }
1242
1243 /* Space holding and freeing is done to ensure we have space available for
1244  * write_begin/end.
1245  * For now we just assume few parallel writes and check against a small
1246  * number.
1247  * Todo: need to do this with a counter to handle parallel reads better
1248  */
1249
1250 static ssize_t yaffs_hold_space(struct file *f)
1251 {
1252         struct yaffs_obj *obj;
1253         struct yaffs_dev *dev;
1254         int n_free_chunks;
1255
1256         obj = yaffs_dentry_to_obj(f->f_dentry);
1257
1258         dev = obj->my_dev;
1259
1260         yaffs_gross_lock(dev);
1261
1262         n_free_chunks = yaffs_get_n_free_chunks(dev);
1263
1264         yaffs_gross_unlock(dev);
1265
1266         return (n_free_chunks > 20) ? 1 : 0;
1267 }
1268
1269 static void yaffs_release_space(struct file *f)
1270 {
1271         struct yaffs_obj *obj;
1272         struct yaffs_dev *dev;
1273
1274         obj = yaffs_dentry_to_obj(f->f_dentry);
1275
1276         dev = obj->my_dev;
1277
1278         yaffs_gross_lock(dev);
1279
1280         yaffs_gross_unlock(dev);
1281 }
1282
1283 static int yaffs_write_begin(struct file *filp, struct address_space *mapping,
1284                              loff_t pos, unsigned len, unsigned flags,
1285                              struct page **pagep, void **fsdata)
1286 {
1287         struct page *pg = NULL;
1288         pgoff_t index = pos >> PAGE_CACHE_SHIFT;
1289         int ret = 0;
1290         int space_held = 0;
1291
1292         /* Get a page */
1293         pg = grab_cache_page_write_begin(mapping, index, flags);
1294
1295         *pagep = pg;
1296         if (!pg) {
1297                 ret = -ENOMEM;
1298                 goto out;
1299         }
1300         yaffs_trace(YAFFS_TRACE_OS,
1301                 "start yaffs_write_begin index %d(%x) uptodate %d",
1302                 (int)index, (int)index, PageUptodate(pg) ? 1 : 0);
1303
1304         /* Get fs space */
1305         space_held = yaffs_hold_space(filp);
1306
1307         if (!space_held) {
1308                 ret = -ENOSPC;
1309                 goto out;
1310         }
1311
1312         /* Update page if required */
1313
1314         if (!PageUptodate(pg))
1315                 ret = yaffs_readpage_nolock(filp, pg);
1316
1317         if (ret)
1318                 goto out;
1319
1320         /* Happy path return */
1321         yaffs_trace(YAFFS_TRACE_OS, "end yaffs_write_begin - ok");
1322
1323         return 0;
1324
1325 out:
1326         yaffs_trace(YAFFS_TRACE_OS,
1327                 "end yaffs_write_begin fail returning %d", ret);
1328         if (space_held)
1329                 yaffs_release_space(filp);
1330         if (pg) {
1331                 unlock_page(pg);
1332                 page_cache_release(pg);
1333         }
1334         return ret;
1335 }
1336
1337 static ssize_t yaffs_file_write(struct file *f, const char *buf, size_t n,
1338                                 loff_t *pos)
1339 {
1340         struct yaffs_obj *obj;
1341         int n_written, ipos;
1342         struct inode *inode;
1343         struct yaffs_dev *dev;
1344
1345         obj = yaffs_dentry_to_obj(f->f_dentry);
1346
1347         if (!obj) {
1348                 /* This should not happen */
1349                 yaffs_trace(YAFFS_TRACE_OS,
1350                         "yaffs_file_write: hey obj is null!");
1351                 return -EINVAL;
1352         }
1353
1354         dev = obj->my_dev;
1355
1356         yaffs_gross_lock(dev);
1357
1358         inode = f->f_dentry->d_inode;
1359
1360         if (!S_ISBLK(inode->i_mode) && f->f_flags & O_APPEND)
1361                 ipos = inode->i_size;
1362         else
1363                 ipos = *pos;
1364
1365         yaffs_trace(YAFFS_TRACE_OS,
1366                 "yaffs_file_write about to write writing %u(%x) bytes to object %d at %d(%x)",
1367                 (unsigned)n, (unsigned)n, obj->obj_id, ipos, ipos);
1368
1369         n_written = yaffs_wr_file(obj, buf, ipos, n, 0);
1370
1371         yaffs_touch_super(dev);
1372
1373         yaffs_trace(YAFFS_TRACE_OS,
1374                 "yaffs_file_write: %d(%x) bytes written",
1375                 (unsigned)n, (unsigned)n);
1376
1377         if (n_written > 0) {
1378                 ipos += n_written;
1379                 *pos = ipos;
1380                 if (ipos > inode->i_size) {
1381                         inode->i_size = ipos;
1382                         inode->i_blocks = (ipos + 511) >> 9;
1383
1384                         yaffs_trace(YAFFS_TRACE_OS,
1385                                 "yaffs_file_write size updated to %d bytes, %d blocks",
1386                                 ipos, (int)(inode->i_blocks));
1387                 }
1388         }
1389         yaffs_gross_unlock(dev);
1390         return (n_written == 0) && (n > 0) ? -ENOSPC : n_written;
1391 }
1392
1393 static int yaffs_write_end(struct file *filp, struct address_space *mapping,
1394                            loff_t pos, unsigned len, unsigned copied,
1395                            struct page *pg, void *fsdadata)
1396 {
1397         int ret = 0;
1398         void *addr, *kva;
1399         uint32_t offset_into_page = pos & (PAGE_CACHE_SIZE - 1);
1400
1401         kva = kmap(pg);
1402         addr = kva + offset_into_page;
1403
1404         yaffs_trace(YAFFS_TRACE_OS,
1405                 "yaffs_write_end addr %p pos %x n_bytes %d",
1406                 addr, (unsigned)pos, copied);
1407
1408         ret = yaffs_file_write(filp, addr, copied, &pos);
1409
1410         if (ret != copied) {
1411                 yaffs_trace(YAFFS_TRACE_OS,
1412                         "yaffs_write_end not same size ret %d  copied %d",
1413                         ret, copied);
1414                 SetPageError(pg);
1415         }
1416
1417         kunmap(pg);
1418
1419         yaffs_release_space(filp);
1420         unlock_page(pg);
1421         page_cache_release(pg);
1422         return ret;
1423 }
1424
1425 static int yaffs_statfs(struct dentry *dentry, struct kstatfs *buf)
1426 {
1427         struct yaffs_dev *dev = yaffs_dentry_to_obj(dentry)->my_dev;
1428         struct super_block *sb = dentry->d_sb;
1429
1430         yaffs_trace(YAFFS_TRACE_OS, "yaffs_statfs");
1431
1432         yaffs_gross_lock(dev);
1433
1434         buf->f_type = YAFFS_MAGIC;
1435         buf->f_bsize = sb->s_blocksize;
1436         buf->f_namelen = 255;
1437
1438         if (dev->data_bytes_per_chunk & (dev->data_bytes_per_chunk - 1)) {
1439                 /* Do this if chunk size is not a power of 2 */
1440
1441                 uint64_t bytes_in_dev;
1442                 uint64_t bytes_free;
1443
1444                 bytes_in_dev =
1445                     ((uint64_t)
1446                      ((dev->param.end_block - dev->param.start_block + 1))) *
1447                      ((uint64_t) (dev->param.chunks_per_block *
1448                                            dev->data_bytes_per_chunk));
1449
1450                 do_div(bytes_in_dev, sb->s_blocksize);
1451                         /* bytes_in_dev becomes the number of blocks */
1452                 buf->f_blocks = bytes_in_dev;
1453
1454                 bytes_free = ((uint64_t) (yaffs_get_n_free_chunks(dev))) *
1455                     ((uint64_t) (dev->data_bytes_per_chunk));
1456
1457                 do_div(bytes_free, sb->s_blocksize);
1458
1459                 buf->f_bfree = bytes_free;
1460
1461         } else if (sb->s_blocksize > dev->data_bytes_per_chunk) {
1462
1463                 buf->f_blocks =
1464                     (dev->param.end_block - dev->param.start_block + 1) *
1465                     dev->param.chunks_per_block /
1466                     (sb->s_blocksize / dev->data_bytes_per_chunk);
1467                 buf->f_bfree =
1468                     yaffs_get_n_free_chunks(dev) /
1469                     (sb->s_blocksize / dev->data_bytes_per_chunk);
1470         } else {
1471                 buf->f_blocks =
1472                     (dev->param.end_block - dev->param.start_block + 1) *
1473                     dev->param.chunks_per_block *
1474                     (dev->data_bytes_per_chunk / sb->s_blocksize);
1475
1476                 buf->f_bfree =
1477                     yaffs_get_n_free_chunks(dev) *
1478                     (dev->data_bytes_per_chunk / sb->s_blocksize);
1479         }
1480
1481         buf->f_files = 0;
1482         buf->f_ffree = 0;
1483         buf->f_bavail = buf->f_bfree;
1484
1485         yaffs_gross_unlock(dev);
1486         return 0;
1487 }
1488
1489 static void yaffs_flush_inodes(struct super_block *sb)
1490 {
1491         struct inode *iptr;
1492         struct yaffs_obj *obj;
1493
1494         list_for_each_entry(iptr, &sb->s_inodes, i_sb_list) {
1495                 obj = yaffs_inode_to_obj(iptr);
1496                 if (obj) {
1497                         yaffs_trace(YAFFS_TRACE_OS,
1498                                 "flushing obj %d", obj->obj_id);
1499                         yaffs_flush_file(obj, 1, 0, 0);
1500                 }
1501         }
1502 }
1503
1504 static void yaffs_flush_super(struct super_block *sb, int do_checkpoint)
1505 {
1506         struct yaffs_dev *dev = yaffs_super_to_dev(sb);
1507
1508         if (!dev)
1509                 return;
1510
1511         yaffs_flush_inodes(sb);
1512         yaffs_update_dirty_dirs(dev);
1513         yaffs_flush_whole_cache(dev);
1514         if (do_checkpoint)
1515                 yaffs_checkpoint_save(dev);
1516 }
1517
1518 static unsigned yaffs_bg_gc_urgency(struct yaffs_dev *dev)
1519 {
1520         unsigned erased_chunks =
1521             dev->n_erased_blocks * dev->param.chunks_per_block;
1522         struct yaffs_linux_context *context = yaffs_dev_to_lc(dev);
1523         unsigned scattered = 0; /* Free chunks not in an erased block */
1524
1525         if (erased_chunks < dev->n_free_chunks)
1526                 scattered = (dev->n_free_chunks - erased_chunks);
1527
1528         if (!context->bg_running)
1529                 return 0;
1530         else if (scattered < (dev->param.chunks_per_block * 2))
1531                 return 0;
1532         else if (erased_chunks > dev->n_free_chunks / 2)
1533                 return 0;
1534         else if (erased_chunks > dev->n_free_chunks / 4)
1535                 return 1;
1536         else
1537                 return 2;
1538 }
1539
1540 static int yaffs_do_sync_fs(struct super_block *sb, int request_checkpoint)
1541 {
1542
1543         struct yaffs_dev *dev = yaffs_super_to_dev(sb);
1544         unsigned int oneshot_checkpoint = (yaffs_auto_checkpoint & 4);
1545         unsigned gc_urgent = yaffs_bg_gc_urgency(dev);
1546         int do_checkpoint;
1547
1548         yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC | YAFFS_TRACE_BACKGROUND,
1549                 "yaffs_do_sync_fs: gc-urgency %d %s %s%s",
1550                 gc_urgent,
1551                 sb->s_dirt ? "dirty" : "clean",
1552                 request_checkpoint ? "checkpoint requested" : "no checkpoint",
1553                 oneshot_checkpoint ? " one-shot" : "");
1554
1555         yaffs_gross_lock(dev);
1556         do_checkpoint = ((request_checkpoint && !gc_urgent) ||
1557                          oneshot_checkpoint) && !dev->is_checkpointed;
1558
1559         if (sb->s_dirt || do_checkpoint) {
1560                 yaffs_flush_super(sb, !dev->is_checkpointed && do_checkpoint);
1561                 sb->s_dirt = 0;
1562                 if (oneshot_checkpoint)
1563                         yaffs_auto_checkpoint &= ~4;
1564         }
1565         yaffs_gross_unlock(dev);
1566
1567         return 0;
1568 }
1569
1570 /*
1571  * yaffs background thread functions .
1572  * yaffs_bg_thread_fn() the thread function
1573  * yaffs_bg_start() launches the background thread.
1574  * yaffs_bg_stop() cleans up the background thread.
1575  *
1576  * NB:
1577  * The thread should only run after the yaffs is initialised
1578  * The thread should be stopped before yaffs is unmounted.
1579  * The thread should not do any writing while the fs is in read only.
1580  */
1581
1582 void yaffs_background_waker(unsigned long data)
1583 {
1584         wake_up_process((struct task_struct *)data);
1585 }
1586
1587 static int yaffs_bg_thread_fn(void *data)
1588 {
1589         struct yaffs_dev *dev = (struct yaffs_dev *)data;
1590         struct yaffs_linux_context *context = yaffs_dev_to_lc(dev);
1591         unsigned long now = jiffies;
1592         unsigned long next_dir_update = now;
1593         unsigned long next_gc = now;
1594         unsigned long expires;
1595         unsigned int urgency;
1596         int gc_result;
1597         struct timer_list timer;
1598
1599         yaffs_trace(YAFFS_TRACE_BACKGROUND,
1600                 "yaffs_background starting for dev %p", (void *)dev);
1601
1602         set_freezable();
1603         while (context->bg_running) {
1604                 yaffs_trace(YAFFS_TRACE_BACKGROUND, "yaffs_background");
1605
1606                 if (kthread_should_stop())
1607                         break;
1608
1609                 if (try_to_freeze())
1610                         continue;
1611
1612                 yaffs_gross_lock(dev);
1613
1614                 now = jiffies;
1615
1616                 if (time_after(now, next_dir_update) && yaffs_bg_enable) {
1617                         yaffs_update_dirty_dirs(dev);
1618                         next_dir_update = now + HZ;
1619                 }
1620
1621                 if (time_after(now, next_gc) && yaffs_bg_enable) {
1622                         if (!dev->is_checkpointed) {
1623                                 urgency = yaffs_bg_gc_urgency(dev);
1624                                 gc_result = yaffs_bg_gc(dev, urgency);
1625                                 if (urgency > 1)
1626                                         next_gc = now + HZ / 20 + 1;
1627                                 else if (urgency > 0)
1628                                         next_gc = now + HZ / 10 + 1;
1629                                 else
1630                                         next_gc = now + HZ * 2;
1631                         } else  {
1632                                 /*
1633                                  * gc not running so set to next_dir_update
1634                                  * to cut down on wake ups
1635                                  */
1636                                 next_gc = next_dir_update;
1637                         }
1638                 }
1639                 yaffs_gross_unlock(dev);
1640                 expires = next_dir_update;
1641                 if (time_before(next_gc, expires))
1642                         expires = next_gc;
1643                 if (time_before(expires, now))
1644                         expires = now + HZ;
1645
1646                 init_timer_on_stack(&timer);
1647                 timer.expires = expires + 1;
1648                 timer.data = (unsigned long)current;
1649                 timer.function = yaffs_background_waker;
1650
1651                 set_current_state(TASK_INTERRUPTIBLE);
1652                 add_timer(&timer);
1653                 schedule();
1654                 del_timer_sync(&timer);
1655         }
1656
1657         return 0;
1658 }
1659
1660 static int yaffs_bg_start(struct yaffs_dev *dev)
1661 {
1662         int retval = 0;
1663         struct yaffs_linux_context *context = yaffs_dev_to_lc(dev);
1664
1665         if (dev->read_only)
1666                 return -1;
1667
1668         context->bg_running = 1;
1669
1670         context->bg_thread = kthread_run(yaffs_bg_thread_fn,
1671                                          (void *)dev, "yaffs-bg-%d",
1672                                          context->mount_id);
1673
1674         if (IS_ERR(context->bg_thread)) {
1675                 retval = PTR_ERR(context->bg_thread);
1676                 context->bg_thread = NULL;
1677                 context->bg_running = 0;
1678         }
1679         return retval;
1680 }
1681
1682 static void yaffs_bg_stop(struct yaffs_dev *dev)
1683 {
1684         struct yaffs_linux_context *ctxt = yaffs_dev_to_lc(dev);
1685
1686         ctxt->bg_running = 0;
1687
1688         if (ctxt->bg_thread) {
1689                 kthread_stop(ctxt->bg_thread);
1690                 ctxt->bg_thread = NULL;
1691         }
1692 }
1693
1694 static void yaffs_write_super(struct super_block *sb)
1695 {
1696         unsigned request_checkpoint = (yaffs_auto_checkpoint >= 2);
1697
1698         yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC | YAFFS_TRACE_BACKGROUND,
1699                 "yaffs_write_super%s",
1700                 request_checkpoint ? " checkpt" : "");
1701
1702         yaffs_do_sync_fs(sb, request_checkpoint);
1703
1704 }
1705
1706 static int yaffs_sync_fs(struct super_block *sb, int wait)
1707 {
1708         unsigned request_checkpoint = (yaffs_auto_checkpoint >= 1);
1709
1710         yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_SYNC,
1711                 "yaffs_sync_fs%s", request_checkpoint ? " checkpt" : "");
1712
1713         yaffs_do_sync_fs(sb, request_checkpoint);
1714
1715         return 0;
1716 }
1717
1718 static LIST_HEAD(yaffs_context_list);
1719 struct mutex yaffs_context_lock;
1720
1721 struct yaffs_options {
1722         int inband_tags;
1723         int skip_checkpoint_read;
1724         int skip_checkpoint_write;
1725         int no_cache;
1726         int tags_ecc_on;
1727         int tags_ecc_overridden;
1728         int lazy_loading_enabled;
1729         int lazy_loading_overridden;
1730         int empty_lost_and_found;
1731         int empty_lost_and_found_overridden;
1732 };
1733
1734 #define MAX_OPT_LEN 30
1735 static int yaffs_parse_options(struct yaffs_options *options,
1736                                 const char *options_str)
1737 {
1738         char cur_opt[MAX_OPT_LEN + 1];
1739         int p;
1740         int error = 0;
1741
1742         /* Parse through the options which is a comma seperated list */
1743
1744         while (options_str && *options_str && !error) {
1745                 memset(cur_opt, 0, MAX_OPT_LEN + 1);
1746                 p = 0;
1747
1748                 while (*options_str == ',')
1749                         options_str++;
1750
1751                 while (*options_str && *options_str != ',') {
1752                         if (p < MAX_OPT_LEN) {
1753                                 cur_opt[p] = *options_str;
1754                                 p++;
1755                         }
1756                         options_str++;
1757                 }
1758
1759                 if (!strcmp(cur_opt, "inband-tags")) {
1760                         options->inband_tags = 1;
1761                 } else if (!strcmp(cur_opt, "tags-ecc-off")) {
1762                         options->tags_ecc_on = 0;
1763                         options->tags_ecc_overridden = 1;
1764                 } else if (!strcmp(cur_opt, "tags-ecc-on")) {
1765                         options->tags_ecc_on = 1;
1766                         options->tags_ecc_overridden = 1;
1767                 } else if (!strcmp(cur_opt, "lazy-loading-off")) {
1768                         options->lazy_loading_enabled = 0;
1769                         options->lazy_loading_overridden = 1;
1770                 } else if (!strcmp(cur_opt, "lazy-loading-on")) {
1771                         options->lazy_loading_enabled = 1;
1772                         options->lazy_loading_overridden = 1;
1773                 } else if (!strcmp(cur_opt, "empty-lost-and-found-off")) {
1774                         options->empty_lost_and_found = 0;
1775                         options->empty_lost_and_found_overridden = 1;
1776                 } else if (!strcmp(cur_opt, "empty-lost-and-found-on")) {
1777                         options->empty_lost_and_found = 1;
1778                         options->empty_lost_and_found_overridden = 1;
1779                 } else if (!strcmp(cur_opt, "no-cache")) {
1780                         options->no_cache = 1;
1781                 } else if (!strcmp(cur_opt, "no-checkpoint-read")) {
1782                         options->skip_checkpoint_read = 1;
1783                 } else if (!strcmp(cur_opt, "no-checkpoint-write")) {
1784                         options->skip_checkpoint_write = 1;
1785                 } else if (!strcmp(cur_opt, "no-checkpoint")) {
1786                         options->skip_checkpoint_read = 1;
1787                         options->skip_checkpoint_write = 1;
1788                 } else {
1789                         printk(KERN_INFO "yaffs: Bad mount option \"%s\"\n",
1790                                cur_opt);
1791                         error = 1;
1792                 }
1793         }
1794         return error;
1795 }
1796
1797 static const struct address_space_operations yaffs_file_address_operations = {
1798         .readpage = yaffs_readpage,
1799         .writepage = yaffs_writepage,
1800         .write_begin = yaffs_write_begin,
1801         .write_end = yaffs_write_end,
1802 };
1803
1804
1805
1806 static const struct inode_operations yaffs_file_inode_operations = {
1807         .setattr = yaffs_setattr,
1808         .setxattr = yaffs_setxattr,
1809         .getxattr = yaffs_getxattr,
1810         .listxattr = yaffs_listxattr,
1811         .removexattr = yaffs_removexattr,
1812 };
1813
1814 static const struct inode_operations yaffs_symlink_inode_operations = {
1815         .readlink = yaffs_readlink,
1816         .follow_link = yaffs_follow_link,
1817         .put_link = yaffs_put_link,
1818         .setattr = yaffs_setattr,
1819         .setxattr = yaffs_setxattr,
1820         .getxattr = yaffs_getxattr,
1821         .listxattr = yaffs_listxattr,
1822         .removexattr = yaffs_removexattr,
1823 };
1824
1825 static void yaffs_fill_inode_from_obj(struct inode *inode,
1826                                       struct yaffs_obj *obj)
1827 {
1828         u32 mode;
1829
1830         if (!inode || !obj)  {
1831                 yaffs_trace(YAFFS_TRACE_OS,
1832                         "yaffs_fill_inode invalid parameters");
1833                 return;
1834         }
1835
1836         /* Check mode against the variant type
1837          * and attempt to repair if broken. */
1838         mode = obj->yst_mode;
1839
1840         switch (obj->variant_type) {
1841         case YAFFS_OBJECT_TYPE_FILE:
1842                 if (!S_ISREG(mode)) {
1843                         obj->yst_mode &= ~S_IFMT;
1844                         obj->yst_mode |= S_IFREG;
1845                 }
1846                 break;
1847         case YAFFS_OBJECT_TYPE_SYMLINK:
1848                 if (!S_ISLNK(mode)) {
1849                         obj->yst_mode &= ~S_IFMT;
1850                         obj->yst_mode |= S_IFLNK;
1851                 }
1852                 break;
1853         case YAFFS_OBJECT_TYPE_DIRECTORY:
1854                 if (!S_ISDIR(mode)) {
1855                         obj->yst_mode &= ~S_IFMT;
1856                         obj->yst_mode |= S_IFDIR;
1857                 }
1858                 break;
1859         case YAFFS_OBJECT_TYPE_UNKNOWN:
1860         case YAFFS_OBJECT_TYPE_HARDLINK:
1861         case YAFFS_OBJECT_TYPE_SPECIAL:
1862         default:
1863                 /* TODO? */
1864                 break;
1865         }
1866
1867         inode->i_flags |= S_NOATIME;
1868         inode->i_ino = obj->obj_id;
1869         inode->i_mode = obj->yst_mode;
1870         inode->i_uid = obj->yst_uid;
1871         inode->i_gid = obj->yst_gid;
1872
1873         inode->i_rdev = old_decode_dev(obj->yst_rdev);
1874
1875         inode->i_atime.tv_sec = (time_t) (obj->yst_atime);
1876         inode->i_atime.tv_nsec = 0;
1877         inode->i_mtime.tv_sec = (time_t) obj->yst_mtime;
1878         inode->i_mtime.tv_nsec = 0;
1879         inode->i_ctime.tv_sec = (time_t) obj->yst_ctime;
1880         inode->i_ctime.tv_nsec = 0;
1881         inode->i_size = yaffs_get_obj_length(obj);
1882         inode->i_blocks = (inode->i_size + 511) >> 9;
1883         set_nlink(inode, yaffs_get_obj_link_count(obj));
1884         yaffs_trace(YAFFS_TRACE_OS,
1885                 "yaffs_fill_inode mode %x uid %d gid %d size %d count %d",
1886                 inode->i_mode, inode->i_uid, inode->i_gid,
1887                 (int)inode->i_size, atomic_read(&inode->i_count));
1888
1889         switch (obj->yst_mode & S_IFMT) {
1890         default:        /* fifo, device or socket */
1891                 init_special_inode(inode, obj->yst_mode,
1892                                    old_decode_dev(obj->yst_rdev));
1893                 break;
1894         case S_IFREG:   /* file */
1895                 inode->i_op = &yaffs_file_inode_operations;
1896                 inode->i_fop = &yaffs_file_operations;
1897                 inode->i_mapping->a_ops = &yaffs_file_address_operations;
1898                 break;
1899         case S_IFDIR:   /* directory */
1900                 inode->i_op = &yaffs_dir_inode_operations;
1901                 inode->i_fop = &yaffs_dir_operations;
1902                 break;
1903         case S_IFLNK:   /* symlink */
1904                 inode->i_op = &yaffs_symlink_inode_operations;
1905                 break;
1906         }
1907
1908         yaffs_inode_to_obj_lv(inode) = obj;
1909         obj->my_inode = inode;
1910 }
1911
1912 static void yaffs_put_super(struct super_block *sb)
1913 {
1914         struct yaffs_dev *dev = yaffs_super_to_dev(sb);
1915         struct mtd_info *mtd = yaffs_dev_to_mtd(dev);
1916
1917         yaffs_trace(YAFFS_TRACE_OS, "yaffs_put_super");
1918
1919         yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_BACKGROUND,
1920                 "Shutting down yaffs background thread");
1921         yaffs_bg_stop(dev);
1922         yaffs_trace(YAFFS_TRACE_OS | YAFFS_TRACE_BACKGROUND,
1923                 "yaffs background thread shut down");
1924
1925         yaffs_gross_lock(dev);
1926
1927         yaffs_flush_super(sb, 1);
1928
1929         if (yaffs_dev_to_lc(dev)->put_super_fn)
1930                 yaffs_dev_to_lc(dev)->put_super_fn(sb);
1931
1932         yaffs_deinitialise(dev);
1933
1934         yaffs_gross_unlock(dev);
1935         mutex_lock(&yaffs_context_lock);
1936         list_del_init(&(yaffs_dev_to_lc(dev)->context_list));
1937         mutex_unlock(&yaffs_context_lock);
1938
1939         if (yaffs_dev_to_lc(dev)->spare_buffer) {
1940                 kfree(yaffs_dev_to_lc(dev)->spare_buffer);
1941                 yaffs_dev_to_lc(dev)->spare_buffer = NULL;
1942         }
1943
1944         kfree(dev);
1945
1946
1947
1948         if (mtd && mtd->sync)
1949                 mtd->sync(mtd);
1950
1951         if (mtd)
1952                 put_mtd_device(mtd);
1953 }
1954
1955 static const struct super_operations yaffs_super_ops = {
1956         .statfs = yaffs_statfs,
1957         .put_super = yaffs_put_super,
1958         .evict_inode = yaffs_evict_inode,
1959         .sync_fs = yaffs_sync_fs,
1960         .write_super = yaffs_write_super,
1961 };
1962
1963 static struct super_block *yaffs_internal_read_super(int yaffs_version,
1964                                                      struct super_block *sb,
1965                                                      void *data, int silent)
1966 {
1967         int n_blocks;
1968         struct inode *inode = NULL;
1969         struct dentry *root;
1970         struct yaffs_dev *dev = 0;
1971         char devname_buf[BDEVNAME_SIZE + 1];
1972         struct mtd_info *mtd;
1973         int err;
1974         char *data_str = (char *)data;
1975         struct yaffs_linux_context *context = NULL;
1976         struct yaffs_param *param;
1977         int read_only = 0;
1978         struct yaffs_options options;
1979         unsigned mount_id;
1980         int found;
1981         struct yaffs_linux_context *context_iterator;
1982         struct list_head *l;
1983
1984         if (!sb) {
1985                 printk(KERN_INFO "yaffs: sb is NULL\n");
1986                 return NULL;
1987         }
1988
1989         sb->s_magic = YAFFS_MAGIC;
1990         sb->s_op = &yaffs_super_ops;
1991         sb->s_flags |= MS_NOATIME;
1992
1993         read_only = ((sb->s_flags & MS_RDONLY) != 0);
1994
1995         sb->s_export_op = &yaffs_export_ops;
1996
1997         if (!sb->s_dev)
1998                 printk(KERN_INFO "yaffs: sb->s_dev is NULL\n");
1999         else if (!yaffs_devname(sb, devname_buf))
2000                 printk(KERN_INFO "yaffs: devname is NULL\n");
2001         else
2002                 printk(KERN_INFO "yaffs: dev is %d name is \"%s\" %s\n",
2003                        sb->s_dev,
2004                        yaffs_devname(sb, devname_buf), read_only ? "ro" : "rw");
2005
2006         if (!data_str)
2007                 data_str = "";
2008
2009         printk(KERN_INFO "yaffs: passed flags \"%s\"\n", data_str);
2010
2011         memset(&options, 0, sizeof(options));
2012
2013         if (yaffs_parse_options(&options, data_str))
2014                 /* Option parsing failed */
2015                 return NULL;
2016
2017         sb->s_blocksize = PAGE_CACHE_SIZE;
2018         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
2019
2020         yaffs_trace(YAFFS_TRACE_OS,
2021                 "yaffs_read_super: Using yaffs%d", yaffs_version);
2022         yaffs_trace(YAFFS_TRACE_OS,
2023                 "yaffs_read_super: block size %d", (int)(sb->s_blocksize));
2024
2025         yaffs_trace(YAFFS_TRACE_ALWAYS,
2026                 "Attempting MTD mount of %u.%u,\"%s\"",
2027                 MAJOR(sb->s_dev), MINOR(sb->s_dev),
2028                 yaffs_devname(sb, devname_buf));
2029
2030         /* Check it's an mtd device..... */
2031         if (MAJOR(sb->s_dev) != MTD_BLOCK_MAJOR)
2032                 return NULL;    /* This isn't an mtd device */
2033
2034         /* Get the device */
2035         mtd = get_mtd_device(NULL, MINOR(sb->s_dev));
2036         if (IS_ERR(mtd)) {
2037                 yaffs_trace(YAFFS_TRACE_ALWAYS,
2038                         "MTD device #%u doesn't appear to exist",
2039                         MINOR(sb->s_dev));
2040                 return NULL;
2041         }
2042         /* Check it's NAND */
2043         if (mtd->type != MTD_NANDFLASH) {
2044                 yaffs_trace(YAFFS_TRACE_ALWAYS,
2045                         "MTD device is not NAND it's type %d",
2046                         mtd->type);
2047                 return NULL;
2048         }
2049
2050         yaffs_trace(YAFFS_TRACE_OS, " erase %p", mtd->erase);
2051         yaffs_trace(YAFFS_TRACE_OS, " read %p", mtd->read);
2052         yaffs_trace(YAFFS_TRACE_OS, " write %p", mtd->write);
2053         yaffs_trace(YAFFS_TRACE_OS, " readoob %p", mtd->read_oob);
2054         yaffs_trace(YAFFS_TRACE_OS, " writeoob %p", mtd->write_oob);
2055         yaffs_trace(YAFFS_TRACE_OS, " block_isbad %p", mtd->block_isbad);
2056         yaffs_trace(YAFFS_TRACE_OS, " block_markbad %p", mtd->block_markbad);
2057         yaffs_trace(YAFFS_TRACE_OS, " writesize %d", mtd->writesize);
2058         yaffs_trace(YAFFS_TRACE_OS, " oobsize %d", mtd->oobsize);
2059         yaffs_trace(YAFFS_TRACE_OS, " erasesize %d", mtd->erasesize);
2060         yaffs_trace(YAFFS_TRACE_OS, " size %lld", mtd->size);
2061
2062         if (yaffs_auto_select && yaffs_version == 1 && mtd->writesize >= 2048) {
2063                 yaffs_trace(YAFFS_TRACE_ALWAYS, "auto selecting yaffs2");
2064                 yaffs_version = 2;
2065         }
2066
2067         if (yaffs_auto_select && yaffs_version == 2 && !options.inband_tags &&
2068                 mtd->writesize == 512) {
2069                 yaffs_trace(YAFFS_TRACE_ALWAYS, "auto selecting yaffs1");
2070                 yaffs_version = 1;
2071         }
2072
2073         if (yaffs_version == 2) {
2074                 /* Check for version 2 style functions */
2075                 if (!mtd->erase ||
2076                     !mtd->block_isbad ||
2077                     !mtd->block_markbad ||
2078                     !mtd->read ||
2079                     !mtd->write || !mtd->read_oob || !mtd->write_oob) {
2080                         yaffs_trace(YAFFS_TRACE_ALWAYS,
2081                                 "MTD device does not support required functions");
2082                         return NULL;
2083                 }
2084
2085                 if ((mtd->writesize < YAFFS_MIN_YAFFS2_CHUNK_SIZE ||
2086                      mtd->oobsize < YAFFS_MIN_YAFFS2_SPARE_SIZE) &&
2087                     !options.inband_tags) {
2088                         yaffs_trace(YAFFS_TRACE_ALWAYS,
2089                                 "MTD device does not have the right page sizes");
2090                         return NULL;
2091                 }
2092         } else {
2093                 /* Check for V1 style functions */
2094                 if (!mtd->erase ||
2095                     !mtd->read ||
2096                     !mtd->write || !mtd->read_oob || !mtd->write_oob) {
2097                         yaffs_trace(YAFFS_TRACE_ALWAYS,
2098                                 "MTD device does not support required functions");
2099                         return NULL;
2100                 }
2101
2102                 if (mtd->writesize < YAFFS_BYTES_PER_CHUNK ||
2103                     mtd->oobsize != YAFFS_BYTES_PER_SPARE) {
2104                         yaffs_trace(YAFFS_TRACE_ALWAYS,
2105                                 "MTD device does not support have the right page sizes");
2106                         return NULL;
2107                 }
2108         }
2109
2110         /* OK, so if we got here, we have an MTD that's NAND and looks
2111          * like it has the right capabilities
2112          * Set the struct yaffs_dev up for mtd
2113          */
2114
2115         if (!read_only && !(mtd->flags & MTD_WRITEABLE)) {
2116                 read_only = 1;
2117                 printk(KERN_INFO
2118                        "yaffs: mtd is read only, setting superblock read only");
2119                 sb->s_flags |= MS_RDONLY;
2120         }
2121
2122         dev = kmalloc(sizeof(struct yaffs_dev), GFP_KERNEL);
2123         context = kmalloc(sizeof(struct yaffs_linux_context), GFP_KERNEL);
2124
2125         if (!dev || !context) {
2126                 kfree(dev);
2127                 kfree(context);
2128                 dev = NULL;
2129                 context = NULL;
2130
2131                 /* Deep shit could not allocate device structure */
2132                 yaffs_trace(YAFFS_TRACE_ALWAYS,
2133                         "yaffs_read_super failed trying to allocate yaffs_dev");
2134                 return NULL;
2135         }
2136         memset(dev, 0, sizeof(struct yaffs_dev));
2137         param = &(dev->param);
2138
2139         memset(context, 0, sizeof(struct yaffs_linux_context));
2140         dev->os_context = context;
2141         INIT_LIST_HEAD(&(context->context_list));
2142         context->dev = dev;
2143         context->super = sb;
2144
2145         dev->read_only = read_only;
2146
2147         sb->s_fs_info = dev;
2148
2149         dev->driver_context = mtd;
2150         param->name = mtd->name;
2151
2152         /* Set up the memory size parameters.... */
2153
2154         n_blocks =
2155             YCALCBLOCKS(mtd->size,
2156                         (YAFFS_CHUNKS_PER_BLOCK * YAFFS_BYTES_PER_CHUNK));
2157
2158         param->start_block = 0;
2159         param->end_block = n_blocks - 1;
2160         param->chunks_per_block = YAFFS_CHUNKS_PER_BLOCK;
2161         param->total_bytes_per_chunk = YAFFS_BYTES_PER_CHUNK;
2162         param->n_reserved_blocks = 5;
2163         param->n_caches = (options.no_cache) ? 0 : 10;
2164         param->inband_tags = options.inband_tags;
2165
2166         param->disable_lazy_load = 1;
2167         param->enable_xattr = 1;
2168         if (options.lazy_loading_overridden)
2169                 param->disable_lazy_load = !options.lazy_loading_enabled;
2170
2171         param->defered_dir_update = 1;
2172
2173         if (options.tags_ecc_overridden)
2174                 param->no_tags_ecc = !options.tags_ecc_on;
2175
2176         param->empty_lost_n_found = 1;
2177
2178         param->refresh_period = 500;
2179
2180         if (options.empty_lost_and_found_overridden)
2181                 param->empty_lost_n_found = options.empty_lost_and_found;
2182
2183         /* ... and the functions. */
2184         if (yaffs_version == 2) {
2185                 param->write_chunk_tags_fn = nandmtd2_write_chunk_tags;
2186                 param->read_chunk_tags_fn = nandmtd2_read_chunk_tags;
2187                 param->bad_block_fn = nandmtd2_mark_block_bad;
2188                 param->query_block_fn = nandmtd2_query_block;
2189                 yaffs_dev_to_lc(dev)->spare_buffer =
2190                                 kmalloc(mtd->oobsize, GFP_NOFS);
2191                 param->is_yaffs2 = 1;
2192                 param->total_bytes_per_chunk = mtd->writesize;
2193                 param->chunks_per_block = mtd->erasesize / mtd->writesize;
2194                 n_blocks = YCALCBLOCKS(mtd->size, mtd->erasesize);
2195
2196                 param->start_block = 0;
2197                 param->end_block = n_blocks - 1;
2198         } else {
2199                 /* use the MTD interface in yaffs_mtdif1.c */
2200                 param->write_chunk_tags_fn = nandmtd1_write_chunk_tags;
2201                 param->read_chunk_tags_fn = nandmtd1_read_chunk_tags;
2202                 param->bad_block_fn = nandmtd1_mark_block_bad;
2203                 param->query_block_fn = nandmtd1_query_block;
2204                 param->is_yaffs2 = 0;
2205         }
2206         /* ... and common functions */
2207         param->erase_fn = nandmtd_erase_block;
2208         param->initialise_flash_fn = nandmtd_initialise;
2209
2210         yaffs_dev_to_lc(dev)->put_super_fn = yaffs_mtd_put_super;
2211
2212         param->sb_dirty_fn = yaffs_touch_super;
2213         param->gc_control_fn = yaffs_gc_control_callback;
2214
2215         yaffs_dev_to_lc(dev)->super = sb;
2216
2217         param->use_nand_ecc = 1;
2218
2219         param->skip_checkpt_rd = options.skip_checkpoint_read;
2220         param->skip_checkpt_wr = options.skip_checkpoint_write;
2221
2222         mutex_lock(&yaffs_context_lock);
2223         /* Get a mount id */
2224         for (mount_id = 0, found = 0; !found; mount_id++) {
2225                 found = 1;
2226                 list_for_each(l, &yaffs_context_list) {
2227                         context_iterator =
2228                                 list_entry(l, struct yaffs_linux_context,
2229                                         context_list);
2230                         if (context_iterator->mount_id == mount_id)
2231                                 found = 0;
2232                 }
2233         }
2234         context->mount_id = mount_id;
2235
2236         list_add_tail(&(yaffs_dev_to_lc(dev)->context_list),
2237                       &yaffs_context_list);
2238         mutex_unlock(&yaffs_context_lock);
2239
2240         /* Directory search handling... */
2241         INIT_LIST_HEAD(&(yaffs_dev_to_lc(dev)->search_contexts));
2242         param->remove_obj_fn = yaffs_remove_obj_callback;
2243
2244         mutex_init(&(yaffs_dev_to_lc(dev)->gross_lock));
2245
2246         yaffs_gross_lock(dev);
2247
2248         err = yaffs_guts_initialise(dev);
2249
2250         yaffs_trace(YAFFS_TRACE_OS,
2251                 "yaffs_read_super: guts initialised %s",
2252                 (err == YAFFS_OK) ? "OK" : "FAILED");
2253
2254         if (err == YAFFS_OK)
2255                 yaffs_bg_start(dev);
2256
2257         if (!context->bg_thread)
2258                 param->defered_dir_update = 0;
2259
2260         sb->s_maxbytes = yaffs_max_file_size(dev);
2261
2262         /* Release lock before yaffs_get_inode() */
2263         yaffs_gross_unlock(dev);
2264
2265         /* Create root inode */
2266         if (err == YAFFS_OK)
2267                 inode = yaffs_get_inode(sb, S_IFDIR | 0755, 0, yaffs_root(dev));
2268
2269         if (!inode)
2270                 return NULL;
2271
2272         inode->i_op = &yaffs_dir_inode_operations;
2273         inode->i_fop = &yaffs_dir_operations;
2274
2275         yaffs_trace(YAFFS_TRACE_OS, "yaffs_read_super: got root inode");
2276
2277         root = d_alloc_root(inode);
2278
2279         yaffs_trace(YAFFS_TRACE_OS, "yaffs_read_super: d_alloc_root done");
2280
2281         if (!root) {
2282                 iput(inode);
2283                 return NULL;
2284         }
2285         sb->s_root = root;
2286         sb->s_dirt = !dev->is_checkpointed;
2287         yaffs_trace(YAFFS_TRACE_ALWAYS,
2288                 "yaffs_read_super: is_checkpointed %d",
2289                 dev->is_checkpointed);
2290
2291         yaffs_trace(YAFFS_TRACE_OS, "yaffs_read_super: done");
2292         return sb;
2293 }
2294
2295 static int yaffs_internal_read_super_mtd(struct super_block *sb, void *data,
2296                                          int silent)
2297 {
2298         return yaffs_internal_read_super(1, sb, data, silent) ? 0 : -EINVAL;
2299 }
2300
2301 static struct dentry *yaffs_mount(struct file_system_type *fs,
2302                             int flags, const char *dev_name,
2303                             void *data)
2304 {
2305         return mount_bdev(fs, flags, dev_name, data,
2306                            yaffs_internal_read_super_mtd);
2307 }
2308
2309 static struct file_system_type yaffs_fs_type = {
2310         .owner = THIS_MODULE,
2311         .name = "yaffs",
2312         .mount = yaffs_mount,
2313         .kill_sb = kill_block_super,
2314         .fs_flags = FS_REQUIRES_DEV,
2315 };
2316
2317 static int yaffs2_internal_read_super_mtd(struct super_block *sb, void *data,
2318                                           int silent)
2319 {
2320         return yaffs_internal_read_super(2, sb, data, silent) ? 0 : -EINVAL;
2321 }
2322
2323 static struct dentry *yaffs2_mount(struct file_system_type *fs,
2324                              int flags, const char *dev_name, void *data)
2325 {
2326         return mount_bdev(fs, flags, dev_name, data,
2327                            yaffs2_internal_read_super_mtd);
2328 }
2329
2330 static struct file_system_type yaffs2_fs_type = {
2331         .owner = THIS_MODULE,
2332         .name = "yaffs2",
2333         .mount = yaffs2_mount,
2334         .kill_sb = kill_block_super,
2335         .fs_flags = FS_REQUIRES_DEV,
2336 };
2337
2338
2339 static struct proc_dir_entry *my_proc_entry;
2340
2341 static char *yaffs_dump_dev_part0(char *buf, struct yaffs_dev *dev)
2342 {
2343         struct yaffs_param *param = &dev->param;
2344
2345         buf += sprintf(buf, "start_block........... %d\n", param->start_block);
2346         buf += sprintf(buf, "end_block............. %d\n", param->end_block);
2347         buf += sprintf(buf, "total_bytes_per_chunk. %d\n",
2348                         param->total_bytes_per_chunk);
2349         buf += sprintf(buf, "use_nand_ecc.......... %d\n",
2350                         param->use_nand_ecc);
2351         buf += sprintf(buf, "no_tags_ecc........... %d\n", param->no_tags_ecc);
2352         buf += sprintf(buf, "is_yaffs2............. %d\n", param->is_yaffs2);
2353         buf += sprintf(buf, "inband_tags........... %d\n", param->inband_tags);
2354         buf += sprintf(buf, "empty_lost_n_found.... %d\n",
2355                         param->empty_lost_n_found);
2356         buf += sprintf(buf, "disable_lazy_load..... %d\n",
2357                         param->disable_lazy_load);
2358         buf += sprintf(buf, "refresh_period........ %d\n",
2359                         param->refresh_period);
2360         buf += sprintf(buf, "n_caches.............. %d\n", param->n_caches);
2361         buf += sprintf(buf, "n_reserved_blocks..... %d\n",
2362                         param->n_reserved_blocks);
2363         buf += sprintf(buf, "always_check_erased... %d\n",
2364                         param->always_check_erased);
2365
2366         return buf;
2367 }
2368
2369 static char *yaffs_dump_dev_part1(char *buf, struct yaffs_dev *dev)
2370 {
2371         buf += sprintf(buf, "max file size......... %lld\n",
2372                         (long long) yaffs_max_file_size(dev));
2373         buf += sprintf(buf, "data_bytes_per_chunk.. %d\n",
2374                         dev->data_bytes_per_chunk);
2375         buf += sprintf(buf, "chunk_grp_bits........ %d\n", dev->chunk_grp_bits);
2376         buf += sprintf(buf, "chunk_grp_size........ %d\n", dev->chunk_grp_size);
2377         buf +=
2378             sprintf(buf, "n_erased_blocks....... %d\n", dev->n_erased_blocks);
2379         buf +=
2380             sprintf(buf, "blocks_in_checkpt..... %d\n", dev->blocks_in_checkpt);
2381         buf += sprintf(buf, "\n");
2382         buf += sprintf(buf, "n_tnodes.............. %d\n", dev->n_tnodes);
2383         buf += sprintf(buf, "n_obj................. %d\n", dev->n_obj);
2384         buf += sprintf(buf, "n_free_chunks......... %d\n", dev->n_free_chunks);
2385         buf += sprintf(buf, "\n");
2386         buf += sprintf(buf, "n_page_writes......... %u\n", dev->n_page_writes);
2387         buf += sprintf(buf, "n_page_reads.......... %u\n", dev->n_page_reads);
2388         buf += sprintf(buf, "n_erasures............ %u\n", dev->n_erasures);
2389         buf += sprintf(buf, "n_gc_copies........... %u\n", dev->n_gc_copies);
2390         buf += sprintf(buf, "all_gcs............... %u\n", dev->all_gcs);
2391         buf +=
2392             sprintf(buf, "passive_gc_count...... %u\n", dev->passive_gc_count);
2393         buf +=
2394             sprintf(buf, "oldest_dirty_gc_count. %u\n",
2395                     dev->oldest_dirty_gc_count);
2396         buf += sprintf(buf, "n_gc_blocks........... %u\n", dev->n_gc_blocks);
2397         buf += sprintf(buf, "bg_gcs................ %u\n", dev->bg_gcs);
2398         buf +=
2399             sprintf(buf, "n_retried_writes...... %u\n", dev->n_retried_writes);
2400         buf +=
2401             sprintf(buf, "n_retired_blocks...... %u\n", dev->n_retired_blocks);
2402         buf += sprintf(buf, "n_ecc_fixed........... %u\n", dev->n_ecc_fixed);
2403         buf += sprintf(buf, "n_ecc_unfixed......... %u\n", dev->n_ecc_unfixed);
2404         buf +=
2405             sprintf(buf, "n_tags_ecc_fixed...... %u\n", dev->n_tags_ecc_fixed);
2406         buf +=
2407             sprintf(buf, "n_tags_ecc_unfixed.... %u\n",
2408                     dev->n_tags_ecc_unfixed);
2409         buf += sprintf(buf, "cache_hits............ %u\n", dev->cache_hits);
2410         buf +=
2411             sprintf(buf, "n_deleted_files....... %u\n", dev->n_deleted_files);
2412         buf +=
2413             sprintf(buf, "n_unlinked_files...... %u\n", dev->n_unlinked_files);
2414         buf += sprintf(buf, "refresh_count......... %u\n", dev->refresh_count);
2415         buf += sprintf(buf, "n_bg_deletions........ %u\n", dev->n_bg_deletions);
2416
2417         return buf;
2418 }
2419
2420 static int yaffs_proc_read(char *page,
2421                            char **start,
2422                            off_t offset, int count, int *eof, void *data)
2423 {
2424         struct list_head *item;
2425         char *buf = page;
2426         int step = offset;
2427         int n = 0;
2428
2429         /* Get proc_file_read() to step 'offset' by one on each sucessive call.
2430          * We use 'offset' (*ppos) to indicate where we are in dev_list.
2431          * This also assumes the user has posted a read buffer large
2432          * enough to hold the complete output; but that's life in /proc.
2433          */
2434
2435         *(int *)start = 1;
2436
2437         /* Print header first */
2438         if (step == 0)
2439                 buf += sprintf(buf, "YAFFS built:" __DATE__ " " __TIME__ "\n");
2440         else if (step == 1)
2441                 buf += sprintf(buf, "\n");
2442         else {
2443                 step -= 2;
2444
2445                 mutex_lock(&yaffs_context_lock);
2446
2447                 /* Locate and print the Nth entry.
2448                  * Order N-squared but N is small. */
2449                 list_for_each(item, &yaffs_context_list) {
2450                         struct yaffs_linux_context *dc =
2451                             list_entry(item, struct yaffs_linux_context,
2452                                        context_list);
2453                         struct yaffs_dev *dev = dc->dev;
2454
2455                         if (n < (step & ~1)) {
2456                                 n += 2;
2457                                 continue;
2458                         }
2459                         if ((step & 1) == 0) {
2460                                 buf +=
2461                                     sprintf(buf, "\nDevice %d \"%s\"\n", n,
2462                                             dev->param.name);
2463                                 buf = yaffs_dump_dev_part0(buf, dev);
2464                         } else {
2465                                 buf = yaffs_dump_dev_part1(buf, dev);
2466                         }
2467
2468                         break;
2469                 }
2470                 mutex_unlock(&yaffs_context_lock);
2471         }
2472
2473         return buf - page < count ? buf - page : count;
2474 }
2475
2476
2477
2478 /* Stuff to handle installation of file systems */
2479 struct file_system_to_install {
2480         struct file_system_type *fst;
2481         int installed;
2482 };
2483
2484 static struct file_system_to_install fs_to_install[] = {
2485         {&yaffs_fs_type, 0},
2486         {&yaffs2_fs_type, 0},
2487         {NULL, 0}
2488 };
2489
2490 static int __init init_yaffs_fs(void)
2491 {
2492         int error = 0;
2493         struct file_system_to_install *fsinst;
2494
2495         yaffs_trace(YAFFS_TRACE_ALWAYS,
2496                 "yaffs built " __DATE__ " " __TIME__ " Installing.");
2497
2498         mutex_init(&yaffs_context_lock);
2499
2500         /* Install the proc_fs entries */
2501         my_proc_entry = create_proc_entry("yaffs",
2502                                           S_IRUGO | S_IFREG, NULL);
2503
2504         if (my_proc_entry) {
2505                 my_proc_entry->write_proc = NULL;
2506                 my_proc_entry->read_proc = yaffs_proc_read;
2507                 my_proc_entry->data = NULL;
2508         } else {
2509                 return -ENOMEM;
2510         }
2511
2512
2513         /* Now add the file system entries */
2514
2515         fsinst = fs_to_install;
2516
2517         while (fsinst->fst && !error) {
2518                 error = register_filesystem(fsinst->fst);
2519                 if (!error)
2520                         fsinst->installed = 1;
2521                 fsinst++;
2522         }
2523
2524         /* Any errors? uninstall  */
2525         if (error) {
2526                 fsinst = fs_to_install;
2527
2528                 while (fsinst->fst) {
2529                         if (fsinst->installed) {
2530                                 unregister_filesystem(fsinst->fst);
2531                                 fsinst->installed = 0;
2532                         }
2533                         fsinst++;
2534                 }
2535         }
2536
2537         return error;
2538 }
2539
2540 static void __exit exit_yaffs_fs(void)
2541 {
2542
2543         struct file_system_to_install *fsinst;
2544
2545         yaffs_trace(YAFFS_TRACE_ALWAYS,
2546                 "yaffs built " __DATE__ " " __TIME__ " removing.");
2547
2548         remove_proc_entry("yaffs", NULL);
2549
2550         fsinst = fs_to_install;
2551
2552         while (fsinst->fst) {
2553                 if (fsinst->installed) {
2554                         unregister_filesystem(fsinst->fst);
2555                         fsinst->installed = 0;
2556                 }
2557                 fsinst++;
2558         }
2559 }
2560
2561 module_init(init_yaffs_fs)
2562 module_exit(exit_yaffs_fs)
2563
2564 MODULE_DESCRIPTION("YAFFS2 - a NAND specific flash file system");
2565 MODULE_AUTHOR("Charles Manning, Aleph One Ltd., 2002-2011");
2566 MODULE_LICENSE("GPL");