OpenCores
URL https://opencores.org/ocsvn/or1k/or1k/trunk

Subversion Repositories or1k

[/] [or1k/] [trunk/] [linux/] [linux-2.4/] [fs/] [ext3/] [inode.c] - Blame information for rev 1765

Details | Compare with Previous | View Log

Line No. Rev Author Line
1 1275 phoenix
/*
2
 *  linux/fs/ext3/inode.c
3
 *
4
 * Copyright (C) 1992, 1993, 1994, 1995
5
 * Remy Card (card@masi.ibp.fr)
6
 * Laboratoire MASI - Institut Blaise Pascal
7
 * Universite Pierre et Marie Curie (Paris VI)
8
 *
9
 *  from
10
 *
11
 *  linux/fs/minix/inode.c
12
 *
13
 *  Copyright (C) 1991, 1992  Linus Torvalds
14
 *
15
 *  Goal-directed block allocation by Stephen Tweedie
16
 *      (sct@redhat.com), 1993, 1998
17
 *  Big-endian to little-endian byte-swapping/bitmaps by
18
 *        David S. Miller (davem@caip.rutgers.edu), 1995
19
 *  64-bit file support on 64-bit platforms by Jakub Jelinek
20
 *      (jj@sunsite.ms.mff.cuni.cz)
21
 *
22
 *  Assorted race fixes, rewrite of ext3_get_block() by Al Viro, 2000
23
 */
24
 
25
#include <linux/fs.h>
26
#include <linux/sched.h>
27
#include <linux/ext3_jbd.h>
28
#include <linux/jbd.h>
29
#include <linux/locks.h>
30
#include <linux/smp_lock.h>
31
#include <linux/highuid.h>
32
#include <linux/quotaops.h>
33
#include <linux/module.h>
34
 
35
/*
36
 * SEARCH_FROM_ZERO forces each block allocation to search from the start
37
 * of the filesystem.  This is to force rapid reallocation of recently-freed
38
 * blocks.  The file fragmentation is horrendous.
39
 */
40
#undef SEARCH_FROM_ZERO
41
 
42
/*
43
 * Test whether an inode is a fast symlink.
44
 */
45
static inline int ext3_inode_is_fast_symlink(struct inode *inode)
46
{
47
        int ea_blocks = EXT3_I(inode)->i_file_acl ?
48
                (inode->i_sb->s_blocksize >> 9) : 0;
49
 
50
        return (S_ISLNK(inode->i_mode) &&
51
                inode->i_blocks - ea_blocks == 0);
52
}
53
 
54
/* The ext3 forget function must perform a revoke if we are freeing data
55
 * which has been journaled.  Metadata (eg. indirect blocks) must be
56
 * revoked in all cases.
57
 *
58
 * "bh" may be NULL: a metadata block may have been freed from memory
59
 * but there may still be a record of it in the journal, and that record
60
 * still needs to be revoked.
61
 */
62
 
63
static int ext3_forget(handle_t *handle, int is_metadata,
64
                       struct inode *inode, struct buffer_head *bh,
65
                       int blocknr)
66
{
67
        int err;
68
 
69
        BUFFER_TRACE(bh, "enter");
70
 
71
        jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
72
                  "data mode %lx\n",
73
                  bh, is_metadata, inode->i_mode,
74
                  test_opt(inode->i_sb, DATA_FLAGS));
75
 
76
        /* Never use the revoke function if we are doing full data
77
         * journaling: there is no need to, and a V1 superblock won't
78
         * support it.  Otherwise, only skip the revoke on un-journaled
79
         * data blocks. */
80
 
81
        if (test_opt(inode->i_sb, DATA_FLAGS) == EXT3_MOUNT_JOURNAL_DATA ||
82
            (!is_metadata && !ext3_should_journal_data(inode))) {
83
                if (bh) {
84
                        BUFFER_TRACE(bh, "call journal_forget");
85
                        ext3_journal_forget(handle, bh);
86
                }
87
                return 0;
88
        }
89
 
90
        /*
91
         * data!=journal && (is_metadata || should_journal_data(inode))
92
         */
93
        BUFFER_TRACE(bh, "call ext3_journal_revoke");
94
        err = ext3_journal_revoke(handle, blocknr, bh);
95
        if (err)
96
                ext3_abort(inode->i_sb, __FUNCTION__,
97
                           "error %d when attempting revoke", err);
98
        BUFFER_TRACE(bh, "exit");
99
        return err;
100
}
101
 
102
/*
103
 * Work out how many blocks we need to progress with the next chunk of a
104
 * truncate transaction.
105
 */
106
 
107
static unsigned long blocks_for_truncate(struct inode *inode)
108
{
109
        unsigned long needed;
110
 
111
        needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
112
 
113
        /* Give ourselves just enough room to cope with inodes in which
114
         * i_blocks is corrupt: we've seen disk corruptions in the past
115
         * which resulted in random data in an inode which looked enough
116
         * like a regular file for ext3 to try to delete it.  Things
117
         * will go a bit crazy if that happens, but at least we should
118
         * try not to panic the whole kernel. */
119
        if (needed < 2)
120
                needed = 2;
121
 
122
        /* But we need to bound the transaction so we don't overflow the
123
         * journal. */
124
        if (needed > EXT3_MAX_TRANS_DATA)
125
                needed = EXT3_MAX_TRANS_DATA;
126
 
127
        return EXT3_DATA_TRANS_BLOCKS + needed;
128
}
129
 
130
/*
131
 * Truncate transactions can be complex and absolutely huge.  So we need to
132
 * be able to restart the transaction at a conventient checkpoint to make
133
 * sure we don't overflow the journal.
134
 *
135
 * start_transaction gets us a new handle for a truncate transaction,
136
 * and extend_transaction tries to extend the existing one a bit.  If
137
 * extend fails, we need to propagate the failure up and restart the
138
 * transaction in the top-level truncate loop. --sct
139
 */
140
 
141
static handle_t *start_transaction(struct inode *inode)
142
{
143
        handle_t *result;
144
 
145
        result = ext3_journal_start(inode, blocks_for_truncate(inode));
146
        if (!IS_ERR(result))
147
                return result;
148
 
149
        ext3_std_error(inode->i_sb, PTR_ERR(result));
150
        return result;
151
}
152
 
153
/*
154
 * Try to extend this transaction for the purposes of truncation.
155
 *
156
 * Returns 0 if we managed to create more room.  If we can't create more
157
 * room, and the transaction must be restarted we return 1.
158
 */
159
static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
160
{
161
        if (handle->h_buffer_credits > EXT3_RESERVE_TRANS_BLOCKS)
162
                return 0;
163
        if (!ext3_journal_extend(handle, blocks_for_truncate(inode)))
164
                return 0;
165
        return 1;
166
}
167
 
168
/*
169
 * Restart the transaction associated with *handle.  This does a commit,
170
 * so before we call here everything must be consistently dirtied against
171
 * this transaction.
172
 */
173
static int ext3_journal_test_restart(handle_t *handle, struct inode *inode)
174
{
175
        jbd_debug(2, "restarting handle %p\n", handle);
176
        return ext3_journal_restart(handle, blocks_for_truncate(inode));
177
}
178
 
179
/*
180
 * Called at each iput()
181
 */
182
void ext3_put_inode (struct inode * inode)
183
{
184
        ext3_discard_prealloc (inode);
185
}
186
 
187
/*
188
 * Called at the last iput() if i_nlink is zero.
189
 */
190
void ext3_delete_inode (struct inode * inode)
191
{
192
        handle_t *handle;
193
 
194
        if (is_bad_inode(inode) ||
195
            inode->i_ino == EXT3_ACL_IDX_INO ||
196
            inode->i_ino == EXT3_ACL_DATA_INO)
197
                goto no_delete;
198
 
199
        lock_kernel();
200
        handle = start_transaction(inode);
201
        if (IS_ERR(handle)) {
202
                /* If we're going to skip the normal cleanup, we still
203
                 * need to make sure that the in-core orphan linked list
204
                 * is properly cleaned up. */
205
                ext3_orphan_del(NULL, inode);
206
 
207
                ext3_std_error(inode->i_sb, PTR_ERR(handle));
208
                unlock_kernel();
209
                goto no_delete;
210
        }
211
 
212
        if (IS_SYNC(inode))
213
                handle->h_sync = 1;
214
        inode->i_size = 0;
215
        if (inode->i_blocks)
216
                ext3_truncate(inode);
217
        /*
218
         * Kill off the orphan record which ext3_truncate created.
219
         * AKPM: I think this can be inside the above `if'.
220
         * Note that ext3_orphan_del() has to be able to cope with the
221
         * deletion of a non-existent orphan - this is because we don't
222
         * know if ext3_truncate() actually created an orphan record.
223
         * (Well, we could do this if we need to, but heck - it works)
224
         */
225
        ext3_orphan_del(handle, inode);
226
        inode->u.ext3_i.i_dtime = CURRENT_TIME;
227
 
228
        /*
229
         * One subtle ordering requirement: if anything has gone wrong
230
         * (transaction abort, IO errors, whatever), then we can still
231
         * do these next steps (the fs will already have been marked as
232
         * having errors), but we can't free the inode if the mark_dirty
233
         * fails.
234
         */
235
        if (ext3_mark_inode_dirty(handle, inode))
236
                /* If that failed, just do the required in-core inode clear. */
237
                clear_inode(inode);
238
        else
239
                ext3_free_inode(handle, inode);
240
        ext3_journal_stop(handle, inode);
241
        unlock_kernel();
242
        return;
243
no_delete:
244
        clear_inode(inode);     /* We must guarantee clearing of inode... */
245
}
246
 
247
void ext3_discard_prealloc (struct inode * inode)
248
{
249
#ifdef EXT3_PREALLOCATE
250
        lock_kernel();
251
        /* Writer: ->i_prealloc* */
252
        if (inode->u.ext3_i.i_prealloc_count) {
253
                unsigned short total = inode->u.ext3_i.i_prealloc_count;
254
                unsigned long block = inode->u.ext3_i.i_prealloc_block;
255
                inode->u.ext3_i.i_prealloc_count = 0;
256
                inode->u.ext3_i.i_prealloc_block = 0;
257
                /* Writer: end */
258
                ext3_free_blocks (inode, block, total);
259
        }
260
        unlock_kernel();
261
#endif
262
}
263
 
264
static int ext3_alloc_block (handle_t *handle,
265
                        struct inode * inode, unsigned long goal, int *err)
266
{
267
#ifdef EXT3FS_DEBUG
268
        static unsigned long alloc_hits = 0, alloc_attempts = 0;
269
#endif
270
        unsigned long result;
271
 
272
#ifdef EXT3_PREALLOCATE
273
        /* Writer: ->i_prealloc* */
274
        if (inode->u.ext3_i.i_prealloc_count &&
275
            (goal == inode->u.ext3_i.i_prealloc_block ||
276
             goal + 1 == inode->u.ext3_i.i_prealloc_block))
277
        {
278
                result = inode->u.ext3_i.i_prealloc_block++;
279
                inode->u.ext3_i.i_prealloc_count--;
280
                /* Writer: end */
281
                ext3_debug ("preallocation hit (%lu/%lu).\n",
282
                            ++alloc_hits, ++alloc_attempts);
283
        } else {
284
                ext3_discard_prealloc (inode);
285
                ext3_debug ("preallocation miss (%lu/%lu).\n",
286
                            alloc_hits, ++alloc_attempts);
287
                if (S_ISREG(inode->i_mode))
288
                        result = ext3_new_block (inode, goal,
289
                                 &inode->u.ext3_i.i_prealloc_count,
290
                                 &inode->u.ext3_i.i_prealloc_block, err);
291
                else
292
                        result = ext3_new_block (inode, goal, 0, 0, err);
293
                /*
294
                 * AKPM: this is somewhat sticky.  I'm not surprised it was
295
                 * disabled in 2.2's ext3.  Need to integrate b_committed_data
296
                 * guarding with preallocation, if indeed preallocation is
297
                 * effective.
298
                 */
299
        }
300
#else
301
        result = ext3_new_block (handle, inode, goal, 0, 0, err);
302
#endif
303
        return result;
304
}
305
 
306
 
307
typedef struct {
308
        u32     *p;
309
        u32     key;
310
        struct buffer_head *bh;
311
} Indirect;
312
 
313
static inline void add_chain(Indirect *p, struct buffer_head *bh, u32 *v)
314
{
315
        p->key = *(p->p = v);
316
        p->bh = bh;
317
}
318
 
319
static inline int verify_chain(Indirect *from, Indirect *to)
320
{
321
        while (from <= to && from->key == *from->p)
322
                from++;
323
        return (from > to);
324
}
325
 
326
/**
327
 *      ext3_block_to_path - parse the block number into array of offsets
328
 *      @inode: inode in question (we are only interested in its superblock)
329
 *      @i_block: block number to be parsed
330
 *      @offsets: array to store the offsets in
331
 *
332
 *      To store the locations of file's data ext3 uses a data structure common
333
 *      for UNIX filesystems - tree of pointers anchored in the inode, with
334
 *      data blocks at leaves and indirect blocks in intermediate nodes.
335
 *      This function translates the block number into path in that tree -
336
 *      return value is the path length and @offsets[n] is the offset of
337
 *      pointer to (n+1)th node in the nth one. If @block is out of range
338
 *      (negative or too large) warning is printed and zero returned.
339
 *
340
 *      Note: function doesn't find node addresses, so no IO is needed. All
341
 *      we need to know is the capacity of indirect blocks (taken from the
342
 *      inode->i_sb).
343
 */
344
 
345
/*
346
 * Portability note: the last comparison (check that we fit into triple
347
 * indirect block) is spelled differently, because otherwise on an
348
 * architecture with 32-bit longs and 8Kb pages we might get into trouble
349
 * if our filesystem had 8Kb blocks. We might use long long, but that would
350
 * kill us on x86. Oh, well, at least the sign propagation does not matter -
351
 * i_block would have to be negative in the very beginning, so we would not
352
 * get there at all.
353
 */
354
 
