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