Blame view

fs/ntfs/file.c 60.6 KB
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1
  /*
f25dfb5e4   Anton Altaparmakov   NTFS: Remove bogu...
2
   * file.c - NTFS kernel file operations.  Part of the Linux-NTFS project.
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
3
   *
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
4
   * Copyright (c) 2001-2015 Anton Altaparmakov and Tuxera Inc.
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
   *
   * This program/include file is free software; you can redistribute it and/or
   * modify it under the terms of the GNU General Public License as published
   * by the Free Software Foundation; either version 2 of the License, or
   * (at your option) any later version.
   *
   * This program/include file is distributed in the hope that it will be
   * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
   * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with this program (in the main directory of the Linux-NTFS
   * distribution in the file COPYING); if not, write to the Free Software
   * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   */
de1414a65   Christoph Hellwig   fs: export inode_...
21
  #include <linux/backing-dev.h>
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
22
  #include <linux/buffer_head.h>
5a0e3ad6a   Tejun Heo   include cleanup: ...
23
  #include <linux/gfp.h>
98b270362   Anton Altaparmakov   NTFS: The big ntf...
24
25
  #include <linux/pagemap.h>
  #include <linux/pagevec.h>
174cd4b1e   Ingo Molnar   sched/headers: Pr...
26
  #include <linux/sched/signal.h>
98b270362   Anton Altaparmakov   NTFS: The big ntf...
27
28
29
  #include <linux/swap.h>
  #include <linux/uio.h>
  #include <linux/writeback.h>
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
30

98b270362   Anton Altaparmakov   NTFS: The big ntf...
31
  #include <asm/page.h>
7c0f6ba68   Linus Torvalds   Replace <asm/uacc...
32
  #include <linux/uaccess.h>
98b270362   Anton Altaparmakov   NTFS: The big ntf...
33
34
35
  
  #include "attrib.h"
  #include "bitmap.h"
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
36
37
  #include "inode.h"
  #include "debug.h"
98b270362   Anton Altaparmakov   NTFS: The big ntf...
38
39
40
  #include "lcnalloc.h"
  #include "malloc.h"
  #include "mft.h"
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
  #include "ntfs.h"
  
  /**
   * ntfs_file_open - called when an inode is about to be opened
   * @vi:		inode to be opened
   * @filp:	file structure describing the inode
   *
   * Limit file size to the page cache limit on architectures where unsigned long
   * is 32-bits. This is the most we can do for now without overflowing the page
   * cache page index. Doing it this way means we don't run into problems because
   * of existing too large files. It would be better to allow the user to read
   * the beginning of the file but I doubt very much anyone is going to hit this
   * check on a 32-bit architecture, so there is no point in adding the extra
   * complexity required to support this.
   *
   * On 64-bit architectures, the check is hopefully optimized away by the
   * compiler.
   *
   * After the check passes, just call generic_file_open() to do its work.
   */
  static int ntfs_file_open(struct inode *vi, struct file *filp)
  {
  	if (sizeof(unsigned long) < 8) {
d4b9ba7bf   Anton Altaparmakov   NTFS: Use i_size_...
64
  		if (i_size_read(vi) > MAX_LFS_FILESIZE)
a9c62a18a   Alan Cox   fs: correct SuS c...
65
  			return -EOVERFLOW;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
66
67
68
69
70
71
72
  	}
  	return generic_file_open(vi, filp);
  }
  
  #ifdef NTFS_RW
  
  /**
98b270362   Anton Altaparmakov   NTFS: The big ntf...
73
74
75
   * ntfs_attr_extend_initialized - extend the initialized size of an attribute
   * @ni:			ntfs inode of the attribute to extend
   * @new_init_size:	requested new initialized size in bytes
98b270362   Anton Altaparmakov   NTFS: The big ntf...
76
77
78
79
   *
   * Extend the initialized size of an attribute described by the ntfs inode @ni
   * to @new_init_size bytes.  This involves zeroing any non-sparse space between
   * the old initialized size and @new_init_size both in the page cache and on
dda65b941   Anton Altaparmakov   NTFS: Fix compila...
80
81
   * disk (if relevant complete pages are already uptodate in the page cache then
   * these are simply marked dirty).
98b270362   Anton Altaparmakov   NTFS: The big ntf...
82
83
84
85
86
87
88
89
90
91
92
93
94
95
   *
   * As a side-effect, the file size (vfs inode->i_size) may be incremented as,
   * in the resident attribute case, it is tied to the initialized size and, in
   * the non-resident attribute case, it may not fall below the initialized size.
   *
   * Note that if the attribute is resident, we do not need to touch the page
   * cache at all.  This is because if the page cache page is not uptodate we
   * bring it uptodate later, when doing the write to the mft record since we
   * then already have the page mapped.  And if the page is uptodate, the
   * non-initialized region will already have been zeroed when the page was
   * brought uptodate and the region may in fact already have been overwritten
   * with new data via mmap() based writes, so we cannot just zero it.  And since
   * POSIX specifies that the behaviour of resizing a file whilst it is mmap()ped
   * is unspecified, we choose not to do zeroing and thus we do not need to touch
dda65b941   Anton Altaparmakov   NTFS: Fix compila...
96
97
   * the page at all.  For a more detailed explanation see ntfs_truncate() in
   * fs/ntfs/inode.c.
98b270362   Anton Altaparmakov   NTFS: The big ntf...
98
   *
98b270362   Anton Altaparmakov   NTFS: The big ntf...
99
100
101
102
103
104
   * Return 0 on success and -errno on error.  In the case that an error is
   * encountered it is possible that the initialized size will already have been
   * incremented some way towards @new_init_size but it is guaranteed that if
   * this is the case, the necessary zeroing will also have happened and that all
   * metadata is self-consistent.
   *
1b1dcc1b5   Jes Sorensen   [PATCH] mutex sub...
105
   * Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be
dda65b941   Anton Altaparmakov   NTFS: Fix compila...
106
   *	    held by the caller.
98b270362   Anton Altaparmakov   NTFS: The big ntf...
107
   */
2ec93b0bf   Minchan Kim   ntfs: clean up nt...
108
  static int ntfs_attr_extend_initialized(ntfs_inode *ni, const s64 new_init_size)
98b270362   Anton Altaparmakov   NTFS: The big ntf...
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
  {
  	s64 old_init_size;
  	loff_t old_i_size;
  	pgoff_t index, end_index;
  	unsigned long flags;
  	struct inode *vi = VFS_I(ni);
  	ntfs_inode *base_ni;
  	MFT_RECORD *m = NULL;
  	ATTR_RECORD *a;
  	ntfs_attr_search_ctx *ctx = NULL;
  	struct address_space *mapping;
  	struct page *page = NULL;
  	u8 *kattr;
  	int err;
  	u32 attr_len;
  
  	read_lock_irqsave(&ni->size_lock, flags);
  	old_init_size = ni->initialized_size;
  	old_i_size = i_size_read(vi);
  	BUG_ON(new_init_size > ni->allocated_size);
  	read_unlock_irqrestore(&ni->size_lock, flags);
  	ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
  			"old_initialized_size 0x%llx, "
  			"new_initialized_size 0x%llx, i_size 0x%llx.",
  			vi->i_ino, (unsigned)le32_to_cpu(ni->type),
  			(unsigned long long)old_init_size,
  			(unsigned long long)new_init_size, old_i_size);
  	if (!NInoAttr(ni))
  		base_ni = ni;
  	else
  		base_ni = ni->ext.base_ntfs_ino;
  	/* Use goto to reduce indentation and we need the label below anyway. */
  	if (NInoNonResident(ni))
  		goto do_non_resident_extend;
  	BUG_ON(old_init_size != old_i_size);
  	m = map_mft_record(base_ni);
  	if (IS_ERR(m)) {
  		err = PTR_ERR(m);
  		m = NULL;
  		goto err_out;
  	}
  	ctx = ntfs_attr_get_search_ctx(base_ni, m);
  	if (unlikely(!ctx)) {
  		err = -ENOMEM;
  		goto err_out;
  	}
  	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  			CASE_SENSITIVE, 0, NULL, 0, ctx);
  	if (unlikely(err)) {
  		if (err == -ENOENT)
  			err = -EIO;
  		goto err_out;
  	}
  	m = ctx->mrec;
  	a = ctx->attr;
  	BUG_ON(a->non_resident);
  	/* The total length of the attribute value. */
  	attr_len = le32_to_cpu(a->data.resident.value_length);
  	BUG_ON(old_i_size != (loff_t)attr_len);
  	/*
  	 * Do the zeroing in the mft record and update the attribute size in
  	 * the mft record.
  	 */
  	kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
  	memset(kattr + attr_len, 0, new_init_size - attr_len);
  	a->data.resident.value_length = cpu_to_le32((u32)new_init_size);
  	/* Finally, update the sizes in the vfs and ntfs inodes. */
  	write_lock_irqsave(&ni->size_lock, flags);
  	i_size_write(vi, new_init_size);
  	ni->initialized_size = new_init_size;
  	write_unlock_irqrestore(&ni->size_lock, flags);
  	goto done;
  do_non_resident_extend:
  	/*
  	 * If the new initialized size @new_init_size exceeds the current file
  	 * size (vfs inode->i_size), we need to extend the file size to the
  	 * new initialized size.
  	 */
  	if (new_init_size > old_i_size) {
  		m = map_mft_record(base_ni);
  		if (IS_ERR(m)) {
  			err = PTR_ERR(m);
  			m = NULL;
  			goto err_out;
  		}
  		ctx = ntfs_attr_get_search_ctx(base_ni, m);
  		if (unlikely(!ctx)) {
  			err = -ENOMEM;
  			goto err_out;
  		}
  		err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  				CASE_SENSITIVE, 0, NULL, 0, ctx);
  		if (unlikely(err)) {
  			if (err == -ENOENT)
  				err = -EIO;
  			goto err_out;
  		}
  		m = ctx->mrec;
  		a = ctx->attr;
  		BUG_ON(!a->non_resident);
  		BUG_ON(old_i_size != (loff_t)
  				sle64_to_cpu(a->data.non_resident.data_size));
  		a->data.non_resident.data_size = cpu_to_sle64(new_init_size);
  		flush_dcache_mft_record_page(ctx->ntfs_ino);
  		mark_mft_record_dirty(ctx->ntfs_ino);
  		/* Update the file size in the vfs inode. */
  		i_size_write(vi, new_init_size);
  		ntfs_attr_put_search_ctx(ctx);
  		ctx = NULL;
  		unmap_mft_record(base_ni);
  		m = NULL;
  	}
  	mapping = vi->i_mapping;
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
222
223
  	index = old_init_size >> PAGE_SHIFT;
  	end_index = (new_init_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
224
225
226
227
228
  	do {
  		/*
  		 * Read the page.  If the page is not present, this will zero
  		 * the uninitialized regions for us.
  		 */
090d2b185   Pekka Enberg   [PATCH] read_mapp...
229
  		page = read_mapping_page(mapping, index, NULL);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
230
231
232
233
  		if (IS_ERR(page)) {
  			err = PTR_ERR(page);
  			goto init_err_out;
  		}
6fe6900e1   Nick Piggin   mm: make read_cac...
234
  		if (unlikely(PageError(page))) {
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
235
  			put_page(page);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
236
237
238
239
240
241
242
243
  			err = -EIO;
  			goto init_err_out;
  		}
  		/*
  		 * Update the initialized size in the ntfs inode.  This is
  		 * enough to make ntfs_writepage() work.
  		 */
  		write_lock_irqsave(&ni->size_lock, flags);
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
244
  		ni->initialized_size = (s64)(index + 1) << PAGE_SHIFT;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
245
246
247
248
249
  		if (ni->initialized_size > new_init_size)
  			ni->initialized_size = new_init_size;
  		write_unlock_irqrestore(&ni->size_lock, flags);
  		/* Set the page dirty so it gets written out. */
  		set_page_dirty(page);
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
250
  		put_page(page);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
  		/*
  		 * Play nice with the vm and the rest of the system.  This is
  		 * very much needed as we can potentially be modifying the
  		 * initialised size from a very small value to a really huge
  		 * value, e.g.
  		 *	f = open(somefile, O_TRUNC);
  		 *	truncate(f, 10GiB);
  		 *	seek(f, 10GiB);
  		 *	write(f, 1);
  		 * And this would mean we would be marking dirty hundreds of
  		 * thousands of pages or as in the above example more than
  		 * two and a half million pages!
  		 *
  		 * TODO: For sparse pages could optimize this workload by using
  		 * the FsMisc / MiscFs page bit as a "PageIsSparse" bit.  This
  		 * would be set in readpage for sparse pages and here we would
  		 * not need to mark dirty any pages which have this bit set.
  		 * The only caveat is that we have to clear the bit everywhere
  		 * where we allocate any clusters that lie in the page or that
  		 * contain the page.
  		 *
  		 * TODO: An even greater optimization would be for us to only
  		 * call readpage() on pages which are not in sparse regions as
  		 * determined from the runlist.  This would greatly reduce the
  		 * number of pages we read and make dirty in the case of sparse
  		 * files.
  		 */
  		balance_dirty_pages_ratelimited(mapping);
  		cond_resched();
  	} while (++index < end_index);
  	read_lock_irqsave(&ni->size_lock, flags);
  	BUG_ON(ni->initialized_size != new_init_size);
  	read_unlock_irqrestore(&ni->size_lock, flags);
  	/* Now bring in sync the initialized_size in the mft record. */
  	m = map_mft_record(base_ni);
  	if (IS_ERR(m)) {
  		err = PTR_ERR(m);
  		m = NULL;
  		goto init_err_out;
  	}
  	ctx = ntfs_attr_get_search_ctx(base_ni, m);
  	if (unlikely(!ctx)) {
  		err = -ENOMEM;
  		goto init_err_out;
  	}
  	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  			CASE_SENSITIVE, 0, NULL, 0, ctx);
  	if (unlikely(err)) {
  		if (err == -ENOENT)
  			err = -EIO;
  		goto init_err_out;
  	}
  	m = ctx->mrec;
  	a = ctx->attr;
  	BUG_ON(!a->non_resident);
  	a->data.non_resident.initialized_size = cpu_to_sle64(new_init_size);
  done:
  	flush_dcache_mft_record_page(ctx->ntfs_ino);
  	mark_mft_record_dirty(ctx->ntfs_ino);
  	if (ctx)
  		ntfs_attr_put_search_ctx(ctx);
  	if (m)
  		unmap_mft_record(base_ni);
  	ntfs_debug("Done, initialized_size 0x%llx, i_size 0x%llx.",
  			(unsigned long long)new_init_size, i_size_read(vi));
  	return 0;
  init_err_out:
  	write_lock_irqsave(&ni->size_lock, flags);
  	ni->initialized_size = old_init_size;
  	write_unlock_irqrestore(&ni->size_lock, flags);
  err_out:
  	if (ctx)
  		ntfs_attr_put_search_ctx(ctx);
  	if (m)
  		unmap_mft_record(base_ni);
  	ntfs_debug("Failed.  Returning error code %i.", err);
  	return err;
  }