355
static int ext3_block_to_path(struct inode *inode, long i_block, int offsets[4])
356
{
357
        int ptrs = EXT3_ADDR_PER_BLOCK(inode->i_sb);
358
        int ptrs_bits = EXT3_ADDR_PER_BLOCK_BITS(inode->i_sb);
359
        const long direct_blocks = EXT3_NDIR_BLOCKS,
360
                indirect_blocks = ptrs,
361
                double_blocks = (1 << (ptrs_bits * 2));
362
        int n = 0;
363
 
364
        if (i_block < 0) {
365
                ext3_warning (inode->i_sb, "ext3_block_to_path", "block < 0");
366
        } else if (i_block < direct_blocks) {
367
                offsets[n++] = i_block;
368
        } else if ( (i_block -= direct_blocks) < indirect_blocks) {
369
                offsets[n++] = EXT3_IND_BLOCK;
370
                offsets[n++] = i_block;
371
        } else if ((i_block -= indirect_blocks) < double_blocks) {
372
                offsets[n++] = EXT3_DIND_BLOCK;
373
                offsets[n++] = i_block >> ptrs_bits;
374
                offsets[n++] = i_block & (ptrs - 1);
375
        } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
376
                offsets[n++] = EXT3_TIND_BLOCK;
377
                offsets[n++] = i_block >> (ptrs_bits * 2);
378
                offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
379
                offsets[n++] = i_block & (ptrs - 1);
380
        } else {
381
                ext3_warning (inode->i_sb, "ext3_block_to_path", "block > big");
382
        }
383
        return n;
384
}
385
 
386
/**
387
 *      ext3_get_branch - read the chain of indirect blocks leading to data
388
 *      @inode: inode in question
389
 *      @depth: depth of the chain (1 - direct pointer, etc.)
390
 *      @offsets: offsets of pointers in inode/indirect blocks
391
 *      @chain: place to store the result
392
 *      @err: here we store the error value
393
 *
394
 *      Function fills the array of triples <key, p, bh> and returns %NULL
395
 *      if everything went OK or the pointer to the last filled triple
396
 *      (incomplete one) otherwise. Upon the return chain[i].key contains
397
 *      the number of (i+1)-th block in the chain (as it is stored in memory,
398
 *      i.e. little-endian 32-bit), chain[i].p contains the address of that
399
 *      number (it points into struct inode for i==0 and into the bh->b_data
400
 *      for i>0) and chain[i].bh points to the buffer_head of i-th indirect
401
 *      block for i>0 and NULL for i==0. In other words, it holds the block
402
 *      numbers of the chain, addresses they were taken from (and where we can
403
 *      verify that chain did not change) and buffer_heads hosting these
404
 *      numbers.
405
 *
406
 *      Function stops when it stumbles upon zero pointer (absent block)
407
 *              (pointer to last triple returned, *@err == 0)
408
 *      or when it gets an IO error reading an indirect block
409
 *              (ditto, *@err == -EIO)
410
 *      or when it notices that chain had been changed while it was reading
411
 *              (ditto, *@err == -EAGAIN)
412
 *      or when it reads all @depth-1 indirect blocks successfully and finds
413
 *      the whole chain, all way to the data (returns %NULL, *err == 0).
414
 */
415
static Indirect *ext3_get_branch(struct inode *inode, int depth, int *offsets,
416
                                 Indirect chain[4], int *err)
417
{
418
        struct super_block *sb = inode->i_sb;
419
        Indirect *p = chain;
420
        struct buffer_head *bh;
421
 
422
        *err = 0;
423
        /* i_data is not going away, no lock needed */
424
        add_chain (chain, NULL, inode->u.ext3_i.i_data + *offsets);
425
        if (!p->key)
426
                goto no_block;
427
        while (--depth) {
428
                bh = sb_bread(sb, le32_to_cpu(p->key));
429
                if (!bh)
430
                        goto failure;
431
                /* Reader: pointers */
432
                if (!verify_chain(chain, p))
433
                        goto changed;
434
                add_chain(++p, bh, (u32*)bh->b_data + *++offsets);
435
                /* Reader: end */
436
                if (!p->key)
437
                        goto no_block;
438
        }
439
        return NULL;
440
 
441
changed:
442
        brelse(bh);
443
        *err = -EAGAIN;
444
        goto no_block;
445
failure:
446
        *err = -EIO;
447
no_block:
448
        return p;
449
}
450
 
451
/**
452
 *      ext3_find_near - find a place for allocation with sufficient locality
453
 *      @inode: owner
454
 *      @ind: descriptor of indirect block.
455
 *
456
 *      This function returns the prefered place for block allocation.
457
 *      It is used when heuristic for sequential allocation fails.
458
 *      Rules are:
459
 *        + if there is a block to the left of our position - allocate near it.
460
 *        + if pointer will live in indirect block - allocate near that block.
461
 *        + if pointer will live in inode - allocate in the same
462
 *          cylinder group.
463
 *      Caller must make sure that @ind is valid and will stay that way.
464
 */
465
 
466
static inline unsigned long ext3_find_near(struct inode *inode, Indirect *ind)
467
{
468
        u32 *start = ind->bh ? (u32*) ind->bh->b_data : inode->u.ext3_i.i_data;
469
        u32 *p;
470
 
471
        /* Try to find previous block */
472
        for (p = ind->p - 1; p >= start; p--)
473
                if (*p)
474
                        return le32_to_cpu(*p);
475
 
476
        /* No such thing, so let's try location of indirect block */
477
        if (ind->bh)
478
                return ind->bh->b_blocknr;
479
 
480
        /*
481
         * It is going to be refered from inode itself? OK, just put it into
482
         * the same cylinder group then.
483
         */
484
        return (inode->u.ext3_i.i_block_group *
485
                EXT3_BLOCKS_PER_GROUP(inode->i_sb)) +
486
               le32_to_cpu(inode->i_sb->u.ext3_sb.s_es->s_first_data_block);
487
}
488
 
489
/**
490
 *      ext3_find_goal - find a prefered place for allocation.
491
 *      @inode: owner
492
 *      @block:  block we want
493
 *      @chain:  chain of indirect blocks
494
 *      @partial: pointer to the last triple within a chain
495
 *      @goal:  place to store the result.
496
 *
497
 *      Normally this function find the prefered place for block allocation,
498
 *      stores it in *@goal and returns zero. If the branch had been changed
499
 *      under us we return -EAGAIN.
500
 */
501
 
502
static int ext3_find_goal(struct inode *inode, long block, Indirect chain[4],
503
                          Indirect *partial, unsigned long *goal)
504
{
505
        /* Writer: ->i_next_alloc* */
506
        if (block == inode->u.ext3_i.i_next_alloc_block + 1) {
507
                inode->u.ext3_i.i_next_alloc_block++;
508
                inode->u.ext3_i.i_next_alloc_goal++;
509
        }
510
#ifdef SEARCH_FROM_ZERO
511
        inode->u.ext3_i.i_next_alloc_block = 0;
512
        inode->u.ext3_i.i_next_alloc_goal = 0;
513
#endif
514
        /* Writer: end */
515
        /* Reader: pointers, ->i_next_alloc* */
516
        if (verify_chain(chain, partial)) {
517
                /*
518
                 * try the heuristic for sequential allocation,
519
                 * failing that at least try to get decent locality.
520
                 */
521
                if (block == inode->u.ext3_i.i_next_alloc_block)
522
                        *goal = inode->u.ext3_i.i_next_alloc_goal;
523
                if (!*goal)
524
                        *goal = ext3_find_near(inode, partial);
525
#ifdef SEARCH_FROM_ZERO
526
                *goal = 0;
527
#endif
528
                return 0;
529
        }
530
        /* Reader: end */
531
        return -EAGAIN;
532
}
533
 
534
/**
535
 *      ext3_alloc_branch - allocate and set up a chain of blocks.
536
 *      @inode: owner
537
 *      @num: depth of the chain (number of blocks to allocate)
538
 *      @offsets: offsets (in the blocks) to store the pointers to next.
539
 *      @branch: place to store the chain in.
540
 *
541
 *      This function allocates @num blocks, zeroes out all but the last one,
542
 *      links them into chain and (if we are synchronous) writes them to disk.
543
 *      In other words, it prepares a branch that can be spliced onto the
544
 *      inode. It stores the information about that chain in the branch[], in
545
 *      the same format as ext3_get_branch() would do. We are calling it after
546
 *      we had read the existing part of chain and partial points to the last
547
 *      triple of that (one with zero ->key). Upon the exit we have the same
548
 *      picture as after the successful ext3_get_block(), excpet that in one
549
 *      place chain is disconnected - *branch->p is still zero (we did not
550
 *      set the last link), but branch->key contains the number that should
551
 *      be placed into *branch->p to fill that gap.
552
 *
553
 *      If allocation fails we free all blocks we've allocated (and forget
554
 *      their buffer_heads) and return the error value the from failed
555
 *      ext3_alloc_block() (normally -ENOSPC). Otherwise we set the chain
556
 *      as described above and return 0.
557
 */
558
 
559
static int ext3_alloc_branch(handle_t *handle, struct inode *inode,
560
                             int num,
561
                             unsigned long goal,
562
                             int *offsets,
563
                             Indirect *branch)
564
{
565
        int blocksize = inode->i_sb->s_blocksize;
566
        int n = 0, keys = 0;
567
        int err = 0;
568
        int i;
569
        int parent = ext3_alloc_block(handle, inode, goal, &err);
570
 
571
        branch[0].key = cpu_to_le32(parent);
572
        if (parent) {
573
                for (n = 1; n < num; n++) {
574
                        struct buffer_head *bh;
575
                        /* Allocate the next block */
576
                        int nr = ext3_alloc_block(handle, inode, parent, &err);
577
                        if (!nr)
578
                                break;
579
                        branch[n].key = cpu_to_le32(nr);
580
                        keys = n+1;
581
 
582
                        /*
583
                         * Get buffer_head for parent block, zero it out
584
                         * and set the pointer to new one, then send
585
                         * parent to disk.
586
                         */
587
                        bh = sb_getblk(inode->i_sb, parent);
588
                        branch[n].bh = bh;
589
                        lock_buffer(bh);
590
                        BUFFER_TRACE(bh, "call get_create_access");
591
                        err = ext3_journal_get_create_access(handle, bh);
592
                        if (err) {
593
                                unlock_buffer(bh);
594
                                brelse(bh);
595
                                break;
596
                        }
597
 
598
                        memset(bh->b_data, 0, blocksize);
599
                        branch[n].p = (u32*) bh->b_data + offsets[n];
600
                        *branch[n].p = branch[n].key;
601
                        BUFFER_TRACE(bh, "marking uptodate");
602
                        mark_buffer_uptodate(bh, 1);
603
                        unlock_buffer(bh);
604
 
605
                        BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
606
                        err = ext3_journal_dirty_metadata(handle, bh);
607
                        if (err)
608
                                break;
609
 
610
                        parent = nr;
611
                }
612
        }
613
        if (n == num)
614
                return 0;
615
 
616
        /* Allocation failed, free what we already allocated */
617
        for (i = 1; i < keys; i++) {
618
                BUFFER_TRACE(branch[i].bh, "call journal_forget");
619
                ext3_journal_forget(handle, branch[i].bh);
620
        }
621
        for (i = 0; i < keys; i++)
622
                ext3_free_blocks(handle, inode, le32_to_cpu(branch[i].key), 1);
623
        return err;
624
}
625
 
626
/**
627
 *      ext3_splice_branch - splice the allocated branch onto inode.
628
 *      @inode: owner
629
 *      @block: (logical) number of block we are adding
630
 *      @chain: chain of indirect blocks (with a missing link - see
631
 *              ext3_alloc_branch)
632
 *      @where: location of missing link
633
 *      @num:   number of blocks we are adding
634
 *
635
 *      This function verifies that chain (up to the missing link) had not
636
 *      changed, fills the missing link and does all housekeeping needed in
637
 *      inode (->i_blocks, etc.). In case of success we end up with the full
638
 *      chain to new block and return 0. Otherwise (== chain had been changed)
639
 *      we free the new blocks (forgetting their buffer_heads, indeed) and
640
 *      return -EAGAIN.
641
 */
642
 
643
static int ext3_splice_branch(handle_t *handle, struct inode *inode, long block,
644
                              Indirect chain[4], Indirect *where, int num)
645
{
646
        int i;
647
        int err = 0;
648
 
649
        /*
650
         * If we're splicing into a [td]indirect block (as opposed to the
651
         * inode) then we need to get write access to the [td]indirect block
652
         * before the splice.
653
         */
654
        if (where->bh) {
655
                BUFFER_TRACE(where->bh, "get_write_access");
656
                err = ext3_journal_get_write_access(handle, where->bh);
657
                if (err)
658
                        goto err_out;
659
        }
660
        /* Verify that place we are splicing to is still there and vacant */
661
 
662
        /* Writer: pointers, ->i_next_alloc* */
663
        if (!verify_chain(chain, where-1) || *where->p)
664
                /* Writer: end */
665
                goto changed;
666
 
667
        /* That's it */
668
 
669
        *where->p = where->key;
670
        inode->u.ext3_i.i_next_alloc_block = block;
671
        inode->u.ext3_i.i_next_alloc_goal = le32_to_cpu(where[num-1].key);
672
#ifdef SEARCH_FROM_ZERO
673
        inode->u.ext3_i.i_next_alloc_block = 0;
674
        inode->u.ext3_i.i_next_alloc_goal = 0;
675
#endif
676
        /* Writer: end */
677
 
678
        /* We are done with atomic stuff, now do the rest of housekeeping */
679
 
680
        inode->i_ctime = CURRENT_TIME;
681
        ext3_mark_inode_dirty(handle, inode);
682
 
683
        /* had we spliced it onto indirect block? */
684
        if (where->bh) {
685
                /*
686
                 * akpm: If we spliced it onto an indirect block, we haven't
687
                 * altered the inode.  Note however that if it is being spliced
688
                 * onto an indirect block at the very end of the file (the
689
                 * file is growing) then we *will* alter the inode to reflect
690
                 * the new i_size.  But that is not done here - it is done in
691
                 * generic_commit_write->__mark_inode_dirty->ext3_dirty_inode.
692
                 */
693
                jbd_debug(5, "splicing indirect only\n");
694
                BUFFER_TRACE(where->bh, "call ext3_journal_dirty_metadata");
695
                err = ext3_journal_dirty_metadata(handle, where->bh);
696
                if (err)
697
                        goto err_out;
698
        } else {
699
                /*
700
                 * OK, we spliced it into the inode itself on a direct block.
701
                 * Inode was dirtied above.
702
                 */
703
                jbd_debug(5, "splicing direct\n");
704
        }
705
        return err;
706
 
707
changed:
708
        /*
709
         * AKPM: if where[i].bh isn't part of the current updating
710
         * transaction then we explode nastily.  Test this code path.
711
         */
712
        jbd_debug(1, "the chain changed: try again\n");
713
        err = -EAGAIN;
714
 
715
err_out:
716
        for (i = 1; i < num; i++) {
717
                BUFFER_TRACE(where[i].bh, "call journal_forget");
718
                ext3_journal_forget(handle, where[i].bh);
719
        }
720
        /* For the normal collision cleanup case, we free up the blocks.
721
         * On genuine filesystem errors we don't even think about doing
722
         * that. */
723
        if (err == -EAGAIN)
724
                for (i = 0; i < num; i++)
725
                        ext3_free_blocks(handle, inode,
726
                                         le32_to_cpu(where[i].key), 1);
727
        return err;
728
}
729
 
