Merge branch 'for-linus' of git://git.kernel.dk/linux-2.6-block
[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  * Nonsparse file systems fully allocate before we get to the write
733  * code. This prevents ocfs2_write() from tagging the write as an
734  * allocating one, which means ocfs2_map_page_blocks() might try to
735  * read-in the blocks at the tail of our file. Avoid reading them by
736  * testing i_size against each block offset.
737  */
738 static int ocfs2_should_read_blk(struct inode *inode, struct page *page,
739                                  unsigned int block_start)
740 {
741         u64 offset = page_offset(page) + block_start;
742
743         if (ocfs2_sparse_alloc(OCFS2_SB(inode->i_sb)))
744                 return 1;
745
746         if (i_size_read(inode) > offset)
747                 return 1;
748
749         return 0;
750 }
751
752 /*
753  * Some of this taken from block_prepare_write(). We already have our
754  * mapping by now though, and the entire write will be allocating or
755  * it won't, so not much need to use BH_New.
756  *
757  * This will also skip zeroing, which is handled externally.
758  */
759 int ocfs2_map_page_blocks(struct page *page, u64 *p_blkno,
760                           struct inode *inode, unsigned int from,
761                           unsigned int to, int new)
762 {
763         int ret = 0;
764         struct buffer_head *head, *bh, *wait[2], **wait_bh = wait;
765         unsigned int block_end, block_start;
766         unsigned int bsize = 1 << inode->i_blkbits;
767
768         if (!page_has_buffers(page))
769                 create_empty_buffers(page, bsize, 0);
770
771         head = page_buffers(page);
772         for (bh = head, block_start = 0; bh != head || !block_start;
773              bh = bh->b_this_page, block_start += bsize) {
774                 block_end = block_start + bsize;
775
776                 clear_buffer_new(bh);
777
778                 /*
779                  * Ignore blocks outside of our i/o range -
780                  * they may belong to unallocated clusters.
781                  */
782                 if (block_start >= to || block_end <= from) {
783                         if (PageUptodate(page))
784                                 set_buffer_uptodate(bh);
785                         continue;
786                 }
787
788                 /*
789                  * For an allocating write with cluster size >= page
790                  * size, we always write the entire page.
791                  */
792                 if (new)
793                         set_buffer_new(bh);
794
795                 if (!buffer_mapped(bh)) {
796                         map_bh(bh, inode->i_sb, *p_blkno);
797                         unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
798                 }
799
800                 if (PageUptodate(page)) {
801                         if (!buffer_uptodate(bh))
802                                 set_buffer_uptodate(bh);
803                 } else if (!buffer_uptodate(bh) && !buffer_delay(bh) &&
804                            !buffer_new(bh) &&
805                            ocfs2_should_read_blk(inode, page, block_start) &&
806                            (block_start < from || block_end > to)) {
807                         ll_rw_block(READ, 1, &bh);
808                         *wait_bh++=bh;
809                 }
810
811                 *p_blkno = *p_blkno + 1;
812         }
813
814         /*
815          * If we issued read requests - let them complete.
816          */
817         while(wait_bh > wait) {
818                 wait_on_buffer(*--wait_bh);
819                 if (!buffer_uptodate(*wait_bh))
820                         ret = -EIO;
821         }
822
823         if (ret == 0 || !new)
824                 return ret;
825
826         /*
827          * If we get -EIO above, zero out any newly allocated blocks
828          * to avoid exposing stale data.
829          */
830         bh = head;
831         block_start = 0;
832         do {
833                 block_end = block_start + bsize;
834                 if (block_end <= from)
835                         goto next_bh;
836                 if (block_start >= to)
837                         break;
838
839                 zero_user_page(page, block_start, bh->b_size, KM_USER0);
840                 set_buffer_uptodate(bh);
841                 mark_buffer_dirty(bh);
842
843 next_bh:
844                 block_start = block_end;
845                 bh = bh->b_this_page;
846         } while (bh != head);
847
848         return ret;
849 }
850
851 #if (PAGE_CACHE_SIZE >= OCFS2_MAX_CLUSTERSIZE)
852 #define OCFS2_MAX_CTXT_PAGES    1
853 #else
854 #define OCFS2_MAX_CTXT_PAGES    (OCFS2_MAX_CLUSTERSIZE / PAGE_CACHE_SIZE)
855 #endif
856
857 #define OCFS2_MAX_CLUSTERS_PER_PAGE     (PAGE_CACHE_SIZE / OCFS2_MIN_CLUSTERSIZE)
858
859 /*
860  * Describe the state of a single cluster to be written to.
861  */
862 struct ocfs2_write_cluster_desc {
863         u32             c_cpos;
864         u32             c_phys;
865         /*
866          * Give this a unique field because c_phys eventually gets
867          * filled.
868          */
869         unsigned        c_new;
870         unsigned        c_unwritten;
871 };
872
873 static inline int ocfs2_should_zero_cluster(struct ocfs2_write_cluster_desc *d)
874 {
875         return d->c_new || d->c_unwritten;
876 }
877
878 struct ocfs2_write_ctxt {
879         /* Logical cluster position / len of write */
880         u32                             w_cpos;
881         u32                             w_clen;
882
883         struct ocfs2_write_cluster_desc w_desc[OCFS2_MAX_CLUSTERS_PER_PAGE];
884
885         /*
886          * This is true if page_size > cluster_size.
887          *
888          * It triggers a set of special cases during write which might
889          * have to deal with allocating writes to partial pages.
890          */
891         unsigned int                    w_large_pages;
892
893         /*
894          * Pages involved in this write.
895          *
896          * w_target_page is the page being written to by the user.
897          *
898          * w_pages is an array of pages which always contains
899          * w_target_page, and in the case of an allocating write with
900          * page_size < cluster size, it will contain zero'd and mapped
901          * pages adjacent to w_target_page which need to be written
902          * out in so that future reads from that region will get
903          * zero's.
904          */
905         struct page                     *w_pages[OCFS2_MAX_CTXT_PAGES];
906         unsigned int                    w_num_pages;
907         struct page                     *w_target_page;
908
909         /*
910          * ocfs2_write_end() uses this to know what the real range to
911          * write in the target should be.
912          */
913         unsigned int                    w_target_from;
914         unsigned int                    w_target_to;
915
916         /*
917          * We could use journal_current_handle() but this is cleaner,
918          * IMHO -Mark
919          */
920         handle_t                        *w_handle;
921
922         struct buffer_head              *w_di_bh;
923
924         struct ocfs2_cached_dealloc_ctxt w_dealloc;
925 };
926
927 void ocfs2_unlock_and_free_pages(struct page **pages, int num_pages)
928 {
929         int i;
930
931         for(i = 0; i < num_pages; i++) {
932                 if (pages[i]) {
933                         unlock_page(pages[i]);
934                         mark_page_accessed(pages[i]);
935                         page_cache_release(pages[i]);
936                 }
937         }
938 }
939
940 static void ocfs2_free_write_ctxt(struct ocfs2_write_ctxt *wc)
941 {
942         ocfs2_unlock_and_free_pages(wc->w_pages, wc->w_num_pages);
943
944         brelse(wc->w_di_bh);
945         kfree(wc);
946 }
947
948 static int ocfs2_alloc_write_ctxt(struct ocfs2_write_ctxt **wcp,
949                                   struct ocfs2_super *osb, loff_t pos,
950                                   unsigned len, struct buffer_head *di_bh)
951 {
952         u32 cend;
953         struct ocfs2_write_ctxt *wc;
954
955         wc = kzalloc(sizeof(struct ocfs2_write_ctxt), GFP_NOFS);
956         if (!wc)
957                 return -ENOMEM;
958
959         wc->w_cpos = pos >> osb->s_clustersize_bits;
960         cend = (pos + len - 1) >> osb->s_clustersize_bits;
961         wc->w_clen = cend - wc->w_cpos + 1;
962         get_bh(di_bh);
963         wc->w_di_bh = di_bh;
964
965         if (unlikely(PAGE_CACHE_SHIFT > osb->s_clustersize_bits))
966                 wc->w_large_pages = 1;
967         else
968                 wc->w_large_pages = 0;
969
970         ocfs2_init_dealloc_ctxt(&wc->w_dealloc);
971
972         *wcp = wc;
973
974         return 0;
975 }
976
977 /*
978  * If a page has any new buffers, zero them out here, and mark them uptodate
979  * and dirty so they'll be written out (in order to prevent uninitialised
980  * block data from leaking). And clear the new bit.
981  */
982 static void ocfs2_zero_new_buffers(struct page *page, unsigned from, unsigned to)
983 {
984         unsigned int block_start, block_end;
985         struct buffer_head *head, *bh;
986
987         BUG_ON(!PageLocked(page));
988         if (!page_has_buffers(page))
989                 return;
990
991         bh = head = page_buffers(page);
992         block_start = 0;
993         do {
994                 block_end = block_start + bh->b_size;
995
996                 if (buffer_new(bh)) {
997                         if (block_end > from && block_start < to) {
998                                 if (!PageUptodate(page)) {
999                                         unsigned start, end;
1000
1001                                         start = max(from, block_start);
1002                                         end = min(to, block_end);
1003
1004                                         zero_user_page(page, start, end - start, KM_USER0);
1005                                         set_buffer_uptodate(bh);
1006                                 }
1007
1008                                 clear_buffer_new(bh);
1009                                 mark_buffer_dirty(bh);
1010                         }
1011                 }
1012
1013                 block_start = block_end;
1014                 bh = bh->b_this_page;
1015         } while (bh != head);
1016 }
1017
1018 /*
1019  * Only called when we have a failure during allocating write to write
1020  * zero's to the newly allocated region.
1021  */
1022 static void ocfs2_write_failure(struct inode *inode,
1023                                 struct ocfs2_write_ctxt *wc,
1024                                 loff_t user_pos, unsigned user_len)
1025 {
1026         int i;
1027         unsigned from = user_pos & (PAGE_CACHE_SIZE - 1),
1028                 to = user_pos + user_len;
1029         struct page *tmppage;
1030
1031         ocfs2_zero_new_buffers(wc->w_target_page, from, to);
1032
1033         for(i = 0; i < wc->w_num_pages; i++) {
1034                 tmppage = wc->w_pages[i];
1035
1036                 if (ocfs2_should_order_data(inode))
1037                         walk_page_buffers(wc->w_handle, page_buffers(tmppage),
1038                                           from, to, NULL,
1039                                           ocfs2_journal_dirty_data);
1040
1041                 block_commit_write(tmppage, from, to);
1042         }
1043 }
1044
1045 static int ocfs2_prepare_page_for_write(struct inode *inode, u64 *p_blkno,
1046                                         struct ocfs2_write_ctxt *wc,
1047                                         struct page *page, u32 cpos,
1048                                         loff_t user_pos, unsigned user_len,
1049                                         int new)
1050 {
1051         int ret;
1052         unsigned int map_from = 0, map_to = 0;
1053         unsigned int cluster_start, cluster_end;
1054         unsigned int user_data_from = 0, user_data_to = 0;
1055
1056         ocfs2_figure_cluster_boundaries(OCFS2_SB(inode->i_sb), cpos,
1057                                         &cluster_start, &cluster_end);
1058
1059         if (page == wc->w_target_page) {
1060                 map_from = user_pos & (PAGE_CACHE_SIZE - 1);
1061                 map_to = map_from + user_len;
1062
1063                 if (new)
1064                         ret = ocfs2_map_page_blocks(page, p_blkno, inode,
1065                                                     cluster_start, cluster_end,
1066                                                     new);
1067                 else
1068                         ret = ocfs2_map_page_blocks(page, p_blkno, inode,
1069                                                     map_from, map_to, new);
1070                 if (ret) {
1071                         mlog_errno(ret);
1072                         goto out;
1073                 }
1074
1075                 user_data_from = map_from;
1076                 user_data_to = map_to;
1077                 if (new) {
1078                         map_from = cluster_start;
1079                         map_to = cluster_end;
1080                 }
1081         } else {
1082                 /*
1083                  * If we haven't allocated the new page yet, we
1084                  * shouldn't be writing it out without copying user
1085                  * data. This is likely a math error from the caller.
1086                  */
1087                 BUG_ON(!new);
1088
1089                 map_from = cluster_start;
1090                 map_to = cluster_end;
1091
1092                 ret = ocfs2_map_page_blocks(page, p_blkno, inode,
1093                                             cluster_start, cluster_end, new);
1094                 if (ret) {
1095                         mlog_errno(ret);
1096                         goto out;
1097                 }
1098         }
1099
1100         /*
1101          * Parts of newly allocated pages need to be zero'd.
1102          *
1103          * Above, we have also rewritten 'to' and 'from' - as far as
1104          * the rest of the function is concerned, the entire cluster
1105          * range inside of a page needs to be written.
1106          *
1107          * We can skip this if the page is up to date - it's already
1108          * been zero'd from being read in as a hole.
1109          */
1110         if (new && !PageUptodate(page))
1111                 ocfs2_clear_page_regions(page, OCFS2_SB(inode->i_sb),
1112                                          cpos, user_data_from, user_data_to);
1113
1114         flush_dcache_page(page);
1115
1116 out:
1117         return ret;
1118 }
1119
1120 /*
1121  * This function will only grab one clusters worth of pages.
1122  */
1123 static int ocfs2_grab_pages_for_write(struct address_space *mapping,
1124                                       struct ocfs2_write_ctxt *wc,
1125                                       u32 cpos, loff_t user_pos, int new,
1126                                       struct page *mmap_page)
1127 {
1128         int ret = 0, i;
1129         unsigned long start, target_index, index;
1130         struct inode *inode = mapping->host;
1131
1132         target_index = user_pos >> PAGE_CACHE_SHIFT;
1133
1134         /*
1135          * Figure out how many pages we'll be manipulating here. For
1136          * non allocating write, we just change the one
1137          * page. Otherwise, we'll need a whole clusters worth.
1138          */
1139         if (new) {
1140                 wc->w_num_pages = ocfs2_pages_per_cluster(inode->i_sb);
1141                 start = ocfs2_align_clusters_to_page_index(inode->i_sb, cpos);
1142         } else {
1143                 wc->w_num_pages = 1;
1144                 start = target_index;
1145         }
1146
1147         for(i = 0; i < wc->w_num_pages; i++) {
1148                 index = start + i;
1149
1150                 if (index == target_index && mmap_page) {
1151                         /*
1152                          * ocfs2_pagemkwrite() is a little different
1153                          * and wants us to directly use the page
1154                          * passed in.
1155                          */
1156                         lock_page(mmap_page);
1157
1158                         if (mmap_page->mapping != mapping) {
1159                                 unlock_page(mmap_page);
1160                                 /*
1161                                  * Sanity check - the locking in
1162                                  * ocfs2_pagemkwrite() should ensure
1163                                  * that this code doesn't trigger.
1164                                  */
1165                                 ret = -EINVAL;
1166                                 mlog_errno(ret);
1167                                 goto out;
1168                         }
1169
1170                         page_cache_get(mmap_page);
1171                         wc->w_pages[i] = mmap_page;
1172                 } else {
1173                         wc->w_pages[i] = find_or_create_page(mapping, index,
1174                                                              GFP_NOFS);
1175                         if (!wc->w_pages[i]) {
1176                                 ret = -ENOMEM;
1177                                 mlog_errno(ret);
1178                                 goto out;
1179                         }
1180                 }
1181
1182                 if (index == target_index)
1183                         wc->w_target_page = wc->w_pages[i];
1184         }
1185 out:
1186         return ret;
1187 }
1188
1189 /*
1190  * Prepare a single cluster for write one cluster into the file.
1191  */
1192 static int ocfs2_write_cluster(struct address_space *mapping,
1193                                u32 phys, unsigned int unwritten,
1194                                struct ocfs2_alloc_context *data_ac,
1195                                struct ocfs2_alloc_context *meta_ac,
1196                                struct ocfs2_write_ctxt *wc, u32 cpos,
1197                                loff_t user_pos, unsigned user_len)
1198 {
1199         int ret, i, new, should_zero = 0;
1200         u64 v_blkno, p_blkno;
1201         struct inode *inode = mapping->host;
1202
1203         new = phys == 0 ? 1 : 0;
1204         if (new || unwritten)
1205                 should_zero = 1;
1206
1207         if (new) {
1208                 u32 tmp_pos;
1209
1210                 /*
1211                  * This is safe to call with the page locks - it won't take
1212                  * any additional semaphores or cluster locks.
1213                  */
1214                 tmp_pos = cpos;
1215                 ret = ocfs2_do_extend_allocation(OCFS2_SB(inode->i_sb), inode,
1216                                                  &tmp_pos, 1, 0, wc->w_di_bh,
1217                                                  wc->w_handle, data_ac,
1218                                                  meta_ac, NULL);
1219                 /*
1220                  * This shouldn't happen because we must have already
1221                  * calculated the correct meta data allocation required. The
1222                  * internal tree allocation code should know how to increase
1223                  * transaction credits itself.
1224                  *
1225                  * If need be, we could handle -EAGAIN for a
1226                  * RESTART_TRANS here.
1227                  */
1228                 mlog_bug_on_msg(ret == -EAGAIN,
1229                                 "Inode %llu: EAGAIN return during allocation.\n",
1230                                 (unsigned long long)OCFS2_I(inode)->ip_blkno);
1231                 if (ret < 0) {
1232                         mlog_errno(ret);
1233                         goto out;
1234                 }
1235         } else if (unwritten) {
1236                 ret = ocfs2_mark_extent_written(inode, wc->w_di_bh,
1237                                                 wc->w_handle, cpos, 1, phys,
1238                                                 meta_ac, &wc->w_dealloc);
1239                 if (ret < 0) {
1240                         mlog_errno(ret);
1241                         goto out;
1242                 }
1243         }
1244
1245         if (should_zero)
1246                 v_blkno = ocfs2_clusters_to_blocks(inode->i_sb, cpos);
1247         else
1248                 v_blkno = user_pos >> inode->i_sb->s_blocksize_bits;
1249
1250         /*
1251          * The only reason this should fail is due to an inability to
1252          * find the extent added.
1253          */
1254         ret = ocfs2_extent_map_get_blocks(inode, v_blkno, &p_blkno, NULL,
1255                                           NULL);
1256         if (ret < 0) {
1257                 ocfs2_error(inode->i_sb, "Corrupting extend for inode %llu, "
1258                             "at logical block %llu",
1259                             (unsigned long long)OCFS2_I(inode)->ip_blkno,
1260                             (unsigned long long)v_blkno);
1261                 goto out;
1262         }
1263
1264         BUG_ON(p_blkno == 0);
1265
1266         for(i = 0; i < wc->w_num_pages; i++) {
1267                 int tmpret;
1268
1269                 tmpret = ocfs2_prepare_page_for_write(inode, &p_blkno, wc,
1270                                                       wc->w_pages[i], cpos,
1271                                                       user_pos, user_len,
1272                                                       should_zero);
1273                 if (tmpret) {
1274                         mlog_errno(tmpret);
1275                         if (ret == 0)
1276                                 tmpret = ret;
1277                 }
1278         }
1279
1280         /*
1281          * We only have cleanup to do in case of allocating write.
1282          */
1283         if (ret && new)
1284                 ocfs2_write_failure(inode, wc, user_pos, user_len);
1285
1286 out:
1287
1288         return ret;
1289 }
1290
1291 static int ocfs2_write_cluster_by_desc(struct address_space *mapping,
1292                                        struct ocfs2_alloc_context *data_ac,
1293                                        struct ocfs2_alloc_context *meta_ac,
1294                                        struct ocfs2_write_ctxt *wc,
1295                                        loff_t pos, unsigned len)
1296 {
1297         int ret, i;
1298         loff_t cluster_off;
1299         unsigned int local_len = len;
1300         struct ocfs2_write_cluster_desc *desc;
1301         struct ocfs2_super *osb = OCFS2_SB(mapping->host->i_sb);
1302
1303         for (i = 0; i < wc->w_clen; i++) {
1304                 desc = &wc->w_desc[i];
1305
1306                 /*
1307                  * We have to make sure that the total write passed in
1308                  * doesn't extend past a single cluster.
1309                  */
1310                 local_len = len;
1311                 cluster_off = pos & (osb->s_clustersize - 1);
1312                 if ((cluster_off + local_len) > osb->s_clustersize)
1313                         local_len = osb->s_clustersize - cluster_off;
1314
1315                 ret = ocfs2_write_cluster(mapping, desc->c_phys,
1316                                           desc->c_unwritten, data_ac, meta_ac,
1317                                           wc, desc->c_cpos, pos, local_len);
1318                 if (ret) {
1319                         mlog_errno(ret);
1320                         goto out;
1321                 }
1322
1323                 len -= local_len;
1324                 pos += local_len;
1325         }
1326
1327         ret = 0;
1328 out:
1329         return ret;
1330 }
1331
1332 /*
1333  * ocfs2_write_end() wants to know which parts of the target page it
1334  * should complete the write on. It's easiest to compute them ahead of
1335  * time when a more complete view of the write is available.
1336  */
1337 static void ocfs2_set_target_boundaries(struct ocfs2_super *osb,
1338                                         struct ocfs2_write_ctxt *wc,
1339                                         loff_t pos, unsigned len, int alloc)
1340 {
1341         struct ocfs2_write_cluster_desc *desc;
1342
1343         wc->w_target_from = pos & (PAGE_CACHE_SIZE - 1);
1344         wc->w_target_to = wc->w_target_from + len;
1345
1346         if (alloc == 0)
1347                 return;
1348
1349         /*
1350          * Allocating write - we may have different boundaries based
1351          * on page size and cluster size.
1352          *
1353          * NOTE: We can no longer compute one value from the other as
1354          * the actual write length and user provided length may be
1355          * different.
1356          */
1357
1358         if (wc->w_large_pages) {
1359                 /*
1360                  * We only care about the 1st and last cluster within
1361                  * our range and whether they should be zero'd or not. Either
1362                  * value may be extended out to the start/end of a
1363                  * newly allocated cluster.
1364                  */
1365                 desc = &wc->w_desc[0];
1366                 if (ocfs2_should_zero_cluster(desc))
1367                         ocfs2_figure_cluster_boundaries(osb,
1368                                                         desc->c_cpos,
1369                                                         &wc->w_target_from,
1370                                                         NULL);
1371
1372                 desc = &wc->w_desc[wc->w_clen - 1];
1373                 if (ocfs2_should_zero_cluster(desc))
1374                         ocfs2_figure_cluster_boundaries(osb,
1375                                                         desc->c_cpos,
1376                                                         NULL,
1377                                                         &wc->w_target_to);
1378         } else {
1379                 wc->w_target_from = 0;
1380                 wc->w_target_to = PAGE_CACHE_SIZE;
1381         }
1382 }
1383
1384 /*
1385  * Populate each single-cluster write descriptor in the write context
1386  * with information about the i/o to be done.
1387  *
1388  * Returns the number of clusters that will have to be allocated, as
1389  * well as a worst case estimate of the number of extent records that
1390  * would have to be created during a write to an unwritten region.
1391  */
1392 static int ocfs2_populate_write_desc(struct inode *inode,
1393                                      struct ocfs2_write_ctxt *wc,
1394                                      unsigned int *clusters_to_alloc,
1395                                      unsigned int *extents_to_split)
1396 {
1397         int ret;
1398         struct ocfs2_write_cluster_desc *desc;
1399         unsigned int num_clusters = 0;
1400         unsigned int ext_flags = 0;
1401         u32 phys = 0;
1402         int i;
1403
1404         *clusters_to_alloc = 0;
1405         *extents_to_split = 0;
1406
1407         for (i = 0; i < wc->w_clen; i++) {
1408                 desc = &wc->w_desc[i];
1409                 desc->c_cpos = wc->w_cpos + i;
1410
1411                 if (num_clusters == 0) {
1412                         /*
1413                          * Need to look up the next extent record.
1414                          */
1415                         ret = ocfs2_get_clusters(inode, desc->c_cpos, &phys,
1416                                                  &num_clusters, &ext_flags);
1417                         if (ret) {
1418                                 mlog_errno(ret);
1419                                 goto out;
1420                         }
1421
1422                         /*
1423                          * Assume worst case - that we're writing in
1424                          * the middle of the extent.
1425                          *
1426                          * We can assume that the write proceeds from
1427                          * left to right, in which case the extent
1428                          * insert code is smart enough to coalesce the
1429                          * next splits into the previous records created.
1430                          */
1431                         if (ext_flags & OCFS2_EXT_UNWRITTEN)
1432                                 *extents_to_split = *extents_to_split + 2;
1433                 } else if (phys) {
1434                         /*
1435                          * Only increment phys if it doesn't describe
1436                          * a hole.
1437                          */
1438                         phys++;
1439                 }
1440
1441                 desc->c_phys = phys;
1442                 if (phys == 0) {
1443                         desc->c_new = 1;
1444                         *clusters_to_alloc = *clusters_to_alloc + 1;
1445                 }
1446                 if (ext_flags & OCFS2_EXT_UNWRITTEN)
1447                         desc->c_unwritten = 1;
1448
1449                 num_clusters--;
1450         }
1451
1452         ret = 0;
1453 out:
1454         return ret;
1455 }
1456
1457 static int ocfs2_write_begin_inline(struct address_space *mapping,
1458                                     struct inode *inode,
1459                                     struct ocfs2_write_ctxt *wc)
1460 {
1461         int ret;
1462         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1463         struct page *page;
1464         handle_t *handle;
1465         struct ocfs2_dinode *di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1466
1467         page = find_or_create_page(mapping, 0, GFP_NOFS);
1468         if (!page) {
1469                 ret = -ENOMEM;
1470                 mlog_errno(ret);
1471                 goto out;
1472         }
1473         /*
1474          * If we don't set w_num_pages then this page won't get unlocked
1475          * and freed on cleanup of the write context.
1476          */
1477         wc->w_pages[0] = wc->w_target_page = page;
1478         wc->w_num_pages = 1;
1479
1480         handle = ocfs2_start_trans(osb, OCFS2_INODE_UPDATE_CREDITS);
1481         if (IS_ERR(handle)) {
1482                 ret = PTR_ERR(handle);
1483                 mlog_errno(ret);
1484                 goto out;
1485         }
1486
1487         ret = ocfs2_journal_access(handle, inode, wc->w_di_bh,
1488                                    OCFS2_JOURNAL_ACCESS_WRITE);
1489         if (ret) {
1490                 ocfs2_commit_trans(osb, handle);
1491
1492                 mlog_errno(ret);
1493                 goto out;
1494         }
1495
1496         if (!(OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL))
1497                 ocfs2_set_inode_data_inline(inode, di);
1498
1499         if (!PageUptodate(page)) {
1500                 ret = ocfs2_read_inline_data(inode, page, wc->w_di_bh);
1501                 if (ret) {
1502                         ocfs2_commit_trans(osb, handle);
1503
1504                         goto out;
1505                 }
1506         }
1507
1508         wc->w_handle = handle;
1509 out:
1510         return ret;
1511 }
1512
1513 int ocfs2_size_fits_inline_data(struct buffer_head *di_bh, u64 new_size)
1514 {
1515         struct ocfs2_dinode *di = (struct ocfs2_dinode *)di_bh->b_data;
1516
1517         if (new_size < le16_to_cpu(di->id2.i_data.id_count))
1518                 return 1;
1519         return 0;
1520 }
1521
1522 static int ocfs2_try_to_write_inline_data(struct address_space *mapping,
1523                                           struct inode *inode, loff_t pos,
1524                                           unsigned len, struct page *mmap_page,
1525                                           struct ocfs2_write_ctxt *wc)
1526 {
1527         int ret, written = 0;
1528         loff_t end = pos + len;
1529         struct ocfs2_inode_info *oi = OCFS2_I(inode);
1530
1531         mlog(0, "Inode %llu, write of %u bytes at off %llu. features: 0x%x\n",
1532              (unsigned long long)oi->ip_blkno, len, (unsigned long long)pos,
1533              oi->ip_dyn_features);
1534
1535         /*
1536          * Handle inodes which already have inline data 1st.
1537          */
1538         if (oi->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1539                 if (mmap_page == NULL &&
1540                     ocfs2_size_fits_inline_data(wc->w_di_bh, end))
1541                         goto do_inline_write;
1542
1543                 /*
1544                  * The write won't fit - we have to give this inode an
1545                  * inline extent list now.
1546                  */
1547                 ret = ocfs2_convert_inline_data_to_extents(inode, wc->w_di_bh);
1548                 if (ret)
1549                         mlog_errno(ret);
1550                 goto out;
1551         }
1552
1553         /*
1554          * Check whether the inode can accept inline data.
1555          */
1556         if (oi->ip_clusters != 0 || i_size_read(inode) != 0)
1557                 return 0;
1558
1559         /*
1560          * Check whether the write can fit.
1561          */
1562         if (mmap_page || end > ocfs2_max_inline_data(inode->i_sb))
1563                 return 0;
1564
1565 do_inline_write:
1566         ret = ocfs2_write_begin_inline(mapping, inode, wc);
1567         if (ret) {
1568                 mlog_errno(ret);
1569                 goto out;
1570         }
1571
1572         /*
1573          * This signals to the caller that the data can be written
1574          * inline.
1575          */
1576         written = 1;
1577 out:
1578         return written ? written : ret;
1579 }
1580
1581 /*
1582  * This function only does anything for file systems which can't
1583  * handle sparse files.
1584  *
1585  * What we want to do here is fill in any hole between the current end
1586  * of allocation and the end of our write. That way the rest of the
1587  * write path can treat it as an non-allocating write, which has no
1588  * special case code for sparse/nonsparse files.
1589  */
1590 static int ocfs2_expand_nonsparse_inode(struct inode *inode, loff_t pos,
1591                                         unsigned len,
1592                                         struct ocfs2_write_ctxt *wc)
1593 {
1594         int ret;
1595         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1596         loff_t newsize = pos + len;
1597
1598         if (ocfs2_sparse_alloc(osb))
1599                 return 0;
1600
1601         if (newsize <= i_size_read(inode))
1602                 return 0;
1603
1604         ret = ocfs2_extend_no_holes(inode, newsize, newsize - len);
1605         if (ret)
1606                 mlog_errno(ret);
1607
1608         return ret;
1609 }
1610
1611 int ocfs2_write_begin_nolock(struct address_space *mapping,
1612                              loff_t pos, unsigned len, unsigned flags,
1613                              struct page **pagep, void **fsdata,
1614                              struct buffer_head *di_bh, struct page *mmap_page)
1615 {
1616         int ret, credits = OCFS2_INODE_UPDATE_CREDITS;
1617         unsigned int clusters_to_alloc, extents_to_split;
1618         struct ocfs2_write_ctxt *wc;
1619         struct inode *inode = mapping->host;
1620         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1621         struct ocfs2_dinode *di;
1622         struct ocfs2_alloc_context *data_ac = NULL;
1623         struct ocfs2_alloc_context *meta_ac = NULL;
1624         handle_t *handle;
1625
1626         ret = ocfs2_alloc_write_ctxt(&wc, osb, pos, len, di_bh);
1627         if (ret) {
1628                 mlog_errno(ret);
1629                 return ret;
1630         }
1631
1632         if (ocfs2_supports_inline_data(osb)) {
1633                 ret = ocfs2_try_to_write_inline_data(mapping, inode, pos, len,
1634                                                      mmap_page, wc);
1635                 if (ret == 1) {
1636                         ret = 0;
1637                         goto success;
1638                 }
1639                 if (ret < 0) {
1640                         mlog_errno(ret);
1641                         goto out;
1642                 }
1643         }
1644
1645         ret = ocfs2_expand_nonsparse_inode(inode, pos, len, wc);
1646         if (ret) {
1647                 mlog_errno(ret);
1648                 goto out;
1649         }
1650
1651         ret = ocfs2_populate_write_desc(inode, wc, &clusters_to_alloc,
1652                                         &extents_to_split);
1653         if (ret) {
1654                 mlog_errno(ret);
1655                 goto out;
1656         }
1657
1658         di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1659
1660         /*
1661          * We set w_target_from, w_target_to here so that
1662          * ocfs2_write_end() knows which range in the target page to
1663          * write out. An allocation requires that we write the entire
1664          * cluster range.
1665          */
1666         if (clusters_to_alloc || extents_to_split) {
1667                 /*
1668                  * XXX: We are stretching the limits of
1669                  * ocfs2_lock_allocators(). It greatly over-estimates
1670                  * the work to be done.
1671                  */
1672                 ret = ocfs2_lock_allocators(inode, di, clusters_to_alloc,
1673                                             extents_to_split, &data_ac, &meta_ac);
1674                 if (ret) {
1675                         mlog_errno(ret);
1676                         goto out;
1677                 }
1678
1679                 credits = ocfs2_calc_extend_credits(inode->i_sb, di,
1680                                                     clusters_to_alloc);
1681
1682         }
1683
1684         ocfs2_set_target_boundaries(osb, wc, pos, len,
1685                                     clusters_to_alloc + extents_to_split);
1686
1687         handle = ocfs2_start_trans(osb, credits);
1688         if (IS_ERR(handle)) {
1689                 ret = PTR_ERR(handle);
1690                 mlog_errno(ret);
1691                 goto out;
1692         }
1693
1694         wc->w_handle = handle;
1695
1696         /*
1697          * We don't want this to fail in ocfs2_write_end(), so do it
1698          * here.
1699          */
1700         ret = ocfs2_journal_access(handle, inode, wc->w_di_bh,
1701                                    OCFS2_JOURNAL_ACCESS_WRITE);
1702         if (ret) {
1703                 mlog_errno(ret);
1704                 goto out_commit;
1705         }
1706
1707         /*
1708          * Fill our page array first. That way we've grabbed enough so
1709          * that we can zero and flush if we error after adding the
1710          * extent.
1711          */
1712         ret = ocfs2_grab_pages_for_write(mapping, wc, wc->w_cpos, pos,
1713                                          clusters_to_alloc + extents_to_split,
1714                                          mmap_page);
1715         if (ret) {
1716                 mlog_errno(ret);
1717                 goto out_commit;
1718         }
1719
1720         ret = ocfs2_write_cluster_by_desc(mapping, data_ac, meta_ac, wc, pos,
1721                                           len);
1722         if (ret) {
1723                 mlog_errno(ret);
1724                 goto out_commit;
1725         }
1726
1727         if (data_ac)
1728                 ocfs2_free_alloc_context(data_ac);
1729         if (meta_ac)
1730                 ocfs2_free_alloc_context(meta_ac);
1731
1732 success:
1733         *pagep = wc->w_target_page;
1734         *fsdata = wc;
1735         return 0;
1736 out_commit:
1737         ocfs2_commit_trans(osb, handle);
1738
1739 out:
1740         ocfs2_free_write_ctxt(wc);
1741
1742         if (data_ac)
1743                 ocfs2_free_alloc_context(data_ac);
1744         if (meta_ac)
1745                 ocfs2_free_alloc_context(meta_ac);
1746         return ret;
1747 }
1748
1749 static int ocfs2_write_begin(struct file *file, struct address_space *mapping,
1750                              loff_t pos, unsigned len, unsigned flags,
1751                              struct page **pagep, void **fsdata)
1752 {
1753         int ret;
1754         struct buffer_head *di_bh = NULL;
1755         struct inode *inode = mapping->host;
1756
1757         ret = ocfs2_meta_lock(inode, &di_bh, 1);
1758         if (ret) {
1759                 mlog_errno(ret);
1760                 return ret;
1761         }
1762
1763         /*
1764          * Take alloc sem here to prevent concurrent lookups. That way
1765          * the mapping, zeroing and tree manipulation within
1766          * ocfs2_write() will be safe against ->readpage(). This
1767          * should also serve to lock out allocation from a shared
1768          * writeable region.
1769          */
1770         down_write(&OCFS2_I(inode)->ip_alloc_sem);
1771
1772         ret = ocfs2_data_lock(inode, 1);
1773         if (ret) {
1774                 mlog_errno(ret);
1775                 goto out_fail;
1776         }
1777
1778         ret = ocfs2_write_begin_nolock(mapping, pos, len, flags, pagep,
1779                                        fsdata, di_bh, NULL);
1780         if (ret) {
1781                 mlog_errno(ret);
1782                 goto out_fail_data;
1783         }
1784
1785         brelse(di_bh);
1786
1787         return 0;
1788
1789 out_fail_data:
1790         ocfs2_data_unlock(inode, 1);
1791 out_fail:
1792         up_write(&OCFS2_I(inode)->ip_alloc_sem);
1793
1794         brelse(di_bh);
1795         ocfs2_meta_unlock(inode, 1);
1796
1797         return ret;
1798 }
1799
1800 static void ocfs2_write_end_inline(struct inode *inode, loff_t pos,
1801                                    unsigned len, unsigned *copied,
1802                                    struct ocfs2_dinode *di,
1803                                    struct ocfs2_write_ctxt *wc)
1804 {
1805         void *kaddr;
1806
1807         if (unlikely(*copied < len)) {
1808                 if (!PageUptodate(wc->w_target_page)) {
1809                         *copied = 0;
1810                         return;
1811                 }
1812         }
1813
1814         kaddr = kmap_atomic(wc->w_target_page, KM_USER0);
1815         memcpy(di->id2.i_data.id_data + pos, kaddr + pos, *copied);
1816         kunmap_atomic(kaddr, KM_USER0);
1817
1818         mlog(0, "Data written to inode at offset %llu. "
1819              "id_count = %u, copied = %u, i_dyn_features = 0x%x\n",
1820              (unsigned long long)pos, *copied,
1821              le16_to_cpu(di->id2.i_data.id_count),
1822              le16_to_cpu(di->i_dyn_features));
1823 }
1824
1825 int ocfs2_write_end_nolock(struct address_space *mapping,
1826                            loff_t pos, unsigned len, unsigned copied,
1827                            struct page *page, void *fsdata)
1828 {
1829         int i;
1830         unsigned from, to, start = pos & (PAGE_CACHE_SIZE - 1);
1831         struct inode *inode = mapping->host;
1832         struct ocfs2_super *osb = OCFS2_SB(inode->i_sb);
1833         struct ocfs2_write_ctxt *wc = fsdata;
1834         struct ocfs2_dinode *di = (struct ocfs2_dinode *)wc->w_di_bh->b_data;
1835         handle_t *handle = wc->w_handle;
1836         struct page *tmppage;
1837
1838         if (OCFS2_I(inode)->ip_dyn_features & OCFS2_INLINE_DATA_FL) {
1839                 ocfs2_write_end_inline(inode, pos, len, &copied, di, wc);
1840                 goto out_write_size;
1841         }
1842
1843         if (unlikely(copied < len)) {
1844                 if (!PageUptodate(wc->w_target_page))
1845                         copied = 0;
1846
1847                 ocfs2_zero_new_buffers(wc->w_target_page, start+copied,
1848                                        start+len);
1849         }
1850         flush_dcache_page(wc->w_target_page);
1851
1852         for(i = 0; i < wc->w_num_pages; i++) {
1853                 tmppage = wc->w_pages[i];
1854
1855                 if (tmppage == wc->w_target_page) {
1856                         from = wc->w_target_from;
1857                         to = wc->w_target_to;
1858
1859                         BUG_ON(from > PAGE_CACHE_SIZE ||
1860                                to > PAGE_CACHE_SIZE ||
1861                                to < from);
1862                 } else {
1863                         /*
1864                          * Pages adjacent to the target (if any) imply
1865                          * a hole-filling write in which case we want
1866                          * to flush their entire range.
1867                          */
1868                         from = 0;
1869                         to = PAGE_CACHE_SIZE;
1870                 }
1871
1872                 if (ocfs2_should_order_data(inode))
1873                         walk_page_buffers(wc->w_handle, page_buffers(tmppage),
1874                                           from, to, NULL,
1875                                           ocfs2_journal_dirty_data);
1876
1877                 block_commit_write(tmppage, from, to);
1878         }
1879
1880 out_write_size:
1881         pos += copied;
1882         if (pos > inode->i_size) {
1883                 i_size_write(inode, pos);
1884                 mark_inode_dirty(inode);
1885         }
1886         inode->i_blocks = ocfs2_inode_sector_count(inode);
1887         di->i_size = cpu_to_le64((u64)i_size_read(inode));
1888         inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1889         di->i_mtime = di->i_ctime = cpu_to_le64(inode->i_mtime.tv_sec);
1890         di->i_mtime_nsec = di->i_ctime_nsec = cpu_to_le32(inode->i_mtime.tv_nsec);
1891         ocfs2_journal_dirty(handle, wc->w_di_bh);
1892
1893         ocfs2_commit_trans(osb, handle);
1894
1895         ocfs2_run_deallocs(osb, &wc->w_dealloc);
1896
1897         ocfs2_free_write_ctxt(wc);
1898
1899         return copied;
1900 }
1901
1902 static int ocfs2_write_end(struct file *file, struct address_space *mapping,
1903                            loff_t pos, unsigned len, unsigned copied,
1904                            struct page *page, void *fsdata)
1905 {
1906         int ret;
1907         struct inode *inode = mapping->host;
1908
1909         ret = ocfs2_write_end_nolock(mapping, pos, len, copied, page, fsdata);
1910
1911         ocfs2_data_unlock(inode, 1);
1912         up_write(&OCFS2_I(inode)->ip_alloc_sem);
1913         ocfs2_meta_unlock(inode, 1);
1914
1915         return ret;
1916 }
1917
1918 const struct address_space_operations ocfs2_aops = {
1919         .readpage       = ocfs2_readpage,
1920         .writepage      = ocfs2_writepage,
1921         .write_begin    = ocfs2_write_begin,
1922         .write_end      = ocfs2_write_end,
1923         .bmap           = ocfs2_bmap,
1924         .sync_page      = block_sync_page,
1925         .direct_IO      = ocfs2_direct_IO,
1926         .invalidatepage = ocfs2_invalidatepage,
1927         .releasepage    = ocfs2_releasepage,
1928         .migratepage    = buffer_migrate_page,
1929 };