ccca26835   Al Viro   ntfs: move iov_it...
329
330
  static ssize_t ntfs_prepare_file_for_write(struct kiocb *iocb,
  		struct iov_iter *from)
98b270362   Anton Altaparmakov   NTFS: The big ntf...
331
  {
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
332
333
334
335
  	loff_t pos;
  	s64 end, ll;
  	ssize_t err;
  	unsigned long flags;
ccca26835   Al Viro   ntfs: move iov_it...
336
  	struct file *file = iocb->ki_filp;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
337
338
339
  	struct inode *vi = file_inode(file);
  	ntfs_inode *base_ni, *ni = NTFS_I(vi);
  	ntfs_volume *vol = ni->vol;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
340

a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
341
  	ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
ccca26835   Al Viro   ntfs: move iov_it...
342
  			"0x%llx, count 0x%zx.", vi->i_ino,
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
343
  			(unsigned)le32_to_cpu(ni->type),
3309dd04c   Al Viro   switch generic_wr...
344
345
346
347
  			(unsigned long long)iocb->ki_pos,
  			iov_iter_count(from));
  	err = generic_write_checks(iocb, from);
  	if (unlikely(err <= 0))
ccca26835   Al Viro   ntfs: move iov_it...
348
  		goto out;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
  	/*
  	 * All checks have passed.  Before we start doing any writing we want
  	 * to abort any totally illegal writes.
  	 */
  	BUG_ON(NInoMstProtected(ni));
  	BUG_ON(ni->type != AT_DATA);
  	/* If file is encrypted, deny access, just like NT4. */
  	if (NInoEncrypted(ni)) {
  		/* Only $DATA attributes can be encrypted. */
  		/*
  		 * Reminder for later: Encrypted files are _always_
  		 * non-resident so that the content can always be encrypted.
  		 */
  		ntfs_debug("Denying write access to encrypted file.");
  		err = -EACCES;
  		goto out;
  	}
  	if (NInoCompressed(ni)) {
  		/* Only unnamed $DATA attribute can be compressed. */
  		BUG_ON(ni->name_len);
  		/*
  		 * Reminder for later: If resident, the data is not actually
  		 * compressed.  Only on the switch to non-resident does
  		 * compression kick in.  This is in contrast to encrypted files
  		 * (see above).
  		 */
  		ntfs_error(vi->i_sb, "Writing to compressed files is not "
  				"implemented yet.  Sorry.");
  		err = -EOPNOTSUPP;
  		goto out;
  	}
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
380
381
382
  	base_ni = ni;
  	if (NInoAttr(ni))
  		base_ni = ni->ext.base_ntfs_ino;
5fa8e0a1c   Jan Kara   fs: Rename file_r...
383
  	err = file_remove_privs(file);
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
384
385
386
387
388
389
390
  	if (unlikely(err))
  		goto out;
  	/*
  	 * Our ->update_time method always succeeds thus file_update_time()
  	 * cannot fail either so there is no need to check the return code.
  	 */
  	file_update_time(file);
ccca26835   Al Viro   ntfs: move iov_it...
391
  	pos = iocb->ki_pos;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
392
  	/* The first byte after the last cluster being written to. */
ccca26835   Al Viro   ntfs: move iov_it...
393
  	end = (pos + iov_iter_count(from) + vol->cluster_size_mask) &
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
  			~(u64)vol->cluster_size_mask;
  	/*
  	 * If the write goes beyond the allocated size, extend the allocation
  	 * to cover the whole of the write, rounded up to the nearest cluster.
  	 */
  	read_lock_irqsave(&ni->size_lock, flags);
  	ll = ni->allocated_size;
  	read_unlock_irqrestore(&ni->size_lock, flags);
  	if (end > ll) {
  		/*
  		 * Extend the allocation without changing the data size.
  		 *
  		 * Note we ensure the allocation is big enough to at least
  		 * write some data but we do not require the allocation to be
  		 * complete, i.e. it may be partial.
  		 */
  		ll = ntfs_attr_extend_allocation(ni, end, -1, pos);
  		if (likely(ll >= 0)) {
  			BUG_ON(pos >= ll);
  			/* If the extension was partial truncate the write. */
  			if (end > ll) {
  				ntfs_debug("Truncating write to inode 0x%lx, "
  						"attribute type 0x%x, because "
  						"the allocation was only "
  						"partially extended.",
  						vi->i_ino, (unsigned)
  						le32_to_cpu(ni->type));
ccca26835   Al Viro   ntfs: move iov_it...
421
  				iov_iter_truncate(from, ll - pos);
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
  			}
  		} else {
  			err = ll;
  			read_lock_irqsave(&ni->size_lock, flags);
  			ll = ni->allocated_size;
  			read_unlock_irqrestore(&ni->size_lock, flags);
  			/* Perform a partial write if possible or fail. */
  			if (pos < ll) {
  				ntfs_debug("Truncating write to inode 0x%lx "
  						"attribute type 0x%x, because "
  						"extending the allocation "
  						"failed (error %d).",
  						vi->i_ino, (unsigned)
  						le32_to_cpu(ni->type),
  						(int)-err);
ccca26835   Al Viro   ntfs: move iov_it...
437
  				iov_iter_truncate(from, ll - pos);
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
  			} else {
  				if (err != -ENOSPC)
  					ntfs_error(vi->i_sb, "Cannot perform "
  							"write to inode "
  							"0x%lx, attribute "
  							"type 0x%x, because "
  							"extending the "
  							"allocation failed "
  							"(error %ld).",
  							vi->i_ino, (unsigned)
  							le32_to_cpu(ni->type),
  							(long)-err);
  				else
  					ntfs_debug("Cannot perform write to "
  							"inode 0x%lx, "
  							"attribute type 0x%x, "
  							"because there is not "
  							"space left.",
  							vi->i_ino, (unsigned)
  							le32_to_cpu(ni->type));
  				goto out;
  			}
  		}
  	}
  	/*
  	 * If the write starts beyond the initialized size, extend it up to the
  	 * beginning of the write and initialize all non-sparse space between
  	 * the old initialized size and the new one.  This automatically also
  	 * increments the vfs inode->i_size to keep it above or equal to the
  	 * initialized_size.
  	 */
  	read_lock_irqsave(&ni->size_lock, flags);
  	ll = ni->initialized_size;
  	read_unlock_irqrestore(&ni->size_lock, flags);
  	if (pos > ll) {
  		/*
  		 * Wait for ongoing direct i/o to complete before proceeding.
  		 * New direct i/o cannot start as we hold i_mutex.
  		 */
  		inode_dio_wait(vi);
  		err = ntfs_attr_extend_initialized(ni, pos);
  		if (unlikely(err < 0))
  			ntfs_error(vi->i_sb, "Cannot perform write to inode "
  					"0x%lx, attribute type 0x%x, because "
  					"extending the initialized size "
  					"failed (error %d).", vi->i_ino,
  					(unsigned)le32_to_cpu(ni->type),
  					(int)-err);
  	}
  out:
  	return err;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
