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