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