patch-2.6.6-vs1.9.0
[linux-2.6.git] / fs / reiserfs / file.c
1 /*
2  * Copyright 2000 by Hans Reiser, licensing governed by reiserfs/README
3  */
4
5
6 #include <linux/time.h>
7 #include <linux/reiserfs_fs.h>
8 #include <linux/smp_lock.h>
9 #include <asm/uaccess.h>
10 #include <linux/pagemap.h>
11 #include <linux/writeback.h>
12 #include <linux/blkdev.h>
13 #include <linux/buffer_head.h>
14
15 /*
16 ** We pack the tails of files on file close, not at the time they are written.
17 ** This implies an unnecessary copy of the tail and an unnecessary indirect item
18 ** insertion/balancing, for files that are written in one write.
19 ** It avoids unnecessary tail packings (balances) for files that are written in
20 ** multiple writes and are small enough to have tails.
21 ** 
22 ** file_release is called by the VFS layer when the file is closed.  If
23 ** this is the last open file descriptor, and the file
24 ** small enough to have a tail, and the tail is currently in an
25 ** unformatted node, the tail is converted back into a direct item.
26 ** 
27 ** We use reiserfs_truncate_file to pack the tail, since it already has
28 ** all the conditions coded.  
29 */
30 static int reiserfs_file_release (struct inode * inode, struct file * filp)
31 {
32
33     struct reiserfs_transaction_handle th ;
34
35     if (!S_ISREG (inode->i_mode))
36         BUG ();
37
38     /* fast out for when nothing needs to be done */
39     if ((atomic_read(&inode->i_count) > 1 ||
40         !(REISERFS_I(inode)->i_flags & i_pack_on_close_mask) || 
41          !tail_has_to_be_packed(inode))       && 
42         REISERFS_I(inode)->i_prealloc_count <= 0) {
43         return 0;
44     }    
45     
46     reiserfs_write_lock(inode->i_sb);
47     down (&inode->i_sem); 
48     journal_begin(&th, inode->i_sb, JOURNAL_PER_BALANCE_CNT * 3) ;
49     reiserfs_update_inode_transaction(inode) ;
50
51 #ifdef REISERFS_PREALLOCATE
52     reiserfs_discard_prealloc (&th, inode);
53 #endif
54     journal_end(&th, inode->i_sb, JOURNAL_PER_BALANCE_CNT * 3) ;
55
56     if (atomic_read(&inode->i_count) <= 1 &&
57         (REISERFS_I(inode)->i_flags & i_pack_on_close_mask) &&
58         tail_has_to_be_packed (inode)) {
59         /* if regular file is released by last holder and it has been
60            appended (we append by unformatted node only) or its direct
61            item(s) had to be converted, then it may have to be
62            indirect2direct converted */
63         reiserfs_truncate_file(inode, 0) ;
64     }
65     up (&inode->i_sem); 
66     reiserfs_write_unlock(inode->i_sb);
67     return 0;
68 }
69
70 static void reiserfs_vfs_truncate_file(struct inode *inode) {
71     reiserfs_truncate_file(inode, 1) ;
72 }
73
74 /* Sync a reiserfs file. */
75
76 /*
77  * FIXME: sync_mapping_buffers() never has anything to sync.  Can
78  * be removed...
79  */
80
81 static int reiserfs_sync_file(
82                               struct file   * p_s_filp,
83                               struct dentry * p_s_dentry,
84                               int datasync
85                               ) {
86   struct inode * p_s_inode = p_s_dentry->d_inode;
87   int n_err;
88
89   reiserfs_write_lock(p_s_inode->i_sb);
90
91   if (!S_ISREG(p_s_inode->i_mode))
92       BUG ();
93
94   n_err = sync_mapping_buffers(p_s_inode->i_mapping) ;
95   reiserfs_commit_for_inode(p_s_inode) ;
96   reiserfs_write_unlock(p_s_inode->i_sb);
97   return ( n_err < 0 ) ? -EIO : 0;
98 }
99
100 int reiserfs_setattr_flags(struct inode *inode, unsigned int flags)
101 {
102         unsigned int oldflags, newflags;
103
104         oldflags = REISERFS_I(inode)->i_flags;
105         newflags = oldflags & ~(REISERFS_IMMUTABLE_FL |
106                 REISERFS_IUNLINK_FL | REISERFS_BARRIER_FL);
107         if (flags & ATTR_FLAG_IMMUTABLE)
108                 newflags |= REISERFS_IMMUTABLE_FL;
109         if (flags & ATTR_FLAG_IUNLINK)
110                 newflags |= REISERFS_IUNLINK_FL;
111         if (flags & ATTR_FLAG_BARRIER)
112                 newflags |= REISERFS_BARRIER_FL;
113
114         if (oldflags ^ newflags) {
115                 REISERFS_I(inode)->i_flags = newflags;
116                 inode->i_ctime = CURRENT_TIME;
117         }
118         return 0;
119 }
120
121 int reiserfs_setattr(struct dentry *dentry, struct iattr *attr) {
122     struct inode *inode = dentry->d_inode ;
123     int error ;
124
125     reiserfs_write_lock(inode->i_sb);
126     if (S_ISDIR(inode->i_mode))
127         goto is_dir;
128
129     if (attr->ia_valid & ATTR_SIZE) {
130         /* version 2 items will be caught by the s_maxbytes check
131         ** done for us in vmtruncate
132         */
133         if (get_inode_item_key_version(inode) == KEY_FORMAT_3_5 &&
134             attr->ia_size > MAX_NON_LFS) {
135             error = -EFBIG ;
136             goto out;
137         }
138         /* fill in hole pointers in the expanding truncate case. */
139         if (attr->ia_size > inode->i_size) {
140             error = generic_cont_expand(inode, attr->ia_size) ;
141             if (REISERFS_I(inode)->i_prealloc_count > 0) {
142                 struct reiserfs_transaction_handle th ;
143                 /* we're changing at most 2 bitmaps, inode + super */
144                 journal_begin(&th, inode->i_sb, 4) ;
145                 reiserfs_discard_prealloc (&th, inode);
146                 journal_end(&th, inode->i_sb, 4) ;
147             }
148             if (error)
149                 goto out;
150         }
151     }
152
153     if ((((attr->ia_valid & ATTR_UID) && (attr->ia_uid & ~0xffff)) ||
154          ((attr->ia_valid & ATTR_GID) && (attr->ia_gid & ~0xffff))) &&
155         (get_inode_sd_version (inode) == STAT_DATA_V1)) {
156                 /* stat data of format v3.5 has 16 bit uid and gid */
157             error = -EINVAL;
158             goto out;   
159         }
160
161 is_dir:
162     error = inode_change_ok(inode, attr) ;
163
164     if (!error && attr->ia_valid & ATTR_ATTR_FLAG)
165         reiserfs_setattr_flags(inode, attr->ia_attr_flags);
166
167     if (!error)
168         inode_setattr(inode, attr) ;
169
170 out:
171     reiserfs_write_unlock(inode->i_sb);
172     return error ;
173 }
174
175 /* I really do not want to play with memory shortage right now, so
176    to simplify the code, we are not going to write more than this much pages at
177    a time. This still should considerably improve performance compared to 4k
178    at a time case. This is 32 pages of 4k size. */
179 #define REISERFS_WRITE_PAGES_AT_A_TIME (128 * 1024) / PAGE_CACHE_SIZE
180
181 /* Allocates blocks for a file to fulfil write request.
182    Maps all unmapped but prepared pages from the list.
183    Updates metadata with newly allocated blocknumbers as needed */
184 int reiserfs_allocate_blocks_for_region(
185                                 struct reiserfs_transaction_handle *th,
186                                 struct inode *inode, /* Inode we work with */
187                                 loff_t pos, /* Writing position */
188                                 int num_pages, /* number of pages write going
189                                                   to touch */
190                                 int write_bytes, /* amount of bytes to write */
191                                 struct page **prepared_pages, /* array of
192                                                                  prepared pages
193                                                                */
194                                 int blocks_to_allocate /* Amount of blocks we
195                                                           need to allocate to
196                                                           fit the data into file
197                                                          */
198                                 )
199 {
200     struct cpu_key key; // cpu key of item that we are going to deal with
201     struct item_head *ih; // pointer to item head that we are going to deal with
202     struct buffer_head *bh; // Buffer head that contains items that we are going to deal with
203     __u32 * item; // pointer to item we are going to deal with
204     INITIALIZE_PATH(path); // path to item, that we are going to deal with.
205     b_blocknr_t allocated_blocks[blocks_to_allocate]; // Pointer to a place where allocated blocknumbers would be stored. Right now statically allocated, later that will change.
206     reiserfs_blocknr_hint_t hint; // hint structure for block allocator.
207     size_t res; // return value of various functions that we call.
208     int curr_block; // current block used to keep track of unmapped blocks.
209     int i; // loop counter
210     int itempos; // position in item
211     unsigned int from = (pos & (PAGE_CACHE_SIZE - 1)); // writing position in
212                                                        // first page
213     unsigned int to = ((pos + write_bytes - 1) & (PAGE_CACHE_SIZE - 1)) + 1; /* last modified byte offset in last page */
214     __u64 hole_size ; // amount of blocks for a file hole, if it needed to be created.
215     int modifying_this_item = 0; // Flag for items traversal code to keep track
216                                  // of the fact that we already prepared
217                                  // current block for journal
218
219
220     RFALSE(!blocks_to_allocate, "green-9004: tried to allocate zero blocks?");
221
222     /* First we compose a key to point at the writing position, we want to do
223        that outside of any locking region. */
224     make_cpu_key (&key, inode, pos+1, TYPE_ANY, 3/*key length*/);
225
226     /* If we came here, it means we absolutely need to open a transaction,
227        since we need to allocate some blocks */
228     reiserfs_write_lock(inode->i_sb); // Journaling stuff and we need that.
229     journal_begin(th, inode->i_sb, JOURNAL_PER_BALANCE_CNT * 3 + 1); // Wish I know if this number enough
230     reiserfs_update_inode_transaction(inode) ;
231
232     /* Look for the in-tree position of our write, need path for block allocator */
233     res = search_for_position_by_key(inode->i_sb, &key, &path);
234     if ( res == IO_ERROR ) {
235         res = -EIO;
236         goto error_exit;
237     }
238    
239     /* Allocate blocks */
240     /* First fill in "hint" structure for block allocator */
241     hint.th = th; // transaction handle.
242     hint.path = &path; // Path, so that block allocator can determine packing locality or whatever it needs to determine.
243     hint.inode = inode; // Inode is needed by block allocator too.
244     hint.search_start = 0; // We have no hint on where to search free blocks for block allocator.
245     hint.key = key.on_disk_key; // on disk key of file.
246     hint.block = inode->i_blocks>>(inode->i_sb->s_blocksize_bits-9); // Number of disk blocks this file occupies already.
247     hint.formatted_node = 0; // We are allocating blocks for unformatted node.
248
249     /* only preallocate if this is a small write */
250     if (blocks_to_allocate <
251         REISERFS_SB(inode->i_sb)->s_alloc_options.preallocsize)
252         hint.preallocate = 1;
253     else
254         hint.preallocate = 0;
255
256     /* Call block allocator to allocate blocks */
257     res = reiserfs_allocate_blocknrs(&hint, allocated_blocks, blocks_to_allocate, blocks_to_allocate);
258     if ( res != CARRY_ON ) {
259         if ( res == NO_DISK_SPACE ) {
260             /* We flush the transaction in case of no space. This way some
261                blocks might become free */
262             SB_JOURNAL(inode->i_sb)->j_must_wait = 1;
263             restart_transaction(th, inode, &path);
264
265             /* We might have scheduled, so search again */
266             res = search_for_position_by_key(inode->i_sb, &key, &path);
267             if ( res == IO_ERROR ) {
268                 res = -EIO;
269                 goto error_exit;
270             }
271
272             /* update changed info for hint structure. */
273             res = reiserfs_allocate_blocknrs(&hint, allocated_blocks, blocks_to_allocate, blocks_to_allocate);
274             if ( res != CARRY_ON ) {
275                 res = -ENOSPC; 
276                 pathrelse(&path);
277                 goto error_exit;
278             }
279         } else {
280             res = -ENOSPC;
281             pathrelse(&path);
282             goto error_exit;
283         }
284     }
285
286 #ifdef __BIG_ENDIAN
287         // Too bad, I have not found any way to convert a given region from
288         // cpu format to little endian format
289     {
290         int i;
291         for ( i = 0; i < blocks_to_allocate ; i++)
292             allocated_blocks[i]=cpu_to_le32(allocated_blocks[i]);
293     }
294 #endif
295
296     /* Blocks allocating well might have scheduled and tree might have changed,
297        let's search the tree again */
298     /* find where in the tree our write should go */
299     res = search_for_position_by_key(inode->i_sb, &key, &path);
300     if ( res == IO_ERROR ) {
301         res = -EIO;
302         goto error_exit_free_blocks;
303     }
304
305     bh = get_last_bh( &path ); // Get a bufferhead for last element in path.
306     ih = get_ih( &path );      // Get a pointer to last item head in path.
307     item = get_item( &path );  // Get a pointer to last item in path
308
309     /* Let's see what we have found */
310     if ( res != POSITION_FOUND ) { /* position not found, this means that we
311                                       might need to append file with holes
312                                       first */
313         // Since we are writing past the file's end, we need to find out if
314         // there is a hole that needs to be inserted before our writing
315         // position, and how many blocks it is going to cover (we need to
316         //  populate pointers to file blocks representing the hole with zeros)
317
318         {
319             int item_offset = 1;
320             /*
321              * if ih is stat data, its offset is 0 and we don't want to
322              * add 1 to pos in the hole_size calculation
323              */
324             if (is_statdata_le_ih(ih))
325                 item_offset = 0;
326             hole_size = (pos + item_offset -
327                     (le_key_k_offset( get_inode_item_key_version(inode),
328                     &(ih->ih_key)) +
329                     op_bytes_number(ih, inode->i_sb->s_blocksize))) >>
330                     inode->i_sb->s_blocksize_bits;
331         }
332
333         if ( hole_size > 0 ) {
334             int to_paste = min_t(__u64, hole_size, MAX_ITEM_LEN(inode->i_sb->s_blocksize)/UNFM_P_SIZE ); // How much data to insert first time.
335             /* area filled with zeroes, to supply as list of zero blocknumbers
336                We allocate it outside of loop just in case loop would spin for
337                several iterations. */
338             char *zeros = kmalloc(to_paste*UNFM_P_SIZE, GFP_ATOMIC); // We cannot insert more than MAX_ITEM_LEN bytes anyway.
339             if ( !zeros ) {
340                 res = -ENOMEM;
341                 goto error_exit_free_blocks;
342             }
343             memset ( zeros, 0, to_paste*UNFM_P_SIZE);
344             do {
345                 to_paste = min_t(__u64, hole_size, MAX_ITEM_LEN(inode->i_sb->s_blocksize)/UNFM_P_SIZE );
346                 if ( is_indirect_le_ih(ih) ) {
347                     /* Ok, there is existing indirect item already. Need to append it */
348                     /* Calculate position past inserted item */
349                     make_cpu_key( &key, inode, le_key_k_offset( get_inode_item_key_version(inode), &(ih->ih_key)) + op_bytes_number(ih, inode->i_sb->s_blocksize), TYPE_INDIRECT, 3);
350                     res = reiserfs_paste_into_item( th, &path, &key, (char *)zeros, UNFM_P_SIZE*to_paste);
351                     if ( res ) {
352                         kfree(zeros);
353                         goto error_exit_free_blocks;
354                     }
355                 } else if ( is_statdata_le_ih(ih) ) {
356                     /* No existing item, create it */
357                     /* item head for new item */
358                     struct item_head ins_ih;
359
360                     /* create a key for our new item */
361                     make_cpu_key( &key, inode, 1, TYPE_INDIRECT, 3);
362
363                     /* Create new item head for our new item */
364                     make_le_item_head (&ins_ih, &key, key.version, 1,
365                                        TYPE_INDIRECT, to_paste*UNFM_P_SIZE,
366                                        0 /* free space */);
367
368                     /* Find where such item should live in the tree */
369                     res = search_item (inode->i_sb, &key, &path);
370                     if ( res != ITEM_NOT_FOUND ) {
371                         /* item should not exist, otherwise we have error */
372                         if ( res != -ENOSPC ) {
373                             reiserfs_warning ("green-9008: search_by_key (%K) returned %d\n",
374                                                &key, res);
375                         }
376                         res = -EIO;
377                         kfree(zeros);
378                         goto error_exit_free_blocks;
379                     }
380                     res = reiserfs_insert_item( th, &path, &key, &ins_ih, (char *)zeros);
381                 } else {
382                     reiserfs_panic(inode->i_sb, "green-9011: Unexpected key type %K\n", &key);
383                 }
384                 if ( res ) {
385                     kfree(zeros);
386                     goto error_exit_free_blocks;
387                 }
388                 /* Now we want to check if transaction is too full, and if it is
389                    we restart it. This will also free the path. */
390                 if (journal_transaction_should_end(th, th->t_blocks_allocated))
391                     restart_transaction(th, inode, &path);
392
393                 /* Well, need to recalculate path and stuff */
394                 set_cpu_key_k_offset( &key, cpu_key_k_offset(&key) + (to_paste << inode->i_blkbits));
395                 res = search_for_position_by_key(inode->i_sb, &key, &path);
396                 if ( res == IO_ERROR ) {
397                     res = -EIO;
398                     kfree(zeros);
399                     goto error_exit_free_blocks;
400                 }
401                 bh=get_last_bh(&path);
402                 ih=get_ih(&path);
403                 item = get_item(&path);
404                 hole_size -= to_paste;
405             } while ( hole_size );
406             kfree(zeros);
407         }
408     }
409
410     // Go through existing indirect items first
411     // replace all zeroes with blocknumbers from list
412     // Note that if no corresponding item was found, by previous search,
413     // it means there are no existing in-tree representation for file area
414     // we are going to overwrite, so there is nothing to scan through for holes.
415     for ( curr_block = 0, itempos = path.pos_in_item ; curr_block < blocks_to_allocate && res == POSITION_FOUND ; ) {
416 retry:
417         if ( itempos >= ih_item_len(ih)/UNFM_P_SIZE ) {
418             /* We run out of data in this indirect item, let's look for another
419                one. */
420             /* First if we are already modifying current item, log it */
421             if ( modifying_this_item ) {
422                 journal_mark_dirty (th, inode->i_sb, bh);
423                 modifying_this_item = 0;
424             }
425             /* Then set the key to look for a new indirect item (offset of old
426                item is added to old item length */
427             set_cpu_key_k_offset( &key, le_key_k_offset( get_inode_item_key_version(inode), &(ih->ih_key)) + op_bytes_number(ih, inode->i_sb->s_blocksize));
428             /* Search ofor position of new key in the tree. */
429             res = search_for_position_by_key(inode->i_sb, &key, &path);
430             if ( res == IO_ERROR) {
431                 res = -EIO;
432                 goto error_exit_free_blocks;
433             }
434             bh=get_last_bh(&path);
435             ih=get_ih(&path);
436             item = get_item(&path);
437             itempos = path.pos_in_item;
438             continue; // loop to check all kinds of conditions and so on.
439         }
440         /* Ok, we have correct position in item now, so let's see if it is
441            representing file hole (blocknumber is zero) and fill it if needed */
442         if ( !item[itempos] ) {
443             /* Ok, a hole. Now we need to check if we already prepared this
444                block to be journaled */
445             while ( !modifying_this_item ) { // loop until succeed
446                 /* Well, this item is not journaled yet, so we must prepare
447                    it for journal first, before we can change it */
448                 struct item_head tmp_ih; // We copy item head of found item,
449                                          // here to detect if fs changed under
450                                          // us while we were preparing for
451                                          // journal.
452                 int fs_gen; // We store fs generation here to find if someone
453                             // changes fs under our feet
454
455                 copy_item_head (&tmp_ih, ih); // Remember itemhead
456                 fs_gen = get_generation (inode->i_sb); // remember fs generation
457                 reiserfs_prepare_for_journal(inode->i_sb, bh, 1); // Prepare a buffer within which indirect item is stored for changing.
458                 if (fs_changed (fs_gen, inode->i_sb) && item_moved (&tmp_ih, &path)) {
459                     // Sigh, fs was changed under us, we need to look for new
460                     // location of item we are working with
461
462                     /* unmark prepaerd area as journaled and search for it's
463                        new position */
464                     reiserfs_restore_prepared_buffer(inode->i_sb, bh);
465                     res = search_for_position_by_key(inode->i_sb, &key, &path);
466                     if ( res == IO_ERROR) {
467                         res = -EIO;
468                         goto error_exit_free_blocks;
469                     }
470                     bh=get_last_bh(&path);
471                     ih=get_ih(&path);
472                     item = get_item(&path);
473                     itempos = path.pos_in_item;
474                     goto retry;
475                 }
476                 modifying_this_item = 1;
477             }
478             item[itempos] = allocated_blocks[curr_block]; // Assign new block
479             curr_block++;
480         }
481         itempos++;
482     }
483
484     if ( modifying_this_item ) { // We need to log last-accessed block, if it
485                                  // was modified, but not logged yet.
486         journal_mark_dirty (th, inode->i_sb, bh);
487     }
488
489     if ( curr_block < blocks_to_allocate ) {
490         // Oh, well need to append to indirect item, or to create indirect item
491         // if there weren't any
492         if ( is_indirect_le_ih(ih) ) {
493             // Existing indirect item - append. First calculate key for append
494             // position. We do not need to recalculate path as it should
495             // already point to correct place.
496             make_cpu_key( &key, inode, le_key_k_offset( get_inode_item_key_version(inode), &(ih->ih_key)) + op_bytes_number(ih, inode->i_sb->s_blocksize), TYPE_INDIRECT, 3);
497             res = reiserfs_paste_into_item( th, &path, &key, (char *)(allocated_blocks+curr_block), UNFM_P_SIZE*(blocks_to_allocate-curr_block));
498             if ( res ) {
499                 goto error_exit_free_blocks;
500             }
501         } else if (is_statdata_le_ih(ih) ) {
502             // Last found item was statdata. That means we need to create indirect item.
503             struct item_head ins_ih; /* itemhead for new item */
504
505             /* create a key for our new item */
506             make_cpu_key( &key, inode, 1, TYPE_INDIRECT, 3); // Position one,
507                                                             // because that's
508                                                             // where first
509                                                             // indirect item
510                                                             // begins
511             /* Create new item head for our new item */
512             make_le_item_head (&ins_ih, &key, key.version, 1, TYPE_INDIRECT,
513                                (blocks_to_allocate-curr_block)*UNFM_P_SIZE,
514                                0 /* free space */);
515             /* Find where such item should live in the tree */
516             res = search_item (inode->i_sb, &key, &path);
517             if ( res != ITEM_NOT_FOUND ) {
518                 /* Well, if we have found such item already, or some error
519                    occured, we need to warn user and return error */
520                 if ( res != -ENOSPC ) {
521                     reiserfs_warning ("green-9009: search_by_key (%K) returned %d\n",
522                                       &key, res);
523                 }
524                 res = -EIO;
525                 goto error_exit_free_blocks;
526             }
527             /* Insert item into the tree with the data as its body */
528             res = reiserfs_insert_item( th, &path, &key, &ins_ih, (char *)(allocated_blocks+curr_block));
529         } else {
530             reiserfs_panic(inode->i_sb, "green-9010: unexpected item type for key %K\n",&key);
531         }
532     }
533
534     // the caller is responsible for closing the transaction
535     // unless we return an error, they are also responsible for logging
536     // the inode.
537     //
538     inode->i_blocks += blocks_to_allocate << (inode->i_blkbits - 9);
539     pathrelse(&path);
540     reiserfs_write_unlock(inode->i_sb);
541
542     // go through all the pages/buffers and map the buffers to newly allocated
543     // blocks (so that system knows where to write these pages later).
544     curr_block = 0;
545     for ( i = 0; i < num_pages ; i++ ) {
546         struct page *page=prepared_pages[i]; //current page
547         struct buffer_head *head = page_buffers(page);// first buffer for a page
548         int block_start, block_end; // in-page offsets for buffers.
549
550         if (!page_buffers(page))
551             reiserfs_panic(inode->i_sb, "green-9005: No buffers for prepared page???");
552
553         /* For each buffer in page */
554         for(bh = head, block_start = 0; bh != head || !block_start;
555             block_start=block_end, bh = bh->b_this_page) {
556             if (!bh)
557                 reiserfs_panic(inode->i_sb, "green-9006: Allocated but absent buffer for a page?");
558             block_end = block_start+inode->i_sb->s_blocksize;
559             if (i == 0 && block_end <= from )
560                 /* if this buffer is before requested data to map, skip it */
561                 continue;
562             if (i == num_pages - 1 && block_start >= to)
563                 /* If this buffer is after requested data to map, abort
564                    processing of current page */
565                 break;
566
567             if ( !buffer_mapped(bh) ) { // Ok, unmapped buffer, need to map it
568                 map_bh( bh, inode->i_sb, le32_to_cpu(allocated_blocks[curr_block]));
569                 curr_block++;
570                 set_buffer_new(bh);
571             }
572         }
573     }
574
575     RFALSE( curr_block > blocks_to_allocate, "green-9007: Used too many blocks? weird");
576
577     return 0;
578
579 // Need to deal with transaction here.
580 error_exit_free_blocks:
581     pathrelse(&path);
582     // free blocks
583     for( i = 0; i < blocks_to_allocate; i++ )
584         reiserfs_free_block(th, le32_to_cpu(allocated_blocks[i]));
585
586 error_exit:
587     reiserfs_update_sd(th, inode); // update any changes we made to blk count
588     journal_end(th, inode->i_sb, JOURNAL_PER_BALANCE_CNT * 3 + 1);
589     reiserfs_write_unlock(inode->i_sb);
590
591     return res;
592 }
593
594 /* Unlock pages prepared by reiserfs_prepare_file_region_for_write */
595 void reiserfs_unprepare_pages(struct page **prepared_pages, /* list of locked pages */
596                               int num_pages /* amount of pages */) {
597     int i; // loop counter
598
599     for (i=0; i < num_pages ; i++) {
600         struct page *page = prepared_pages[i];
601
602         try_to_free_buffers(page);
603         unlock_page(page);
604         page_cache_release(page);
605     }
606 }
607
608 /* This function will copy data from userspace to specified pages within
609    supplied byte range */
610 int reiserfs_copy_from_user_to_file_region(
611                                 loff_t pos, /* In-file position */
612                                 int num_pages, /* Number of pages affected */
613                                 int write_bytes, /* Amount of bytes to write */
614                                 struct page **prepared_pages, /* pointer to 
615                                                                  array to
616                                                                  prepared pages
617                                                                 */
618                                 const char *buf /* Pointer to user-supplied
619                                                    data*/
620                                 )
621 {
622     long page_fault=0; // status of copy_from_user.
623     int i; // loop counter.
624     int offset; // offset in page
625
626     for ( i = 0, offset = (pos & (PAGE_CACHE_SIZE-1)); i < num_pages ; i++,offset=0) {
627         int count = min_t(int,PAGE_CACHE_SIZE-offset,write_bytes); // How much of bytes to write to this page
628         struct page *page=prepared_pages[i]; // Current page we process.
629
630         fault_in_pages_readable( buf, count);
631
632         /* Copy data from userspace to the current page */
633         kmap(page);
634         page_fault = __copy_from_user(page_address(page)+offset, buf, count); // Copy the data.
635         /* Flush processor's dcache for this page */
636         flush_dcache_page(page);
637         kunmap(page);
638         buf+=count;
639         write_bytes-=count;
640
641         if (page_fault)
642             break; // Was there a fault? abort.
643     }
644
645     return page_fault?-EFAULT:0;
646 }
647
648 /* taken fs/buffer.c:__block_commit_write */
649 int reiserfs_commit_page(struct inode *inode, struct page *page,
650                 unsigned from, unsigned to)
651 {
652     unsigned block_start, block_end;
653     int partial = 0;
654     unsigned blocksize;
655     struct buffer_head *bh, *head;
656     unsigned long i_size_index = inode->i_size >> PAGE_CACHE_SHIFT;
657     int new;
658
659     blocksize = 1 << inode->i_blkbits;
660
661     for(bh = head = page_buffers(page), block_start = 0;
662         bh != head || !block_start;
663         block_start=block_end, bh = bh->b_this_page)
664     {
665
666         new = buffer_new(bh);
667         clear_buffer_new(bh);
668         block_end = block_start + blocksize;
669         if (block_end <= from || block_start >= to) {
670             if (!buffer_uptodate(bh))
671                     partial = 1;
672         } else {
673             set_buffer_uptodate(bh);
674             if (!buffer_dirty(bh)) {
675                 mark_buffer_dirty(bh);
676                 /* do data=ordered on any page past the end
677                  * of file and any buffer marked BH_New.
678                  */
679                 if (reiserfs_data_ordered(inode->i_sb) &&
680                     (new || page->index >= i_size_index)) {
681                     reiserfs_add_ordered_list(inode, bh);
682                 }
683             }
684         }
685     }
686
687     /*
688      * If this is a partial write which happened to make all buffers
689      * uptodate then we can optimize away a bogus readpage() for
690      * the next read(). Here we 'discover' whether the page went
691      * uptodate as a result of this (potentially partial) write.
692      */
693     if (!partial)
694         SetPageUptodate(page);
695     return 0;
696 }
697
698
699 /* Submit pages for write. This was separated from actual file copying
700    because we might want to allocate block numbers in-between.
701    This function assumes that caller will adjust file size to correct value. */
702 int reiserfs_submit_file_region_for_write(
703                                 struct reiserfs_transaction_handle *th,
704                                 struct inode *inode,
705                                 loff_t pos, /* Writing position offset */
706                                 int num_pages, /* Number of pages to write */
707                                 int write_bytes, /* number of bytes to write */
708                                 struct page **prepared_pages /* list of pages */
709                                 )
710 {
711     int status; // return status of block_commit_write.
712     int retval = 0; // Return value we are going to return.
713     int i; // loop counter
714     int offset; // Writing offset in page.
715     int orig_write_bytes = write_bytes;
716     int sd_update = 0;
717
718     for ( i = 0, offset = (pos & (PAGE_CACHE_SIZE-1)); i < num_pages ; i++,offset=0) {
719         int count = min_t(int,PAGE_CACHE_SIZE-offset,write_bytes); // How much of bytes to write to this page
720         struct page *page=prepared_pages[i]; // Current page we process.
721
722         status = reiserfs_commit_page(inode, page, offset, offset+count);
723         if ( status )
724             retval = status; // To not overcomplicate matters We are going to
725                              // submit all the pages even if there was error.
726                              // we only remember error status to report it on
727                              // exit.
728         write_bytes-=count;
729         SetPageReferenced(page);
730         unlock_page(page); // We unlock the page as it was locked by earlier call
731                           // to grab_cache_page
732         page_cache_release(page);
733     }
734     /* now that we've gotten all the ordered buffers marked dirty,
735      * we can safely update i_size and close any running transaction
736      */
737     if ( pos + orig_write_bytes > inode->i_size) {
738         inode->i_size = pos + orig_write_bytes; // Set new size
739         /* If the file have grown so much that tail packing is no
740          * longer possible, reset "need to pack" flag */
741         if ( (have_large_tails (inode->i_sb) &&
742               inode->i_size > i_block_size (inode)*4) ||
743              (have_small_tails (inode->i_sb) &&
744              inode->i_size > i_block_size(inode)) )
745             REISERFS_I(inode)->i_flags &= ~i_pack_on_close_mask ;
746         else if ( (have_large_tails (inode->i_sb) &&
747                   inode->i_size < i_block_size (inode)*4) ||
748                   (have_small_tails (inode->i_sb) &&
749                   inode->i_size < i_block_size(inode)) )
750             REISERFS_I(inode)->i_flags |= i_pack_on_close_mask ;
751
752         if (th->t_trans_id) {
753             reiserfs_write_lock(inode->i_sb);
754             reiserfs_update_sd(th, inode); // And update on-disk metadata
755             reiserfs_write_unlock(inode->i_sb);
756         } else
757             inode->i_sb->s_op->dirty_inode(inode);
758
759         sd_update = 1;
760     }
761     if (th->t_trans_id) {
762         reiserfs_write_lock(inode->i_sb);
763         if (!sd_update)
764             reiserfs_update_sd(th, inode);
765         journal_end(th, th->t_super, th->t_blocks_allocated);
766         reiserfs_write_unlock(inode->i_sb);
767     }
768     th->t_trans_id = 0;
769     return retval;
770 }
771
772 /* Look if passed writing region is going to touch file's tail
773    (if it is present). And if it is, convert the tail to unformatted node */
774 int reiserfs_check_for_tail_and_convert( struct inode *inode, /* inode to deal with */
775                                          loff_t pos, /* Writing position */
776                                          int write_bytes /* amount of bytes to write */
777                                         )
778 {
779     INITIALIZE_PATH(path); // needed for search_for_position
780     struct cpu_key key; // Key that would represent last touched writing byte.
781     struct item_head *ih; // item header of found block;
782     int res; // Return value of various functions we call.
783     int cont_expand_offset; // We will put offset for generic_cont_expand here
784                             // This can be int just because tails are created
785                             // only for small files.
786  
787 /* this embodies a dependency on a particular tail policy */
788     if ( inode->i_size >= inode->i_sb->s_blocksize*4 ) {
789         /* such a big files do not have tails, so we won't bother ourselves
790            to look for tails, simply return */
791         return 0;
792     }
793
794     reiserfs_write_lock(inode->i_sb);
795     /* find the item containing the last byte to be written, or if
796      * writing past the end of the file then the last item of the
797      * file (and then we check its type). */
798     make_cpu_key (&key, inode, pos+write_bytes+1, TYPE_ANY, 3/*key length*/);
799     res = search_for_position_by_key(inode->i_sb, &key, &path);
800     if ( res == IO_ERROR ) {
801         reiserfs_write_unlock(inode->i_sb);
802         return -EIO;
803     }
804     ih = get_ih(&path);
805     res = 0;
806     if ( is_direct_le_ih(ih) ) {
807         /* Ok, closest item is file tail (tails are stored in "direct"
808          * items), so we need to unpack it. */
809         /* To not overcomplicate matters, we just call generic_cont_expand
810            which will in turn call other stuff and finally will boil down to
811             reiserfs_get_block() that would do necessary conversion. */
812         cont_expand_offset = le_key_k_offset(get_inode_item_key_version(inode), &(ih->ih_key));
813         pathrelse(&path);
814         res = generic_cont_expand( inode, cont_expand_offset);
815     } else
816         pathrelse(&path);
817
818     reiserfs_write_unlock(inode->i_sb);
819     return res;
820 }
821
822 /* This function locks pages starting from @pos for @inode.
823    @num_pages pages are locked and stored in
824    @prepared_pages array. Also buffers are allocated for these pages.
825    First and last page of the region is read if it is overwritten only
826    partially. If last page did not exist before write (file hole or file
827    append), it is zeroed, then. 
828    Returns number of unallocated blocks that should be allocated to cover
829    new file data.*/
830 int reiserfs_prepare_file_region_for_write(
831                                 struct inode *inode /* Inode of the file */,
832                                 loff_t pos, /* position in the file */
833                                 int num_pages, /* number of pages to
834                                                   prepare */
835                                 int write_bytes, /* Amount of bytes to be
836                                                     overwritten from
837                                                     @pos */
838                                 struct page **prepared_pages /* pointer to array
839                                                                where to store
840                                                                prepared pages */
841                                            )
842 {
843     int res=0; // Return values of different functions we call.
844     unsigned long index = pos >> PAGE_CACHE_SHIFT; // Offset in file in pages.
845     int from = (pos & (PAGE_CACHE_SIZE - 1)); // Writing offset in first page
846     int to = ((pos + write_bytes - 1) & (PAGE_CACHE_SIZE - 1)) + 1;
847                                          /* offset of last modified byte in last
848                                             page */
849     struct address_space *mapping = inode->i_mapping; // Pages are mapped here.
850     int i; // Simple counter
851     int blocks = 0; /* Return value (blocks that should be allocated) */
852     struct buffer_head *bh, *head; // Current bufferhead and first bufferhead
853                                    // of a page.
854     unsigned block_start, block_end; // Starting and ending offsets of current
855                                      // buffer in the page.
856     struct buffer_head *wait[2], **wait_bh=wait; // Buffers for page, if
857                                                  // Page appeared to be not up
858                                                  // to date. Note how we have
859                                                  // at most 2 buffers, this is
860                                                  // because we at most may
861                                                  // partially overwrite two
862                                                  // buffers for one page. One at                                                 // the beginning of write area
863                                                  // and one at the end.
864                                                  // Everything inthe middle gets                                                 // overwritten totally.
865
866     struct cpu_key key; // cpu key of item that we are going to deal with
867     struct item_head *ih = NULL; // pointer to item head that we are going to deal with
868     struct buffer_head *itembuf=NULL; // Buffer head that contains items that we are going to deal with
869     INITIALIZE_PATH(path); // path to item, that we are going to deal with.
870     __u32 * item=0; // pointer to item we are going to deal with
871     int item_pos=-1; /* Position in indirect item */
872
873
874     if ( num_pages < 1 ) {
875         reiserfs_warning("green-9001: reiserfs_prepare_file_region_for_write called with zero number of pages to process\n");
876         return -EFAULT;
877     }
878
879     /* We have 2 loops for pages. In first loop we grab and lock the pages, so
880        that nobody would touch these until we release the pages. Then
881        we'd start to deal with mapping buffers to blocks. */
882     for ( i = 0; i < num_pages; i++) {
883         prepared_pages[i] = grab_cache_page(mapping, index + i); // locks the page
884         if ( !prepared_pages[i]) {
885             res = -ENOMEM;
886             goto failed_page_grabbing;
887         }
888         if (!page_has_buffers(prepared_pages[i]))
889             create_empty_buffers(prepared_pages[i], inode->i_sb->s_blocksize, 0);
890     }
891
892     /* Let's count amount of blocks for a case where all the blocks
893        overwritten are new (we will substract already allocated blocks later)*/
894     if ( num_pages > 2 )
895         /* These are full-overwritten pages so we count all the blocks in
896            these pages are counted as needed to be allocated */
897         blocks = (num_pages - 2) << (PAGE_CACHE_SHIFT - inode->i_blkbits);
898
899     /* count blocks needed for first page (possibly partially written) */
900     blocks += ((PAGE_CACHE_SIZE - from) >> inode->i_blkbits) +
901            !!(from & (inode->i_sb->s_blocksize-1)); /* roundup */
902
903     /* Now we account for last page. If last page == first page (we
904        overwrite only one page), we substract all the blocks past the
905        last writing position in a page out of already calculated number
906        of blocks */
907     blocks += ((num_pages > 1) << (PAGE_CACHE_SHIFT-inode->i_blkbits)) -
908            ((PAGE_CACHE_SIZE - to) >> inode->i_blkbits);
909            /* Note how we do not roundup here since partial blocks still
910                    should be allocated */
911
912     /* Now if all the write area lies past the file end, no point in
913        maping blocks, since there is none, so we just zero out remaining
914        parts of first and last pages in write area (if needed) */
915     if ( (pos & ~((loff_t)PAGE_CACHE_SIZE - 1)) > inode->i_size ) {
916         if ( from != 0 ) {/* First page needs to be partially zeroed */
917             char *kaddr = kmap_atomic(prepared_pages[0], KM_USER0);
918             memset(kaddr, 0, from);
919             kunmap_atomic( kaddr, KM_USER0);
920         }
921         if ( to != PAGE_CACHE_SIZE ) { /* Last page needs to be partially zeroed */
922             char *kaddr = kmap_atomic(prepared_pages[num_pages-1], KM_USER0);
923             memset(kaddr+to, 0, PAGE_CACHE_SIZE - to);
924             kunmap_atomic( kaddr, KM_USER0);
925         }
926
927         /* Since all blocks are new - use already calculated value */
928         return blocks;
929     }
930
931     /* Well, since we write somewhere into the middle of a file, there is
932        possibility we are writing over some already allocated blocks, so
933        let's map these blocks and substract number of such blocks out of blocks
934        we need to allocate (calculated above) */
935     /* Mask write position to start on blocksize, we do it out of the
936        loop for performance reasons */
937     pos &= ~((loff_t) inode->i_sb->s_blocksize - 1);
938     /* Set cpu key to the starting position in a file (on left block boundary)*/
939     make_cpu_key (&key, inode, 1 + ((pos) & ~((loff_t) inode->i_sb->s_blocksize - 1)), TYPE_ANY, 3/*key length*/);
940
941     reiserfs_write_lock(inode->i_sb); // We need that for at least search_by_key()
942     for ( i = 0; i < num_pages ; i++ ) { 
943
944         head = page_buffers(prepared_pages[i]);
945         /* For each buffer in the page */
946         for(bh = head, block_start = 0; bh != head || !block_start;
947             block_start=block_end, bh = bh->b_this_page) {
948                 if (!bh)
949                     reiserfs_panic(inode->i_sb, "green-9002: Allocated but absent buffer for a page?");
950                 /* Find where this buffer ends */
951                 block_end = block_start+inode->i_sb->s_blocksize;
952                 if (i == 0 && block_end <= from )
953                     /* if this buffer is before requested data to map, skip it*/
954                     continue;
955
956                 if (i == num_pages - 1 && block_start >= to) {
957                     /* If this buffer is after requested data to map, abort
958                        processing of current page */
959                     break;
960                 }
961
962                 if ( buffer_mapped(bh) && bh->b_blocknr !=0 ) {
963                     /* This is optimisation for a case where buffer is mapped
964                        and have blocknumber assigned. In case significant amount
965                        of such buffers are present, we may avoid some amount
966                        of search_by_key calls.
967                        Probably it would be possible to move parts of this code
968                        out of BKL, but I afraid that would overcomplicate code
969                        without any noticeable benefit.
970                     */
971                     item_pos++;
972                     /* Update the key */
973                     set_cpu_key_k_offset( &key, cpu_key_k_offset(&key) + inode->i_sb->s_blocksize);
974                     blocks--; // Decrease the amount of blocks that need to be
975                               // allocated
976                     continue; // Go to the next buffer
977                 }
978
979                 if ( !itembuf || /* if first iteration */
980                      item_pos >= ih_item_len(ih)/UNFM_P_SIZE)
981                                              { /* or if we progressed past the
982                                                   current unformatted_item */
983                         /* Try to find next item */
984                         res = search_for_position_by_key(inode->i_sb, &key, &path);
985                         /* Abort if no more items */
986                         if ( res != POSITION_FOUND ) {
987                             /* make sure later loops don't use this item */
988                             itembuf = NULL;
989                             item = NULL;
990                             break;
991                         }
992
993                         /* Update information about current indirect item */
994                         itembuf = get_last_bh( &path );
995                         ih = get_ih( &path );
996                         item = get_item( &path );
997                         item_pos = path.pos_in_item;
998
999                         RFALSE( !is_indirect_le_ih (ih), "green-9003: indirect item expected");
1000                 }
1001
1002                 /* See if there is some block associated with the file
1003                    at that position, map the buffer to this block */
1004                 if ( get_block_num(item,item_pos) ) {
1005                     map_bh(bh, inode->i_sb, get_block_num(item,item_pos));
1006                     blocks--; // Decrease the amount of blocks that need to be
1007                               // allocated
1008                 }
1009                 item_pos++;
1010                 /* Update the key */
1011                 set_cpu_key_k_offset( &key, cpu_key_k_offset(&key) + inode->i_sb->s_blocksize);
1012         }
1013     }
1014     pathrelse(&path); // Free the path
1015     reiserfs_write_unlock(inode->i_sb);
1016
1017         /* Now zero out unmappend buffers for the first and last pages of
1018            write area or issue read requests if page is mapped. */
1019         /* First page, see if it is not uptodate */
1020         if ( !PageUptodate(prepared_pages[0]) ) {
1021             head = page_buffers(prepared_pages[0]);
1022
1023             /* For each buffer in page */
1024             for(bh = head, block_start = 0; bh != head || !block_start;
1025                 block_start=block_end, bh = bh->b_this_page) {
1026
1027                 if (!bh)
1028                     reiserfs_panic(inode->i_sb, "green-9002: Allocated but absent buffer for a page?");
1029                 /* Find where this buffer ends */
1030                 block_end = block_start+inode->i_sb->s_blocksize;
1031                 if ( block_end <= from )
1032                     /* if this buffer is before requested data to map, skip it*/
1033                     continue;
1034                 if ( block_start < from ) { /* Aha, our partial buffer */
1035                     if ( buffer_mapped(bh) ) { /* If it is mapped, we need to
1036                                                   issue READ request for it to
1037                                                   not loose data */
1038                         ll_rw_block(READ, 1, &bh);
1039                         *wait_bh++=bh;
1040                     } else { /* Not mapped, zero it */
1041                         char *kaddr = kmap_atomic(prepared_pages[0], KM_USER0);
1042                         memset(kaddr+block_start, 0, from-block_start);
1043                         kunmap_atomic( kaddr, KM_USER0);
1044                         set_buffer_uptodate(bh);
1045                     }
1046                 }
1047             }
1048         }
1049
1050         /* Last page, see if it is not uptodate, or if the last page is past the end of the file. */
1051         if ( !PageUptodate(prepared_pages[num_pages-1]) || 
1052             ((pos+write_bytes)>>PAGE_CACHE_SHIFT) > (inode->i_size>>PAGE_CACHE_SHIFT) ) {
1053             head = page_buffers(prepared_pages[num_pages-1]);
1054
1055             /* for each buffer in page */
1056             for(bh = head, block_start = 0; bh != head || !block_start;
1057                 block_start=block_end, bh = bh->b_this_page) {
1058
1059                 if (!bh)
1060                     reiserfs_panic(inode->i_sb, "green-9002: Allocated but absent buffer for a page?");
1061                 /* Find where this buffer ends */
1062                 block_end = block_start+inode->i_sb->s_blocksize;
1063                 if ( block_start >= to )
1064                     /* if this buffer is after requested data to map, skip it*/
1065                     break;
1066                 if ( block_end > to ) { /* Aha, our partial buffer */
1067                     if ( buffer_mapped(bh) ) { /* If it is mapped, we need to
1068                                                   issue READ request for it to
1069                                                   not loose data */
1070                         ll_rw_block(READ, 1, &bh);
1071                         *wait_bh++=bh;
1072                     } else { /* Not mapped, zero it */
1073                         char *kaddr = kmap_atomic(prepared_pages[num_pages-1], KM_USER0);
1074                         memset(kaddr+to, 0, block_end-to);
1075                         kunmap_atomic( kaddr, KM_USER0);
1076                         set_buffer_uptodate(bh);
1077                     }
1078                 }
1079             }
1080         }
1081
1082     /* Wait for read requests we made to happen, if necessary */
1083     while(wait_bh > wait) {
1084         wait_on_buffer(*--wait_bh);
1085         if (!buffer_uptodate(*wait_bh)) {
1086             res = -EIO;
1087             goto failed_read;
1088         }
1089     }
1090
1091     return blocks;
1092 failed_page_grabbing:
1093     num_pages = i;
1094 failed_read:
1095     reiserfs_unprepare_pages(prepared_pages, num_pages);
1096     return res;
1097 }
1098
1099 /* Write @count bytes at position @ppos in a file indicated by @file
1100    from the buffer @buf.  
1101
1102    generic_file_write() is only appropriate for filesystems that are not seeking to optimize performance and want
1103    something simple that works.  It is not for serious use by general purpose filesystems, excepting the one that it was
1104    written for (ext2/3).  This is for several reasons:
1105
1106    * It has no understanding of any filesystem specific optimizations.
1107
1108    * It enters the filesystem repeatedly for each page that is written.
1109
1110    * It depends on reiserfs_get_block() function which if implemented by reiserfs performs costly search_by_key
1111    * operation for each page it is supplied with. By contrast reiserfs_file_write() feeds as much as possible at a time
1112    * to reiserfs which allows for fewer tree traversals.
1113
1114    * Each indirect pointer insertion takes a lot of cpu, because it involves memory moves inside of blocks.
1115
1116    * Asking the block allocation code for blocks one at a time is slightly less efficient.
1117
1118    All of these reasons for not using only generic file write were understood back when reiserfs was first miscoded to
1119    use it, but we were in a hurry to make code freeze, and so it couldn't be revised then.  This new code should make
1120    things right finally.
1121
1122    Future Features: providing search_by_key with hints.
1123
1124 */
1125 ssize_t reiserfs_file_write( struct file *file, /* the file we are going to write into */
1126                              const char *buf, /*  pointer to user supplied data
1127 (in userspace) */
1128                              size_t count, /* amount of bytes to write */
1129                              loff_t *ppos /* pointer to position in file that we start writing at. Should be updated to
1130                                            * new current position before returning. */ )
1131 {
1132     size_t already_written = 0; // Number of bytes already written to the file.
1133     loff_t pos; // Current position in the file.
1134     size_t res; // return value of various functions that we call.
1135     struct inode *inode = file->f_dentry->d_inode; // Inode of the file that we are writing to.
1136                                 /* To simplify coding at this time, we store
1137                                    locked pages in array for now */
1138     struct page * prepared_pages[REISERFS_WRITE_PAGES_AT_A_TIME];
1139     struct reiserfs_transaction_handle th;
1140     th.t_trans_id = 0;
1141
1142     if ( file->f_flags & O_DIRECT) { // Direct IO needs treatment
1143         int result, after_file_end = 0;
1144         if ( (*ppos + count >= inode->i_size) || (file->f_flags & O_APPEND) ) {
1145             /* If we are appending a file, we need to put this savelink in here.
1146                If we will crash while doing direct io, finish_unfinished will
1147                cut the garbage from the file end. */
1148             reiserfs_write_lock(inode->i_sb);
1149             journal_begin(&th, inode->i_sb,  JOURNAL_PER_BALANCE_CNT );
1150             reiserfs_update_inode_transaction(inode);
1151             add_save_link (&th, inode, 1 /* Truncate */);
1152             journal_end(&th, inode->i_sb, JOURNAL_PER_BALANCE_CNT );
1153             reiserfs_write_unlock(inode->i_sb);
1154             after_file_end = 1;
1155         }
1156         result = generic_file_write(file, buf, count, ppos);
1157
1158         if ( after_file_end ) { /* Now update i_size and remove the savelink */
1159             struct reiserfs_transaction_handle th;
1160             reiserfs_write_lock(inode->i_sb);
1161             journal_begin(&th, inode->i_sb, 1);
1162             reiserfs_update_inode_transaction(inode);
1163             reiserfs_update_sd(&th, inode);
1164             journal_end(&th, inode->i_sb, 1);
1165             remove_save_link (inode, 1/* truncate */);
1166             reiserfs_write_unlock(inode->i_sb);
1167         }
1168
1169         return result;
1170     }
1171
1172     if ( unlikely((ssize_t) count < 0 ))
1173         return -EINVAL;
1174
1175     if (unlikely(!access_ok(VERIFY_READ, buf, count)))
1176         return -EFAULT;
1177
1178     down(&inode->i_sem); // locks the entire file for just us
1179
1180     pos = *ppos;
1181
1182     /* Check if we can write to specified region of file, file
1183        is not overly big and this kind of stuff. Adjust pos and
1184        count, if needed */
1185     res = generic_write_checks(file, &pos, &count, 0);
1186     if (res)
1187         goto out;
1188
1189     if ( count == 0 )
1190         goto out;
1191
1192     res = remove_suid(file->f_dentry);
1193     if (res)
1194         goto out;
1195
1196     inode_update_time(inode, 1); /* Both mtime and ctime */
1197
1198     // Ok, we are done with all the checks.
1199
1200     // Now we should start real work
1201
1202     /* If we are going to write past the file's packed tail or if we are going
1203        to overwrite part of the tail, we need that tail to be converted into
1204        unformatted node */
1205     res = reiserfs_check_for_tail_and_convert( inode, pos, count);
1206     if (res)
1207         goto out;
1208
1209     while ( count > 0) {
1210         /* This is the main loop in which we running until some error occures
1211            or until we write all of the data. */
1212         int num_pages;/* amount of pages we are going to write this iteration */
1213         int write_bytes; /* amount of bytes to write during this iteration */
1214         int blocks_to_allocate; /* how much blocks we need to allocate for
1215                                    this iteration */
1216         
1217         /*  (pos & (PAGE_CACHE_SIZE-1)) is an idiom for offset into a page of pos*/
1218         num_pages = !!((pos+count) & (PAGE_CACHE_SIZE - 1)) + /* round up partial
1219                                                           pages */
1220                     ((count + (pos & (PAGE_CACHE_SIZE-1))) >> PAGE_CACHE_SHIFT); 
1221                                                 /* convert size to amount of
1222                                                    pages */
1223         reiserfs_write_lock(inode->i_sb);
1224         if ( num_pages > REISERFS_WRITE_PAGES_AT_A_TIME 
1225                 || num_pages > reiserfs_can_fit_pages(inode->i_sb) ) {
1226             /* If we were asked to write more data than we want to or if there
1227                is not that much space, then we shorten amount of data to write
1228                for this iteration. */
1229             num_pages = min_t(int, REISERFS_WRITE_PAGES_AT_A_TIME, reiserfs_can_fit_pages(inode->i_sb));
1230             /* Also we should not forget to set size in bytes accordingly */
1231             write_bytes = (num_pages << PAGE_CACHE_SHIFT) - 
1232                             (pos & (PAGE_CACHE_SIZE-1));
1233                                          /* If position is not on the
1234                                             start of the page, we need
1235                                             to substract the offset
1236                                             within page */
1237         } else
1238             write_bytes = count;
1239
1240         /* reserve the blocks to be allocated later, so that later on
1241            we still have the space to write the blocks to */
1242         reiserfs_claim_blocks_to_be_allocated(inode->i_sb, num_pages << (PAGE_CACHE_SHIFT - inode->i_blkbits));
1243         reiserfs_write_unlock(inode->i_sb);
1244
1245         if ( !num_pages ) { /* If we do not have enough space even for */
1246             res = -ENOSPC;  /* single page, return -ENOSPC */
1247             if ( pos > (inode->i_size & (inode->i_sb->s_blocksize-1)))
1248                 break; // In case we are writing past the file end, break.
1249             // Otherwise we are possibly overwriting the file, so
1250             // let's set write size to be equal or less than blocksize.
1251             // This way we get it correctly for file holes.
1252             // But overwriting files on absolutelly full volumes would not
1253             // be very efficient. Well, people are not supposed to fill
1254             // 100% of disk space anyway.
1255             write_bytes = min_t(int, count, inode->i_sb->s_blocksize - (pos & (inode->i_sb->s_blocksize - 1)));
1256             num_pages = 1;
1257             // No blocks were claimed before, so do it now.
1258             reiserfs_claim_blocks_to_be_allocated(inode->i_sb, 1 << (PAGE_CACHE_SHIFT - inode->i_blkbits));
1259         }
1260
1261         /* Prepare for writing into the region, read in all the
1262            partially overwritten pages, if needed. And lock the pages,
1263            so that nobody else can access these until we are done.
1264            We get number of actual blocks needed as a result.*/
1265         blocks_to_allocate = reiserfs_prepare_file_region_for_write(inode, pos, num_pages, write_bytes, prepared_pages);
1266         if ( blocks_to_allocate < 0 ) {
1267             res = blocks_to_allocate;
1268             reiserfs_release_claimed_blocks(inode->i_sb, num_pages << (PAGE_CACHE_SHIFT - inode->i_blkbits));
1269             break;
1270         }
1271
1272         /* First we correct our estimate of how many blocks we need */
1273         reiserfs_release_claimed_blocks(inode->i_sb, (num_pages << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits)) - blocks_to_allocate );
1274
1275         if ( blocks_to_allocate > 0) {/*We only allocate blocks if we need to*/
1276             /* Fill in all the possible holes and append the file if needed */
1277             res = reiserfs_allocate_blocks_for_region(&th, inode, pos, num_pages, write_bytes, prepared_pages, blocks_to_allocate);
1278         }
1279
1280         /* well, we have allocated the blocks, so it is time to free
1281            the reservation we made earlier. */
1282         reiserfs_release_claimed_blocks(inode->i_sb, blocks_to_allocate);
1283         if ( res ) {
1284             reiserfs_unprepare_pages(prepared_pages, num_pages);
1285             break;
1286         }
1287
1288 /* NOTE that allocating blocks and filling blocks can be done in reverse order
1289    and probably we would do that just to get rid of garbage in files after a
1290    crash */
1291
1292         /* Copy data from user-supplied buffer to file's pages */
1293         res = reiserfs_copy_from_user_to_file_region(pos, num_pages, write_bytes, prepared_pages, buf);
1294         if ( res ) {
1295             reiserfs_unprepare_pages(prepared_pages, num_pages);
1296             break;
1297         }
1298
1299         /* Send the pages to disk and unlock them. */
1300         res = reiserfs_submit_file_region_for_write(&th, inode, pos, num_pages,
1301                                                     write_bytes,prepared_pages);
1302         if ( res )
1303             break;
1304
1305         already_written += write_bytes;
1306         buf += write_bytes;
1307         *ppos = pos += write_bytes;
1308         count -= write_bytes;
1309         balance_dirty_pages_ratelimited(inode->i_mapping);
1310     }
1311
1312     /* this is only true on error */
1313     if (th.t_trans_id) {
1314         reiserfs_write_lock(inode->i_sb);
1315         journal_end(&th, th.t_super, th.t_blocks_allocated);
1316         reiserfs_write_unlock(inode->i_sb);
1317     }
1318     if ((file->f_flags & O_SYNC) || IS_SYNC(inode))
1319         res = generic_osync_inode(inode, file->f_mapping, OSYNC_METADATA|OSYNC_DATA);
1320
1321     up(&inode->i_sem);
1322     reiserfs_async_progress_wait(inode->i_sb);
1323     return (already_written != 0)?already_written:res;
1324
1325 out:
1326     up(&inode->i_sem); // unlock the file on exit.
1327     return res;
1328 }
1329
1330 static ssize_t reiserfs_aio_write(struct kiocb *iocb, const char __user *buf,
1331                                size_t count, loff_t pos)
1332 {
1333     return generic_file_aio_write(iocb, buf, count, pos);
1334 }
1335
1336
1337
1338 struct file_operations reiserfs_file_operations = {
1339     .read       = generic_file_read,
1340     .write      = reiserfs_file_write,
1341     .ioctl      = reiserfs_ioctl,
1342     .mmap       = generic_file_mmap,
1343     .release    = reiserfs_file_release,
1344     .fsync      = reiserfs_sync_file,
1345     .sendfile   = generic_file_sendfile,
1346     .aio_read   = generic_file_aio_read,
1347     .aio_write  = reiserfs_aio_write,
1348 };
1349
1350
1351 struct  inode_operations reiserfs_file_inode_operations = {
1352     .truncate   = reiserfs_vfs_truncate_file,
1353     .setattr    = reiserfs_setattr,
1354 };
1355
1356