blob: 77087d5ad45828558e06cb8ff7937134edeef647 [file] [log] [blame]
Linus Torvalds1da177e2005-04-16 15:20:36 -07001/*
Anton Altaparmakovf25dfb52005-09-08 20:35:33 +01002 * file.c - NTFS kernel file operations. Part of the Linux-NTFS project.
Linus Torvalds1da177e2005-04-16 15:20:36 -07003 *
Anton Altaparmakova632f552015-03-11 10:43:32 -04004 * Copyright (c) 2001-2015 Anton Altaparmakov and Tuxera Inc.
Linus Torvalds1da177e2005-04-16 15:20:36 -07005 *
6 * This program/include file is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License as published
8 * by the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program/include file is distributed in the hope that it will be
12 * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program (in the main directory of the Linux-NTFS
18 * distribution in the file COPYING); if not, write to the Free Software
19 * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21
Christoph Hellwigde1414a2015-01-14 10:42:36 +010022#include <linux/backing-dev.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070023#include <linux/buffer_head.h>
Tejun Heo5a0e3ad2010-03-24 17:04:11 +090024#include <linux/gfp.h>
Anton Altaparmakov98b27032005-10-11 15:40:40 +010025#include <linux/pagemap.h>
26#include <linux/pagevec.h>
27#include <linux/sched.h>
28#include <linux/swap.h>
29#include <linux/uio.h>
30#include <linux/writeback.h>
Linus Torvalds1da177e2005-04-16 15:20:36 -070031
Anton Altaparmakov98b27032005-10-11 15:40:40 +010032#include <asm/page.h>
33#include <asm/uaccess.h>
34
35#include "attrib.h"
36#include "bitmap.h"
Linus Torvalds1da177e2005-04-16 15:20:36 -070037#include "inode.h"
38#include "debug.h"
Anton Altaparmakov98b27032005-10-11 15:40:40 +010039#include "lcnalloc.h"
40#include "malloc.h"
41#include "mft.h"
Linus Torvalds1da177e2005-04-16 15:20:36 -070042#include "ntfs.h"
43
44/**
45 * ntfs_file_open - called when an inode is about to be opened
46 * @vi: inode to be opened
47 * @filp: file structure describing the inode
48 *
49 * Limit file size to the page cache limit on architectures where unsigned long
50 * is 32-bits. This is the most we can do for now without overflowing the page
51 * cache page index. Doing it this way means we don't run into problems because
52 * of existing too large files. It would be better to allow the user to read
53 * the beginning of the file but I doubt very much anyone is going to hit this
54 * check on a 32-bit architecture, so there is no point in adding the extra
55 * complexity required to support this.
56 *
57 * On 64-bit architectures, the check is hopefully optimized away by the
58 * compiler.
59 *
60 * After the check passes, just call generic_file_open() to do its work.
61 */
62static int ntfs_file_open(struct inode *vi, struct file *filp)
63{
64 if (sizeof(unsigned long) < 8) {
Anton Altaparmakovd4b9ba72004-11-17 15:45:08 +000065 if (i_size_read(vi) > MAX_LFS_FILESIZE)
Alan Coxa9c62a12007-10-16 23:30:22 -070066 return -EOVERFLOW;
Linus Torvalds1da177e2005-04-16 15:20:36 -070067 }
68 return generic_file_open(vi, filp);
69}
70
71#ifdef NTFS_RW
72
73/**
Anton Altaparmakov98b27032005-10-11 15:40:40 +010074 * ntfs_attr_extend_initialized - extend the initialized size of an attribute
75 * @ni: ntfs inode of the attribute to extend
76 * @new_init_size: requested new initialized size in bytes
Anton Altaparmakov98b27032005-10-11 15:40:40 +010077 *
78 * Extend the initialized size of an attribute described by the ntfs inode @ni
79 * to @new_init_size bytes. This involves zeroing any non-sparse space between
80 * the old initialized size and @new_init_size both in the page cache and on
Anton Altaparmakovdda65b92005-10-24 08:57:59 +010081 * disk (if relevant complete pages are already uptodate in the page cache then
82 * these are simply marked dirty).
Anton Altaparmakov98b27032005-10-11 15:40:40 +010083 *
84 * As a side-effect, the file size (vfs inode->i_size) may be incremented as,
85 * in the resident attribute case, it is tied to the initialized size and, in
86 * the non-resident attribute case, it may not fall below the initialized size.
87 *
88 * Note that if the attribute is resident, we do not need to touch the page
89 * cache at all. This is because if the page cache page is not uptodate we
90 * bring it uptodate later, when doing the write to the mft record since we
91 * then already have the page mapped. And if the page is uptodate, the
92 * non-initialized region will already have been zeroed when the page was
93 * brought uptodate and the region may in fact already have been overwritten
94 * with new data via mmap() based writes, so we cannot just zero it. And since
95 * POSIX specifies that the behaviour of resizing a file whilst it is mmap()ped
96 * is unspecified, we choose not to do zeroing and thus we do not need to touch
Anton Altaparmakovdda65b92005-10-24 08:57:59 +010097 * the page at all. For a more detailed explanation see ntfs_truncate() in
98 * fs/ntfs/inode.c.
Anton Altaparmakov98b27032005-10-11 15:40:40 +010099 *
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100100 * Return 0 on success and -errno on error. In the case that an error is
101 * encountered it is possible that the initialized size will already have been
102 * incremented some way towards @new_init_size but it is guaranteed that if
103 * this is the case, the necessary zeroing will also have happened and that all
104 * metadata is self-consistent.
105 *
Jes Sorensen1b1dcc12006-01-09 15:59:24 -0800106 * Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be
Anton Altaparmakovdda65b92005-10-24 08:57:59 +0100107 * held by the caller.
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100108 */
Minchan Kim2ec93b02010-05-24 14:33:06 -0700109static int ntfs_attr_extend_initialized(ntfs_inode *ni, const s64 new_init_size)
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100110{
111 s64 old_init_size;
112 loff_t old_i_size;
113 pgoff_t index, end_index;
114 unsigned long flags;
115 struct inode *vi = VFS_I(ni);
116 ntfs_inode *base_ni;
117 MFT_RECORD *m = NULL;
118 ATTR_RECORD *a;
119 ntfs_attr_search_ctx *ctx = NULL;
120 struct address_space *mapping;
121 struct page *page = NULL;
122 u8 *kattr;
123 int err;
124 u32 attr_len;
125
126 read_lock_irqsave(&ni->size_lock, flags);
127 old_init_size = ni->initialized_size;
128 old_i_size = i_size_read(vi);
129 BUG_ON(new_init_size > ni->allocated_size);
130 read_unlock_irqrestore(&ni->size_lock, flags);
131 ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
132 "old_initialized_size 0x%llx, "
133 "new_initialized_size 0x%llx, i_size 0x%llx.",
134 vi->i_ino, (unsigned)le32_to_cpu(ni->type),
135 (unsigned long long)old_init_size,
136 (unsigned long long)new_init_size, old_i_size);
137 if (!NInoAttr(ni))
138 base_ni = ni;
139 else
140 base_ni = ni->ext.base_ntfs_ino;
141 /* Use goto to reduce indentation and we need the label below anyway. */
142 if (NInoNonResident(ni))
143 goto do_non_resident_extend;
144 BUG_ON(old_init_size != old_i_size);
145 m = map_mft_record(base_ni);
146 if (IS_ERR(m)) {
147 err = PTR_ERR(m);
148 m = NULL;
149 goto err_out;
150 }
151 ctx = ntfs_attr_get_search_ctx(base_ni, m);
152 if (unlikely(!ctx)) {
153 err = -ENOMEM;
154 goto err_out;
155 }
156 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
157 CASE_SENSITIVE, 0, NULL, 0, ctx);
158 if (unlikely(err)) {
159 if (err == -ENOENT)
160 err = -EIO;
161 goto err_out;
162 }
163 m = ctx->mrec;
164 a = ctx->attr;
165 BUG_ON(a->non_resident);
166 /* The total length of the attribute value. */
167 attr_len = le32_to_cpu(a->data.resident.value_length);
168 BUG_ON(old_i_size != (loff_t)attr_len);
169 /*
170 * Do the zeroing in the mft record and update the attribute size in
171 * the mft record.
172 */
173 kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
174 memset(kattr + attr_len, 0, new_init_size - attr_len);
175 a->data.resident.value_length = cpu_to_le32((u32)new_init_size);
176 /* Finally, update the sizes in the vfs and ntfs inodes. */
177 write_lock_irqsave(&ni->size_lock, flags);
178 i_size_write(vi, new_init_size);
179 ni->initialized_size = new_init_size;
180 write_unlock_irqrestore(&ni->size_lock, flags);
181 goto done;
182do_non_resident_extend:
183 /*
184 * If the new initialized size @new_init_size exceeds the current file
185 * size (vfs inode->i_size), we need to extend the file size to the
186 * new initialized size.
187 */
188 if (new_init_size > old_i_size) {
189 m = map_mft_record(base_ni);
190 if (IS_ERR(m)) {
191 err = PTR_ERR(m);
192 m = NULL;
193 goto err_out;
194 }
195 ctx = ntfs_attr_get_search_ctx(base_ni, m);
196 if (unlikely(!ctx)) {
197 err = -ENOMEM;
198 goto err_out;
199 }
200 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
201 CASE_SENSITIVE, 0, NULL, 0, ctx);
202 if (unlikely(err)) {
203 if (err == -ENOENT)
204 err = -EIO;
205 goto err_out;
206 }
207 m = ctx->mrec;
208 a = ctx->attr;
209 BUG_ON(!a->non_resident);
210 BUG_ON(old_i_size != (loff_t)
211 sle64_to_cpu(a->data.non_resident.data_size));
212 a->data.non_resident.data_size = cpu_to_sle64(new_init_size);
213 flush_dcache_mft_record_page(ctx->ntfs_ino);
214 mark_mft_record_dirty(ctx->ntfs_ino);
215 /* Update the file size in the vfs inode. */
216 i_size_write(vi, new_init_size);
217 ntfs_attr_put_search_ctx(ctx);
218 ctx = NULL;
219 unmap_mft_record(base_ni);
220 m = NULL;
221 }
222 mapping = vi->i_mapping;
223 index = old_init_size >> PAGE_CACHE_SHIFT;
224 end_index = (new_init_size + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
225 do {
226 /*
227 * Read the page. If the page is not present, this will zero
228 * the uninitialized regions for us.
229 */
Pekka Enberg090d2b12006-06-23 02:05:08 -0700230 page = read_mapping_page(mapping, index, NULL);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100231 if (IS_ERR(page)) {
232 err = PTR_ERR(page);
233 goto init_err_out;
234 }
Nick Piggin6fe69002007-05-06 14:49:04 -0700235 if (unlikely(PageError(page))) {
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100236 page_cache_release(page);
237 err = -EIO;
238 goto init_err_out;
239 }
240 /*
241 * Update the initialized size in the ntfs inode. This is
242 * enough to make ntfs_writepage() work.
243 */
244 write_lock_irqsave(&ni->size_lock, flags);
Anton Altaparmakov3c6af7f2005-11-24 13:41:33 +0000245 ni->initialized_size = (s64)(index + 1) << PAGE_CACHE_SHIFT;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100246 if (ni->initialized_size > new_init_size)
247 ni->initialized_size = new_init_size;
248 write_unlock_irqrestore(&ni->size_lock, flags);
249 /* Set the page dirty so it gets written out. */
250 set_page_dirty(page);
251 page_cache_release(page);
252 /*
253 * Play nice with the vm and the rest of the system. This is
254 * very much needed as we can potentially be modifying the
255 * initialised size from a very small value to a really huge
256 * value, e.g.
257 * f = open(somefile, O_TRUNC);
258 * truncate(f, 10GiB);
259 * seek(f, 10GiB);
260 * write(f, 1);
261 * And this would mean we would be marking dirty hundreds of
262 * thousands of pages or as in the above example more than
263 * two and a half million pages!
264 *
265 * TODO: For sparse pages could optimize this workload by using
266 * the FsMisc / MiscFs page bit as a "PageIsSparse" bit. This
267 * would be set in readpage for sparse pages and here we would
268 * not need to mark dirty any pages which have this bit set.
269 * The only caveat is that we have to clear the bit everywhere
270 * where we allocate any clusters that lie in the page or that
271 * contain the page.
272 *
273 * TODO: An even greater optimization would be for us to only
274 * call readpage() on pages which are not in sparse regions as
275 * determined from the runlist. This would greatly reduce the
276 * number of pages we read and make dirty in the case of sparse
277 * files.
278 */
279 balance_dirty_pages_ratelimited(mapping);
280 cond_resched();
281 } while (++index < end_index);
282 read_lock_irqsave(&ni->size_lock, flags);
283 BUG_ON(ni->initialized_size != new_init_size);
284 read_unlock_irqrestore(&ni->size_lock, flags);
285 /* Now bring in sync the initialized_size in the mft record. */
286 m = map_mft_record(base_ni);
287 if (IS_ERR(m)) {
288 err = PTR_ERR(m);
289 m = NULL;
290 goto init_err_out;
291 }
292 ctx = ntfs_attr_get_search_ctx(base_ni, m);
293 if (unlikely(!ctx)) {
294 err = -ENOMEM;
295 goto init_err_out;
296 }
297 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
298 CASE_SENSITIVE, 0, NULL, 0, ctx);
299 if (unlikely(err)) {
300 if (err == -ENOENT)
301 err = -EIO;
302 goto init_err_out;
303 }
304 m = ctx->mrec;
305 a = ctx->attr;
306 BUG_ON(!a->non_resident);
307 a->data.non_resident.initialized_size = cpu_to_sle64(new_init_size);
308done:
309 flush_dcache_mft_record_page(ctx->ntfs_ino);
310 mark_mft_record_dirty(ctx->ntfs_ino);
311 if (ctx)
312 ntfs_attr_put_search_ctx(ctx);
313 if (m)
314 unmap_mft_record(base_ni);
315 ntfs_debug("Done, initialized_size 0x%llx, i_size 0x%llx.",
316 (unsigned long long)new_init_size, i_size_read(vi));
317 return 0;
318init_err_out:
319 write_lock_irqsave(&ni->size_lock, flags);
320 ni->initialized_size = old_init_size;
321 write_unlock_irqrestore(&ni->size_lock, flags);
322err_out:
323 if (ctx)
324 ntfs_attr_put_search_ctx(ctx);
325 if (m)
326 unmap_mft_record(base_ni);
327 ntfs_debug("Failed. Returning error code %i.", err);
328 return err;
329}
330
Al Viroccca2682015-04-05 14:06:24 -0400331static ssize_t ntfs_prepare_file_for_write(struct kiocb *iocb,
332 struct iov_iter *from)
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100333{
Anton Altaparmakova632f552015-03-11 10:43:32 -0400334 loff_t pos;
335 s64 end, ll;
336 ssize_t err;
337 unsigned long flags;
Al Viroccca2682015-04-05 14:06:24 -0400338 struct file *file = iocb->ki_filp;
Anton Altaparmakova632f552015-03-11 10:43:32 -0400339 struct inode *vi = file_inode(file);
340 ntfs_inode *base_ni, *ni = NTFS_I(vi);
341 ntfs_volume *vol = ni->vol;
Al Viroccca2682015-04-05 14:06:24 -0400342 size_t count = iov_iter_count(from);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100343
Anton Altaparmakova632f552015-03-11 10:43:32 -0400344 ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
Al Viroccca2682015-04-05 14:06:24 -0400345 "0x%llx, count 0x%zx.", vi->i_ino,
Anton Altaparmakova632f552015-03-11 10:43:32 -0400346 (unsigned)le32_to_cpu(ni->type),
Al Viroccca2682015-04-05 14:06:24 -0400347 (unsigned long long)iocb->ki_pos, count);
348 err = generic_write_checks(file, &iocb->ki_pos, &count, S_ISBLK(vi->i_mode));
Anton Altaparmakova632f552015-03-11 10:43:32 -0400349 if (unlikely(err))
350 goto out;
Al Viroccca2682015-04-05 14:06:24 -0400351 iov_iter_truncate(from, count);
352 if (count == 0)
353 goto out;
Anton Altaparmakova632f552015-03-11 10:43:32 -0400354 /*
355 * All checks have passed. Before we start doing any writing we want
356 * to abort any totally illegal writes.
357 */
358 BUG_ON(NInoMstProtected(ni));
359 BUG_ON(ni->type != AT_DATA);
360 /* If file is encrypted, deny access, just like NT4. */
361 if (NInoEncrypted(ni)) {
362 /* Only $DATA attributes can be encrypted. */
363 /*
364 * Reminder for later: Encrypted files are _always_
365 * non-resident so that the content can always be encrypted.
366 */
367 ntfs_debug("Denying write access to encrypted file.");
368 err = -EACCES;
369 goto out;
370 }
371 if (NInoCompressed(ni)) {
372 /* Only unnamed $DATA attribute can be compressed. */
373 BUG_ON(ni->name_len);
374 /*
375 * Reminder for later: If resident, the data is not actually
376 * compressed. Only on the switch to non-resident does
377 * compression kick in. This is in contrast to encrypted files
378 * (see above).
379 */
380 ntfs_error(vi->i_sb, "Writing to compressed files is not "
381 "implemented yet. Sorry.");
382 err = -EOPNOTSUPP;
383 goto out;
384 }
Anton Altaparmakova632f552015-03-11 10:43:32 -0400385 base_ni = ni;
386 if (NInoAttr(ni))
387 base_ni = ni->ext.base_ntfs_ino;
388 err = file_remove_suid(file);
389 if (unlikely(err))
390 goto out;
391 /*
392 * Our ->update_time method always succeeds thus file_update_time()
393 * cannot fail either so there is no need to check the return code.
394 */
395 file_update_time(file);
Al Viroccca2682015-04-05 14:06:24 -0400396 pos = iocb->ki_pos;
Anton Altaparmakova632f552015-03-11 10:43:32 -0400397 /* The first byte after the last cluster being written to. */
Al Viroccca2682015-04-05 14:06:24 -0400398 end = (pos + iov_iter_count(from) + vol->cluster_size_mask) &
Anton Altaparmakova632f552015-03-11 10:43:32 -0400399 ~(u64)vol->cluster_size_mask;
400 /*
401 * If the write goes beyond the allocated size, extend the allocation
402 * to cover the whole of the write, rounded up to the nearest cluster.
403 */
404 read_lock_irqsave(&ni->size_lock, flags);
405 ll = ni->allocated_size;
406 read_unlock_irqrestore(&ni->size_lock, flags);
407 if (end > ll) {
408 /*
409 * Extend the allocation without changing the data size.
410 *
411 * Note we ensure the allocation is big enough to at least
412 * write some data but we do not require the allocation to be
413 * complete, i.e. it may be partial.
414 */
415 ll = ntfs_attr_extend_allocation(ni, end, -1, pos);
416 if (likely(ll >= 0)) {
417 BUG_ON(pos >= ll);
418 /* If the extension was partial truncate the write. */
419 if (end > ll) {
420 ntfs_debug("Truncating write to inode 0x%lx, "
421 "attribute type 0x%x, because "
422 "the allocation was only "
423 "partially extended.",
424 vi->i_ino, (unsigned)
425 le32_to_cpu(ni->type));
Al Viroccca2682015-04-05 14:06:24 -0400426 iov_iter_truncate(from, ll - pos);
Anton Altaparmakova632f552015-03-11 10:43:32 -0400427 }
428 } else {
429 err = ll;
430 read_lock_irqsave(&ni->size_lock, flags);
431 ll = ni->allocated_size;
432 read_unlock_irqrestore(&ni->size_lock, flags);
433 /* Perform a partial write if possible or fail. */
434 if (pos < ll) {
435 ntfs_debug("Truncating write to inode 0x%lx "
436 "attribute type 0x%x, because "
437 "extending the allocation "
438 "failed (error %d).",
439 vi->i_ino, (unsigned)
440 le32_to_cpu(ni->type),
441 (int)-err);
Al Viroccca2682015-04-05 14:06:24 -0400442 iov_iter_truncate(from, ll - pos);
Anton Altaparmakova632f552015-03-11 10:43:32 -0400443 } else {
444 if (err != -ENOSPC)
445 ntfs_error(vi->i_sb, "Cannot perform "
446 "write to inode "
447 "0x%lx, attribute "
448 "type 0x%x, because "
449 "extending the "
450 "allocation failed "
451 "(error %ld).",
452 vi->i_ino, (unsigned)
453 le32_to_cpu(ni->type),
454 (long)-err);
455 else
456 ntfs_debug("Cannot perform write to "
457 "inode 0x%lx, "
458 "attribute type 0x%x, "
459 "because there is not "
460 "space left.",
461 vi->i_ino, (unsigned)
462 le32_to_cpu(ni->type));
463 goto out;
464 }
465 }
466 }
467 /*
468 * If the write starts beyond the initialized size, extend it up to the
469 * beginning of the write and initialize all non-sparse space between
470 * the old initialized size and the new one. This automatically also
471 * increments the vfs inode->i_size to keep it above or equal to the
472 * initialized_size.
473 */
474 read_lock_irqsave(&ni->size_lock, flags);
475 ll = ni->initialized_size;
476 read_unlock_irqrestore(&ni->size_lock, flags);
477 if (pos > ll) {
478 /*
479 * Wait for ongoing direct i/o to complete before proceeding.
480 * New direct i/o cannot start as we hold i_mutex.
481 */
482 inode_dio_wait(vi);
483 err = ntfs_attr_extend_initialized(ni, pos);
484 if (unlikely(err < 0))
485 ntfs_error(vi->i_sb, "Cannot perform write to inode "
486 "0x%lx, attribute type 0x%x, because "
487 "extending the initialized size "
488 "failed (error %d).", vi->i_ino,
489 (unsigned)le32_to_cpu(ni->type),
490 (int)-err);
491 }
492out:
493 return err;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100494}
495
496/**
497 * __ntfs_grab_cache_pages - obtain a number of locked pages
498 * @mapping: address space mapping from which to obtain page cache pages
499 * @index: starting index in @mapping at which to begin obtaining pages
500 * @nr_pages: number of page cache pages to obtain
501 * @pages: array of pages in which to return the obtained page cache pages
502 * @cached_page: allocated but as yet unused page
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100503 *
André Goddard Rosaaf901ca2009-11-14 13:09:05 -0200504 * Obtain @nr_pages locked page cache pages from the mapping @mapping and
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100505 * starting at index @index.
506 *
Minchan Kim4c990002010-05-24 14:33:07 -0700507 * If a page is newly created, add it to lru list
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100508 *
509 * Note, the page locks are obtained in ascending page index order.
510 */
511static inline int __ntfs_grab_cache_pages(struct address_space *mapping,
512 pgoff_t index, const unsigned nr_pages, struct page **pages,
Minchan Kim4c990002010-05-24 14:33:07 -0700513 struct page **cached_page)
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100514{
515 int err, nr;
516
517 BUG_ON(!nr_pages);
518 err = nr = 0;
519 do {
Anton Altaparmakov5272d032014-10-09 15:24:46 -0700520 pages[nr] = find_get_page_flags(mapping, index, FGP_LOCK |
521 FGP_ACCESSED);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100522 if (!pages[nr]) {
523 if (!*cached_page) {
524 *cached_page = page_cache_alloc(mapping);
525 if (unlikely(!*cached_page)) {
526 err = -ENOMEM;
527 goto err_out;
528 }
529 }
Anton Altaparmakova632f552015-03-11 10:43:32 -0400530 err = add_to_page_cache_lru(*cached_page, mapping,
531 index, GFP_KERNEL);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100532 if (unlikely(err)) {
533 if (err == -EEXIST)
534 continue;
535 goto err_out;
536 }
537 pages[nr] = *cached_page;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100538 *cached_page = NULL;
539 }
540 index++;
541 nr++;
542 } while (nr < nr_pages);
543out:
544 return err;
545err_out:
546 while (nr > 0) {
547 unlock_page(pages[--nr]);
548 page_cache_release(pages[nr]);
549 }
550 goto out;
551}
552
553static inline int ntfs_submit_bh_for_read(struct buffer_head *bh)
554{
555 lock_buffer(bh);
556 get_bh(bh);
557 bh->b_end_io = end_buffer_read_sync;
558 return submit_bh(READ, bh);
559}
560
561/**
562 * ntfs_prepare_pages_for_non_resident_write - prepare pages for receiving data
563 * @pages: array of destination pages
564 * @nr_pages: number of pages in @pages
565 * @pos: byte position in file at which the write begins
566 * @bytes: number of bytes to be written
567 *
568 * This is called for non-resident attributes from ntfs_file_buffered_write()
Jes Sorensen1b1dcc12006-01-09 15:59:24 -0800569 * with i_mutex held on the inode (@pages[0]->mapping->host). There are
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100570 * @nr_pages pages in @pages which are locked but not kmap()ped. The source
571 * data has not yet been copied into the @pages.
572 *
573 * Need to fill any holes with actual clusters, allocate buffers if necessary,
574 * ensure all the buffers are mapped, and bring uptodate any buffers that are
575 * only partially being written to.
576 *
577 * If @nr_pages is greater than one, we are guaranteed that the cluster size is
578 * greater than PAGE_CACHE_SIZE, that all pages in @pages are entirely inside
579 * the same cluster and that they are the entirety of that cluster, and that
580 * the cluster is sparse, i.e. we need to allocate a cluster to fill the hole.
581 *
582 * i_size is not to be modified yet.
583 *
584 * Return 0 on success or -errno on error.
585 */
586static int ntfs_prepare_pages_for_non_resident_write(struct page **pages,
587 unsigned nr_pages, s64 pos, size_t bytes)
588{
589 VCN vcn, highest_vcn = 0, cpos, cend, bh_cpos, bh_cend;
590 LCN lcn;
591 s64 bh_pos, vcn_len, end, initialized_size;
592 sector_t lcn_block;
593 struct page *page;
594 struct inode *vi;
595 ntfs_inode *ni, *base_ni = NULL;
596 ntfs_volume *vol;
597 runlist_element *rl, *rl2;
598 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
599 ntfs_attr_search_ctx *ctx = NULL;
600 MFT_RECORD *m = NULL;
601 ATTR_RECORD *a = NULL;
602 unsigned long flags;
603 u32 attr_rec_len = 0;
604 unsigned blocksize, u;
605 int err, mp_size;
Richard Knutssonc49c3112006-09-30 23:27:12 -0700606 bool rl_write_locked, was_hole, is_retry;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100607 unsigned char blocksize_bits;
608 struct {
609 u8 runlist_merged:1;
610 u8 mft_attr_mapped:1;
611 u8 mp_rebuilt:1;
612 u8 attr_switched:1;
613 } status = { 0, 0, 0, 0 };
614
615 BUG_ON(!nr_pages);
616 BUG_ON(!pages);
617 BUG_ON(!*pages);
618 vi = pages[0]->mapping->host;
619 ni = NTFS_I(vi);
620 vol = ni->vol;
621 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
Anton Altaparmakovd04bd1f2005-10-24 08:41:24 +0100622 "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100623 vi->i_ino, ni->type, pages[0]->index, nr_pages,
624 (long long)pos, bytes);
Anton Altaparmakov78af34f2006-02-24 10:32:33 +0000625 blocksize = vol->sb->s_blocksize;
626 blocksize_bits = vol->sb->s_blocksize_bits;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100627 u = 0;
628 do {
Anton Altaparmakovbfab36e2007-10-12 09:37:15 +0100629 page = pages[u];
630 BUG_ON(!page);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100631 /*
632 * create_empty_buffers() will create uptodate/dirty buffers if
633 * the page is uptodate/dirty.
634 */
635 if (!page_has_buffers(page)) {
636 create_empty_buffers(page, blocksize, 0);
637 if (unlikely(!page_has_buffers(page)))
638 return -ENOMEM;
639 }
640 } while (++u < nr_pages);
Richard Knutssonc49c3112006-09-30 23:27:12 -0700641 rl_write_locked = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100642 rl = NULL;
643 err = 0;
644 vcn = lcn = -1;
645 vcn_len = 0;
646 lcn_block = -1;
Richard Knutssonc49c3112006-09-30 23:27:12 -0700647 was_hole = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100648 cpos = pos >> vol->cluster_size_bits;
649 end = pos + bytes;
650 cend = (end + vol->cluster_size - 1) >> vol->cluster_size_bits;
651 /*
652 * Loop over each page and for each page over each buffer. Use goto to
653 * reduce indentation.
654 */
655 u = 0;
656do_next_page:
657 page = pages[u];
658 bh_pos = (s64)page->index << PAGE_CACHE_SHIFT;
659 bh = head = page_buffers(page);
660 do {
661 VCN cdelta;
662 s64 bh_end;
663 unsigned bh_cofs;
664
665 /* Clear buffer_new on all buffers to reinitialise state. */
666 if (buffer_new(bh))
667 clear_buffer_new(bh);
668 bh_end = bh_pos + blocksize;
669 bh_cpos = bh_pos >> vol->cluster_size_bits;
670 bh_cofs = bh_pos & vol->cluster_size_mask;
671 if (buffer_mapped(bh)) {
672 /*
673 * The buffer is already mapped. If it is uptodate,
674 * ignore it.
675 */
676 if (buffer_uptodate(bh))
677 continue;
678 /*
679 * The buffer is not uptodate. If the page is uptodate
680 * set the buffer uptodate and otherwise ignore it.
681 */
682 if (PageUptodate(page)) {
683 set_buffer_uptodate(bh);
684 continue;
685 }
686 /*
687 * Neither the page nor the buffer are uptodate. If
688 * the buffer is only partially being written to, we
689 * need to read it in before the write, i.e. now.
690 */
691 if ((bh_pos < pos && bh_end > pos) ||
692 (bh_pos < end && bh_end > end)) {
693 /*
694 * If the buffer is fully or partially within
695 * the initialized size, do an actual read.
696 * Otherwise, simply zero the buffer.
697 */
698 read_lock_irqsave(&ni->size_lock, flags);
699 initialized_size = ni->initialized_size;
700 read_unlock_irqrestore(&ni->size_lock, flags);
701 if (bh_pos < initialized_size) {
702 ntfs_submit_bh_for_read(bh);
703 *wait_bh++ = bh;
704 } else {
Christoph Lametereebd2aa2008-02-04 22:28:29 -0800705 zero_user(page, bh_offset(bh),
706 blocksize);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100707 set_buffer_uptodate(bh);
708 }
709 }
710 continue;
711 }
712 /* Unmapped buffer. Need to map it. */
713 bh->b_bdev = vol->sb->s_bdev;
714 /*
715 * If the current buffer is in the same clusters as the map
716 * cache, there is no need to check the runlist again. The
717 * map cache is made up of @vcn, which is the first cached file
718 * cluster, @vcn_len which is the number of cached file
719 * clusters, @lcn is the device cluster corresponding to @vcn,
720 * and @lcn_block is the block number corresponding to @lcn.
721 */
722 cdelta = bh_cpos - vcn;
723 if (likely(!cdelta || (cdelta > 0 && cdelta < vcn_len))) {
724map_buffer_cached:
725 BUG_ON(lcn < 0);
726 bh->b_blocknr = lcn_block +
727 (cdelta << (vol->cluster_size_bits -
728 blocksize_bits)) +
729 (bh_cofs >> blocksize_bits);
730 set_buffer_mapped(bh);
731 /*
732 * If the page is uptodate so is the buffer. If the
733 * buffer is fully outside the write, we ignore it if
734 * it was already allocated and we mark it dirty so it
735 * gets written out if we allocated it. On the other
736 * hand, if we allocated the buffer but we are not
737 * marking it dirty we set buffer_new so we can do
738 * error recovery.
739 */
740 if (PageUptodate(page)) {
741 if (!buffer_uptodate(bh))
742 set_buffer_uptodate(bh);
743 if (unlikely(was_hole)) {
744 /* We allocated the buffer. */
745 unmap_underlying_metadata(bh->b_bdev,
746 bh->b_blocknr);
747 if (bh_end <= pos || bh_pos >= end)
748 mark_buffer_dirty(bh);
749 else
750 set_buffer_new(bh);
751 }
752 continue;
753 }
754 /* Page is _not_ uptodate. */
755 if (likely(!was_hole)) {
756 /*
757 * Buffer was already allocated. If it is not
758 * uptodate and is only partially being written
759 * to, we need to read it in before the write,
760 * i.e. now.
761 */
Anton Altaparmakov3aebf252005-11-01 15:49:31 +0000762 if (!buffer_uptodate(bh) && bh_pos < end &&
763 bh_end > pos &&
764 (bh_pos < pos ||
765 bh_end > end)) {
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100766 /*
767 * If the buffer is fully or partially
768 * within the initialized size, do an
769 * actual read. Otherwise, simply zero
770 * the buffer.
771 */
772 read_lock_irqsave(&ni->size_lock,
773 flags);
774 initialized_size = ni->initialized_size;
775 read_unlock_irqrestore(&ni->size_lock,
776 flags);
777 if (bh_pos < initialized_size) {
778 ntfs_submit_bh_for_read(bh);
779 *wait_bh++ = bh;
780 } else {
Christoph Lametereebd2aa2008-02-04 22:28:29 -0800781 zero_user(page, bh_offset(bh),
782 blocksize);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100783 set_buffer_uptodate(bh);
784 }
785 }
786 continue;
787 }
788 /* We allocated the buffer. */
789 unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
790 /*
791 * If the buffer is fully outside the write, zero it,
792 * set it uptodate, and mark it dirty so it gets
793 * written out. If it is partially being written to,
794 * zero region surrounding the write but leave it to
795 * commit write to do anything else. Finally, if the
796 * buffer is fully being overwritten, do nothing.
797 */
798 if (bh_end <= pos || bh_pos >= end) {
799 if (!buffer_uptodate(bh)) {
Christoph Lametereebd2aa2008-02-04 22:28:29 -0800800 zero_user(page, bh_offset(bh),
801 blocksize);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100802 set_buffer_uptodate(bh);
803 }
804 mark_buffer_dirty(bh);
805 continue;
806 }
807 set_buffer_new(bh);
808 if (!buffer_uptodate(bh) &&
809 (bh_pos < pos || bh_end > end)) {
810 u8 *kaddr;
811 unsigned pofs;
812
Cong Wanga3ac1412011-11-25 23:14:34 +0800813 kaddr = kmap_atomic(page);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100814 if (bh_pos < pos) {
815 pofs = bh_pos & ~PAGE_CACHE_MASK;
816 memset(kaddr + pofs, 0, pos - bh_pos);
817 }
818 if (bh_end > end) {
819 pofs = end & ~PAGE_CACHE_MASK;
820 memset(kaddr + pofs, 0, bh_end - end);
821 }
Cong Wanga3ac1412011-11-25 23:14:34 +0800822 kunmap_atomic(kaddr);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100823 flush_dcache_page(page);
824 }
825 continue;
826 }
827 /*
828 * Slow path: this is the first buffer in the cluster. If it
829 * is outside allocated size and is not uptodate, zero it and
830 * set it uptodate.
831 */
832 read_lock_irqsave(&ni->size_lock, flags);
833 initialized_size = ni->allocated_size;
834 read_unlock_irqrestore(&ni->size_lock, flags);
835 if (bh_pos > initialized_size) {
836 if (PageUptodate(page)) {
837 if (!buffer_uptodate(bh))
838 set_buffer_uptodate(bh);
839 } else if (!buffer_uptodate(bh)) {
Christoph Lametereebd2aa2008-02-04 22:28:29 -0800840 zero_user(page, bh_offset(bh), blocksize);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100841 set_buffer_uptodate(bh);
842 }
843 continue;
844 }
Richard Knutssonc49c3112006-09-30 23:27:12 -0700845 is_retry = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100846 if (!rl) {
847 down_read(&ni->runlist.lock);
848retry_remap:
849 rl = ni->runlist.rl;
850 }
851 if (likely(rl != NULL)) {
852 /* Seek to element containing target cluster. */
853 while (rl->length && rl[1].vcn <= bh_cpos)
854 rl++;
855 lcn = ntfs_rl_vcn_to_lcn(rl, bh_cpos);
856 if (likely(lcn >= 0)) {
857 /*
858 * Successful remap, setup the map cache and
859 * use that to deal with the buffer.
860 */
Richard Knutssonc49c3112006-09-30 23:27:12 -0700861 was_hole = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100862 vcn = bh_cpos;
863 vcn_len = rl[1].vcn - vcn;
864 lcn_block = lcn << (vol->cluster_size_bits -
865 blocksize_bits);
Anton Altaparmakovd5aeaef2005-10-19 12:23:10 +0100866 cdelta = 0;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100867 /*
Anton Altaparmakov3aebf252005-11-01 15:49:31 +0000868 * If the number of remaining clusters touched
869 * by the write is smaller or equal to the
870 * number of cached clusters, unlock the
871 * runlist as the map cache will be used from
872 * now on.
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100873 */
874 if (likely(vcn + vcn_len >= cend)) {
875 if (rl_write_locked) {
876 up_write(&ni->runlist.lock);
Richard Knutssonc49c3112006-09-30 23:27:12 -0700877 rl_write_locked = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100878 } else
879 up_read(&ni->runlist.lock);
880 rl = NULL;
881 }
882 goto map_buffer_cached;
883 }
884 } else
885 lcn = LCN_RL_NOT_MAPPED;
886 /*
887 * If it is not a hole and not out of bounds, the runlist is
888 * probably unmapped so try to map it now.
889 */
890 if (unlikely(lcn != LCN_HOLE && lcn != LCN_ENOENT)) {
891 if (likely(!is_retry && lcn == LCN_RL_NOT_MAPPED)) {
892 /* Attempt to map runlist. */
893 if (!rl_write_locked) {
894 /*
895 * We need the runlist locked for
896 * writing, so if it is locked for
897 * reading relock it now and retry in
898 * case it changed whilst we dropped
899 * the lock.
900 */
901 up_read(&ni->runlist.lock);
902 down_write(&ni->runlist.lock);
Richard Knutssonc49c3112006-09-30 23:27:12 -0700903 rl_write_locked = true;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100904 goto retry_remap;
905 }
906 err = ntfs_map_runlist_nolock(ni, bh_cpos,
907 NULL);
908 if (likely(!err)) {
Richard Knutssonc49c3112006-09-30 23:27:12 -0700909 is_retry = true;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100910 goto retry_remap;
911 }
912 /*
913 * If @vcn is out of bounds, pretend @lcn is
914 * LCN_ENOENT. As long as the buffer is out
915 * of bounds this will work fine.
916 */
917 if (err == -ENOENT) {
918 lcn = LCN_ENOENT;
919 err = 0;
920 goto rl_not_mapped_enoent;
921 }
922 } else
923 err = -EIO;
924 /* Failed to map the buffer, even after retrying. */
925 bh->b_blocknr = -1;
926 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
927 "attribute type 0x%x, vcn 0x%llx, "
928 "vcn offset 0x%x, because its "
929 "location on disk could not be "
930 "determined%s (error code %i).",
931 ni->mft_no, ni->type,
932 (unsigned long long)bh_cpos,
933 (unsigned)bh_pos &
934 vol->cluster_size_mask,
935 is_retry ? " even after retrying" : "",
936 err);
937 break;
938 }
939rl_not_mapped_enoent:
940 /*
941 * The buffer is in a hole or out of bounds. We need to fill
942 * the hole, unless the buffer is in a cluster which is not
943 * touched by the write, in which case we just leave the buffer
944 * unmapped. This can only happen when the cluster size is
945 * less than the page cache size.
946 */
947 if (unlikely(vol->cluster_size < PAGE_CACHE_SIZE)) {
948 bh_cend = (bh_end + vol->cluster_size - 1) >>
949 vol->cluster_size_bits;
950 if ((bh_cend <= cpos || bh_cpos >= cend)) {
951 bh->b_blocknr = -1;
952 /*
953 * If the buffer is uptodate we skip it. If it
954 * is not but the page is uptodate, we can set
955 * the buffer uptodate. If the page is not
956 * uptodate, we can clear the buffer and set it
957 * uptodate. Whether this is worthwhile is
958 * debatable and this could be removed.
959 */
960 if (PageUptodate(page)) {
961 if (!buffer_uptodate(bh))
962 set_buffer_uptodate(bh);
963 } else if (!buffer_uptodate(bh)) {
Christoph Lametereebd2aa2008-02-04 22:28:29 -0800964 zero_user(page, bh_offset(bh),
965 blocksize);
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100966 set_buffer_uptodate(bh);
967 }
968 continue;
969 }
970 }
971 /*
972 * Out of bounds buffer is invalid if it was not really out of
973 * bounds.
974 */
975 BUG_ON(lcn != LCN_HOLE);
976 /*
977 * We need the runlist locked for writing, so if it is locked
978 * for reading relock it now and retry in case it changed
979 * whilst we dropped the lock.
980 */
981 BUG_ON(!rl);
982 if (!rl_write_locked) {
983 up_read(&ni->runlist.lock);
984 down_write(&ni->runlist.lock);
Richard Knutssonc49c3112006-09-30 23:27:12 -0700985 rl_write_locked = true;
Anton Altaparmakov98b27032005-10-11 15:40:40 +0100986 goto retry_remap;
987 }
988 /* Find the previous last allocated cluster. */
989 BUG_ON(rl->lcn != LCN_HOLE);
990 lcn = -1;
991 rl2 = rl;
992 while (--rl2 >= ni->runlist.rl) {
993 if (rl2->lcn >= 0) {
994 lcn = rl2->lcn + rl2->length;
995 break;
996 }
997 }
998 rl2 = ntfs_cluster_alloc(vol, bh_cpos, 1, lcn, DATA_ZONE,
Richard Knutssonc49c3112006-09-30 23:27:12 -0700999 false);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001000 if (IS_ERR(rl2)) {
1001 err = PTR_ERR(rl2);
1002 ntfs_debug("Failed to allocate cluster, error code %i.",
1003 err);
1004 break;
1005 }
1006 lcn = rl2->lcn;
1007 rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
1008 if (IS_ERR(rl)) {
1009 err = PTR_ERR(rl);
1010 if (err != -ENOMEM)
1011 err = -EIO;
1012 if (ntfs_cluster_free_from_rl(vol, rl2)) {
1013 ntfs_error(vol->sb, "Failed to release "
1014 "allocated cluster in error "
1015 "code path. Run chkdsk to "
1016 "recover the lost cluster.");
1017 NVolSetErrors(vol);
1018 }
1019 ntfs_free(rl2);
1020 break;
1021 }
1022 ni->runlist.rl = rl;
1023 status.runlist_merged = 1;
Anton Altaparmakovbb8047d2006-03-07 11:53:46 +00001024 ntfs_debug("Allocated cluster, lcn 0x%llx.",
1025 (unsigned long long)lcn);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001026 /* Map and lock the mft record and get the attribute record. */
1027 if (!NInoAttr(ni))
1028 base_ni = ni;
1029 else
1030 base_ni = ni->ext.base_ntfs_ino;
1031 m = map_mft_record(base_ni);
1032 if (IS_ERR(m)) {
1033 err = PTR_ERR(m);
1034 break;
1035 }
1036 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1037 if (unlikely(!ctx)) {
1038 err = -ENOMEM;
1039 unmap_mft_record(base_ni);
1040 break;
1041 }
1042 status.mft_attr_mapped = 1;
1043 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1044 CASE_SENSITIVE, bh_cpos, NULL, 0, ctx);
1045 if (unlikely(err)) {
1046 if (err == -ENOENT)
1047 err = -EIO;
1048 break;
1049 }
1050 m = ctx->mrec;
1051 a = ctx->attr;
1052 /*
1053 * Find the runlist element with which the attribute extent
1054 * starts. Note, we cannot use the _attr_ version because we
1055 * have mapped the mft record. That is ok because we know the
1056 * runlist fragment must be mapped already to have ever gotten
1057 * here, so we can just use the _rl_ version.
1058 */
1059 vcn = sle64_to_cpu(a->data.non_resident.lowest_vcn);
1060 rl2 = ntfs_rl_find_vcn_nolock(rl, vcn);
1061 BUG_ON(!rl2);
1062 BUG_ON(!rl2->length);
1063 BUG_ON(rl2->lcn < LCN_HOLE);
1064 highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
1065 /*
1066 * If @highest_vcn is zero, calculate the real highest_vcn
1067 * (which can really be zero).
1068 */
1069 if (!highest_vcn)
1070 highest_vcn = (sle64_to_cpu(
1071 a->data.non_resident.allocated_size) >>
1072 vol->cluster_size_bits) - 1;
1073 /*
1074 * Determine the size of the mapping pairs array for the new
1075 * extent, i.e. the old extent with the hole filled.
1076 */
1077 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, vcn,
1078 highest_vcn);
1079 if (unlikely(mp_size <= 0)) {
1080 if (!(err = mp_size))
1081 err = -EIO;
1082 ntfs_debug("Failed to get size for mapping pairs "
1083 "array, error code %i.", err);
1084 break;
1085 }
1086 /*
1087 * Resize the attribute record to fit the new mapping pairs
1088 * array.
1089 */
1090 attr_rec_len = le32_to_cpu(a->length);
1091 err = ntfs_attr_record_resize(m, a, mp_size + le16_to_cpu(
1092 a->data.non_resident.mapping_pairs_offset));
1093 if (unlikely(err)) {
1094 BUG_ON(err != -ENOSPC);
1095 // TODO: Deal with this by using the current attribute
1096 // and fill it with as much of the mapping pairs
1097 // array as possible. Then loop over each attribute
1098 // extent rewriting the mapping pairs arrays as we go
1099 // along and if when we reach the end we have not
1100 // enough space, try to resize the last attribute
1101 // extent and if even that fails, add a new attribute
1102 // extent.
1103 // We could also try to resize at each step in the hope
1104 // that we will not need to rewrite every single extent.
1105 // Note, we may need to decompress some extents to fill
1106 // the runlist as we are walking the extents...
1107 ntfs_error(vol->sb, "Not enough space in the mft "
1108 "record for the extended attribute "
1109 "record. This case is not "
1110 "implemented yet.");
1111 err = -EOPNOTSUPP;
1112 break ;
1113 }
1114 status.mp_rebuilt = 1;
1115 /*
1116 * Generate the mapping pairs array directly into the attribute
1117 * record.
1118 */
1119 err = ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1120 a->data.non_resident.mapping_pairs_offset),
1121 mp_size, rl2, vcn, highest_vcn, NULL);
1122 if (unlikely(err)) {
1123 ntfs_error(vol->sb, "Cannot fill hole in inode 0x%lx, "
1124 "attribute type 0x%x, because building "
1125 "the mapping pairs failed with error "
1126 "code %i.", vi->i_ino,
1127 (unsigned)le32_to_cpu(ni->type), err);
1128 err = -EIO;
1129 break;
1130 }
1131 /* Update the highest_vcn but only if it was not set. */
1132 if (unlikely(!a->data.non_resident.highest_vcn))
1133 a->data.non_resident.highest_vcn =
1134 cpu_to_sle64(highest_vcn);
1135 /*
1136 * If the attribute is sparse/compressed, update the compressed
1137 * size in the ntfs_inode structure and the attribute record.
1138 */
1139 if (likely(NInoSparse(ni) || NInoCompressed(ni))) {
1140 /*
1141 * If we are not in the first attribute extent, switch
1142 * to it, but first ensure the changes will make it to
1143 * disk later.
1144 */
1145 if (a->data.non_resident.lowest_vcn) {
1146 flush_dcache_mft_record_page(ctx->ntfs_ino);
1147 mark_mft_record_dirty(ctx->ntfs_ino);
1148 ntfs_attr_reinit_search_ctx(ctx);
1149 err = ntfs_attr_lookup(ni->type, ni->name,
1150 ni->name_len, CASE_SENSITIVE,
1151 0, NULL, 0, ctx);
1152 if (unlikely(err)) {
1153 status.attr_switched = 1;
1154 break;
1155 }
1156 /* @m is not used any more so do not set it. */
1157 a = ctx->attr;
1158 }
1159 write_lock_irqsave(&ni->size_lock, flags);
1160 ni->itype.compressed.size += vol->cluster_size;
1161 a->data.non_resident.compressed_size =
1162 cpu_to_sle64(ni->itype.compressed.size);
1163 write_unlock_irqrestore(&ni->size_lock, flags);
1164 }
1165 /* Ensure the changes make it to disk. */
1166 flush_dcache_mft_record_page(ctx->ntfs_ino);
1167 mark_mft_record_dirty(ctx->ntfs_ino);
1168 ntfs_attr_put_search_ctx(ctx);
1169 unmap_mft_record(base_ni);
1170 /* Successfully filled the hole. */
1171 status.runlist_merged = 0;
1172 status.mft_attr_mapped = 0;
1173 status.mp_rebuilt = 0;
1174 /* Setup the map cache and use that to deal with the buffer. */
Richard Knutssonc49c3112006-09-30 23:27:12 -07001175 was_hole = true;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001176 vcn = bh_cpos;
1177 vcn_len = 1;
1178 lcn_block = lcn << (vol->cluster_size_bits - blocksize_bits);
1179 cdelta = 0;
1180 /*
1181 * If the number of remaining clusters in the @pages is smaller
1182 * or equal to the number of cached clusters, unlock the
1183 * runlist as the map cache will be used from now on.
1184 */
1185 if (likely(vcn + vcn_len >= cend)) {
1186 up_write(&ni->runlist.lock);
Richard Knutssonc49c3112006-09-30 23:27:12 -07001187 rl_write_locked = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001188 rl = NULL;
1189 }
1190 goto map_buffer_cached;
1191 } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
1192 /* If there are no errors, do the next page. */
1193 if (likely(!err && ++u < nr_pages))
1194 goto do_next_page;
1195 /* If there are no errors, release the runlist lock if we took it. */
1196 if (likely(!err)) {
1197 if (unlikely(rl_write_locked)) {
1198 up_write(&ni->runlist.lock);
Richard Knutssonc49c3112006-09-30 23:27:12 -07001199 rl_write_locked = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001200 } else if (unlikely(rl))
1201 up_read(&ni->runlist.lock);
1202 rl = NULL;
1203 }
1204 /* If we issued read requests, let them complete. */
1205 read_lock_irqsave(&ni->size_lock, flags);
1206 initialized_size = ni->initialized_size;
1207 read_unlock_irqrestore(&ni->size_lock, flags);
1208 while (wait_bh > wait) {
1209 bh = *--wait_bh;
1210 wait_on_buffer(bh);
1211 if (likely(buffer_uptodate(bh))) {
1212 page = bh->b_page;
1213 bh_pos = ((s64)page->index << PAGE_CACHE_SHIFT) +
1214 bh_offset(bh);
1215 /*
1216 * If the buffer overflows the initialized size, need
1217 * to zero the overflowing region.
1218 */
1219 if (unlikely(bh_pos + blocksize > initialized_size)) {
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001220 int ofs = 0;
1221
1222 if (likely(bh_pos < initialized_size))
1223 ofs = initialized_size - bh_pos;
Christoph Lametereebd2aa2008-02-04 22:28:29 -08001224 zero_user_segment(page, bh_offset(bh) + ofs,
1225 blocksize);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001226 }
1227 } else /* if (unlikely(!buffer_uptodate(bh))) */
1228 err = -EIO;
1229 }
1230 if (likely(!err)) {
1231 /* Clear buffer_new on all buffers. */
1232 u = 0;
1233 do {
1234 bh = head = page_buffers(pages[u]);
1235 do {
1236 if (buffer_new(bh))
1237 clear_buffer_new(bh);
1238 } while ((bh = bh->b_this_page) != head);
1239 } while (++u < nr_pages);
1240 ntfs_debug("Done.");
1241 return err;
1242 }
1243 if (status.attr_switched) {
1244 /* Get back to the attribute extent we modified. */
1245 ntfs_attr_reinit_search_ctx(ctx);
1246 if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1247 CASE_SENSITIVE, bh_cpos, NULL, 0, ctx)) {
1248 ntfs_error(vol->sb, "Failed to find required "
1249 "attribute extent of attribute in "
1250 "error code path. Run chkdsk to "
1251 "recover.");
1252 write_lock_irqsave(&ni->size_lock, flags);
1253 ni->itype.compressed.size += vol->cluster_size;
1254 write_unlock_irqrestore(&ni->size_lock, flags);
1255 flush_dcache_mft_record_page(ctx->ntfs_ino);
1256 mark_mft_record_dirty(ctx->ntfs_ino);
1257 /*
1258 * The only thing that is now wrong is the compressed
1259 * size of the base attribute extent which chkdsk
1260 * should be able to fix.
1261 */
1262 NVolSetErrors(vol);
1263 } else {
1264 m = ctx->mrec;
1265 a = ctx->attr;
1266 status.attr_switched = 0;
1267 }
1268 }
1269 /*
1270 * If the runlist has been modified, need to restore it by punching a
1271 * hole into it and we then need to deallocate the on-disk cluster as
1272 * well. Note, we only modify the runlist if we are able to generate a
1273 * new mapping pairs array, i.e. only when the mapped attribute extent
1274 * is not switched.
1275 */
1276 if (status.runlist_merged && !status.attr_switched) {
1277 BUG_ON(!rl_write_locked);
1278 /* Make the file cluster we allocated sparse in the runlist. */
1279 if (ntfs_rl_punch_nolock(vol, &ni->runlist, bh_cpos, 1)) {
1280 ntfs_error(vol->sb, "Failed to punch hole into "
1281 "attribute runlist in error code "
1282 "path. Run chkdsk to recover the "
1283 "lost cluster.");
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001284 NVolSetErrors(vol);
1285 } else /* if (success) */ {
1286 status.runlist_merged = 0;
1287 /*
1288 * Deallocate the on-disk cluster we allocated but only
1289 * if we succeeded in punching its vcn out of the
1290 * runlist.
1291 */
1292 down_write(&vol->lcnbmp_lock);
1293 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1294 ntfs_error(vol->sb, "Failed to release "
1295 "allocated cluster in error "
1296 "code path. Run chkdsk to "
1297 "recover the lost cluster.");
1298 NVolSetErrors(vol);
1299 }
1300 up_write(&vol->lcnbmp_lock);
1301 }
1302 }
1303 /*
1304 * Resize the attribute record to its old size and rebuild the mapping
1305 * pairs array. Note, we only can do this if the runlist has been
1306 * restored to its old state which also implies that the mapped
1307 * attribute extent is not switched.
1308 */
1309 if (status.mp_rebuilt && !status.runlist_merged) {
1310 if (ntfs_attr_record_resize(m, a, attr_rec_len)) {
1311 ntfs_error(vol->sb, "Failed to restore attribute "
1312 "record in error code path. Run "
1313 "chkdsk to recover.");
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001314 NVolSetErrors(vol);
1315 } else /* if (success) */ {
1316 if (ntfs_mapping_pairs_build(vol, (u8*)a +
1317 le16_to_cpu(a->data.non_resident.
1318 mapping_pairs_offset), attr_rec_len -
1319 le16_to_cpu(a->data.non_resident.
1320 mapping_pairs_offset), ni->runlist.rl,
1321 vcn, highest_vcn, NULL)) {
1322 ntfs_error(vol->sb, "Failed to restore "
1323 "mapping pairs array in error "
1324 "code path. Run chkdsk to "
1325 "recover.");
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001326 NVolSetErrors(vol);
1327 }
1328 flush_dcache_mft_record_page(ctx->ntfs_ino);
1329 mark_mft_record_dirty(ctx->ntfs_ino);
1330 }
1331 }
1332 /* Release the mft record and the attribute. */
1333 if (status.mft_attr_mapped) {
1334 ntfs_attr_put_search_ctx(ctx);
1335 unmap_mft_record(base_ni);
1336 }
1337 /* Release the runlist lock. */
1338 if (rl_write_locked)
1339 up_write(&ni->runlist.lock);
1340 else if (rl)
1341 up_read(&ni->runlist.lock);
1342 /*
1343 * Zero out any newly allocated blocks to avoid exposing stale data.
1344 * If BH_New is set, we know that the block was newly allocated above
1345 * and that it has not been fully zeroed and marked dirty yet.
1346 */
1347 nr_pages = u;
1348 u = 0;
1349 end = bh_cpos << vol->cluster_size_bits;
1350 do {
1351 page = pages[u];
1352 bh = head = page_buffers(page);
1353 do {
1354 if (u == nr_pages &&
1355 ((s64)page->index << PAGE_CACHE_SHIFT) +
1356 bh_offset(bh) >= end)
1357 break;
1358 if (!buffer_new(bh))
1359 continue;
1360 clear_buffer_new(bh);
1361 if (!buffer_uptodate(bh)) {
1362 if (PageUptodate(page))
1363 set_buffer_uptodate(bh);
1364 else {
Christoph Lametereebd2aa2008-02-04 22:28:29 -08001365 zero_user(page, bh_offset(bh),
1366 blocksize);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001367 set_buffer_uptodate(bh);
1368 }
1369 }
1370 mark_buffer_dirty(bh);
1371 } while ((bh = bh->b_this_page) != head);
1372 } while (++u <= nr_pages);
1373 ntfs_error(vol->sb, "Failed. Returning error code %i.", err);
1374 return err;
1375}
1376
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001377static inline void ntfs_flush_dcache_pages(struct page **pages,
1378 unsigned nr_pages)
1379{
1380 BUG_ON(!nr_pages);
Anton Altaparmakovf893afb2006-06-22 14:47:15 -07001381 /*
1382 * Warning: Do not do the decrement at the same time as the call to
1383 * flush_dcache_page() because it is a NULL macro on i386 and hence the
1384 * decrement never happens so the loop never terminates.
1385 */
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001386 do {
Anton Altaparmakovf893afb2006-06-22 14:47:15 -07001387 --nr_pages;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001388 flush_dcache_page(pages[nr_pages]);
Anton Altaparmakovf893afb2006-06-22 14:47:15 -07001389 } while (nr_pages > 0);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001390}
1391
1392/**
1393 * ntfs_commit_pages_after_non_resident_write - commit the received data
1394 * @pages: array of destination pages
1395 * @nr_pages: number of pages in @pages
1396 * @pos: byte position in file at which the write begins
1397 * @bytes: number of bytes to be written
1398 *
1399 * See description of ntfs_commit_pages_after_write(), below.
1400 */
1401static inline int ntfs_commit_pages_after_non_resident_write(
1402 struct page **pages, const unsigned nr_pages,
1403 s64 pos, size_t bytes)
1404{
1405 s64 end, initialized_size;
1406 struct inode *vi;
1407 ntfs_inode *ni, *base_ni;
1408 struct buffer_head *bh, *head;
1409 ntfs_attr_search_ctx *ctx;
1410 MFT_RECORD *m;
1411 ATTR_RECORD *a;
1412 unsigned long flags;
1413 unsigned blocksize, u;
1414 int err;
1415
1416 vi = pages[0]->mapping->host;
1417 ni = NTFS_I(vi);
Anton Altaparmakov78af34f2006-02-24 10:32:33 +00001418 blocksize = vi->i_sb->s_blocksize;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001419 end = pos + bytes;
1420 u = 0;
1421 do {
1422 s64 bh_pos;
1423 struct page *page;
Richard Knutssonc49c3112006-09-30 23:27:12 -07001424 bool partial;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001425
1426 page = pages[u];
1427 bh_pos = (s64)page->index << PAGE_CACHE_SHIFT;
1428 bh = head = page_buffers(page);
Richard Knutssonc49c3112006-09-30 23:27:12 -07001429 partial = false;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001430 do {
1431 s64 bh_end;
1432
1433 bh_end = bh_pos + blocksize;
1434 if (bh_end <= pos || bh_pos >= end) {
1435 if (!buffer_uptodate(bh))
Richard Knutssonc49c3112006-09-30 23:27:12 -07001436 partial = true;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001437 } else {
1438 set_buffer_uptodate(bh);
1439 mark_buffer_dirty(bh);
1440 }
1441 } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
1442 /*
1443 * If all buffers are now uptodate but the page is not, set the
1444 * page uptodate.
1445 */
1446 if (!partial && !PageUptodate(page))
1447 SetPageUptodate(page);
1448 } while (++u < nr_pages);
1449 /*
1450 * Finally, if we do not need to update initialized_size or i_size we
1451 * are finished.
1452 */
1453 read_lock_irqsave(&ni->size_lock, flags);
1454 initialized_size = ni->initialized_size;
1455 read_unlock_irqrestore(&ni->size_lock, flags);
1456 if (end <= initialized_size) {
1457 ntfs_debug("Done.");
1458 return 0;
1459 }
1460 /*
1461 * Update initialized_size/i_size as appropriate, both in the inode and
1462 * the mft record.
1463 */
1464 if (!NInoAttr(ni))
1465 base_ni = ni;
1466 else
1467 base_ni = ni->ext.base_ntfs_ino;
1468 /* Map, pin, and lock the mft record. */
1469 m = map_mft_record(base_ni);
1470 if (IS_ERR(m)) {
1471 err = PTR_ERR(m);
1472 m = NULL;
1473 ctx = NULL;
1474 goto err_out;
1475 }
1476 BUG_ON(!NInoNonResident(ni));
1477 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1478 if (unlikely(!ctx)) {
1479 err = -ENOMEM;
1480 goto err_out;
1481 }
1482 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1483 CASE_SENSITIVE, 0, NULL, 0, ctx);
1484 if (unlikely(err)) {
1485 if (err == -ENOENT)
1486 err = -EIO;
1487 goto err_out;
1488 }
1489 a = ctx->attr;
1490 BUG_ON(!a->non_resident);
1491 write_lock_irqsave(&ni->size_lock, flags);
1492 BUG_ON(end > ni->allocated_size);
1493 ni->initialized_size = end;
1494 a->data.non_resident.initialized_size = cpu_to_sle64(end);
1495 if (end > i_size_read(vi)) {
1496 i_size_write(vi, end);
1497 a->data.non_resident.data_size =
1498 a->data.non_resident.initialized_size;
1499 }
1500 write_unlock_irqrestore(&ni->size_lock, flags);
1501 /* Mark the mft record dirty, so it gets written back. */
1502 flush_dcache_mft_record_page(ctx->ntfs_ino);
1503 mark_mft_record_dirty(ctx->ntfs_ino);
1504 ntfs_attr_put_search_ctx(ctx);
1505 unmap_mft_record(base_ni);
1506 ntfs_debug("Done.");
1507 return 0;
1508err_out:
1509 if (ctx)
1510 ntfs_attr_put_search_ctx(ctx);
1511 if (m)
1512 unmap_mft_record(base_ni);
1513 ntfs_error(vi->i_sb, "Failed to update initialized_size/i_size (error "
1514 "code %i).", err);
Anton Altaparmakovf95c4012006-03-23 15:59:32 +00001515 if (err != -ENOMEM)
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001516 NVolSetErrors(ni->vol);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001517 return err;
1518}
1519
1520/**
1521 * ntfs_commit_pages_after_write - commit the received data
1522 * @pages: array of destination pages
1523 * @nr_pages: number of pages in @pages
1524 * @pos: byte position in file at which the write begins
1525 * @bytes: number of bytes to be written
1526 *
Jes Sorensen1b1dcc12006-01-09 15:59:24 -08001527 * This is called from ntfs_file_buffered_write() with i_mutex held on the inode
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001528 * (@pages[0]->mapping->host). There are @nr_pages pages in @pages which are
1529 * locked but not kmap()ped. The source data has already been copied into the
1530 * @page. ntfs_prepare_pages_for_non_resident_write() has been called before
1531 * the data was copied (for non-resident attributes only) and it returned
1532 * success.
1533 *
1534 * Need to set uptodate and mark dirty all buffers within the boundary of the
1535 * write. If all buffers in a page are uptodate we set the page uptodate, too.
1536 *
1537 * Setting the buffers dirty ensures that they get written out later when
1538 * ntfs_writepage() is invoked by the VM.
1539 *
1540 * Finally, we need to update i_size and initialized_size as appropriate both
1541 * in the inode and the mft record.
1542 *
1543 * This is modelled after fs/buffer.c::generic_commit_write(), which marks
1544 * buffers uptodate and dirty, sets the page uptodate if all buffers in the
1545 * page are uptodate, and updates i_size if the end of io is beyond i_size. In
1546 * that case, it also marks the inode dirty.
1547 *
1548 * If things have gone as outlined in
1549 * ntfs_prepare_pages_for_non_resident_write(), we do not need to do any page
1550 * content modifications here for non-resident attributes. For resident
1551 * attributes we need to do the uptodate bringing here which we combine with
1552 * the copying into the mft record which means we save one atomic kmap.
1553 *
1554 * Return 0 on success or -errno on error.
1555 */
1556static int ntfs_commit_pages_after_write(struct page **pages,
1557 const unsigned nr_pages, s64 pos, size_t bytes)
1558{
1559 s64 end, initialized_size;
1560 loff_t i_size;
1561 struct inode *vi;
1562 ntfs_inode *ni, *base_ni;
1563 struct page *page;
1564 ntfs_attr_search_ctx *ctx;
1565 MFT_RECORD *m;
1566 ATTR_RECORD *a;
1567 char *kattr, *kaddr;
1568 unsigned long flags;
1569 u32 attr_len;
1570 int err;
1571
1572 BUG_ON(!nr_pages);
1573 BUG_ON(!pages);
1574 page = pages[0];
1575 BUG_ON(!page);
1576 vi = page->mapping->host;
1577 ni = NTFS_I(vi);
1578 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
Anton Altaparmakovd04bd1f2005-10-24 08:41:24 +01001579 "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001580 vi->i_ino, ni->type, page->index, nr_pages,
1581 (long long)pos, bytes);
1582 if (NInoNonResident(ni))
1583 return ntfs_commit_pages_after_non_resident_write(pages,
1584 nr_pages, pos, bytes);
1585 BUG_ON(nr_pages > 1);
1586 /*
1587 * Attribute is resident, implying it is not compressed, encrypted, or
1588 * sparse.
1589 */
1590 if (!NInoAttr(ni))
1591 base_ni = ni;
1592 else
1593 base_ni = ni->ext.base_ntfs_ino;
1594 BUG_ON(NInoNonResident(ni));
1595 /* Map, pin, and lock the mft record. */
1596 m = map_mft_record(base_ni);
1597 if (IS_ERR(m)) {
1598 err = PTR_ERR(m);
1599 m = NULL;
1600 ctx = NULL;
1601 goto err_out;
1602 }
1603 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1604 if (unlikely(!ctx)) {
1605 err = -ENOMEM;
1606 goto err_out;
1607 }
1608 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1609 CASE_SENSITIVE, 0, NULL, 0, ctx);
1610 if (unlikely(err)) {
1611 if (err == -ENOENT)
1612 err = -EIO;
1613 goto err_out;
1614 }
1615 a = ctx->attr;
1616 BUG_ON(a->non_resident);
1617 /* The total length of the attribute value. */
1618 attr_len = le32_to_cpu(a->data.resident.value_length);
1619 i_size = i_size_read(vi);
1620 BUG_ON(attr_len != i_size);
1621 BUG_ON(pos > attr_len);
1622 end = pos + bytes;
1623 BUG_ON(end > le32_to_cpu(a->length) -
1624 le16_to_cpu(a->data.resident.value_offset));
1625 kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
Cong Wanga3ac1412011-11-25 23:14:34 +08001626 kaddr = kmap_atomic(page);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001627 /* Copy the received data from the page to the mft record. */
1628 memcpy(kattr + pos, kaddr + pos, bytes);
1629 /* Update the attribute length if necessary. */
1630 if (end > attr_len) {
1631 attr_len = end;
1632 a->data.resident.value_length = cpu_to_le32(attr_len);
1633 }
1634 /*
1635 * If the page is not uptodate, bring the out of bounds area(s)
1636 * uptodate by copying data from the mft record to the page.
1637 */
1638 if (!PageUptodate(page)) {
1639 if (pos > 0)
1640 memcpy(kaddr, kattr, pos);
1641 if (end < attr_len)
1642 memcpy(kaddr + end, kattr + end, attr_len - end);
1643 /* Zero the region outside the end of the attribute value. */
1644 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1645 flush_dcache_page(page);
1646 SetPageUptodate(page);
1647 }
Cong Wanga3ac1412011-11-25 23:14:34 +08001648 kunmap_atomic(kaddr);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001649 /* Update initialized_size/i_size if necessary. */
1650 read_lock_irqsave(&ni->size_lock, flags);
1651 initialized_size = ni->initialized_size;
1652 BUG_ON(end > ni->allocated_size);
1653 read_unlock_irqrestore(&ni->size_lock, flags);
1654 BUG_ON(initialized_size != i_size);
1655 if (end > initialized_size) {
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001656 write_lock_irqsave(&ni->size_lock, flags);
1657 ni->initialized_size = end;
1658 i_size_write(vi, end);
1659 write_unlock_irqrestore(&ni->size_lock, flags);
1660 }
1661 /* Mark the mft record dirty, so it gets written back. */
1662 flush_dcache_mft_record_page(ctx->ntfs_ino);
1663 mark_mft_record_dirty(ctx->ntfs_ino);
1664 ntfs_attr_put_search_ctx(ctx);
1665 unmap_mft_record(base_ni);
1666 ntfs_debug("Done.");
1667 return 0;
1668err_out:
1669 if (err == -ENOMEM) {
1670 ntfs_warning(vi->i_sb, "Error allocating memory required to "
1671 "commit the write.");
1672 if (PageUptodate(page)) {
1673 ntfs_warning(vi->i_sb, "Page is uptodate, setting "
1674 "dirty so the write will be retried "
1675 "later on by the VM.");
1676 /*
1677 * Put the page on mapping->dirty_pages, but leave its
1678 * buffers' dirty state as-is.
1679 */
1680 __set_page_dirty_nobuffers(page);
1681 err = 0;
1682 } else
1683 ntfs_error(vi->i_sb, "Page is not uptodate. Written "
1684 "data has been lost.");
1685 } else {
1686 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
1687 "with error %i.", err);
1688 NVolSetErrors(ni->vol);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001689 }
1690 if (ctx)
1691 ntfs_attr_put_search_ctx(ctx);
1692 if (m)
1693 unmap_mft_record(base_ni);
1694 return err;
1695}
1696
Anton Altaparmakova632f552015-03-11 10:43:32 -04001697/*
1698 * Copy as much as we can into the pages and return the number of bytes which
1699 * were successfully copied. If a fault is encountered then clear the pages
1700 * out to (ofs + bytes) and return the number of bytes which were copied.
1701 */
1702static size_t ntfs_copy_from_user_iter(struct page **pages, unsigned nr_pages,
1703 unsigned ofs, struct iov_iter *i, size_t bytes)
Marco Stornelli9014da72012-12-15 11:58:36 +01001704{
Anton Altaparmakova632f552015-03-11 10:43:32 -04001705 struct page **last_page = pages + nr_pages;
1706 size_t total = 0;
1707 struct iov_iter data = *i;
1708 unsigned len, copied;
Marco Stornelli9014da72012-12-15 11:58:36 +01001709
Anton Altaparmakova632f552015-03-11 10:43:32 -04001710 do {
1711 len = PAGE_CACHE_SIZE - ofs;
1712 if (len > bytes)
1713 len = bytes;
1714 copied = iov_iter_copy_from_user_atomic(*pages, &data, ofs,
1715 len);
1716 total += copied;
1717 bytes -= copied;
1718 if (!bytes)
1719 break;
1720 iov_iter_advance(&data, copied);
1721 if (copied < len)
1722 goto err;
1723 ofs = 0;
1724 } while (++pages < last_page);
1725out:
1726 return total;
1727err:
1728 /* Zero the rest of the target like __copy_from_user(). */
1729 len = PAGE_CACHE_SIZE - copied;
1730 do {
1731 if (len > bytes)
1732 len = bytes;
1733 zero_user(*pages, copied, len);
1734 bytes -= len;
1735 copied = 0;
1736 len = PAGE_CACHE_SIZE;
1737 } while (++pages < last_page);
1738 goto out;
Marco Stornelli9014da72012-12-15 11:58:36 +01001739}
1740
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001741/**
Anton Altaparmakova632f552015-03-11 10:43:32 -04001742 * ntfs_perform_write - perform buffered write to a file
1743 * @file: file to write to
1744 * @i: iov_iter with data to write
1745 * @pos: byte offset in file at which to begin writing to
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001746 */
Anton Altaparmakova632f552015-03-11 10:43:32 -04001747static ssize_t ntfs_perform_write(struct file *file, struct iov_iter *i,
1748 loff_t pos)
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001749{
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001750 struct address_space *mapping = file->f_mapping;
1751 struct inode *vi = mapping->host;
1752 ntfs_inode *ni = NTFS_I(vi);
1753 ntfs_volume *vol = ni->vol;
1754 struct page *pages[NTFS_MAX_PAGES_PER_CLUSTER];
1755 struct page *cached_page = NULL;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001756 VCN last_vcn;
1757 LCN lcn;
Anton Altaparmakova632f552015-03-11 10:43:32 -04001758 size_t bytes;
1759 ssize_t status, written = 0;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001760 unsigned nr_pages;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001761
Anton Altaparmakova632f552015-03-11 10:43:32 -04001762 ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
1763 "0x%llx, count 0x%lx.", vi->i_ino,
1764 (unsigned)le32_to_cpu(ni->type),
1765 (unsigned long long)pos,
1766 (unsigned long)iov_iter_count(i));
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001767 /*
1768 * If a previous ntfs_truncate() failed, repeat it and abort if it
1769 * fails again.
1770 */
1771 if (unlikely(NInoTruncateFailed(ni))) {
Anton Altaparmakova632f552015-03-11 10:43:32 -04001772 int err;
1773
Christoph Hellwigbd5fe6c2011-06-24 14:29:43 -04001774 inode_dio_wait(vi);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001775 err = ntfs_truncate(vi);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001776 if (err || NInoTruncateFailed(ni)) {
1777 if (!err)
1778 err = -EIO;
1779 ntfs_error(vol->sb, "Cannot perform write to inode "
1780 "0x%lx, attribute type 0x%x, because "
1781 "ntfs_truncate() failed (error code "
1782 "%i).", vi->i_ino,
1783 (unsigned)le32_to_cpu(ni->type), err);
1784 return err;
1785 }
1786 }
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001787 /*
1788 * Determine the number of pages per cluster for non-resident
1789 * attributes.
1790 */
1791 nr_pages = 1;
1792 if (vol->cluster_size > PAGE_CACHE_SIZE && NInoNonResident(ni))
1793 nr_pages = vol->cluster_size >> PAGE_CACHE_SHIFT;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001794 last_vcn = -1;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001795 do {
1796 VCN vcn;
1797 pgoff_t idx, start_idx;
1798 unsigned ofs, do_pages, u;
1799 size_t copied;
1800
1801 start_idx = idx = pos >> PAGE_CACHE_SHIFT;
1802 ofs = pos & ~PAGE_CACHE_MASK;
1803 bytes = PAGE_CACHE_SIZE - ofs;
1804 do_pages = 1;
1805 if (nr_pages > 1) {
1806 vcn = pos >> vol->cluster_size_bits;
1807 if (vcn != last_vcn) {
1808 last_vcn = vcn;
1809 /*
1810 * Get the lcn of the vcn the write is in. If
1811 * it is a hole, need to lock down all pages in
1812 * the cluster.
1813 */
1814 down_read(&ni->runlist.lock);
1815 lcn = ntfs_attr_vcn_to_lcn_nolock(ni, pos >>
Richard Knutssonc49c3112006-09-30 23:27:12 -07001816 vol->cluster_size_bits, false);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001817 up_read(&ni->runlist.lock);
1818 if (unlikely(lcn < LCN_HOLE)) {
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001819 if (lcn == LCN_ENOMEM)
1820 status = -ENOMEM;
Anton Altaparmakova632f552015-03-11 10:43:32 -04001821 else {
1822 status = -EIO;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001823 ntfs_error(vol->sb, "Cannot "
1824 "perform write to "
1825 "inode 0x%lx, "
1826 "attribute type 0x%x, "
1827 "because the attribute "
1828 "is corrupt.",
1829 vi->i_ino, (unsigned)
1830 le32_to_cpu(ni->type));
Anton Altaparmakova632f552015-03-11 10:43:32 -04001831 }
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001832 break;
1833 }
1834 if (lcn == LCN_HOLE) {
1835 start_idx = (pos & ~(s64)
1836 vol->cluster_size_mask)
1837 >> PAGE_CACHE_SHIFT;
1838 bytes = vol->cluster_size - (pos &
1839 vol->cluster_size_mask);
1840 do_pages = nr_pages;
1841 }
1842 }
1843 }
Anton Altaparmakova632f552015-03-11 10:43:32 -04001844 if (bytes > iov_iter_count(i))
1845 bytes = iov_iter_count(i);
1846again:
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001847 /*
1848 * Bring in the user page(s) that we will copy from _first_.
1849 * Otherwise there is a nasty deadlock on copying from the same
1850 * page(s) as we are writing to, without it/them being marked
1851 * up-to-date. Note, at present there is nothing to stop the
1852 * pages being swapped out between us bringing them into memory
1853 * and doing the actual copying.
1854 */
Anton Altaparmakova632f552015-03-11 10:43:32 -04001855 if (unlikely(iov_iter_fault_in_multipages_readable(i, bytes))) {
1856 status = -EFAULT;
1857 break;
1858 }
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001859 /* Get and lock @do_pages starting at index @start_idx. */
1860 status = __ntfs_grab_cache_pages(mapping, start_idx, do_pages,
Minchan Kim4c990002010-05-24 14:33:07 -07001861 pages, &cached_page);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001862 if (unlikely(status))
1863 break;
1864 /*
1865 * For non-resident attributes, we need to fill any holes with
1866 * actual clusters and ensure all bufferes are mapped. We also
1867 * need to bring uptodate any buffers that are only partially
1868 * being written to.
1869 */
1870 if (NInoNonResident(ni)) {
1871 status = ntfs_prepare_pages_for_non_resident_write(
1872 pages, do_pages, pos, bytes);
1873 if (unlikely(status)) {
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001874 do {
1875 unlock_page(pages[--do_pages]);
1876 page_cache_release(pages[do_pages]);
1877 } while (do_pages);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001878 break;
1879 }
1880 }
1881 u = (pos >> PAGE_CACHE_SHIFT) - pages[0]->index;
Anton Altaparmakova632f552015-03-11 10:43:32 -04001882 copied = ntfs_copy_from_user_iter(pages + u, do_pages - u, ofs,
1883 i, bytes);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001884 ntfs_flush_dcache_pages(pages + u, do_pages - u);
Anton Altaparmakova632f552015-03-11 10:43:32 -04001885 status = 0;
1886 if (likely(copied == bytes)) {
1887 status = ntfs_commit_pages_after_write(pages, do_pages,
1888 pos, bytes);
1889 if (!status)
1890 status = bytes;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001891 }
1892 do {
1893 unlock_page(pages[--do_pages]);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001894 page_cache_release(pages[do_pages]);
1895 } while (do_pages);
Anton Altaparmakova632f552015-03-11 10:43:32 -04001896 if (unlikely(status < 0))
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001897 break;
Anton Altaparmakova632f552015-03-11 10:43:32 -04001898 copied = status;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001899 cond_resched();
Anton Altaparmakova632f552015-03-11 10:43:32 -04001900 if (unlikely(!copied)) {
1901 size_t sc;
1902
1903 /*
1904 * We failed to copy anything. Fall back to single
1905 * segment length write.
1906 *
1907 * This is needed to avoid possible livelock in the
1908 * case that all segments in the iov cannot be copied
1909 * at once without a pagefault.
1910 */
1911 sc = iov_iter_single_seg_count(i);
1912 if (bytes > sc)
1913 bytes = sc;
1914 goto again;
1915 }
1916 iov_iter_advance(i, copied);
1917 pos += copied;
1918 written += copied;
1919 balance_dirty_pages_ratelimited(mapping);
1920 if (fatal_signal_pending(current)) {
1921 status = -EINTR;
1922 break;
1923 }
1924 } while (iov_iter_count(i));
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001925 if (cached_page)
1926 page_cache_release(cached_page);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001927 ntfs_debug("Done. Returning %s (written 0x%lx, status %li).",
1928 written ? "written" : "status", (unsigned long)written,
1929 (long)status);
1930 return written ? written : status;
1931}
1932
1933/**
Anton Altaparmakova632f552015-03-11 10:43:32 -04001934 * ntfs_file_write_iter - simple wrapper for ntfs_file_write_iter_nolock()
1935 * @iocb: IO state structure
1936 * @from: iov_iter with data to write
1937 *
1938 * Basically the same as generic_file_write_iter() except that it ends up
Al Viroccca2682015-04-05 14:06:24 -04001939 * up calling ntfs_perform_write() instead of generic_perform_write() and that
1940 * O_DIRECT is not implemented.
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001941 */
Anton Altaparmakova632f552015-03-11 10:43:32 -04001942static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001943{
1944 struct file *file = iocb->ki_filp;
Anton Altaparmakova632f552015-03-11 10:43:32 -04001945 struct inode *vi = file_inode(file);
Al Viroccca2682015-04-05 14:06:24 -04001946 ssize_t written = 0;
1947 ssize_t err;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001948
Anton Altaparmakova632f552015-03-11 10:43:32 -04001949 mutex_lock(&vi->i_mutex);
Al Viroccca2682015-04-05 14:06:24 -04001950 /* We can write back this queue in page reclaim. */
1951 current->backing_dev_info = inode_to_bdi(vi);
1952 err = ntfs_prepare_file_for_write(iocb, from);
1953 if (iov_iter_count(from) && !err)
1954 written = ntfs_perform_write(file, from, iocb->ki_pos);
1955 current->backing_dev_info = NULL;
Anton Altaparmakova632f552015-03-11 10:43:32 -04001956 mutex_unlock(&vi->i_mutex);
Al Viroccca2682015-04-05 14:06:24 -04001957 if (likely(written > 0)) {
1958 err = generic_write_sync(file, iocb->ki_pos, written);
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001959 if (err < 0)
Al Viroccca2682015-04-05 14:06:24 -04001960 written = 0;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001961 }
Al Viroccca2682015-04-05 14:06:24 -04001962 iocb->ki_pos += written;
1963 return written ? written : err;
Anton Altaparmakov98b27032005-10-11 15:40:40 +01001964}
1965
1966/**
Linus Torvalds1da177e2005-04-16 15:20:36 -07001967 * ntfs_file_fsync - sync a file to disk
1968 * @filp: file to be synced
Linus Torvalds1da177e2005-04-16 15:20:36 -07001969 * @datasync: if non-zero only flush user data and not metadata
1970 *
1971 * Data integrity sync of a file to disk. Used for fsync, fdatasync, and msync
1972 * system calls. This function is inspired by fs/buffer.c::file_fsync().
1973 *
1974 * If @datasync is false, write the mft record and all associated extent mft
1975 * records as well as the $DATA attribute and then sync the block device.
1976 *
1977 * If @datasync is true and the attribute is non-resident, we skip the writing
1978 * of the mft record and all associated extent mft records (this might still
1979 * happen due to the write_inode_now() call).
1980 *
1981 * Also, if @datasync is true, we do not wait on the inode to be written out
1982 * but we always wait on the page cache pages to be written out.
1983 *
Jes Sorensen1b1dcc12006-01-09 15:59:24 -08001984 * Locking: Caller must hold i_mutex on the inode.
Linus Torvalds1da177e2005-04-16 15:20:36 -07001985 *
1986 * TODO: We should probably also write all attribute/index inodes associated
1987 * with this inode but since we have no simple way of getting to them we ignore
1988 * this problem for now.
1989 */
Josef Bacik02c24a82011-07-16 20:44:56 -04001990static int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end,
1991 int datasync)
Linus Torvalds1da177e2005-04-16 15:20:36 -07001992{
Christoph Hellwig7ea80852010-05-26 17:53:25 +02001993 struct inode *vi = filp->f_mapping->host;
Linus Torvalds1da177e2005-04-16 15:20:36 -07001994 int err, ret = 0;
1995
1996 ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
Josef Bacik02c24a82011-07-16 20:44:56 -04001997
1998 err = filemap_write_and_wait_range(vi->i_mapping, start, end);
1999 if (err)
2000 return err;
2001 mutex_lock(&vi->i_mutex);
2002
Linus Torvalds1da177e2005-04-16 15:20:36 -07002003 BUG_ON(S_ISDIR(vi->i_mode));
2004 if (!datasync || !NInoNonResident(NTFS_I(vi)))
Christoph Hellwiga9185b42010-03-05 09:21:37 +01002005 ret = __ntfs_write_inode(vi, 1);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002006 write_inode_now(vi, !datasync);
Anton Altaparmakovf25dfb52005-09-08 20:35:33 +01002007 /*
2008 * NOTE: If we were to use mapping->private_list (see ext2 and
2009 * fs/buffer.c) for dirty blocks then we could optimize the below to be
2010 * sync_mapping_buffers(vi->i_mapping).
2011 */
Linus Torvalds1da177e2005-04-16 15:20:36 -07002012 err = sync_blockdev(vi->i_sb->s_bdev);
2013 if (unlikely(err && !ret))
2014 ret = err;
2015 if (likely(!ret))
2016 ntfs_debug("Done.");
2017 else
2018 ntfs_warning(vi->i_sb, "Failed to f%ssync inode 0x%lx. Error "
2019 "%u.", datasync ? "data" : "", vi->i_ino, -ret);
Josef Bacik02c24a82011-07-16 20:44:56 -04002020 mutex_unlock(&vi->i_mutex);
Linus Torvalds1da177e2005-04-16 15:20:36 -07002021 return ret;
2022}
2023
2024#endif /* NTFS_RW */
2025
Arjan van de Ven4b6f5d22006-03-28 01:56:42 -08002026const struct file_operations ntfs_file_ops = {
Anton Altaparmakova632f552015-03-11 10:43:32 -04002027 .llseek = generic_file_llseek,
Anton Altaparmakova632f552015-03-11 10:43:32 -04002028 .read_iter = generic_file_read_iter,
Linus Torvalds1da177e2005-04-16 15:20:36 -07002029#ifdef NTFS_RW
Anton Altaparmakova632f552015-03-11 10:43:32 -04002030 .write_iter = ntfs_file_write_iter,
2031 .fsync = ntfs_file_fsync,
Linus Torvalds1da177e2005-04-16 15:20:36 -07002032#endif /* NTFS_RW */
Anton Altaparmakova632f552015-03-11 10:43:32 -04002033 .mmap = generic_file_mmap,
2034 .open = ntfs_file_open,
2035 .splice_read = generic_file_splice_read,
Linus Torvalds1da177e2005-04-16 15:20:36 -07002036};
2037
Arjan van de Ven92e1d5b2007-02-12 00:55:39 -08002038const struct inode_operations ntfs_file_inode_ops = {
Linus Torvalds1da177e2005-04-16 15:20:36 -07002039#ifdef NTFS_RW
Linus Torvalds1da177e2005-04-16 15:20:36 -07002040 .setattr = ntfs_setattr,
2041#endif /* NTFS_RW */
2042};
2043
Arjan van de Ven4b6f5d22006-03-28 01:56:42 -08002044const struct file_operations ntfs_empty_file_ops = {};
Linus Torvalds1da177e2005-04-16 15:20:36 -07002045
Arjan van de Ven92e1d5b2007-02-12 00:55:39 -08002046const struct inode_operations ntfs_empty_inode_ops = {};