730
/*
731
 * Allocation strategy is simple: if we have to allocate something, we will
732
 * have to go the whole way to leaf. So let's do it before attaching anything
733
 * to tree, set linkage between the newborn blocks, write them if sync is
734
 * required, recheck the path, free and repeat if check fails, otherwise
735
 * set the last missing link (that will protect us from any truncate-generated
736
 * removals - all blocks on the path are immune now) and possibly force the
737
 * write on the parent block.
738
 * That has a nice additional property: no special recovery from the failed
739
 * allocations is needed - we simply release blocks and do not touch anything
740
 * reachable from inode.
741
 *
742
 * akpm: `handle' can be NULL if create == 0.
743
 *
744
 * The BKL may not be held on entry here.  Be sure to take it early.
745
 */
746
 
747
static int ext3_get_block_handle(handle_t *handle, struct inode *inode,
748
                                 long iblock,
749
                                 struct buffer_head *bh_result, int create)
750
{
751
        int err = -EIO;
752
        int offsets[4];
753
        Indirect chain[4];
754
        Indirect *partial;
755
        unsigned long goal;
756
        int left;
757
        int depth = ext3_block_to_path(inode, iblock, offsets);
758
        loff_t new_size;
759
 
760
        J_ASSERT(handle != NULL || create == 0);
761
 
762
        if (depth == 0)
763
                goto out;
764
 
765
        lock_kernel();
766
reread:
767
        partial = ext3_get_branch(inode, depth, offsets, chain, &err);
768
 
769
        /* Simplest case - block found, no allocation needed */
770
        if (!partial) {
771
                bh_result->b_state &= ~(1UL << BH_New);
772
got_it:
773
                bh_result->b_dev = inode->i_dev;
774
                bh_result->b_blocknr = le32_to_cpu(chain[depth-1].key);
775
                bh_result->b_state |= (1UL << BH_Mapped);
776
                /* Clean up and exit */
777
                partial = chain+depth-1; /* the whole chain */
778
                goto cleanup;
779
        }
780
 
781
        /* Next simple case - plain lookup or failed read of indirect block */
782
        if (!create || err == -EIO) {
783
cleanup:
784
                while (partial > chain) {
785
                        BUFFER_TRACE(partial->bh, "call brelse");
786
                        brelse(partial->bh);
787
                        partial--;
788
                }
789
                BUFFER_TRACE(bh_result, "returned");
790
                unlock_kernel();
791
out:
792
                return err;
793
        }
794
 
795
        /*
796
         * Indirect block might be removed by truncate while we were
797
         * reading it. Handling of that case (forget what we've got and
798
         * reread) is taken out of the main path.
799
         */
800
        if (err == -EAGAIN)
801
                goto changed;
802
 
803
        if (ext3_find_goal(inode, iblock, chain, partial, &goal) < 0)
804
                goto changed;
805
 
806
        left = (chain + depth) - partial;
807
 
808
        /*
809
         * Block out ext3_truncate while we alter the tree
810
         */
811
        down_read(&inode->u.ext3_i.truncate_sem);
812
        err = ext3_alloc_branch(handle, inode, left, goal,
813
                                        offsets+(partial-chain), partial);
814
 
815
        /* The ext3_splice_branch call will free and forget any buffers
816
         * on the new chain if there is a failure, but that risks using
817
         * up transaction credits, especially for bitmaps where the
818
         * credits cannot be returned.  Can we handle this somehow?  We
819
         * may need to return -EAGAIN upwards in the worst case.  --sct */
820
        if (!err)
821
                err = ext3_splice_branch(handle, inode, iblock, chain,
822
                                         partial, left);
823
        up_read(&inode->u.ext3_i.truncate_sem);
824
        if (err == -EAGAIN)
825
                goto changed;
826
        if (err)
827
                goto cleanup;
828
 
829
        new_size = inode->i_size;
830
        /*
831
         * This is not racy against ext3_truncate's modification of i_disksize
832
         * because VM/VFS ensures that the file cannot be extended while
833
         * truncate is in progress.  It is racy between multiple parallel
834
         * instances of get_block, but we have the BKL.
835
         */
836
        if (new_size > inode->u.ext3_i.i_disksize)
837
                inode->u.ext3_i.i_disksize = new_size;
838
 
839
        bh_result->b_state |= (1UL << BH_New);
840
        goto got_it;
841
 
842
changed:
843
        while (partial > chain) {
844
                jbd_debug(1, "buffer chain changed, retrying\n");
845
                BUFFER_TRACE(partial->bh, "brelsing");
846
                brelse(partial->bh);
847
                partial--;
848
        }
849
        goto reread;
850
}
851
 
852
/*
853
 * The BKL is not held on entry here.
854
 */
855
static int ext3_get_block(struct inode *inode, long iblock,
856
                        struct buffer_head *bh_result, int create)
857
{
858
        handle_t *handle = 0;
859
        int ret;
860
 
861
        if (create) {
862
                handle = ext3_journal_current_handle();
863
                J_ASSERT(handle != 0);
864
        }
865
        ret = ext3_get_block_handle(handle, inode, iblock, bh_result, create);
866
        return ret;
867
}
868
 
869
/*
870
 * `handle' can be NULL if create is zero
871
 */
872
struct buffer_head *ext3_getblk(handle_t *handle, struct inode * inode,
873
                                long block, int create, int * errp)
874
{
875
        struct buffer_head dummy;
876
        int fatal = 0, err;
877
 
878
        J_ASSERT(handle != NULL || create == 0);
879
 
880
        dummy.b_state = 0;
881
        dummy.b_blocknr = -1000;
882
        buffer_trace_init(&dummy.b_history);
883
        *errp = ext3_get_block_handle(handle, inode, block, &dummy, create);
884
        if (!*errp && buffer_mapped(&dummy)) {
885
                struct buffer_head *bh;
886
                bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
887
                if (buffer_new(&dummy)) {
888
                        J_ASSERT(create != 0);
889
                        J_ASSERT(handle != 0);
890
 
891
                        /* Now that we do not always journal data, we
892
                           should keep in mind whether this should
893
                           always journal the new buffer as metadata.
894
                           For now, regular file writes use
895
                           ext3_get_block instead, so it's not a
896
                           problem. */
897
                        lock_kernel();
898
                        lock_buffer(bh);
899
                        BUFFER_TRACE(bh, "call get_create_access");
900
                        fatal = ext3_journal_get_create_access(handle, bh);
901
                        if (!fatal) {
902
                                memset(bh->b_data, 0,
903
                                       inode->i_sb->s_blocksize);
904
                                mark_buffer_uptodate(bh, 1);
905
                        }
906
                        unlock_buffer(bh);
907
                        BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
908
                        err = ext3_journal_dirty_metadata(handle, bh);
909
                        if (!fatal) fatal = err;
910
                        unlock_kernel();
911
                } else {
912
                        BUFFER_TRACE(bh, "not a new buffer");
913
                }
914
                if (fatal) {
915
                        *errp = fatal;
916
                        brelse(bh);
917
                        bh = NULL;
918
                }
919
                return bh;
920
        }
921
        return NULL;
922
}
923
 
924
struct buffer_head *ext3_bread(handle_t *handle, struct inode * inode,
925
                               int block, int create, int *err)
926
{
927
        struct buffer_head * bh;
928
        int prev_blocks;
929
 
930
        prev_blocks = inode->i_blocks;
931
 
932
        bh = ext3_getblk (handle, inode, block, create, err);
933
        if (!bh)
934
                return bh;
935
#ifdef EXT3_PREALLOCATE
936
        /*
937
         * If the inode has grown, and this is a directory, then use a few
938
         * more of the preallocated blocks to keep directory fragmentation
939
         * down.  The preallocated blocks are guaranteed to be contiguous.
940
         */
941
        if (create &&
942
            S_ISDIR(inode->i_mode) &&
943
            inode->i_blocks > prev_blocks &&
944
            EXT3_HAS_COMPAT_FEATURE(inode->i_sb,
945
                                    EXT3_FEATURE_COMPAT_DIR_PREALLOC)) {
946
                int i;
947
                struct buffer_head *tmp_bh;
948
 
949
                for (i = 1;
950
                     inode->u.ext3_i.i_prealloc_count &&
951
                     i < EXT3_SB(inode->i_sb)->s_es->s_prealloc_dir_blocks;
952
                     i++) {
953
                        /*
954
                         * ext3_getblk will zero out the contents of the
955
                         * directory for us
956
                         */
957
                        tmp_bh = ext3_getblk(handle, inode,
958
                                                block+i, create, err);
959
                        if (!tmp_bh) {
960
                                brelse (bh);
961
                                return 0;
962
                        }
963
                        brelse (tmp_bh);
964
                }
965
        }
966
#endif
967
        if (buffer_uptodate(bh))
968
                return bh;
969
        ll_rw_block (READ, 1, &bh);
970
        wait_on_buffer (bh);
971
        if (buffer_uptodate(bh))
972
                return bh;
973
        brelse (bh);
974
        *err = -EIO;
975
        return NULL;
976
}
977
 
978
static int walk_page_buffers(   handle_t *handle,
979
                                struct inode *inode,
980
                                struct buffer_head *head,
981
                                unsigned from,
982
                                unsigned to,
983
                                int *partial,
984
                                int (*fn)(      handle_t *handle,
985
                                                struct inode *inode,
986
                                                struct buffer_head *bh))
987
{
988
        struct buffer_head *bh;
989
        unsigned block_start, block_end;
990
        unsigned blocksize = head->b_size;
991
        int err, ret = 0;
992
 
993
        for (   bh = head, block_start = 0;
994
                ret == 0 && (bh != head || !block_start);
995
                block_start = block_end, bh = bh->b_this_page)
996
        {
997
                block_end = block_start + blocksize;
998
                if (block_end <= from || block_start >= to) {
999
                        if (partial && !buffer_uptodate(bh))
1000
                                *partial = 1;
1001
                        continue;
1002
                }
1003
                err = (*fn)(handle, inode, bh);
1004
                if (!ret)
1005
                        ret = err;
1006
        }
1007
        return ret;
1008
}
1009
 
1010
/*
1011
 * To preserve ordering, it is essential that the hole instantiation and
1012
 * the data write be encapsulated in a single transaction.  We cannot
1013
 * close off a transaction and start a new one between the ext3_get_block()
1014
 * and the commit_write().  So doing the journal_start at the start of
1015
 * prepare_write() is the right place.
1016
 *
1017
 * Also, this function can nest inside ext3_writepage() ->
1018
 * block_write_full_page(). In that case, we *know* that ext3_writepage()
1019
 * has generated enough buffer credits to do the whole page.  So we won't
1020
 * block on the journal in that case, which is good, because the caller may
1021
 * be PF_MEMALLOC.
1022
 *
1023
 * By accident, ext3 can be reentered when a transaction is open via
1024
 * quota file writes.  If we were to commit the transaction while thus
1025
 * reentered, there can be a deadlock - we would be holding a quota
1026
 * lock, and the commit would never complete if another thread had a
1027
 * transaction open and was blocking on the quota lock - a ranking
1028
 * violation.
1029
 *
1030
 * So what we do is to rely on the fact that journal_stop/journal_start
1031
 * will _not_ run commit under these circumstances because handle->h_ref
1032
 * is elevated.  We'll still have enough credits for the tiny quotafile
1033
 * write.
1034
 */
1035
 
1036
static int do_journal_get_write_access(handle_t *handle, struct inode *inode,
1037
                                       struct buffer_head *bh)
1038
{
1039
        return ext3_journal_get_write_access(handle, bh);
1040
}
1041
 
1042
static int ext3_prepare_write(struct file *file, struct page *page,
1043
                              unsigned from, unsigned to)
1044
{
1045
        struct inode *inode = page->mapping->host;
1046
        int ret, needed_blocks = ext3_writepage_trans_blocks(inode);
1047
        handle_t *handle;
1048
 
1049
        lock_kernel();
1050
        handle = ext3_journal_start(inode, needed_blocks);
1051
        if (IS_ERR(handle)) {
1052
                ret = PTR_ERR(handle);
1053
                goto out;
1054
        }
1055
        unlock_kernel();
1056
        ret = block_prepare_write(page, from, to, ext3_get_block);
1057
        lock_kernel();
1058
        if (ret != 0)
1059
                goto prepare_write_failed;
1060
 
1061
        if (ext3_should_journal_data(inode)) {
1062
                ret = walk_page_buffers(handle, inode, page->buffers,
1063
                                from, to, NULL, do_journal_get_write_access);
1064
                if (ret) {
1065
                        /*
1066
                         * We're going to fail this prepare_write(),
1067
                         * so commit_write() will not be called.
1068
                         * We need to undo block_prepare_write()'s kmap().
1069
                         * AKPM: Do we need to clear PageUptodate?  I don't
1070
                         * think so.
1071
                         */
1072
                        kunmap(page);
1073
                }
1074
        }
1075
prepare_write_failed:
1076
        if (ret)
1077
                ext3_journal_stop(handle, inode);
1078
out:
1079
        unlock_kernel();
1080
        return ret;
1081
}
1082
 
