Btrfs: Implement basic support for -ENOSPC
[pandora-kernel.git] / fs / btrfs / file.c
1 /*
2  * Copyright (C) 2007 Oracle.  All rights reserved.
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public
6  * License v2 as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public
14  * License along with this program; if not, write to the
15  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
16  * Boston, MA 021110-1307, USA.
17  */
18
19 #include <linux/fs.h>
20 #include <linux/pagemap.h>
21 #include <linux/highmem.h>
22 #include <linux/time.h>
23 #include <linux/init.h>
24 #include <linux/string.h>
25 #include <linux/smp_lock.h>
26 #include <linux/backing-dev.h>
27 #include <linux/mpage.h>
28 #include <linux/swap.h>
29 #include <linux/writeback.h>
30 #include <linux/statfs.h>
31 #include <linux/compat.h>
32 #include <linux/version.h>
33 #include "ctree.h"
34 #include "disk-io.h"
35 #include "transaction.h"
36 #include "btrfs_inode.h"
37 #include "ioctl.h"
38 #include "print-tree.h"
39
40
41 static int btrfs_copy_from_user(loff_t pos, int num_pages, int write_bytes,
42                                 struct page **prepared_pages,
43                                 const char __user * buf)
44 {
45         long page_fault = 0;
46         int i;
47         int offset = pos & (PAGE_CACHE_SIZE - 1);
48
49         for (i = 0; i < num_pages && write_bytes > 0; i++, offset = 0) {
50                 size_t count = min_t(size_t,
51                                      PAGE_CACHE_SIZE - offset, write_bytes);
52                 struct page *page = prepared_pages[i];
53                 fault_in_pages_readable(buf, count);
54
55                 /* Copy data from userspace to the current page */
56                 kmap(page);
57                 page_fault = __copy_from_user(page_address(page) + offset,
58                                               buf, count);
59                 /* Flush processor's dcache for this page */
60                 flush_dcache_page(page);
61                 kunmap(page);
62                 buf += count;
63                 write_bytes -= count;
64
65                 if (page_fault)
66                         break;
67         }
68         return page_fault ? -EFAULT : 0;
69 }
70
71 static void btrfs_drop_pages(struct page **pages, size_t num_pages)
72 {
73         size_t i;
74         for (i = 0; i < num_pages; i++) {
75                 if (!pages[i])
76                         break;
77                 unlock_page(pages[i]);
78                 mark_page_accessed(pages[i]);
79                 page_cache_release(pages[i]);
80         }
81 }
82
83 static int insert_inline_extent(struct btrfs_trans_handle *trans,
84                                 struct btrfs_root *root, struct inode *inode,
85                                 u64 offset, size_t size,
86                                 struct page **pages, size_t page_offset,
87                                 int num_pages)
88 {
89         struct btrfs_key key;
90         struct btrfs_path *path;
91         struct extent_buffer *leaf;
92         char *kaddr;
93         unsigned long ptr;
94         struct btrfs_file_extent_item *ei;
95         struct page *page;
96         u32 datasize;
97         int err = 0;
98         int ret;
99         int i;
100         ssize_t cur_size;
101
102         path = btrfs_alloc_path();
103         if (!path)
104                 return -ENOMEM;
105
106         btrfs_set_trans_block_group(trans, inode);
107
108         key.objectid = inode->i_ino;
109         key.offset = offset;
110         btrfs_set_key_type(&key, BTRFS_EXTENT_DATA_KEY);
111
112         ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
113         if (ret < 0) {
114                 err = ret;
115                 goto fail;
116         }
117         if (ret == 1) {
118                 struct btrfs_key found_key;
119
120                 if (path->slots[0] == 0)
121                         goto insert;
122
123                 path->slots[0]--;
124                 leaf = path->nodes[0];
125                 btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
126
127                 if (found_key.objectid != inode->i_ino)
128                         goto insert;
129
130                 if (found_key.type != BTRFS_EXTENT_DATA_KEY)
131                         goto insert;
132                 ei = btrfs_item_ptr(leaf, path->slots[0],
133                                     struct btrfs_file_extent_item);
134
135                 if (btrfs_file_extent_type(leaf, ei) !=
136                     BTRFS_FILE_EXTENT_INLINE) {
137                         goto insert;
138                 }
139                 btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
140                 ret = 0;
141         }
142         if (ret == 0) {
143                 u32 found_size;
144                 u64 found_end;
145
146                 leaf = path->nodes[0];
147                 ei = btrfs_item_ptr(leaf, path->slots[0],
148                                     struct btrfs_file_extent_item);
149
150                 if (btrfs_file_extent_type(leaf, ei) !=
151                     BTRFS_FILE_EXTENT_INLINE) {
152                         err = ret;
153                         btrfs_print_leaf(root, leaf);
154                         printk("found wasn't inline offset %Lu inode %lu\n",
155                                offset, inode->i_ino);
156                         goto fail;
157                 }
158                 found_size = btrfs_file_extent_inline_len(leaf,
159                                           btrfs_item_nr(leaf, path->slots[0]));
160                 found_end = key.offset + found_size;
161
162                 if (found_end < offset + size) {
163                         btrfs_release_path(root, path);
164                         ret = btrfs_search_slot(trans, root, &key, path,
165                                                 offset + size - found_end, 1);
166                         BUG_ON(ret != 0);
167
168                         ret = btrfs_extend_item(trans, root, path,
169                                                 offset + size - found_end);
170                         if (ret) {
171                                 err = ret;
172                                 goto fail;
173                         }
174                         leaf = path->nodes[0];
175                         ei = btrfs_item_ptr(leaf, path->slots[0],
176                                             struct btrfs_file_extent_item);
177                 }
178                 if (found_end < offset) {
179                         ptr = btrfs_file_extent_inline_start(ei) + found_size;
180                         memset_extent_buffer(leaf, 0, ptr, offset - found_end);
181                 }
182         } else {
183 insert:
184                 btrfs_release_path(root, path);
185                 datasize = offset + size - key.offset;
186                 datasize = btrfs_file_extent_calc_inline_size(datasize);
187                 ret = btrfs_insert_empty_item(trans, root, path, &key,
188                                               datasize);
189                 if (ret) {
190                         err = ret;
191                         printk("got bad ret %d\n", ret);
192                         goto fail;
193                 }
194                 leaf = path->nodes[0];
195                 ei = btrfs_item_ptr(leaf, path->slots[0],
196                                     struct btrfs_file_extent_item);
197                 btrfs_set_file_extent_generation(leaf, ei, trans->transid);
198                 btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
199         }
200         ptr = btrfs_file_extent_inline_start(ei) + offset - key.offset;
201
202         cur_size = size;
203         i = 0;
204         while (size > 0) {
205                 page = pages[i];
206                 kaddr = kmap_atomic(page, KM_USER0);
207                 cur_size = min_t(size_t, PAGE_CACHE_SIZE - page_offset, size);
208                 write_extent_buffer(leaf, kaddr + page_offset, ptr, cur_size);
209                 kunmap_atomic(kaddr, KM_USER0);
210                 page_offset = 0;
211                 ptr += cur_size;
212                 size -= cur_size;
213                 if (i >= num_pages) {
214                         printk("i %d num_pages %d\n", i, num_pages);
215                 }
216                 i++;
217         }
218         btrfs_mark_buffer_dirty(leaf);
219 fail:
220         btrfs_free_path(path);
221         return err;
222 }
223
224 static int dirty_and_release_pages(struct btrfs_trans_handle *trans,
225                                    struct btrfs_root *root,
226                                    struct file *file,
227                                    struct page **pages,
228                                    size_t num_pages,
229                                    loff_t pos,
230                                    size_t write_bytes)
231 {
232         int err = 0;
233         int i;
234         struct inode *inode = fdentry(file)->d_inode;
235         struct extent_map *em;
236         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
237         u64 hint_byte;
238         u64 num_bytes;
239         u64 start_pos;
240         u64 end_of_last_block;
241         u64 end_pos = pos + write_bytes;
242         u64 inline_size;
243         loff_t isize = i_size_read(inode);
244         em = alloc_extent_map(GFP_NOFS);
245         if (!em)
246                 return -ENOMEM;
247
248         em->bdev = inode->i_sb->s_bdev;
249
250         start_pos = pos & ~((u64)root->sectorsize - 1);
251         num_bytes = (write_bytes + pos - start_pos +
252                     root->sectorsize - 1) & ~((u64)root->sectorsize - 1);
253
254         down_read(&BTRFS_I(inode)->root->snap_sem);
255         end_of_last_block = start_pos + num_bytes - 1;
256
257         lock_extent(em_tree, start_pos, end_of_last_block, GFP_NOFS);
258         mutex_lock(&root->fs_info->fs_mutex);
259         trans = btrfs_start_transaction(root, 1);
260         if (!trans) {
261                 err = -ENOMEM;
262                 goto out_unlock;
263         }
264         btrfs_set_trans_block_group(trans, inode);
265         inode->i_blocks += num_bytes >> 9;
266         hint_byte = 0;
267
268         if ((end_of_last_block & 4095) == 0) {
269                 printk("strange end of last %Lu %zu %Lu\n", start_pos, write_bytes, end_of_last_block);
270         }
271         set_extent_uptodate(em_tree, start_pos, end_of_last_block, GFP_NOFS);
272
273         /* FIXME...EIEIO, ENOSPC and more */
274
275         /* insert any holes we need to create */
276         if (inode->i_size < start_pos) {
277                 u64 last_pos_in_file;
278                 u64 hole_size;
279                 u64 mask = root->sectorsize - 1;
280                 last_pos_in_file = (isize + mask) & ~mask;
281                 hole_size = (start_pos - last_pos_in_file + mask) & ~mask;
282
283                 if (last_pos_in_file < start_pos) {
284                         err = btrfs_drop_extents(trans, root, inode,
285                                                  last_pos_in_file,
286                                                  last_pos_in_file + hole_size,
287                                                  last_pos_in_file,
288                                                  &hint_byte);
289                         if (err)
290                                 goto failed;
291
292                         err = btrfs_insert_file_extent(trans, root,
293                                                        inode->i_ino,
294                                                        last_pos_in_file,
295                                                        0, 0, hole_size);
296                 }
297                 if (err)
298                         goto failed;
299         }
300
301         /*
302          * either allocate an extent for the new bytes or setup the key
303          * to show we are doing inline data in the extent
304          */
305         inline_size = end_pos;
306         if (isize >= BTRFS_MAX_INLINE_DATA_SIZE(root) ||
307             inline_size > 32768 ||
308             inline_size >= BTRFS_MAX_INLINE_DATA_SIZE(root)) {
309                 u64 last_end;
310                 u64 existing_delalloc = 0;
311
312                 for (i = 0; i < num_pages; i++) {
313                         struct page *p = pages[i];
314                         SetPageUptodate(p);
315                         set_page_dirty(p);
316                 }
317                 last_end = (u64)(pages[num_pages -1]->index) <<
318                                 PAGE_CACHE_SHIFT;
319                 last_end += PAGE_CACHE_SIZE - 1;
320                 if (start_pos < isize) {
321                         u64 delalloc_start = start_pos;
322                         existing_delalloc = count_range_bits(em_tree,
323                                              &delalloc_start,
324                                              end_of_last_block, (u64)-1,
325                                              EXTENT_DELALLOC);
326                 }
327                 set_extent_delalloc(em_tree, start_pos, end_of_last_block,
328                                  GFP_NOFS);
329                 spin_lock(&root->fs_info->delalloc_lock);
330                 root->fs_info->delalloc_bytes += (end_of_last_block + 1 -
331                                           start_pos) - existing_delalloc;
332                 spin_unlock(&root->fs_info->delalloc_lock);
333         } else {
334                 u64 aligned_end;
335                 /* step one, delete the existing extents in this range */
336                 aligned_end = (pos + write_bytes + root->sectorsize - 1) &
337                         ~((u64)root->sectorsize - 1);
338                 err = btrfs_drop_extents(trans, root, inode, start_pos,
339                                          aligned_end, aligned_end, &hint_byte);
340                 if (err)
341                         goto failed;
342                 if (isize > inline_size)
343                         inline_size = min_t(u64, isize, aligned_end);
344                 inline_size -= start_pos;
345                 err = insert_inline_extent(trans, root, inode, start_pos,
346                                            inline_size, pages, 0, num_pages);
347                 BUG_ON(err);
348         }
349         if (end_pos > isize) {
350                 i_size_write(inode, end_pos);
351                 btrfs_update_inode(trans, root, inode);
352         }
353 failed:
354         err = btrfs_end_transaction(trans, root);
355 out_unlock:
356         mutex_unlock(&root->fs_info->fs_mutex);
357         unlock_extent(em_tree, start_pos, end_of_last_block, GFP_NOFS);
358         free_extent_map(em);
359         up_read(&BTRFS_I(inode)->root->snap_sem);
360         return err;
361 }
362
363 int btrfs_drop_extent_cache(struct inode *inode, u64 start, u64 end)
364 {
365         struct extent_map *em;
366         struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
367
368         while(1) {
369                 em = lookup_extent_mapping(em_tree, start, end);
370                 if (!em)
371                         break;
372                 remove_extent_mapping(em_tree, em);
373                 /* once for us */
374                 free_extent_map(em);
375                 /* once for the tree*/
376                 free_extent_map(em);
377         }
378         return 0;
379 }
380
381 /*
382  * this is very complex, but the basic idea is to drop all extents
383  * in the range start - end.  hint_block is filled in with a block number
384  * that would be a good hint to the block allocator for this file.
385  *
386  * If an extent intersects the range but is not entirely inside the range
387  * it is either truncated or split.  Anything entirely inside the range
388  * is deleted from the tree.
389  */
390 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
391                        struct btrfs_root *root, struct inode *inode,
392                        u64 start, u64 end, u64 inline_limit, u64 *hint_byte)
393 {
394         u64 extent_end = 0;
395         u64 search_start = start;
396         struct extent_buffer *leaf;
397         struct btrfs_file_extent_item *extent;
398         struct btrfs_path *path;
399         struct btrfs_key key;
400         struct btrfs_file_extent_item old;
401         int keep;
402         int slot;
403         int bookend;
404         int found_type;
405         int found_extent;
406         int found_inline;
407         int recow;
408         int ret;
409
410         btrfs_drop_extent_cache(inode, start, end - 1);
411
412         path = btrfs_alloc_path();
413         if (!path)
414                 return -ENOMEM;
415         while(1) {
416                 recow = 0;
417                 btrfs_release_path(root, path);
418                 ret = btrfs_lookup_file_extent(trans, root, path, inode->i_ino,
419                                                search_start, -1);
420                 if (ret < 0)
421                         goto out;
422                 if (ret > 0) {
423                         if (path->slots[0] == 0) {
424                                 ret = 0;
425                                 goto out;
426                         }
427                         path->slots[0]--;
428                 }
429 next_slot:
430                 keep = 0;
431                 bookend = 0;
432                 found_extent = 0;
433                 found_inline = 0;
434                 extent = NULL;
435                 leaf = path->nodes[0];
436                 slot = path->slots[0];
437                 ret = 0;
438                 btrfs_item_key_to_cpu(leaf, &key, slot);
439                 if (key.offset >= end || key.objectid != inode->i_ino) {
440                         goto out;
441                 }
442                 if (btrfs_key_type(&key) > BTRFS_EXTENT_DATA_KEY) {
443                         goto out;
444                 }
445                 if (recow) {
446                         search_start = key.offset;
447                         continue;
448                 }
449                 if (btrfs_key_type(&key) == BTRFS_EXTENT_DATA_KEY) {
450                         extent = btrfs_item_ptr(leaf, slot,
451                                                 struct btrfs_file_extent_item);
452                         found_type = btrfs_file_extent_type(leaf, extent);
453                         if (found_type == BTRFS_FILE_EXTENT_REG) {
454                                 extent_end =
455                                      btrfs_file_extent_disk_bytenr(leaf,
456                                                                    extent);
457                                 if (extent_end)
458                                         *hint_byte = extent_end;
459
460                                 extent_end = key.offset +
461                                      btrfs_file_extent_num_bytes(leaf, extent);
462                                 found_extent = 1;
463                         } else if (found_type == BTRFS_FILE_EXTENT_INLINE) {
464                                 struct btrfs_item *item;
465                                 item = btrfs_item_nr(leaf, slot);
466                                 found_inline = 1;
467                                 extent_end = key.offset +
468                                      btrfs_file_extent_inline_len(leaf, item);
469                         }
470                 } else {
471                         extent_end = search_start;
472                 }
473
474                 /* we found nothing we can drop */
475                 if ((!found_extent && !found_inline) ||
476                     search_start >= extent_end) {
477                         int nextret;
478                         u32 nritems;
479                         nritems = btrfs_header_nritems(leaf);
480                         if (slot >= nritems - 1) {
481                                 nextret = btrfs_next_leaf(root, path);
482                                 if (nextret)
483                                         goto out;
484                                 recow = 1;
485                         } else {
486                                 path->slots[0]++;
487                         }
488                         goto next_slot;
489                 }
490
491                 if (found_inline) {
492                         u64 mask = root->sectorsize - 1;
493                         search_start = (extent_end + mask) & ~mask;
494                 } else
495                         search_start = extent_end;
496                 if (end <= extent_end && start >= key.offset && found_inline) {
497                         *hint_byte = EXTENT_MAP_INLINE;
498                         continue;
499                 }
500                 if (end < extent_end && end >= key.offset) {
501                         if (found_extent) {
502                                 u64 disk_bytenr =
503                                     btrfs_file_extent_disk_bytenr(leaf, extent);
504                                 u64 disk_num_bytes =
505                                     btrfs_file_extent_disk_num_bytes(leaf,
506                                                                       extent);
507                                 read_extent_buffer(leaf, &old,
508                                                    (unsigned long)extent,
509                                                    sizeof(old));
510                                 if (disk_bytenr != 0) {
511                                         ret = btrfs_inc_extent_ref(trans, root,
512                                                  disk_bytenr, disk_num_bytes,
513                                                  root->root_key.objectid,
514                                                  trans->transid,
515                                                  key.objectid, end);
516                                         BUG_ON(ret);
517                                 }
518                         }
519                         bookend = 1;
520                         if (found_inline && start <= key.offset &&
521                             inline_limit < extent_end)
522                                 keep = 1;
523                 }
524                 /* truncate existing extent */
525                 if (start > key.offset) {
526                         u64 new_num;
527                         u64 old_num;
528                         keep = 1;
529                         WARN_ON(start & (root->sectorsize - 1));
530                         if (found_extent) {
531                                 new_num = start - key.offset;
532                                 old_num = btrfs_file_extent_num_bytes(leaf,
533                                                                       extent);
534                                 *hint_byte =
535                                         btrfs_file_extent_disk_bytenr(leaf,
536                                                                       extent);
537                                 if (btrfs_file_extent_disk_bytenr(leaf,
538                                                                   extent)) {
539                                         inode->i_blocks -=
540                                                 (old_num - new_num) >> 9;
541                                 }
542                                 btrfs_set_file_extent_num_bytes(leaf, extent,
543                                                                 new_num);
544                                 btrfs_mark_buffer_dirty(leaf);
545                         } else if (key.offset < inline_limit &&
546                                    (end > extent_end) &&
547                                    (inline_limit < extent_end)) {
548                                 u32 new_size;
549                                 new_size = btrfs_file_extent_calc_inline_size(
550                                                    inline_limit - key.offset);
551                                 btrfs_truncate_item(trans, root, path,
552                                                     new_size, 1);
553                         }
554                 }
555                 /* delete the entire extent */
556                 if (!keep) {
557                         u64 disk_bytenr = 0;
558                         u64 disk_num_bytes = 0;
559                         u64 extent_num_bytes = 0;
560                         u64 root_gen;
561                         u64 root_owner;
562
563                         root_gen = btrfs_header_generation(leaf);
564                         root_owner = btrfs_header_owner(leaf);
565                         if (found_extent) {
566                                 disk_bytenr =
567                                       btrfs_file_extent_disk_bytenr(leaf,
568                                                                      extent);
569                                 disk_num_bytes =
570                                       btrfs_file_extent_disk_num_bytes(leaf,
571                                                                        extent);
572                                 extent_num_bytes =
573                                       btrfs_file_extent_num_bytes(leaf, extent);
574                                 *hint_byte =
575                                         btrfs_file_extent_disk_bytenr(leaf,
576                                                                       extent);
577                         }
578                         ret = btrfs_del_item(trans, root, path);
579                         /* TODO update progress marker and return */
580                         BUG_ON(ret);
581                         btrfs_release_path(root, path);
582                         extent = NULL;
583                         if (found_extent && disk_bytenr != 0) {
584                                 inode->i_blocks -= extent_num_bytes >> 9;
585                                 ret = btrfs_free_extent(trans, root,
586                                                 disk_bytenr,
587                                                 disk_num_bytes,
588                                                 root_owner,
589                                                 root_gen, inode->i_ino,
590                                                 key.offset, 0);
591                         }
592
593                         BUG_ON(ret);
594                         if (!bookend && search_start >= end) {
595                                 ret = 0;
596                                 goto out;
597                         }
598                         if (!bookend)
599                                 continue;
600                 }
601                 if (bookend && found_inline && start <= key.offset &&
602                     inline_limit < extent_end && key.offset <= inline_limit) {
603                         u32 new_size;
604                         new_size = btrfs_file_extent_calc_inline_size(
605                                                    extent_end - inline_limit);
606                         btrfs_truncate_item(trans, root, path, new_size, 0);
607                 }
608                 /* create bookend, splitting the extent in two */
609                 if (bookend && found_extent) {
610                         struct btrfs_key ins;
611                         ins.objectid = inode->i_ino;
612                         ins.offset = end;
613                         btrfs_set_key_type(&ins, BTRFS_EXTENT_DATA_KEY);
614                         btrfs_release_path(root, path);
615                         ret = btrfs_insert_empty_item(trans, root, path, &ins,
616                                                       sizeof(*extent));
617
618                         leaf = path->nodes[0];
619                         if (ret) {
620                                 btrfs_print_leaf(root, leaf);
621                                 printk("got %d on inserting %Lu %u %Lu start %Lu end %Lu found %Lu %Lu keep was %d\n", ret , ins.objectid, ins.type, ins.offset, start, end, key.offset, extent_end, keep);
622                         }
623                         BUG_ON(ret);
624                         extent = btrfs_item_ptr(leaf, path->slots[0],
625                                                 struct btrfs_file_extent_item);
626                         write_extent_buffer(leaf, &old,
627                                             (unsigned long)extent, sizeof(old));
628
629                         btrfs_set_file_extent_offset(leaf, extent,
630                                     le64_to_cpu(old.offset) + end - key.offset);
631                         WARN_ON(le64_to_cpu(old.num_bytes) <
632                                 (extent_end - end));
633                         btrfs_set_file_extent_num_bytes(leaf, extent,
634                                                         extent_end - end);
635                         btrfs_set_file_extent_type(leaf, extent,
636                                                    BTRFS_FILE_EXTENT_REG);
637
638                         btrfs_mark_buffer_dirty(path->nodes[0]);
639                         if (le64_to_cpu(old.disk_bytenr) != 0) {
640                                 inode->i_blocks +=
641                                       btrfs_file_extent_num_bytes(leaf,
642                                                                   extent) >> 9;
643                         }
644                         ret = 0;
645                         goto out;
646                 }
647         }
648 out:
649         btrfs_free_path(path);
650         return ret;
651 }
652
653 /*
654  * this gets pages into the page cache and locks them down
655  */
656 static int prepare_pages(struct btrfs_root *root,
657                          struct file *file,
658                          struct page **pages,
659                          size_t num_pages,
660                          loff_t pos,
661                          unsigned long first_index,
662                          unsigned long last_index,
663                          size_t write_bytes)
664 {
665         int i;
666         unsigned long index = pos >> PAGE_CACHE_SHIFT;
667         struct inode *inode = fdentry(file)->d_inode;
668         int err = 0;
669         u64 start_pos;
670
671         start_pos = pos & ~((u64)root->sectorsize - 1);
672
673         memset(pages, 0, num_pages * sizeof(struct page *));
674
675         for (i = 0; i < num_pages; i++) {
676                 pages[i] = grab_cache_page(inode->i_mapping, index + i);
677                 if (!pages[i]) {
678                         err = -ENOMEM;
679                         BUG_ON(1);
680                 }
681 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
682                 ClearPageDirty(pages[i]);
683 #else
684                 cancel_dirty_page(pages[i], PAGE_CACHE_SIZE);
685 #endif
686                 wait_on_page_writeback(pages[i]);
687                 set_page_extent_mapped(pages[i]);
688                 WARN_ON(!PageLocked(pages[i]));
689         }
690         return 0;
691 }
692
693 static ssize_t btrfs_file_write(struct file *file, const char __user *buf,
694                                 size_t count, loff_t *ppos)
695 {
696         loff_t pos;
697         loff_t start_pos;
698         ssize_t num_written = 0;
699         ssize_t err = 0;
700         int ret = 0;
701         struct inode *inode = fdentry(file)->d_inode;
702         struct btrfs_root *root = BTRFS_I(inode)->root;
703         struct page **pages = NULL;
704         int nrptrs;
705         struct page *pinned[2];
706         unsigned long first_index;
707         unsigned long last_index;
708
709         nrptrs = min((count + PAGE_CACHE_SIZE - 1) / PAGE_CACHE_SIZE,
710                      PAGE_CACHE_SIZE / (sizeof(struct page *)));
711         pinned[0] = NULL;
712         pinned[1] = NULL;
713         if (file->f_flags & O_DIRECT)
714                 return -EINVAL;
715
716         pos = *ppos;
717         start_pos = pos;
718
719         vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
720         current->backing_dev_info = inode->i_mapping->backing_dev_info;
721         err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
722         if (err)
723                 goto out_nolock;
724         if (count == 0)
725                 goto out_nolock;
726         err = remove_suid(fdentry(file));
727         if (err)
728                 goto out_nolock;
729         file_update_time(file);
730
731         pages = kmalloc(nrptrs * sizeof(struct page *), GFP_KERNEL);
732
733         mutex_lock(&inode->i_mutex);
734         first_index = pos >> PAGE_CACHE_SHIFT;
735         last_index = (pos + count) >> PAGE_CACHE_SHIFT;
736
737         /*
738          * there are lots of better ways to do this, but this code
739          * makes sure the first and last page in the file range are
740          * up to date and ready for cow
741          */
742         if ((pos & (PAGE_CACHE_SIZE - 1))) {
743                 pinned[0] = grab_cache_page(inode->i_mapping, first_index);
744                 if (!PageUptodate(pinned[0])) {
745                         ret = btrfs_readpage(NULL, pinned[0]);
746                         BUG_ON(ret);
747                         wait_on_page_locked(pinned[0]);
748                 } else {
749                         unlock_page(pinned[0]);
750                 }
751         }
752         if ((pos + count) & (PAGE_CACHE_SIZE - 1)) {
753                 pinned[1] = grab_cache_page(inode->i_mapping, last_index);
754                 if (!PageUptodate(pinned[1])) {
755                         ret = btrfs_readpage(NULL, pinned[1]);
756                         BUG_ON(ret);
757                         wait_on_page_locked(pinned[1]);
758                 } else {
759                         unlock_page(pinned[1]);
760                 }
761         }
762
763         while(count > 0) {
764                 size_t offset = pos & (PAGE_CACHE_SIZE - 1);
765                 size_t write_bytes = min(count, nrptrs *
766                                         (size_t)PAGE_CACHE_SIZE -
767                                          offset);
768                 size_t num_pages = (write_bytes + PAGE_CACHE_SIZE - 1) >>
769                                         PAGE_CACHE_SHIFT;
770
771                 WARN_ON(num_pages > nrptrs);
772                 memset(pages, 0, sizeof(pages));
773
774                 mutex_lock(&root->fs_info->fs_mutex);
775                 ret = btrfs_check_free_space(root, write_bytes, 0);
776                 mutex_unlock(&root->fs_info->fs_mutex);
777                 if (ret)
778                         goto out;
779
780                 ret = prepare_pages(root, file, pages, num_pages,
781                                     pos, first_index, last_index,
782                                     write_bytes);
783                 if (ret)
784                         goto out;
785
786                 ret = btrfs_copy_from_user(pos, num_pages,
787                                            write_bytes, pages, buf);
788                 if (ret) {
789                         btrfs_drop_pages(pages, num_pages);
790                         goto out;
791                 }
792
793                 ret = dirty_and_release_pages(NULL, root, file, pages,
794                                               num_pages, pos, write_bytes);
795                 btrfs_drop_pages(pages, num_pages);
796                 if (ret)
797                         goto out;
798
799                 buf += write_bytes;
800                 count -= write_bytes;
801                 pos += write_bytes;
802                 num_written += write_bytes;
803
804                 balance_dirty_pages_ratelimited_nr(inode->i_mapping, num_pages);
805                 if (num_pages < (root->leafsize >> PAGE_CACHE_SHIFT) + 1)
806                         btrfs_btree_balance_dirty(root, 1);
807                 cond_resched();
808         }
809 out:
810         mutex_unlock(&inode->i_mutex);
811 out_nolock:
812         kfree(pages);
813         if (pinned[0])
814                 page_cache_release(pinned[0]);
815         if (pinned[1])
816                 page_cache_release(pinned[1]);
817         *ppos = pos;
818
819         if (num_written > 0 && ((file->f_flags & O_SYNC) || IS_SYNC(inode))) {
820                 err = sync_page_range(inode, inode->i_mapping,
821                                       start_pos, num_written);
822                 if (err < 0)
823                         num_written = err;
824         }
825         current->backing_dev_info = NULL;
826         return num_written ? num_written : err;
827 }
828
829 static int btrfs_sync_file(struct file *file,
830                            struct dentry *dentry, int datasync)
831 {
832         struct inode *inode = dentry->d_inode;
833         struct btrfs_root *root = BTRFS_I(inode)->root;
834         int ret = 0;
835         struct btrfs_trans_handle *trans;
836
837         /*
838          * check the transaction that last modified this inode
839          * and see if its already been committed
840          */
841         mutex_lock(&root->fs_info->fs_mutex);
842         if (!BTRFS_I(inode)->last_trans)
843                 goto out;
844         mutex_lock(&root->fs_info->trans_mutex);
845         if (BTRFS_I(inode)->last_trans <=
846             root->fs_info->last_trans_committed) {
847                 BTRFS_I(inode)->last_trans = 0;
848                 mutex_unlock(&root->fs_info->trans_mutex);
849                 goto out;
850         }
851         mutex_unlock(&root->fs_info->trans_mutex);
852
853         /*
854          * ok we haven't committed the transaction yet, lets do a commit
855          */
856         trans = btrfs_start_transaction(root, 1);
857         if (!trans) {
858                 ret = -ENOMEM;
859                 goto out;
860         }
861         ret = btrfs_commit_transaction(trans, root);
862 out:
863         mutex_unlock(&root->fs_info->fs_mutex);
864         return ret > 0 ? EIO : ret;
865 }
866
867 static struct vm_operations_struct btrfs_file_vm_ops = {
868 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
869         .nopage         = filemap_nopage,
870         .populate       = filemap_populate,
871 #else
872         .fault          = filemap_fault,
873 #endif
874         .page_mkwrite   = btrfs_page_mkwrite,
875 };
876
877 static int btrfs_file_mmap(struct file  *filp, struct vm_area_struct *vma)
878 {
879         vma->vm_ops = &btrfs_file_vm_ops;
880         file_accessed(filp);
881         return 0;
882 }
883
884 struct file_operations btrfs_file_operations = {
885         .llseek         = generic_file_llseek,
886         .read           = do_sync_read,
887         .aio_read       = generic_file_aio_read,
888         .splice_read    = generic_file_splice_read,
889 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,18)
890         .sendfile       = generic_file_sendfile,
891 #endif
892         .write          = btrfs_file_write,
893         .mmap           = btrfs_file_mmap,
894         .open           = generic_file_open,
895         .fsync          = btrfs_sync_file,
896         .unlocked_ioctl = btrfs_ioctl,
897 #ifdef CONFIG_COMPAT
898         .compat_ioctl   = btrfs_ioctl,
899 #endif
900 };
901