]> bbs.cooldavid.org Git - net-next-2.6.git/blame - fs/ntfs/file.c
ntfs: clean up ntfs_attr_extend_initialized
[net-next-2.6.git] / fs / ntfs / file.c
CommitLineData
1da177e4 1/*
f25dfb5e 2 * file.c - NTFS kernel file operations. Part of the Linux-NTFS project.
1da177e4 3 *
bfab36e8 4 * Copyright (c) 2001-2007 Anton Altaparmakov
1da177e4
LT
5 *
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
1da177e4 22#include <linux/buffer_head.h>
5a0e3ad6 23#include <linux/gfp.h>
98b27036
AA
24#include <linux/pagemap.h>
25#include <linux/pagevec.h>
26#include <linux/sched.h>
27#include <linux/swap.h>
28#include <linux/uio.h>
29#include <linux/writeback.h>
1da177e4 30
98b27036
AA
31#include <asm/page.h>
32#include <asm/uaccess.h>
33
34#include "attrib.h"
35#include "bitmap.h"
1da177e4
LT
36#include "inode.h"
37#include "debug.h"
98b27036
AA
38#include "lcnalloc.h"
39#include "malloc.h"
40#include "mft.h"
1da177e4
LT
41#include "ntfs.h"
42
43/**
44 * ntfs_file_open - called when an inode is about to be opened
45 * @vi: inode to be opened
46 * @filp: file structure describing the inode
47 *
48 * Limit file size to the page cache limit on architectures where unsigned long
49 * is 32-bits. This is the most we can do for now without overflowing the page
50 * cache page index. Doing it this way means we don't run into problems because
51 * of existing too large files. It would be better to allow the user to read
52 * the beginning of the file but I doubt very much anyone is going to hit this
53 * check on a 32-bit architecture, so there is no point in adding the extra
54 * complexity required to support this.
55 *
56 * On 64-bit architectures, the check is hopefully optimized away by the
57 * compiler.
58 *
59 * After the check passes, just call generic_file_open() to do its work.
60 */
61static int ntfs_file_open(struct inode *vi, struct file *filp)
62{
63 if (sizeof(unsigned long) < 8) {
d4b9ba7b 64 if (i_size_read(vi) > MAX_LFS_FILESIZE)
a9c62a18 65 return -EOVERFLOW;
1da177e4
LT
66 }
67 return generic_file_open(vi, filp);
68}
69
70#ifdef NTFS_RW
71
98b27036
AA
72/**
73 * ntfs_attr_extend_initialized - extend the initialized size of an attribute
74 * @ni: ntfs inode of the attribute to extend
75 * @new_init_size: requested new initialized size in bytes
76 * @cached_page: store any allocated but unused page here
77 * @lru_pvec: lru-buffering pagevec of the caller
78 *
79 * Extend the initialized size of an attribute described by the ntfs inode @ni
80 * to @new_init_size bytes. This involves zeroing any non-sparse space between
81 * the old initialized size and @new_init_size both in the page cache and on
dda65b94
AA
82 * disk (if relevant complete pages are already uptodate in the page cache then
83 * these are simply marked dirty).
98b27036
AA
84 *
85 * As a side-effect, the file size (vfs inode->i_size) may be incremented as,
86 * in the resident attribute case, it is tied to the initialized size and, in
87 * the non-resident attribute case, it may not fall below the initialized size.
88 *
89 * Note that if the attribute is resident, we do not need to touch the page
90 * cache at all. This is because if the page cache page is not uptodate we
91 * bring it uptodate later, when doing the write to the mft record since we
92 * then already have the page mapped. And if the page is uptodate, the
93 * non-initialized region will already have been zeroed when the page was
94 * brought uptodate and the region may in fact already have been overwritten
95 * with new data via mmap() based writes, so we cannot just zero it. And since
96 * POSIX specifies that the behaviour of resizing a file whilst it is mmap()ped
97 * is unspecified, we choose not to do zeroing and thus we do not need to touch
dda65b94
AA
98 * the page at all. For a more detailed explanation see ntfs_truncate() in
99 * fs/ntfs/inode.c.
98b27036 100 *
98b27036
AA
101 * Return 0 on success and -errno on error. In the case that an error is
102 * encountered it is possible that the initialized size will already have been
103 * incremented some way towards @new_init_size but it is guaranteed that if
104 * this is the case, the necessary zeroing will also have happened and that all
105 * metadata is self-consistent.
106 *
1b1dcc1b 107 * Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be
dda65b94 108 * held by the caller.
98b27036 109 */
2ec93b0b 110static int ntfs_attr_extend_initialized(ntfs_inode *ni, const s64 new_init_size)
98b27036
AA
111{
112 s64 old_init_size;
113 loff_t old_i_size;
114 pgoff_t index, end_index;
115 unsigned long flags;
116 struct inode *vi = VFS_I(ni);
117 ntfs_inode *base_ni;
118 MFT_RECORD *m = NULL;
119 ATTR_RECORD *a;
120 ntfs_attr_search_ctx *ctx = NULL;
121 struct address_space *mapping;
122 struct page *page = NULL;
123 u8 *kattr;
124 int err;
125 u32 attr_len;
126
127 read_lock_irqsave(&ni->size_lock, flags);
128 old_init_size = ni->initialized_size;
129 old_i_size = i_size_read(vi);
130 BUG_ON(new_init_size > ni->allocated_size);
131 read_unlock_irqrestore(&ni->size_lock, flags);
132 ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
133 "old_initialized_size 0x%llx, "
134 "new_initialized_size 0x%llx, i_size 0x%llx.",
135 vi->i_ino, (unsigned)le32_to_cpu(ni->type),
136 (unsigned long long)old_init_size,
137 (unsigned long long)new_init_size, old_i_size);
138 if (!NInoAttr(ni))
139 base_ni = ni;
140 else
141 base_ni = ni->ext.base_ntfs_ino;
142 /* Use goto to reduce indentation and we need the label below anyway. */
143 if (NInoNonResident(ni))
144 goto do_non_resident_extend;
145 BUG_ON(old_init_size != old_i_size);
146 m = map_mft_record(base_ni);
147 if (IS_ERR(m)) {
148 err = PTR_ERR(m);
149 m = NULL;
150 goto err_out;
151 }
152 ctx = ntfs_attr_get_search_ctx(base_ni, m);
153 if (unlikely(!ctx)) {
154 err = -ENOMEM;
155 goto err_out;
156 }
157 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
158 CASE_SENSITIVE, 0, NULL, 0, ctx);
159 if (unlikely(err)) {
160 if (err == -ENOENT)
161 err = -EIO;
162 goto err_out;
163 }
164 m = ctx->mrec;
165 a = ctx->attr;
166 BUG_ON(a->non_resident);
167 /* The total length of the attribute value. */
168 attr_len = le32_to_cpu(a->data.resident.value_length);
169 BUG_ON(old_i_size != (loff_t)attr_len);
170 /*
171 * Do the zeroing in the mft record and update the attribute size in
172 * the mft record.
173 */
174 kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
175 memset(kattr + attr_len, 0, new_init_size - attr_len);
176 a->data.resident.value_length = cpu_to_le32((u32)new_init_size);
177 /* Finally, update the sizes in the vfs and ntfs inodes. */
178 write_lock_irqsave(&ni->size_lock, flags);
179 i_size_write(vi, new_init_size);
180 ni->initialized_size = new_init_size;
181 write_unlock_irqrestore(&ni->size_lock, flags);
182 goto done;
183do_non_resident_extend:
184 /*
185 * If the new initialized size @new_init_size exceeds the current file
186 * size (vfs inode->i_size), we need to extend the file size to the
187 * new initialized size.
188 */
189 if (new_init_size > old_i_size) {
190 m = map_mft_record(base_ni);
191 if (IS_ERR(m)) {
192 err = PTR_ERR(m);
193 m = NULL;
194 goto err_out;
195 }
196 ctx = ntfs_attr_get_search_ctx(base_ni, m);
197 if (unlikely(!ctx)) {
198 err = -ENOMEM;
199 goto err_out;
200 }
201 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
202 CASE_SENSITIVE, 0, NULL, 0, ctx);
203 if (unlikely(err)) {
204 if (err == -ENOENT)
205 err = -EIO;
206 goto err_out;
207 }
208 m = ctx->mrec;
209 a = ctx->attr;
210 BUG_ON(!a->non_resident);
211 BUG_ON(old_i_size != (loff_t)
212 sle64_to_cpu(a->data.non_resident.data_size));
213 a->data.non_resident.data_size = cpu_to_sle64(new_init_size);
214 flush_dcache_mft_record_page(ctx->ntfs_ino);
215 mark_mft_record_dirty(ctx->ntfs_ino);
216 /* Update the file size in the vfs inode. */
217 i_size_write(vi, new_init_size);
218 ntfs_attr_put_search_ctx(ctx);
219 ctx = NULL;
220 unmap_mft_record(base_ni);
221 m = NULL;
222 }
223 mapping = vi->i_mapping;
224 index = old_init_size >> PAGE_CACHE_SHIFT;
225 end_index = (new_init_size + PAGE_CACHE_SIZE - 1) >> PAGE_CACHE_SHIFT;
226 do {
227 /*
228 * Read the page. If the page is not present, this will zero
229 * the uninitialized regions for us.
230 */
090d2b18 231 page = read_mapping_page(mapping, index, NULL);
98b27036
AA
232 if (IS_ERR(page)) {
233 err = PTR_ERR(page);
234 goto init_err_out;
235 }
6fe6900e 236 if (unlikely(PageError(page))) {
98b27036
AA
237 page_cache_release(page);
238 err = -EIO;
239 goto init_err_out;
240 }
241 /*
242 * Update the initialized size in the ntfs inode. This is
243 * enough to make ntfs_writepage() work.
244 */
245 write_lock_irqsave(&ni->size_lock, flags);
3c6af7fa 246 ni->initialized_size = (s64)(index + 1) << PAGE_CACHE_SHIFT;
98b27036
AA
247 if (ni->initialized_size > new_init_size)
248 ni->initialized_size = new_init_size;
249 write_unlock_irqrestore(&ni->size_lock, flags);
250 /* Set the page dirty so it gets written out. */
251 set_page_dirty(page);
252 page_cache_release(page);
253 /*
254 * Play nice with the vm and the rest of the system. This is
255 * very much needed as we can potentially be modifying the
256 * initialised size from a very small value to a really huge
257 * value, e.g.
258 * f = open(somefile, O_TRUNC);
259 * truncate(f, 10GiB);
260 * seek(f, 10GiB);
261 * write(f, 1);
262 * And this would mean we would be marking dirty hundreds of
263 * thousands of pages or as in the above example more than
264 * two and a half million pages!
265 *
266 * TODO: For sparse pages could optimize this workload by using
267 * the FsMisc / MiscFs page bit as a "PageIsSparse" bit. This
268 * would be set in readpage for sparse pages and here we would
269 * not need to mark dirty any pages which have this bit set.
270 * The only caveat is that we have to clear the bit everywhere
271 * where we allocate any clusters that lie in the page or that
272 * contain the page.
273 *
274 * TODO: An even greater optimization would be for us to only
275 * call readpage() on pages which are not in sparse regions as
276 * determined from the runlist. This would greatly reduce the
277 * number of pages we read and make dirty in the case of sparse
278 * files.
279 */
280 balance_dirty_pages_ratelimited(mapping);
281 cond_resched();
282 } while (++index < end_index);
283 read_lock_irqsave(&ni->size_lock, flags);
284 BUG_ON(ni->initialized_size != new_init_size);
285 read_unlock_irqrestore(&ni->size_lock, flags);
286 /* Now bring in sync the initialized_size in the mft record. */
287 m = map_mft_record(base_ni);
288 if (IS_ERR(m)) {
289 err = PTR_ERR(m);
290 m = NULL;
291 goto init_err_out;
292 }
293 ctx = ntfs_attr_get_search_ctx(base_ni, m);
294 if (unlikely(!ctx)) {
295 err = -ENOMEM;
296 goto init_err_out;
297 }
298 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
299 CASE_SENSITIVE, 0, NULL, 0, ctx);
300 if (unlikely(err)) {
301 if (err == -ENOENT)
302 err = -EIO;
303 goto init_err_out;
304 }
305 m = ctx->mrec;
306 a = ctx->attr;
307 BUG_ON(!a->non_resident);
308 a->data.non_resident.initialized_size = cpu_to_sle64(new_init_size);
309done:
310 flush_dcache_mft_record_page(ctx->ntfs_ino);
311 mark_mft_record_dirty(ctx->ntfs_ino);
312 if (ctx)
313 ntfs_attr_put_search_ctx(ctx);
314 if (m)
315 unmap_mft_record(base_ni);
316 ntfs_debug("Done, initialized_size 0x%llx, i_size 0x%llx.",
317 (unsigned long long)new_init_size, i_size_read(vi));
318 return 0;
319init_err_out:
320 write_lock_irqsave(&ni->size_lock, flags);
321 ni->initialized_size = old_init_size;
322 write_unlock_irqrestore(&ni->size_lock, flags);
323err_out:
324 if (ctx)
325 ntfs_attr_put_search_ctx(ctx);
326 if (m)
327 unmap_mft_record(base_ni);
328 ntfs_debug("Failed. Returning error code %i.", err);
329 return err;
330}
331
332/**
333 * ntfs_fault_in_pages_readable -
334 *
335 * Fault a number of userspace pages into pagetables.
336 *
337 * Unlike include/linux/pagemap.h::fault_in_pages_readable(), this one copes
338 * with more than two userspace pages as well as handling the single page case
339 * elegantly.
340 *
341 * If you find this difficult to understand, then think of the while loop being
342 * the following code, except that we do without the integer variable ret:
343 *
344 * do {
345 * ret = __get_user(c, uaddr);
346 * uaddr += PAGE_SIZE;
347 * } while (!ret && uaddr < end);
348 *
349 * Note, the final __get_user() may well run out-of-bounds of the user buffer,
350 * but _not_ out-of-bounds of the page the user buffer belongs to, and since
351 * this is only a read and not a write, and since it is still in the same page,
352 * it should not matter and this makes the code much simpler.
353 */
354static inline void ntfs_fault_in_pages_readable(const char __user *uaddr,
355 int bytes)
356{
357 const char __user *end;
358 volatile char c;
359
360 /* Set @end to the first byte outside the last page we care about. */
bfab36e8 361 end = (const char __user*)PAGE_ALIGN((unsigned long)uaddr + bytes);
98b27036
AA
362
363 while (!__get_user(c, uaddr) && (uaddr += PAGE_SIZE, uaddr < end))
364 ;
365}
366
367/**
368 * ntfs_fault_in_pages_readable_iovec -
369 *
370 * Same as ntfs_fault_in_pages_readable() but operates on an array of iovecs.
371 */
372static inline void ntfs_fault_in_pages_readable_iovec(const struct iovec *iov,
373 size_t iov_ofs, int bytes)
374{
375 do {
376 const char __user *buf;
377 unsigned len;
378
379 buf = iov->iov_base + iov_ofs;
380 len = iov->iov_len - iov_ofs;
381 if (len > bytes)
382 len = bytes;
383 ntfs_fault_in_pages_readable(buf, len);
384 bytes -= len;
385 iov++;
386 iov_ofs = 0;
387 } while (bytes);
388}
389
390/**
391 * __ntfs_grab_cache_pages - obtain a number of locked pages
392 * @mapping: address space mapping from which to obtain page cache pages
393 * @index: starting index in @mapping at which to begin obtaining pages
394 * @nr_pages: number of page cache pages to obtain
395 * @pages: array of pages in which to return the obtained page cache pages
396 * @cached_page: allocated but as yet unused page
397 * @lru_pvec: lru-buffering pagevec of caller
398 *
af901ca1 399 * Obtain @nr_pages locked page cache pages from the mapping @mapping and
98b27036
AA
400 * starting at index @index.
401 *
402 * If a page is newly created, increment its refcount and add it to the
403 * caller's lru-buffering pagevec @lru_pvec.
404 *
405 * This is the same as mm/filemap.c::__grab_cache_page(), except that @nr_pages
406 * are obtained at once instead of just one page and that 0 is returned on
407 * success and -errno on error.
408 *
409 * Note, the page locks are obtained in ascending page index order.
410 */
411static inline int __ntfs_grab_cache_pages(struct address_space *mapping,
412 pgoff_t index, const unsigned nr_pages, struct page **pages,
413 struct page **cached_page, struct pagevec *lru_pvec)
414{
415 int err, nr;
416
417 BUG_ON(!nr_pages);
418 err = nr = 0;
419 do {
420 pages[nr] = find_lock_page(mapping, index);
421 if (!pages[nr]) {
422 if (!*cached_page) {
423 *cached_page = page_cache_alloc(mapping);
424 if (unlikely(!*cached_page)) {
425 err = -ENOMEM;
426 goto err_out;
427 }
428 }
429 err = add_to_page_cache(*cached_page, mapping, index,
430 GFP_KERNEL);
431 if (unlikely(err)) {
432 if (err == -EEXIST)
433 continue;
434 goto err_out;
435 }
436 pages[nr] = *cached_page;
437 page_cache_get(*cached_page);
438 if (unlikely(!pagevec_add(lru_pvec, *cached_page)))
4f98a2fe 439 __pagevec_lru_add_file(lru_pvec);
98b27036
AA
440 *cached_page = NULL;
441 }
442 index++;
443 nr++;
444 } while (nr < nr_pages);
445out:
446 return err;
447err_out:
448 while (nr > 0) {
449 unlock_page(pages[--nr]);
450 page_cache_release(pages[nr]);
451 }
452 goto out;
453}
454
455static inline int ntfs_submit_bh_for_read(struct buffer_head *bh)
456{
457 lock_buffer(bh);
458 get_bh(bh);
459 bh->b_end_io = end_buffer_read_sync;
460 return submit_bh(READ, bh);
461}
462
463/**
464 * ntfs_prepare_pages_for_non_resident_write - prepare pages for receiving data
465 * @pages: array of destination pages
466 * @nr_pages: number of pages in @pages
467 * @pos: byte position in file at which the write begins
468 * @bytes: number of bytes to be written
469 *
470 * This is called for non-resident attributes from ntfs_file_buffered_write()
1b1dcc1b 471 * with i_mutex held on the inode (@pages[0]->mapping->host). There are
98b27036
AA
472 * @nr_pages pages in @pages which are locked but not kmap()ped. The source
473 * data has not yet been copied into the @pages.
474 *
475 * Need to fill any holes with actual clusters, allocate buffers if necessary,
476 * ensure all the buffers are mapped, and bring uptodate any buffers that are
477 * only partially being written to.
478 *
479 * If @nr_pages is greater than one, we are guaranteed that the cluster size is
480 * greater than PAGE_CACHE_SIZE, that all pages in @pages are entirely inside
481 * the same cluster and that they are the entirety of that cluster, and that
482 * the cluster is sparse, i.e. we need to allocate a cluster to fill the hole.
483 *
484 * i_size is not to be modified yet.
485 *
486 * Return 0 on success or -errno on error.
487 */
488static int ntfs_prepare_pages_for_non_resident_write(struct page **pages,
489 unsigned nr_pages, s64 pos, size_t bytes)
490{
491 VCN vcn, highest_vcn = 0, cpos, cend, bh_cpos, bh_cend;
492 LCN lcn;
493 s64 bh_pos, vcn_len, end, initialized_size;
494 sector_t lcn_block;
495 struct page *page;
496 struct inode *vi;
497 ntfs_inode *ni, *base_ni = NULL;
498 ntfs_volume *vol;
499 runlist_element *rl, *rl2;
500 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
501 ntfs_attr_search_ctx *ctx = NULL;
502 MFT_RECORD *m = NULL;
503 ATTR_RECORD *a = NULL;
504 unsigned long flags;
505 u32 attr_rec_len = 0;
506 unsigned blocksize, u;
507 int err, mp_size;
c49c3111 508 bool rl_write_locked, was_hole, is_retry;
98b27036
AA
509 unsigned char blocksize_bits;
510 struct {
511 u8 runlist_merged:1;
512 u8 mft_attr_mapped:1;
513 u8 mp_rebuilt:1;
514 u8 attr_switched:1;
515 } status = { 0, 0, 0, 0 };
516
517 BUG_ON(!nr_pages);
518 BUG_ON(!pages);
519 BUG_ON(!*pages);
520 vi = pages[0]->mapping->host;
521 ni = NTFS_I(vi);
522 vol = ni->vol;
523 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
d04bd1fb 524 "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
98b27036
AA
525 vi->i_ino, ni->type, pages[0]->index, nr_pages,
526 (long long)pos, bytes);
78af34f0
AA
527 blocksize = vol->sb->s_blocksize;
528 blocksize_bits = vol->sb->s_blocksize_bits;
98b27036
AA
529 u = 0;
530 do {
bfab36e8
AA
531 page = pages[u];
532 BUG_ON(!page);
98b27036
AA
533 /*
534 * create_empty_buffers() will create uptodate/dirty buffers if
535 * the page is uptodate/dirty.
536 */
537 if (!page_has_buffers(page)) {
538 create_empty_buffers(page, blocksize, 0);
539 if (unlikely(!page_has_buffers(page)))
540 return -ENOMEM;
541 }
542 } while (++u < nr_pages);
c49c3111 543 rl_write_locked = false;
98b27036
AA
544 rl = NULL;
545 err = 0;
546 vcn = lcn = -1;
547 vcn_len = 0;
548 lcn_block = -1;
c49c3111 549 was_hole = false;
98b27036
AA
550 cpos = pos >> vol->cluster_size_bits;
551 end = pos + bytes;
552 cend = (end + vol->cluster_size - 1) >> vol->cluster_size_bits;
553 /*
554 * Loop over each page and for each page over each buffer. Use goto to
555 * reduce indentation.
556 */
557 u = 0;
558do_next_page:
559 page = pages[u];
560 bh_pos = (s64)page->index << PAGE_CACHE_SHIFT;
561 bh = head = page_buffers(page);
562 do {
563 VCN cdelta;
564 s64 bh_end;
565 unsigned bh_cofs;
566
567 /* Clear buffer_new on all buffers to reinitialise state. */
568 if (buffer_new(bh))
569 clear_buffer_new(bh);
570 bh_end = bh_pos + blocksize;
571 bh_cpos = bh_pos >> vol->cluster_size_bits;
572 bh_cofs = bh_pos & vol->cluster_size_mask;
573 if (buffer_mapped(bh)) {
574 /*
575 * The buffer is already mapped. If it is uptodate,
576 * ignore it.
577 */
578 if (buffer_uptodate(bh))
579 continue;
580 /*
581 * The buffer is not uptodate. If the page is uptodate
582 * set the buffer uptodate and otherwise ignore it.
583 */
584 if (PageUptodate(page)) {
585 set_buffer_uptodate(bh);
586 continue;
587 }
588 /*
589 * Neither the page nor the buffer are uptodate. If
590 * the buffer is only partially being written to, we
591 * need to read it in before the write, i.e. now.
592 */
593 if ((bh_pos < pos && bh_end > pos) ||
594 (bh_pos < end && bh_end > end)) {
595 /*
596 * If the buffer is fully or partially within
597 * the initialized size, do an actual read.
598 * Otherwise, simply zero the buffer.
599 */
600 read_lock_irqsave(&ni->size_lock, flags);
601 initialized_size = ni->initialized_size;
602 read_unlock_irqrestore(&ni->size_lock, flags);
603 if (bh_pos < initialized_size) {
604 ntfs_submit_bh_for_read(bh);
605 *wait_bh++ = bh;
606 } else {
eebd2aa3
CL
607 zero_user(page, bh_offset(bh),
608 blocksize);
98b27036
AA
609 set_buffer_uptodate(bh);
610 }
611 }
612 continue;
613 }
614 /* Unmapped buffer. Need to map it. */
615 bh->b_bdev = vol->sb->s_bdev;
616 /*
617 * If the current buffer is in the same clusters as the map
618 * cache, there is no need to check the runlist again. The
619 * map cache is made up of @vcn, which is the first cached file
620 * cluster, @vcn_len which is the number of cached file
621 * clusters, @lcn is the device cluster corresponding to @vcn,
622 * and @lcn_block is the block number corresponding to @lcn.
623 */
624 cdelta = bh_cpos - vcn;
625 if (likely(!cdelta || (cdelta > 0 && cdelta < vcn_len))) {
626map_buffer_cached:
627 BUG_ON(lcn < 0);
628 bh->b_blocknr = lcn_block +
629 (cdelta << (vol->cluster_size_bits -
630 blocksize_bits)) +
631 (bh_cofs >> blocksize_bits);
632 set_buffer_mapped(bh);
633 /*
634 * If the page is uptodate so is the buffer. If the
635 * buffer is fully outside the write, we ignore it if
636 * it was already allocated and we mark it dirty so it
637 * gets written out if we allocated it. On the other
638 * hand, if we allocated the buffer but we are not
639 * marking it dirty we set buffer_new so we can do
640 * error recovery.
641 */
642 if (PageUptodate(page)) {
643 if (!buffer_uptodate(bh))
644 set_buffer_uptodate(bh);
645 if (unlikely(was_hole)) {
646 /* We allocated the buffer. */
647 unmap_underlying_metadata(bh->b_bdev,
648 bh->b_blocknr);
649 if (bh_end <= pos || bh_pos >= end)
650 mark_buffer_dirty(bh);
651 else
652 set_buffer_new(bh);
653 }
654 continue;
655 }
656 /* Page is _not_ uptodate. */
657 if (likely(!was_hole)) {
658 /*
659 * Buffer was already allocated. If it is not
660 * uptodate and is only partially being written
661 * to, we need to read it in before the write,
662 * i.e. now.
663 */
3aebf25b
AA
664 if (!buffer_uptodate(bh) && bh_pos < end &&
665 bh_end > pos &&
666 (bh_pos < pos ||
667 bh_end > end)) {
98b27036
AA
668 /*
669 * If the buffer is fully or partially
670 * within the initialized size, do an
671 * actual read. Otherwise, simply zero
672 * the buffer.
673 */
674 read_lock_irqsave(&ni->size_lock,
675 flags);
676 initialized_size = ni->initialized_size;
677 read_unlock_irqrestore(&ni->size_lock,
678 flags);
679 if (bh_pos < initialized_size) {
680 ntfs_submit_bh_for_read(bh);
681 *wait_bh++ = bh;
682 } else {
eebd2aa3
CL
683 zero_user(page, bh_offset(bh),
684 blocksize);
98b27036
AA
685 set_buffer_uptodate(bh);
686 }
687 }
688 continue;
689 }
690 /* We allocated the buffer. */
691 unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
692 /*
693 * If the buffer is fully outside the write, zero it,
694 * set it uptodate, and mark it dirty so it gets
695 * written out. If it is partially being written to,
696 * zero region surrounding the write but leave it to
697 * commit write to do anything else. Finally, if the
698 * buffer is fully being overwritten, do nothing.
699 */
700 if (bh_end <= pos || bh_pos >= end) {
701 if (!buffer_uptodate(bh)) {
eebd2aa3
CL
702 zero_user(page, bh_offset(bh),
703 blocksize);
98b27036
AA
704 set_buffer_uptodate(bh);
705 }
706 mark_buffer_dirty(bh);
707 continue;
708 }
709 set_buffer_new(bh);
710 if (!buffer_uptodate(bh) &&
711 (bh_pos < pos || bh_end > end)) {
712 u8 *kaddr;
713 unsigned pofs;
714
715 kaddr = kmap_atomic(page, KM_USER0);
716 if (bh_pos < pos) {
717 pofs = bh_pos & ~PAGE_CACHE_MASK;
718 memset(kaddr + pofs, 0, pos - bh_pos);
719 }
720 if (bh_end > end) {
721 pofs = end & ~PAGE_CACHE_MASK;
722 memset(kaddr + pofs, 0, bh_end - end);
723 }
724 kunmap_atomic(kaddr, KM_USER0);
725 flush_dcache_page(page);
726 }
727 continue;
728 }
729 /*
730 * Slow path: this is the first buffer in the cluster. If it
731 * is outside allocated size and is not uptodate, zero it and
732 * set it uptodate.
733 */
734 read_lock_irqsave(&ni->size_lock, flags);
735 initialized_size = ni->allocated_size;
736 read_unlock_irqrestore(&ni->size_lock, flags);
737 if (bh_pos > initialized_size) {
738 if (PageUptodate(page)) {
739 if (!buffer_uptodate(bh))
740 set_buffer_uptodate(bh);
741 } else if (!buffer_uptodate(bh)) {
eebd2aa3 742 zero_user(page, bh_offset(bh), blocksize);
98b27036
AA
743 set_buffer_uptodate(bh);
744 }
745 continue;
746 }
c49c3111 747 is_retry = false;
98b27036
AA
748 if (!rl) {
749 down_read(&ni->runlist.lock);
750retry_remap:
751 rl = ni->runlist.rl;
752 }
753 if (likely(rl != NULL)) {
754 /* Seek to element containing target cluster. */
755 while (rl->length && rl[1].vcn <= bh_cpos)
756 rl++;
757 lcn = ntfs_rl_vcn_to_lcn(rl, bh_cpos);
758 if (likely(lcn >= 0)) {
759 /*
760 * Successful remap, setup the map cache and
761 * use that to deal with the buffer.
762 */
c49c3111 763 was_hole = false;
98b27036
AA
764 vcn = bh_cpos;
765 vcn_len = rl[1].vcn - vcn;
766 lcn_block = lcn << (vol->cluster_size_bits -
767 blocksize_bits);
d5aeaef3 768 cdelta = 0;
98b27036 769 /*
3aebf25b
AA
770 * If the number of remaining clusters touched
771 * by the write is smaller or equal to the
772 * number of cached clusters, unlock the
773 * runlist as the map cache will be used from
774 * now on.
98b27036
AA
775 */
776 if (likely(vcn + vcn_len >= cend)) {
777 if (rl_write_locked) {
778 up_write(&ni->runlist.lock);
c49c3111 779 rl_write_locked = false;
98b27036
AA
780 } else
781 up_read(&ni->runlist.lock);
782 rl = NULL;
783 }
784 goto map_buffer_cached;
785 }
786 } else
787 lcn = LCN_RL_NOT_MAPPED;
788 /*
789 * If it is not a hole and not out of bounds, the runlist is
790 * probably unmapped so try to map it now.
791 */
792 if (unlikely(lcn != LCN_HOLE && lcn != LCN_ENOENT)) {
793 if (likely(!is_retry && lcn == LCN_RL_NOT_MAPPED)) {
794 /* Attempt to map runlist. */
795 if (!rl_write_locked) {
796 /*
797 * We need the runlist locked for
798 * writing, so if it is locked for
799 * reading relock it now and retry in
800 * case it changed whilst we dropped
801 * the lock.
802 */
803 up_read(&ni->runlist.lock);
804 down_write(&ni->runlist.lock);
c49c3111 805 rl_write_locked = true;
98b27036
AA
806 goto retry_remap;
807 }
808 err = ntfs_map_runlist_nolock(ni, bh_cpos,
809 NULL);
810 if (likely(!err)) {
c49c3111 811 is_retry = true;
98b27036
AA
812 goto retry_remap;
813 }
814 /*
815 * If @vcn is out of bounds, pretend @lcn is
816 * LCN_ENOENT. As long as the buffer is out
817 * of bounds this will work fine.
818 */
819 if (err == -ENOENT) {
820 lcn = LCN_ENOENT;
821 err = 0;
822 goto rl_not_mapped_enoent;
823 }
824 } else
825 err = -EIO;
826 /* Failed to map the buffer, even after retrying. */
827 bh->b_blocknr = -1;
828 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
829 "attribute type 0x%x, vcn 0x%llx, "
830 "vcn offset 0x%x, because its "
831 "location on disk could not be "
832 "determined%s (error code %i).",
833 ni->mft_no, ni->type,
834 (unsigned long long)bh_cpos,
835 (unsigned)bh_pos &
836 vol->cluster_size_mask,
837 is_retry ? " even after retrying" : "",
838 err);
839 break;
840 }
841rl_not_mapped_enoent:
842 /*
843 * The buffer is in a hole or out of bounds. We need to fill
844 * the hole, unless the buffer is in a cluster which is not
845 * touched by the write, in which case we just leave the buffer
846 * unmapped. This can only happen when the cluster size is
847 * less than the page cache size.
848 */
849 if (unlikely(vol->cluster_size < PAGE_CACHE_SIZE)) {
850 bh_cend = (bh_end + vol->cluster_size - 1) >>
851 vol->cluster_size_bits;
852 if ((bh_cend <= cpos || bh_cpos >= cend)) {
853 bh->b_blocknr = -1;
854 /*
855 * If the buffer is uptodate we skip it. If it
856 * is not but the page is uptodate, we can set
857 * the buffer uptodate. If the page is not
858 * uptodate, we can clear the buffer and set it
859 * uptodate. Whether this is worthwhile is
860 * debatable and this could be removed.
861 */
862 if (PageUptodate(page)) {
863 if (!buffer_uptodate(bh))
864 set_buffer_uptodate(bh);
865 } else if (!buffer_uptodate(bh)) {
eebd2aa3
CL
866 zero_user(page, bh_offset(bh),
867 blocksize);
98b27036
AA
868 set_buffer_uptodate(bh);
869 }
870 continue;
871 }
872 }
873 /*
874 * Out of bounds buffer is invalid if it was not really out of
875 * bounds.
876 */
877 BUG_ON(lcn != LCN_HOLE);
878 /*
879 * We need the runlist locked for writing, so if it is locked
880 * for reading relock it now and retry in case it changed
881 * whilst we dropped the lock.
882 */
883 BUG_ON(!rl);
884 if (!rl_write_locked) {
885 up_read(&ni->runlist.lock);
886 down_write(&ni->runlist.lock);
c49c3111 887 rl_write_locked = true;
98b27036
AA
888 goto retry_remap;
889 }
890 /* Find the previous last allocated cluster. */
891 BUG_ON(rl->lcn != LCN_HOLE);
892 lcn = -1;
893 rl2 = rl;
894 while (--rl2 >= ni->runlist.rl) {
895 if (rl2->lcn >= 0) {
896 lcn = rl2->lcn + rl2->length;
897 break;
898 }
899 }
900 rl2 = ntfs_cluster_alloc(vol, bh_cpos, 1, lcn, DATA_ZONE,
c49c3111 901 false);
98b27036
AA
902 if (IS_ERR(rl2)) {
903 err = PTR_ERR(rl2);
904 ntfs_debug("Failed to allocate cluster, error code %i.",
905 err);
906 break;
907 }
908 lcn = rl2->lcn;
909 rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
910 if (IS_ERR(rl)) {
911 err = PTR_ERR(rl);
912 if (err != -ENOMEM)
913 err = -EIO;
914 if (ntfs_cluster_free_from_rl(vol, rl2)) {
915 ntfs_error(vol->sb, "Failed to release "
916 "allocated cluster in error "
917 "code path. Run chkdsk to "
918 "recover the lost cluster.");
919 NVolSetErrors(vol);
920 }
921 ntfs_free(rl2);
922 break;
923 }
924 ni->runlist.rl = rl;
925 status.runlist_merged = 1;
bb8047d3
AA
926 ntfs_debug("Allocated cluster, lcn 0x%llx.",
927 (unsigned long long)lcn);
98b27036
AA
928 /* Map and lock the mft record and get the attribute record. */
929 if (!NInoAttr(ni))
930 base_ni = ni;
931 else
932 base_ni = ni->ext.base_ntfs_ino;
933 m = map_mft_record(base_ni);
934 if (IS_ERR(m)) {
935 err = PTR_ERR(m);
936 break;
937 }
938 ctx = ntfs_attr_get_search_ctx(base_ni, m);
939 if (unlikely(!ctx)) {
940 err = -ENOMEM;
941 unmap_mft_record(base_ni);
942 break;
943 }
944 status.mft_attr_mapped = 1;
945 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
946 CASE_SENSITIVE, bh_cpos, NULL, 0, ctx);
947 if (unlikely(err)) {
948 if (err == -ENOENT)
949 err = -EIO;
950 break;
951 }
952 m = ctx->mrec;
953 a = ctx->attr;
954 /*
955 * Find the runlist element with which the attribute extent
956 * starts. Note, we cannot use the _attr_ version because we
957 * have mapped the mft record. That is ok because we know the
958 * runlist fragment must be mapped already to have ever gotten
959 * here, so we can just use the _rl_ version.
960 */
961 vcn = sle64_to_cpu(a->data.non_resident.lowest_vcn);
962 rl2 = ntfs_rl_find_vcn_nolock(rl, vcn);
963 BUG_ON(!rl2);
964 BUG_ON(!rl2->length);
965 BUG_ON(rl2->lcn < LCN_HOLE);
966 highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
967 /*
968 * If @highest_vcn is zero, calculate the real highest_vcn
969 * (which can really be zero).
970 */
971 if (!highest_vcn)
972 highest_vcn = (sle64_to_cpu(
973 a->data.non_resident.allocated_size) >>
974 vol->cluster_size_bits) - 1;
975 /*
976 * Determine the size of the mapping pairs array for the new
977 * extent, i.e. the old extent with the hole filled.
978 */
979 mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, vcn,
980 highest_vcn);
981 if (unlikely(mp_size <= 0)) {
982 if (!(err = mp_size))
983 err = -EIO;
984 ntfs_debug("Failed to get size for mapping pairs "
985 "array, error code %i.", err);
986 break;
987 }
988 /*
989 * Resize the attribute record to fit the new mapping pairs
990 * array.
991 */
992 attr_rec_len = le32_to_cpu(a->length);
993 err = ntfs_attr_record_resize(m, a, mp_size + le16_to_cpu(
994 a->data.non_resident.mapping_pairs_offset));
995 if (unlikely(err)) {
996 BUG_ON(err != -ENOSPC);
997 // TODO: Deal with this by using the current attribute
998 // and fill it with as much of the mapping pairs
999 // array as possible. Then loop over each attribute
1000 // extent rewriting the mapping pairs arrays as we go
1001 // along and if when we reach the end we have not
1002 // enough space, try to resize the last attribute
1003 // extent and if even that fails, add a new attribute
1004 // extent.
1005 // We could also try to resize at each step in the hope
1006 // that we will not need to rewrite every single extent.
1007 // Note, we may need to decompress some extents to fill
1008 // the runlist as we are walking the extents...
1009 ntfs_error(vol->sb, "Not enough space in the mft "
1010 "record for the extended attribute "
1011 "record. This case is not "
1012 "implemented yet.");
1013 err = -EOPNOTSUPP;
1014 break ;
1015 }
1016 status.mp_rebuilt = 1;
1017 /*
1018 * Generate the mapping pairs array directly into the attribute
1019 * record.
1020 */
1021 err = ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
1022 a->data.non_resident.mapping_pairs_offset),
1023 mp_size, rl2, vcn, highest_vcn, NULL);
1024 if (unlikely(err)) {
1025 ntfs_error(vol->sb, "Cannot fill hole in inode 0x%lx, "
1026 "attribute type 0x%x, because building "
1027 "the mapping pairs failed with error "
1028 "code %i.", vi->i_ino,
1029 (unsigned)le32_to_cpu(ni->type), err);
1030 err = -EIO;
1031 break;
1032 }
1033 /* Update the highest_vcn but only if it was not set. */
1034 if (unlikely(!a->data.non_resident.highest_vcn))
1035 a->data.non_resident.highest_vcn =
1036 cpu_to_sle64(highest_vcn);
1037 /*
1038 * If the attribute is sparse/compressed, update the compressed
1039 * size in the ntfs_inode structure and the attribute record.
1040 */
1041 if (likely(NInoSparse(ni) || NInoCompressed(ni))) {
1042 /*
1043 * If we are not in the first attribute extent, switch
1044 * to it, but first ensure the changes will make it to
1045 * disk later.
1046 */
1047 if (a->data.non_resident.lowest_vcn) {
1048 flush_dcache_mft_record_page(ctx->ntfs_ino);
1049 mark_mft_record_dirty(ctx->ntfs_ino);
1050 ntfs_attr_reinit_search_ctx(ctx);
1051 err = ntfs_attr_lookup(ni->type, ni->name,
1052 ni->name_len, CASE_SENSITIVE,
1053 0, NULL, 0, ctx);
1054 if (unlikely(err)) {
1055 status.attr_switched = 1;
1056 break;
1057 }
1058 /* @m is not used any more so do not set it. */
1059 a = ctx->attr;
1060 }
1061 write_lock_irqsave(&ni->size_lock, flags);
1062 ni->itype.compressed.size += vol->cluster_size;
1063 a->data.non_resident.compressed_size =
1064 cpu_to_sle64(ni->itype.compressed.size);
1065 write_unlock_irqrestore(&ni->size_lock, flags);
1066 }
1067 /* Ensure the changes make it to disk. */
1068 flush_dcache_mft_record_page(ctx->ntfs_ino);
1069 mark_mft_record_dirty(ctx->ntfs_ino);
1070 ntfs_attr_put_search_ctx(ctx);
1071 unmap_mft_record(base_ni);
1072 /* Successfully filled the hole. */
1073 status.runlist_merged = 0;
1074 status.mft_attr_mapped = 0;
1075 status.mp_rebuilt = 0;
1076 /* Setup the map cache and use that to deal with the buffer. */
c49c3111 1077 was_hole = true;
98b27036
AA
1078 vcn = bh_cpos;
1079 vcn_len = 1;
1080 lcn_block = lcn << (vol->cluster_size_bits - blocksize_bits);
1081 cdelta = 0;
1082 /*
1083 * If the number of remaining clusters in the @pages is smaller
1084 * or equal to the number of cached clusters, unlock the
1085 * runlist as the map cache will be used from now on.
1086 */
1087 if (likely(vcn + vcn_len >= cend)) {
1088 up_write(&ni->runlist.lock);
c49c3111 1089 rl_write_locked = false;
98b27036
AA
1090 rl = NULL;
1091 }
1092 goto map_buffer_cached;
1093 } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
1094 /* If there are no errors, do the next page. */
1095 if (likely(!err && ++u < nr_pages))
1096 goto do_next_page;
1097 /* If there are no errors, release the runlist lock if we took it. */
1098 if (likely(!err)) {
1099 if (unlikely(rl_write_locked)) {
1100 up_write(&ni->runlist.lock);
c49c3111 1101 rl_write_locked = false;
98b27036
AA
1102 } else if (unlikely(rl))
1103 up_read(&ni->runlist.lock);
1104 rl = NULL;
1105 }
1106 /* If we issued read requests, let them complete. */
1107 read_lock_irqsave(&ni->size_lock, flags);
1108 initialized_size = ni->initialized_size;
1109 read_unlock_irqrestore(&ni->size_lock, flags);
1110 while (wait_bh > wait) {
1111 bh = *--wait_bh;
1112 wait_on_buffer(bh);
1113 if (likely(buffer_uptodate(bh))) {
1114 page = bh->b_page;
1115 bh_pos = ((s64)page->index << PAGE_CACHE_SHIFT) +
1116 bh_offset(bh);
1117 /*
1118 * If the buffer overflows the initialized size, need
1119 * to zero the overflowing region.
1120 */
1121 if (unlikely(bh_pos + blocksize > initialized_size)) {
98b27036
AA
1122 int ofs = 0;
1123
1124 if (likely(bh_pos < initialized_size))
1125 ofs = initialized_size - bh_pos;
eebd2aa3
CL
1126 zero_user_segment(page, bh_offset(bh) + ofs,
1127 blocksize);
98b27036
AA
1128 }
1129 } else /* if (unlikely(!buffer_uptodate(bh))) */
1130 err = -EIO;
1131 }
1132 if (likely(!err)) {
1133 /* Clear buffer_new on all buffers. */
1134 u = 0;
1135 do {
1136 bh = head = page_buffers(pages[u]);
1137 do {
1138 if (buffer_new(bh))
1139 clear_buffer_new(bh);
1140 } while ((bh = bh->b_this_page) != head);
1141 } while (++u < nr_pages);
1142 ntfs_debug("Done.");
1143 return err;
1144 }
1145 if (status.attr_switched) {
1146 /* Get back to the attribute extent we modified. */
1147 ntfs_attr_reinit_search_ctx(ctx);
1148 if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1149 CASE_SENSITIVE, bh_cpos, NULL, 0, ctx)) {
1150 ntfs_error(vol->sb, "Failed to find required "
1151 "attribute extent of attribute in "
1152 "error code path. Run chkdsk to "
1153 "recover.");
1154 write_lock_irqsave(&ni->size_lock, flags);
1155 ni->itype.compressed.size += vol->cluster_size;
1156 write_unlock_irqrestore(&ni->size_lock, flags);
1157 flush_dcache_mft_record_page(ctx->ntfs_ino);
1158 mark_mft_record_dirty(ctx->ntfs_ino);
1159 /*
1160 * The only thing that is now wrong is the compressed
1161 * size of the base attribute extent which chkdsk
1162 * should be able to fix.
1163 */
1164 NVolSetErrors(vol);
1165 } else {
1166 m = ctx->mrec;
1167 a = ctx->attr;
1168 status.attr_switched = 0;
1169 }
1170 }
1171 /*
1172 * If the runlist has been modified, need to restore it by punching a
1173 * hole into it and we then need to deallocate the on-disk cluster as
1174 * well. Note, we only modify the runlist if we are able to generate a
1175 * new mapping pairs array, i.e. only when the mapped attribute extent
1176 * is not switched.
1177 */
1178 if (status.runlist_merged && !status.attr_switched) {
1179 BUG_ON(!rl_write_locked);
1180 /* Make the file cluster we allocated sparse in the runlist. */
1181 if (ntfs_rl_punch_nolock(vol, &ni->runlist, bh_cpos, 1)) {
1182 ntfs_error(vol->sb, "Failed to punch hole into "
1183 "attribute runlist in error code "
1184 "path. Run chkdsk to recover the "
1185 "lost cluster.");
98b27036
AA
1186 NVolSetErrors(vol);
1187 } else /* if (success) */ {
1188 status.runlist_merged = 0;
1189 /*
1190 * Deallocate the on-disk cluster we allocated but only
1191 * if we succeeded in punching its vcn out of the
1192 * runlist.
1193 */
1194 down_write(&vol->lcnbmp_lock);
1195 if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
1196 ntfs_error(vol->sb, "Failed to release "
1197 "allocated cluster in error "
1198 "code path. Run chkdsk to "
1199 "recover the lost cluster.");
1200 NVolSetErrors(vol);
1201 }
1202 up_write(&vol->lcnbmp_lock);
1203 }
1204 }
1205 /*
1206 * Resize the attribute record to its old size and rebuild the mapping
1207 * pairs array. Note, we only can do this if the runlist has been
1208 * restored to its old state which also implies that the mapped
1209 * attribute extent is not switched.
1210 */
1211 if (status.mp_rebuilt && !status.runlist_merged) {
1212 if (ntfs_attr_record_resize(m, a, attr_rec_len)) {
1213 ntfs_error(vol->sb, "Failed to restore attribute "
1214 "record in error code path. Run "
1215 "chkdsk to recover.");
98b27036
AA
1216 NVolSetErrors(vol);
1217 } else /* if (success) */ {
1218 if (ntfs_mapping_pairs_build(vol, (u8*)a +
1219 le16_to_cpu(a->data.non_resident.
1220 mapping_pairs_offset), attr_rec_len -
1221 le16_to_cpu(a->data.non_resident.
1222 mapping_pairs_offset), ni->runlist.rl,
1223 vcn, highest_vcn, NULL)) {
1224 ntfs_error(vol->sb, "Failed to restore "
1225 "mapping pairs array in error "
1226 "code path. Run chkdsk to "
1227 "recover.");
98b27036
AA
1228 NVolSetErrors(vol);
1229 }
1230 flush_dcache_mft_record_page(ctx->ntfs_ino);
1231 mark_mft_record_dirty(ctx->ntfs_ino);
1232 }
1233 }
1234 /* Release the mft record and the attribute. */
1235 if (status.mft_attr_mapped) {
1236 ntfs_attr_put_search_ctx(ctx);
1237 unmap_mft_record(base_ni);
1238 }
1239 /* Release the runlist lock. */
1240 if (rl_write_locked)
1241 up_write(&ni->runlist.lock);
1242 else if (rl)
1243 up_read(&ni->runlist.lock);
1244 /*
1245 * Zero out any newly allocated blocks to avoid exposing stale data.
1246 * If BH_New is set, we know that the block was newly allocated above
1247 * and that it has not been fully zeroed and marked dirty yet.
1248 */
1249 nr_pages = u;
1250 u = 0;
1251 end = bh_cpos << vol->cluster_size_bits;
1252 do {
1253 page = pages[u];
1254 bh = head = page_buffers(page);
1255 do {
1256 if (u == nr_pages &&
1257 ((s64)page->index << PAGE_CACHE_SHIFT) +
1258 bh_offset(bh) >= end)
1259 break;
1260 if (!buffer_new(bh))
1261 continue;
1262 clear_buffer_new(bh);
1263 if (!buffer_uptodate(bh)) {
1264 if (PageUptodate(page))
1265 set_buffer_uptodate(bh);
1266 else {
eebd2aa3
CL
1267 zero_user(page, bh_offset(bh),
1268 blocksize);
98b27036
AA
1269 set_buffer_uptodate(bh);
1270 }
1271 }
1272 mark_buffer_dirty(bh);
1273 } while ((bh = bh->b_this_page) != head);
1274 } while (++u <= nr_pages);
1275 ntfs_error(vol->sb, "Failed. Returning error code %i.", err);
1276 return err;
1277}
1278
1279/*
1280 * Copy as much as we can into the pages and return the number of bytes which
af901ca1 1281 * were successfully copied. If a fault is encountered then clear the pages
98b27036
AA
1282 * out to (ofs + bytes) and return the number of bytes which were copied.
1283 */
1284static inline size_t ntfs_copy_from_user(struct page **pages,
1285 unsigned nr_pages, unsigned ofs, const char __user *buf,
1286 size_t bytes)
1287{
1288 struct page **last_page = pages + nr_pages;
bfab36e8 1289 char *addr;
98b27036
AA
1290 size_t total = 0;
1291 unsigned len;
1292 int left;
1293
1294 do {
1295 len = PAGE_CACHE_SIZE - ofs;
1296 if (len > bytes)
1297 len = bytes;
bfab36e8
AA
1298 addr = kmap_atomic(*pages, KM_USER0);
1299 left = __copy_from_user_inatomic(addr + ofs, buf, len);
1300 kunmap_atomic(addr, KM_USER0);
98b27036
AA
1301 if (unlikely(left)) {
1302 /* Do it the slow way. */
bfab36e8
AA
1303 addr = kmap(*pages);
1304 left = __copy_from_user(addr + ofs, buf, len);
98b27036
AA
1305 kunmap(*pages);
1306 if (unlikely(left))
1307 goto err_out;
1308 }
1309 total += len;
1310 bytes -= len;
1311 if (!bytes)
1312 break;
1313 buf += len;
1314 ofs = 0;
1315 } while (++pages < last_page);
1316out:
1317 return total;
1318err_out:
1319 total += len - left;
1320 /* Zero the rest of the target like __copy_from_user(). */
1321 while (++pages < last_page) {
1322 bytes -= len;
1323 if (!bytes)
1324 break;
1325 len = PAGE_CACHE_SIZE;
1326 if (len > bytes)
1327 len = bytes;
eebd2aa3 1328 zero_user(*pages, 0, len);
98b27036
AA
1329 }
1330 goto out;
1331}
1332
01408c49 1333static size_t __ntfs_copy_from_user_iovec_inatomic(char *vaddr,
98b27036
AA
1334 const struct iovec *iov, size_t iov_ofs, size_t bytes)
1335{
1336 size_t total = 0;
1337
1338 while (1) {
1339 const char __user *buf = iov->iov_base + iov_ofs;
1340 unsigned len;
1341 size_t left;
1342
1343 len = iov->iov_len - iov_ofs;
1344 if (len > bytes)
1345 len = bytes;
1346 left = __copy_from_user_inatomic(vaddr, buf, len);
1347 total += len;
1348 bytes -= len;
1349 vaddr += len;
1350 if (unlikely(left)) {
98b27036
AA
1351 total -= left;
1352 break;
1353 }
1354 if (!bytes)
1355 break;
1356 iov++;
1357 iov_ofs = 0;
1358 }
1359 return total;
1360}
1361
1362static inline void ntfs_set_next_iovec(const struct iovec **iovp,
1363 size_t *iov_ofsp, size_t bytes)
1364{
1365 const struct iovec *iov = *iovp;
1366 size_t iov_ofs = *iov_ofsp;
1367
1368 while (bytes) {
1369 unsigned len;
1370
1371 len = iov->iov_len - iov_ofs;
1372 if (len > bytes)
1373 len = bytes;
1374 bytes -= len;
1375 iov_ofs += len;
1376 if (iov->iov_len == iov_ofs) {
1377 iov++;
1378 iov_ofs = 0;
1379 }
1380 }
1381 *iovp = iov;
1382 *iov_ofsp = iov_ofs;
1383}
1384
1385/*
1386 * This has the same side-effects and return value as ntfs_copy_from_user().
1387 * The difference is that on a fault we need to memset the remainder of the
1388 * pages (out to offset + bytes), to emulate ntfs_copy_from_user()'s
1389 * single-segment behaviour.
1390 *
01408c49
N
1391 * We call the same helper (__ntfs_copy_from_user_iovec_inatomic()) both
1392 * when atomic and when not atomic. This is ok because
1393 * __ntfs_copy_from_user_iovec_inatomic() calls __copy_from_user_inatomic()
1394 * and it is ok to call this when non-atomic.
1395 * Infact, the only difference between __copy_from_user_inatomic() and
1396 * __copy_from_user() is that the latter calls might_sleep() and the former
1397 * should not zero the tail of the buffer on error. And on many
98b27036
AA
1398 * architectures __copy_from_user_inatomic() is just defined to
1399 * __copy_from_user() so it makes no difference at all on those architectures.
1400 */
1401static inline size_t ntfs_copy_from_user_iovec(struct page **pages,
1402 unsigned nr_pages, unsigned ofs, const struct iovec **iov,
1403 size_t *iov_ofs, size_t bytes)
1404{
1405 struct page **last_page = pages + nr_pages;
bfab36e8 1406 char *addr;
98b27036
AA
1407 size_t copied, len, total = 0;
1408
1409 do {
1410 len = PAGE_CACHE_SIZE - ofs;
1411 if (len > bytes)
1412 len = bytes;
bfab36e8
AA
1413 addr = kmap_atomic(*pages, KM_USER0);
1414 copied = __ntfs_copy_from_user_iovec_inatomic(addr + ofs,
98b27036 1415 *iov, *iov_ofs, len);
bfab36e8 1416 kunmap_atomic(addr, KM_USER0);
98b27036
AA
1417 if (unlikely(copied != len)) {
1418 /* Do it the slow way. */
bfab36e8
AA
1419 addr = kmap(*pages);
1420 copied = __ntfs_copy_from_user_iovec_inatomic(addr + ofs,
98b27036 1421 *iov, *iov_ofs, len);
01408c49
N
1422 /*
1423 * Zero the rest of the target like __copy_from_user().
1424 */
bfab36e8 1425 memset(addr + ofs + copied, 0, len - copied);
98b27036
AA
1426 kunmap(*pages);
1427 if (unlikely(copied != len))
1428 goto err_out;
1429 }
1430 total += len;
1431 bytes -= len;
1432 if (!bytes)
1433 break;
1434 ntfs_set_next_iovec(iov, iov_ofs, len);
1435 ofs = 0;
1436 } while (++pages < last_page);
1437out:
1438 return total;
1439err_out:
1440 total += copied;
1441 /* Zero the rest of the target like __copy_from_user(). */
1442 while (++pages < last_page) {
1443 bytes -= len;
1444 if (!bytes)
1445 break;
1446 len = PAGE_CACHE_SIZE;
1447 if (len > bytes)
1448 len = bytes;
eebd2aa3 1449 zero_user(*pages, 0, len);
98b27036
AA
1450 }
1451 goto out;
1452}
1453
1454static inline void ntfs_flush_dcache_pages(struct page **pages,
1455 unsigned nr_pages)
1456{
1457 BUG_ON(!nr_pages);
f893afbe
AA
1458 /*
1459 * Warning: Do not do the decrement at the same time as the call to
1460 * flush_dcache_page() because it is a NULL macro on i386 and hence the
1461 * decrement never happens so the loop never terminates.
1462 */
98b27036 1463 do {
f893afbe 1464 --nr_pages;
98b27036 1465 flush_dcache_page(pages[nr_pages]);
f893afbe 1466 } while (nr_pages > 0);
98b27036
AA
1467}
1468
1469/**
1470 * ntfs_commit_pages_after_non_resident_write - commit the received data
1471 * @pages: array of destination pages
1472 * @nr_pages: number of pages in @pages
1473 * @pos: byte position in file at which the write begins
1474 * @bytes: number of bytes to be written
1475 *
1476 * See description of ntfs_commit_pages_after_write(), below.
1477 */
1478static inline int ntfs_commit_pages_after_non_resident_write(
1479 struct page **pages, const unsigned nr_pages,
1480 s64 pos, size_t bytes)
1481{
1482 s64 end, initialized_size;
1483 struct inode *vi;
1484 ntfs_inode *ni, *base_ni;
1485 struct buffer_head *bh, *head;
1486 ntfs_attr_search_ctx *ctx;
1487 MFT_RECORD *m;
1488 ATTR_RECORD *a;
1489 unsigned long flags;
1490 unsigned blocksize, u;
1491 int err;
1492
1493 vi = pages[0]->mapping->host;
1494 ni = NTFS_I(vi);
78af34f0 1495 blocksize = vi->i_sb->s_blocksize;
98b27036
AA
1496 end = pos + bytes;
1497 u = 0;
1498 do {
1499 s64 bh_pos;
1500 struct page *page;
c49c3111 1501 bool partial;
98b27036
AA
1502
1503 page = pages[u];
1504 bh_pos = (s64)page->index << PAGE_CACHE_SHIFT;
1505 bh = head = page_buffers(page);
c49c3111 1506 partial = false;
98b27036
AA
1507 do {
1508 s64 bh_end;
1509
1510 bh_end = bh_pos + blocksize;
1511 if (bh_end <= pos || bh_pos >= end) {
1512 if (!buffer_uptodate(bh))
c49c3111 1513 partial = true;
98b27036
AA
1514 } else {
1515 set_buffer_uptodate(bh);
1516 mark_buffer_dirty(bh);
1517 }
1518 } while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
1519 /*
1520 * If all buffers are now uptodate but the page is not, set the
1521 * page uptodate.
1522 */
1523 if (!partial && !PageUptodate(page))
1524 SetPageUptodate(page);
1525 } while (++u < nr_pages);
1526 /*
1527 * Finally, if we do not need to update initialized_size or i_size we
1528 * are finished.
1529 */
1530 read_lock_irqsave(&ni->size_lock, flags);
1531 initialized_size = ni->initialized_size;
1532 read_unlock_irqrestore(&ni->size_lock, flags);
1533 if (end <= initialized_size) {
1534 ntfs_debug("Done.");
1535 return 0;
1536 }
1537 /*
1538 * Update initialized_size/i_size as appropriate, both in the inode and
1539 * the mft record.
1540 */
1541 if (!NInoAttr(ni))
1542 base_ni = ni;
1543 else
1544 base_ni = ni->ext.base_ntfs_ino;
1545 /* Map, pin, and lock the mft record. */
1546 m = map_mft_record(base_ni);
1547 if (IS_ERR(m)) {
1548 err = PTR_ERR(m);
1549 m = NULL;
1550 ctx = NULL;
1551 goto err_out;
1552 }
1553 BUG_ON(!NInoNonResident(ni));
1554 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1555 if (unlikely(!ctx)) {
1556 err = -ENOMEM;
1557 goto err_out;
1558 }
1559 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1560 CASE_SENSITIVE, 0, NULL, 0, ctx);
1561 if (unlikely(err)) {
1562 if (err == -ENOENT)
1563 err = -EIO;
1564 goto err_out;
1565 }
1566 a = ctx->attr;
1567 BUG_ON(!a->non_resident);
1568 write_lock_irqsave(&ni->size_lock, flags);
1569 BUG_ON(end > ni->allocated_size);
1570 ni->initialized_size = end;
1571 a->data.non_resident.initialized_size = cpu_to_sle64(end);
1572 if (end > i_size_read(vi)) {
1573 i_size_write(vi, end);
1574 a->data.non_resident.data_size =
1575 a->data.non_resident.initialized_size;
1576 }
1577 write_unlock_irqrestore(&ni->size_lock, flags);
1578 /* Mark the mft record dirty, so it gets written back. */
1579 flush_dcache_mft_record_page(ctx->ntfs_ino);
1580 mark_mft_record_dirty(ctx->ntfs_ino);
1581 ntfs_attr_put_search_ctx(ctx);
1582 unmap_mft_record(base_ni);
1583 ntfs_debug("Done.");
1584 return 0;
1585err_out:
1586 if (ctx)
1587 ntfs_attr_put_search_ctx(ctx);
1588 if (m)
1589 unmap_mft_record(base_ni);
1590 ntfs_error(vi->i_sb, "Failed to update initialized_size/i_size (error "
1591 "code %i).", err);
f95c4018 1592 if (err != -ENOMEM)
98b27036 1593 NVolSetErrors(ni->vol);
98b27036
AA
1594 return err;
1595}
1596
1597/**
1598 * ntfs_commit_pages_after_write - commit the received data
1599 * @pages: array of destination pages
1600 * @nr_pages: number of pages in @pages
1601 * @pos: byte position in file at which the write begins
1602 * @bytes: number of bytes to be written
1603 *
1b1dcc1b 1604 * This is called from ntfs_file_buffered_write() with i_mutex held on the inode
98b27036
AA
1605 * (@pages[0]->mapping->host). There are @nr_pages pages in @pages which are
1606 * locked but not kmap()ped. The source data has already been copied into the
1607 * @page. ntfs_prepare_pages_for_non_resident_write() has been called before
1608 * the data was copied (for non-resident attributes only) and it returned
1609 * success.
1610 *
1611 * Need to set uptodate and mark dirty all buffers within the boundary of the
1612 * write. If all buffers in a page are uptodate we set the page uptodate, too.
1613 *
1614 * Setting the buffers dirty ensures that they get written out later when
1615 * ntfs_writepage() is invoked by the VM.
1616 *
1617 * Finally, we need to update i_size and initialized_size as appropriate both
1618 * in the inode and the mft record.
1619 *
1620 * This is modelled after fs/buffer.c::generic_commit_write(), which marks
1621 * buffers uptodate and dirty, sets the page uptodate if all buffers in the
1622 * page are uptodate, and updates i_size if the end of io is beyond i_size. In
1623 * that case, it also marks the inode dirty.
1624 *
1625 * If things have gone as outlined in
1626 * ntfs_prepare_pages_for_non_resident_write(), we do not need to do any page
1627 * content modifications here for non-resident attributes. For resident
1628 * attributes we need to do the uptodate bringing here which we combine with
1629 * the copying into the mft record which means we save one atomic kmap.
1630 *
1631 * Return 0 on success or -errno on error.
1632 */
1633static int ntfs_commit_pages_after_write(struct page **pages,
1634 const unsigned nr_pages, s64 pos, size_t bytes)
1635{
1636 s64 end, initialized_size;
1637 loff_t i_size;
1638 struct inode *vi;
1639 ntfs_inode *ni, *base_ni;
1640 struct page *page;
1641 ntfs_attr_search_ctx *ctx;
1642 MFT_RECORD *m;
1643 ATTR_RECORD *a;
1644 char *kattr, *kaddr;
1645 unsigned long flags;
1646 u32 attr_len;
1647 int err;
1648
1649 BUG_ON(!nr_pages);
1650 BUG_ON(!pages);
1651 page = pages[0];
1652 BUG_ON(!page);
1653 vi = page->mapping->host;
1654 ni = NTFS_I(vi);
1655 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
d04bd1fb 1656 "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
98b27036
AA
1657 vi->i_ino, ni->type, page->index, nr_pages,
1658 (long long)pos, bytes);
1659 if (NInoNonResident(ni))
1660 return ntfs_commit_pages_after_non_resident_write(pages,
1661 nr_pages, pos, bytes);
1662 BUG_ON(nr_pages > 1);
1663 /*
1664 * Attribute is resident, implying it is not compressed, encrypted, or
1665 * sparse.
1666 */
1667 if (!NInoAttr(ni))
1668 base_ni = ni;
1669 else
1670 base_ni = ni->ext.base_ntfs_ino;
1671 BUG_ON(NInoNonResident(ni));
1672 /* Map, pin, and lock the mft record. */
1673 m = map_mft_record(base_ni);
1674 if (IS_ERR(m)) {
1675 err = PTR_ERR(m);
1676 m = NULL;
1677 ctx = NULL;
1678 goto err_out;
1679 }
1680 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1681 if (unlikely(!ctx)) {
1682 err = -ENOMEM;
1683 goto err_out;
1684 }
1685 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1686 CASE_SENSITIVE, 0, NULL, 0, ctx);
1687 if (unlikely(err)) {
1688 if (err == -ENOENT)
1689 err = -EIO;
1690 goto err_out;
1691 }
1692 a = ctx->attr;
1693 BUG_ON(a->non_resident);
1694 /* The total length of the attribute value. */
1695 attr_len = le32_to_cpu(a->data.resident.value_length);
1696 i_size = i_size_read(vi);
1697 BUG_ON(attr_len != i_size);
1698 BUG_ON(pos > attr_len);
1699 end = pos + bytes;
1700 BUG_ON(end > le32_to_cpu(a->length) -
1701 le16_to_cpu(a->data.resident.value_offset));
1702 kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
1703 kaddr = kmap_atomic(page, KM_USER0);
1704 /* Copy the received data from the page to the mft record. */
1705 memcpy(kattr + pos, kaddr + pos, bytes);
1706 /* Update the attribute length if necessary. */
1707 if (end > attr_len) {
1708 attr_len = end;
1709 a->data.resident.value_length = cpu_to_le32(attr_len);
1710 }
1711 /*
1712 * If the page is not uptodate, bring the out of bounds area(s)
1713 * uptodate by copying data from the mft record to the page.
1714 */
1715 if (!PageUptodate(page)) {
1716 if (pos > 0)
1717 memcpy(kaddr, kattr, pos);
1718 if (end < attr_len)
1719 memcpy(kaddr + end, kattr + end, attr_len - end);
1720 /* Zero the region outside the end of the attribute value. */
1721 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1722 flush_dcache_page(page);
1723 SetPageUptodate(page);
1724 }
1725 kunmap_atomic(kaddr, KM_USER0);
1726 /* Update initialized_size/i_size if necessary. */
1727 read_lock_irqsave(&ni->size_lock, flags);
1728 initialized_size = ni->initialized_size;
1729 BUG_ON(end > ni->allocated_size);
1730 read_unlock_irqrestore(&ni->size_lock, flags);
1731 BUG_ON(initialized_size != i_size);
1732 if (end > initialized_size) {
98b27036
AA
1733 write_lock_irqsave(&ni->size_lock, flags);
1734 ni->initialized_size = end;
1735 i_size_write(vi, end);
1736 write_unlock_irqrestore(&ni->size_lock, flags);
1737 }
1738 /* Mark the mft record dirty, so it gets written back. */
1739 flush_dcache_mft_record_page(ctx->ntfs_ino);
1740 mark_mft_record_dirty(ctx->ntfs_ino);
1741 ntfs_attr_put_search_ctx(ctx);
1742 unmap_mft_record(base_ni);
1743 ntfs_debug("Done.");
1744 return 0;
1745err_out:
1746 if (err == -ENOMEM) {
1747 ntfs_warning(vi->i_sb, "Error allocating memory required to "
1748 "commit the write.");
1749 if (PageUptodate(page)) {
1750 ntfs_warning(vi->i_sb, "Page is uptodate, setting "
1751 "dirty so the write will be retried "
1752 "later on by the VM.");
1753 /*
1754 * Put the page on mapping->dirty_pages, but leave its
1755 * buffers' dirty state as-is.
1756 */
1757 __set_page_dirty_nobuffers(page);
1758 err = 0;
1759 } else
1760 ntfs_error(vi->i_sb, "Page is not uptodate. Written "
1761 "data has been lost.");
1762 } else {
1763 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
1764 "with error %i.", err);
1765 NVolSetErrors(ni->vol);
98b27036
AA
1766 }
1767 if (ctx)
1768 ntfs_attr_put_search_ctx(ctx);
1769 if (m)
1770 unmap_mft_record(base_ni);
1771 return err;
1772}
1773
1774/**
1775 * ntfs_file_buffered_write -
1776 *
1b1dcc1b 1777 * Locking: The vfs is holding ->i_mutex on the inode.
98b27036
AA
1778 */
1779static ssize_t ntfs_file_buffered_write(struct kiocb *iocb,
1780 const struct iovec *iov, unsigned long nr_segs,
1781 loff_t pos, loff_t *ppos, size_t count)
1782{
1783 struct file *file = iocb->ki_filp;
1784 struct address_space *mapping = file->f_mapping;
1785 struct inode *vi = mapping->host;
1786 ntfs_inode *ni = NTFS_I(vi);
1787 ntfs_volume *vol = ni->vol;
1788 struct page *pages[NTFS_MAX_PAGES_PER_CLUSTER];
1789 struct page *cached_page = NULL;
1790 char __user *buf = NULL;
1791 s64 end, ll;
1792 VCN last_vcn;
1793 LCN lcn;
1794 unsigned long flags;
dda65b94 1795 size_t bytes, iov_ofs = 0; /* Offset in the current iovec. */
98b27036
AA
1796 ssize_t status, written;
1797 unsigned nr_pages;
1798 int err;
1799 struct pagevec lru_pvec;
1800
1801 ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
1802 "pos 0x%llx, count 0x%lx.",
1803 vi->i_ino, (unsigned)le32_to_cpu(ni->type),
1804 (unsigned long long)pos, (unsigned long)count);
1805 if (unlikely(!count))
1806 return 0;
1807 BUG_ON(NInoMstProtected(ni));
1808 /*
1809 * If the attribute is not an index root and it is encrypted or
1810 * compressed, we cannot write to it yet. Note we need to check for
1811 * AT_INDEX_ALLOCATION since this is the type of both directory and
1812 * index inodes.
1813 */
1814 if (ni->type != AT_INDEX_ALLOCATION) {
1815 /* If file is encrypted, deny access, just like NT4. */
1816 if (NInoEncrypted(ni)) {
7d0ffdb2
AA
1817 /*
1818 * Reminder for later: Encrypted files are _always_
1819 * non-resident so that the content can always be
1820 * encrypted.
1821 */
98b27036
AA
1822 ntfs_debug("Denying write access to encrypted file.");
1823 return -EACCES;
1824 }
1825 if (NInoCompressed(ni)) {
7d0ffdb2
AA
1826 /* Only unnamed $DATA attribute can be compressed. */
1827 BUG_ON(ni->type != AT_DATA);
1828 BUG_ON(ni->name_len);
1829 /*
1830 * Reminder for later: If resident, the data is not
1831 * actually compressed. Only on the switch to non-
1832 * resident does compression kick in. This is in
1833 * contrast to encrypted files (see above).
1834 */
98b27036
AA
1835 ntfs_error(vi->i_sb, "Writing to compressed files is "
1836 "not implemented yet. Sorry.");
1837 return -EOPNOTSUPP;
1838 }
1839 }
1840 /*
1841 * If a previous ntfs_truncate() failed, repeat it and abort if it
1842 * fails again.
1843 */
1844 if (unlikely(NInoTruncateFailed(ni))) {
1845 down_write(&vi->i_alloc_sem);
1846 err = ntfs_truncate(vi);
1847 up_write(&vi->i_alloc_sem);
1848 if (err || NInoTruncateFailed(ni)) {
1849 if (!err)
1850 err = -EIO;
1851 ntfs_error(vol->sb, "Cannot perform write to inode "
1852 "0x%lx, attribute type 0x%x, because "
1853 "ntfs_truncate() failed (error code "
1854 "%i).", vi->i_ino,
1855 (unsigned)le32_to_cpu(ni->type), err);
1856 return err;
1857 }
1858 }
1859 /* The first byte after the write. */
1860 end = pos + count;
1861 /*
1862 * If the write goes beyond the allocated size, extend the allocation
1863 * to cover the whole of the write, rounded up to the nearest cluster.
1864 */
1865 read_lock_irqsave(&ni->size_lock, flags);
1866 ll = ni->allocated_size;
1867 read_unlock_irqrestore(&ni->size_lock, flags);
1868 if (end > ll) {
1869 /* Extend the allocation without changing the data size. */
1870 ll = ntfs_attr_extend_allocation(ni, end, -1, pos);
1871 if (likely(ll >= 0)) {
1872 BUG_ON(pos >= ll);
1873 /* If the extension was partial truncate the write. */
1874 if (end > ll) {
1875 ntfs_debug("Truncating write to inode 0x%lx, "
1876 "attribute type 0x%x, because "
1877 "the allocation was only "
1878 "partially extended.",
1879 vi->i_ino, (unsigned)
1880 le32_to_cpu(ni->type));
1881 end = ll;
1882 count = ll - pos;
1883 }
1884 } else {
1885 err = ll;
1886 read_lock_irqsave(&ni->size_lock, flags);
1887 ll = ni->allocated_size;
1888 read_unlock_irqrestore(&ni->size_lock, flags);
1889 /* Perform a partial write if possible or fail. */
1890 if (pos < ll) {
1891 ntfs_debug("Truncating write to inode 0x%lx, "
1892 "attribute type 0x%x, because "
1893 "extending the allocation "
1894 "failed (error code %i).",
1895 vi->i_ino, (unsigned)
1896 le32_to_cpu(ni->type), err);
1897 end = ll;
1898 count = ll - pos;
1899 } else {
1900 ntfs_error(vol->sb, "Cannot perform write to "
1901 "inode 0x%lx, attribute type "
1902 "0x%x, because extending the "
1903 "allocation failed (error "
1904 "code %i).", vi->i_ino,
1905 (unsigned)
1906 le32_to_cpu(ni->type), err);
1907 return err;
1908 }
1909 }
1910 }
1911 pagevec_init(&lru_pvec, 0);
1912 written = 0;
1913 /*
1914 * If the write starts beyond the initialized size, extend it up to the
1915 * beginning of the write and initialize all non-sparse space between
1916 * the old initialized size and the new one. This automatically also
1917 * increments the vfs inode->i_size to keep it above or equal to the
1918 * initialized_size.
1919 */
1920 read_lock_irqsave(&ni->size_lock, flags);
1921 ll = ni->initialized_size;
1922 read_unlock_irqrestore(&ni->size_lock, flags);
1923 if (pos > ll) {
2ec93b0b 1924 err = ntfs_attr_extend_initialized(ni, pos);
98b27036
AA
1925 if (err < 0) {
1926 ntfs_error(vol->sb, "Cannot perform write to inode "
1927 "0x%lx, attribute type 0x%x, because "
1928 "extending the initialized size "
1929 "failed (error code %i).", vi->i_ino,
1930 (unsigned)le32_to_cpu(ni->type), err);
1931 status = err;
1932 goto err_out;
1933 }
1934 }
1935 /*
1936 * Determine the number of pages per cluster for non-resident
1937 * attributes.
1938 */
1939 nr_pages = 1;
1940 if (vol->cluster_size > PAGE_CACHE_SIZE && NInoNonResident(ni))
1941 nr_pages = vol->cluster_size >> PAGE_CACHE_SHIFT;
1942 /* Finally, perform the actual write. */
1943 last_vcn = -1;
1944 if (likely(nr_segs == 1))
1945 buf = iov->iov_base;
98b27036
AA
1946 do {
1947 VCN vcn;
1948 pgoff_t idx, start_idx;
1949 unsigned ofs, do_pages, u;
1950 size_t copied;
1951
1952 start_idx = idx = pos >> PAGE_CACHE_SHIFT;
1953 ofs = pos & ~PAGE_CACHE_MASK;
1954 bytes = PAGE_CACHE_SIZE - ofs;
1955 do_pages = 1;
1956 if (nr_pages > 1) {
1957 vcn = pos >> vol->cluster_size_bits;
1958 if (vcn != last_vcn) {
1959 last_vcn = vcn;
1960 /*
1961 * Get the lcn of the vcn the write is in. If
1962 * it is a hole, need to lock down all pages in
1963 * the cluster.
1964 */
1965 down_read(&ni->runlist.lock);
1966 lcn = ntfs_attr_vcn_to_lcn_nolock(ni, pos >>
c49c3111 1967 vol->cluster_size_bits, false);
98b27036
AA
1968 up_read(&ni->runlist.lock);
1969 if (unlikely(lcn < LCN_HOLE)) {
1970 status = -EIO;
1971 if (lcn == LCN_ENOMEM)
1972 status = -ENOMEM;
1973 else
1974 ntfs_error(vol->sb, "Cannot "
1975 "perform write to "
1976 "inode 0x%lx, "
1977 "attribute type 0x%x, "
1978 "because the attribute "
1979 "is corrupt.",
1980 vi->i_ino, (unsigned)
1981 le32_to_cpu(ni->type));
1982 break;
1983 }
1984 if (lcn == LCN_HOLE) {
1985 start_idx = (pos & ~(s64)
1986 vol->cluster_size_mask)
1987 >> PAGE_CACHE_SHIFT;
1988 bytes = vol->cluster_size - (pos &
1989 vol->cluster_size_mask);
1990 do_pages = nr_pages;
1991 }
1992 }
1993 }
1994 if (bytes > count)
1995 bytes = count;
1996 /*
1997 * Bring in the user page(s) that we will copy from _first_.
1998 * Otherwise there is a nasty deadlock on copying from the same
1999 * page(s) as we are writing to, without it/them being marked
2000 * up-to-date. Note, at present there is nothing to stop the
2001 * pages being swapped out between us bringing them into memory
2002 * and doing the actual copying.
2003 */
2004 if (likely(nr_segs == 1))
2005 ntfs_fault_in_pages_readable(buf, bytes);
2006 else
2007 ntfs_fault_in_pages_readable_iovec(iov, iov_ofs, bytes);
2008 /* Get and lock @do_pages starting at index @start_idx. */
2009 status = __ntfs_grab_cache_pages(mapping, start_idx, do_pages,
2010 pages, &cached_page, &lru_pvec);
2011 if (unlikely(status))
2012 break;
2013 /*
2014 * For non-resident attributes, we need to fill any holes with
2015 * actual clusters and ensure all bufferes are mapped. We also
2016 * need to bring uptodate any buffers that are only partially
2017 * being written to.
2018 */
2019 if (NInoNonResident(ni)) {
2020 status = ntfs_prepare_pages_for_non_resident_write(
2021 pages, do_pages, pos, bytes);
2022 if (unlikely(status)) {
2023 loff_t i_size;
2024
2025 do {
2026 unlock_page(pages[--do_pages]);
2027 page_cache_release(pages[do_pages]);
2028 } while (do_pages);
2029 /*
2030 * The write preparation may have instantiated
2031 * allocated space outside i_size. Trim this
2032 * off again. We can ignore any errors in this
2033 * case as we will just be waisting a bit of
2034 * allocated space, which is not a disaster.
2035 */
2036 i_size = i_size_read(vi);
2037 if (pos + bytes > i_size)
2038 vmtruncate(vi, i_size);
2039 break;
2040 }
2041 }
2042 u = (pos >> PAGE_CACHE_SHIFT) - pages[0]->index;
2043 if (likely(nr_segs == 1)) {
2044 copied = ntfs_copy_from_user(pages + u, do_pages - u,
2045 ofs, buf, bytes);
2046 buf += copied;
2047 } else
2048 copied = ntfs_copy_from_user_iovec(pages + u,
2049 do_pages - u, ofs, &iov, &iov_ofs,
2050 bytes);
2051 ntfs_flush_dcache_pages(pages + u, do_pages - u);
2052 status = ntfs_commit_pages_after_write(pages, do_pages, pos,
2053 bytes);
2054 if (likely(!status)) {
2055 written += copied;
2056 count -= copied;
2057 pos += copied;
2058 if (unlikely(copied != bytes))
2059 status = -EFAULT;
2060 }
2061 do {
2062 unlock_page(pages[--do_pages]);
2063 mark_page_accessed(pages[do_pages]);
2064 page_cache_release(pages[do_pages]);
2065 } while (do_pages);
2066 if (unlikely(status))
2067 break;
2068 balance_dirty_pages_ratelimited(mapping);
2069 cond_resched();
2070 } while (count);
2071err_out:
2072 *ppos = pos;
2073 if (cached_page)
2074 page_cache_release(cached_page);
4f98a2fe 2075 pagevec_lru_add_file(&lru_pvec);
98b27036
AA
2076 ntfs_debug("Done. Returning %s (written 0x%lx, status %li).",
2077 written ? "written" : "status", (unsigned long)written,
2078 (long)status);
2079 return written ? written : status;
2080}
2081
2082/**
2083 * ntfs_file_aio_write_nolock -
2084 */
2085static ssize_t ntfs_file_aio_write_nolock(struct kiocb *iocb,
2086 const struct iovec *iov, unsigned long nr_segs, loff_t *ppos)
2087{
2088 struct file *file = iocb->ki_filp;
2089 struct address_space *mapping = file->f_mapping;
2090 struct inode *inode = mapping->host;
2091 loff_t pos;
98b27036
AA
2092 size_t count; /* after file limit checks */
2093 ssize_t written, err;
2094
2095 count = 0;
0ceb3314
DM
2096 err = generic_segment_checks(iov, &nr_segs, &count, VERIFY_READ);
2097 if (err)
2098 return err;
98b27036
AA
2099 pos = *ppos;
2100 vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
2101 /* We can write back this queue in page reclaim. */
2102 current->backing_dev_info = mapping->backing_dev_info;
2103 written = 0;
2104 err = generic_write_checks(file, &pos, &count, S_ISBLK(inode->i_mode));
2105 if (err)
2106 goto out;
2107 if (!count)
2108 goto out;
2f1936b8 2109 err = file_remove_suid(file);
98b27036
AA
2110 if (err)
2111 goto out;
870f4817 2112 file_update_time(file);
98b27036
AA
2113 written = ntfs_file_buffered_write(iocb, iov, nr_segs, pos, ppos,
2114 count);
2115out:
2116 current->backing_dev_info = NULL;
2117 return written ? written : err;
2118}
2119
2120/**
2121 * ntfs_file_aio_write -
2122 */
027445c3
BP
2123static ssize_t ntfs_file_aio_write(struct kiocb *iocb, const struct iovec *iov,
2124 unsigned long nr_segs, loff_t pos)
98b27036
AA
2125{
2126 struct file *file = iocb->ki_filp;
2127 struct address_space *mapping = file->f_mapping;
2128 struct inode *inode = mapping->host;
2129 ssize_t ret;
98b27036
AA
2130
2131 BUG_ON(iocb->ki_pos != pos);
2132
1b1dcc1b 2133 mutex_lock(&inode->i_mutex);
027445c3 2134 ret = ntfs_file_aio_write_nolock(iocb, iov, nr_segs, &iocb->ki_pos);
1b1dcc1b 2135 mutex_unlock(&inode->i_mutex);
ebbbf757
JK
2136 if (ret > 0) {
2137 int err = generic_write_sync(file, pos, ret);
98b27036
AA
2138 if (err < 0)
2139 ret = err;
2140 }
2141 return ret;
2142}
2143
1da177e4
LT
2144/**
2145 * ntfs_file_fsync - sync a file to disk
2146 * @filp: file to be synced
2147 * @dentry: dentry describing the file to sync
2148 * @datasync: if non-zero only flush user data and not metadata
2149 *
2150 * Data integrity sync of a file to disk. Used for fsync, fdatasync, and msync
2151 * system calls. This function is inspired by fs/buffer.c::file_fsync().
2152 *
2153 * If @datasync is false, write the mft record and all associated extent mft
2154 * records as well as the $DATA attribute and then sync the block device.
2155 *
2156 * If @datasync is true and the attribute is non-resident, we skip the writing
2157 * of the mft record and all associated extent mft records (this might still
2158 * happen due to the write_inode_now() call).
2159 *
2160 * Also, if @datasync is true, we do not wait on the inode to be written out
2161 * but we always wait on the page cache pages to be written out.
2162 *
2163 * Note: In the past @filp could be NULL so we ignore it as we don't need it
2164 * anyway.
2165 *
1b1dcc1b 2166 * Locking: Caller must hold i_mutex on the inode.
1da177e4
LT
2167 *
2168 * TODO: We should probably also write all attribute/index inodes associated
2169 * with this inode but since we have no simple way of getting to them we ignore
2170 * this problem for now.
2171 */
2172static int ntfs_file_fsync(struct file *filp, struct dentry *dentry,
2173 int datasync)
2174{
2175 struct inode *vi = dentry->d_inode;
2176 int err, ret = 0;
2177
2178 ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
2179 BUG_ON(S_ISDIR(vi->i_mode));
2180 if (!datasync || !NInoNonResident(NTFS_I(vi)))
a9185b41 2181 ret = __ntfs_write_inode(vi, 1);
1da177e4 2182 write_inode_now(vi, !datasync);
f25dfb5e
AA
2183 /*
2184 * NOTE: If we were to use mapping->private_list (see ext2 and
2185 * fs/buffer.c) for dirty blocks then we could optimize the below to be
2186 * sync_mapping_buffers(vi->i_mapping).
2187 */
1da177e4
LT
2188 err = sync_blockdev(vi->i_sb->s_bdev);
2189 if (unlikely(err && !ret))
2190 ret = err;
2191 if (likely(!ret))
2192 ntfs_debug("Done.");
2193 else
2194 ntfs_warning(vi->i_sb, "Failed to f%ssync inode 0x%lx. Error "
2195 "%u.", datasync ? "data" : "", vi->i_ino, -ret);
2196 return ret;
2197}
2198
2199#endif /* NTFS_RW */
2200
4b6f5d20 2201const struct file_operations ntfs_file_ops = {
98b27036 2202 .llseek = generic_file_llseek, /* Seek inside file. */
543ade1f 2203 .read = do_sync_read, /* Read from file. */
98b27036 2204 .aio_read = generic_file_aio_read, /* Async read from file. */
1da177e4 2205#ifdef NTFS_RW
8a9f47dd 2206 .write = do_sync_write, /* Write to file. */
98b27036 2207 .aio_write = ntfs_file_aio_write, /* Async write to file. */
98b27036
AA
2208 /*.release = ,*/ /* Last file is closed. See
2209 fs/ext2/file.c::
2210 ext2_release_file() for
2211 how to use this to discard
2212 preallocated space for
2213 write opened files. */
2214 .fsync = ntfs_file_fsync, /* Sync a file to disk. */
2215 /*.aio_fsync = ,*/ /* Sync all outstanding async
2216 i/o operations on a
2217 kiocb. */
1da177e4 2218#endif /* NTFS_RW */
98b27036
AA
2219 /*.ioctl = ,*/ /* Perform function on the
2220 mounted filesystem. */
2221 .mmap = generic_file_mmap, /* Mmap file. */
2222 .open = ntfs_file_open, /* Open file. */
5ffc4ef4 2223 .splice_read = generic_file_splice_read /* Zero-copy data send with
98b27036
AA
2224 the data source being on
2225 the ntfs partition. We do
2226 not need to care about the
2227 data destination. */
2228 /*.sendpage = ,*/ /* Zero-copy data send with
2229 the data destination being
2230 on the ntfs partition. We
2231 do not need to care about
2232 the data source. */
1da177e4
LT
2233};
2234
92e1d5be 2235const struct inode_operations ntfs_file_inode_ops = {
1da177e4
LT
2236#ifdef NTFS_RW
2237 .truncate = ntfs_truncate_vfs,
2238 .setattr = ntfs_setattr,
2239#endif /* NTFS_RW */
2240};
2241
4b6f5d20 2242const struct file_operations ntfs_empty_file_ops = {};
1da177e4 2243
92e1d5be 2244const struct inode_operations ntfs_empty_inode_ops = {};