1083
static int journal_dirty_sync_data(handle_t *handle, struct inode *inode,
1084
                                   struct buffer_head *bh)
1085
{
1086
        int ret = ext3_journal_dirty_data(handle, bh, 0);
1087
        buffer_insert_inode_data_queue(bh, inode);
1088
        return ret;
1089
}
1090
 
1091
/*
1092
 * For ext3_writepage().  We also brelse() the buffer to account for
1093
 * the bget() which ext3_writepage() performs.
1094
 */
1095
static int journal_dirty_async_data(handle_t *handle, struct inode *inode,
1096
                                    struct buffer_head *bh)
1097
{
1098
        int ret = ext3_journal_dirty_data(handle, bh, 1);
1099
        buffer_insert_inode_data_queue(bh, inode);
1100
        __brelse(bh);
1101
        return ret;
1102
}
1103
 
1104
/* For commit_write() in data=journal mode */
1105
static int commit_write_fn(handle_t *handle, struct inode *inode,
1106
                           struct buffer_head *bh)
1107
{
1108
        set_bit(BH_Uptodate, &bh->b_state);
1109
        return ext3_journal_dirty_metadata(handle, bh);
1110
}
1111
 
1112
/*
1113
 * We need to pick up the new inode size which generic_commit_write gave us
1114
 * `file' can be NULL - eg, when called from block_symlink().
1115
 *
1116
 * ext3 inode->i_dirty_buffers policy:  If we're journalling data we
1117
 * definitely don't want them to appear on the inode at all - instead
1118
 * we need to manage them at the JBD layer and we need to intercept
1119
 * the relevant sync operations and translate them into journal operations.
1120
 *
1121
 * If we're not journalling data then we can just leave the buffers
1122
 * on ->i_dirty_buffers.  If someone writes them out for us then thanks.
1123
 * Otherwise we'll do it in commit, if we're using ordered data.
1124
 */
1125
 
1126
static int ext3_commit_write(struct file *file, struct page *page,
1127
                             unsigned from, unsigned to)
1128
{
1129
        handle_t *handle = ext3_journal_current_handle();
1130
        struct inode *inode = page->mapping->host;
1131
        int ret = 0, ret2;
1132
 
1133
        lock_kernel();
1134
        if (ext3_should_journal_data(inode)) {
1135
                /*
1136
                 * Here we duplicate the generic_commit_write() functionality
1137
                 */
1138
                int partial = 0;
1139
                loff_t pos = ((loff_t)page->index << PAGE_CACHE_SHIFT) + to;
1140
 
1141
                ret = walk_page_buffers(handle, inode, page->buffers,
1142
                        from, to, &partial, commit_write_fn);
1143
                if (!partial)
1144
                        SetPageUptodate(page);
1145
                kunmap(page);
1146
                if (pos > inode->i_size)
1147
                        inode->i_size = pos;
1148
                EXT3_I(inode)->i_state |= EXT3_STATE_JDATA;
1149
        } else {
1150
                if (ext3_should_order_data(inode)) {
1151
                        ret = walk_page_buffers(handle, inode, page->buffers,
1152
                                from, to, NULL, journal_dirty_sync_data);
1153
                }
1154
                /* Be careful here if generic_commit_write becomes a
1155
                 * required invocation after block_prepare_write. */
1156
                if (ret == 0) {
1157
                        ret = generic_commit_write(file, page, from, to);
1158
                } else {
1159
                        /*
1160
                         * block_prepare_write() was called, but we're not
1161
                         * going to call generic_commit_write().  So we
1162
                         * need to perform generic_commit_write()'s kunmap
1163
                         * by hand.
1164
                         */
1165
                        kunmap(page);
1166
                }
1167
        }
1168
        if (inode->i_size > inode->u.ext3_i.i_disksize) {
1169
                inode->u.ext3_i.i_disksize = inode->i_size;
1170
                ret2 = ext3_mark_inode_dirty(handle, inode);
1171
                if (!ret)
1172
                        ret = ret2;
1173
        }
1174
        ret2 = ext3_journal_stop(handle, inode);
1175
        unlock_kernel();
1176
        if (!ret)
1177
                ret = ret2;
1178
        return ret;
1179
}
1180
 
1181
/*
1182
 * bmap() is special.  It gets used by applications such as lilo and by
1183
 * the swapper to find the on-disk block of a specific piece of data.
1184
 *
1185
 * Naturally, this is dangerous if the block concerned is still in the
1186
 * journal.  If somebody makes a swapfile on an ext3 data-journaling
1187
 * filesystem and enables swap, then they may get a nasty shock when the
1188
 * data getting swapped to that swapfile suddenly gets overwritten by
1189
 * the original zero's written out previously to the journal and
1190
 * awaiting writeback in the kernel's buffer cache.
1191
 *
1192
 * So, if we see any bmap calls here on a modified, data-journaled file,
1193
 * take extra steps to flush any blocks which might be in the cache.
1194
 */
1195
static int ext3_bmap(struct address_space *mapping, long block)
1196
{
1197
        struct inode *inode = mapping->host;
1198
        journal_t *journal;
1199
        int err;
1200
 
1201
        if (EXT3_I(inode)->i_state & EXT3_STATE_JDATA) {
1202
                /*
1203
                 * This is a REALLY heavyweight approach, but the use of
1204
                 * bmap on dirty files is expected to be extremely rare:
1205
                 * only if we run lilo or swapon on a freshly made file
1206
                 * do we expect this to happen.
1207
                 *
1208
                 * (bmap requires CAP_SYS_RAWIO so this does not
1209
                 * represent an unprivileged user DOS attack --- we'd be
1210
                 * in trouble if mortal users could trigger this path at
1211
                 * will.)
1212
                 *
1213
                 * NB. EXT3_STATE_JDATA is not set on files other than
1214
                 * regular files.  If somebody wants to bmap a directory
1215
                 * or symlink and gets confused because the buffer
1216
                 * hasn't yet been flushed to disk, they deserve
1217
                 * everything they get.
1218
                 */
1219
 
1220
                EXT3_I(inode)->i_state &= ~EXT3_STATE_JDATA;
1221
                journal = EXT3_JOURNAL(inode);
1222
                journal_lock_updates(journal);
1223
                err = journal_flush(journal);
1224
                journal_unlock_updates(journal);
1225
 
1226
                if (err)
1227
                        return 0;
1228
        }
1229
 
1230
        return generic_block_bmap(mapping,block,ext3_get_block);
1231
}
1232
 
1233
static int bget_one(handle_t *handle, struct inode *inode,
1234
                    struct buffer_head *bh)
1235
{
1236
        atomic_inc(&bh->b_count);
1237
        return 0;
1238
}
1239
 
1240
/*
1241
 * Note that we always start a transaction even if we're not journalling
1242
 * data.  This is to preserve ordering: any hole instantiation within
1243
 * __block_write_full_page -> ext3_get_block() should be journalled
1244
 * along with the data so we don't crash and then get metadata which
1245
 * refers to old data.
1246
 *
1247
 * In all journalling modes block_write_full_page() will start the I/O.
1248
 *
1249
 * Problem:
1250
 *
1251
 *      ext3_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
1252
 *              ext3_writepage()
1253
 *
1254
 * Similar for:
1255
 *
1256
 *      ext3_file_write() -> generic_file_write() -> __alloc_pages() -> ...
1257
 *
1258
 * Same applies to ext3_get_block().  We will deadlock on various things like
1259
 * lock_journal and i_truncate_sem.
1260
 *
1261
 * Setting PF_MEMALLOC here doesn't work - too many internal memory
1262
 * allocations fail.
1263
 *
1264
 * 16May01: If we're reentered then journal_current_handle() will be
1265
 *          non-zero. We simply *return*.
1266
 *
1267
 * 1 July 2001: @@@ FIXME:
1268
 *   In journalled data mode, a data buffer may be metadata against the
1269
 *   current transaction.  But the same file is part of a shared mapping
1270
 *   and someone does a writepage() on it.
1271
 *
1272
 *   We will move the buffer onto the async_data list, but *after* it has
1273
 *   been dirtied. So there's a small window where we have dirty data on
1274
 *   BJ_Metadata.
1275
 *
1276
 *   Note that this only applies to the last partial page in the file.  The
1277
 *   bit which block_write_full_page() uses prepare/commit for.  (That's
1278
 *   broken code anyway: it's wrong for msync()).
1279
 *
1280
 *   It's a rare case: affects the final partial page, for journalled data
1281
 *   where the file is subject to bith write() and writepage() in the same
1282
 *   transction.  To fix it we'll need a custom block_write_full_page().
1283
 *   We'll probably need that anyway for journalling writepage() output.
1284
 *
1285
 * We don't honour synchronous mounts for writepage().  That would be
1286
 * disastrous.  Any write() or metadata operation will sync the fs for
1287
 * us.
1288
 */
1289
static int ext3_writepage(struct page *page)
1290
{
1291
        struct inode *inode = page->mapping->host;
1292
        struct buffer_head *page_buffers;
1293
        handle_t *handle = NULL;
1294
        int ret = 0, err;
1295
        int needed;
1296
        int order_data;
1297
 
1298
        J_ASSERT(PageLocked(page));
1299
 
1300
        /*
1301
         * We give up here if we're reentered, because it might be
1302
         * for a different filesystem.  One *could* look for a
1303
         * nested transaction opportunity.
1304
         */
1305
        lock_kernel();
1306
        if (ext3_journal_current_handle())
1307
                goto out_fail;
1308
 
1309
        needed = ext3_writepage_trans_blocks(inode);
1310
        if (current->flags & PF_MEMALLOC)
1311
                handle = ext3_journal_try_start(inode, needed);
1312
        else
1313
                handle = ext3_journal_start(inode, needed);
1314
 
1315
        if (IS_ERR(handle)) {
1316
                ret = PTR_ERR(handle);
1317
                goto out_fail;
1318
        }
1319
 
1320
        order_data = ext3_should_order_data(inode) ||
1321
                        ext3_should_journal_data(inode);
1322
 
1323
        unlock_kernel();
1324
 
1325
        page_buffers = NULL;    /* Purely to prevent compiler warning */
1326
 
1327
        /* bget() all the buffers */
1328
        if (order_data) {
1329
                if (!page->buffers)
1330
                        create_empty_buffers(page,
1331
                                inode->i_dev, inode->i_sb->s_blocksize);
1332
                page_buffers = page->buffers;
1333
                walk_page_buffers(handle, inode, page_buffers, 0,
1334
                                PAGE_CACHE_SIZE, NULL, bget_one);
1335
        }
1336
 
1337
        ret = block_write_full_page(page, ext3_get_block);
1338
 
1339
        /*
1340
         * The page can become unlocked at any point now, and
1341
         * truncate can then come in and change things.  So we
1342
         * can't touch *page from now on.  But *page_buffers is
1343
         * safe due to elevated refcount.
1344
         */
1345
 
1346
        handle = ext3_journal_current_handle();
1347
        lock_kernel();
1348
 
1349
        /* And attach them to the current transaction */
1350
        if (order_data) {
1351
                err = walk_page_buffers(handle, inode, page_buffers,
1352
                        0, PAGE_CACHE_SIZE, NULL, journal_dirty_async_data);
1353
                if (!ret)
1354
                        ret = err;
1355
        }
1356
 
1357
        err = ext3_journal_stop(handle, inode);
1358
        if (!ret)
1359
                ret = err;
1360
        unlock_kernel();
1361
        return ret;
1362
 
1363
out_fail:
1364
 
1365
        unlock_kernel();
1366
        SetPageDirty(page);
1367
        UnlockPage(page);
1368
        return ret;
1369
}
1370
 
1371
static int ext3_readpage(struct file *file, struct page *page)
1372
{
1373
        return block_read_full_page(page,ext3_get_block);
1374
}
1375
 
1376
 
1377
static int ext3_flushpage(struct page *page, unsigned long offset)
1378
{
1379
        journal_t *journal = EXT3_JOURNAL(page->mapping->host);
1380
        return journal_flushpage(journal, page, offset);
1381
}
1382
 
1383
static int ext3_releasepage(struct page *page, int wait)
1384
{
1385
        journal_t *journal = EXT3_JOURNAL(page->mapping->host);
1386
        return journal_try_to_free_buffers(journal, page, wait);
1387
}
1388
 
1389
 
1390
struct address_space_operations ext3_aops = {
1391
        readpage:       ext3_readpage,          /* BKL not held.  Don't need */
1392
        writepage:      ext3_writepage,         /* BKL not held.  We take it */
1393
        sync_page:      block_sync_page,
1394
        prepare_write:  ext3_prepare_write,     /* BKL not held.  We take it */
1395
        commit_write:   ext3_commit_write,      /* BKL not held.  We take it */
1396
        bmap:           ext3_bmap,              /* BKL held */
1397
        flushpage:      ext3_flushpage,         /* BKL not held.  Don't need */
1398
        releasepage:    ext3_releasepage,       /* BKL not held.  Don't need */
1399
};
1400
 
1401
/*
1402
 * ext3_block_truncate_page() zeroes out a mapping from file offset `from'
1403
 * up to the end of the block which corresponds to `from'.
1404
 * This required during truncate. We need to physically zero the tail end
1405
 * of that block so it doesn't yield old data if the file is later grown.
1406
 */
1407
static int ext3_block_truncate_page(handle_t *handle,
1408
                struct address_space *mapping, loff_t from)
