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