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