1409
{
1410
        unsigned long index = from >> PAGE_CACHE_SHIFT;
1411
        unsigned offset = from & (PAGE_CACHE_SIZE-1);
1412
        unsigned blocksize, iblock, length, pos;
1413
        struct inode *inode = mapping->host;
1414
        struct page *page;
1415
        struct buffer_head *bh;
1416
        int err;
1417
 
1418
        blocksize = inode->i_sb->s_blocksize;
1419
        length = offset & (blocksize - 1);
1420
 
1421
        /* Block boundary? Nothing to do */
1422
        if (!length)
1423
                return 0;
1424
 
1425
        length = blocksize - length;
1426
        iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
1427
 
1428
        page = find_or_create_page(mapping, index, GFP_NOFS);
1429
        err = -ENOMEM;
1430
        if (!page)
1431
                goto out;
1432
 
1433
        if (!page->buffers)
1434
                create_empty_buffers(page, inode->i_dev, blocksize);
1435
 
1436
        /* Find the buffer that contains "offset" */
1437
        bh = page->buffers;
1438
        pos = blocksize;
1439
        while (offset >= pos) {
1440
                bh = bh->b_this_page;
1441
                iblock++;
1442
                pos += blocksize;
1443
        }
1444
 
1445
        err = 0;
1446
        if (!buffer_mapped(bh)) {
1447
                /* Hole? Nothing to do */
1448
                if (buffer_uptodate(bh))
1449
                        goto unlock;
1450
                ext3_get_block(inode, iblock, bh, 0);
1451
                /* Still unmapped? Nothing to do */
1452
                if (!buffer_mapped(bh))
1453
                        goto unlock;
1454
        }
1455
 
1456
        /* Ok, it's mapped. Make sure it's up-to-date */
1457
        if (Page_Uptodate(page))
1458
                set_bit(BH_Uptodate, &bh->b_state);
1459
 
1460
        if (!buffer_uptodate(bh)) {
1461
                err = -EIO;
1462
                ll_rw_block(READ, 1, &bh);
1463
                wait_on_buffer(bh);
1464
                /* Uhhuh. Read error. Complain and punt. */
1465
                if (!buffer_uptodate(bh))
1466
                        goto unlock;
1467
        }
1468
 
1469
        if (ext3_should_journal_data(inode)) {
1470
                BUFFER_TRACE(bh, "get write access");
1471
                err = ext3_journal_get_write_access(handle, bh);
1472
                if (err)
1473
                        goto unlock;
1474
        }
1475
 
1476
        memset(kmap(page) + offset, 0, length);
1477
        flush_dcache_page(page);
1478
        kunmap(page);
1479
 
1480
        BUFFER_TRACE(bh, "zeroed end of block");
1481
 
1482
        err = 0;
1483
        if (ext3_should_journal_data(inode)) {
1484
                err = ext3_journal_dirty_metadata(handle, bh);
1485
        } else {
1486
                if (ext3_should_order_data(inode))
1487
                        err = ext3_journal_dirty_data(handle, bh, 0);
1488
                __mark_buffer_dirty(bh);
1489
        }
1490
 
1491
unlock:
1492
        UnlockPage(page);
1493
        page_cache_release(page);
1494
out:
1495
        return err;
1496
}
1497
 
1498
/*
1499
 * Probably it should be a library function... search for first non-zero word
1500
 * or memcmp with zero_page, whatever is better for particular architecture.
1501
 * Linus?
1502
 */
1503
static inline int all_zeroes(u32 *p, u32 *q)
1504
{
1505
        while (p < q)
1506
                if (*p++)
1507
                        return 0;
1508
        return 1;
1509
}
1510
 
1511
/**
1512
 *      ext3_find_shared - find the indirect blocks for partial truncation.
1513
 *      @inode:   inode in question
1514
 *      @depth:   depth of the affected branch
1515
 *      @offsets: offsets of pointers in that branch (see ext3_block_to_path)
1516
 *      @chain:   place to store the pointers to partial indirect blocks
1517
 *      @top:     place to the (detached) top of branch
1518
 *
1519
 *      This is a helper function used by ext3_truncate().
1520
 *
1521
 *      When we do truncate() we may have to clean the ends of several
1522
 *      indirect blocks but leave the blocks themselves alive. Block is
1523
 *      partially truncated if some data below the new i_size is refered
1524
 *      from it (and it is on the path to the first completely truncated
1525
 *      data block, indeed).  We have to free the top of that path along
1526
 *      with everything to the right of the path. Since no allocation
1527
 *      past the truncation point is possible until ext3_truncate()
1528
 *      finishes, we may safely do the latter, but top of branch may
1529
 *      require special attention - pageout below the truncation point
1530
 *      might try to populate it.
1531
 *
1532
 *      We atomically detach the top of branch from the tree, store the
1533
 *      block number of its root in *@top, pointers to buffer_heads of
1534
 *      partially truncated blocks - in @chain[].bh and pointers to
1535
 *      their last elements that should not be removed - in
1536
 *      @chain[].p. Return value is the pointer to last filled element
1537
 *      of @chain.
1538
 *
1539
 *      The work left to caller to do the actual freeing of subtrees:
1540
 *              a) free the subtree starting from *@top
1541
 *              b) free the subtrees whose roots are stored in
1542
 *                      (@chain[i].p+1 .. end of @chain[i].bh->b_data)
1543
 *              c) free the subtrees growing from the inode past the @chain[0].
1544
 *                      (no partially truncated stuff there).  */
1545
 
1546
static Indirect *ext3_find_shared(struct inode *inode,
1547
                                int depth,
1548
                                int offsets[4],
1549
                                Indirect chain[4],
1550
                                u32 *top)
1551
{
1552
        Indirect *partial, *p;
1553
        int k, err;
1554
 
1555
        *top = 0;
1556
        /* Make k index the deepest non-null offest + 1 */
1557
        for (k = depth; k > 1 && !offsets[k-1]; k--)
1558
                ;
1559
        partial = ext3_get_branch(inode, k, offsets, chain, &err);
1560
        /* Writer: pointers */
1561
        if (!partial)
1562
                partial = chain + k-1;
1563
        /*
1564
         * If the branch acquired continuation since we've looked at it -
1565
         * fine, it should all survive and (new) top doesn't belong to us.
1566
         */
1567
        if (!partial->key && *partial->p)
1568
                /* Writer: end */
1569
                goto no_top;
1570
        for (p=partial; p>chain && all_zeroes((u32*)p->bh->b_data,p->p); p--)
1571
                ;
1572
        /*
1573
         * OK, we've found the last block that must survive. The rest of our
1574
         * branch should be detached before unlocking. However, if that rest
1575
         * of branch is all ours and does not grow immediately from the inode
1576
         * it's easier to cheat and just decrement partial->p.
1577
         */
1578
        if (p == chain + k - 1 && p > chain) {
1579
                p->p--;
1580
        } else {
1581
                *top = *p->p;
1582
                /* Nope, don't do this in ext3.  Must leave the tree intact */
1583
#if 0
1584
                *p->p = 0;
1585
#endif
1586
        }
1587
        /* Writer: end */
1588
 
1589
        while(partial > p)
1590
        {
1591
                brelse(partial->bh);
1592
                partial--;
1593
        }
1594
no_top:
1595
        return partial;
1596
}
1597
 
1598
/*
1599
 * Zero a number of block pointers in either an inode or an indirect block.
1600
 * If we restart the transaction we must again get write access to the
1601
 * indirect block for further modification.
1602
 *
1603
 * We release `count' blocks on disk, but (last - first) may be greater
1604
 * than `count' because there can be holes in there.
1605
 */
1606
static void
1607
ext3_clear_blocks(handle_t *handle, struct inode *inode, struct buffer_head *bh,
1608
                unsigned long block_to_free, unsigned long count,
1609
                u32 *first, u32 *last)
1610
{
1611
        u32 *p;
1612
        if (try_to_extend_transaction(handle, inode)) {
1613
                if (bh) {
1614
                        BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
1615
                        ext3_journal_dirty_metadata(handle, bh);
1616
                }
1617
                ext3_mark_inode_dirty(handle, inode);
1618
                ext3_journal_test_restart(handle, inode);
1619
                if (bh) {
1620
                        BUFFER_TRACE(bh, "retaking write access");
1621
                        ext3_journal_get_write_access(handle, bh);
1622
                }
1623
        }
1624
 
1625
        /*
1626
         * Any buffers which are on the journal will be in memory. We find
1627
         * them on the hash table so journal_revoke() will run journal_forget()
1628
         * on them.  We've already detached each block from the file, so
1629
         * bforget() in journal_forget() should be safe.
1630
         *
1631
         * AKPM: turn on bforget in journal_forget()!!!
1632
         */
1633
        for (p = first; p < last; p++) {
1634
                u32 nr = le32_to_cpu(*p);
1635
                if (nr) {
1636
                        struct buffer_head *bh;
1637
 
1638
                        *p = 0;
1639
                        bh = sb_get_hash_table(inode->i_sb, nr);
1640
                        ext3_forget(handle, 0, inode, bh, nr);
1641
                }
1642
        }
1643
 
1644
        ext3_free_blocks(handle, inode, block_to_free, count);
1645
}
1646
 
1647
/**
1648
 * ext3_free_data - free a list of data blocks
1649
 * @handle:     handle for this transaction
1650
 * @inode:      inode we are dealing with
1651
 * @this_bh:    indirect buffer_head which contains *@first and *@last
1652
 * @first:      array of block numbers
1653
 * @last:       points immediately past the end of array
1654
 *
1655
 * We are freeing all blocks refered from that array (numbers are stored as
1656
 * little-endian 32-bit) and updating @inode->i_blocks appropriately.
1657
 *
1658
 * We accumulate contiguous runs of blocks to free.  Conveniently, if these
1659
 * blocks are contiguous then releasing them at one time will only affect one
1660
 * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
1661
 * actually use a lot of journal space.
1662
 *
1663
 * @this_bh will be %NULL if @first and @last point into the inode's direct
1664
 * block pointers.
1665
 */
1666
static void ext3_free_data(handle_t *handle, struct inode *inode,
1667
                           struct buffer_head *this_bh, u32 *first, u32 *last)
1668
{
1669
        unsigned long block_to_free = 0;    /* Starting block # of a run */
1670
        unsigned long count = 0;     /* Number of blocks in the run */
1671
        u32 *block_to_free_p = NULL;        /* Pointer into inode/ind
1672
                                               corresponding to
1673
                                               block_to_free */
1674
        unsigned long nr;                   /* Current block # */
1675
        u32 *p;                             /* Pointer into inode/ind
1676
                                               for current block */
1677
        int err;
1678
 
1679
        if (this_bh) {                          /* For indirect block */
1680
                BUFFER_TRACE(this_bh, "get_write_access");
1681
                err = ext3_journal_get_write_access(handle, this_bh);
1682
                /* Important: if we can't update the indirect pointers
1683
                 * to the blocks, we can't free them. */
1684
                if (err)
1685
                        return;
1686
        }
1687
 
1688
        for (p = first; p < last; p++) {
1689
                nr = le32_to_cpu(*p);
1690
                if (nr) {
1691
                        /* accumulate blocks to free if they're contiguous */
1692
                        if (count == 0) {
1693
                                block_to_free = nr;
1694
                                block_to_free_p = p;
1695
                                count = 1;
1696
                        } else if (nr == block_to_free + count) {
1697
                                count++;
1698
                        } else {
1699
                                ext3_clear_blocks(handle, inode, this_bh,
1700
                                                  block_to_free,
1701
                                                  count, block_to_free_p, p);
1702
                                block_to_free = nr;
1703
                                block_to_free_p = p;
1704
                                count = 1;
1705
                        }
1706
                }
1707
        }
1708
 
1709
        if (count > 0)
1710
                ext3_clear_blocks(handle, inode, this_bh, block_to_free,
1711
                                  count, block_to_free_p, p);
1712
 
1713
        if (this_bh) {
1714
                BUFFER_TRACE(this_bh, "call ext3_journal_dirty_metadata");
1715
                ext3_journal_dirty_metadata(handle, this_bh);
1716
        }
1717
}
1718
 
1719
/**
1720
 *      ext3_free_branches - free an array of branches
1721
 *      @handle: JBD handle for this transaction
1722
 *      @inode: inode we are dealing with
1723
 *      @parent_bh: the buffer_head which contains *@first and *@last
1724
 *      @first: array of block numbers
1725
 *      @last:  pointer immediately past the end of array
1726
 *      @depth: depth of the branches to free
1727
 *
1728
 *      We are freeing all blocks refered from these branches (numbers are
1729
 *      stored as little-endian 32-bit) and updating @inode->i_blocks
1730
 *      appropriately.
1731
 */
1732
static void ext3_free_branches(handle_t *handle, struct inode *inode,
1733
                               struct buffer_head *parent_bh,
1734
                               u32 *first, u32 *last, int depth)
