Merge git://git.kernel.org/pub/scm/linux/kernel/git/bunk/trivial
[safe/jmp/linux-2.6] / fs / reiserfs / inode.c
1 /*
2  * Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
3  */
4
5 #include <linux/time.h>
6 #include <linux/fs.h>
7 #include <linux/reiserfs_fs.h>
8 #include <linux/reiserfs_acl.h>
9 #include <linux/reiserfs_xattr.h>
10 #include <linux/smp_lock.h>
11 #include <linux/pagemap.h>
12 #include <linux/highmem.h>
13 #include <asm/uaccess.h>
14 #include <asm/unaligned.h>
15 #include <linux/buffer_head.h>
16 #include <linux/mpage.h>
17 #include <linux/writeback.h>
18 #include <linux/quotaops.h>
19
20 extern int reiserfs_default_io_size;    /* default io size devuned in super.c */
21
22 static int reiserfs_commit_write(struct file *f, struct page *page,
23                                  unsigned from, unsigned to);
24 static int reiserfs_prepare_write(struct file *f, struct page *page,
25                                   unsigned from, unsigned to);
26
27 void reiserfs_delete_inode(struct inode *inode)
28 {
29         /* We need blocks for transaction + (user+group) quota update (possibly delete) */
30         int jbegin_count =
31             JOURNAL_PER_BALANCE_CNT * 2 +
32             2 * REISERFS_QUOTA_INIT_BLOCKS(inode->i_sb);
33         struct reiserfs_transaction_handle th;
34         int err;
35
36         truncate_inode_pages(&inode->i_data, 0);
37
38         reiserfs_write_lock(inode->i_sb);
39
40         /* The = 0 happens when we abort creating a new inode for some reason like lack of space.. */
41         if (!(inode->i_state & I_NEW) && INODE_PKEY(inode)->k_objectid != 0) {  /* also handles bad_inode case */
42                 mutex_lock(&inode->i_mutex);
43
44                 reiserfs_delete_xattrs(inode);
45
46                 if (journal_begin(&th, inode->i_sb, jbegin_count)) {
47                         mutex_unlock(&inode->i_mutex);
48                         goto out;
49                 }
50                 reiserfs_update_inode_transaction(inode);
51
52                 err = reiserfs_delete_object(&th, inode);
53
54                 /* Do quota update inside a transaction for journaled quotas. We must do that
55                  * after delete_object so that quota updates go into the same transaction as
56                  * stat data deletion */
57                 if (!err) 
58                         DQUOT_FREE_INODE(inode);
59
60                 if (journal_end(&th, inode->i_sb, jbegin_count)) {
61                         mutex_unlock(&inode->i_mutex);
62                         goto out;
63                 }
64
65                 mutex_unlock(&inode->i_mutex);
66
67                 /* check return value from reiserfs_delete_object after
68                  * ending the transaction
69                  */
70                 if (err)
71                     goto out;
72
73                 /* all items of file are deleted, so we can remove "save" link */
74                 remove_save_link(inode, 0 /* not truncate */ ); /* we can't do anything
75                                                                  * about an error here */
76         } else {
77                 /* no object items are in the tree */
78                 ;
79         }
80       out:
81         clear_inode(inode);     /* note this must go after the journal_end to prevent deadlock */
82         inode->i_blocks = 0;
83         reiserfs_write_unlock(inode->i_sb);
84 }
85
86 static void _make_cpu_key(struct cpu_key *key, int version, __u32 dirid,
87                           __u32 objectid, loff_t offset, int type, int length)
88 {
89         key->version = version;
90
91         key->on_disk_key.k_dir_id = dirid;
92         key->on_disk_key.k_objectid = objectid;
93         set_cpu_key_k_offset(key, offset);
94         set_cpu_key_k_type(key, type);
95         key->key_length = length;
96 }
97
98 /* take base of inode_key (it comes from inode always) (dirid, objectid) and version from an inode, set
99    offset and type of key */
100 void make_cpu_key(struct cpu_key *key, struct inode *inode, loff_t offset,
101                   int type, int length)
102 {
103         _make_cpu_key(key, get_inode_item_key_version(inode),
104                       le32_to_cpu(INODE_PKEY(inode)->k_dir_id),
105                       le32_to_cpu(INODE_PKEY(inode)->k_objectid), offset, type,
106                       length);
107 }
108
109 //
110 // when key is 0, do not set version and short key
111 //
112 inline void make_le_item_head(struct item_head *ih, const struct cpu_key *key,
113                               int version,
114                               loff_t offset, int type, int length,
115                               int entry_count /*or ih_free_space */ )
116 {
117         if (key) {
118                 ih->ih_key.k_dir_id = cpu_to_le32(key->on_disk_key.k_dir_id);
119                 ih->ih_key.k_objectid =
120                     cpu_to_le32(key->on_disk_key.k_objectid);
121         }
122         put_ih_version(ih, version);
123         set_le_ih_k_offset(ih, offset);
124         set_le_ih_k_type(ih, type);
125         put_ih_item_len(ih, length);
126         /*    set_ih_free_space (ih, 0); */
127         // for directory items it is entry count, for directs and stat
128         // datas - 0xffff, for indirects - 0
129         put_ih_entry_count(ih, entry_count);
130 }
131
132 //
133 // FIXME: we might cache recently accessed indirect item
134
135 // Ugh.  Not too eager for that....
136 //  I cut the code until such time as I see a convincing argument (benchmark).
137 // I don't want a bloated inode struct..., and I don't like code complexity....
138
139 /* cutting the code is fine, since it really isn't in use yet and is easy
140 ** to add back in.  But, Vladimir has a really good idea here.  Think
141 ** about what happens for reading a file.  For each page,
142 ** The VFS layer calls reiserfs_readpage, who searches the tree to find
143 ** an indirect item.  This indirect item has X number of pointers, where
144 ** X is a big number if we've done the block allocation right.  But,
145 ** we only use one or two of these pointers during each call to readpage,
146 ** needlessly researching again later on.
147 **
148 ** The size of the cache could be dynamic based on the size of the file.
149 **
150 ** I'd also like to see us cache the location the stat data item, since
151 ** we are needlessly researching for that frequently.
152 **
153 ** --chris
154 */
155
156 /* If this page has a file tail in it, and
157 ** it was read in by get_block_create_0, the page data is valid,
158 ** but tail is still sitting in a direct item, and we can't write to
159 ** it.  So, look through this page, and check all the mapped buffers
160 ** to make sure they have valid block numbers.  Any that don't need
161 ** to be unmapped, so that block_prepare_write will correctly call
162 ** reiserfs_get_block to convert the tail into an unformatted node
163 */
164 static inline void fix_tail_page_for_writing(struct page *page)
165 {
166         struct buffer_head *head, *next, *bh;
167
168         if (page && page_has_buffers(page)) {
169                 head = page_buffers(page);
170                 bh = head;
171                 do {
172                         next = bh->b_this_page;
173                         if (buffer_mapped(bh) && bh->b_blocknr == 0) {
174                                 reiserfs_unmap_buffer(bh);
175                         }
176                         bh = next;
177                 } while (bh != head);
178         }
179 }
180
181 /* reiserfs_get_block does not need to allocate a block only if it has been
182    done already or non-hole position has been found in the indirect item */
183 static inline int allocation_needed(int retval, b_blocknr_t allocated,
184                                     struct item_head *ih,
185                                     __le32 * item, int pos_in_item)
186 {
187         if (allocated)
188                 return 0;
189         if (retval == POSITION_FOUND && is_indirect_le_ih(ih) &&
190             get_block_num(item, pos_in_item))
191                 return 0;
192         return 1;
193 }
194
195 static inline int indirect_item_found(int retval, struct item_head *ih)
196 {
197         return (retval == POSITION_FOUND) && is_indirect_le_ih(ih);
198 }
199
200 static inline void set_block_dev_mapped(struct buffer_head *bh,
201                                         b_blocknr_t block, struct inode *inode)
202 {
203         map_bh(bh, inode->i_sb, block);
204 }
205
206 //
207 // files which were created in the earlier version can not be longer,
208 // than 2 gb
209 //
210 static int file_capable(struct inode *inode, long block)
211 {
212         if (get_inode_item_key_version(inode) != KEY_FORMAT_3_5 ||      // it is new file.
213             block < (1 << (31 - inode->i_sb->s_blocksize_bits)))        // old file, but 'block' is inside of 2gb
214                 return 1;
215
216         return 0;
217 }
218
219 /*static*/ int restart_transaction(struct reiserfs_transaction_handle *th,
220                                    struct inode *inode, struct path *path)
221 {
222         struct super_block *s = th->t_super;
223         int len = th->t_blocks_allocated;
224         int err;
225
226         BUG_ON(!th->t_trans_id);
227         BUG_ON(!th->t_refcount);
228
229         /* we cannot restart while nested */
230         if (th->t_refcount > 1) {
231                 return 0;
232         }
233         pathrelse(path);
234         reiserfs_update_sd(th, inode);
235         err = journal_end(th, s, len);
236         if (!err) {
237                 err = journal_begin(th, s, JOURNAL_PER_BALANCE_CNT * 6);
238                 if (!err)
239                         reiserfs_update_inode_transaction(inode);
240         }
241         return err;
242 }
243
244 // it is called by get_block when create == 0. Returns block number
245 // for 'block'-th logical block of file. When it hits direct item it
246 // returns 0 (being called from bmap) or read direct item into piece
247 // of page (bh_result)
248
249 // Please improve the english/clarity in the comment above, as it is
250 // hard to understand.
251
252 static int _get_block_create_0(struct inode *inode, long block,
253                                struct buffer_head *bh_result, int args)
254 {
255         INITIALIZE_PATH(path);
256         struct cpu_key key;
257         struct buffer_head *bh;
258         struct item_head *ih, tmp_ih;
259         int fs_gen;
260         int blocknr;
261         char *p = NULL;
262         int chars;
263         int ret;
264         int result;
265         int done = 0;
266         unsigned long offset;
267
268         // prepare the key to look for the 'block'-th block of file
269         make_cpu_key(&key, inode,
270                      (loff_t) block * inode->i_sb->s_blocksize + 1, TYPE_ANY,
271                      3);
272
273       research:
274         result = search_for_position_by_key(inode->i_sb, &key, &path);
275         if (result != POSITION_FOUND) {
276                 pathrelse(&path);
277                 if (p)
278                         kunmap(bh_result->b_page);
279                 if (result == IO_ERROR)
280                         return -EIO;
281                 // We do not return -ENOENT if there is a hole but page is uptodate, because it means
282                 // That there is some MMAPED data associated with it that is yet to be written to disk.
283                 if ((args & GET_BLOCK_NO_HOLE)
284                     && !PageUptodate(bh_result->b_page)) {
285                         return -ENOENT;
286                 }
287                 return 0;
288         }
289         //
290         bh = get_last_bh(&path);
291         ih = get_ih(&path);
292         if (is_indirect_le_ih(ih)) {
293                 __le32 *ind_item = (__le32 *) B_I_PITEM(bh, ih);
294
295                 /* FIXME: here we could cache indirect item or part of it in
296                    the inode to avoid search_by_key in case of subsequent
297                    access to file */
298                 blocknr = get_block_num(ind_item, path.pos_in_item);
299                 ret = 0;
300                 if (blocknr) {
301                         map_bh(bh_result, inode->i_sb, blocknr);
302                         if (path.pos_in_item ==
303                             ((ih_item_len(ih) / UNFM_P_SIZE) - 1)) {
304                                 set_buffer_boundary(bh_result);
305                         }
306                 } else
307                         // We do not return -ENOENT if there is a hole but page is uptodate, because it means
308                         // That there is some MMAPED data associated with it that is yet to  be written to disk.
309                 if ((args & GET_BLOCK_NO_HOLE)
310                             && !PageUptodate(bh_result->b_page)) {
311                         ret = -ENOENT;
312                 }
313
314                 pathrelse(&path);
315                 if (p)
316                         kunmap(bh_result->b_page);
317                 return ret;
318         }
319         // requested data are in direct item(s)
320         if (!(args & GET_BLOCK_READ_DIRECT)) {
321                 // we are called by bmap. FIXME: we can not map block of file
322                 // when it is stored in direct item(s)
323                 pathrelse(&path);
324                 if (p)
325                         kunmap(bh_result->b_page);
326                 return -ENOENT;
327         }
328
329         /* if we've got a direct item, and the buffer or page was uptodate,
330          ** we don't want to pull data off disk again.  skip to the
331          ** end, where we map the buffer and return
332          */
333         if (buffer_uptodate(bh_result)) {
334                 goto finished;
335         } else
336                 /*
337                  ** grab_tail_page can trigger calls to reiserfs_get_block on up to date
338                  ** pages without any buffers.  If the page is up to date, we don't want
339                  ** read old data off disk.  Set the up to date bit on the buffer instead
340                  ** and jump to the end
341                  */
342         if (!bh_result->b_page || PageUptodate(bh_result->b_page)) {
343                 set_buffer_uptodate(bh_result);
344                 goto finished;
345         }
346         // read file tail into part of page
347         offset = (cpu_key_k_offset(&key) - 1) & (PAGE_CACHE_SIZE - 1);
348         fs_gen = get_generation(inode->i_sb);
349         copy_item_head(&tmp_ih, ih);
350
351         /* we only want to kmap if we are reading the tail into the page.
352          ** this is not the common case, so we don't kmap until we are
353          ** sure we need to.  But, this means the item might move if
354          ** kmap schedules
355          */
356         if (!p) {
357                 p = (char *)kmap(bh_result->b_page);
358                 if (fs_changed(fs_gen, inode->i_sb)
359                     && item_moved(&tmp_ih, &path)) {
360                         goto research;
361                 }
362         }
363         p += offset;
364         memset(p, 0, inode->i_sb->s_blocksize);
365         do {
366                 if (!is_direct_le_ih(ih)) {
367                         BUG();
368                 }
369                 /* make sure we don't read more bytes than actually exist in
370                  ** the file.  This can happen in odd cases where i_size isn't
371                  ** correct, and when direct item padding results in a few 
372                  ** extra bytes at the end of the direct item
373                  */
374                 if ((le_ih_k_offset(ih) + path.pos_in_item) > inode->i_size)
375                         break;
376                 if ((le_ih_k_offset(ih) - 1 + ih_item_len(ih)) > inode->i_size) {
377                         chars =
378                             inode->i_size - (le_ih_k_offset(ih) - 1) -
379                             path.pos_in_item;
380                         done = 1;
381                 } else {
382                         chars = ih_item_len(ih) - path.pos_in_item;
383                 }
384                 memcpy(p, B_I_PITEM(bh, ih) + path.pos_in_item, chars);
385
386                 if (done)
387                         break;
388
389                 p += chars;
390
391                 if (PATH_LAST_POSITION(&path) != (B_NR_ITEMS(bh) - 1))
392                         // we done, if read direct item is not the last item of
393                         // node FIXME: we could try to check right delimiting key
394                         // to see whether direct item continues in the right
395                         // neighbor or rely on i_size
396                         break;
397
398                 // update key to look for the next piece
399                 set_cpu_key_k_offset(&key, cpu_key_k_offset(&key) + chars);
400                 result = search_for_position_by_key(inode->i_sb, &key, &path);
401                 if (result != POSITION_FOUND)
402                         // i/o error most likely
403                         break;
404                 bh = get_last_bh(&path);
405                 ih = get_ih(&path);
406         } while (1);
407
408         flush_dcache_page(bh_result->b_page);
409         kunmap(bh_result->b_page);
410
411       finished:
412         pathrelse(&path);
413
414         if (result == IO_ERROR)
415                 return -EIO;
416
417         /* this buffer has valid data, but isn't valid for io.  mapping it to
418          * block #0 tells the rest of reiserfs it just has a tail in it
419          */
420         map_bh(bh_result, inode->i_sb, 0);
421         set_buffer_uptodate(bh_result);
422         return 0;
423 }
424
425 // this is called to create file map. So, _get_block_create_0 will not
426 // read direct item
427 static int reiserfs_bmap(struct inode *inode, sector_t block,
428                          struct buffer_head *bh_result, int create)
429 {
430         if (!file_capable(inode, block))
431                 return -EFBIG;
432
433         reiserfs_write_lock(inode->i_sb);
434         /* do not read the direct item */
435         _get_block_create_0(inode, block, bh_result, 0);
436         reiserfs_write_unlock(inode->i_sb);
437         return 0;
438 }
439
440 /* special version of get_block that is only used by grab_tail_page right
441 ** now.  It is sent to block_prepare_write, and when you try to get a
442 ** block past the end of the file (or a block from a hole) it returns
443 ** -ENOENT instead of a valid buffer.  block_prepare_write expects to
444 ** be able to do i/o on the buffers returned, unless an error value
445 ** is also returned.
446 ** 
447 ** So, this allows block_prepare_write to be used for reading a single block
448 ** in a page.  Where it does not produce a valid page for holes, or past the
449 ** end of the file.  This turns out to be exactly what we need for reading
450 ** tails for conversion.
451 **
452 ** The point of the wrapper is forcing a certain value for create, even
453 ** though the VFS layer is calling this function with create==1.  If you 
454 ** don't want to send create == GET_BLOCK_NO_HOLE to reiserfs_get_block, 
455 ** don't use this function.
456 */
457 static int reiserfs_get_block_create_0(struct inode *inode, sector_t block,
458                                        struct buffer_head *bh_result,
459                                        int create)
460 {
461         return reiserfs_get_block(inode, block, bh_result, GET_BLOCK_NO_HOLE);
462 }
463
464 /* This is special helper for reiserfs_get_block in case we are executing
465    direct_IO request. */
466 static int reiserfs_get_blocks_direct_io(struct inode *inode,
467                                          sector_t iblock,
468                                          struct buffer_head *bh_result,
469                                          int create)
470 {
471         int ret;
472
473         bh_result->b_page = NULL;
474
475         /* We set the b_size before reiserfs_get_block call since it is
476            referenced in convert_tail_for_hole() that may be called from
477            reiserfs_get_block() */
478         bh_result->b_size = (1 << inode->i_blkbits);
479
480         ret = reiserfs_get_block(inode, iblock, bh_result,
481                                  create | GET_BLOCK_NO_DANGLE);
482         if (ret)
483                 goto out;
484
485         /* don't allow direct io onto tail pages */
486         if (buffer_mapped(bh_result) && bh_result->b_blocknr == 0) {
487                 /* make sure future calls to the direct io funcs for this offset
488                  ** in the file fail by unmapping the buffer
489                  */
490                 clear_buffer_mapped(bh_result);
491                 ret = -EINVAL;
492         }
493         /* Possible unpacked tail. Flush the data before pages have
494            disappeared */
495         if (REISERFS_I(inode)->i_flags & i_pack_on_close_mask) {
496                 int err;
497                 lock_kernel();
498                 err = reiserfs_commit_for_inode(inode);
499                 REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask;
500                 unlock_kernel();
501                 if (err < 0)
502                         ret = err;
503         }
504       out:
505         return ret;
506 }
507
508 /*
509 ** helper function for when reiserfs_get_block is called for a hole
510 ** but the file tail is still in a direct item
511 ** bh_result is the buffer head for the hole
512 ** tail_offset is the offset of the start of the tail in the file
513 **
514 ** This calls prepare_write, which will start a new transaction
515 ** you should not be in a transaction, or have any paths held when you
516 ** call this.
517 */
518 static int convert_tail_for_hole(struct inode *inode,
519                                  struct buffer_head *bh_result,
520                                  loff_t tail_offset)
521 {
522         unsigned long index;
523         unsigned long tail_end;
524         unsigned long tail_start;
525         struct page *tail_page;
526         struct page *hole_page = bh_result->b_page;
527         int retval = 0;
528
529         if ((tail_offset & (bh_result->b_size - 1)) != 1)
530                 return -EIO;
531
532         /* always try to read until the end of the block */
533         tail_start = tail_offset & (PAGE_CACHE_SIZE - 1);
534         tail_end = (tail_start | (bh_result->b_size - 1)) + 1;
535
536         index = tail_offset >> PAGE_CACHE_SHIFT;
537         /* hole_page can be zero in case of direct_io, we are sure
538            that we cannot get here if we write with O_DIRECT into
539            tail page */
540         if (!hole_page || index != hole_page->index) {
541                 tail_page = grab_cache_page(inode->i_mapping, index);
542                 retval = -ENOMEM;
543                 if (!tail_page) {
544                         goto out;
545                 }
546         } else {
547                 tail_page = hole_page;
548         }
549
550         /* we don't have to make sure the conversion did not happen while
551          ** we were locking the page because anyone that could convert
552          ** must first take i_mutex.
553          **
554          ** We must fix the tail page for writing because it might have buffers
555          ** that are mapped, but have a block number of 0.  This indicates tail
556          ** data that has been read directly into the page, and block_prepare_write
557          ** won't trigger a get_block in this case.
558          */
559         fix_tail_page_for_writing(tail_page);
560         retval = reiserfs_prepare_write(NULL, tail_page, tail_start, tail_end);
561         if (retval)
562                 goto unlock;
563
564         /* tail conversion might change the data in the page */
565         flush_dcache_page(tail_page);
566
567         retval = reiserfs_commit_write(NULL, tail_page, tail_start, tail_end);
568
569       unlock:
570         if (tail_page != hole_page) {
571                 unlock_page(tail_page);
572                 page_cache_release(tail_page);
573         }
574       out:
575         return retval;
576 }
577
578 static inline int _allocate_block(struct reiserfs_transaction_handle *th,
579                                   long block,
580                                   struct inode *inode,
581                                   b_blocknr_t * allocated_block_nr,
582                                   struct path *path, int flags)
583 {
584         BUG_ON(!th->t_trans_id);
585
586 #ifdef REISERFS_PREALLOCATE
587         if (!(flags & GET_BLOCK_NO_IMUX)) {
588                 return reiserfs_new_unf_blocknrs2(th, inode, allocated_block_nr,
589                                                   path, block);
590         }
591 #endif
592         return reiserfs_new_unf_blocknrs(th, inode, allocated_block_nr, path,
593                                          block);
594 }
595
596 int reiserfs_get_block(struct inode *inode, sector_t block,
597                        struct buffer_head *bh_result, int create)
598 {
599         int repeat, retval = 0;
600         b_blocknr_t allocated_block_nr = 0;     // b_blocknr_t is (unsigned) 32 bit int
601         INITIALIZE_PATH(path);
602         int pos_in_item;
603         struct cpu_key key;
604         struct buffer_head *bh, *unbh = NULL;
605         struct item_head *ih, tmp_ih;
606         __le32 *item;
607         int done;
608         int fs_gen;
609         struct reiserfs_transaction_handle *th = NULL;
610         /* space reserved in transaction batch: 
611            . 3 balancings in direct->indirect conversion
612            . 1 block involved into reiserfs_update_sd()
613            XXX in practically impossible worst case direct2indirect()
614            can incur (much) more than 3 balancings.
615            quota update for user, group */
616         int jbegin_count =
617             JOURNAL_PER_BALANCE_CNT * 3 + 1 +
618             2 * REISERFS_QUOTA_TRANS_BLOCKS(inode->i_sb);
619         int version;
620         int dangle = 1;
621         loff_t new_offset =
622             (((loff_t) block) << inode->i_sb->s_blocksize_bits) + 1;
623
624         /* bad.... */
625         reiserfs_write_lock(inode->i_sb);
626         version = get_inode_item_key_version(inode);
627
628         if (!file_capable(inode, block)) {
629                 reiserfs_write_unlock(inode->i_sb);
630                 return -EFBIG;
631         }
632
633         /* if !create, we aren't changing the FS, so we don't need to
634          ** log anything, so we don't need to start a transaction
635          */
636         if (!(create & GET_BLOCK_CREATE)) {
637                 int ret;
638                 /* find number of block-th logical block of the file */
639                 ret = _get_block_create_0(inode, block, bh_result,
640                                           create | GET_BLOCK_READ_DIRECT);
641                 reiserfs_write_unlock(inode->i_sb);
642                 return ret;
643         }
644         /*
645          * if we're already in a transaction, make sure to close
646          * any new transactions we start in this func
647          */
648         if ((create & GET_BLOCK_NO_DANGLE) ||
649             reiserfs_transaction_running(inode->i_sb))
650                 dangle = 0;
651
652         /* If file is of such a size, that it might have a tail and tails are enabled
653          ** we should mark it as possibly needing tail packing on close
654          */
655         if ((have_large_tails(inode->i_sb)
656              && inode->i_size < i_block_size(inode) * 4)
657             || (have_small_tails(inode->i_sb)
658                 && inode->i_size < i_block_size(inode)))
659                 REISERFS_I(inode)->i_flags |= i_pack_on_close_mask;
660
661         /* set the key of the first byte in the 'block'-th block of file */
662         make_cpu_key(&key, inode, new_offset, TYPE_ANY, 3 /*key length */ );
663         if ((new_offset + inode->i_sb->s_blocksize - 1) > inode->i_size) {
664               start_trans:
665                 th = reiserfs_persistent_transaction(inode->i_sb, jbegin_count);
666                 if (!th) {
667                         retval = -ENOMEM;
668                         goto failure;
669                 }
670                 reiserfs_update_inode_transaction(inode);
671         }
672       research:
673
674         retval = search_for_position_by_key(inode->i_sb, &key, &path);
675         if (retval == IO_ERROR) {
676                 retval = -EIO;
677                 goto failure;
678         }
679
680         bh = get_last_bh(&path);
681         ih = get_ih(&path);
682         item = get_item(&path);
683         pos_in_item = path.pos_in_item;
684
685         fs_gen = get_generation(inode->i_sb);
686         copy_item_head(&tmp_ih, ih);
687
688         if (allocation_needed
689             (retval, allocated_block_nr, ih, item, pos_in_item)) {
690                 /* we have to allocate block for the unformatted node */
691                 if (!th) {
692                         pathrelse(&path);
693                         goto start_trans;
694                 }
695
696                 repeat =
697                     _allocate_block(th, block, inode, &allocated_block_nr,
698                                     &path, create);
699
700                 if (repeat == NO_DISK_SPACE || repeat == QUOTA_EXCEEDED) {
701                         /* restart the transaction to give the journal a chance to free
702                          ** some blocks.  releases the path, so we have to go back to
703                          ** research if we succeed on the second try
704                          */
705                         SB_JOURNAL(inode->i_sb)->j_next_async_flush = 1;
706                         retval = restart_transaction(th, inode, &path);
707                         if (retval)
708                                 goto failure;
709                         repeat =
710                             _allocate_block(th, block, inode,
711                                             &allocated_block_nr, NULL, create);
712
713                         if (repeat != NO_DISK_SPACE && repeat != QUOTA_EXCEEDED) {
714                                 goto research;
715                         }
716                         if (repeat == QUOTA_EXCEEDED)
717                                 retval = -EDQUOT;
718                         else
719                                 retval = -ENOSPC;
720                         goto failure;
721                 }
722
723                 if (fs_changed(fs_gen, inode->i_sb)
724                     && item_moved(&tmp_ih, &path)) {
725                         goto research;
726                 }
727         }
728
729         if (indirect_item_found(retval, ih)) {
730                 b_blocknr_t unfm_ptr;
731                 /* 'block'-th block is in the file already (there is
732                    corresponding cell in some indirect item). But it may be
733                    zero unformatted node pointer (hole) */
734                 unfm_ptr = get_block_num(item, pos_in_item);
735                 if (unfm_ptr == 0) {
736                         /* use allocated block to plug the hole */
737                         reiserfs_prepare_for_journal(inode->i_sb, bh, 1);
738                         if (fs_changed(fs_gen, inode->i_sb)
739                             && item_moved(&tmp_ih, &path)) {
740                                 reiserfs_restore_prepared_buffer(inode->i_sb,
741                                                                  bh);
742                                 goto research;
743                         }
744                         set_buffer_new(bh_result);
745                         if (buffer_dirty(bh_result)
746                             && reiserfs_data_ordered(inode->i_sb))
747                                 reiserfs_add_ordered_list(inode, bh_result);
748                         put_block_num(item, pos_in_item, allocated_block_nr);
749                         unfm_ptr = allocated_block_nr;
750                         journal_mark_dirty(th, inode->i_sb, bh);
751                         reiserfs_update_sd(th, inode);
752                 }
753                 set_block_dev_mapped(bh_result, unfm_ptr, inode);
754                 pathrelse(&path);
755                 retval = 0;
756                 if (!dangle && th)
757                         retval = reiserfs_end_persistent_transaction(th);
758
759                 reiserfs_write_unlock(inode->i_sb);
760
761                 /* the item was found, so new blocks were not added to the file
762                  ** there is no need to make sure the inode is updated with this 
763                  ** transaction
764                  */
765                 return retval;
766         }
767
768         if (!th) {
769                 pathrelse(&path);
770                 goto start_trans;
771         }
772
773         /* desired position is not found or is in the direct item. We have
774            to append file with holes up to 'block'-th block converting
775            direct items to indirect one if necessary */
776         done = 0;
777         do {
778                 if (is_statdata_le_ih(ih)) {
779                         __le32 unp = 0;
780                         struct cpu_key tmp_key;
781
782                         /* indirect item has to be inserted */
783                         make_le_item_head(&tmp_ih, &key, version, 1,
784                                           TYPE_INDIRECT, UNFM_P_SIZE,
785                                           0 /* free_space */ );
786
787                         if (cpu_key_k_offset(&key) == 1) {
788                                 /* we are going to add 'block'-th block to the file. Use
789                                    allocated block for that */
790                                 unp = cpu_to_le32(allocated_block_nr);
791                                 set_block_dev_mapped(bh_result,
792                                                      allocated_block_nr, inode);
793                                 set_buffer_new(bh_result);
794                                 done = 1;
795                         }
796                         tmp_key = key;  // ;)
797                         set_cpu_key_k_offset(&tmp_key, 1);
798                         PATH_LAST_POSITION(&path)++;
799
800                         retval =
801                             reiserfs_insert_item(th, &path, &tmp_key, &tmp_ih,
802                                                  inode, (char *)&unp);
803                         if (retval) {
804                                 reiserfs_free_block(th, inode,
805                                                     allocated_block_nr, 1);
806                                 goto failure;   // retval == -ENOSPC, -EDQUOT or -EIO or -EEXIST
807                         }
808                         //mark_tail_converted (inode);
809                 } else if (is_direct_le_ih(ih)) {
810                         /* direct item has to be converted */
811                         loff_t tail_offset;
812
813                         tail_offset =
814                             ((le_ih_k_offset(ih) -
815                               1) & ~(inode->i_sb->s_blocksize - 1)) + 1;
816                         if (tail_offset == cpu_key_k_offset(&key)) {
817                                 /* direct item we just found fits into block we have
818                                    to map. Convert it into unformatted node: use
819                                    bh_result for the conversion */
820                                 set_block_dev_mapped(bh_result,
821                                                      allocated_block_nr, inode);
822                                 unbh = bh_result;
823                                 done = 1;
824                         } else {
825                                 /* we have to padd file tail stored in direct item(s)
826                                    up to block size and convert it to unformatted
827                                    node. FIXME: this should also get into page cache */
828
829                                 pathrelse(&path);
830                                 /*
831                                  * ugly, but we can only end the transaction if
832                                  * we aren't nested
833                                  */
834                                 BUG_ON(!th->t_refcount);
835                                 if (th->t_refcount == 1) {
836                                         retval =
837                                             reiserfs_end_persistent_transaction
838                                             (th);
839                                         th = NULL;
840                                         if (retval)
841                                                 goto failure;
842                                 }
843
844                                 retval =
845                                     convert_tail_for_hole(inode, bh_result,
846                                                           tail_offset);
847                                 if (retval) {
848                                         if (retval != -ENOSPC)
849                                                 reiserfs_warning(inode->i_sb,
850                                                                  "clm-6004: convert tail failed inode %lu, error %d",
851                                                                  inode->i_ino,
852                                                                  retval);
853                                         if (allocated_block_nr) {
854                                                 /* the bitmap, the super, and the stat data == 3 */
855                                                 if (!th)
856                                                         th = reiserfs_persistent_transaction(inode->i_sb, 3);
857                                                 if (th)
858                                                         reiserfs_free_block(th,
859                                                                             inode,
860                                                                             allocated_block_nr,
861                                                                             1);
862                                         }
863                                         goto failure;
864                                 }
865                                 goto research;
866                         }
867                         retval =
868                             direct2indirect(th, inode, &path, unbh,
869                                             tail_offset);
870                         if (retval) {
871                                 reiserfs_unmap_buffer(unbh);
872                                 reiserfs_free_block(th, inode,
873                                                     allocated_block_nr, 1);
874                                 goto failure;
875                         }
876                         /* it is important the set_buffer_uptodate is done after
877                          ** the direct2indirect.  The buffer might contain valid
878                          ** data newer than the data on disk (read by readpage, changed,
879                          ** and then sent here by writepage).  direct2indirect needs
880                          ** to know if unbh was already up to date, so it can decide
881                          ** if the data in unbh needs to be replaced with data from
882                          ** the disk
883                          */
884                         set_buffer_uptodate(unbh);
885
886                         /* unbh->b_page == NULL in case of DIRECT_IO request, this means
887                            buffer will disappear shortly, so it should not be added to
888                          */
889                         if (unbh->b_page) {
890                                 /* we've converted the tail, so we must
891                                  ** flush unbh before the transaction commits
892                                  */
893                                 reiserfs_add_tail_list(inode, unbh);
894
895                                 /* mark it dirty now to prevent commit_write from adding
896                                  ** this buffer to the inode's dirty buffer list
897                                  */
898                                 /*
899                                  * AKPM: changed __mark_buffer_dirty to mark_buffer_dirty().
900                                  * It's still atomic, but it sets the page dirty too,
901                                  * which makes it eligible for writeback at any time by the
902                                  * VM (which was also the case with __mark_buffer_dirty())
903                                  */
904                                 mark_buffer_dirty(unbh);
905                         }
906                 } else {
907                         /* append indirect item with holes if needed, when appending
908                            pointer to 'block'-th block use block, which is already
909                            allocated */
910                         struct cpu_key tmp_key;
911                         unp_t unf_single = 0;   // We use this in case we need to allocate only
912                         // one block which is a fastpath
913                         unp_t *un;
914                         __u64 max_to_insert =
915                             MAX_ITEM_LEN(inode->i_sb->s_blocksize) /
916                             UNFM_P_SIZE;
917                         __u64 blocks_needed;
918
919                         RFALSE(pos_in_item != ih_item_len(ih) / UNFM_P_SIZE,
920                                "vs-804: invalid position for append");
921                         /* indirect item has to be appended, set up key of that position */
922                         make_cpu_key(&tmp_key, inode,
923                                      le_key_k_offset(version,
924                                                      &(ih->ih_key)) +
925                                      op_bytes_number(ih,
926                                                      inode->i_sb->s_blocksize),
927                                      //pos_in_item * inode->i_sb->s_blocksize,
928                                      TYPE_INDIRECT, 3); // key type is unimportant
929
930                         RFALSE(cpu_key_k_offset(&tmp_key) > cpu_key_k_offset(&key),
931                                "green-805: invalid offset");
932                         blocks_needed =
933                             1 +
934                             ((cpu_key_k_offset(&key) -
935                               cpu_key_k_offset(&tmp_key)) >> inode->i_sb->
936                              s_blocksize_bits);
937
938                         if (blocks_needed == 1) {
939                                 un = &unf_single;
940                         } else {
941                                 un = kmalloc(min(blocks_needed, max_to_insert) * UNFM_P_SIZE, GFP_ATOMIC);      // We need to avoid scheduling.
942                                 if (!un) {
943                                         un = &unf_single;
944                                         blocks_needed = 1;
945                                         max_to_insert = 0;
946                                 } else
947                                         memset(un, 0,
948                                                UNFM_P_SIZE * min(blocks_needed,
949                                                                  max_to_insert));
950                         }
951                         if (blocks_needed <= max_to_insert) {
952                                 /* we are going to add target block to the file. Use allocated
953                                    block for that */
954                                 un[blocks_needed - 1] =
955                                     cpu_to_le32(allocated_block_nr);
956                                 set_block_dev_mapped(bh_result,
957                                                      allocated_block_nr, inode);
958                                 set_buffer_new(bh_result);
959                                 done = 1;
960                         } else {
961                                 /* paste hole to the indirect item */
962                                 /* If kmalloc failed, max_to_insert becomes zero and it means we
963                                    only have space for one block */
964                                 blocks_needed =
965                                     max_to_insert ? max_to_insert : 1;
966                         }
967                         retval =
968                             reiserfs_paste_into_item(th, &path, &tmp_key, inode,
969                                                      (char *)un,
970                                                      UNFM_P_SIZE *
971                                                      blocks_needed);
972
973                         if (blocks_needed != 1)
974                                 kfree(un);
975
976                         if (retval) {
977                                 reiserfs_free_block(th, inode,
978                                                     allocated_block_nr, 1);
979                                 goto failure;
980                         }
981                         if (!done) {
982                                 /* We need to mark new file size in case this function will be
983                                    interrupted/aborted later on. And we may do this only for
984                                    holes. */
985                                 inode->i_size +=
986                                     inode->i_sb->s_blocksize * blocks_needed;
987                         }
988                 }
989
990                 if (done == 1)
991                         break;
992
993                 /* this loop could log more blocks than we had originally asked
994                  ** for.  So, we have to allow the transaction to end if it is
995                  ** too big or too full.  Update the inode so things are 
996                  ** consistent if we crash before the function returns
997                  **
998                  ** release the path so that anybody waiting on the path before
999                  ** ending their transaction will be able to continue.
1000                  */
1001                 if (journal_transaction_should_end(th, th->t_blocks_allocated)) {
1002                         retval = restart_transaction(th, inode, &path);
1003                         if (retval)
1004                                 goto failure;
1005                 }
1006                 /* inserting indirect pointers for a hole can take a 
1007                  ** long time.  reschedule if needed
1008                  */
1009                 cond_resched();
1010
1011                 retval = search_for_position_by_key(inode->i_sb, &key, &path);
1012                 if (retval == IO_ERROR) {
1013                         retval = -EIO;
1014                         goto failure;
1015                 }
1016                 if (retval == POSITION_FOUND) {
1017                         reiserfs_warning(inode->i_sb,
1018                                          "vs-825: reiserfs_get_block: "
1019                                          "%K should not be found", &key);
1020                         retval = -EEXIST;
1021                         if (allocated_block_nr)
1022                                 reiserfs_free_block(th, inode,
1023                                                     allocated_block_nr, 1);
1024                         pathrelse(&path);
1025                         goto failure;
1026                 }
1027                 bh = get_last_bh(&path);
1028                 ih = get_ih(&path);
1029                 item = get_item(&path);
1030                 pos_in_item = path.pos_in_item;
1031         } while (1);
1032
1033         retval = 0;
1034
1035       failure:
1036         if (th && (!dangle || (retval && !th->t_trans_id))) {
1037                 int err;
1038                 if (th->t_trans_id)
1039                         reiserfs_update_sd(th, inode);
1040                 err = reiserfs_end_persistent_transaction(th);
1041                 if (err)
1042                         retval = err;
1043         }
1044
1045         reiserfs_write_unlock(inode->i_sb);
1046         reiserfs_check_path(&path);
1047         return retval;
1048 }
1049
1050 static int
1051 reiserfs_readpages(struct file *file, struct address_space *mapping,
1052                    struct list_head *pages, unsigned nr_pages)
1053 {
1054         return mpage_readpages(mapping, pages, nr_pages, reiserfs_get_block);
1055 }
1056
1057 /* Compute real number of used bytes by file
1058  * Following three functions can go away when we'll have enough space in stat item
1059  */
1060 static int real_space_diff(struct inode *inode, int sd_size)
1061 {
1062         int bytes;
1063         loff_t blocksize = inode->i_sb->s_blocksize;
1064
1065         if (S_ISLNK(inode->i_mode) || S_ISDIR(inode->i_mode))
1066                 return sd_size;
1067
1068         /* End of file is also in full block with indirect reference, so round
1069          ** up to the next block.
1070          **
1071          ** there is just no way to know if the tail is actually packed
1072          ** on the file, so we have to assume it isn't.  When we pack the
1073          ** tail, we add 4 bytes to pretend there really is an unformatted
1074          ** node pointer
1075          */
1076         bytes =
1077             ((inode->i_size +
1078               (blocksize - 1)) >> inode->i_sb->s_blocksize_bits) * UNFM_P_SIZE +
1079             sd_size;
1080         return bytes;
1081 }
1082
1083 static inline loff_t to_real_used_space(struct inode *inode, ulong blocks,
1084                                         int sd_size)
1085 {
1086         if (S_ISLNK(inode->i_mode) || S_ISDIR(inode->i_mode)) {
1087                 return inode->i_size +
1088                     (loff_t) (real_space_diff(inode, sd_size));
1089         }
1090         return ((loff_t) real_space_diff(inode, sd_size)) +
1091             (((loff_t) blocks) << 9);
1092 }
1093
1094 /* Compute number of blocks used by file in ReiserFS counting */
1095 static inline ulong to_fake_used_blocks(struct inode *inode, int sd_size)
1096 {
1097         loff_t bytes = inode_get_bytes(inode);
1098         loff_t real_space = real_space_diff(inode, sd_size);
1099
1100         /* keeps fsck and non-quota versions of reiserfs happy */
1101         if (S_ISLNK(inode->i_mode) || S_ISDIR(inode->i_mode)) {
1102                 bytes += (loff_t) 511;
1103         }
1104
1105         /* files from before the quota patch might i_blocks such that
1106          ** bytes < real_space.  Deal with that here to prevent it from
1107          ** going negative.
1108          */
1109         if (bytes < real_space)
1110                 return 0;
1111         return (bytes - real_space) >> 9;
1112 }
1113
1114 //
1115 // BAD: new directories have stat data of new type and all other items
1116 // of old type. Version stored in the inode says about body items, so
1117 // in update_stat_data we can not rely on inode, but have to check
1118 // item version directly
1119 //
1120
1121 // called by read_locked_inode
1122 static void init_inode(struct inode *inode, struct path *path)
1123 {
1124         struct buffer_head *bh;
1125         struct item_head *ih;
1126         __u32 rdev;
1127         //int version = ITEM_VERSION_1;
1128
1129         bh = PATH_PLAST_BUFFER(path);
1130         ih = PATH_PITEM_HEAD(path);
1131
1132         copy_key(INODE_PKEY(inode), &(ih->ih_key));
1133         inode->i_blksize = reiserfs_default_io_size;
1134
1135         INIT_LIST_HEAD(&(REISERFS_I(inode)->i_prealloc_list));
1136         REISERFS_I(inode)->i_flags = 0;
1137         REISERFS_I(inode)->i_prealloc_block = 0;
1138         REISERFS_I(inode)->i_prealloc_count = 0;
1139         REISERFS_I(inode)->i_trans_id = 0;
1140         REISERFS_I(inode)->i_jl = NULL;
1141         REISERFS_I(inode)->i_acl_access = NULL;
1142         REISERFS_I(inode)->i_acl_default = NULL;
1143         init_rwsem(&REISERFS_I(inode)->xattr_sem);
1144
1145         if (stat_data_v1(ih)) {
1146                 struct stat_data_v1 *sd =
1147                     (struct stat_data_v1 *)B_I_PITEM(bh, ih);
1148                 unsigned long blocks;
1149
1150                 set_inode_item_key_version(inode, KEY_FORMAT_3_5);
1151                 set_inode_sd_version(inode, STAT_DATA_V1);
1152                 inode->i_mode = sd_v1_mode(sd);
1153                 inode->i_nlink = sd_v1_nlink(sd);
1154                 inode->i_uid = sd_v1_uid(sd);
1155                 inode->i_gid = sd_v1_gid(sd);
1156                 inode->i_size = sd_v1_size(sd);
1157                 inode->i_atime.tv_sec = sd_v1_atime(sd);
1158                 inode->i_mtime.tv_sec = sd_v1_mtime(sd);
1159                 inode->i_ctime.tv_sec = sd_v1_ctime(sd);
1160                 inode->i_atime.tv_nsec = 0;
1161                 inode->i_ctime.tv_nsec = 0;
1162                 inode->i_mtime.tv_nsec = 0;
1163
1164                 inode->i_blocks = sd_v1_blocks(sd);
1165                 inode->i_generation = le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
1166                 blocks = (inode->i_size + 511) >> 9;
1167                 blocks = _ROUND_UP(blocks, inode->i_sb->s_blocksize >> 9);
1168                 if (inode->i_blocks > blocks) {
1169                         // there was a bug in <=3.5.23 when i_blocks could take negative
1170                         // values. Starting from 3.5.17 this value could even be stored in
1171                         // stat data. For such files we set i_blocks based on file
1172                         // size. Just 2 notes: this can be wrong for sparce files. On-disk value will be
1173                         // only updated if file's inode will ever change
1174                         inode->i_blocks = blocks;
1175                 }
1176
1177                 rdev = sd_v1_rdev(sd);
1178                 REISERFS_I(inode)->i_first_direct_byte =
1179                     sd_v1_first_direct_byte(sd);
1180                 /* an early bug in the quota code can give us an odd number for the
1181                  ** block count.  This is incorrect, fix it here.
1182                  */
1183                 if (inode->i_blocks & 1) {
1184                         inode->i_blocks++;
1185                 }
1186                 inode_set_bytes(inode,
1187                                 to_real_used_space(inode, inode->i_blocks,
1188                                                    SD_V1_SIZE));
1189                 /* nopack is initially zero for v1 objects. For v2 objects,
1190                    nopack is initialised from sd_attrs */
1191                 REISERFS_I(inode)->i_flags &= ~i_nopack_mask;
1192         } else {
1193                 // new stat data found, but object may have old items
1194                 // (directories and symlinks)
1195                 struct stat_data *sd = (struct stat_data *)B_I_PITEM(bh, ih);
1196
1197                 inode->i_mode = sd_v2_mode(sd);
1198                 inode->i_nlink = sd_v2_nlink(sd);
1199                 inode->i_uid = sd_v2_uid(sd);
1200                 inode->i_size = sd_v2_size(sd);
1201                 inode->i_gid = sd_v2_gid(sd);
1202                 inode->i_mtime.tv_sec = sd_v2_mtime(sd);
1203                 inode->i_atime.tv_sec = sd_v2_atime(sd);
1204                 inode->i_ctime.tv_sec = sd_v2_ctime(sd);
1205                 inode->i_ctime.tv_nsec = 0;
1206                 inode->i_mtime.tv_nsec = 0;
1207                 inode->i_atime.tv_nsec = 0;
1208                 inode->i_blocks = sd_v2_blocks(sd);
1209                 rdev = sd_v2_rdev(sd);
1210                 if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
1211                         inode->i_generation =
1212                             le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
1213                 else
1214                         inode->i_generation = sd_v2_generation(sd);
1215
1216                 if (S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode))
1217                         set_inode_item_key_version(inode, KEY_FORMAT_3_5);
1218                 else
1219                         set_inode_item_key_version(inode, KEY_FORMAT_3_6);
1220                 REISERFS_I(inode)->i_first_direct_byte = 0;
1221                 set_inode_sd_version(inode, STAT_DATA_V2);
1222                 inode_set_bytes(inode,
1223                                 to_real_used_space(inode, inode->i_blocks,
1224                                                    SD_V2_SIZE));
1225                 /* read persistent inode attributes from sd and initalise
1226                    generic inode flags from them */
1227                 REISERFS_I(inode)->i_attrs = sd_v2_attrs(sd);
1228                 sd_attrs_to_i_attrs(sd_v2_attrs(sd), inode);
1229         }
1230
1231         pathrelse(path);
1232         if (S_ISREG(inode->i_mode)) {
1233                 inode->i_op = &reiserfs_file_inode_operations;
1234                 inode->i_fop = &reiserfs_file_operations;
1235                 inode->i_mapping->a_ops = &reiserfs_address_space_operations;
1236         } else if (S_ISDIR(inode->i_mode)) {
1237                 inode->i_op = &reiserfs_dir_inode_operations;
1238                 inode->i_fop = &reiserfs_dir_operations;
1239         } else if (S_ISLNK(inode->i_mode)) {
1240                 inode->i_op = &reiserfs_symlink_inode_operations;
1241                 inode->i_mapping->a_ops = &reiserfs_address_space_operations;
1242         } else {
1243                 inode->i_blocks = 0;
1244                 inode->i_op = &reiserfs_special_inode_operations;
1245                 init_special_inode(inode, inode->i_mode, new_decode_dev(rdev));
1246         }
1247 }
1248
1249 // update new stat data with inode fields
1250 static void inode2sd(void *sd, struct inode *inode, loff_t size)
1251 {
1252         struct stat_data *sd_v2 = (struct stat_data *)sd;
1253         __u16 flags;
1254
1255         set_sd_v2_mode(sd_v2, inode->i_mode);
1256         set_sd_v2_nlink(sd_v2, inode->i_nlink);
1257         set_sd_v2_uid(sd_v2, inode->i_uid);
1258         set_sd_v2_size(sd_v2, size);
1259         set_sd_v2_gid(sd_v2, inode->i_gid);
1260         set_sd_v2_mtime(sd_v2, inode->i_mtime.tv_sec);
1261         set_sd_v2_atime(sd_v2, inode->i_atime.tv_sec);
1262         set_sd_v2_ctime(sd_v2, inode->i_ctime.tv_sec);
1263         set_sd_v2_blocks(sd_v2, to_fake_used_blocks(inode, SD_V2_SIZE));
1264         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
1265                 set_sd_v2_rdev(sd_v2, new_encode_dev(inode->i_rdev));
1266         else
1267                 set_sd_v2_generation(sd_v2, inode->i_generation);
1268         flags = REISERFS_I(inode)->i_attrs;
1269         i_attrs_to_sd_attrs(inode, &flags);
1270         set_sd_v2_attrs(sd_v2, flags);
1271 }
1272
1273 // used to copy inode's fields to old stat data
1274 static void inode2sd_v1(void *sd, struct inode *inode, loff_t size)
1275 {
1276         struct stat_data_v1 *sd_v1 = (struct stat_data_v1 *)sd;
1277
1278         set_sd_v1_mode(sd_v1, inode->i_mode);
1279         set_sd_v1_uid(sd_v1, inode->i_uid);
1280         set_sd_v1_gid(sd_v1, inode->i_gid);
1281         set_sd_v1_nlink(sd_v1, inode->i_nlink);
1282         set_sd_v1_size(sd_v1, size);
1283         set_sd_v1_atime(sd_v1, inode->i_atime.tv_sec);
1284         set_sd_v1_ctime(sd_v1, inode->i_ctime.tv_sec);
1285         set_sd_v1_mtime(sd_v1, inode->i_mtime.tv_sec);
1286
1287         if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
1288                 set_sd_v1_rdev(sd_v1, new_encode_dev(inode->i_rdev));
1289         else
1290                 set_sd_v1_blocks(sd_v1, to_fake_used_blocks(inode, SD_V1_SIZE));
1291
1292         // Sigh. i_first_direct_byte is back
1293         set_sd_v1_first_direct_byte(sd_v1,
1294                                     REISERFS_I(inode)->i_first_direct_byte);
1295 }
1296
1297 /* NOTE, you must prepare the buffer head before sending it here,
1298 ** and then log it after the call
1299 */
1300 static void update_stat_data(struct path *path, struct inode *inode,
1301                              loff_t size)
1302 {
1303         struct buffer_head *bh;
1304         struct item_head *ih;
1305
1306         bh = PATH_PLAST_BUFFER(path);
1307         ih = PATH_PITEM_HEAD(path);
1308
1309         if (!is_statdata_le_ih(ih))
1310                 reiserfs_panic(inode->i_sb,
1311                                "vs-13065: update_stat_data: key %k, found item %h",
1312                                INODE_PKEY(inode), ih);
1313
1314         if (stat_data_v1(ih)) {
1315                 // path points to old stat data
1316                 inode2sd_v1(B_I_PITEM(bh, ih), inode, size);
1317         } else {
1318                 inode2sd(B_I_PITEM(bh, ih), inode, size);
1319         }
1320
1321         return;
1322 }
1323
1324 void reiserfs_update_sd_size(struct reiserfs_transaction_handle *th,
1325                              struct inode *inode, loff_t size)
1326 {
1327         struct cpu_key key;
1328         INITIALIZE_PATH(path);
1329         struct buffer_head *bh;
1330         int fs_gen;
1331         struct item_head *ih, tmp_ih;
1332         int retval;
1333
1334         BUG_ON(!th->t_trans_id);
1335
1336         make_cpu_key(&key, inode, SD_OFFSET, TYPE_STAT_DATA, 3);        //key type is unimportant
1337
1338         for (;;) {
1339                 int pos;
1340                 /* look for the object's stat data */
1341                 retval = search_item(inode->i_sb, &key, &path);
1342                 if (retval == IO_ERROR) {
1343                         reiserfs_warning(inode->i_sb,
1344                                          "vs-13050: reiserfs_update_sd: "
1345                                          "i/o failure occurred trying to update %K stat data",
1346                                          &key);
1347                         return;
1348                 }
1349                 if (retval == ITEM_NOT_FOUND) {
1350                         pos = PATH_LAST_POSITION(&path);
1351                         pathrelse(&path);
1352                         if (inode->i_nlink == 0) {
1353                                 /*reiserfs_warning (inode->i_sb, "vs-13050: reiserfs_update_sd: i_nlink == 0, stat data not found"); */
1354                                 return;
1355                         }
1356                         reiserfs_warning(inode->i_sb,
1357                                          "vs-13060: reiserfs_update_sd: "
1358                                          "stat data of object %k (nlink == %d) not found (pos %d)",
1359                                          INODE_PKEY(inode), inode->i_nlink,
1360                                          pos);
1361                         reiserfs_check_path(&path);
1362                         return;
1363                 }
1364
1365                 /* sigh, prepare_for_journal might schedule.  When it schedules the
1366                  ** FS might change.  We have to detect that, and loop back to the
1367                  ** search if the stat data item has moved
1368                  */
1369                 bh = get_last_bh(&path);
1370                 ih = get_ih(&path);
1371                 copy_item_head(&tmp_ih, ih);
1372                 fs_gen = get_generation(inode->i_sb);
1373                 reiserfs_prepare_for_journal(inode->i_sb, bh, 1);
1374                 if (fs_changed(fs_gen, inode->i_sb)
1375                     && item_moved(&tmp_ih, &path)) {
1376                         reiserfs_restore_prepared_buffer(inode->i_sb, bh);
1377                         continue;       /* Stat_data item has been moved after scheduling. */
1378                 }
1379                 break;
1380         }
1381         update_stat_data(&path, inode, size);
1382         journal_mark_dirty(th, th->t_super, bh);
1383         pathrelse(&path);
1384         return;
1385 }
1386
1387 /* reiserfs_read_locked_inode is called to read the inode off disk, and it
1388 ** does a make_bad_inode when things go wrong.  But, we need to make sure
1389 ** and clear the key in the private portion of the inode, otherwise a
1390 ** corresponding iput might try to delete whatever object the inode last
1391 ** represented.
1392 */
1393 static void reiserfs_make_bad_inode(struct inode *inode)
1394 {
1395         memset(INODE_PKEY(inode), 0, KEY_SIZE);
1396         make_bad_inode(inode);
1397 }
1398
1399 //
1400 // initially this function was derived from minix or ext2's analog and
1401 // evolved as the prototype did
1402 //
1403
1404 int reiserfs_init_locked_inode(struct inode *inode, void *p)
1405 {
1406         struct reiserfs_iget_args *args = (struct reiserfs_iget_args *)p;
1407         inode->i_ino = args->objectid;
1408         INODE_PKEY(inode)->k_dir_id = cpu_to_le32(args->dirid);
1409         return 0;
1410 }
1411
1412 /* looks for stat data in the tree, and fills up the fields of in-core
1413    inode stat data fields */
1414 void reiserfs_read_locked_inode(struct inode *inode,
1415                                 struct reiserfs_iget_args *args)
1416 {
1417         INITIALIZE_PATH(path_to_sd);
1418         struct cpu_key key;
1419         unsigned long dirino;
1420         int retval;
1421
1422         dirino = args->dirid;
1423
1424         /* set version 1, version 2 could be used too, because stat data
1425            key is the same in both versions */
1426         key.version = KEY_FORMAT_3_5;
1427         key.on_disk_key.k_dir_id = dirino;
1428         key.on_disk_key.k_objectid = inode->i_ino;
1429         key.on_disk_key.k_offset = 0;
1430         key.on_disk_key.k_type = 0;
1431
1432         /* look for the object's stat data */
1433         retval = search_item(inode->i_sb, &key, &path_to_sd);
1434         if (retval == IO_ERROR) {
1435                 reiserfs_warning(inode->i_sb,
1436                                  "vs-13070: reiserfs_read_locked_inode: "
1437                                  "i/o failure occurred trying to find stat data of %K",
1438                                  &key);
1439                 reiserfs_make_bad_inode(inode);
1440                 return;
1441         }
1442         if (retval != ITEM_FOUND) {
1443                 /* a stale NFS handle can trigger this without it being an error */
1444                 pathrelse(&path_to_sd);
1445                 reiserfs_make_bad_inode(inode);
1446                 inode->i_nlink = 0;
1447                 return;
1448         }
1449
1450         init_inode(inode, &path_to_sd);
1451
1452         /* It is possible that knfsd is trying to access inode of a file
1453            that is being removed from the disk by some other thread. As we
1454            update sd on unlink all that is required is to check for nlink
1455            here. This bug was first found by Sizif when debugging
1456            SquidNG/Butterfly, forgotten, and found again after Philippe
1457            Gramoulle <philippe.gramoulle@mmania.com> reproduced it. 
1458
1459            More logical fix would require changes in fs/inode.c:iput() to
1460            remove inode from hash-table _after_ fs cleaned disk stuff up and
1461            in iget() to return NULL if I_FREEING inode is found in
1462            hash-table. */
1463         /* Currently there is one place where it's ok to meet inode with
1464            nlink==0: processing of open-unlinked and half-truncated files
1465            during mount (fs/reiserfs/super.c:finish_unfinished()). */
1466         if ((inode->i_nlink == 0) &&
1467             !REISERFS_SB(inode->i_sb)->s_is_unlinked_ok) {
1468                 reiserfs_warning(inode->i_sb,
1469                                  "vs-13075: reiserfs_read_locked_inode: "
1470                                  "dead inode read from disk %K. "
1471                                  "This is likely to be race with knfsd. Ignore",
1472                                  &key);
1473                 reiserfs_make_bad_inode(inode);
1474         }
1475
1476         reiserfs_check_path(&path_to_sd);       /* init inode should be relsing */
1477
1478 }
1479
1480 /**
1481  * reiserfs_find_actor() - "find actor" reiserfs supplies to iget5_locked().
1482  *
1483  * @inode:    inode from hash table to check
1484  * @opaque:   "cookie" passed to iget5_locked(). This is &reiserfs_iget_args.
1485  *
1486  * This function is called by iget5_locked() to distinguish reiserfs inodes
1487  * having the same inode numbers. Such inodes can only exist due to some
1488  * error condition. One of them should be bad. Inodes with identical
1489  * inode numbers (objectids) are distinguished by parent directory ids.
1490  *
1491  */
1492 int reiserfs_find_actor(struct inode *inode, void *opaque)
1493 {
1494         struct reiserfs_iget_args *args;
1495
1496         args = opaque;
1497         /* args is already in CPU order */
1498         return (inode->i_ino == args->objectid) &&
1499             (le32_to_cpu(INODE_PKEY(inode)->k_dir_id) == args->dirid);
1500 }
1501
1502 struct inode *reiserfs_iget(struct super_block *s, const struct cpu_key *key)
1503 {
1504         struct inode *inode;
1505         struct reiserfs_iget_args args;
1506
1507         args.objectid = key->on_disk_key.k_objectid;
1508         args.dirid = key->on_disk_key.k_dir_id;
1509         inode = iget5_locked(s, key->on_disk_key.k_objectid,
1510                              reiserfs_find_actor, reiserfs_init_locked_inode,
1511                              (void *)(&args));
1512         if (!inode)
1513                 return ERR_PTR(-ENOMEM);
1514
1515         if (inode->i_state & I_NEW) {
1516                 reiserfs_read_locked_inode(inode, &args);
1517                 unlock_new_inode(inode);
1518         }
1519
1520         if (comp_short_keys(INODE_PKEY(inode), key) || is_bad_inode(inode)) {
1521                 /* either due to i/o error or a stale NFS handle */
1522                 iput(inode);
1523                 inode = NULL;
1524         }
1525         return inode;
1526 }
1527
1528 struct dentry *reiserfs_get_dentry(struct super_block *sb, void *vobjp)
1529 {
1530         __u32 *data = vobjp;
1531         struct cpu_key key;
1532         struct dentry *result;
1533         struct inode *inode;
1534
1535         key.on_disk_key.k_objectid = data[0];
1536         key.on_disk_key.k_dir_id = data[1];
1537         reiserfs_write_lock(sb);
1538         inode = reiserfs_iget(sb, &key);
1539         if (inode && !IS_ERR(inode) && data[2] != 0 &&
1540             data[2] != inode->i_generation) {
1541                 iput(inode);
1542                 inode = NULL;
1543         }
1544         reiserfs_write_unlock(sb);
1545         if (!inode)
1546                 inode = ERR_PTR(-ESTALE);
1547         if (IS_ERR(inode))
1548                 return ERR_PTR(PTR_ERR(inode));
1549         result = d_alloc_anon(inode);
1550         if (!result) {
1551                 iput(inode);
1552                 return ERR_PTR(-ENOMEM);
1553         }
1554         return result;
1555 }
1556
1557 struct dentry *reiserfs_decode_fh(struct super_block *sb, __u32 * data,
1558                                   int len, int fhtype,
1559                                   int (*acceptable) (void *contect,
1560                                                      struct dentry * de),
1561                                   void *context)
1562 {
1563         __u32 obj[3], parent[3];
1564
1565         /* fhtype happens to reflect the number of u32s encoded.
1566          * due to a bug in earlier code, fhtype might indicate there
1567          * are more u32s then actually fitted.
1568          * so if fhtype seems to be more than len, reduce fhtype.
1569          * Valid types are:
1570          *   2 - objectid + dir_id - legacy support
1571          *   3 - objectid + dir_id + generation
1572          *   4 - objectid + dir_id + objectid and dirid of parent - legacy
1573          *   5 - objectid + dir_id + generation + objectid and dirid of parent
1574          *   6 - as above plus generation of directory
1575          * 6 does not fit in NFSv2 handles
1576          */
1577         if (fhtype > len) {
1578                 if (fhtype != 6 || len != 5)
1579                         reiserfs_warning(sb,
1580                                          "nfsd/reiserfs, fhtype=%d, len=%d - odd",
1581                                          fhtype, len);
1582                 fhtype = 5;
1583         }
1584
1585         obj[0] = data[0];
1586         obj[1] = data[1];
1587         if (fhtype == 3 || fhtype >= 5)
1588                 obj[2] = data[2];
1589         else
1590                 obj[2] = 0;     /* generation number */
1591
1592         if (fhtype >= 4) {
1593                 parent[0] = data[fhtype >= 5 ? 3 : 2];
1594                 parent[1] = data[fhtype >= 5 ? 4 : 3];
1595                 if (fhtype == 6)
1596                         parent[2] = data[5];
1597                 else
1598                         parent[2] = 0;
1599         }
1600         return sb->s_export_op->find_exported_dentry(sb, obj,
1601                                                      fhtype < 4 ? NULL : parent,
1602                                                      acceptable, context);
1603 }
1604
1605 int reiserfs_encode_fh(struct dentry *dentry, __u32 * data, int *lenp,
1606                        int need_parent)
1607 {
1608         struct inode *inode = dentry->d_inode;
1609         int maxlen = *lenp;
1610
1611         if (maxlen < 3)
1612                 return 255;
1613
1614         data[0] = inode->i_ino;
1615         data[1] = le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
1616         data[2] = inode->i_generation;
1617         *lenp = 3;
1618         /* no room for directory info? return what we've stored so far */
1619         if (maxlen < 5 || !need_parent)
1620                 return 3;
1621
1622         spin_lock(&dentry->d_lock);
1623         inode = dentry->d_parent->d_inode;
1624         data[3] = inode->i_ino;
1625         data[4] = le32_to_cpu(INODE_PKEY(inode)->k_dir_id);
1626         *lenp = 5;
1627         if (maxlen >= 6) {
1628                 data[5] = inode->i_generation;
1629                 *lenp = 6;
1630         }
1631         spin_unlock(&dentry->d_lock);
1632         return *lenp;
1633 }
1634
1635 /* looks for stat data, then copies fields to it, marks the buffer
1636    containing stat data as dirty */
1637 /* reiserfs inodes are never really dirty, since the dirty inode call
1638 ** always logs them.  This call allows the VFS inode marking routines
1639 ** to properly mark inodes for datasync and such, but only actually
1640 ** does something when called for a synchronous update.
1641 */
1642 int reiserfs_write_inode(struct inode *inode, int do_sync)
1643 {
1644         struct reiserfs_transaction_handle th;
1645         int jbegin_count = 1;
1646
1647         if (inode->i_sb->s_flags & MS_RDONLY)
1648                 return -EROFS;
1649         /* memory pressure can sometimes initiate write_inode calls with sync == 1,
1650          ** these cases are just when the system needs ram, not when the 
1651          ** inode needs to reach disk for safety, and they can safely be
1652          ** ignored because the altered inode has already been logged.
1653          */
1654         if (do_sync && !(current->flags & PF_MEMALLOC)) {
1655                 reiserfs_write_lock(inode->i_sb);
1656                 if (!journal_begin(&th, inode->i_sb, jbegin_count)) {
1657                         reiserfs_update_sd(&th, inode);
1658                         journal_end_sync(&th, inode->i_sb, jbegin_count);
1659                 }
1660                 reiserfs_write_unlock(inode->i_sb);
1661         }
1662         return 0;
1663 }
1664
1665 /* stat data of new object is inserted already, this inserts the item
1666    containing "." and ".." entries */
1667 static int reiserfs_new_directory(struct reiserfs_transaction_handle *th,
1668                                   struct inode *inode,
1669                                   struct item_head *ih, struct path *path,
1670                                   struct inode *dir)
1671 {
1672         struct super_block *sb = th->t_super;
1673         char empty_dir[EMPTY_DIR_SIZE];
1674         char *body = empty_dir;
1675         struct cpu_key key;
1676         int retval;
1677
1678         BUG_ON(!th->t_trans_id);
1679
1680         _make_cpu_key(&key, KEY_FORMAT_3_5, le32_to_cpu(ih->ih_key.k_dir_id),
1681                       le32_to_cpu(ih->ih_key.k_objectid), DOT_OFFSET,
1682                       TYPE_DIRENTRY, 3 /*key length */ );
1683
1684         /* compose item head for new item. Directories consist of items of
1685            old type (ITEM_VERSION_1). Do not set key (second arg is 0), it
1686            is done by reiserfs_new_inode */
1687         if (old_format_only(sb)) {
1688                 make_le_item_head(ih, NULL, KEY_FORMAT_3_5, DOT_OFFSET,
1689                                   TYPE_DIRENTRY, EMPTY_DIR_SIZE_V1, 2);
1690
1691                 make_empty_dir_item_v1(body, ih->ih_key.k_dir_id,
1692                                        ih->ih_key.k_objectid,
1693                                        INODE_PKEY(dir)->k_dir_id,
1694                                        INODE_PKEY(dir)->k_objectid);
1695         } else {
1696                 make_le_item_head(ih, NULL, KEY_FORMAT_3_5, DOT_OFFSET,
1697                                   TYPE_DIRENTRY, EMPTY_DIR_SIZE, 2);
1698
1699                 make_empty_dir_item(body, ih->ih_key.k_dir_id,
1700                                     ih->ih_key.k_objectid,
1701                                     INODE_PKEY(dir)->k_dir_id,
1702                                     INODE_PKEY(dir)->k_objectid);
1703         }
1704
1705         /* look for place in the tree for new item */
1706         retval = search_item(sb, &key, path);
1707         if (retval == IO_ERROR) {
1708                 reiserfs_warning(sb, "vs-13080: reiserfs_new_directory: "
1709                                  "i/o failure occurred creating new directory");
1710                 return -EIO;
1711         }
1712         if (retval == ITEM_FOUND) {
1713                 pathrelse(path);
1714                 reiserfs_warning(sb, "vs-13070: reiserfs_new_directory: "
1715                                  "object with this key exists (%k)",
1716                                  &(ih->ih_key));
1717                 return -EEXIST;
1718         }
1719
1720         /* insert item, that is empty directory item */
1721         return reiserfs_insert_item(th, path, &key, ih, inode, body);
1722 }
1723
1724 /* stat data of object has been inserted, this inserts the item
1725    containing the body of symlink */
1726 static int reiserfs_new_symlink(struct reiserfs_transaction_handle *th, struct inode *inode,    /* Inode of symlink */
1727                                 struct item_head *ih,
1728                                 struct path *path, const char *symname,
1729                                 int item_len)
1730 {
1731         struct super_block *sb = th->t_super;
1732         struct cpu_key key;
1733         int retval;
1734
1735         BUG_ON(!th->t_trans_id);
1736
1737         _make_cpu_key(&key, KEY_FORMAT_3_5,
1738                       le32_to_cpu(ih->ih_key.k_dir_id),
1739                       le32_to_cpu(ih->ih_key.k_objectid),
1740                       1, TYPE_DIRECT, 3 /*key length */ );
1741
1742         make_le_item_head(ih, NULL, KEY_FORMAT_3_5, 1, TYPE_DIRECT, item_len,
1743                           0 /*free_space */ );
1744
1745         /* look for place in the tree for new item */
1746         retval = search_item(sb, &key, path);
1747         if (retval == IO_ERROR) {
1748                 reiserfs_warning(sb, "vs-13080: reiserfs_new_symlinik: "
1749                                  "i/o failure occurred creating new symlink");
1750                 return -EIO;
1751         }
1752         if (retval == ITEM_FOUND) {
1753                 pathrelse(path);
1754                 reiserfs_warning(sb, "vs-13080: reiserfs_new_symlink: "
1755                                  "object with this key exists (%k)",
1756                                  &(ih->ih_key));
1757                 return -EEXIST;
1758         }
1759
1760         /* insert item, that is body of symlink */
1761         return reiserfs_insert_item(th, path, &key, ih, inode, symname);
1762 }
1763
1764 /* inserts the stat data into the tree, and then calls
1765    reiserfs_new_directory (to insert ".", ".." item if new object is
1766    directory) or reiserfs_new_symlink (to insert symlink body if new
1767    object is symlink) or nothing (if new object is regular file) 
1768
1769    NOTE! uid and gid must already be set in the inode.  If we return
1770    non-zero due to an error, we have to drop the quota previously allocated
1771    for the fresh inode.  This can only be done outside a transaction, so
1772    if we return non-zero, we also end the transaction.  */
1773 int reiserfs_new_inode(struct reiserfs_transaction_handle *th,
1774                        struct inode *dir, int mode, const char *symname,
1775                        /* 0 for regular, EMTRY_DIR_SIZE for dirs, 
1776                           strlen (symname) for symlinks) */
1777                        loff_t i_size, struct dentry *dentry,
1778                        struct inode *inode)
1779 {
1780         struct super_block *sb;
1781         INITIALIZE_PATH(path_to_key);
1782         struct cpu_key key;
1783         struct item_head ih;
1784         struct stat_data sd;
1785         int retval;
1786         int err;
1787
1788         BUG_ON(!th->t_trans_id);
1789
1790         if (DQUOT_ALLOC_INODE(inode)) {
1791                 err = -EDQUOT;
1792                 goto out_end_trans;
1793         }
1794         if (!dir || !dir->i_nlink) {
1795                 err = -EPERM;
1796                 goto out_bad_inode;
1797         }
1798
1799         sb = dir->i_sb;
1800
1801         /* item head of new item */
1802         ih.ih_key.k_dir_id = reiserfs_choose_packing(dir);
1803         ih.ih_key.k_objectid = cpu_to_le32(reiserfs_get_unused_objectid(th));
1804         if (!ih.ih_key.k_objectid) {
1805                 err = -ENOMEM;
1806                 goto out_bad_inode;
1807         }
1808         if (old_format_only(sb))
1809                 /* not a perfect generation count, as object ids can be reused, but 
1810                  ** this is as good as reiserfs can do right now.
1811                  ** note that the private part of inode isn't filled in yet, we have
1812                  ** to use the directory.
1813                  */
1814                 inode->i_generation = le32_to_cpu(INODE_PKEY(dir)->k_objectid);
1815         else
1816 #if defined( USE_INODE_GENERATION_COUNTER )
1817                 inode->i_generation =
1818                     le32_to_cpu(REISERFS_SB(sb)->s_rs->s_inode_generation);
1819 #else
1820                 inode->i_generation = ++event;
1821 #endif
1822
1823         /* fill stat data */
1824         inode->i_nlink = (S_ISDIR(mode) ? 2 : 1);
1825
1826         /* uid and gid must already be set by the caller for quota init */
1827
1828         /* symlink cannot be immutable or append only, right? */
1829         if (S_ISLNK(inode->i_mode))
1830                 inode->i_flags &= ~(S_IMMUTABLE | S_APPEND);
1831
1832         inode->i_mtime = inode->i_atime = inode->i_ctime = CURRENT_TIME_SEC;
1833         inode->i_size = i_size;
1834         inode->i_blocks = 0;
1835         inode->i_bytes = 0;
1836         REISERFS_I(inode)->i_first_direct_byte = S_ISLNK(mode) ? 1 :
1837             U32_MAX /*NO_BYTES_IN_DIRECT_ITEM */ ;
1838
1839         INIT_LIST_HEAD(&(REISERFS_I(inode)->i_prealloc_list));
1840         REISERFS_I(inode)->i_flags = 0;
1841         REISERFS_I(inode)->i_prealloc_block = 0;
1842         REISERFS_I(inode)->i_prealloc_count = 0;
1843         REISERFS_I(inode)->i_trans_id = 0;
1844         REISERFS_I(inode)->i_jl = NULL;
1845         REISERFS_I(inode)->i_attrs =
1846             REISERFS_I(dir)->i_attrs & REISERFS_INHERIT_MASK;
1847         sd_attrs_to_i_attrs(REISERFS_I(inode)->i_attrs, inode);
1848         REISERFS_I(inode)->i_acl_access = NULL;
1849         REISERFS_I(inode)->i_acl_default = NULL;
1850         init_rwsem(&REISERFS_I(inode)->xattr_sem);
1851
1852         if (old_format_only(sb))
1853                 make_le_item_head(&ih, NULL, KEY_FORMAT_3_5, SD_OFFSET,
1854                                   TYPE_STAT_DATA, SD_V1_SIZE, MAX_US_INT);
1855         else
1856                 make_le_item_head(&ih, NULL, KEY_FORMAT_3_6, SD_OFFSET,
1857                                   TYPE_STAT_DATA, SD_SIZE, MAX_US_INT);
1858
1859         /* key to search for correct place for new stat data */
1860         _make_cpu_key(&key, KEY_FORMAT_3_6, le32_to_cpu(ih.ih_key.k_dir_id),
1861                       le32_to_cpu(ih.ih_key.k_objectid), SD_OFFSET,
1862                       TYPE_STAT_DATA, 3 /*key length */ );
1863
1864         /* find proper place for inserting of stat data */
1865         retval = search_item(sb, &key, &path_to_key);
1866         if (retval == IO_ERROR) {
1867                 err = -EIO;
1868                 goto out_bad_inode;
1869         }
1870         if (retval == ITEM_FOUND) {
1871                 pathrelse(&path_to_key);
1872                 err = -EEXIST;
1873                 goto out_bad_inode;
1874         }
1875         if (old_format_only(sb)) {
1876                 if (inode->i_uid & ~0xffff || inode->i_gid & ~0xffff) {
1877                         pathrelse(&path_to_key);
1878                         /* i_uid or i_gid is too big to be stored in stat data v3.5 */
1879                         err = -EINVAL;
1880                         goto out_bad_inode;
1881                 }
1882                 inode2sd_v1(&sd, inode, inode->i_size);
1883         } else {
1884                 inode2sd(&sd, inode, inode->i_size);
1885         }
1886         // these do not go to on-disk stat data
1887         inode->i_ino = le32_to_cpu(ih.ih_key.k_objectid);
1888         inode->i_blksize = reiserfs_default_io_size;
1889
1890         // store in in-core inode the key of stat data and version all
1891         // object items will have (directory items will have old offset
1892         // format, other new objects will consist of new items)
1893         memcpy(INODE_PKEY(inode), &(ih.ih_key), KEY_SIZE);
1894         if (old_format_only(sb) || S_ISDIR(mode) || S_ISLNK(mode))
1895                 set_inode_item_key_version(inode, KEY_FORMAT_3_5);
1896         else
1897                 set_inode_item_key_version(inode, KEY_FORMAT_3_6);
1898         if (old_format_only(sb))
1899                 set_inode_sd_version(inode, STAT_DATA_V1);
1900         else
1901                 set_inode_sd_version(inode, STAT_DATA_V2);
1902
1903         /* insert the stat data into the tree */
1904 #ifdef DISPLACE_NEW_PACKING_LOCALITIES
1905         if (REISERFS_I(dir)->new_packing_locality)
1906                 th->displace_new_blocks = 1;
1907 #endif
1908         retval =
1909             reiserfs_insert_item(th, &path_to_key, &key, &ih, inode,
1910                                  (char *)(&sd));
1911         if (retval) {
1912                 err = retval;
1913                 reiserfs_check_path(&path_to_key);
1914                 goto out_bad_inode;
1915         }
1916 #ifdef DISPLACE_NEW_PACKING_LOCALITIES
1917         if (!th->displace_new_blocks)
1918                 REISERFS_I(dir)->new_packing_locality = 0;
1919 #endif
1920         if (S_ISDIR(mode)) {
1921                 /* insert item with "." and ".." */
1922                 retval =
1923                     reiserfs_new_directory(th, inode, &ih, &path_to_key, dir);
1924         }
1925
1926         if (S_ISLNK(mode)) {
1927                 /* insert body of symlink */
1928                 if (!old_format_only(sb))
1929                         i_size = ROUND_UP(i_size);
1930                 retval =
1931                     reiserfs_new_symlink(th, inode, &ih, &path_to_key, symname,
1932                                          i_size);
1933         }
1934         if (retval) {
1935                 err = retval;
1936                 reiserfs_check_path(&path_to_key);
1937                 journal_end(th, th->t_super, th->t_blocks_allocated);
1938                 goto out_inserted_sd;
1939         }
1940
1941         /* XXX CHECK THIS */
1942         if (reiserfs_posixacl(inode->i_sb)) {
1943                 retval = reiserfs_inherit_default_acl(dir, dentry, inode);
1944                 if (retval) {
1945                         err = retval;
1946                         reiserfs_check_path(&path_to_key);
1947                         journal_end(th, th->t_super, th->t_blocks_allocated);
1948                         goto out_inserted_sd;
1949                 }
1950         } else if (inode->i_sb->s_flags & MS_POSIXACL) {
1951                 reiserfs_warning(inode->i_sb, "ACLs aren't enabled in the fs, "
1952                                  "but vfs thinks they are!");
1953         } else if (is_reiserfs_priv_object(dir)) {
1954                 reiserfs_mark_inode_private(inode);
1955         }
1956
1957         insert_inode_hash(inode);
1958         reiserfs_update_sd(th, inode);
1959         reiserfs_check_path(&path_to_key);
1960
1961         return 0;
1962
1963 /* it looks like you can easily compress these two goto targets into
1964  * one.  Keeping it like this doesn't actually hurt anything, and they
1965  * are place holders for what the quota code actually needs.
1966  */
1967       out_bad_inode:
1968         /* Invalidate the object, nothing was inserted yet */
1969         INODE_PKEY(inode)->k_objectid = 0;
1970
1971         /* Quota change must be inside a transaction for journaling */
1972         DQUOT_FREE_INODE(inode);
1973
1974       out_end_trans:
1975         journal_end(th, th->t_super, th->t_blocks_allocated);
1976         /* Drop can be outside and it needs more credits so it's better to have it outside */
1977         DQUOT_DROP(inode);
1978         inode->i_flags |= S_NOQUOTA;
1979         make_bad_inode(inode);
1980
1981       out_inserted_sd:
1982         inode->i_nlink = 0;
1983         th->t_trans_id = 0;     /* so the caller can't use this handle later */
1984
1985         /* If we were inheriting an ACL, we need to release the lock so that
1986          * iput doesn't deadlock in reiserfs_delete_xattrs. The locking
1987          * code really needs to be reworked, but this will take care of it
1988          * for now. -jeffm */
1989         if (REISERFS_I(dir)->i_acl_default && !IS_ERR(REISERFS_I(dir)->i_acl_default)) {
1990                 reiserfs_write_unlock_xattrs(dir->i_sb);
1991                 iput(inode);
1992                 reiserfs_write_lock_xattrs(dir->i_sb);
1993         } else
1994                 iput(inode);
1995         return err;
1996 }
1997
1998 /*
1999 ** finds the tail page in the page cache,
2000 ** reads the last block in.
2001 **
2002 ** On success, page_result is set to a locked, pinned page, and bh_result
2003 ** is set to an up to date buffer for the last block in the file.  returns 0.
2004 **
2005 ** tail conversion is not done, so bh_result might not be valid for writing
2006 ** check buffer_mapped(bh_result) and bh_result->b_blocknr != 0 before
2007 ** trying to write the block.
2008 **
2009 ** on failure, nonzero is returned, page_result and bh_result are untouched.
2010 */
2011 static int grab_tail_page(struct inode *p_s_inode,
2012                           struct page **page_result,
2013                           struct buffer_head **bh_result)
2014 {
2015
2016         /* we want the page with the last byte in the file,
2017          ** not the page that will hold the next byte for appending
2018          */
2019         unsigned long index = (p_s_inode->i_size - 1) >> PAGE_CACHE_SHIFT;
2020         unsigned long pos = 0;
2021         unsigned long start = 0;
2022         unsigned long blocksize = p_s_inode->i_sb->s_blocksize;
2023         unsigned long offset = (p_s_inode->i_size) & (PAGE_CACHE_SIZE - 1);
2024         struct buffer_head *bh;
2025         struct buffer_head *head;
2026         struct page *page;
2027         int error;
2028
2029         /* we know that we are only called with inode->i_size > 0.
2030          ** we also know that a file tail can never be as big as a block
2031          ** If i_size % blocksize == 0, our file is currently block aligned
2032          ** and it won't need converting or zeroing after a truncate.
2033          */
2034         if ((offset & (blocksize - 1)) == 0) {
2035                 return -ENOENT;
2036         }
2037         page = grab_cache_page(p_s_inode->i_mapping, index);
2038         error = -ENOMEM;
2039         if (!page) {
2040                 goto out;
2041         }
2042         /* start within the page of the last block in the file */
2043         start = (offset / blocksize) * blocksize;
2044
2045         error = block_prepare_write(page, start, offset,
2046                                     reiserfs_get_block_create_0);
2047         if (error)
2048                 goto unlock;
2049
2050         head = page_buffers(page);
2051         bh = head;
2052         do {
2053                 if (pos >= start) {
2054                         break;
2055                 }
2056                 bh = bh->b_this_page;
2057                 pos += blocksize;
2058         } while (bh != head);
2059
2060         if (!buffer_uptodate(bh)) {
2061                 /* note, this should never happen, prepare_write should
2062                  ** be taking care of this for us.  If the buffer isn't up to date,
2063                  ** I've screwed up the code to find the buffer, or the code to
2064                  ** call prepare_write
2065                  */
2066                 reiserfs_warning(p_s_inode->i_sb,
2067                                  "clm-6000: error reading block %lu on dev %s",
2068                                  bh->b_blocknr,
2069                                  reiserfs_bdevname(p_s_inode->i_sb));
2070                 error = -EIO;
2071                 goto unlock;
2072         }
2073         *bh_result = bh;
2074         *page_result = page;
2075
2076       out:
2077         return error;
2078
2079       unlock:
2080         unlock_page(page);
2081         page_cache_release(page);
2082         return error;
2083 }
2084
2085 /*
2086 ** vfs version of truncate file.  Must NOT be called with
2087 ** a transaction already started.
2088 **
2089 ** some code taken from block_truncate_page
2090 */
2091 int reiserfs_truncate_file(struct inode *p_s_inode, int update_timestamps)
2092 {
2093         struct reiserfs_transaction_handle th;
2094         /* we want the offset for the first byte after the end of the file */
2095         unsigned long offset = p_s_inode->i_size & (PAGE_CACHE_SIZE - 1);
2096         unsigned blocksize = p_s_inode->i_sb->s_blocksize;
2097         unsigned length;
2098         struct page *page = NULL;
2099         int error;
2100         struct buffer_head *bh = NULL;
2101         int err2;
2102
2103         reiserfs_write_lock(p_s_inode->i_sb);
2104
2105         if (p_s_inode->i_size > 0) {
2106                 if ((error = grab_tail_page(p_s_inode, &page, &bh))) {
2107                         // -ENOENT means we truncated past the end of the file, 
2108                         // and get_block_create_0 could not find a block to read in,
2109                         // which is ok.
2110                         if (error != -ENOENT)
2111                                 reiserfs_warning(p_s_inode->i_sb,
2112                                                  "clm-6001: grab_tail_page failed %d",
2113                                                  error);
2114                         page = NULL;
2115                         bh = NULL;
2116                 }
2117         }
2118
2119         /* so, if page != NULL, we have a buffer head for the offset at 
2120          ** the end of the file. if the bh is mapped, and bh->b_blocknr != 0, 
2121          ** then we have an unformatted node.  Otherwise, we have a direct item, 
2122          ** and no zeroing is required on disk.  We zero after the truncate, 
2123          ** because the truncate might pack the item anyway 
2124          ** (it will unmap bh if it packs).
2125          */
2126         /* it is enough to reserve space in transaction for 2 balancings:
2127            one for "save" link adding and another for the first
2128            cut_from_item. 1 is for update_sd */
2129         error = journal_begin(&th, p_s_inode->i_sb,
2130                               JOURNAL_PER_BALANCE_CNT * 2 + 1);
2131         if (error)
2132                 goto out;
2133         reiserfs_update_inode_transaction(p_s_inode);
2134         if (update_timestamps)
2135                 /* we are doing real truncate: if the system crashes before the last
2136                    transaction of truncating gets committed - on reboot the file
2137                    either appears truncated properly or not truncated at all */
2138                 add_save_link(&th, p_s_inode, 1);
2139         err2 = reiserfs_do_truncate(&th, p_s_inode, page, update_timestamps);
2140         error =
2141             journal_end(&th, p_s_inode->i_sb, JOURNAL_PER_BALANCE_CNT * 2 + 1);
2142         if (error)
2143                 goto out;
2144
2145         /* check reiserfs_do_truncate after ending the transaction */
2146         if (err2) {
2147                 error = err2;
2148                 goto out;
2149         }
2150         
2151         if (update_timestamps) {
2152                 error = remove_save_link(p_s_inode, 1 /* truncate */ );
2153                 if (error)
2154                         goto out;
2155         }
2156
2157         if (page) {
2158                 length = offset & (blocksize - 1);
2159                 /* if we are not on a block boundary */
2160                 if (length) {
2161                         char *kaddr;
2162
2163                         length = blocksize - length;
2164                         kaddr = kmap_atomic(page, KM_USER0);
2165                         memset(kaddr + offset, 0, length);
2166                         flush_dcache_page(page);
2167                         kunmap_atomic(kaddr, KM_USER0);
2168                         if (buffer_mapped(bh) && bh->b_blocknr != 0) {
2169                                 mark_buffer_dirty(bh);
2170                         }
2171                 }
2172                 unlock_page(page);
2173                 page_cache_release(page);
2174         }
2175
2176         reiserfs_write_unlock(p_s_inode->i_sb);
2177         return 0;
2178       out:
2179         if (page) {
2180                 unlock_page(page);
2181                 page_cache_release(page);
2182         }
2183         reiserfs_write_unlock(p_s_inode->i_sb);
2184         return error;
2185 }
2186
2187 static int map_block_for_writepage(struct inode *inode,
2188                                    struct buffer_head *bh_result,
2189                                    unsigned long block)
2190 {
2191         struct reiserfs_transaction_handle th;
2192         int fs_gen;
2193         struct item_head tmp_ih;
2194         struct item_head *ih;
2195         struct buffer_head *bh;
2196         __le32 *item;
2197         struct cpu_key key;
2198         INITIALIZE_PATH(path);
2199         int pos_in_item;
2200         int jbegin_count = JOURNAL_PER_BALANCE_CNT;
2201         loff_t byte_offset = ((loff_t)block << inode->i_sb->s_blocksize_bits)+1;
2202         int retval;
2203         int use_get_block = 0;
2204         int bytes_copied = 0;
2205         int copy_size;
2206         int trans_running = 0;
2207
2208         /* catch places below that try to log something without starting a trans */
2209         th.t_trans_id = 0;
2210
2211         if (!buffer_uptodate(bh_result)) {
2212                 return -EIO;
2213         }
2214
2215         kmap(bh_result->b_page);
2216       start_over:
2217         reiserfs_write_lock(inode->i_sb);
2218         make_cpu_key(&key, inode, byte_offset, TYPE_ANY, 3);
2219
2220       research:
2221         retval = search_for_position_by_key(inode->i_sb, &key, &path);
2222         if (retval != POSITION_FOUND) {
2223                 use_get_block = 1;
2224                 goto out;
2225         }
2226
2227         bh = get_last_bh(&path);
2228         ih = get_ih(&path);
2229         item = get_item(&path);
2230         pos_in_item = path.pos_in_item;
2231
2232         /* we've found an unformatted node */
2233         if (indirect_item_found(retval, ih)) {
2234                 if (bytes_copied > 0) {
2235                         reiserfs_warning(inode->i_sb,
2236                                          "clm-6002: bytes_copied %d",
2237                                          bytes_copied);
2238                 }
2239                 if (!get_block_num(item, pos_in_item)) {
2240                         /* crap, we are writing to a hole */
2241                         use_get_block = 1;
2242                         goto out;
2243                 }
2244                 set_block_dev_mapped(bh_result,
2245                                      get_block_num(item, pos_in_item), inode);
2246         } else if (is_direct_le_ih(ih)) {
2247                 char *p;
2248                 p = page_address(bh_result->b_page);
2249                 p += (byte_offset - 1) & (PAGE_CACHE_SIZE - 1);
2250                 copy_size = ih_item_len(ih) - pos_in_item;
2251
2252                 fs_gen = get_generation(inode->i_sb);
2253                 copy_item_head(&tmp_ih, ih);
2254
2255                 if (!trans_running) {
2256                         /* vs-3050 is gone, no need to drop the path */
2257                         retval = journal_begin(&th, inode->i_sb, jbegin_count);
2258                         if (retval)
2259                                 goto out;
2260                         reiserfs_update_inode_transaction(inode);
2261                         trans_running = 1;
2262                         if (fs_changed(fs_gen, inode->i_sb)
2263                             && item_moved(&tmp_ih, &path)) {
2264                                 reiserfs_restore_prepared_buffer(inode->i_sb,
2265                                                                  bh);
2266                                 goto research;
2267                         }
2268                 }
2269
2270                 reiserfs_prepare_for_journal(inode->i_sb, bh, 1);
2271
2272                 if (fs_changed(fs_gen, inode->i_sb)
2273                     && item_moved(&tmp_ih, &path)) {
2274                         reiserfs_restore_prepared_buffer(inode->i_sb, bh);
2275                         goto research;
2276                 }
2277
2278                 memcpy(B_I_PITEM(bh, ih) + pos_in_item, p + bytes_copied,
2279                        copy_size);
2280
2281                 journal_mark_dirty(&th, inode->i_sb, bh);
2282                 bytes_copied += copy_size;
2283                 set_block_dev_mapped(bh_result, 0, inode);
2284
2285                 /* are there still bytes left? */
2286                 if (bytes_copied < bh_result->b_size &&
2287                     (byte_offset + bytes_copied) < inode->i_size) {
2288                         set_cpu_key_k_offset(&key,
2289                                              cpu_key_k_offset(&key) +
2290                                              copy_size);
2291                         goto research;
2292                 }
2293         } else {
2294                 reiserfs_warning(inode->i_sb,
2295                                  "clm-6003: bad item inode %lu, device %s",
2296                                  inode->i_ino, reiserfs_bdevname(inode->i_sb));
2297                 retval = -EIO;
2298                 goto out;
2299         }
2300         retval = 0;
2301
2302       out:
2303         pathrelse(&path);
2304         if (trans_running) {
2305                 int err = journal_end(&th, inode->i_sb, jbegin_count);
2306                 if (err)
2307                         retval = err;
2308                 trans_running = 0;
2309         }
2310         reiserfs_write_unlock(inode->i_sb);
2311
2312         /* this is where we fill in holes in the file. */
2313         if (use_get_block) {
2314                 retval = reiserfs_get_block(inode, block, bh_result,
2315                                             GET_BLOCK_CREATE | GET_BLOCK_NO_IMUX
2316                                             | GET_BLOCK_NO_DANGLE);
2317                 if (!retval) {
2318                         if (!buffer_mapped(bh_result)
2319                             || bh_result->b_blocknr == 0) {
2320                                 /* get_block failed to find a mapped unformatted node. */
2321                                 use_get_block = 0;
2322                                 goto start_over;
2323                         }
2324                 }
2325         }
2326         kunmap(bh_result->b_page);
2327
2328         if (!retval && buffer_mapped(bh_result) && bh_result->b_blocknr == 0) {
2329                 /* we've copied data from the page into the direct item, so the
2330                  * buffer in the page is now clean, mark it to reflect that.
2331                  */
2332                 lock_buffer(bh_result);
2333                 clear_buffer_dirty(bh_result);
2334                 unlock_buffer(bh_result);
2335         }
2336         return retval;
2337 }
2338
2339 /* 
2340  * mason@suse.com: updated in 2.5.54 to follow the same general io 
2341  * start/recovery path as __block_write_full_page, along with special
2342  * code to handle reiserfs tails.
2343  */
2344 static int reiserfs_write_full_page(struct page *page,
2345                                     struct writeback_control *wbc)
2346 {
2347         struct inode *inode = page->mapping->host;
2348         unsigned long end_index = inode->i_size >> PAGE_CACHE_SHIFT;
2349         int error = 0;
2350         unsigned long block;
2351         struct buffer_head *head, *bh;
2352         int partial = 0;
2353         int nr = 0;
2354         int checked = PageChecked(page);
2355         struct reiserfs_transaction_handle th;
2356         struct super_block *s = inode->i_sb;
2357         int bh_per_page = PAGE_CACHE_SIZE / s->s_blocksize;
2358         th.t_trans_id = 0;
2359
2360         /* no logging allowed when nonblocking or from PF_MEMALLOC */
2361         if (checked && (current->flags & PF_MEMALLOC)) {
2362                 redirty_page_for_writepage(wbc, page);
2363                 unlock_page(page);
2364                 return 0;
2365         }
2366
2367         /* The page dirty bit is cleared before writepage is called, which
2368          * means we have to tell create_empty_buffers to make dirty buffers
2369          * The page really should be up to date at this point, so tossing
2370          * in the BH_Uptodate is just a sanity check.
2371          */
2372         if (!page_has_buffers(page)) {
2373                 create_empty_buffers(page, s->s_blocksize,
2374                                      (1 << BH_Dirty) | (1 << BH_Uptodate));
2375         }
2376         head = page_buffers(page);
2377
2378         /* last page in the file, zero out any contents past the
2379          ** last byte in the file
2380          */
2381         if (page->index >= end_index) {
2382                 char *kaddr;
2383                 unsigned last_offset;
2384
2385                 last_offset = inode->i_size & (PAGE_CACHE_SIZE - 1);
2386                 /* no file contents in this page */
2387                 if (page->index >= end_index + 1 || !last_offset) {
2388                         unlock_page(page);
2389                         return 0;
2390                 }
2391                 kaddr = kmap_atomic(page, KM_USER0);
2392                 memset(kaddr + last_offset, 0, PAGE_CACHE_SIZE - last_offset);
2393                 flush_dcache_page(page);
2394                 kunmap_atomic(kaddr, KM_USER0);
2395         }
2396         bh = head;
2397         block = page->index << (PAGE_CACHE_SHIFT - s->s_blocksize_bits);
2398         /* first map all the buffers, logging any direct items we find */
2399         do {
2400                 if ((checked || buffer_dirty(bh)) && (!buffer_mapped(bh) ||
2401                                                       (buffer_mapped(bh)
2402                                                        && bh->b_blocknr ==
2403                                                        0))) {
2404                         /* not mapped yet, or it points to a direct item, search
2405                          * the btree for the mapping info, and log any direct
2406                          * items found
2407                          */
2408                         if ((error = map_block_for_writepage(inode, bh, block))) {
2409                                 goto fail;
2410                         }
2411                 }
2412                 bh = bh->b_this_page;
2413                 block++;
2414         } while (bh != head);
2415
2416         /*
2417          * we start the transaction after map_block_for_writepage,
2418          * because it can create holes in the file (an unbounded operation).
2419          * starting it here, we can make a reliable estimate for how many
2420          * blocks we're going to log
2421          */
2422         if (checked) {
2423                 ClearPageChecked(page);
2424                 reiserfs_write_lock(s);
2425                 error = journal_begin(&th, s, bh_per_page + 1);
2426                 if (error) {
2427                         reiserfs_write_unlock(s);
2428                         goto fail;
2429                 }
2430                 reiserfs_update_inode_transaction(inode);
2431         }
2432         /* now go through and lock any dirty buffers on the page */
2433         do {
2434                 get_bh(bh);
2435                 if (!buffer_mapped(bh))
2436                         continue;
2437                 if (buffer_mapped(bh) && bh->b_blocknr == 0)
2438                         continue;
2439
2440                 if (checked) {
2441                         reiserfs_prepare_for_journal(s, bh, 1);
2442                         journal_mark_dirty(&th, s, bh);
2443                         continue;
2444                 }
2445                 /* from this point on, we know the buffer is mapped to a
2446                  * real block and not a direct item
2447                  */
2448                 if (wbc->sync_mode != WB_SYNC_NONE || !wbc->nonblocking) {
2449                         lock_buffer(bh);
2450                 } else {
2451                         if (test_set_buffer_locked(bh)) {
2452                                 redirty_page_for_writepage(wbc, page);
2453                                 continue;
2454                         }
2455                 }
2456                 if (test_clear_buffer_dirty(bh)) {
2457                         mark_buffer_async_write(bh);
2458                 } else {
2459                         unlock_buffer(bh);
2460                 }
2461         } while ((bh = bh->b_this_page) != head);
2462
2463         if (checked) {
2464                 error = journal_end(&th, s, bh_per_page + 1);
2465                 reiserfs_write_unlock(s);
2466                 if (error)
2467                         goto fail;
2468         }
2469         BUG_ON(PageWriteback(page));
2470         set_page_writeback(page);
2471         unlock_page(page);
2472
2473         /*
2474          * since any buffer might be the only dirty buffer on the page, 
2475          * the first submit_bh can bring the page out of writeback.
2476          * be careful with the buffers.
2477          */
2478         do {
2479                 struct buffer_head *next = bh->b_this_page;
2480                 if (buffer_async_write(bh)) {
2481                         submit_bh(WRITE, bh);
2482                         nr++;
2483                 }
2484                 put_bh(bh);
2485                 bh = next;
2486         } while (bh != head);
2487
2488         error = 0;
2489       done:
2490         if (nr == 0) {
2491                 /*
2492                  * if this page only had a direct item, it is very possible for
2493                  * no io to be required without there being an error.  Or, 
2494                  * someone else could have locked them and sent them down the 
2495                  * pipe without locking the page
2496                  */
2497                 bh = head;
2498                 do {
2499                         if (!buffer_uptodate(bh)) {
2500                                 partial = 1;
2501                                 break;
2502                         }
2503                         bh = bh->b_this_page;
2504                 } while (bh != head);
2505                 if (!partial)
2506                         SetPageUptodate(page);
2507                 end_page_writeback(page);
2508         }
2509         return error;
2510
2511       fail:
2512         /* catches various errors, we need to make sure any valid dirty blocks
2513          * get to the media.  The page is currently locked and not marked for 
2514          * writeback
2515          */
2516         ClearPageUptodate(page);
2517         bh = head;
2518         do {
2519                 get_bh(bh);
2520                 if (buffer_mapped(bh) && buffer_dirty(bh) && bh->b_blocknr) {
2521                         lock_buffer(bh);
2522                         mark_buffer_async_write(bh);
2523                 } else {
2524                         /*
2525                          * clear any dirty bits that might have come from getting
2526                          * attached to a dirty page
2527                          */
2528                         clear_buffer_dirty(bh);
2529                 }
2530                 bh = bh->b_this_page;
2531         } while (bh != head);
2532         SetPageError(page);
2533         BUG_ON(PageWriteback(page));
2534         set_page_writeback(page);
2535         unlock_page(page);
2536         do {
2537                 struct buffer_head *next = bh->b_this_page;
2538                 if (buffer_async_write(bh)) {
2539                         clear_buffer_dirty(bh);
2540                         submit_bh(WRITE, bh);
2541                         nr++;
2542                 }
2543                 put_bh(bh);
2544                 bh = next;
2545         } while (bh != head);
2546         goto done;
2547 }
2548
2549 static int reiserfs_readpage(struct file *f, struct page *page)
2550 {
2551         return block_read_full_page(page, reiserfs_get_block);
2552 }
2553
2554 static int reiserfs_writepage(struct page *page, struct writeback_control *wbc)
2555 {
2556         struct inode *inode = page->mapping->host;
2557         reiserfs_wait_on_write_block(inode->i_sb);
2558         return reiserfs_write_full_page(page, wbc);
2559 }
2560
2561 static int reiserfs_prepare_write(struct file *f, struct page *page,
2562                                   unsigned from, unsigned to)
2563 {
2564         struct inode *inode = page->mapping->host;
2565         int ret;
2566         int old_ref = 0;
2567
2568         reiserfs_wait_on_write_block(inode->i_sb);
2569         fix_tail_page_for_writing(page);
2570         if (reiserfs_transaction_running(inode->i_sb)) {
2571                 struct reiserfs_transaction_handle *th;
2572                 th = (struct reiserfs_transaction_handle *)current->
2573                     journal_info;
2574                 BUG_ON(!th->t_refcount);
2575                 BUG_ON(!th->t_trans_id);
2576                 old_ref = th->t_refcount;
2577                 th->t_refcount++;
2578         }
2579
2580         ret = block_prepare_write(page, from, to, reiserfs_get_block);
2581         if (ret && reiserfs_transaction_running(inode->i_sb)) {
2582                 struct reiserfs_transaction_handle *th = current->journal_info;
2583                 /* this gets a little ugly.  If reiserfs_get_block returned an
2584                  * error and left a transacstion running, we've got to close it,
2585                  * and we've got to free handle if it was a persistent transaction.
2586                  *
2587                  * But, if we had nested into an existing transaction, we need
2588                  * to just drop the ref count on the handle.
2589                  *
2590                  * If old_ref == 0, the transaction is from reiserfs_get_block,
2591                  * and it was a persistent trans.  Otherwise, it was nested above.
2592                  */
2593                 if (th->t_refcount > old_ref) {
2594                         if (old_ref)
2595                                 th->t_refcount--;
2596                         else {
2597                                 int err;
2598                                 reiserfs_write_lock(inode->i_sb);
2599                                 err = reiserfs_end_persistent_transaction(th);
2600                                 reiserfs_write_unlock(inode->i_sb);
2601                                 if (err)
2602                                         ret = err;
2603                         }
2604                 }
2605         }
2606         return ret;
2607
2608 }
2609
2610 static sector_t reiserfs_aop_bmap(struct address_space *as, sector_t block)
2611 {
2612         return generic_block_bmap(as, block, reiserfs_bmap);
2613 }
2614
2615 static int reiserfs_commit_write(struct file *f, struct page *page,
2616                                  unsigned from, unsigned to)
2617 {
2618         struct inode *inode = page->mapping->host;
2619         loff_t pos = ((loff_t) page->index << PAGE_CACHE_SHIFT) + to;
2620         int ret = 0;
2621         int update_sd = 0;
2622         struct reiserfs_transaction_handle *th = NULL;
2623
2624         reiserfs_wait_on_write_block(inode->i_sb);
2625         if (reiserfs_transaction_running(inode->i_sb)) {
2626                 th = current->journal_info;
2627         }
2628         reiserfs_commit_page(inode, page, from, to);
2629
2630         /* generic_commit_write does this for us, but does not update the
2631          ** transaction tracking stuff when the size changes.  So, we have
2632          ** to do the i_size updates here.
2633          */
2634         if (pos > inode->i_size) {
2635                 struct reiserfs_transaction_handle myth;
2636                 reiserfs_write_lock(inode->i_sb);
2637                 /* If the file have grown beyond the border where it
2638                    can have a tail, unmark it as needing a tail
2639                    packing */
2640                 if ((have_large_tails(inode->i_sb)
2641                      && inode->i_size > i_block_size(inode) * 4)
2642                     || (have_small_tails(inode->i_sb)
2643                         && inode->i_size > i_block_size(inode)))
2644                         REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask;
2645
2646                 ret = journal_begin(&myth, inode->i_sb, 1);
2647                 if (ret) {
2648                         reiserfs_write_unlock(inode->i_sb);
2649                         goto journal_error;
2650                 }
2651                 reiserfs_update_inode_transaction(inode);
2652                 inode->i_size = pos;
2653                 /*
2654                  * this will just nest into our transaction.  It's important
2655                  * to use mark_inode_dirty so the inode gets pushed around on the
2656                  * dirty lists, and so that O_SYNC works as expected
2657                  */
2658                 mark_inode_dirty(inode);
2659                 reiserfs_update_sd(&myth, inode);
2660                 update_sd = 1;
2661                 ret = journal_end(&myth, inode->i_sb, 1);
2662                 reiserfs_write_unlock(inode->i_sb);
2663                 if (ret)
2664                         goto journal_error;
2665         }
2666         if (th) {
2667                 reiserfs_write_lock(inode->i_sb);
2668                 if (!update_sd)
2669                         mark_inode_dirty(inode);
2670                 ret = reiserfs_end_persistent_transaction(th);
2671                 reiserfs_write_unlock(inode->i_sb);
2672                 if (ret)
2673                         goto out;
2674         }
2675
2676       out:
2677         return ret;
2678
2679       journal_error:
2680         if (th) {
2681                 reiserfs_write_lock(inode->i_sb);
2682                 if (!update_sd)
2683                         reiserfs_update_sd(th, inode);
2684                 ret = reiserfs_end_persistent_transaction(th);
2685                 reiserfs_write_unlock(inode->i_sb);
2686         }
2687
2688         return ret;
2689 }
2690
2691 void sd_attrs_to_i_attrs(__u16 sd_attrs, struct inode *inode)
2692 {
2693         if (reiserfs_attrs(inode->i_sb)) {
2694                 if (sd_attrs & REISERFS_SYNC_FL)
2695                         inode->i_flags |= S_SYNC;
2696                 else
2697                         inode->i_flags &= ~S_SYNC;
2698                 if (sd_attrs & REISERFS_IMMUTABLE_FL)
2699                         inode->i_flags |= S_IMMUTABLE;
2700                 else
2701                         inode->i_flags &= ~S_IMMUTABLE;
2702                 if (sd_attrs & REISERFS_APPEND_FL)
2703                         inode->i_flags |= S_APPEND;
2704                 else
2705                         inode->i_flags &= ~S_APPEND;
2706                 if (sd_attrs & REISERFS_NOATIME_FL)
2707                         inode->i_flags |= S_NOATIME;
2708                 else
2709                         inode->i_flags &= ~S_NOATIME;
2710                 if (sd_attrs & REISERFS_NOTAIL_FL)
2711                         REISERFS_I(inode)->i_flags |= i_nopack_mask;
2712                 else
2713                         REISERFS_I(inode)->i_flags &= ~i_nopack_mask;
2714         }
2715 }
2716
2717 void i_attrs_to_sd_attrs(struct inode *inode, __u16 * sd_attrs)
2718 {
2719         if (reiserfs_attrs(inode->i_sb)) {
2720                 if (inode->i_flags & S_IMMUTABLE)
2721                         *sd_attrs |= REISERFS_IMMUTABLE_FL;
2722                 else
2723                         *sd_attrs &= ~REISERFS_IMMUTABLE_FL;
2724                 if (inode->i_flags & S_SYNC)
2725                         *sd_attrs |= REISERFS_SYNC_FL;
2726                 else
2727                         *sd_attrs &= ~REISERFS_SYNC_FL;
2728                 if (inode->i_flags & S_NOATIME)
2729                         *sd_attrs |= REISERFS_NOATIME_FL;
2730                 else
2731                         *sd_attrs &= ~REISERFS_NOATIME_FL;
2732                 if (REISERFS_I(inode)->i_flags & i_nopack_mask)
2733                         *sd_attrs |= REISERFS_NOTAIL_FL;
2734                 else
2735                         *sd_attrs &= ~REISERFS_NOTAIL_FL;
2736         }
2737 }
2738
2739 /* decide if this buffer needs to stay around for data logging or ordered
2740 ** write purposes
2741 */
2742 static int invalidatepage_can_drop(struct inode *inode, struct buffer_head *bh)
2743 {
2744         int ret = 1;
2745         struct reiserfs_journal *j = SB_JOURNAL(inode->i_sb);
2746
2747         lock_buffer(bh);
2748         spin_lock(&j->j_dirty_buffers_lock);
2749         if (!buffer_mapped(bh)) {
2750                 goto free_jh;
2751         }
2752         /* the page is locked, and the only places that log a data buffer
2753          * also lock the page.
2754          */
2755         if (reiserfs_file_data_log(inode)) {
2756                 /*
2757                  * very conservative, leave the buffer pinned if
2758                  * anyone might need it.
2759                  */
2760                 if (buffer_journaled(bh) || buffer_journal_dirty(bh)) {
2761                         ret = 0;
2762                 }
2763         } else  if (buffer_dirty(bh)) {
2764                 struct reiserfs_journal_list *jl;
2765                 struct reiserfs_jh *jh = bh->b_private;
2766
2767                 /* why is this safe?
2768                  * reiserfs_setattr updates i_size in the on disk
2769                  * stat data before allowing vmtruncate to be called.
2770                  *
2771                  * If buffer was put onto the ordered list for this
2772                  * transaction, we know for sure either this transaction
2773                  * or an older one already has updated i_size on disk,
2774                  * and this ordered data won't be referenced in the file
2775                  * if we crash.
2776                  *
2777                  * if the buffer was put onto the ordered list for an older
2778                  * transaction, we need to leave it around
2779                  */
2780                 if (jh && (jl = jh->jl)
2781                     && jl != SB_JOURNAL(inode->i_sb)->j_current_jl)
2782                         ret = 0;
2783         }
2784       free_jh:
2785         if (ret && bh->b_private) {
2786                 reiserfs_free_jh(bh);
2787         }
2788         spin_unlock(&j->j_dirty_buffers_lock);
2789         unlock_buffer(bh);
2790         return ret;
2791 }
2792
2793 /* clm -- taken from fs/buffer.c:block_invalidate_page */
2794 static void reiserfs_invalidatepage(struct page *page, unsigned long offset)
2795 {
2796         struct buffer_head *head, *bh, *next;
2797         struct inode *inode = page->mapping->host;
2798         unsigned int curr_off = 0;
2799         int ret = 1;
2800
2801         BUG_ON(!PageLocked(page));
2802
2803         if (offset == 0)
2804                 ClearPageChecked(page);
2805
2806         if (!page_has_buffers(page))
2807                 goto out;
2808
2809         head = page_buffers(page);
2810         bh = head;
2811         do {
2812                 unsigned int next_off = curr_off + bh->b_size;
2813                 next = bh->b_this_page;
2814
2815                 /*
2816                  * is this block fully invalidated?
2817                  */
2818                 if (offset <= curr_off) {
2819                         if (invalidatepage_can_drop(inode, bh))
2820                                 reiserfs_unmap_buffer(bh);
2821                         else
2822                                 ret = 0;
2823                 }
2824                 curr_off = next_off;
2825                 bh = next;
2826         } while (bh != head);
2827
2828         /*
2829          * We release buffers only if the entire page is being invalidated.
2830          * The get_block cached value has been unconditionally invalidated,
2831          * so real IO is not possible anymore.
2832          */
2833         if (!offset && ret) {
2834                 ret = try_to_release_page(page, 0);
2835                 /* maybe should BUG_ON(!ret); - neilb */
2836         }
2837       out:
2838         return;
2839 }
2840
2841 static int reiserfs_set_page_dirty(struct page *page)
2842 {
2843         struct inode *inode = page->mapping->host;
2844         if (reiserfs_file_data_log(inode)) {
2845                 SetPageChecked(page);
2846                 return __set_page_dirty_nobuffers(page);
2847         }
2848         return __set_page_dirty_buffers(page);
2849 }
2850
2851 /*
2852  * Returns 1 if the page's buffers were dropped.  The page is locked.
2853  *
2854  * Takes j_dirty_buffers_lock to protect the b_assoc_buffers list_heads
2855  * in the buffers at page_buffers(page).
2856  *
2857  * even in -o notail mode, we can't be sure an old mount without -o notail
2858  * didn't create files with tails.
2859  */
2860 static int reiserfs_releasepage(struct page *page, gfp_t unused_gfp_flags)
2861 {
2862         struct inode *inode = page->mapping->host;
2863         struct reiserfs_journal *j = SB_JOURNAL(inode->i_sb);
2864         struct buffer_head *head;
2865         struct buffer_head *bh;
2866         int ret = 1;
2867
2868         WARN_ON(PageChecked(page));
2869         spin_lock(&j->j_dirty_buffers_lock);
2870         head = page_buffers(page);
2871         bh = head;
2872         do {
2873                 if (bh->b_private) {
2874                         if (!buffer_dirty(bh) && !buffer_locked(bh)) {
2875                                 reiserfs_free_jh(bh);
2876                         } else {
2877                                 ret = 0;
2878                                 break;
2879                         }
2880                 }
2881                 bh = bh->b_this_page;
2882         } while (bh != head);
2883         if (ret)
2884                 ret = try_to_free_buffers(page);
2885         spin_unlock(&j->j_dirty_buffers_lock);
2886         return ret;
2887 }
2888
2889 /* We thank Mingming Cao for helping us understand in great detail what
2890    to do in this section of the code. */
2891 static ssize_t reiserfs_direct_IO(int rw, struct kiocb *iocb,
2892                                   const struct iovec *iov, loff_t offset,
2893                                   unsigned long nr_segs)
2894 {
2895         struct file *file = iocb->ki_filp;
2896         struct inode *inode = file->f_mapping->host;
2897
2898         return blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
2899                                   offset, nr_segs,
2900                                   reiserfs_get_blocks_direct_io, NULL);
2901 }
2902
2903 int reiserfs_setattr(struct dentry *dentry, struct iattr *attr)
2904 {
2905         struct inode *inode = dentry->d_inode;
2906         int error;
2907         unsigned int ia_valid = attr->ia_valid;
2908         reiserfs_write_lock(inode->i_sb);
2909         if (attr->ia_valid & ATTR_SIZE) {
2910                 /* version 2 items will be caught by the s_maxbytes check
2911                  ** done for us in vmtruncate
2912                  */
2913                 if (get_inode_item_key_version(inode) == KEY_FORMAT_3_5 &&
2914                     attr->ia_size > MAX_NON_LFS) {
2915                         error = -EFBIG;
2916                         goto out;
2917                 }
2918                 /* fill in hole pointers in the expanding truncate case. */
2919                 if (attr->ia_size > inode->i_size) {
2920                         error = generic_cont_expand(inode, attr->ia_size);
2921                         if (REISERFS_I(inode)->i_prealloc_count > 0) {
2922                                 int err;
2923                                 struct reiserfs_transaction_handle th;
2924                                 /* we're changing at most 2 bitmaps, inode + super */
2925                                 err = journal_begin(&th, inode->i_sb, 4);
2926                                 if (!err) {
2927                                         reiserfs_discard_prealloc(&th, inode);
2928                                         err = journal_end(&th, inode->i_sb, 4);
2929                                 }
2930                                 if (err)
2931                                         error = err;
2932                         }
2933                         if (error)
2934                                 goto out;
2935                 }
2936         }
2937
2938         if ((((attr->ia_valid & ATTR_UID) && (attr->ia_uid & ~0xffff)) ||
2939              ((attr->ia_valid & ATTR_GID) && (attr->ia_gid & ~0xffff))) &&
2940             (get_inode_sd_version(inode) == STAT_DATA_V1)) {
2941                 /* stat data of format v3.5 has 16 bit uid and gid */
2942                 error = -EINVAL;
2943                 goto out;
2944         }
2945
2946         error = inode_change_ok(inode, attr);
2947         if (!error) {
2948                 if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
2949                     (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
2950                         error = reiserfs_chown_xattrs(inode, attr);
2951
2952                         if (!error) {
2953                                 struct reiserfs_transaction_handle th;
2954                                 int jbegin_count =
2955                                     2 *
2956                                     (REISERFS_QUOTA_INIT_BLOCKS(inode->i_sb) +
2957                                      REISERFS_QUOTA_DEL_BLOCKS(inode->i_sb)) +
2958                                     2;
2959
2960                                 /* (user+group)*(old+new) structure - we count quota info and , inode write (sb, inode) */
2961                                 error =
2962                                     journal_begin(&th, inode->i_sb,
2963                                                   jbegin_count);
2964                                 if (error)
2965                                         goto out;
2966                                 error =
2967                                     DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
2968                                 if (error) {
2969                                         journal_end(&th, inode->i_sb,
2970                                                     jbegin_count);
2971                                         goto out;
2972                                 }
2973                                 /* Update corresponding info in inode so that everything is in
2974                                  * one transaction */
2975                                 if (attr->ia_valid & ATTR_UID)
2976                                         inode->i_uid = attr->ia_uid;
2977                                 if (attr->ia_valid & ATTR_GID)
2978                                         inode->i_gid = attr->ia_gid;
2979                                 mark_inode_dirty(inode);
2980                                 error =
2981                                     journal_end(&th, inode->i_sb, jbegin_count);
2982                         }
2983                 }
2984                 if (!error)
2985                         error = inode_setattr(inode, attr);
2986         }
2987
2988         if (!error && reiserfs_posixacl(inode->i_sb)) {
2989                 if (attr->ia_valid & ATTR_MODE)
2990                         error = reiserfs_acl_chmod(inode);
2991         }
2992
2993       out:
2994         reiserfs_write_unlock(inode->i_sb);
2995         return error;
2996 }
2997
2998 const struct address_space_operations reiserfs_address_space_operations = {
2999         .writepage = reiserfs_writepage,
3000         .readpage = reiserfs_readpage,
3001         .readpages = reiserfs_readpages,
3002         .releasepage = reiserfs_releasepage,
3003         .invalidatepage = reiserfs_invalidatepage,
3004         .sync_page = block_sync_page,
3005         .prepare_write = reiserfs_prepare_write,
3006         .commit_write = reiserfs_commit_write,
3007         .bmap = reiserfs_aop_bmap,
3008         .direct_IO = reiserfs_direct_IO,
3009         .set_page_dirty = reiserfs_set_page_dirty,
3010 };