489
490
491
492
493
494
495
496
497
  }
  
  /**
   * __ntfs_grab_cache_pages - obtain a number of locked pages
   * @mapping:	address space mapping from which to obtain page cache pages
   * @index:	starting index in @mapping at which to begin obtaining pages
   * @nr_pages:	number of page cache pages to obtain
   * @pages:	array of pages in which to return the obtained page cache pages
   * @cached_page: allocated but as yet unused page
98b270362   Anton Altaparmakov   NTFS: The big ntf...
498
   *
af901ca18   André Goddard Rosa   tree-wide: fix as...
499
   * Obtain @nr_pages locked page cache pages from the mapping @mapping and
98b270362   Anton Altaparmakov   NTFS: The big ntf...
500
501
   * starting at index @index.
   *
4c99000ac   Minchan Kim   ntfs: use add_to_...
502
   * If a page is newly created, add it to lru list
98b270362   Anton Altaparmakov   NTFS: The big ntf...
503
504
505
506
507
   *
   * Note, the page locks are obtained in ascending page index order.
   */
  static inline int __ntfs_grab_cache_pages(struct address_space *mapping,
  		pgoff_t index, const unsigned nr_pages, struct page **pages,
4c99000ac   Minchan Kim   ntfs: use add_to_...
508
  		struct page **cached_page)
98b270362   Anton Altaparmakov   NTFS: The big ntf...
509
510
511
512
513
514
  {
  	int err, nr;
  
  	BUG_ON(!nr_pages);
  	err = nr = 0;
  	do {
5272d036b   Anton Altaparmakov   ntfs: use find_ge...
515
516
  		pages[nr] = find_get_page_flags(mapping, index, FGP_LOCK |
  				FGP_ACCESSED);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
517
518
519
520
521
522
523
524
  		if (!pages[nr]) {
  			if (!*cached_page) {
  				*cached_page = page_cache_alloc(mapping);
  				if (unlikely(!*cached_page)) {
  					err = -ENOMEM;
  					goto err_out;
  				}
  			}
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
525
  			err = add_to_page_cache_lru(*cached_page, mapping,
c62d25556   Michal Hocko   mm, fs: introduce...
526
527
  				   index,
  				   mapping_gfp_constraint(mapping, GFP_KERNEL));
98b270362   Anton Altaparmakov   NTFS: The big ntf...
528
529
530
531
532
533
  			if (unlikely(err)) {
  				if (err == -EEXIST)
  					continue;
  				goto err_out;
  			}
  			pages[nr] = *cached_page;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
534
535
536
537
538
539
540
541
542
543
  			*cached_page = NULL;
  		}
  		index++;
  		nr++;
  	} while (nr < nr_pages);
  out:
  	return err;
  err_out:
  	while (nr > 0) {
  		unlock_page(pages[--nr]);
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
544
  		put_page(pages[nr]);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
545
546
547
548
549
550
551
552
553
  	}
  	goto out;
  }
  
  static inline int ntfs_submit_bh_for_read(struct buffer_head *bh)
  {
  	lock_buffer(bh);
  	get_bh(bh);
  	bh->b_end_io = end_buffer_read_sync;
2a222ca99   Mike Christie   fs: have submit_b...
554
  	return submit_bh(REQ_OP_READ, 0, bh);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
555
556
557
558
559
560
561
562
563
564
  }
  
  /**
   * ntfs_prepare_pages_for_non_resident_write - prepare pages for receiving data
   * @pages:	array of destination pages
   * @nr_pages:	number of pages in @pages
   * @pos:	byte position in file at which the write begins
   * @bytes:	number of bytes to be written
   *
   * This is called for non-resident attributes from ntfs_file_buffered_write()
1b1dcc1b5   Jes Sorensen   [PATCH] mutex sub...
565
   * with i_mutex held on the inode (@pages[0]->mapping->host).  There are
98b270362   Anton Altaparmakov   NTFS: The big ntf...
566
567
568
569
570
571
572
573
   * @nr_pages pages in @pages which are locked but not kmap()ped.  The source
   * data has not yet been copied into the @pages.
   * 
   * Need to fill any holes with actual clusters, allocate buffers if necessary,
   * ensure all the buffers are mapped, and bring uptodate any buffers that are
   * only partially being written to.
   *
   * If @nr_pages is greater than one, we are guaranteed that the cluster size is
ea1754a08   Kirill A. Shutemov   mm, fs: remove re...
574
   * greater than PAGE_SIZE, that all pages in @pages are entirely inside
98b270362   Anton Altaparmakov   NTFS: The big ntf...
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
   * the same cluster and that they are the entirety of that cluster, and that
   * the cluster is sparse, i.e. we need to allocate a cluster to fill the hole.
   *
   * i_size is not to be modified yet.
   *
   * Return 0 on success or -errno on error.
   */
  static int ntfs_prepare_pages_for_non_resident_write(struct page **pages,
  		unsigned nr_pages, s64 pos, size_t bytes)
  {
  	VCN vcn, highest_vcn = 0, cpos, cend, bh_cpos, bh_cend;
  	LCN lcn;
  	s64 bh_pos, vcn_len, end, initialized_size;
  	sector_t lcn_block;
  	struct page *page;
  	struct inode *vi;
  	ntfs_inode *ni, *base_ni = NULL;
  	ntfs_volume *vol;
  	runlist_element *rl, *rl2;
  	struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
  	ntfs_attr_search_ctx *ctx = NULL;
  	MFT_RECORD *m = NULL;
  	ATTR_RECORD *a = NULL;
  	unsigned long flags;
  	u32 attr_rec_len = 0;
  	unsigned blocksize, u;
  	int err, mp_size;
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
602
  	bool rl_write_locked, was_hole, is_retry;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
  	unsigned char blocksize_bits;
  	struct {
  		u8 runlist_merged:1;
  		u8 mft_attr_mapped:1;
  		u8 mp_rebuilt:1;
  		u8 attr_switched:1;
  	} status = { 0, 0, 0, 0 };
  
  	BUG_ON(!nr_pages);
  	BUG_ON(!pages);
  	BUG_ON(!*pages);
  	vi = pages[0]->mapping->host;
  	ni = NTFS_I(vi);
  	vol = ni->vol;
  	ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
d04bd1fb6   Anton Altaparmakov   NTFS: Use %z for ...
618
  			"index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
98b270362   Anton Altaparmakov   NTFS: The big ntf...
619
620
  			vi->i_ino, ni->type, pages[0]->index, nr_pages,
  			(long long)pos, bytes);
78af34f03   Anton Altaparmakov   NTFS: Implement s...
621
622
  	blocksize = vol->sb->s_blocksize;
  	blocksize_bits = vol->sb->s_blocksize_bits;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
623
624
  	u = 0;
  	do {
bfab36e81   Anton Altaparmakov   NTFS: Fix a mount...
625
626
  		page = pages[u];
  		BUG_ON(!page);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
627
628
629
630
631
632
633
634
635
636
  		/*
  		 * create_empty_buffers() will create uptodate/dirty buffers if
  		 * the page is uptodate/dirty.
  		 */
  		if (!page_has_buffers(page)) {
  			create_empty_buffers(page, blocksize, 0);
  			if (unlikely(!page_has_buffers(page)))
  				return -ENOMEM;
  		}
  	} while (++u < nr_pages);
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
637
  	rl_write_locked = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
638
639
640
641
642
  	rl = NULL;
  	err = 0;
  	vcn = lcn = -1;
  	vcn_len = 0;
  	lcn_block = -1;
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
643
  	was_hole = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
