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