1735
{
1736
        unsigned long nr;
1737
        u32 *p;
1738
 
1739
        if (is_handle_aborted(handle))
1740
                return;
1741
 
1742
        if (depth--) {
1743
                struct buffer_head *bh;
1744
                int addr_per_block = EXT3_ADDR_PER_BLOCK(inode->i_sb);
1745
                p = last;
1746
                while (--p >= first) {
1747
                        nr = le32_to_cpu(*p);
1748
                        if (!nr)
1749
                                continue;               /* A hole */
1750
 
1751
                        /* Go read the buffer for the next level down */
1752
                        bh = sb_bread(inode->i_sb, nr);
1753
 
1754
                        /*
1755
                         * A read failure? Report error and clear slot
1756
                         * (should be rare).
1757
                         */
1758
                        if (!bh) {
1759
                                ext3_error(inode->i_sb, "ext3_free_branches",
1760
                                           "Read failure, inode=%ld, block=%ld",
1761
                                           inode->i_ino, nr);
1762
                                continue;
1763
                        }
1764
 
1765
                        /* This zaps the entire block.  Bottom up. */
1766
                        BUFFER_TRACE(bh, "free child branches");
1767
                        ext3_free_branches(handle, inode, bh, (u32*)bh->b_data,
1768
                                           (u32*)bh->b_data + addr_per_block,
1769
                                           depth);
1770
 
1771
                        /*
1772
                         * We've probably journalled the indirect block several
1773
                         * times during the truncate.  But it's no longer
1774
                         * needed and we now drop it from the transaction via
1775
                         * journal_revoke().
1776
                         *
1777
                         * That's easy if it's exclusively part of this
1778
                         * transaction.  But if it's part of the committing
1779
                         * transaction then journal_forget() will simply
1780
                         * brelse() it.  That means that if the underlying
1781
                         * block is reallocated in ext3_get_block(),
1782
                         * unmap_underlying_metadata() will find this block
1783
                         * and will try to get rid of it.  damn, damn.
1784
                         *
1785
                         * If this block has already been committed to the
1786
                         * journal, a revoke record will be written.  And
1787
                         * revoke records must be emitted *before* clearing
1788
                         * this block's bit in the bitmaps.
1789
                         */
1790
                        ext3_forget(handle, 1, inode, bh, bh->b_blocknr);
1791
 
1792
                        /*
1793
                         * Everything below this this pointer has been
1794
                         * released.  Now let this top-of-subtree go.
1795
                         *
1796
                         * We want the freeing of this indirect block to be
1797
                         * atomic in the journal with the updating of the
1798
                         * bitmap block which owns it.  So make some room in
1799
                         * the journal.
1800
                         *
1801
                         * We zero the parent pointer *after* freeing its
1802
                         * pointee in the bitmaps, so if extend_transaction()
1803
                         * for some reason fails to put the bitmap changes and
1804
                         * the release into the same transaction, recovery
1805
                         * will merely complain about releasing a free block,
1806
                         * rather than leaking blocks.
1807
                         */
1808
                        if (is_handle_aborted(handle))
1809
                                return;
1810
                        if (try_to_extend_transaction(handle, inode)) {
1811
                                ext3_mark_inode_dirty(handle, inode);
1812
                                ext3_journal_test_restart(handle, inode);
1813
                        }
1814
 
1815
                        ext3_free_blocks(handle, inode, nr, 1);
1816
 
1817
                        if (parent_bh) {
1818
                                /*
1819
                                 * The block which we have just freed is
1820
                                 * pointed to by an indirect block: journal it
1821
                                 */
1822
                                BUFFER_TRACE(parent_bh, "get_write_access");
1823
                                if (!ext3_journal_get_write_access(handle,
1824
                                                                   parent_bh)){
1825
                                        *p = 0;
1826
                                        BUFFER_TRACE(parent_bh,
1827
                                        "call ext3_journal_dirty_metadata");
1828
                                        ext3_journal_dirty_metadata(handle,
1829
                                                                    parent_bh);
1830
                                }
1831
                        }
1832
                }
1833
        } else {
1834
                /* We have reached the bottom of the tree. */
1835
                BUFFER_TRACE(parent_bh, "free data blocks");
1836
                ext3_free_data(handle, inode, parent_bh, first, last);
1837
        }
1838
}
1839
 
1840
/*
1841
 * ext3_truncate()
1842
 *
1843
 * We block out ext3_get_block() block instantiations across the entire
1844
 * transaction, and VFS/VM ensures that ext3_truncate() cannot run
1845
 * simultaneously on behalf of the same inode.
1846
 *
1847
 * As we work through the truncate and commmit bits of it to the journal there
1848
 * is one core, guiding principle: the file's tree must always be consistent on
1849
 * disk.  We must be able to restart the truncate after a crash.
1850
 *
1851
 * The file's tree may be transiently inconsistent in memory (although it
1852
 * probably isn't), but whenever we close off and commit a journal transaction,
1853
 * the contents of (the filesystem + the journal) must be consistent and
1854
 * restartable.  It's pretty simple, really: bottom up, right to left (although
1855
 * left-to-right works OK too).
1856
 *
1857
 * Note that at recovery time, journal replay occurs *before* the restart of
1858
 * truncate against the orphan inode list.
1859
 *
1860
 * The committed inode has the new, desired i_size (which is the same as
1861
 * i_disksize in this case).  After a crash, ext3_orphan_cleanup() will see
1862
 * that this inode's truncate did not complete and it will again call
1863
 * ext3_truncate() to have another go.  So there will be instantiated blocks
1864
 * to the right of the truncation point in a crashed ext3 filesystem.  But
1865
 * that's fine - as long as they are linked from the inode, the post-crash
1866
 * ext3_truncate() run will find them and release them.
1867
 */
1868
 
1869
void ext3_truncate(struct inode * inode)
1870
{
1871
        handle_t *handle;
1872
        u32 *i_data = inode->u.ext3_i.i_data;
1873
        int addr_per_block = EXT3_ADDR_PER_BLOCK(inode->i_sb);
1874
        int offsets[4];
1875
        Indirect chain[4];
1876
        Indirect *partial;
1877
        int nr = 0;
1878
        int n;
1879
        long last_block;
1880
        unsigned blocksize;
1881
 
1882
        if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
1883
            S_ISLNK(inode->i_mode)))
1884
                return;
1885
        if (ext3_inode_is_fast_symlink(inode))
1886
                return;
1887
        if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
1888
                return;
1889
 
1890
        ext3_discard_prealloc(inode);
1891
 
1892
        handle = start_transaction(inode);
1893
        if (IS_ERR(handle))
1894
                return;         /* AKPM: return what? */
1895
 
1896
        blocksize = inode->i_sb->s_blocksize;
1897
        last_block = (inode->i_size + blocksize-1)
1898
                                        >> EXT3_BLOCK_SIZE_BITS(inode->i_sb);
1899
 
1900
        ext3_block_truncate_page(handle, inode->i_mapping, inode->i_size);
1901
 
1902
 
1903
        n = ext3_block_to_path(inode, last_block, offsets);
1904
        if (n == 0)
1905
                goto out_stop;  /* error */
1906
 
1907
        /*
1908
         * OK.  This truncate is going to happen.  We add the inode to the
1909
         * orphan list, so that if this truncate spans multiple transactions,
1910
         * and we crash, we will resume the truncate when the filesystem
1911
         * recovers.  It also marks the inode dirty, to catch the new size.
1912
         *
1913
         * Implication: the file must always be in a sane, consistent
1914
         * truncatable state while each transaction commits.
1915
         */
1916
        if (ext3_orphan_add(handle, inode))
1917
                goto out_stop;
1918
 
1919
        /*
1920
         * The orphan list entry will now protect us from any crash which
1921
         * occurs before the truncate completes, so it is now safe to propagate
1922
         * the new, shorter inode size (held for now in i_size) into the
1923
         * on-disk inode. We do this via i_disksize, which is the value which
1924
         * ext3 *really* writes onto the disk inode.
1925
         */
1926
        inode->u.ext3_i.i_disksize = inode->i_size;
1927
 
1928
        /*
1929
         * From here we block out all ext3_get_block() callers who want to
1930
         * modify the block allocation tree.
1931
         */
1932
        down_write(&inode->u.ext3_i.truncate_sem);
1933
 
1934
        if (n == 1) {           /* direct blocks */
1935
                ext3_free_data(handle, inode, NULL, i_data+offsets[0],
1936
                               i_data + EXT3_NDIR_BLOCKS);
1937
                goto do_indirects;
1938
        }
1939
 
1940
        partial = ext3_find_shared(inode, n, offsets, chain, &nr);
1941
        /* Kill the top of shared branch (not detached) */
1942
        if (nr) {
1943
                if (partial == chain) {
1944
                        /* Shared branch grows from the inode */
1945
                        ext3_free_branches(handle, inode, NULL,
1946
                                           &nr, &nr+1, (chain+n-1) - partial);
1947
                        *partial->p = 0;
1948
                        /*
1949
                         * We mark the inode dirty prior to restart,
1950
                         * and prior to stop.  No need for it here.
1951
                         */
1952
                } else {
1953
                        /* Shared branch grows from an indirect block */
1954
                        BUFFER_TRACE(partial->bh, "get_write_access");
1955
                        ext3_free_branches(handle, inode, partial->bh,
1956
                                        partial->p,
1957
                                        partial->p+1, (chain+n-1) - partial);
1958
                }
1959
        }
1960
        /* Clear the ends of indirect blocks on the shared branch */
1961
        while (partial > chain) {
1962
                ext3_free_branches(handle, inode, partial->bh, partial->p + 1,
1963
                                   (u32*)partial->bh->b_data + addr_per_block,
1964
                                   (chain+n-1) - partial);
1965
                BUFFER_TRACE(partial->bh, "call brelse");
1966
                brelse (partial->bh);
1967
                partial--;
1968
        }
1969
do_indirects:
1970
        /* Kill the remaining (whole) subtrees */
1971
        switch (offsets[0]) {
1972
                default:
1973
                        nr = i_data[EXT3_IND_BLOCK];
1974
                        if (nr) {
1975
                                ext3_free_branches(handle, inode, NULL,
1976
                                                   &nr, &nr+1, 1);
1977
                                i_data[EXT3_IND_BLOCK] = 0;
1978
                        }
1979
                case EXT3_IND_BLOCK:
1980
                        nr = i_data[EXT3_DIND_BLOCK];
1981
                        if (nr) {
1982
                                ext3_free_branches(handle, inode, NULL,
1983
                                                   &nr, &nr+1, 2);
1984
                                i_data[EXT3_DIND_BLOCK] = 0;
1985
                        }
1986
                case EXT3_DIND_BLOCK:
1987
                        nr = i_data[EXT3_TIND_BLOCK];
1988
                        if (nr) {
1989
                                ext3_free_branches(handle, inode, NULL,
1990
                                                   &nr, &nr+1, 3);
1991
                                i_data[EXT3_TIND_BLOCK] = 0;
1992
                        }
1993
                case EXT3_TIND_BLOCK:
1994
                        ;
1995
        }
1996
        up_write(&inode->u.ext3_i.truncate_sem);
1997
        inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1998
        ext3_mark_inode_dirty(handle, inode);
1999
 
2000
        /* In a multi-transaction truncate, we only make the final
2001
         * transaction synchronous */
2002
        if (IS_SYNC(inode))
2003
                handle->h_sync = 1;
2004
out_stop:
2005
        /*
2006
         * If this was a simple ftruncate(), and the file will remain alive
2007
         * then we need to clear up the orphan record which we created above.
2008
         * However, if this was a real unlink then we were called by
2009
         * ext3_delete_inode(), and we allow that function to clean up the
2010
         * orphan info for us.
2011
         */
2012
        if (inode->i_nlink)
2013
                ext3_orphan_del(handle, inode);
2014
 
2015
        ext3_journal_stop(handle, inode);
2016
}
2017
 
2018
/*
2019
 * ext3_get_inode_loc returns with an extra refcount against the
2020
 * inode's underlying buffer_head on success.
2021
 */
2022
 
2023
int ext3_get_inode_loc (struct inode *inode, struct ext3_iloc *iloc)
2024
{
2025
        struct buffer_head *bh = 0;
2026
        unsigned long block;
2027
        unsigned long block_group;
2028
        unsigned long group_desc;
2029
        unsigned long desc;
2030
        unsigned long offset;
2031
        struct ext3_group_desc * gdp;
2032
 
2033
        if ((inode->i_ino != EXT3_ROOT_INO &&
2034
                inode->i_ino != EXT3_ACL_IDX_INO &&
2035
                inode->i_ino != EXT3_ACL_DATA_INO &&
2036
                inode->i_ino != EXT3_JOURNAL_INO &&
2037
                inode->i_ino < EXT3_FIRST_INO(inode->i_sb)) ||
2038
                inode->i_ino > le32_to_cpu(
2039
                        inode->i_sb->u.ext3_sb.s_es->s_inodes_count)) {
2040
                ext3_error (inode->i_sb, "ext3_get_inode_loc",
2041
                            "bad inode number: %lu", inode->i_ino);
2042
                goto bad_inode;
2043
        }
2044
        block_group = (inode->i_ino - 1) / EXT3_INODES_PER_GROUP(inode->i_sb);
2045
        if (block_group >= inode->i_sb->u.ext3_sb.s_groups_count) {
2046
                ext3_error (inode->i_sb, "ext3_get_inode_loc",
2047
                            "group >= groups count");
2048
                goto bad_inode;
2049
        }
2050
        group_desc = block_group >> EXT3_DESC_PER_BLOCK_BITS(inode->i_sb);
2051
        desc = block_group & (EXT3_DESC_PER_BLOCK(inode->i_sb) - 1);
2052
        bh = inode->i_sb->u.ext3_sb.s_group_desc[group_desc];
2053
        if (!bh) {
2054
                ext3_error (inode->i_sb, "ext3_get_inode_loc",
2055
                            "Descriptor not loaded");
2056
                goto bad_inode;
2057
        }
2058
 
2059
        gdp = (struct ext3_group_desc *) bh->b_data;
2060
        /*
2061
         * Figure out the offset within the block group inode table
2062
         */
2063
        offset = ((inode->i_ino - 1) % EXT3_INODES_PER_GROUP(inode->i_sb)) *
2064
                EXT3_INODE_SIZE(inode->i_sb);
2065
        block = le32_to_cpu(gdp[desc].bg_inode_table) +
2066
                (offset >> EXT3_BLOCK_SIZE_BITS(inode->i_sb));
2067
        if (!(bh = sb_bread(inode->i_sb, block))) {
2068
                ext3_error (inode->i_sb, "ext3_get_inode_loc",
2069
                            "unable to read inode block - "
2070
                            "inode=%lu, block=%lu", inode->i_ino, block);
2071
                goto bad_inode;
2072
        }
2073
        offset &= (EXT3_BLOCK_SIZE(inode->i_sb) - 1);
2074
 
2075
        iloc->bh = bh;
2076
        iloc->raw_inode = (struct ext3_inode *) (bh->b_data + offset);
2077
        iloc->block_group = block_group;
2078
 
2079
        return 0;
2080
 
2081
 bad_inode:
2082
        return -EIO;
2083
}
2084
 
2085
void ext3_set_inode_flags(struct inode *inode)
2086
{
2087
        unsigned int flags = inode->u.ext3_i.i_flags;
2088
 
2089
        inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME);
2090
        if (flags & EXT3_SYNC_FL)
2091
                inode->i_flags |= S_SYNC;
2092
        if (flags & EXT3_APPEND_FL)