644
645
646
647
648
649
650
651
652
653
  	cpos = pos >> vol->cluster_size_bits;
  	end = pos + bytes;
  	cend = (end + vol->cluster_size - 1) >> vol->cluster_size_bits;
  	/*
  	 * Loop over each page and for each page over each buffer.  Use goto to
  	 * reduce indentation.
  	 */
  	u = 0;
  do_next_page:
  	page = pages[u];
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
654
  	bh_pos = (s64)page->index << PAGE_SHIFT;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
  	bh = head = page_buffers(page);
  	do {
  		VCN cdelta;
  		s64 bh_end;
  		unsigned bh_cofs;
  
  		/* Clear buffer_new on all buffers to reinitialise state. */
  		if (buffer_new(bh))
  			clear_buffer_new(bh);
  		bh_end = bh_pos + blocksize;
  		bh_cpos = bh_pos >> vol->cluster_size_bits;
  		bh_cofs = bh_pos & vol->cluster_size_mask;
  		if (buffer_mapped(bh)) {
  			/*
  			 * The buffer is already mapped.  If it is uptodate,
  			 * ignore it.
  			 */
  			if (buffer_uptodate(bh))
  				continue;
  			/*
  			 * The buffer is not uptodate.  If the page is uptodate
  			 * set the buffer uptodate and otherwise ignore it.
  			 */
  			if (PageUptodate(page)) {
  				set_buffer_uptodate(bh);
  				continue;
  			}
  			/*
  			 * Neither the page nor the buffer are uptodate.  If
  			 * the buffer is only partially being written to, we
  			 * need to read it in before the write, i.e. now.
  			 */
  			if ((bh_pos < pos && bh_end > pos) ||
  					(bh_pos < end && bh_end > end)) {
  				/*
  				 * If the buffer is fully or partially within
  				 * the initialized size, do an actual read.
  				 * Otherwise, simply zero the buffer.
  				 */
  				read_lock_irqsave(&ni->size_lock, flags);
  				initialized_size = ni->initialized_size;
  				read_unlock_irqrestore(&ni->size_lock, flags);
  				if (bh_pos < initialized_size) {
  					ntfs_submit_bh_for_read(bh);
  					*wait_bh++ = bh;
  				} else {
eebd2aa35   Christoph Lameter   Pagecache zeroing...
701
702
  					zero_user(page, bh_offset(bh),
  							blocksize);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
  					set_buffer_uptodate(bh);
  				}
  			}
  			continue;
  		}
  		/* Unmapped buffer.  Need to map it. */
  		bh->b_bdev = vol->sb->s_bdev;
  		/*
  		 * If the current buffer is in the same clusters as the map
  		 * cache, there is no need to check the runlist again.  The
  		 * map cache is made up of @vcn, which is the first cached file
  		 * cluster, @vcn_len which is the number of cached file
  		 * clusters, @lcn is the device cluster corresponding to @vcn,
  		 * and @lcn_block is the block number corresponding to @lcn.
  		 */
  		cdelta = bh_cpos - vcn;
  		if (likely(!cdelta || (cdelta > 0 && cdelta < vcn_len))) {
  map_buffer_cached:
  			BUG_ON(lcn < 0);
  			bh->b_blocknr = lcn_block +
  					(cdelta << (vol->cluster_size_bits -
  					blocksize_bits)) +
  					(bh_cofs >> blocksize_bits);
  			set_buffer_mapped(bh);
  			/*
  			 * If the page is uptodate so is the buffer.  If the
  			 * buffer is fully outside the write, we ignore it if
  			 * it was already allocated and we mark it dirty so it
  			 * gets written out if we allocated it.  On the other
  			 * hand, if we allocated the buffer but we are not
  			 * marking it dirty we set buffer_new so we can do
  			 * error recovery.
  			 */
  			if (PageUptodate(page)) {
  				if (!buffer_uptodate(bh))
  					set_buffer_uptodate(bh);
  				if (unlikely(was_hole)) {
  					/* We allocated the buffer. */
e64855c6c   Jan Kara   fs: Add helper to...
741
  					clean_bdev_bh_alias(bh);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
  					if (bh_end <= pos || bh_pos >= end)
  						mark_buffer_dirty(bh);
  					else
  						set_buffer_new(bh);
  				}
  				continue;
  			}
  			/* Page is _not_ uptodate. */
  			if (likely(!was_hole)) {
  				/*
  				 * Buffer was already allocated.  If it is not
  				 * uptodate and is only partially being written
  				 * to, we need to read it in before the write,
  				 * i.e. now.
  				 */
3aebf25bd   Anton Altaparmakov   NTFS: Fix a stupi...
757
758
759
760
  				if (!buffer_uptodate(bh) && bh_pos < end &&
  						bh_end > pos &&
  						(bh_pos < pos ||
  						bh_end > end)) {
98b270362   Anton Altaparmakov   NTFS: The big ntf...
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
  					/*
  					 * If the buffer is fully or partially
  					 * within the initialized size, do an
  					 * actual read.  Otherwise, simply zero
  					 * the buffer.
  					 */
  					read_lock_irqsave(&ni->size_lock,
  							flags);
  					initialized_size = ni->initialized_size;
  					read_unlock_irqrestore(&ni->size_lock,
  							flags);
  					if (bh_pos < initialized_size) {
  						ntfs_submit_bh_for_read(bh);
  						*wait_bh++ = bh;
  					} else {
eebd2aa35   Christoph Lameter   Pagecache zeroing...
776
777
  						zero_user(page, bh_offset(bh),
  								blocksize);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
778
779
780
781
782
783
  						set_buffer_uptodate(bh);
  					}
  				}
  				continue;
  			}
  			/* We allocated the buffer. */
e64855c6c   Jan Kara   fs: Add helper to...
784
  			clean_bdev_bh_alias(bh);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
785
786
787
788
789
790
791
792
793
794
  			/*
  			 * If the buffer is fully outside the write, zero it,
  			 * set it uptodate, and mark it dirty so it gets
  			 * written out.  If it is partially being written to,
  			 * zero region surrounding the write but leave it to
  			 * commit write to do anything else.  Finally, if the
  			 * buffer is fully being overwritten, do nothing.
  			 */
  			if (bh_end <= pos || bh_pos >= end) {
  				if (!buffer_uptodate(bh)) {
eebd2aa35   Christoph Lameter   Pagecache zeroing...
795
796
  					zero_user(page, bh_offset(bh),
  							blocksize);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
797
798
799
800
801
802
803
804
805
806
807
  					set_buffer_uptodate(bh);
  				}
  				mark_buffer_dirty(bh);
  				continue;
  			}
  			set_buffer_new(bh);
  			if (!buffer_uptodate(bh) &&
  					(bh_pos < pos || bh_end > end)) {
  				u8 *kaddr;
  				unsigned pofs;
  					
a3ac1414e   Cong Wang   ntfs: remove the ...
808
  				kaddr = kmap_atomic(page);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
809
  				if (bh_pos < pos) {
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
810
  					pofs = bh_pos & ~PAGE_MASK;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
811
812
813
  					memset(kaddr + pofs, 0, pos - bh_pos);
  				}
  				if (bh_end > end) {
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
814
  					pofs = end & ~PAGE_MASK;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
815
816
  					memset(kaddr + pofs, 0, bh_end - end);
  				}
a3ac1414e   Cong Wang   ntfs: remove the ...
817
  				kunmap_atomic(kaddr);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
  				flush_dcache_page(page);
  			}
  			continue;
  		}
  		/*
  		 * Slow path: this is the first buffer in the cluster.  If it
  		 * is outside allocated size and is not uptodate, zero it and
  		 * set it uptodate.
  		 */
  		read_lock_irqsave(&ni->size_lock, flags);
  		initialized_size = ni->allocated_size;
  		read_unlock_irqrestore(&ni->size_lock, flags);
  		if (bh_pos > initialized_size) {
  			if (PageUptodate(page)) {
  				if (!buffer_uptodate(bh))
  					set_buffer_uptodate(bh);
  			} else if (!buffer_uptodate(bh)) {
eebd2aa35   Christoph Lameter   Pagecache zeroing...
835
  				zero_user(page, bh_offset(bh), blocksize);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
836
837
838
839
  				set_buffer_uptodate(bh);
  			}
  			continue;
  		}
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
840
  		is_retry = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
  		if (!rl) {
  			down_read(&ni->runlist.lock);
  retry_remap:
  			rl = ni->runlist.rl;
  		}
  		if (likely(rl != NULL)) {
  			/* Seek to element containing target cluster. */
  			while (rl->length && rl[1].vcn <= bh_cpos)
  				rl++;
  			lcn = ntfs_rl_vcn_to_lcn(rl, bh_cpos);
  			if (likely(lcn >= 0)) {
  				/*
  				 * Successful remap, setup the map cache and
  				 * use that to deal with the buffer.
  				 */
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
856
  				was_hole = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
857
858
859
860
  				vcn = bh_cpos;
  				vcn_len = rl[1].vcn - vcn;
  				lcn_block = lcn << (vol->cluster_size_bits -
  						blocksize_bits);
d5aeaef37   Anton Altaparmakov   NTFS: Fix serious...
861
  				cdelta = 0;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
862
  				/*
3aebf25bd   Anton Altaparmakov   NTFS: Fix a stupi...
863
864
865
866
867
  				 * If the number of remaining clusters touched
  				 * by the write is smaller or equal to the
  				 * number of cached clusters, unlock the
  				 * runlist as the map cache will be used from
  				 * now on.
98b270362   Anton Altaparmakov   NTFS: The big ntf...
868
869
870
871
  				 */
  				if (likely(vcn + vcn_len >= cend)) {
  					if (rl_write_locked) {
  						up_write(&ni->runlist.lock);
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
872
  						rl_write_locked = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
  					} else
  						up_read(&ni->runlist.lock);
  					rl = NULL;
  				}
  				goto map_buffer_cached;
  			}
  		} else
  			lcn = LCN_RL_NOT_MAPPED;
  		/*
  		 * If it is not a hole and not out of bounds, the runlist is
  		 * probably unmapped so try to map it now.
  		 */
  		if (unlikely(lcn != LCN_HOLE && lcn != LCN_ENOENT)) {
  			if (likely(!is_retry && lcn == LCN_RL_NOT_MAPPED)) {
  				/* Attempt to map runlist. */
  				if (!rl_write_locked) {
  					/*
  					 * We need the runlist locked for
  					 * writing, so if it is locked for
  					 * reading relock it now and retry in
  					 * case it changed whilst we dropped
  					 * the lock.
  					 */
  					up_read(&ni->runlist.lock);
  					down_write(&ni->runlist.lock);
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
898
  					rl_write_locked = true;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
899
900
901
902
903
  					goto retry_remap;
  				}
  				err = ntfs_map_runlist_nolock(ni, bh_cpos,
  						NULL);
  				if (likely(!err)) {
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
904
  					is_retry = true;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
  					goto retry_remap;
  				}
  				/*
  				 * If @vcn is out of bounds, pretend @lcn is
  				 * LCN_ENOENT.  As long as the buffer is out
  				 * of bounds this will work fine.
  				 */
  				if (err == -ENOENT) {
  					lcn = LCN_ENOENT;
  					err = 0;
  					goto rl_not_mapped_enoent;
  				}
  			} else
  				err = -EIO;
  			/* Failed to map the buffer, even after retrying. */
  			bh->b_blocknr = -1;
  			ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
  					"attribute type 0x%x, vcn 0x%llx, "
  					"vcn offset 0x%x, because its "
  					"location on disk could not be "
  					"determined%s (error code %i).",
  					ni->mft_no, ni->type,
  					(unsigned long long)bh_cpos,
  					(unsigned)bh_pos &
  					vol->cluster_size_mask,
  					is_retry ? " even after retrying" : "",
  					err);
  			break;
  		}
  rl_not_mapped_enoent:
  		/*
  		 * The buffer is in a hole or out of bounds.  We need to fill
  		 * the hole, unless the buffer is in a cluster which is not
  		 * touched by the write, in which case we just leave the buffer
  		 * unmapped.  This can only happen when the cluster size is
  		 * less than the page cache size.
  		 */
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
942
  		if (unlikely(vol->cluster_size < PAGE_SIZE)) {
98b270362   Anton Altaparmakov   NTFS: The big ntf...
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
  			bh_cend = (bh_end + vol->cluster_size - 1) >>
  					vol->cluster_size_bits;
  			if ((bh_cend <= cpos || bh_cpos >= cend)) {
  				bh->b_blocknr = -1;
  				/*
  				 * If the buffer is uptodate we skip it.  If it
  				 * is not but the page is uptodate, we can set
  				 * the buffer uptodate.  If the page is not
  				 * uptodate, we can clear the buffer and set it
  				 * uptodate.  Whether this is worthwhile is
  				 * debatable and this could be removed.
  				 */
  				if (PageUptodate(page)) {
  					if (!buffer_uptodate(bh))
  						set_buffer_uptodate(bh);
  				} else if (!buffer_uptodate(bh)) {
eebd2aa35   Christoph Lameter   Pagecache zeroing...
959
960
  					zero_user(page, bh_offset(bh),
  						blocksize);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
  					set_buffer_uptodate(bh);
  				}
  				continue;
  			}
  		}
  		/*
  		 * Out of bounds buffer is invalid if it was not really out of
  		 * bounds.
  		 */
  		BUG_ON(lcn != LCN_HOLE);
  		/*
  		 * We need the runlist locked for writing, so if it is locked
  		 * for reading relock it now and retry in case it changed
  		 * whilst we dropped the lock.
  		 */
  		BUG_ON(!rl);
  		if (!rl_write_locked) {
  			up_read(&ni->runlist.lock);
  			down_write(&ni->runlist.lock);
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
980
  			rl_write_locked = true;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
981
982
983
984
985
986
987
988
989
990
991
992
993
  			goto retry_remap;
  		}
  		/* Find the previous last allocated cluster. */
  		BUG_ON(rl->lcn != LCN_HOLE);
  		lcn = -1;
  		rl2 = rl;
  		while (--rl2 >= ni->runlist.rl) {
  			if (rl2->lcn >= 0) {
  				lcn = rl2->lcn + rl2->length;
  				break;
  			}
  		}
  		rl2 = ntfs_cluster_alloc(vol, bh_cpos, 1, lcn, DATA_ZONE,
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
994
  				false);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
  		if (IS_ERR(rl2)) {
  			err = PTR_ERR(rl2);
  			ntfs_debug("Failed to allocate cluster, error code %i.",
  					err);
  			break;
  		}
  		lcn = rl2->lcn;
  		rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
  		if (IS_ERR(rl)) {
  			err = PTR_ERR(rl);
  			if (err != -ENOMEM)
  				err = -EIO;
  			if (ntfs_cluster_free_from_rl(vol, rl2)) {
  				ntfs_error(vol->sb, "Failed to release "
  						"allocated cluster in error "
  						"code path.  Run chkdsk to "
  						"recover the lost cluster.");
  				NVolSetErrors(vol);
  			}
  			ntfs_free(rl2);
  			break;
  		}
  		ni->runlist.rl = rl;
  		status.runlist_merged = 1;
