Merge branch 'nfs-server-stable' of git://linux-nfs.org/~bfields/linux
[linux-2.6] / fs / ocfs2 / aops.c
1 /* -*- mode: c; c-basic-offset: 8; -*-
2  * vim: noexpandtab sw=8 ts=8 sts=0:
3  *
4  * Copyright (C) 2002, 2004 Oracle.  All rights reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 021110-1307, USA.
20  */
21
22 #include <linux/fs.h>
23 #include <linux/slab.h>
24 #include <linux/highmem.h>
25 #include <linux/pagemap.h>
26 #include <asm/byteorder.h>
27 #include <linux/swap.h>
28 #include <linux/pipe_fs_i.h>
29
30 #define MLOG_MASK_PREFIX ML_FILE_IO
31 #include <cluster/masklog.h>
32
33 #include "ocfs2.h"
34
35 #include "alloc.h"
36 #include "aops.h"
37 #include "dlmglue.h"
38 #include "extent_map.h"
39 #include "file.h"
40 #include "inode.h"
41 #include "journal.h"
42 #include "suballoc.h"
43 #include "super.h"
44 #include "symlink.h"
45
46 #include "buffer_head_io.h"
47
48 static int ocfs2_symlink_get_block(struct inode *inode, sector_t iblock,
49                                    struct buffer_head *bh_result, int create)
50 {
51         int err = -EIO;
52         int status;
53         struct ocfs2_dinode *fe = NULL;
54         struct buffer_head *bh = NULL;
55         struct buffer_head *buffer_cache_bh = NULL;
56         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
57         void *kaddr;
58
59         mlog_entry("(0x%p, %llu, 0x%p, %d)\n", inode,
60                    (unsigned long long)iblock, bh_result, create);
61
62         BUG_ON(ocfs2_inode_is_fast_symlink(inode));
63
64         if ((iblock << inode->i_sb->s_blocksize_bits) > PATH_MAX + 1) {
65                 mlog(ML_ERROR, "block offset > PATH_MAX: %llu",
66                      (unsigned long long)iblock);
67                 goto bail;
68         }
69
70         status = ocfs2_read_block(OCFS2_SB(inode->i_sb),
71                                   OCFS2_I(inode)->ip_blkno,
72                                   &bh, OCFS2_BH_CACHED, inode);
73         if (status < 0) {
74                 mlog_errno(status);
75                 goto bail;
76         }
77         fe = (struct ocfs2_dinode *) bh->b_data;
78
79         if (!OCFS2_IS_VALID_DINODE(fe)) {
80                 mlog(ML_ERROR, "Invalid dinode #%llu: signature = %.*s\n",
81                      (unsigned long long)le64_to_cpu(fe->i_blkno), 7,
82                      fe->i_signature);
83                 goto bail;
84         }
85
86         if ((u64)iblock >= ocfs2_clusters_to_blocks(inode->i_sb,
87                                                     le32_to_cpu(fe->i_clusters))) {
88                 mlog(ML_ERROR, "block offset is outside the allocated size: "
89                      "%llu\n", (unsigned long long)iblock);
90                 goto bail;
91         }
92
93         /* We don't use the page cache to create symlink data, so if
94          * need be, copy it over from the buffer cache. */
95         if (!buffer_uptodate(bh_result) && ocfs2_inode_is_new(inode)) {
96                 u64 blkno = le64_to_cpu(fe->id2.i_list.l_recs[0].e_blkno) +
97                             iblock;
98                 buffer_cache_bh = sb_getblk(osb->sb, blkno);
99                 if (!buffer_cache_bh) {
100                         mlog(ML_ERROR, "couldn't getblock for symlink!\n");
101                         goto bail;
102                 }
103
104                 /* we haven't locked out transactions, so a commit
105                  * could've happened. Since we've got a reference on
106                  * the bh, even if it commits while we're doing the
107                  * copy, the data is still good. */
108                 if (buffer_jbd(buffer_cache_bh)
109                     && ocfs2_inode_is_new(inode)) {
110                         kaddr = kmap_atomic(bh_result->b_page, KM_USER0);
111                         if (!kaddr) {
112                                 mlog(ML_ERROR, "couldn't kmap!\n");
113                                 goto bail;
114                         }
115                         memcpy(kaddr + (bh_result->b_size * iblock),
116                                buffer_cache_bh->b_data,
117                                bh_result->b_size);
118                         kunmap_atomic(kaddr, KM_USER0);
119                         set_buffer_uptodate(bh_result);
120                 }
121                 brelse(buffer_cache_bh);
122         }
123
124         map_bh(bh_result, inode->i_sb,
125                le64_to_cpu(fe->id2.i_list.l_recs[0].e_blkno) + iblock);
126
127         err = 0;
128
129 bail:
130         if (bh)
131                 brelse(bh);
132
133         mlog_exit(err);
134         return err;
135 }
136
137 static int ocfs2_get_block(struct inode *inode, sector_t iblock,
138                            struct buffer_head *bh_result, int create)
139 {
140         int err = 0;
141         unsigned int ext_flags;
142         u64 p_blkno, past_eof;
143         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
144
145         mlog_entry("(0x%p, %llu, 0x%p, %d)\n", inode,
146                    (unsigned long long)iblock, bh_result, create);
147
148         if (OCFS2_I(inode)->ip_flags & OCFS2_INODE_SYSTEM_FILE)
149                 mlog(ML_NOTICE, "get_block on system inode 0x%p (%lu)\n",
150                      inode, inode->i_ino);
151
152         if (S_ISLNK(inode->i_mode)) {
153                 /* this always does I/O for some reason. */
154                 err = ocfs2_symlink_get_block(inode, iblock, bh_result, create);
155                 goto bail;
156         }
157
158         err = ocfs2_extent_map_get_blocks(inode, iblock, &p_blkno, NULL,
159                                           &ext_flags);
160         if (err) {
161                 mlog(ML_ERROR, "Error %d from get_blocks(0x%p, %llu, 1, "
162                      "%llu, NULL)\n", err, inode, (unsigned long long)iblock,
163                      (unsigned long long)p_blkno);
164                 goto bail;
165         }
166
167         /*
168          * ocfs2 never allocates in this function - the only time we
169          * need to use BH_New is when we're extending i_size on a file
170          * system which doesn't support holes, in which case BH_New
171          * allows block_prepare_write() to zero.
172          */
173         mlog_bug_on_msg(create && p_blkno == 0 && ocfs2_sparse_alloc(osb),
174                         "ino %lu, iblock %llu\n", inode->i_ino,
175                         (unsigned long long)iblock);
176
177         /* Treat the unwritten extent as a hole for zeroing purposes. */
178         if (p_blkno && !(ext_flags & OCFS2_EXT_UNWRITTEN))
179                 map_bh(bh_result, inode->i_sb, p_blkno);
180
181         if (!ocfs2_sparse_alloc(osb)) {
182                 if (p_blkno == 0) {
183                         err = -EIO;
184                         mlog(ML_ERROR,
185                              "iblock = %llu p_blkno = %llu blkno=(%llu)\n",
186                              (unsigned long long)iblock,
187                              (unsigned long long)p_blkno,
188                              (unsigned long long)OCFS2_I(inode)->ip_blkno);
189                         mlog(ML_ERROR, "Size %llu, clusters %u\n", (unsigned long long)i_size_read(inode), OCFS2_I(inode)->ip_clusters);
190                         dump_stack();
191                 }
192
193                 past_eof = ocfs2_blocks_for_bytes(inode->i_sb, i_size_read(inode));
194                 mlog(0, "Inode %lu, past_eof = %llu\n", inode->i_ino,
195                      (unsigned long long)past_eof);
196
197                 if (create && (iblock >= past_eof))
198                         set_buffer_new(bh_result);
199         }
200
201 bail:
202         if (err < 0)
203                 err = -EIO;
204
205         mlog_exit(err);
206         return err;
207 }
208
209 int ocfs2_read_inline_data(struct inode *inode, struct page *page,
210                            struct buffer_head *di_bh)
211 {
212         void *kaddr;
213         unsigned int size;
214         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
215
216         if (!(le16_to_cpu(di->i_dyn_features) & OCFS2_INLINE_DATA_FL)) {
217                 ocfs2_error(inode->i_sb, "Inode %llu lost inline data flag",
218                             (unsigned long long)OCFS2_I(inode)->ip_blkno);
219                 return -EROFS;
220         }
221
222         size = i_size_read(inode);
223
224         if (size > PAGE_CACHE_SIZE ||
225             size > ocfs2_max_inline_data(inode->i_sb)) {
226                 ocfs2_error(inode->i_sb,
227                             "Inode %llu has with inline data has bad size: %u",
228                             (unsigned long long)OCFS2_I(inode)->ip_blkno, size);
229                 return -EROFS;
230         }
231
232         kaddr = kmap_atomic(page, KM_USER0);
233         if (size)
234                 memcpy(kaddr, di->id2.i_data.id_data, size);
235         /* Clear the remaining part of the page */
236         memset(kaddr + size, 0, PAGE_CACHE_SIZE - size);
237         flush_dcache_page(page);
238         kunmap_atomic(kaddr, KM_USER0);
239
240         SetPageUptodate(page);
241
242         return 0;
243 }
244
245 static int ocfs2_readpage_inline(struct inode *inode, struct page *page)
246 {
247         int ret;
248         struct buffer_head *di_bh = NULL;
249         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
250
251         BUG_ON(!PageLocked(page));
252         BUG_ON(!OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL);
253
254         ret = ocfs2_read_block(osb, OCFS2_I(inode)->ip_blkno, &di_bh,
255                                OCFS2_BH_CACHED, inode);
256         if (ret) {
257                 mlog_errno(ret);
258                 goto out;
259         }
260
261         ret = ocfs2_read_inline_data(inode, page, di_bh);
262 out:
263         unlock_page(page);
264
265         brelse(di_bh);
266         return ret;
267 }
268
269 static int ocfs2_readpage(struct file *file, struct page *page)
270 {
271         struct inode *inode = page->mapping->host;
272         struct ocfs2_inode_info *oi = OCFS2_I(inode);
273         loff_t start = (loff_t)page->index << PAGE_CACHE_SHIFT;
274         int ret, unlock = 1;
275
276         mlog_entry("(0x%p, %lu)\n", file, (page ? page->index : 0));
277
278         ret = ocfs2_meta_lock_with_page(inode, NULL, 0, page);
279         if (ret != 0) {
280                 if (ret == AOP_TRUNCATED_PAGE)
281                         unlock = 0;
282                 mlog_errno(ret);
283                 goto out;
284         }
285
286         if (down_read_trylock(&oi->ip_alloc_sem) == 0) {
287                 ret = AOP_TRUNCATED_PAGE;
288                 goto out_meta_unlock;
289         }
290
291         /*
292          * i_size might have just been updated as we grabed the meta lock.  We
293          * might now be discovering a truncate that hit on another node.
294          * block_read_full_page->get_block freaks out if it is asked to read
295          * beyond the end of a file, so we check here.  Callers
296          * (generic_file_read, vm_ops->fault) are clever enough to check i_size
297          * and notice that the page they just read isn't needed.
298          *
299          * XXX sys_readahead() seems to get that wrong?
300          */
301         if (start >= i_size_read(inode)) {
302                 zero_user_page(page, 0, PAGE_SIZE, KM_USER0);
303                 SetPageUptodate(page);
304                 ret = 0;
305                 goto out_alloc;
306         }
307
308         ret = ocfs2_data_lock_with_page(inode, 0, page);
309         if (ret != 0) {
310                 if (ret == AOP_TRUNCATED_PAGE)
311                         unlock = 0;
312                 mlog_errno(ret);
313                 goto out_alloc;
314         }
315
316         if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL)
317                 ret = ocfs2_readpage_inline(inode, page);
318         else
319                 ret = block_read_full_page(page, ocfs2_get_block);
320         unlock = 0;
321
322         ocfs2_data_unlock(inode, 0);
323 out_alloc:
324         up_read(&OCFS2_I(inode)->ip_alloc_sem);
325 out_meta_unlock:
326         ocfs2_meta_unlock(inode, 0);
327 out:
328         if (unlock)
329                 unlock_page(page);
330         mlog_exit(ret);
331         return ret;
332 }
333
334 /* Note: Because we don't support holes, our allocation has
335  * already happened (allocation writes zeros to the file data)
336  * so we don't have to worry about ordered writes in
337  * ocfs2_writepage.
338  *
339  * ->writepage is called during the process of invalidating the page cache
340  * during blocked lock processing.  It can't block on any cluster locks
341  * to during block mapping.  It's relying on the fact that the block
342  * mapping can't have disappeared under the dirty pages that it is
343  * being asked to write back.
344  */
345 static int ocfs2_writepage(struct page *page, struct writeback_control *wbc)
346 {
347         int ret;
348
349         mlog_entry("(0x%p)\n", page);
350
351         ret = block_write_full_page(page, ocfs2_get_block, wbc);
352
353         mlog_exit(ret);
354
355         return ret;
356 }
357
358 /*
359  * This is called from ocfs2_write_zero_page() which has handled it's
360  * own cluster locking and has ensured allocation exists for those
361  * blocks to be written.
362  */
363 int ocfs2_prepare_write_nolock(struct inode *inode, struct page *page,
364                                unsigned from, unsigned to)
365 {
366         int ret;
367
368         ret = block_prepare_write(page, from, to, ocfs2_get_block);
369
370         return ret;
371 }
372
373 /* Taken from ext3. We don't necessarily need the full blown
374  * functionality yet, but IMHO it's better to cut and paste the whole
375  * thing so we can avoid introducing our own bugs (and easily pick up
376  * their fixes when they happen) --Mark */
377 int walk_page_buffers(  handle_t *handle,
378                         struct buffer_head *head,
379                         unsigned from,
380                         unsigned to,
381                         int *partial,
382                         int (*fn)(      handle_t *handle,
383                                         struct buffer_head *bh))
384 {
385         struct buffer_head *bh;
386         unsigned block_start, block_end;
387         unsigned blocksize = head->b_size;
388         int err, ret = 0;
389         struct buffer_head *next;
390
391         for (   bh = head, block_start = 0;
392                 ret == 0 && (bh != head || !block_start);
393                 block_start = block_end, bh = next)
394         {
395                 next = bh->b_this_page;
396                 block_end = block_start + blocksize;
397                 if (block_end <= from || block_start >= to) {
398                         if (partial && !buffer_uptodate(bh))
399                                 *partial = 1;
400                         continue;
401                 }
402                 err = (*fn)(handle, bh);
403                 if (!ret)
404                         ret = err;
405         }
406         return ret;
407 }
408
409 handle_t *ocfs2_start_walk_page_trans(struct inode *inode,
410                                                          struct page *page,
411                                                          unsigned from,
412                                                          unsigned to)
413 {
414         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
415         handle_t *handle = NULL;
416         int ret = 0;
417
418         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
419         if (!handle) {
420                 ret = -ENOMEM;
421                 mlog_errno(ret);
422                 goto out;
423         }
424
425         if (ocfs2_should_order_data(inode)) {
426                 ret = walk_page_buffers(handle,
427                                         page_buffers(page),
428                                         from, to, NULL,
429                                         ocfs2_journal_dirty_data);
430                 if (ret < 0) 
431                         mlog_errno(ret);
432         }
433 out:
434         if (ret) {
435                 if (handle)
436                         ocfs2_commit_trans(osb, handle);
437                 handle = ERR_PTR(ret);
438         }
439         return handle;
440 }
441
442 static sector_t ocfs2_bmap(struct address_space *mapping, sector_t block)
443 {
444         sector_t status;
445         u64 p_blkno = 0;
446         int err = 0;
447         struct inode *inode = mapping->host;
448
449         mlog_entry("(block = %llu)\n", (unsigned long long)block);
450
451         /* We don't need to lock journal system files, since they aren't
452          * accessed concurrently from multiple nodes.
453          */
454         if (!INODE_JOURNAL(inode)) {
455                 err = ocfs2_meta_lock(inode, NULL, 0);
456                 if (err) {
457                         if (err != -ENOENT)
458                                 mlog_errno(err);
459                         goto bail;
460                 }
461                 down_read(&OCFS2_I(inode)->ip_alloc_sem);
462         }
463
464         if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL))
465                 err = ocfs2_extent_map_get_blocks(inode, block, &p_blkno, NULL,
466                                                   NULL);
467
468         if (!INODE_JOURNAL(inode)) {
469                 up_read(&OCFS2_I(inode)->ip_alloc_sem);
470                 ocfs2_meta_unlock(inode, 0);
471         }
472
473         if (err) {
474                 mlog(ML_ERROR, "get_blocks() failed, block = %llu\n",
475                      (unsigned long long)block);
476                 mlog_errno(err);
477                 goto bail;
478         }
479
480 bail:
481         status = err ? 0 : p_blkno;
482
483         mlog_exit((int)status);
484
485         return status;
486 }
487
488 /*
489  * TODO: Make this into a generic get_blocks function.
490  *
491  * From do_direct_io in direct-io.c:
492  *  "So what we do is to permit the ->get_blocks function to populate
493  *   bh.b_size with the size of IO which is permitted at this offset and
494  *   this i_blkbits."
495  *
496  * This function is called directly from get_more_blocks in direct-io.c.
497  *
498  * called like this: dio->get_blocks(dio->inode, fs_startblk,
499  *                                      fs_count, map_bh, dio->rw == WRITE);
500  */
501 static int ocfs2_direct_IO_get_blocks(struct inode *inode, sector_t iblock,
502                                      struct buffer_head *bh_result, int create)
503 {
504         int ret;
505         u64 p_blkno, inode_blocks, contig_blocks;
506         unsigned int ext_flags;
507         unsigned char blocksize_bits = inode->i_sb->s_blocksize_bits;
508         unsigned long max_blocks = bh_result->b_size >> inode->i_blkbits;
509
510         /* This function won't even be called if the request isn't all
511          * nicely aligned and of the right size, so there's no need
512          * for us to check any of that. */
513
514         inode_blocks = ocfs2_blocks_for_bytes(inode->i_sb, i_size_read(inode));
515
516         /*
517          * Any write past EOF is not allowed because we'd be extending.
518          */
519         if (create && (iblock + max_blocks) > inode_blocks) {
520                 ret = -EIO;
521                 goto bail;
522         }
523
524         /* This figures out the size of the next contiguous block, and
525          * our logical offset */
526         ret = ocfs2_extent_map_get_blocks(inode, iblock, &p_blkno,
527                                           &contig_blocks, &ext_flags);
528         if (ret) {
529                 mlog(ML_ERROR, "get_blocks() failed iblock=%llu\n",
530                      (unsigned long long)iblock);
531                 ret = -EIO;
532                 goto bail;
533         }
534
535         if (!ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)) && !p_blkno) {
536                 ocfs2_error(inode->i_sb,
537                             "Inode %llu has a hole at block %llu\n",
538                             (unsigned long long)OCFS2_I(inode)->ip_blkno,
539                             (unsigned long long)iblock);
540                 ret = -EROFS;
541                 goto bail;
542         }
543
544         /*
545          * get_more_blocks() expects us to describe a hole by clearing
546          * the mapped bit on bh_result().
547          *
548          * Consider an unwritten extent as a hole.
549          */
550         if (p_blkno && !(ext_flags & OCFS2_EXT_UNWRITTEN))
551                 map_bh(bh_result, inode->i_sb, p_blkno);
552         else {
553                 /*
554                  * ocfs2_prepare_inode_for_write() should have caught
555                  * the case where we'd be filling a hole and triggered
556                  * a buffered write instead.
557                  */
558                 if (create) {
559                         ret = -EIO;
560                         mlog_errno(ret);
561                         goto bail;
562                 }
563
564                 clear_buffer_mapped(bh_result);
565         }
566
567         /* make sure we don't map more than max_blocks blocks here as
568            that's all the kernel will handle at this point. */
569         if (max_blocks < contig_blocks)
570                 contig_blocks = max_blocks;
571         bh_result->b_size = contig_blocks << blocksize_bits;
572 bail:
573         return ret;
574 }
575
576 /* 
577  * ocfs2_dio_end_io is called by the dio core when a dio is finished.  We're
578  * particularly interested in the aio/dio case.  Like the core uses
579  * i_alloc_sem, we use the rw_lock DLM lock to protect io on one node from
580  * truncation on another.
581  */
582 static void ocfs2_dio_end_io(struct kiocb *iocb,
583                              loff_t offset,
584                              ssize_t bytes,
585                              void *private)
586 {
587         struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
588         int level;
589
590         /* this io's submitter should not have unlocked this before we could */
591         BUG_ON(!ocfs2_iocb_is_rw_locked(iocb));
592
593         ocfs2_iocb_clear_rw_locked(iocb);
594
595         level = ocfs2_iocb_rw_locked_level(iocb);
596         if (!level)
597                 up_read(&inode->i_alloc_sem);
598         ocfs2_rw_unlock(inode, level);
599 }
600
601 /*
602  * ocfs2_invalidatepage() and ocfs2_releasepage() are shamelessly stolen
603  * from ext3.  PageChecked() bits have been removed as OCFS2 does not
604  * do journalled data.
605  */
606 static void ocfs2_invalidatepage(struct page *page, unsigned long offset)
607 {
608         journal_t *journal = OCFS2_SB(page->mapping->host->i_sb)->journal->j_journal;
609
610         journal_invalidatepage(journal, page, offset);
611 }
612
613 static int ocfs2_releasepage(struct page *page, gfp_t wait)
614 {
615         journal_t *journal = OCFS2_SB(page->mapping->host->i_sb)->journal->j_journal;
616
617         if (!page_has_buffers(page))
618                 return 0;
619         return journal_try_to_free_buffers(journal, page, wait);
620 }
621
622 static ssize_t ocfs2_direct_IO(int rw,
623                                struct kiocb *iocb,
624                                const struct iovec *iov,
625                                loff_t offset,
626                                unsigned long nr_segs)
627 {
628         struct file *file = iocb->ki_filp;
629         struct inode *inode = file->f_path.dentry->d_inode->i_mapping->host;
630         int ret;
631
632         mlog_entry_void();
633
634         /*
635          * Fallback to buffered I/O if we see an inode without
636          * extents.
637          */
638         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL)
639                 return 0;
640
641         if (!ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb))) {
642                 /*
643                  * We get PR data locks even for O_DIRECT.  This
644                  * allows concurrent O_DIRECT I/O but doesn't let
645                  * O_DIRECT with extending and buffered zeroing writes
646                  * race.  If they did race then the buffered zeroing
647                  * could be written back after the O_DIRECT I/O.  It's
648                  * one thing to tell people not to mix buffered and
649                  * O_DIRECT writes, but expecting them to understand
650                  * that file extension is also an implicit buffered
651                  * write is too much.  By getting the PR we force
652                  * writeback of the buffered zeroing before
653                  * proceeding.
654                  */
655                 ret = ocfs2_data_lock(inode, 0);
656                 if (ret < 0) {
657                         mlog_errno(ret);
658                         goto out;
659                 }
660                 ocfs2_data_unlock(inode, 0);
661         }
662
663         ret = blockdev_direct_IO_no_locking(rw, iocb, inode,
664                                             inode->i_sb->s_bdev, iov, offset,
665                                             nr_segs, 
666                                             ocfs2_direct_IO_get_blocks,
667                                             ocfs2_dio_end_io);
668 out:
669         mlog_exit(ret);
670         return ret;
671 }
672
673 static void ocfs2_figure_cluster_boundaries(struct ocfs2_super *osb,
674                                             u32 cpos,
675                                             unsigned int *start,
676                                             unsigned int *end)
677 {
678         unsigned int cluster_start = 0, cluster_end = PAGE_CACHE_SIZE;
679
680         if (unlikely(PAGE_CACHE_SHIFT > osb->s_clustersize_bits)) {
681                 unsigned int cpp;
682
683                 cpp = 1 << (PAGE_CACHE_SHIFT - osb->s_clustersize_bits);
684
685                 cluster_start = cpos % cpp;
686                 cluster_start = cluster_start << osb->s_clustersize_bits;
687
688                 cluster_end = cluster_start + osb->s_clustersize;
689         }
690
691         BUG_ON(cluster_start > PAGE_SIZE);
692         BUG_ON(cluster_end > PAGE_SIZE);
693
694         if (start)
695                 *start = cluster_start;
696         if (end)
697                 *end = cluster_end;
698 }
699
700 /*
701  * 'from' and 'to' are the region in the page to avoid zeroing.
702  *
703  * If pagesize > clustersize, this function will avoid zeroing outside
704  * of the cluster boundary.
705  *
706  * from == to == 0 is code for "zero the entire cluster region"
707  */
708 static void ocfs2_clear_page_regions(struct page *page,
709                                      struct ocfs2_super *osb, u32 cpos,
710                                      unsigned from, unsigned to)
711 {
712         void *kaddr;
713         unsigned int cluster_start, cluster_end;
714
715         ocfs2_figure_cluster_boundaries(osb, cpos, &cluster_start, &cluster_end);
716
717         kaddr = kmap_atomic(page, KM_USER0);
718
719         if (from || to) {
720                 if (from > cluster_start)
721                         memset(kaddr + cluster_start, 0, from - cluster_start);
722                 if (to < cluster_end)
723                         memset(kaddr + to, 0, cluster_end - to);
724         } else {
725                 memset(kaddr + cluster_start, 0, cluster_end - cluster_start);
726         }
727
728         kunmap_atomic(kaddr, KM_USER0);
729 }
730
731 /*
732  * Some of this taken from block_prepare_write(). We already have our
733  * mapping by now though, and the entire write will be allocating or
734  * it won't, so not much need to use BH_New.
735  *
736  * This will also skip zeroing, which is handled externally.
737  */
738 int ocfs2_map_page_blocks(struct page *page, u64 *p_blkno,
739                           struct inode *inode, unsigned int from,
740                           unsigned int to, int new)
741 {
742         int ret = 0;
743         struct buffer_head *head, *bh, *wait[2], **wait_bh = wait;
744         unsigned int block_end, block_start;
745         unsigned int bsize = 1 << inode->i_blkbits;
746
747         if (!page_has_buffers(page))
748                 create_empty_buffers(page, bsize, 0);
749
750         head = page_buffers(page);
751         for (bh = head, block_start = 0; bh != head || !block_start;
752              bh = bh->b_this_page, block_start += bsize) {
753                 block_end = block_start + bsize;
754
755                 clear_buffer_new(bh);
756
757                 /*
758                  * Ignore blocks outside of our i/o range -
759                  * they may belong to unallocated clusters.
760                  */
761                 if (block_start >= to || block_end <= from) {
762                         if (PageUptodate(page))
763                                 set_buffer_uptodate(bh);
764                         continue;
765                 }
766
767                 /*
768                  * For an allocating write with cluster size >= page
769                  * size, we always write the entire page.
770                  */
771                 if (new)
772                         set_buffer_new(bh);
773
774                 if (!buffer_mapped(bh)) {
775                         map_bh(bh, inode->i_sb, *p_blkno);
776                         unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
777                 }
778
779                 if (PageUptodate(page)) {
780                         if (!buffer_uptodate(bh))
781                                 set_buffer_uptodate(bh);
782                 } else if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
783                            !buffer_new(bh) &&
784                            (block_start < from || block_end > to)) {
785                         ll_rw_block(READ, 1, &bh);
786                         *wait_bh++=bh;
787                 }
788
789                 *p_blkno = *p_blkno + 1;
790         }
791
792         /*
793          * If we issued read requests - let them complete.
794          */
795         while(wait_bh > wait) {
796                 wait_on_buffer(*--wait_bh);
797                 if (!buffer_uptodate(*wait_bh))
798                         ret = -EIO;
799         }
800
801         if (ret == 0 || !new)
802                 return ret;
803
804         /*
805          * If we get -EIO above, zero out any newly allocated blocks
806          * to avoid exposing stale data.
807          */
808         bh = head;
809         block_start = 0;
810         do {
811                 block_end = block_start + bsize;
812                 if (block_end <= from)
813                         goto next_bh;
814                 if (block_start >= to)
815                         break;
816
817                 zero_user_page(page, block_start, bh->b_size, KM_USER0);
818                 set_buffer_uptodate(bh);
819                 mark_buffer_dirty(bh);
820
821 next_bh:
822                 block_start = block_end;
823                 bh = bh->b_this_page;
824         } while (bh != head);
825
826         return ret;
827 }
828
829 #if (PAGE_CACHE_SIZE >= OCFS2_MAX_CLUSTERSIZE)
830 #define OCFS2_MAX_CTXT_PAGES    1
831 #else
832 #define OCFS2_MAX_CTXT_PAGES    (OCFS2_MAX_CLUSTERSIZE / PAGE_CACHE_SIZE)
833 #endif
834
835 #define OCFS2_MAX_CLUSTERS_PER_PAGE     (PAGE_CACHE_SIZE / OCFS2_MIN_CLUSTERSIZE)
836
837 /*
838  * Describe the state of a single cluster to be written to.
839  */
840 struct ocfs2_write_cluster_desc {
841         u32             c_cpos;
842         u32             c_phys;
843         /*
844          * Give this a unique field because c_phys eventually gets
845          * filled.
846          */
847         unsigned        c_new;
848         unsigned        c_unwritten;
849 };
850
851 static inline int ocfs2_should_zero_cluster(struct ocfs2_write_cluster_desc *d)
852 {
853         return d->c_new || d->c_unwritten;
854 }
855
856 struct ocfs2_write_ctxt {
857         /* Logical cluster position / len of write */
858         u32                             w_cpos;
859         u32                             w_clen;
860
861         struct ocfs2_write_cluster_desc w_desc[OCFS2_MAX_CLUSTERS_PER_PAGE];
862
863         /*
864          * This is true if page_size > cluster_size.
865          *
866          * It triggers a set of special cases during write which might
867          * have to deal with allocating writes to partial pages.
868          */
869         unsigned int                    w_large_pages;
870
871         /*
872          * Pages involved in this write.
873          *
874          * w_target_page is the page being written to by the user.
875          *
876          * w_pages is an array of pages which always contains
877          * w_target_page, and in the case of an allocating write with
878          * page_size < cluster size, it will contain zero'd and mapped
879          * pages adjacent to w_target_page which need to be written
880          * out in so that future reads from that region will get
881          * zero's.
882          */
883         struct page                     *w_pages[OCFS2_MAX_CTXT_PAGES];
884         unsigned int                    w_num_pages;
885         struct page                     *w_target_page;
886
887         /*
888          * ocfs2_write_end() uses this to know what the real range to
889          * write in the target should be.
890          */
891         unsigned int                    w_target_from;
892         unsigned int                    w_target_to;
893
894         /*
895          * We could use journal_current_handle() but this is cleaner,
896          * IMHO -Mark
897          */
898         handle_t                        *w_handle;
899
900         struct buffer_head              *w_di_bh;
901
902         struct ocfs2_cached_dealloc_ctxt w_dealloc;
903 };
904
905 void ocfs2_unlock_and_free_pages(struct page **pages, int num_pages)
906 {
907         int i;
908
909         for(i = 0; i < num_pages; i++) {
910                 if (pages[i]) {
911                         unlock_page(pages[i]);
912                         mark_page_accessed(pages[i]);
913                         page_cache_release(pages[i]);
914                 }
915         }
916 }
917
918 static void ocfs2_free_write_ctxt(struct ocfs2_write_ctxt *wc)
919 {
920         ocfs2_unlock_and_free_pages(wc->w_pages, wc->w_num_pages);
921
922         brelse(wc->w_di_bh);
923         kfree(wc);
924 }
925
926 static int ocfs2_alloc_write_ctxt(struct ocfs2_write_ctxt **wcp,
927                                   struct ocfs2_super *osb, loff_t pos,
928                                   unsigned len, struct buffer_head *di_bh)
929 {
930         u32 cend;
931         struct ocfs2_write_ctxt *wc;
932
933         wc = kzalloc(sizeof(struct ocfs2_write_ctxt), GFP_NOFS);
934         if (!wc)
935                 return -ENOMEM;
936
937         wc->w_cpos = pos >> osb->s_clustersize_bits;
938         cend = (pos + len - 1) >> osb->s_clustersize_bits;
939         wc->w_clen = cend - wc->w_cpos + 1;
940         get_bh(di_bh);
941         wc->w_di_bh = di_bh;
942
943         if (unlikely(PAGE_CACHE_SHIFT > osb->s_clustersize_bits))
944                 wc->w_large_pages = 1;
945         else
946                 wc->w_large_pages = 0;
947
948         ocfs2_init_dealloc_ctxt(&wc->w_dealloc);
949
950         *wcp = wc;
951
952         return 0;
953 }
954
955 /*
956  * If a page has any new buffers, zero them out here, and mark them uptodate
957  * and dirty so they'll be written out (in order to prevent uninitialised
958  * block data from leaking). And clear the new bit.
959  */
960 static void ocfs2_zero_new_buffers(struct page *page, unsigned from, unsigned to)
961 {
962         unsigned int block_start, block_end;
963         struct buffer_head *head, *bh;
964
965         BUG_ON(!PageLocked(page));
966         if (!page_has_buffers(page))
967                 return;
968
969         bh = head = page_buffers(page);
970         block_start = 0;
971         do {
972                 block_end = block_start + bh->b_size;
973
974                 if (buffer_new(bh)) {
975                         if (block_end > from && block_start < to) {
976                                 if (!PageUptodate(page)) {
977                                         unsigned start, end;
978
979                                         start = max(from, block_start);
980                                         end = min(to, block_end);
981
982                                         zero_user_page(page, start, end - start, KM_USER0);
983                                         set_buffer_uptodate(bh);
984                                 }
985
986                                 clear_buffer_new(bh);
987                                 mark_buffer_dirty(bh);
988                         }
989                 }
990
991                 block_start = block_end;
992                 bh = bh->b_this_page;
993         } while (bh != head);
994 }
995
996 /*
997  * Only called when we have a failure during allocating write to write
998  * zero's to the newly allocated region.
999  */
1000 static void ocfs2_write_failure(struct inode *inode,
1001                                 struct ocfs2_write_ctxt *wc,
1002                                 loff_t user_pos, unsigned user_len)
1003 {
1004         int i;
1005         unsigned from = user_pos & (PAGE_CACHE_SIZE - 1),
1006                 to = user_pos + user_len;
1007         struct page *tmppage;
1008
1009         ocfs2_zero_new_buffers(wc->w_target_page, from, to);
1010
1011         for(i = 0; i < wc->w_num_pages; i++) {
1012                 tmppage = wc->w_pages[i];
1013
1014                 if (ocfs2_should_order_data(inode))
1015                         walk_page_buffers(wc->w_handle, page_buffers(tmppage),
1016                                           from, to, NULL,
1017                                           ocfs2_journal_dirty_data);
1018
1019                 block_commit_write(tmppage, from, to);
1020         }
1021 }
1022
1023 static int ocfs2_prepare_page_for_write(struct inode *inode, u64 *p_blkno,
1024                                         struct ocfs2_write_ctxt *wc,
1025                                         struct page *page, u32 cpos,
1026                                         loff_t user_pos, unsigned user_len,
1027                                         int new)
1028 {
1029         int ret;
1030         unsigned int map_from = 0, map_to = 0;
1031         unsigned int cluster_start, cluster_end;
1032         unsigned int user_data_from = 0, user_data_to = 0;
1033
1034         ocfs2_figure_cluster_boundaries(OCFS2_SB(inode->i_sb), cpos,
1035                                         &cluster_start, &cluster_end);
1036
1037         if (page == wc->w_target_page) {
1038                 map_from = user_pos & (PAGE_CACHE_SIZE - 1);
1039                 map_to = map_from + user_len;
1040
1041                 if (new)
1042                         ret = ocfs2_map_page_blocks(page, p_blkno, inode,
1043                                                     cluster_start, cluster_end,
1044                                                     new);
1045                 else
1046                         ret = ocfs2_map_page_blocks(page, p_blkno, inode,
1047                                                     map_from, map_to, new);
1048                 if (ret) {
1049                         mlog_errno(ret);
1050                         goto out;
1051                 }
1052
1053                 user_data_from = map_from;
1054                 user_data_to = map_to;
1055                 if (new) {
1056                         map_from = cluster_start;
1057                         map_to = cluster_end;
1058                 }
1059         } else {
1060                 /*
1061                  * If we haven't allocated the new page yet, we
1062                  * shouldn't be writing it out without copying user
1063                  * data. This is likely a math error from the caller.
1064                  */
1065                 BUG_ON(!new);
1066
1067                 map_from = cluster_start;
1068                 map_to = cluster_end;
1069
1070                 ret = ocfs2_map_page_blocks(page, p_blkno, inode,
1071                                             cluster_start, cluster_end, new);
1072                 if (ret) {
1073                         mlog_errno(ret);
1074                         goto out;
1075                 }
1076         }
1077
1078         /*
1079          * Parts of newly allocated pages need to be zero'd.
1080          *
1081          * Above, we have also rewritten 'to' and 'from' - as far as
1082          * the rest of the function is concerned, the entire cluster
1083          * range inside of a page needs to be written.
1084          *
1085          * We can skip this if the page is up to date - it's already
1086          * been zero'd from being read in as a hole.
1087          */
1088         if (new && !PageUptodate(page))
1089                 ocfs2_clear_page_regions(page, OCFS2_SB(inode->i_sb),
1090                                          cpos, user_data_from, user_data_to);
1091
1092         flush_dcache_page(page);
1093
1094 out:
1095         return ret;
1096 }
1097
1098 /*
1099  * This function will only grab one clusters worth of pages.
1100  */
1101 static int ocfs2_grab_pages_for_write(struct address_space *mapping,
1102                                       struct ocfs2_write_ctxt *wc,
1103                                       u32 cpos, loff_t user_pos, int new,
1104                                       struct page *mmap_page)
1105 {
1106         int ret = 0, i;
1107         unsigned long start, target_index, index;
1108         struct inode *inode = mapping->host;
1109
1110         target_index = user_pos >> PAGE_CACHE_SHIFT;
1111
1112         /*
1113          * Figure out how many pages we'll be manipulating here. For
1114          * non allocating write, we just change the one
1115          * page. Otherwise, we'll need a whole clusters worth.
1116          */
1117         if (new) {
1118                 wc->w_num_pages = ocfs2_pages_per_cluster(inode->i_sb);
1119                 start = ocfs2_align_clusters_to_page_index(inode->i_sb, cpos);
1120         } else {
1121                 wc->w_num_pages = 1;
1122                 start = target_index;
1123         }
1124
1125         for(i = 0; i < wc->w_num_pages; i++) {
1126                 index = start + i;
1127
1128                 if (index == target_index && mmap_page) {
1129                         /*
1130                          * ocfs2_pagemkwrite() is a little different
1131                          * and wants us to directly use the page
1132                          * passed in.
1133                          */
1134                         lock_page(mmap_page);
1135
1136                         if (mmap_page->mapping != mapping) {
1137                                 unlock_page(mmap_page);
1138                                 /*
1139                                  * Sanity check - the locking in
1140                                  * ocfs2_pagemkwrite() should ensure
1141                                  * that this code doesn't trigger.
1142                                  */
1143                                 ret = -EINVAL;
1144                                 mlog_errno(ret);
1145                                 goto out;
1146                         }
1147
1148                         page_cache_get(mmap_page);
1149                         wc->w_pages[i] = mmap_page;
1150                 } else {
1151                         wc->w_pages[i] = find_or_create_page(mapping, index,
1152                                                              GFP_NOFS);
1153                         if (!wc->w_pages[i]) {
1154                                 ret = -ENOMEM;
1155                                 mlog_errno(ret);
1156                                 goto out;
1157                         }
1158                 }
1159
1160                 if (index == target_index)
1161                         wc->w_target_page = wc->w_pages[i];
1162         }
1163 out:
1164         return ret;
1165 }
1166
1167 /*
1168  * Prepare a single cluster for write one cluster into the file.
1169  */
1170 static int ocfs2_write_cluster(struct address_space *mapping,
1171                                u32 phys, unsigned int unwritten,
1172                                struct ocfs2_alloc_context *data_ac,
1173                                struct ocfs2_alloc_context *meta_ac,
1174                                struct ocfs2_write_ctxt *wc, u32 cpos,
1175                                loff_t user_pos, unsigned user_len)
1176 {
1177         int ret, i, new, should_zero = 0;
1178         u64 v_blkno, p_blkno;
1179         struct inode *inode = mapping->host;
1180
1181         new = phys == 0 ? 1 : 0;
1182         if (new || unwritten)
1183                 should_zero = 1;
1184
1185         if (new) {
1186                 u32 tmp_pos;
1187
1188                 /*
1189                  * This is safe to call with the page locks - it won't take
1190                  * any additional semaphores or cluster locks.
1191                  */
1192                 tmp_pos = cpos;
1193                 ret = ocfs2_do_extend_allocation(OCFS2_SB(inode->i_sb), inode,
1194                                                  &tmp_pos, 1, 0, wc->w_di_bh,
1195                                                  wc->w_handle, data_ac,
1196                                                  meta_ac, NULL);
1197                 /*
1198                  * This shouldn't happen because we must have already
1199                  * calculated the correct meta data allocation required. The
1200                  * internal tree allocation code should know how to increase
1201                  * transaction credits itself.
1202                  *
1203                  * If need be, we could handle -EAGAIN for a
1204                  * RESTART_TRANS here.
1205                  */
1206                 mlog_bug_on_msg(ret == -EAGAIN,
1207                                 "Inode %llu: EAGAIN return during allocation.\n",
1208                                 (unsigned long long)OCFS2_I(inode)->ip_blkno);
1209                 if (ret < 0) {
1210                         mlog_errno(ret);
1211                         goto out;
1212                 }
1213         } else if (unwritten) {
1214                 ret = ocfs2_mark_extent_written(inode, wc->w_di_bh,
1215                                                 wc->w_handle, cpos, 1, phys,
1216                                                 meta_ac, &wc->w_dealloc);
1217                 if (ret < 0) {
1218                         mlog_errno(ret);
1219                         goto out;
1220                 }
1221         }
1222
1223         if (should_zero)
1224                 v_blkno = ocfs2_clusters_to_blocks(inode->i_sb, cpos);
1225         else
1226                 v_blkno = user_pos >> inode->i_sb->s_blocksize_bits;
1227
1228         /*
1229          * The only reason this should fail is due to an inability to
1230          * find the extent added.
1231          */
1232         ret = ocfs2_extent_map_get_blocks(inode, v_blkno, &p_blkno, NULL,
1233                                           NULL);
1234         if (ret < 0) {
1235                 ocfs2_error(inode->i_sb, "Corrupting extend for inode %llu, "
1236                             "at logical block %llu",
1237                             (unsigned long long)OCFS2_I(inode)->ip_blkno,
1238                             (unsigned long long)v_blkno);
1239                 goto out;
1240         }
1241
1242         BUG_ON(p_blkno == 0);
1243
1244         for(i = 0; i < wc->w_num_pages; i++) {
1245                 int tmpret;
1246
1247                 tmpret = ocfs2_prepare_page_for_write(inode, &p_blkno, wc,
1248                                                       wc->w_pages[i], cpos,
1249                                                       user_pos, user_len,
1250                                                       should_zero);
1251                 if (tmpret) {
1252                         mlog_errno(tmpret);
1253                         if (ret == 0)
1254                                 tmpret = ret;
1255                 }
1256         }
1257
1258         /*
1259          * We only have cleanup to do in case of allocating write.
1260          */
1261         if (ret && new)
1262                 ocfs2_write_failure(inode, wc, user_pos, user_len);
1263
1264 out:
1265
1266         return ret;
1267 }
1268
1269 static int ocfs2_write_cluster_by_desc(struct address_space *mapping,
1270                                        struct ocfs2_alloc_context *data_ac,
1271                                        struct ocfs2_alloc_context *meta_ac,
1272                                        struct ocfs2_write_ctxt *wc,
1273                                        loff_t pos, unsigned len)
1274 {
1275         int ret, i;
1276         loff_t cluster_off;
1277         unsigned int local_len = len;
1278         struct ocfs2_write_cluster_desc *desc;
1279         struct ocfs2_super *osb = OCFS2_SB(mapping->host->i_sb);
1280
1281         for (i = 0; i < wc->w_clen; i++) {
1282                 desc = &wc->w_desc[i];
1283
1284                 /*
1285                  * We have to make sure that the total write passed in
1286                  * doesn't extend past a single cluster.
1287                  */
1288                 local_len = len;
1289                 cluster_off = pos & (osb->s_clustersize - 1);
1290                 if ((cluster_off + local_len) > osb->s_clustersize)
1291                         local_len = osb->s_clustersize - cluster_off;
1292
1293                 ret = ocfs2_write_cluster(mapping, desc->c_phys,
1294                                           desc->c_unwritten, data_ac, meta_ac,
1295                                           wc, desc->c_cpos, pos, local_len);
1296                 if (ret) {
1297                         mlog_errno(ret);
1298                         goto out;
1299                 }
1300
1301                 len -= local_len;
1302                 pos += local_len;
1303         }
1304
1305         ret = 0;
1306 out:
1307         return ret;
1308 }
1309
1310 /*
1311  * ocfs2_write_end() wants to know which parts of the target page it
1312  * should complete the write on. It's easiest to compute them ahead of
1313  * time when a more complete view of the write is available.
1314  */
1315 static void ocfs2_set_target_boundaries(struct ocfs2_super *osb,
1316                                         struct ocfs2_write_ctxt *wc,
1317                                         loff_t pos, unsigned len, int alloc)
1318 {
1319         struct ocfs2_write_cluster_desc *desc;
1320
1321         wc->w_target_from = pos & (PAGE_CACHE_SIZE - 1);
1322         wc->w_target_to = wc->w_target_from + len;
1323
1324         if (alloc == 0)
1325                 return;
1326
1327         /*
1328          * Allocating write - we may have different boundaries based
1329          * on page size and cluster size.
1330          *
1331          * NOTE: We can no longer compute one value from the other as
1332          * the actual write length and user provided length may be
1333          * different.
1334          */
1335
1336         if (wc->w_large_pages) {
1337                 /*
1338                  * We only care about the 1st and last cluster within
1339                  * our range and whether they should be zero'd or not. Either
1340                  * value may be extended out to the start/end of a
1341                  * newly allocated cluster.
1342                  */
1343                 desc = &wc->w_desc[0];
1344                 if (ocfs2_should_zero_cluster(desc))
1345                         ocfs2_figure_cluster_boundaries(osb,
1346                                                         desc->c_cpos,
1347                                                         &wc->w_target_from,
1348                                                         NULL);
1349
1350                 desc = &wc->w_desc[wc->w_clen - 1];
1351                 if (ocfs2_should_zero_cluster(desc))
1352                         ocfs2_figure_cluster_boundaries(osb,
1353                                                         desc->c_cpos,
1354                                                         NULL,
1355                                                         &wc->w_target_to);
1356         } else {
1357                 wc->w_target_from = 0;
1358                 wc->w_target_to = PAGE_CACHE_SIZE;
1359         }
1360 }
1361
1362 /*
1363  * Populate each single-cluster write descriptor in the write context
1364  * with information about the i/o to be done.
1365  *
1366  * Returns the number of clusters that will have to be allocated, as
1367  * well as a worst case estimate of the number of extent records that
1368  * would have to be created during a write to an unwritten region.
1369  */
1370 static int ocfs2_populate_write_desc(struct inode *inode,
1371                                      struct ocfs2_write_ctxt *wc,
1372                                      unsigned int *clusters_to_alloc,
1373                                      unsigned int *extents_to_split)
1374 {
1375         int ret;
1376         struct ocfs2_write_cluster_desc *desc;
1377         unsigned int num_clusters = 0;
1378         unsigned int ext_flags = 0;
1379         u32 phys = 0;
1380         int i;
1381
1382         *clusters_to_alloc = 0;
1383         *extents_to_split = 0;
1384
1385         for (i = 0; i < wc->w_clen; i++) {
1386                 desc = &wc->w_desc[i];
1387                 desc->c_cpos = wc->w_cpos + i;
1388
1389                 if (num_clusters == 0) {
1390                         /*
1391                          * Need to look up the next extent record.
1392                          */
1393                         ret = ocfs2_get_clusters(inode, desc->c_cpos, &phys,
1394                                                  &num_clusters, &ext_flags);
1395                         if (ret) {
1396                                 mlog_errno(ret);
1397                                 goto out;
1398                         }
1399
1400                         /*
1401                          * Assume worst case - that we're writing in
1402                          * the middle of the extent.
1403                          *
1404                          * We can assume that the write proceeds from
1405                          * left to right, in which case the extent
1406                          * insert code is smart enough to coalesce the
1407                          * next splits into the previous records created.
1408                          */
1409                         if (ext_flags & OCFS2_EXT_UNWRITTEN)
1410                                 *extents_to_split = *extents_to_split + 2;
1411                 } else if (phys) {
1412                         /*
1413                          * Only increment phys if it doesn't describe
1414                          * a hole.
1415                          */
1416                         phys++;
1417                 }
1418
1419                 desc->c_phys = phys;
1420                 if (phys == 0) {
1421                         desc->c_new = 1;
1422                         *clusters_to_alloc = *clusters_to_alloc + 1;
1423                 }
1424                 if (ext_flags & OCFS2_EXT_UNWRITTEN)
1425                         desc->c_unwritten = 1;
1426
1427                 num_clusters--;
1428         }
1429
1430         ret = 0;
1431 out:
1432         return ret;
1433 }
1434
1435 static int ocfs2_write_begin_inline(struct address_space *mapping,
1436                                     struct inode *inode,
1437                                     struct ocfs2_write_ctxt *wc)
1438 {
1439         int ret;
1440         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1441         struct page *page;
1442         handle_t *handle;
1443         struct ocfs2_dinode *di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1444
1445         page = find_or_create_page(mapping, 0, GFP_NOFS);
1446         if (!page) {
1447                 ret = -ENOMEM;
1448                 mlog_errno(ret);
1449                 goto out;
1450         }
1451         /*
1452          * If we don't set w_num_pages then this page won't get unlocked
1453          * and freed on cleanup of the write context.
1454          */
1455         wc->w_pages[0] = wc->w_target_page = page;
1456         wc->w_num_pages = 1;
1457
1458         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
1459         if (IS_ERR(handle)) {
1460                 ret = PTR_ERR(handle);
1461                 mlog_errno(ret);
1462                 goto out;
1463         }
1464
1465         ret = ocfs2_journal_access(handle, inode, wc->w_di_bh,
1466                                    OCFS2_JOURNAL_ACCESS_WRITE);
1467         if (ret) {
1468                 ocfs2_commit_trans(osb, handle);
1469
1470                 mlog_errno(ret);
1471                 goto out;
1472         }
1473
1474         if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL))
1475                 ocfs2_set_inode_data_inline(inode, di);
1476
1477         if (!PageUptodate(page)) {
1478                 ret = ocfs2_read_inline_data(inode, page, wc->w_di_bh);
1479                 if (ret) {
1480                         ocfs2_commit_trans(osb, handle);
1481
1482                         goto out;
1483                 }
1484         }
1485
1486         wc->w_handle = handle;
1487 out:
1488         return ret;
1489 }
1490
1491 int ocfs2_size_fits_inline_data(struct buffer_head *di_bh, u64 new_size)
1492 {
1493         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1494
1495         if (new_size < le16_to_cpu(di->id2.i_data.id_count))
1496                 return 1;
1497         return 0;
1498 }
1499
1500 static int ocfs2_try_to_write_inline_data(struct address_space *mapping,
1501                                           struct inode *inode, loff_t pos,
1502                                           unsigned len, struct page *mmap_page,
1503                                           struct ocfs2_write_ctxt *wc)
1504 {
1505         int ret, written = 0;
1506         loff_t end = pos + len;
1507         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1508
1509         mlog(0, "Inode %llu, write of %u bytes at off %llu. features: 0x%x\n",
1510              (unsigned long long)oi->ip_blkno, len, (unsigned long long)pos,
1511              oi->ip_dyn_features);
1512
1513         /*
1514          * Handle inodes which already have inline data 1st.
1515          */
1516         if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1517                 if (mmap_page == NULL &&
1518                     ocfs2_size_fits_inline_data(wc->w_di_bh, end))
1519                         goto do_inline_write;
1520
1521                 /*
1522                  * The write won't fit - we have to give this inode an
1523                  * inline extent list now.
1524                  */
1525                 ret = ocfs2_convert_inline_data_to_extents(inode, wc->w_di_bh);
1526                 if (ret)
1527                         mlog_errno(ret);
1528                 goto out;
1529         }
1530
1531         /*
1532          * Check whether the inode can accept inline data.
1533          */
1534         if (oi->ip_clusters != 0 || i_size_read(inode) != 0)
1535                 return 0;
1536
1537         /*
1538          * Check whether the write can fit.
1539          */
1540         if (mmap_page || end > ocfs2_max_inline_data(inode->i_sb))
1541                 return 0;
1542
1543 do_inline_write:
1544         ret = ocfs2_write_begin_inline(mapping, inode, wc);
1545         if (ret) {
1546                 mlog_errno(ret);
1547                 goto out;
1548         }
1549
1550         /*
1551          * This signals to the caller that the data can be written
1552          * inline.
1553          */
1554         written = 1;
1555 out:
1556         return written ? written : ret;
1557 }
1558
1559 /*
1560  * This function only does anything for file systems which can't
1561  * handle sparse files.
1562  *
1563  * What we want to do here is fill in any hole between the current end
1564  * of allocation and the end of our write. That way the rest of the
1565  * write path can treat it as an non-allocating write, which has no
1566  * special case code for sparse/nonsparse files.
1567  */
1568 static int ocfs2_expand_nonsparse_inode(struct inode *inode, loff_t pos,
1569                                         unsigned len,
1570                                         struct ocfs2_write_ctxt *wc)
1571 {
1572         int ret;
1573         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1574         loff_t newsize = pos + len;
1575
1576         if (ocfs2_sparse_alloc(osb))
1577                 return 0;
1578
1579         if (newsize <= i_size_read(inode))
1580                 return 0;
1581
1582         ret = ocfs2_extend_no_holes(inode, newsize, newsize - len);
1583         if (ret)
1584                 mlog_errno(ret);
1585
1586         return ret;
1587 }
1588
1589 int ocfs2_write_begin_nolock(struct address_space *mapping,
1590                              loff_t pos, unsigned len, unsigned flags,
1591                              struct page **pagep, void **fsdata,
1592                              struct buffer_head *di_bh, struct page *mmap_page)
1593 {
1594         int ret, credits = OCFS2_INODE_UPDATE_CREDITS;
1595         unsigned int clusters_to_alloc, extents_to_split;
1596         struct ocfs2_write_ctxt *wc;
1597         struct inode *inode = mapping->host;
1598         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1599         struct ocfs2_dinode *di;
1600         struct ocfs2_alloc_context *data_ac = NULL;
1601         struct ocfs2_alloc_context *meta_ac = NULL;
1602         handle_t *handle;
1603
1604         ret = ocfs2_alloc_write_ctxt(&wc, osb, pos, len, di_bh);
1605         if (ret) {
1606                 mlog_errno(ret);
1607                 return ret;
1608         }
1609
1610         if (ocfs2_supports_inline_data(osb)) {
1611                 ret = ocfs2_try_to_write_inline_data(mapping, inode, pos, len,
1612                                                      mmap_page, wc);
1613                 if (ret == 1) {
1614                         ret = 0;
1615                         goto success;
1616                 }
1617                 if (ret < 0) {
1618                         mlog_errno(ret);
1619                         goto out;
1620                 }
1621         }
1622
1623         ret = ocfs2_expand_nonsparse_inode(inode, pos, len, wc);
1624         if (ret) {
1625                 mlog_errno(ret);
1626                 goto out;
1627         }
1628
1629         ret = ocfs2_populate_write_desc(inode, wc, &clusters_to_alloc,
1630                                         &extents_to_split);
1631         if (ret) {
1632                 mlog_errno(ret);
1633                 goto out;
1634         }
1635
1636         di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1637
1638         /*
1639          * We set w_target_from, w_target_to here so that
1640          * ocfs2_write_end() knows which range in the target page to
1641          * write out. An allocation requires that we write the entire
1642          * cluster range.
1643          */
1644         if (clusters_to_alloc || extents_to_split) {
1645                 /*
1646                  * XXX: We are stretching the limits of
1647                  * ocfs2_lock_allocators(). It greatly over-estimates
1648                  * the work to be done.
1649                  */
1650                 ret = ocfs2_lock_allocators(inode, di, clusters_to_alloc,
1651                                             extents_to_split, &data_ac, &meta_ac);
1652                 if (ret) {
1653                         mlog_errno(ret);
1654                         goto out;
1655                 }
1656
1657                 credits = ocfs2_calc_extend_credits(inode->i_sb, di,
1658                                                     clusters_to_alloc);
1659
1660         }
1661
1662         ocfs2_set_target_boundaries(osb, wc, pos, len,
1663                                     clusters_to_alloc + extents_to_split);
1664
1665         handle = ocfs2_start_trans(osb, credits);
1666         if (IS_ERR(handle)) {
1667                 ret = PTR_ERR(handle);
1668                 mlog_errno(ret);
1669                 goto out;
1670         }
1671
1672         wc->w_handle = handle;
1673
1674         /*
1675          * We don't want this to fail in ocfs2_write_end(), so do it
1676          * here.
1677          */
1678         ret = ocfs2_journal_access(handle, inode, wc->w_di_bh,
1679                                    OCFS2_JOURNAL_ACCESS_WRITE);
1680         if (ret) {
1681                 mlog_errno(ret);
1682                 goto out_commit;
1683         }
1684
1685         /*
1686          * Fill our page array first. That way we've grabbed enough so
1687          * that we can zero and flush if we error after adding the
1688          * extent.
1689          */
1690         ret = ocfs2_grab_pages_for_write(mapping, wc, wc->w_cpos, pos,
1691                                          clusters_to_alloc + extents_to_split,
1692                                          mmap_page);
1693         if (ret) {
1694                 mlog_errno(ret);
1695                 goto out_commit;
1696         }
1697
1698         ret = ocfs2_write_cluster_by_desc(mapping, data_ac, meta_ac, wc, pos,
1699                                           len);
1700         if (ret) {
1701                 mlog_errno(ret);
1702                 goto out_commit;
1703         }
1704
1705         if (data_ac)
1706                 ocfs2_free_alloc_context(data_ac);
1707         if (meta_ac)
1708                 ocfs2_free_alloc_context(meta_ac);
1709
1710 success:
1711         *pagep = wc->w_target_page;
1712         *fsdata = wc;
1713         return 0;
1714 out_commit:
1715         ocfs2_commit_trans(osb, handle);
1716
1717 out:
1718         ocfs2_free_write_ctxt(wc);
1719
1720         if (data_ac)
1721                 ocfs2_free_alloc_context(data_ac);
1722         if (meta_ac)
1723                 ocfs2_free_alloc_context(meta_ac);
1724         return ret;
1725 }
1726
1727 int ocfs2_write_begin(struct file *file, struct address_space *mapping,
1728                       loff_t pos, unsigned len, unsigned flags,
1729                       struct page **pagep, void **fsdata)
1730 {
1731         int ret;
1732         struct buffer_head *di_bh = NULL;
1733         struct inode *inode = mapping->host;
1734
1735         ret = ocfs2_meta_lock(inode, &di_bh, 1);
1736         if (ret) {
1737                 mlog_errno(ret);
1738                 return ret;
1739         }
1740
1741         /*
1742          * Take alloc sem here to prevent concurrent lookups. That way
1743          * the mapping, zeroing and tree manipulation within
1744          * ocfs2_write() will be safe against ->readpage(). This
1745          * should also serve to lock out allocation from a shared
1746          * writeable region.
1747          */
1748         down_write(&OCFS2_I(inode)->ip_alloc_sem);
1749
1750         ret = ocfs2_data_lock(inode, 1);
1751         if (ret) {
1752                 mlog_errno(ret);
1753                 goto out_fail;
1754         }
1755
1756         ret = ocfs2_write_begin_nolock(mapping, pos, len, flags, pagep,
1757                                        fsdata, di_bh, NULL);
1758         if (ret) {
1759                 mlog_errno(ret);
1760                 goto out_fail_data;
1761         }
1762
1763         brelse(di_bh);
1764
1765         return 0;
1766
1767 out_fail_data:
1768         ocfs2_data_unlock(inode, 1);
1769 out_fail:
1770         up_write(&OCFS2_I(inode)->ip_alloc_sem);
1771
1772         brelse(di_bh);
1773         ocfs2_meta_unlock(inode, 1);
1774
1775         return ret;
1776 }
1777
1778 static void ocfs2_write_end_inline(struct inode *inode, loff_t pos,
1779                                    unsigned len, unsigned *copied,
1780                                    struct ocfs2_dinode *di,
1781                                    struct ocfs2_write_ctxt *wc)
1782 {
1783         void *kaddr;
1784
1785         if (unlikely(*copied < len)) {
1786                 if (!PageUptodate(wc->w_target_page)) {
1787                         *copied = 0;
1788                         return;
1789                 }
1790         }
1791
1792         kaddr = kmap_atomic(wc->w_target_page, KM_USER0);
1793         memcpy(di->id2.i_data.id_data + pos, kaddr + pos, *copied);
1794         kunmap_atomic(kaddr, KM_USER0);
1795
1796         mlog(0, "Data written to inode at offset %llu. "
1797              "id_count = %u, copied = %u, i_dyn_features = 0x%x\n",
1798              (unsigned long long)pos, *copied,
1799              le16_to_cpu(di->id2.i_data.id_count),
1800              le16_to_cpu(di->i_dyn_features));
1801 }
1802
1803 int ocfs2_write_end_nolock(struct address_space *mapping,
1804                            loff_t pos, unsigned len, unsigned copied,
1805                            struct page *page, void *fsdata)
1806 {
1807         int i;
1808         unsigned from, to, start = pos & (PAGE_CACHE_SIZE - 1);
1809         struct inode *inode = mapping->host;
1810         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1811         struct ocfs2_write_ctxt *wc = fsdata;
1812         struct ocfs2_dinode *di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1813         handle_t *handle = wc->w_handle;
1814         struct page *tmppage;
1815
1816         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1817                 ocfs2_write_end_inline(inode, pos, len, &copied, di, wc);
1818                 goto out_write_size;
1819         }
1820
1821         if (unlikely(copied < len)) {
1822                 if (!PageUptodate(wc->w_target_page))
1823                         copied = 0;
1824
1825                 ocfs2_zero_new_buffers(wc->w_target_page, start+copied,
1826                                        start+len);
1827         }
1828         flush_dcache_page(wc->w_target_page);
1829
1830         for(i = 0; i < wc->w_num_pages; i++) {
1831                 tmppage = wc->w_pages[i];
1832
1833                 if (tmppage == wc->w_target_page) {
1834                         from = wc->w_target_from;
1835                         to = wc->w_target_to;
1836
1837                         BUG_ON(from > PAGE_CACHE_SIZE ||
1838                                to > PAGE_CACHE_SIZE ||
1839                                to < from);
1840                 } else {
1841                         /*
1842                          * Pages adjacent to the target (if any) imply
1843                          * a hole-filling write in which case we want
1844                          * to flush their entire range.
1845                          */
1846                         from = 0;
1847                         to = PAGE_CACHE_SIZE;
1848                 }
1849
1850                 if (ocfs2_should_order_data(inode))
1851                         walk_page_buffers(wc->w_handle, page_buffers(tmppage),
1852                                           from, to, NULL,
1853                                           ocfs2_journal_dirty_data);
1854
1855                 block_commit_write(tmppage, from, to);
1856         }
1857
1858 out_write_size:
1859         pos += copied;
1860         if (pos > inode->i_size) {
1861                 i_size_write(inode, pos);
1862                 mark_inode_dirty(inode);
1863         }
1864         inode->i_blocks = ocfs2_inode_sector_count(inode);
1865         di->i_size = cpu_to_le64((u64)i_size_read(inode));
1866         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1867         di->i_mtime = di->i_ctime = cpu_to_le64(inode->i_mtime.tv_sec);
1868         di->i_mtime_nsec = di->i_ctime_nsec = cpu_to_le32(inode->i_mtime.tv_nsec);
1869         ocfs2_journal_dirty(handle, wc->w_di_bh);
1870
1871         ocfs2_commit_trans(osb, handle);
1872
1873         ocfs2_run_deallocs(osb, &wc->w_dealloc);
1874
1875         ocfs2_free_write_ctxt(wc);
1876
1877         return copied;
1878 }
1879
1880 int ocfs2_write_end(struct file *file, struct address_space *mapping,
1881                     loff_t pos, unsigned len, unsigned copied,
1882                     struct page *page, void *fsdata)
1883 {
1884         int ret;
1885         struct inode *inode = mapping->host;
1886
1887         ret = ocfs2_write_end_nolock(mapping, pos, len, copied, page, fsdata);
1888
1889         ocfs2_data_unlock(inode, 1);
1890         up_write(&OCFS2_I(inode)->ip_alloc_sem);
1891         ocfs2_meta_unlock(inode, 1);
1892
1893         return ret;
1894 }
1895
1896 const struct address_space_operations ocfs2_aops = {
1897         .readpage       = ocfs2_readpage,
1898         .writepage      = ocfs2_writepage,
1899         .bmap           = ocfs2_bmap,
1900         .sync_page      = block_sync_page,
1901         .direct_IO      = ocfs2_direct_IO,
1902         .invalidatepage = ocfs2_invalidatepage,
1903         .releasepage    = ocfs2_releasepage,
1904         .migratepage    = buffer_migrate_page,
1905 };