2093
                inode->i_flags |= S_APPEND;
2094
        if (flags & EXT3_IMMUTABLE_FL)
2095
                inode->i_flags |= S_IMMUTABLE;
2096
        if (flags & EXT3_NOATIME_FL)
2097
                inode->i_flags |= S_NOATIME;
2098
}
2099
 
2100
 
2101
void ext3_read_inode(struct inode * inode)
2102
{
2103
        struct ext3_iloc iloc;
2104
        struct ext3_inode *raw_inode;
2105
        struct buffer_head *bh;
2106
        int block;
2107
 
2108
        if(ext3_get_inode_loc(inode, &iloc))
2109
                goto bad_inode;
2110
        bh = iloc.bh;
2111
        raw_inode = iloc.raw_inode;
2112
        init_rwsem(&inode->u.ext3_i.truncate_sem);
2113
        inode->i_mode = le16_to_cpu(raw_inode->i_mode);
2114
        inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
2115
        inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
2116
        if(!(test_opt (inode->i_sb, NO_UID32))) {
2117
                inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
2118
                inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
2119
        }
2120
        inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
2121
        inode->i_size = le32_to_cpu(raw_inode->i_size);
2122
        inode->i_atime = le32_to_cpu(raw_inode->i_atime);
2123
        inode->i_ctime = le32_to_cpu(raw_inode->i_ctime);
2124
        inode->i_mtime = le32_to_cpu(raw_inode->i_mtime);
2125
        inode->u.ext3_i.i_dtime = le32_to_cpu(raw_inode->i_dtime);
2126
        /* We now have enough fields to check if the inode was active or not.
2127
         * This is needed because nfsd might try to access dead inodes
2128
         * the test is that same one that e2fsck uses
2129
         * NeilBrown 1999oct15
2130
         */
2131
        if (inode->i_nlink == 0) {
2132
                if (inode->i_mode == 0 ||
2133
                    !(inode->i_sb->u.ext3_sb.s_mount_state & EXT3_ORPHAN_FS)) {
2134
                        /* this inode is deleted */
2135
                        brelse (bh);
2136
                        goto bad_inode;
2137
                }
2138
                /* The only unlinked inodes we let through here have
2139
                 * valid i_mode and are being read by the orphan
2140
                 * recovery code: that's fine, we're about to complete
2141
                 * the process of deleting those. */
2142
        }
2143
        inode->i_blksize = PAGE_SIZE;   /* This is the optimal IO size
2144
                                         * (for stat), not the fs block
2145
                                         * size */
2146
        inode->i_blocks = le32_to_cpu(raw_inode->i_blocks);
2147
        inode->i_version = ++event;
2148
        inode->u.ext3_i.i_flags = le32_to_cpu(raw_inode->i_flags);
2149
#ifdef EXT3_FRAGMENTS
2150
        inode->u.ext3_i.i_faddr = le32_to_cpu(raw_inode->i_faddr);
2151
        inode->u.ext3_i.i_frag_no = raw_inode->i_frag;
2152
        inode->u.ext3_i.i_frag_size = raw_inode->i_fsize;
2153
#endif
2154
        inode->u.ext3_i.i_file_acl = le32_to_cpu(raw_inode->i_file_acl);
2155
        if (!S_ISREG(inode->i_mode)) {
2156
                inode->u.ext3_i.i_dir_acl = le32_to_cpu(raw_inode->i_dir_acl);
2157
        } else {
2158
                inode->i_size |=
2159
                        ((__u64)le32_to_cpu(raw_inode->i_size_high)) << 32;
2160
        }
2161
        inode->u.ext3_i.i_disksize = inode->i_size;
2162
        inode->i_generation = le32_to_cpu(raw_inode->i_generation);
2163
#ifdef EXT3_PREALLOCATE
2164
        inode->u.ext3_i.i_prealloc_count = 0;
2165
#endif
2166
        inode->u.ext3_i.i_block_group = iloc.block_group;
2167
 
2168
        /*
2169
         * NOTE! The in-memory inode i_data array is in little-endian order
2170
         * even on big-endian machines: we do NOT byteswap the block numbers!
2171
         */
2172
        for (block = 0; block < EXT3_N_BLOCKS; block++)
2173
                inode->u.ext3_i.i_data[block] = iloc.raw_inode->i_block[block];
2174
        INIT_LIST_HEAD(&inode->u.ext3_i.i_orphan);
2175
 
2176
        if (inode->i_ino == EXT3_ACL_IDX_INO ||
2177
            inode->i_ino == EXT3_ACL_DATA_INO)
2178
                /* Nothing to do */ ;
2179
        else if (S_ISREG(inode->i_mode)) {
2180
                inode->i_op = &ext3_file_inode_operations;
2181
                inode->i_fop = &ext3_file_operations;
2182
                inode->i_mapping->a_ops = &ext3_aops;
2183
        } else if (S_ISDIR(inode->i_mode)) {
2184
                inode->i_op = &ext3_dir_inode_operations;
2185
                inode->i_fop = &ext3_dir_operations;
2186
        } else if (S_ISLNK(inode->i_mode)) {
2187
                if (ext3_inode_is_fast_symlink(inode))
2188
                        inode->i_op = &ext3_fast_symlink_inode_operations;
2189
                else {
2190
                        inode->i_op = &page_symlink_inode_operations;
2191
                        inode->i_mapping->a_ops = &ext3_aops;
2192
                }
2193
        } else
2194
                init_special_inode(inode, inode->i_mode,
2195
                                   le32_to_cpu(iloc.raw_inode->i_block[0]));
2196
        brelse(iloc.bh);
2197
        ext3_set_inode_flags(inode);
2198
        return;
2199
 
2200
bad_inode:
2201
        make_bad_inode(inode);
2202
        return;
2203
}
2204
 
2205
/*
2206
 * Post the struct inode info into an on-disk inode location in the
2207
 * buffer-cache.  This gobbles the caller's reference to the
2208
 * buffer_head in the inode location struct.
2209
 */
2210
 
2211
static int ext3_do_update_inode(handle_t *handle,
2212
                                struct inode *inode,
2213
                                struct ext3_iloc *iloc)
2214
{
2215
        struct ext3_inode *raw_inode = iloc->raw_inode;
2216
        struct buffer_head *bh = iloc->bh;
2217
        int err = 0, rc, block;
2218
 
2219
        if (handle) {
2220
                BUFFER_TRACE(bh, "get_write_access");
2221
                err = ext3_journal_get_write_access(handle, bh);
2222
                if (err)
2223
                        goto out_brelse;
2224
        }
2225
        /* For fields not not tracking in the in-memory inode,
2226
         * initialise them to zero for new inodes. */
2227
        if (EXT3_I(inode)->i_state & EXT3_STATE_NEW)
2228
                memset(raw_inode, 0, EXT3_SB(inode->i_sb)->s_inode_size);
2229
 
2230
        raw_inode->i_mode = cpu_to_le16(inode->i_mode);
2231
        if(!(test_opt(inode->i_sb, NO_UID32))) {
2232
                raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
2233
                raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
2234
/*
2235
 * Fix up interoperability with old kernels. Otherwise, old inodes get
2236
 * re-used with the upper 16 bits of the uid/gid intact
2237
 */
2238
                if(!inode->u.ext3_i.i_dtime) {
2239
                        raw_inode->i_uid_high =
2240
                                cpu_to_le16(high_16_bits(inode->i_uid));
2241
                        raw_inode->i_gid_high =
2242
                                cpu_to_le16(high_16_bits(inode->i_gid));
2243
                } else {
2244
                        raw_inode->i_uid_high = 0;
2245
                        raw_inode->i_gid_high = 0;
2246
                }
2247
        } else {
2248
                raw_inode->i_uid_low =
2249
                        cpu_to_le16(fs_high2lowuid(inode->i_uid));
2250
                raw_inode->i_gid_low =
2251
                        cpu_to_le16(fs_high2lowgid(inode->i_gid));
2252
                raw_inode->i_uid_high = 0;
2253
                raw_inode->i_gid_high = 0;
2254
        }
2255
        raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
2256
        raw_inode->i_size = cpu_to_le32(inode->u.ext3_i.i_disksize);
2257
        raw_inode->i_atime = cpu_to_le32(inode->i_atime);
2258
        raw_inode->i_ctime = cpu_to_le32(inode->i_ctime);
2259
        raw_inode->i_mtime = cpu_to_le32(inode->i_mtime);
2260
        raw_inode->i_blocks = cpu_to_le32(inode->i_blocks);
2261
        raw_inode->i_dtime = cpu_to_le32(inode->u.ext3_i.i_dtime);
2262
        raw_inode->i_flags = cpu_to_le32(inode->u.ext3_i.i_flags);
2263
#ifdef EXT3_FRAGMENTS
2264
        raw_inode->i_faddr = cpu_to_le32(inode->u.ext3_i.i_faddr);
2265
        raw_inode->i_frag = inode->u.ext3_i.i_frag_no;
2266
        raw_inode->i_fsize = inode->u.ext3_i.i_frag_size;
2267
#endif
2268
        raw_inode->i_file_acl = cpu_to_le32(inode->u.ext3_i.i_file_acl);
2269
        if (!S_ISREG(inode->i_mode)) {
2270
                raw_inode->i_dir_acl = cpu_to_le32(inode->u.ext3_i.i_dir_acl);
2271
        } else {
2272
                raw_inode->i_size_high =
2273
                        cpu_to_le32(inode->u.ext3_i.i_disksize >> 32);
2274
                if (inode->u.ext3_i.i_disksize > 0x7fffffffULL) {
2275
                        struct super_block *sb = inode->i_sb;
2276
                        if (!EXT3_HAS_RO_COMPAT_FEATURE(sb,
2277
                                        EXT3_FEATURE_RO_COMPAT_LARGE_FILE) ||
2278
                            EXT3_SB(sb)->s_es->s_rev_level ==
2279
                                        cpu_to_le32(EXT3_GOOD_OLD_REV)) {
2280
                               /* If this is the first large file
2281
                                * created, add a flag to the superblock.
2282
                                */
2283
                                err = ext3_journal_get_write_access(handle,
2284
                                                sb->u.ext3_sb.s_sbh);
2285
                                if (err)
2286
                                        goto out_brelse;
2287
                                ext3_update_dynamic_rev(sb);
2288
                                EXT3_SET_RO_COMPAT_FEATURE(sb,
2289
                                        EXT3_FEATURE_RO_COMPAT_LARGE_FILE);
2290
                                sb->s_dirt = 1;
2291
                                handle->h_sync = 1;
2292
                                err = ext3_journal_dirty_metadata(handle,
2293
                                                sb->u.ext3_sb.s_sbh);
2294
                        }
2295
                }
2296
        }
2297
        raw_inode->i_generation = cpu_to_le32(inode->i_generation);
2298
        if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
2299
                raw_inode->i_block[0] =
2300
                        cpu_to_le32(kdev_t_to_nr(inode->i_rdev));
2301
        else for (block = 0; block < EXT3_N_BLOCKS; block++)
2302
                raw_inode->i_block[block] = inode->u.ext3_i.i_data[block];
2303
 
2304
        BUFFER_TRACE(bh, "call ext3_journal_dirty_metadata");
2305
        rc = ext3_journal_dirty_metadata(handle, bh);
2306
        if (!err)
2307
                err = rc;
2308
        EXT3_I(inode)->i_state &= ~EXT3_STATE_NEW;
2309
 
2310
out_brelse:
2311
        brelse (bh);
2312
        ext3_std_error(inode->i_sb, err);
2313
        return err;
2314
}
2315
 
2316
/*
2317
 * ext3_write_inode()
2318
 *
2319
 * We are called from a few places:
2320
 *
2321
 * - Within generic_file_write() for O_SYNC files.
2322
 *   Here, there will be no transaction running. We wait for any running
2323
 *   trasnaction to commit.
2324
 *
2325
 * - Within sys_sync(), kupdate and such.
2326
 *   We wait on commit, if tol to.
2327
 *
2328
 * - Within prune_icache() (PF_MEMALLOC == true)
2329
 *   Here we simply return.  We can't afford to block kswapd on the
2330
 *   journal commit.
2331
 *
2332
 * In all cases it is actually safe for us to return without doing anything,
2333
 * because the inode has been copied into a raw inode buffer in
2334
 * ext3_mark_inode_dirty().  This is a correctness thing for O_SYNC and for
2335
 * knfsd.
2336
 *
2337
 * Note that we are absolutely dependent upon all inode dirtiers doing the
2338
 * right thing: they *must* call mark_inode_dirty() after dirtying info in
2339
 * which we are interested.
2340
 *
2341
 * It would be a bug for them to not do this.  The code:
2342
 *
2343
 *      mark_inode_dirty(inode)
2344
 *      stuff();
2345
 *      inode->i_size = expr;
2346
 *
2347
 * is in error because a kswapd-driven write_inode() could occur while
2348
 * `stuff()' is running, and the new i_size will be lost.  Plus the inode
2349
 * will no longer be on the superblock's dirty inode list.
2350
 */
2351
void ext3_write_inode(struct inode *inode, int wait)
2352
{
2353
        if (current->flags & PF_MEMALLOC)
2354
                return;
2355
 
2356
        if (ext3_journal_current_handle()) {
2357
                jbd_debug(0, "called recursively, non-PF_MEMALLOC!\n");
2358
                return;
2359
        }
2360
 
2361
        if (!wait)
2362
                return;
2363
 
2364
        ext3_force_commit(inode->i_sb);
2365
}
2366
 
2367
/*
2368
 * ext3_setattr()
2369
 *
2370
 * Called from notify_change.
2371
 *
2372
 * We want to trap VFS attempts to truncate the file as soon as
2373
 * possible.  In particular, we want to make sure that when the VFS
2374
 * shrinks i_size, we put the inode on the orphan list and modify
2375
 * i_disksize immediately, so that during the subsequent flushing of
2376
 * dirty pages and freeing of disk blocks, we can guarantee that any
2377
 * commit will leave the blocks being flushed in an unused state on
2378
 * disk.  (On recovery, the inode will get truncated and the blocks will
2379
 * be freed, so we have a strong guarantee that no future commit will
2380
 * leave these blocks visible to the user.)
2381
 *
2382
 * This is only needed for regular files.  rmdir() has its own path, and
2383
 * we can never truncate a direcory except on final unlink (at which
2384
 * point i_nlink is zero so recovery is easy.)
2385
 *
2386
 * Called with the BKL.
2387
 */