bb8047d35   Anton Altaparmakov   NTFS: Fix two com...
1019
1020
  		ntfs_debug("Allocated cluster, lcn 0x%llx.",
  				(unsigned long long)lcn);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
  		/* Map and lock the mft record and get the attribute record. */
  		if (!NInoAttr(ni))
  			base_ni = ni;
  		else
  			base_ni = ni->ext.base_ntfs_ino;
  		m = map_mft_record(base_ni);
  		if (IS_ERR(m)) {
  			err = PTR_ERR(m);
  			break;
  		}
  		ctx = ntfs_attr_get_search_ctx(base_ni, m);
  		if (unlikely(!ctx)) {
  			err = -ENOMEM;
  			unmap_mft_record(base_ni);
  			break;
  		}
  		status.mft_attr_mapped = 1;
  		err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  				CASE_SENSITIVE, bh_cpos, NULL, 0, ctx);
  		if (unlikely(err)) {
  			if (err == -ENOENT)
  				err = -EIO;
  			break;
  		}
  		m = ctx->mrec;
  		a = ctx->attr;
  		/*
  		 * Find the runlist element with which the attribute extent
  		 * starts.  Note, we cannot use the _attr_ version because we
  		 * have mapped the mft record.  That is ok because we know the
  		 * runlist fragment must be mapped already to have ever gotten
  		 * here, so we can just use the _rl_ version.
  		 */
  		vcn = sle64_to_cpu(a->data.non_resident.lowest_vcn);
  		rl2 = ntfs_rl_find_vcn_nolock(rl, vcn);
  		BUG_ON(!rl2);
  		BUG_ON(!rl2->length);
  		BUG_ON(rl2->lcn < LCN_HOLE);
  		highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
  		/*
  		 * If @highest_vcn is zero, calculate the real highest_vcn
  		 * (which can really be zero).
  		 */
  		if (!highest_vcn)
  			highest_vcn = (sle64_to_cpu(
  					a->data.non_resident.allocated_size) >>
  					vol->cluster_size_bits) - 1;
  		/*
  		 * Determine the size of the mapping pairs array for the new
  		 * extent, i.e. the old extent with the hole filled.
  		 */
  		mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, vcn,
  				highest_vcn);
  		if (unlikely(mp_size <= 0)) {
  			if (!(err = mp_size))
  				err = -EIO;
  			ntfs_debug("Failed to get size for mapping pairs "
  					"array, error code %i.", err);
  			break;
  		}
  		/*
  		 * Resize the attribute record to fit the new mapping pairs
  		 * array.
  		 */
  		attr_rec_len = le32_to_cpu(a->length);
  		err = ntfs_attr_record_resize(m, a, mp_size + le16_to_cpu(
  				a->data.non_resident.mapping_pairs_offset));
  		if (unlikely(err)) {
  			BUG_ON(err != -ENOSPC);
  			// TODO: Deal with this by using the current attribute
  			// and fill it with as much of the mapping pairs
  			// array as possible.  Then loop over each attribute
  			// extent rewriting the mapping pairs arrays as we go
  			// along and if when we reach the end we have not
  			// enough space, try to resize the last attribute
  			// extent and if even that fails, add a new attribute
  			// extent.
  			// We could also try to resize at each step in the hope
  			// that we will not need to rewrite every single extent.
  			// Note, we may need to decompress some extents to fill
  			// the runlist as we are walking the extents...
  			ntfs_error(vol->sb, "Not enough space in the mft "
  					"record for the extended attribute "
  					"record.  This case is not "
  					"implemented yet.");
  			err = -EOPNOTSUPP;
  			break ;
  		}
  		status.mp_rebuilt = 1;
  		/*
  		 * Generate the mapping pairs array directly into the attribute
  		 * record.
  		 */
  		err = ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
  				a->data.non_resident.mapping_pairs_offset),
  				mp_size, rl2, vcn, highest_vcn, NULL);
  		if (unlikely(err)) {
  			ntfs_error(vol->sb, "Cannot fill hole in inode 0x%lx, "
  					"attribute type 0x%x, because building "
  					"the mapping pairs failed with error "
  					"code %i.", vi->i_ino,
  					(unsigned)le32_to_cpu(ni->type), err);
  			err = -EIO;
  			break;
  		}
  		/* Update the highest_vcn but only if it was not set. */
  		if (unlikely(!a->data.non_resident.highest_vcn))
  			a->data.non_resident.highest_vcn =
  					cpu_to_sle64(highest_vcn);
  		/*
  		 * If the attribute is sparse/compressed, update the compressed
  		 * size in the ntfs_inode structure and the attribute record.
  		 */
  		if (likely(NInoSparse(ni) || NInoCompressed(ni))) {
  			/*
  			 * If we are not in the first attribute extent, switch
  			 * to it, but first ensure the changes will make it to
  			 * disk later.
  			 */
  			if (a->data.non_resident.lowest_vcn) {
  				flush_dcache_mft_record_page(ctx->ntfs_ino);
  				mark_mft_record_dirty(ctx->ntfs_ino);
  				ntfs_attr_reinit_search_ctx(ctx);
  				err = ntfs_attr_lookup(ni->type, ni->name,
  						ni->name_len, CASE_SENSITIVE,
  						0, NULL, 0, ctx);
  				if (unlikely(err)) {
  					status.attr_switched = 1;
  					break;
  				}
  				/* @m is not used any more so do not set it. */
  				a = ctx->attr;
  			}
  			write_lock_irqsave(&ni->size_lock, flags);
  			ni->itype.compressed.size += vol->cluster_size;
  			a->data.non_resident.compressed_size =
  					cpu_to_sle64(ni->itype.compressed.size);
  			write_unlock_irqrestore(&ni->size_lock, flags);
  		}
  		/* Ensure the changes make it to disk. */
  		flush_dcache_mft_record_page(ctx->ntfs_ino);
  		mark_mft_record_dirty(ctx->ntfs_ino);
  		ntfs_attr_put_search_ctx(ctx);
  		unmap_mft_record(base_ni);
  		/* Successfully filled the hole. */
  		status.runlist_merged = 0;
  		status.mft_attr_mapped = 0;
  		status.mp_rebuilt = 0;
  		/* Setup the map cache and use that to deal with the buffer. */
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
1170
  		was_hole = true;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
  		vcn = bh_cpos;
  		vcn_len = 1;
  		lcn_block = lcn << (vol->cluster_size_bits - blocksize_bits);
  		cdelta = 0;
  		/*
  		 * If the number of remaining clusters in the @pages is smaller
  		 * or equal to the number of cached clusters, unlock the
  		 * runlist as the map cache will be used from now on.
  		 */
  		if (likely(vcn + vcn_len >= cend)) {
  			up_write(&ni->runlist.lock);
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
1182
  			rl_write_locked = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
  			rl = NULL;
  		}
  		goto map_buffer_cached;
  	} while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
  	/* If there are no errors, do the next page. */
  	if (likely(!err && ++u < nr_pages))
  		goto do_next_page;
  	/* If there are no errors, release the runlist lock if we took it. */
  	if (likely(!err)) {
  		if (unlikely(rl_write_locked)) {
  			up_write(&ni->runlist.lock);
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
1194
  			rl_write_locked = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
  		} else if (unlikely(rl))
  			up_read(&ni->runlist.lock);
  		rl = NULL;
  	}
  	/* If we issued read requests, let them complete. */
  	read_lock_irqsave(&ni->size_lock, flags);
  	initialized_size = ni->initialized_size;
  	read_unlock_irqrestore(&ni->size_lock, flags);
  	while (wait_bh > wait) {
  		bh = *--wait_bh;
  		wait_on_buffer(bh);
  		if (likely(buffer_uptodate(bh))) {
  			page = bh->b_page;
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1208
  			bh_pos = ((s64)page->index << PAGE_SHIFT) +
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1209
1210
1211
1212
1213
1214
  					bh_offset(bh);
  			/*
  			 * If the buffer overflows the initialized size, need
  			 * to zero the overflowing region.
  			 */
  			if (unlikely(bh_pos + blocksize > initialized_size)) {
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1215
1216
1217
1218
  				int ofs = 0;
  
  				if (likely(bh_pos < initialized_size))
  					ofs = initialized_size - bh_pos;
eebd2aa35   Christoph Lameter   Pagecache zeroing...
1219
1220
  				zero_user_segment(page, bh_offset(bh) + ofs,
  						blocksize);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
  			}
  		} else /* if (unlikely(!buffer_uptodate(bh))) */
  			err = -EIO;
  	}
  	if (likely(!err)) {
  		/* Clear buffer_new on all buffers. */
  		u = 0;
  		do {
  			bh = head = page_buffers(pages[u]);
  			do {
  				if (buffer_new(bh))
  					clear_buffer_new(bh);
  			} while ((bh = bh->b_this_page) != head);
  		} while (++u < nr_pages);
  		ntfs_debug("Done.");
  		return err;
  	}
  	if (status.attr_switched) {
  		/* Get back to the attribute extent we modified. */
  		ntfs_attr_reinit_search_ctx(ctx);
  		if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  				CASE_SENSITIVE, bh_cpos, NULL, 0, ctx)) {
  			ntfs_error(vol->sb, "Failed to find required "
  					"attribute extent of attribute in "
  					"error code path.  Run chkdsk to "
  					"recover.");
  			write_lock_irqsave(&ni->size_lock, flags);
  			ni->itype.compressed.size += vol->cluster_size;
  			write_unlock_irqrestore(&ni->size_lock, flags);
  			flush_dcache_mft_record_page(ctx->ntfs_ino);
  			mark_mft_record_dirty(ctx->ntfs_ino);
  			/*
  			 * The only thing that is now wrong is the compressed
  			 * size of the base attribute extent which chkdsk
  			 * should be able to fix.
  			 */
  			NVolSetErrors(vol);
  		} else {
  			m = ctx->mrec;
  			a = ctx->attr;
  			status.attr_switched = 0;
  		}
  	}
  	/*
  	 * If the runlist has been modified, need to restore it by punching a
  	 * hole into it and we then need to deallocate the on-disk cluster as
  	 * well.  Note, we only modify the runlist if we are able to generate a
  	 * new mapping pairs array, i.e. only when the mapped attribute extent
  	 * is not switched.
  	 */
  	if (status.runlist_merged && !status.attr_switched) {
  		BUG_ON(!rl_write_locked);
  		/* Make the file cluster we allocated sparse in the runlist. */
  		if (ntfs_rl_punch_nolock(vol, &ni->runlist, bh_cpos, 1)) {
  			ntfs_error(vol->sb, "Failed to punch hole into "
  					"attribute runlist in error code "
  					"path.  Run chkdsk to recover the "
  					"lost cluster.");
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
  			NVolSetErrors(vol);
  		} else /* if (success) */ {
  			status.runlist_merged = 0;
  			/*
  			 * Deallocate the on-disk cluster we allocated but only
  			 * if we succeeded in punching its vcn out of the
  			 * runlist.
  			 */
  			down_write(&vol->lcnbmp_lock);
  			if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
  				ntfs_error(vol->sb, "Failed to release "
  						"allocated cluster in error "
  						"code path.  Run chkdsk to "
  						"recover the lost cluster.");
  				NVolSetErrors(vol);
  			}
  			up_write(&vol->lcnbmp_lock);
  		}
  	}
  	/*
  	 * Resize the attribute record to its old size and rebuild the mapping
  	 * pairs array.  Note, we only can do this if the runlist has been
  	 * restored to its old state which also implies that the mapped
  	 * attribute extent is not switched.
  	 */
  	if (status.mp_rebuilt && !status.runlist_merged) {
  		if (ntfs_attr_record_resize(m, a, attr_rec_len)) {
  			ntfs_error(vol->sb, "Failed to restore attribute "
  					"record in error code path.  Run "
  					"chkdsk to recover.");
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
  			NVolSetErrors(vol);
  		} else /* if (success) */ {
  			if (ntfs_mapping_pairs_build(vol, (u8*)a +
  					le16_to_cpu(a->data.non_resident.
  					mapping_pairs_offset), attr_rec_len -
  					le16_to_cpu(a->data.non_resident.
  					mapping_pairs_offset), ni->runlist.rl,
  					vcn, highest_vcn, NULL)) {
  				ntfs_error(vol->sb, "Failed to restore "
  						"mapping pairs array in error "
  						"code path.  Run chkdsk to "
  						"recover.");
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
  				NVolSetErrors(vol);
  			}
  			flush_dcache_mft_record_page(ctx->ntfs_ino);
  			mark_mft_record_dirty(ctx->ntfs_ino);
  		}
  	}
  	/* Release the mft record and the attribute. */
  	if (status.mft_attr_mapped) {
  		ntfs_attr_put_search_ctx(ctx);
  		unmap_mft_record(base_ni);
  	}
  	/* Release the runlist lock. */
  	if (rl_write_locked)
  		up_write(&ni->runlist.lock);
  	else if (rl)
  		up_read(&ni->runlist.lock);
  	/*
  	 * Zero out any newly allocated blocks to avoid exposing stale data.
  	 * If BH_New is set, we know that the block was newly allocated above
  	 * and that it has not been fully zeroed and marked dirty yet.
  	 */
  	nr_pages = u;
  	u = 0;
  	end = bh_cpos << vol->cluster_size_bits;
  	do {
  		page = pages[u];
  		bh = head = page_buffers(page);
  		do {
  			if (u == nr_pages &&
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1350
  					((s64)page->index << PAGE_SHIFT) +
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1351
1352
1353
1354
1355
1356
1357
1358
1359
  					bh_offset(bh) >= end)
  				break;
  			if (!buffer_new(bh))
  				continue;
  			clear_buffer_new(bh);
  			if (!buffer_uptodate(bh)) {
  				if (PageUptodate(page))
  					set_buffer_uptodate(bh);
  				else {
eebd2aa35   Christoph Lameter   Pagecache zeroing...
1360
1361
  					zero_user(page, bh_offset(bh),
  							blocksize);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1362
1363
1364
1365
1366
1367
1368
1369
1370
  					set_buffer_uptodate(bh);
  				}
  			}
  			mark_buffer_dirty(bh);
  		} while ((bh = bh->b_this_page) != head);
  	} while (++u <= nr_pages);
  	ntfs_error(vol->sb, "Failed.  Returning error code %i.", err);
  	return err;
  }
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1371
1372
1373
1374
  static inline void ntfs_flush_dcache_pages(struct page **pages,
  		unsigned nr_pages)
  {
  	BUG_ON(!nr_pages);
f893afbe1   Anton Altaparmakov   [PATCH] NTFS: Cri...
1375
1376
1377
1378
1379
  	/*
  	 * Warning: Do not do the decrement at the same time as the call to
  	 * flush_dcache_page() because it is a NULL macro on i386 and hence the
  	 * decrement never happens so the loop never terminates.
  	 */
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1380
  	do {
f893afbe1   Anton Altaparmakov   [PATCH] NTFS: Cri...
1381
  		--nr_pages;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1382
  		flush_dcache_page(pages[nr_pages]);
f893afbe1   Anton Altaparmakov   [PATCH] NTFS: Cri...
1383
  	} while (nr_pages > 0);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
  }
  
  /**
   * ntfs_commit_pages_after_non_resident_write - commit the received data
   * @pages:	array of destination pages
   * @nr_pages:	number of pages in @pages
   * @pos:	byte position in file at which the write begins
   * @bytes:	number of bytes to be written
   *
   * See description of ntfs_commit_pages_after_write(), below.
   */
  static inline int ntfs_commit_pages_after_non_resident_write(
  		struct page **pages, const unsigned nr_pages,
  		s64 pos, size_t bytes)
  {
  	s64 end, initialized_size;
  	struct inode *vi;
  	ntfs_inode *ni, *base_ni;
  	struct buffer_head *bh, *head;
  	ntfs_attr_search_ctx *ctx;
  	MFT_RECORD *m;
  	ATTR_RECORD *a;
  	unsigned long flags;
  	unsigned blocksize, u;
  	int err;
  
  	vi = pages[0]->mapping->host;
  	ni = NTFS_I(vi);
78af34f03   Anton Altaparmakov   NTFS: Implement s...
1412
  	blocksize = vi->i_sb->s_blocksize;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1413
1414
1415
1416
1417
  	end = pos + bytes;
  	u = 0;
  	do {
  		s64 bh_pos;
  		struct page *page;
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
1418
  		bool partial;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1419
1420
  
  		page = pages[u];
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1421
  		bh_pos = (s64)page->index << PAGE_SHIFT;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1422
  		bh = head = page_buffers(page);
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
1423
  		partial = false;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1424
1425
1426
1427
1428
1429
  		do {
  			s64 bh_end;
  
  			bh_end = bh_pos + blocksize;
  			if (bh_end <= pos || bh_pos >= end) {
  				if (!buffer_uptodate(bh))
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
1430
  					partial = true;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
  			} else {
  				set_buffer_uptodate(bh);
  				mark_buffer_dirty(bh);
  			}
  		} while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
  		/*
  		 * If all buffers are now uptodate but the page is not, set the
  		 * page uptodate.
  		 */
  		if (!partial && !PageUptodate(page))
  			SetPageUptodate(page);
  	} while (++u < nr_pages);
  	/*
  	 * Finally, if we do not need to update initialized_size or i_size we
  	 * are finished.
  	 */
  	read_lock_irqsave(&ni->size_lock, flags);
  	initialized_size = ni->initialized_size;
  	read_unlock_irqrestore(&ni->size_lock, flags);
  	if (end <= initialized_size) {
  		ntfs_debug("Done.");
  		return 0;
  	}
  	/*
  	 * Update initialized_size/i_size as appropriate, both in the inode and
  	 * the mft record.
  	 */
  	if (!NInoAttr(ni))
  		base_ni = ni;
  	else
  		base_ni = ni->ext.base_ntfs_ino;
  	/* Map, pin, and lock the mft record. */
  	m = map_mft_record(base_ni);
  	if (IS_ERR(m)) {
  		err = PTR_ERR(m);
  		m = NULL;
  		ctx = NULL;
  		goto err_out;
  	}
  	BUG_ON(!NInoNonResident(ni));
  	ctx = ntfs_attr_get_search_ctx(base_ni, m);
  	if (unlikely(!ctx)) {
  		err = -ENOMEM;
  		goto err_out;
  	}
  	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  			CASE_SENSITIVE, 0, NULL, 0, ctx);
  	if (unlikely(err)) {
  		if (err == -ENOENT)
  			err = -EIO;
  		goto err_out;
  	}
  	a = ctx->attr;
  	BUG_ON(!a->non_resident);
  	write_lock_irqsave(&ni->size_lock, flags);
  	BUG_ON(end > ni->allocated_size);
  	ni->initialized_size = end;
  	a->data.non_resident.initialized_size = cpu_to_sle64(end);
  	if (end > i_size_read(vi)) {
  		i_size_write(vi, end);
  		a->data.non_resident.data_size =
  				a->data.non_resident.initialized_size;
  	}
  	write_unlock_irqrestore(&ni->size_lock, flags);
  	/* Mark the mft record dirty, so it gets written back. */
  	flush_dcache_mft_record_page(ctx->ntfs_ino);
  	mark_mft_record_dirty(ctx->ntfs_ino);
  	ntfs_attr_put_search_ctx(ctx);
  	unmap_mft_record(base_ni);
  	ntfs_debug("Done.");
  	return 0;
  err_out:
  	if (ctx)
  		ntfs_attr_put_search_ctx(ctx);
  	if (m)
  		unmap_mft_record(base_ni);
  	ntfs_error(vi->i_sb, "Failed to update initialized_size/i_size (error "
  			"code %i).", err);
f95c4018f   Anton Altaparmakov   NTFS: Remove all ...
1509
  	if (err != -ENOMEM)
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1510
  		NVolSetErrors(ni->vol);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
  	return err;
  }
  
  /**
   * ntfs_commit_pages_after_write - commit the received data
   * @pages:	array of destination pages
   * @nr_pages:	number of pages in @pages
   * @pos:	byte position in file at which the write begins
   * @bytes:	number of bytes to be written
   *
1b1dcc1b5   Jes Sorensen   [PATCH] mutex sub...
1521
   * This is called from ntfs_file_buffered_write() with i_mutex held on the inode
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
   * (@pages[0]->mapping->host).  There are @nr_pages pages in @pages which are
   * locked but not kmap()ped.  The source data has already been copied into the
   * @page.  ntfs_prepare_pages_for_non_resident_write() has been called before
   * the data was copied (for non-resident attributes only) and it returned
   * success.
   *
   * Need to set uptodate and mark dirty all buffers within the boundary of the
   * write.  If all buffers in a page are uptodate we set the page uptodate, too.
   *
   * Setting the buffers dirty ensures that they get written out later when
   * ntfs_writepage() is invoked by the VM.
   *
   * Finally, we need to update i_size and initialized_size as appropriate both
   * in the inode and the mft record.
   *
   * This is modelled after fs/buffer.c::generic_commit_write(), which marks
   * buffers uptodate and dirty, sets the page uptodate if all buffers in the
   * page are uptodate, and updates i_size if the end of io is beyond i_size.  In
   * that case, it also marks the inode dirty.
   *
   * If things have gone as outlined in
   * ntfs_prepare_pages_for_non_resident_write(), we do not need to do any page
   * content modifications here for non-resident attributes.  For resident
   * attributes we need to do the uptodate bringing here which we combine with
   * the copying into the mft record which means we save one atomic kmap.
   *
   * Return 0 on success or -errno on error.
   */
  static int ntfs_commit_pages_after_write(struct page **pages,
  		const unsigned nr_pages, s64 pos, size_t bytes)
  {
  	s64 end, initialized_size;
  	loff_t i_size;
  	struct inode *vi;
  	ntfs_inode *ni, *base_ni;
  	struct page *page;
  	ntfs_attr_search_ctx *ctx;
  	MFT_RECORD *m;
  	ATTR_RECORD *a;
  	char *kattr, *kaddr;
  	unsigned long flags;
  	u32 attr_len;
  	int err;
  
  	BUG_ON(!nr_pages);
  	BUG_ON(!pages);
  	page = pages[0];
  	BUG_ON(!page);
  	vi = page->mapping->host;
  	ni = NTFS_I(vi);
  	ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
d04bd1fb6   Anton Altaparmakov   NTFS: Use %z for ...
1573
  			"index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
  			vi->i_ino, ni->type, page->index, nr_pages,
  			(long long)pos, bytes);
  	if (NInoNonResident(ni))
  		return ntfs_commit_pages_after_non_resident_write(pages,
  				nr_pages, pos, bytes);
  	BUG_ON(nr_pages > 1);
  	/*
  	 * Attribute is resident, implying it is not compressed, encrypted, or
  	 * sparse.
  	 */
  	if (!NInoAttr(ni))
  		base_ni = ni;
  	else
  		base_ni = ni->ext.base_ntfs_ino;
  	BUG_ON(NInoNonResident(ni));
  	/* Map, pin, and lock the mft record. */
  	m = map_mft_record(base_ni);
  	if (IS_ERR(m)) {
  		err = PTR_ERR(m);
  		m = NULL;
  		ctx = NULL;
  		goto err_out;
  	}
  	ctx = ntfs_attr_get_search_ctx(base_ni, m);
  	if (unlikely(!ctx)) {
  		err = -ENOMEM;
  		goto err_out;
  	}
  	err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
  			CASE_SENSITIVE, 0, NULL, 0, ctx);
  	if (unlikely(err)) {
  		if (err == -ENOENT)
  			err = -EIO;
  		goto err_out;
  	}
  	a = ctx->attr;
  	BUG_ON(a->non_resident);
  	/* The total length of the attribute value. */
  	attr_len = le32_to_cpu(a->data.resident.value_length);
  	i_size = i_size_read(vi);
  	BUG_ON(attr_len != i_size);
  	BUG_ON(pos > attr_len);
  	end = pos + bytes;
  	BUG_ON(end > le32_to_cpu(a->length) -
  			le16_to_cpu(a->data.resident.value_offset));
  	kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