2388
 
2389
int ext3_setattr(struct dentry *dentry, struct iattr *attr)
2390
{
2391
        struct inode *inode = dentry->d_inode;
2392
        int error, rc = 0;
2393
        const unsigned int ia_valid = attr->ia_valid;
2394
 
2395
        error = inode_change_ok(inode, attr);
2396
        if (error)
2397
                return error;
2398
 
2399
        if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
2400
                (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
2401
                error = DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
2402
                if (error)
2403
                        return error;
2404
        }
2405
 
2406
        if (attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
2407
                handle_t *handle;
2408
 
2409
                handle = ext3_journal_start(inode, 3);
2410
                if (IS_ERR(handle)) {
2411
                        error = PTR_ERR(handle);
2412
                        goto err_out;
2413
                }
2414
 
2415
                error = ext3_orphan_add(handle, inode);
2416
                inode->u.ext3_i.i_disksize = attr->ia_size;
2417
                rc = ext3_mark_inode_dirty(handle, inode);
2418
                if (!error)
2419
                        error = rc;
2420
                ext3_journal_stop(handle, inode);
2421
        }
2422
 
2423
        rc = inode_setattr(inode, attr);
2424
 
2425
        /* If inode_setattr's call to ext3_truncate failed to get a
2426
         * transaction handle at all, we need to clean up the in-core
2427
         * orphan list manually. */
2428
        if (inode->i_nlink)
2429
                ext3_orphan_del(NULL, inode);
2430
 
2431
err_out:
2432
        ext3_std_error(inode->i_sb, error);
2433
        if (!error)
2434
                error = rc;
2435
        return error;
2436
}
2437
 
2438
 
2439
/*
2440
 * akpm: how many blocks doth make a writepage()?
2441
 *
2442
 * With N blocks per page, it may be:
2443
 * N data blocks
2444
 * 2 indirect block
2445
 * 2 dindirect
2446
 * 1 tindirect
2447
 * N+5 bitmap blocks (from the above)
2448
 * N+5 group descriptor summary blocks
2449
 * 1 inode block
2450
 * 1 superblock.
2451
 * 2 * EXT3_SINGLEDATA_TRANS_BLOCKS for the quote files
2452
 *
2453
 * 3 * (N + 5) + 2 + 2 * EXT3_SINGLEDATA_TRANS_BLOCKS
2454
 *
2455
 * With ordered or writeback data it's the same, less the N data blocks.
2456
 *
2457
 * If the inode's direct blocks can hold an integral number of pages then a
2458
 * page cannot straddle two indirect blocks, and we can only touch one indirect
2459
 * and dindirect block, and the "5" above becomes "3".
2460
 *
2461
 * This still overestimates under most circumstances.  If we were to pass the
2462
 * start and end offsets in here as well we could do block_to_path() on each
2463
 * block and work out the exact number of indirects which are touched.  Pah.
2464
 */
2465
 
2466
int ext3_writepage_trans_blocks(struct inode *inode)
2467
{
2468
        int bpp = ext3_journal_blocks_per_page(inode);
2469
        int indirects = (EXT3_NDIR_BLOCKS % bpp) ? 5 : 3;
2470
        int ret;
2471
 
2472
        if (ext3_should_journal_data(inode))
2473
                ret = 3 * (bpp + indirects) + 2;
2474
        else
2475
                ret = 2 * (bpp + indirects) + 2;
2476
 
2477
#ifdef CONFIG_QUOTA
2478
        ret += 2 * EXT3_SINGLEDATA_TRANS_BLOCKS;
2479
#endif
2480
 
2481
        return ret;
2482
}
2483
 
2484
int
2485
ext3_mark_iloc_dirty(handle_t *handle,
2486
                     struct inode *inode,
2487
                     struct ext3_iloc *iloc)
2488
{
2489
        int err = 0;
2490
 
2491
        if (handle) {
2492
                /* the do_update_inode consumes one bh->b_count */
2493
                atomic_inc(&iloc->bh->b_count);
2494
                err = ext3_do_update_inode(handle, inode, iloc);
2495
                /* ext3_do_update_inode() does journal_dirty_metadata */
2496
                brelse(iloc->bh);
2497
        } else {
2498
                printk(KERN_EMERG "%s: called with no handle!\n", __FUNCTION__);
2499
        }
2500
        return err;
2501
}
2502
 
2503
/*
2504
 * On success, We end up with an outstanding reference count against
2505
 * iloc->bh.  This _must_ be cleaned up later.
2506
 */
2507
 
2508
int
2509
ext3_reserve_inode_write(handle_t *handle, struct inode *inode,
2510
                         struct ext3_iloc *iloc)
2511
{
2512
        int err = 0;
2513
        if (handle) {
2514
                err = ext3_get_inode_loc(inode, iloc);
2515
                if (!err) {
2516
                        BUFFER_TRACE(iloc->bh, "get_write_access");
2517
                        err = ext3_journal_get_write_access(handle, iloc->bh);
2518
                        if (err) {
2519
                                brelse(iloc->bh);
2520
                                iloc->bh = NULL;
2521
                        }
2522
                }
2523
        }
2524
        ext3_std_error(inode->i_sb, err);
2525
        return err;
2526
}
2527
 
2528
/*
2529
 * akpm: What we do here is to mark the in-core inode as clean
2530
 * with respect to inode dirtiness (it may still be data-dirty).
2531
 * This means that the in-core inode may be reaped by prune_icache
2532
 * without having to perform any I/O.  This is a very good thing,
2533
 * because *any* task may call prune_icache - even ones which
2534
 * have a transaction open against a different journal.
2535
 *
2536
 * Is this cheating?  Not really.  Sure, we haven't written the
2537
 * inode out, but prune_icache isn't a user-visible syncing function.
2538
 * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
2539
 * we start and wait on commits.
2540
 *
2541
 * Is this efficient/effective?  Well, we're being nice to the system
2542
 * by cleaning up our inodes proactively so they can be reaped
2543
 * without I/O.  But we are potentially leaving up to five seconds'
2544
 * worth of inodes floating about which prune_icache wants us to
2545
 * write out.  One way to fix that would be to get prune_icache()
2546
 * to do a write_super() to free up some memory.  It has the desired
2547
 * effect.
2548
 */
2549
int ext3_mark_inode_dirty(handle_t *handle, struct inode *inode)
2550
{
2551
        struct ext3_iloc iloc;
2552
        int err;
2553
 
2554
        err = ext3_reserve_inode_write(handle, inode, &iloc);
2555
        if (!err)
2556
                err = ext3_mark_iloc_dirty(handle, inode, &iloc);
2557
        return err;
2558
}
2559
 
2560
/*
2561
 * akpm: ext3_dirty_inode() is called from __mark_inode_dirty()
2562
 *
2563
 * We're really interested in the case where a file is being extended.
2564
 * i_size has been changed by generic_commit_write() and we thus need
2565
 * to include the updated inode in the current transaction.
2566
 *
2567
 * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
2568
 * are allocated to the file.
2569
 *
2570
 * If the inode is marked synchronous, we don't honour that here - doing
2571
 * so would cause a commit on atime updates, which we don't bother doing.
2572
 * We handle synchronous inodes at the highest possible level.
2573
 */
2574
void ext3_dirty_inode(struct inode *inode)
2575
{
2576
        handle_t *current_handle = ext3_journal_current_handle();
2577
        handle_t *handle;
2578
 
2579
        lock_kernel();
2580
        handle = ext3_journal_start(inode, 2);
2581
        if (IS_ERR(handle))
2582
                goto out;
2583
        if (current_handle &&
2584
                current_handle->h_transaction != handle->h_transaction) {
2585
                /* This task has a transaction open against a different fs */
2586
                printk(KERN_EMERG "%s: transactions do not match!\n",
2587
                        __FUNCTION__);
2588
        } else {
2589
                jbd_debug(5, "marking dirty.  outer handle=%p\n",
2590
                                current_handle);
2591
                ext3_mark_inode_dirty(handle, inode);
2592
        }
2593
        ext3_journal_stop(handle, inode);
2594
out:
2595
        unlock_kernel();
2596
}
2597
 
2598
#ifdef AKPM
2599
/*
2600
 * Bind an inode's backing buffer_head into this transaction, to prevent
2601
 * it from being flushed to disk early.  Unlike
2602
 * ext3_reserve_inode_write, this leaves behind no bh reference and
2603
 * returns no iloc structure, so the caller needs to repeat the iloc
2604
 * lookup to mark the inode dirty later.
2605
 */
2606
static inline int
2607
ext3_pin_inode(handle_t *handle, struct inode *inode)
2608
{
2609
        struct ext3_iloc iloc;
2610
 
2611
        int err = 0;
2612
        if (handle) {
2613
                err = ext3_get_inode_loc(inode, &iloc);
2614
                if (!err) {
2615
                        BUFFER_TRACE(iloc.bh, "get_write_access");
2616
                        err = journal_get_write_access(handle, iloc.bh);
2617
                        if (!err)
2618
                                err = ext3_journal_dirty_metadata(handle,
2619
                                                                  iloc.bh);
2620
                        brelse(iloc.bh);
2621
                }
2622
        }
2623
        ext3_std_error(inode->i_sb, err);
2624
        return err;
2625
}
2626
#endif
2627
 
2628
int ext3_change_inode_journal_flag(struct inode *inode, int val)
2629
{
2630
        journal_t *journal;
2631
        handle_t *handle;
2632
        int err;
2633
 
2634
        /*
2635
         * We have to be very careful here: changing a data block's
2636
         * journaling status dynamically is dangerous.  If we write a
2637
         * data block to the journal, change the status and then delete
2638
         * that block, we risk forgetting to revoke the old log record
2639
         * from the journal and so a subsequent replay can corrupt data.
2640
         * So, first we make sure that the journal is empty and that
2641
         * nobody is changing anything.
2642
         */
2643
 
2644
        journal = EXT3_JOURNAL(inode);
2645
        if (is_journal_aborted(journal) || IS_RDONLY(inode))
2646
                return -EROFS;
2647
 
2648
        journal_lock_updates(journal);
2649
        journal_flush(journal);
2650
 
2651
        /*
2652
         * OK, there are no updates running now, and all cached data is
2653
         * synced to disk.  We are now in a completely consistent state
2654
         * which doesn't have anything in the journal, and we know that
2655
         * no filesystem updates are running, so it is safe to modify
2656
         * the inode's in-core data-journaling state flag now.
2657
         */
2658
 
2659
        if (val)
2660
                inode->u.ext3_i.i_flags |= EXT3_JOURNAL_DATA_FL;
2661
        else
2662
                inode->u.ext3_i.i_flags &= ~EXT3_JOURNAL_DATA_FL;
2663
 
2664
        journal_unlock_updates(journal);
2665
 
2666
        /* Finally we can mark the inode as dirty. */
2667
 
2668
        handle = ext3_journal_start(inode, 1);
2669
        if (IS_ERR(handle))
2670
                return PTR_ERR(handle);
2671
 
2672
        err = ext3_mark_inode_dirty(handle, inode);
2673
        handle->h_sync = 1;
2674
        ext3_journal_stop(handle, inode);
2675
        ext3_std_error(inode->i_sb, err);
2676
 
2677
        return err;
2678
}
2679
 
2680
 
2681
/*
2682
 * ext3_aops_journal_start().
2683
 *
2684
 * <This function died, but the comment lives on>
2685
 *
2686
 * We need to take the inode semaphore *outside* the
2687
 * journal_start/journal_stop.  Otherwise, a different task could do a
2688
 * wait_for_commit() while holding ->i_sem, which deadlocks.  The rule
2689
 * is: transaction open/closes are considered to be a locking operation
2690
 * and they nest *inside* ->i_sem.
2691
 * ----------------------------------------------------------------------------
2692
 * Possible problem:
2693
 *      ext3_file_write()
2694
 *      -> generic_file_write()
2695
 *         -> __alloc_pages()
2696
 *            -> page_launder()
2697
 *               -> ext3_writepage()
2698
 *
2699
 * And the writepage can be on a different fs while we have a
2700
 * transaction open against this one!  Bad.
2701
 *
2702
 * I tried making the task PF_MEMALLOC here, but that simply results in
2703
 * 0-order allocation failures passed back to generic_file_write().
2704
 * Instead, we rely on the reentrancy protection in ext3_writepage().
2705
 * ----------------------------------------------------------------------------
2706
 * When we do the journal_start() here we don't really need to reserve
2707
 * any blocks - we won't need any until we hit ext3_prepare_write(),
2708
 * which does all the needed journal extending.  However!  There is a
2709
 * problem with quotas:
2710
 *
2711
 * Thread 1:
2712
 * sys_sync
2713
 * ->sync_dquots
2714
 *   ->commit_dquot
2715
 *     ->lock_dquot
2716
 *     ->write_dquot
2717
 *       ->ext3_file_write
2718
 *         ->journal_start
2719
 *         ->ext3_prepare_write
2720
 *           ->journal_extend
2721
 *           ->journal_start
2722
 * Thread 2:
2723
 * ext3_create          (for example)
2724
 * ->ext3_new_inode
2725
 *   ->dquot_initialize
2726
 *     ->lock_dquot
2727
 *
2728
 * Deadlock.  Thread 1's journal_start blocks because thread 2 has a
2729
 * transaction open.  Thread 2's transaction will never close because
2730
 * thread 2 is stuck waiting for the dquot lock.
2731
 *
2732
 * So.  We must ensure that thread 1 *never* needs to extend the journal
2733
 * for quota writes.  We do that by reserving enough journal blocks
2734
 * here, in ext3_aops_journal_start() to ensure that the forthcoming "see if we
2735
 * need to extend" test in ext3_prepare_write() succeeds.
2736
 */

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.