a3ac1414e   Cong Wang   ntfs: remove the ...
1620
  	kaddr = kmap_atomic(page);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
  	/* Copy the received data from the page to the mft record. */
  	memcpy(kattr + pos, kaddr + pos, bytes);
  	/* Update the attribute length if necessary. */
  	if (end > attr_len) {
  		attr_len = end;
  		a->data.resident.value_length = cpu_to_le32(attr_len);
  	}
  	/*
  	 * If the page is not uptodate, bring the out of bounds area(s)
  	 * uptodate by copying data from the mft record to the page.
  	 */
  	if (!PageUptodate(page)) {
  		if (pos > 0)
  			memcpy(kaddr, kattr, pos);
  		if (end < attr_len)
  			memcpy(kaddr + end, kattr + end, attr_len - end);
  		/* Zero the region outside the end of the attribute value. */
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1638
  		memset(kaddr + attr_len, 0, PAGE_SIZE - attr_len);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1639
1640
1641
  		flush_dcache_page(page);
  		SetPageUptodate(page);
  	}
a3ac1414e   Cong Wang   ntfs: remove the ...
1642
  	kunmap_atomic(kaddr);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1643
1644
1645
1646
1647
1648
1649
  	/* Update initialized_size/i_size if necessary. */
  	read_lock_irqsave(&ni->size_lock, flags);
  	initialized_size = ni->initialized_size;
  	BUG_ON(end > ni->allocated_size);
  	read_unlock_irqrestore(&ni->size_lock, flags);
  	BUG_ON(initialized_size != i_size);
  	if (end > initialized_size) {
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
  		write_lock_irqsave(&ni->size_lock, flags);
  		ni->initialized_size = end;
  		i_size_write(vi, end);
  		write_unlock_irqrestore(&ni->size_lock, flags);
  	}
  	/* Mark the mft record dirty, so it gets written back. */
  	flush_dcache_mft_record_page(ctx->ntfs_ino);
  	mark_mft_record_dirty(ctx->ntfs_ino);
  	ntfs_attr_put_search_ctx(ctx);
  	unmap_mft_record(base_ni);
  	ntfs_debug("Done.");
  	return 0;
  err_out:
  	if (err == -ENOMEM) {
  		ntfs_warning(vi->i_sb, "Error allocating memory required to "
  				"commit the write.");
  		if (PageUptodate(page)) {
  			ntfs_warning(vi->i_sb, "Page is uptodate, setting "
  					"dirty so the write will be retried "
  					"later on by the VM.");
  			/*
  			 * Put the page on mapping->dirty_pages, but leave its
  			 * buffers' dirty state as-is.
  			 */
  			__set_page_dirty_nobuffers(page);
  			err = 0;
  		} else
  			ntfs_error(vi->i_sb, "Page is not uptodate.  Written "
  					"data has been lost.");
  	} else {
  		ntfs_error(vi->i_sb, "Resident attribute commit write failed "
  				"with error %i.", err);
  		NVolSetErrors(ni->vol);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1683
1684
1685
1686
1687
1688
1689
  	}
  	if (ctx)
  		ntfs_attr_put_search_ctx(ctx);
  	if (m)
  		unmap_mft_record(base_ni);
  	return err;
  }
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1690
1691
1692
1693
1694
1695
1696
  /*
   * Copy as much as we can into the pages and return the number of bytes which
   * were successfully copied.  If a fault is encountered then clear the pages
   * out to (ofs + bytes) and return the number of bytes which were copied.
   */
  static size_t ntfs_copy_from_user_iter(struct page **pages, unsigned nr_pages,
  		unsigned ofs, struct iov_iter *i, size_t bytes)
9014da752   Marco Stornelli   ntfs: drop vmtrun...
1697
  {
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1698
1699
1700
1701
  	struct page **last_page = pages + nr_pages;
  	size_t total = 0;
  	struct iov_iter data = *i;
  	unsigned len, copied;
9014da752   Marco Stornelli   ntfs: drop vmtrun...
1702

a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1703
  	do {
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1704
  		len = PAGE_SIZE - ofs;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
  		if (len > bytes)
  			len = bytes;
  		copied = iov_iter_copy_from_user_atomic(*pages, &data, ofs,
  				len);
  		total += copied;
  		bytes -= copied;
  		if (!bytes)
  			break;
  		iov_iter_advance(&data, copied);
  		if (copied < len)
  			goto err;
  		ofs = 0;
  	} while (++pages < last_page);
  out:
  	return total;
  err:
  	/* Zero the rest of the target like __copy_from_user(). */
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1722
  	len = PAGE_SIZE - copied;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1723
1724
1725
1726
1727
1728
  	do {
  		if (len > bytes)
  			len = bytes;
  		zero_user(*pages, copied, len);
  		bytes -= len;
  		copied = 0;
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1729
  		len = PAGE_SIZE;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1730
1731
  	} while (++pages < last_page);
  	goto out;
9014da752   Marco Stornelli   ntfs: drop vmtrun...
1732
  }
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1733
  /**
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1734
1735
1736
1737
   * ntfs_perform_write - perform buffered write to a file
   * @file:	file to write to
   * @i:		iov_iter with data to write
   * @pos:	byte offset in file at which to begin writing to
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1738
   */
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1739
1740
  static ssize_t ntfs_perform_write(struct file *file, struct iov_iter *i,
  		loff_t pos)
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1741
  {
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1742
1743
1744
1745
1746
1747
  	struct address_space *mapping = file->f_mapping;
  	struct inode *vi = mapping->host;
  	ntfs_inode *ni = NTFS_I(vi);
  	ntfs_volume *vol = ni->vol;
  	struct page *pages[NTFS_MAX_PAGES_PER_CLUSTER];
  	struct page *cached_page = NULL;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1748
1749
  	VCN last_vcn;
  	LCN lcn;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1750
1751
  	size_t bytes;
  	ssize_t status, written = 0;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1752
  	unsigned nr_pages;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1753

a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1754
1755
1756
1757
1758
  	ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
  			"0x%llx, count 0x%lx.", vi->i_ino,
  			(unsigned)le32_to_cpu(ni->type),
  			(unsigned long long)pos,
  			(unsigned long)iov_iter_count(i));
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1759
1760
1761
1762
1763
  	/*
  	 * If a previous ntfs_truncate() failed, repeat it and abort if it
  	 * fails again.
  	 */
  	if (unlikely(NInoTruncateFailed(ni))) {
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1764
  		int err;
bd5fe6c5e   Christoph Hellwig   fs: kill i_alloc_sem
1765
  		inode_dio_wait(vi);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1766
  		err = ntfs_truncate(vi);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
  		if (err || NInoTruncateFailed(ni)) {
  			if (!err)
  				err = -EIO;
  			ntfs_error(vol->sb, "Cannot perform write to inode "
  					"0x%lx, attribute type 0x%x, because "
  					"ntfs_truncate() failed (error code "
  					"%i).", vi->i_ino,
  					(unsigned)le32_to_cpu(ni->type), err);
  			return err;
  		}
  	}
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1778
1779
1780
1781
1782
  	/*
  	 * Determine the number of pages per cluster for non-resident
  	 * attributes.
  	 */
  	nr_pages = 1;
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1783
1784
  	if (vol->cluster_size > PAGE_SIZE && NInoNonResident(ni))
  		nr_pages = vol->cluster_size >> PAGE_SHIFT;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1785
  	last_vcn = -1;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1786
1787
1788
1789
1790
  	do {
  		VCN vcn;
  		pgoff_t idx, start_idx;
  		unsigned ofs, do_pages, u;
  		size_t copied;
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1791
1792
1793
  		start_idx = idx = pos >> PAGE_SHIFT;
  		ofs = pos & ~PAGE_MASK;
  		bytes = PAGE_SIZE - ofs;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
  		do_pages = 1;
  		if (nr_pages > 1) {
  			vcn = pos >> vol->cluster_size_bits;
  			if (vcn != last_vcn) {
  				last_vcn = vcn;
  				/*
  				 * Get the lcn of the vcn the write is in.  If
  				 * it is a hole, need to lock down all pages in
  				 * the cluster.
  				 */
  				down_read(&ni->runlist.lock);
  				lcn = ntfs_attr_vcn_to_lcn_nolock(ni, pos >>
c49c31115   Richard Knutsson   [PATCH] fs/ntfs: ...
1806
  						vol->cluster_size_bits, false);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1807
1808
  				up_read(&ni->runlist.lock);
  				if (unlikely(lcn < LCN_HOLE)) {
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1809
1810
  					if (lcn == LCN_ENOMEM)
  						status = -ENOMEM;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1811
1812
  					else {
  						status = -EIO;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1813
1814
1815
1816
1817
1818
1819
1820
  						ntfs_error(vol->sb, "Cannot "
  							"perform write to "
  							"inode 0x%lx, "
  							"attribute type 0x%x, "
  							"because the attribute "
  							"is corrupt.",
  							vi->i_ino, (unsigned)
  							le32_to_cpu(ni->type));
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1821
  					}
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1822
1823
1824
1825
1826
  					break;
  				}
  				if (lcn == LCN_HOLE) {
  					start_idx = (pos & ~(s64)
  							vol->cluster_size_mask)
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1827
  							>> PAGE_SHIFT;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1828
1829
1830
1831
1832
1833
  					bytes = vol->cluster_size - (pos &
  							vol->cluster_size_mask);
  					do_pages = nr_pages;
  				}
  			}
  		}
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1834
1835
1836
  		if (bytes > iov_iter_count(i))
  			bytes = iov_iter_count(i);
  again:
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1837
1838
1839
1840
1841
1842
1843
1844
  		/*
  		 * Bring in the user page(s) that we will copy from _first_.
  		 * Otherwise there is a nasty deadlock on copying from the same
  		 * page(s) as we are writing to, without it/them being marked
  		 * up-to-date.  Note, at present there is nothing to stop the
  		 * pages being swapped out between us bringing them into memory
  		 * and doing the actual copying.
  		 */
4bce9f6ee   Al Viro   get rid of separa...
1845
  		if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1846
1847
1848
  			status = -EFAULT;
  			break;
  		}
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1849
1850
  		/* Get and lock @do_pages starting at index @start_idx. */
  		status = __ntfs_grab_cache_pages(mapping, start_idx, do_pages,
4c99000ac   Minchan Kim   ntfs: use add_to_...
1851
  				pages, &cached_page);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
  		if (unlikely(status))
  			break;
  		/*
  		 * For non-resident attributes, we need to fill any holes with
  		 * actual clusters and ensure all bufferes are mapped.  We also
  		 * need to bring uptodate any buffers that are only partially
  		 * being written to.
  		 */
  		if (NInoNonResident(ni)) {
  			status = ntfs_prepare_pages_for_non_resident_write(
  					pages, do_pages, pos, bytes);
  			if (unlikely(status)) {
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1864
1865
  				do {
  					unlock_page(pages[--do_pages]);
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1866
  					put_page(pages[do_pages]);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1867
  				} while (do_pages);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1868
1869
1870
  				break;
  			}
  		}
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1871
  		u = (pos >> PAGE_SHIFT) - pages[0]->index;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1872
1873
  		copied = ntfs_copy_from_user_iter(pages + u, do_pages - u, ofs,
  					i, bytes);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1874
  		ntfs_flush_dcache_pages(pages + u, do_pages - u);
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1875
1876
1877
1878
1879
1880
  		status = 0;
  		if (likely(copied == bytes)) {
  			status = ntfs_commit_pages_after_write(pages, do_pages,
  					pos, bytes);
  			if (!status)
  				status = bytes;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1881
1882
1883
  		}
  		do {
  			unlock_page(pages[--do_pages]);
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1884
  			put_page(pages[do_pages]);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1885
  		} while (do_pages);
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1886
  		if (unlikely(status < 0))
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1887
  			break;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1888
  		copied = status;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1889
  		cond_resched();
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
  		if (unlikely(!copied)) {
  			size_t sc;
  
  			/*
  			 * We failed to copy anything.  Fall back to single
  			 * segment length write.
  			 *
  			 * This is needed to avoid possible livelock in the
  			 * case that all segments in the iov cannot be copied
  			 * at once without a pagefault.
  			 */
  			sc = iov_iter_single_seg_count(i);
  			if (bytes > sc)
  				bytes = sc;
  			goto again;
  		}
  		iov_iter_advance(i, copied);
  		pos += copied;
  		written += copied;
  		balance_dirty_pages_ratelimited(mapping);
  		if (fatal_signal_pending(current)) {
  			status = -EINTR;
  			break;
  		}
  	} while (iov_iter_count(i));
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1915
  	if (cached_page)
09cbfeaf1   Kirill A. Shutemov   mm, fs: get rid o...
1916
  		put_page(cached_page);
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1917
1918
1919
1920
1921
1922
1923
  	ntfs_debug("Done.  Returning %s (written 0x%lx, status %li).",
  			written ? "written" : "status", (unsigned long)written,
  			(long)status);
  	return written ? written : status;
  }
  
  /**
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1924
1925
1926
1927
1928
   * ntfs_file_write_iter - simple wrapper for ntfs_file_write_iter_nolock()
   * @iocb:	IO state structure
   * @from:	iov_iter with data to write
   *
   * Basically the same as generic_file_write_iter() except that it ends up
ccca26835   Al Viro   ntfs: move iov_it...
1929
1930
   * up calling ntfs_perform_write() instead of generic_perform_write() and that
   * O_DIRECT is not implemented.
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1931
   */
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1932
  static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1933
1934
  {
  	struct file *file = iocb->ki_filp;
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
1935
  	struct inode *vi = file_inode(file);
ccca26835   Al Viro   ntfs: move iov_it...
1936
1937
  	ssize_t written = 0;
  	ssize_t err;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1938

5955102c9   Al Viro   wrappers for ->i_...
1939
  	inode_lock(vi);
ccca26835   Al Viro   ntfs: move iov_it...
1940
1941
1942
1943
1944
1945
  	/* We can write back this queue in page reclaim. */
  	current->backing_dev_info = inode_to_bdi(vi);
  	err = ntfs_prepare_file_for_write(iocb, from);
  	if (iov_iter_count(from) && !err)
  		written = ntfs_perform_write(file, from, iocb->ki_pos);
  	current->backing_dev_info = NULL;
5955102c9   Al Viro   wrappers for ->i_...
1946
  	inode_unlock(vi);
ccca26835   Al Viro   ntfs: move iov_it...
1947
  	iocb->ki_pos += written;
e25922176   Christoph Hellwig   fs: simplify the ...
1948
1949
  	if (likely(written > 0))
  		written = generic_write_sync(iocb, written);
ccca26835   Al Viro   ntfs: move iov_it...
1950
  	return written ? written : err;
98b270362   Anton Altaparmakov   NTFS: The big ntf...
1951
1952
1953
  }
  
  /**
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1954
1955
   * ntfs_file_fsync - sync a file to disk
   * @filp:	file to be synced
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
   * @datasync:	if non-zero only flush user data and not metadata
   *
   * Data integrity sync of a file to disk.  Used for fsync, fdatasync, and msync
   * system calls.  This function is inspired by fs/buffer.c::file_fsync().
   *
   * If @datasync is false, write the mft record and all associated extent mft
   * records as well as the $DATA attribute and then sync the block device.
   *
   * If @datasync is true and the attribute is non-resident, we skip the writing
   * of the mft record and all associated extent mft records (this might still
   * happen due to the write_inode_now() call).
   *
   * Also, if @datasync is true, we do not wait on the inode to be written out
   * but we always wait on the page cache pages to be written out.
   *
1b1dcc1b5   Jes Sorensen   [PATCH] mutex sub...
1971
   * Locking: Caller must hold i_mutex on the inode.
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1972
1973
1974
1975
1976
   *
   * TODO: We should probably also write all attribute/index inodes associated
   * with this inode but since we have no simple way of getting to them we ignore
   * this problem for now.
   */
02c24a821   Josef Bacik   fs: push i_mutex ...
1977
1978
  static int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end,
  			   int datasync)
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1979
  {
7ea808591   Christoph Hellwig   drop unused dentr...
1980
  	struct inode *vi = filp->f_mapping->host;
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1981
1982
1983
  	int err, ret = 0;
  
  	ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
02c24a821   Josef Bacik   fs: push i_mutex ...
1984

3b49c9a1e   Jeff Layton   fs: convert a pil...
1985
  	err = file_write_and_wait_range(filp, start, end);
02c24a821   Josef Bacik   fs: push i_mutex ...
1986
1987
  	if (err)
  		return err;
5955102c9   Al Viro   wrappers for ->i_...
1988
  	inode_lock(vi);
02c24a821   Josef Bacik   fs: push i_mutex ...
1989

1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1990
1991
  	BUG_ON(S_ISDIR(vi->i_mode));
  	if (!datasync || !NInoNonResident(NTFS_I(vi)))
a9185b41a   Christoph Hellwig   pass writeback_co...
1992
  		ret = __ntfs_write_inode(vi, 1);
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1993
  	write_inode_now(vi, !datasync);
f25dfb5e4   Anton Altaparmakov   NTFS: Remove bogu...
1994
1995
1996
1997
1998
  	/*
  	 * NOTE: If we were to use mapping->private_list (see ext2 and
  	 * fs/buffer.c) for dirty blocks then we could optimize the below to be
  	 * sync_mapping_buffers(vi->i_mapping).
  	 */
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
1999
2000
2001
2002
2003
2004
2005
2006
  	err = sync_blockdev(vi->i_sb->s_bdev);
  	if (unlikely(err && !ret))
  		ret = err;
  	if (likely(!ret))
  		ntfs_debug("Done.");
  	else
  		ntfs_warning(vi->i_sb, "Failed to f%ssync inode 0x%lx.  Error "
  				"%u.", datasync ? "data" : "", vi->i_ino, -ret);
5955102c9   Al Viro   wrappers for ->i_...
2007
  	inode_unlock(vi);
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
2008
2009
2010
2011
  	return ret;
  }
  
  #endif /* NTFS_RW */
4b6f5d20b   Arjan van de Ven   [PATCH] Make most...
2012
  const struct file_operations ntfs_file_ops = {
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
2013
  	.llseek		= generic_file_llseek,
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
2014
  	.read_iter	= generic_file_read_iter,
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
2015
  #ifdef NTFS_RW
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
2016
2017
  	.write_iter	= ntfs_file_write_iter,
  	.fsync		= ntfs_file_fsync,
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
2018
  #endif /* NTFS_RW */
a632f5593   Anton Altaparmakov   NTFS: Version 2.1...
2019
2020
2021
  	.mmap		= generic_file_mmap,
  	.open		= ntfs_file_open,
  	.splice_read	= generic_file_splice_read,
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
2022
  };
92e1d5be9   Arjan van de Ven   [PATCH] mark stru...
2023
  const struct inode_operations ntfs_file_inode_ops = {
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
2024
  #ifdef NTFS_RW
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
2025
2026
2027
  	.setattr	= ntfs_setattr,
  #endif /* NTFS_RW */
  };
4b6f5d20b   Arjan van de Ven   [PATCH] Make most...
2028
  const struct file_operations ntfs_empty_file_ops = {};
1da177e4c   Linus Torvalds   Linux-2.6.12-rc2
2029

92e1d5be9   Arjan van de Ven   [PATCH] mark stru...
2030
  const struct inode_operations ntfs_empty_inode_ops = {};