generic_write_checks(): drop isblk argument
[firefly-linux-kernel-4.4.55.git] / fs / ntfs / file.c
1 /*
2  * file.c - NTFS kernel file operations.  Part of the Linux-NTFS project.
3  *
4  * Copyright (c) 2001-2015 Anton Altaparmakov and Tuxera Inc.
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
22 #include <linux/backing-dev.h>
23 #include <linux/buffer_head.h>
24 #include <linux/gfp.h>
25 #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>
31
32 #include <asm/page.h>
33 #include <asm/uaccess.h>
34
35 #include "attrib.h"
36 #include "bitmap.h"
37 #include "inode.h"
38 #include "debug.h"
39 #include "lcnalloc.h"
40 #include "malloc.h"
41 #include "mft.h"
42 #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  */
62 static int ntfs_file_open(struct inode *vi, struct file *filp)
63 {
64         if (sizeof(unsigned long) < 8) {
65                 if (i_size_read(vi) > MAX_LFS_FILESIZE)
66                         return -EOVERFLOW;
67         }
68         return generic_file_open(vi, filp);
69 }
70
71 #ifdef NTFS_RW
72
73 /**
74  * 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
77  *
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
81  * disk (if relevant complete pages are already uptodate in the page cache then
82  * these are simply marked dirty).
83  *
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
97  * the page at all.  For a more detailed explanation see ntfs_truncate() in
98  * fs/ntfs/inode.c.
99  *
100  * 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  *
106  * Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be
107  *          held by the caller.
108  */
109 static int ntfs_attr_extend_initialized(ntfs_inode *ni, const s64 new_init_size)
110 {
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;
182 do_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                  */
230                 page = read_mapping_page(mapping, index, NULL);
231                 if (IS_ERR(page)) {
232                         err = PTR_ERR(page);
233                         goto init_err_out;
234                 }
235                 if (unlikely(PageError(page))) {
236                         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);
245                 ni->initialized_size = (s64)(index + 1) << PAGE_CACHE_SHIFT;
246                 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);
308 done:
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;
318 init_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);
322 err_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
331 static ssize_t ntfs_prepare_file_for_write(struct kiocb *iocb,
332                 struct iov_iter *from)
333 {
334         loff_t pos;
335         s64 end, ll;
336         ssize_t err;
337         unsigned long flags;
338         struct file *file = iocb->ki_filp;
339         struct inode *vi = file_inode(file);
340         ntfs_inode *base_ni, *ni = NTFS_I(vi);
341         ntfs_volume *vol = ni->vol;
342         size_t count = iov_iter_count(from);
343
344         ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
345                         "0x%llx, count 0x%zx.", vi->i_ino,
346                         (unsigned)le32_to_cpu(ni->type),
347                         (unsigned long long)iocb->ki_pos, count);
348         err = generic_write_checks(file, &iocb->ki_pos, &count);
349         if (unlikely(err))
350                 goto out;
351         iov_iter_truncate(from, count);
352         if (count == 0)
353                 goto out;
354         /*
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         }
385         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);
396         pos = iocb->ki_pos;
397         /* The first byte after the last cluster being written to. */
398         end = (pos + iov_iter_count(from) + vol->cluster_size_mask) &
399                         ~(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));
426                                 iov_iter_truncate(from, ll - pos);
427                         }
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);
442                                 iov_iter_truncate(from, ll - pos);
443                         } 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         }
492 out:
493         return err;
494 }
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
503  *
504  * Obtain @nr_pages locked page cache pages from the mapping @mapping and
505  * starting at index @index.
506  *
507  * If a page is newly created, add it to lru list
508  *
509  * Note, the page locks are obtained in ascending page index order.
510  */
511 static inline int __ntfs_grab_cache_pages(struct address_space *mapping,
512                 pgoff_t index, const unsigned nr_pages, struct page **pages,
513                 struct page **cached_page)
514 {
515         int err, nr;
516
517         BUG_ON(!nr_pages);
518         err = nr = 0;
519         do {
520                 pages[nr] = find_get_page_flags(mapping, index, FGP_LOCK |
521                                 FGP_ACCESSED);
522                 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                         }
530                         err = add_to_page_cache_lru(*cached_page, mapping,
531                                         index, GFP_KERNEL);
532                         if (unlikely(err)) {
533                                 if (err == -EEXIST)
534                                         continue;
535                                 goto err_out;
536                         }
537                         pages[nr] = *cached_page;
538                         *cached_page = NULL;
539                 }
540                 index++;
541                 nr++;
542         } while (nr < nr_pages);
543 out:
544         return err;
545 err_out:
546         while (nr > 0) {
547                 unlock_page(pages[--nr]);
548                 page_cache_release(pages[nr]);
549         }
550         goto out;
551 }
552
553 static 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()
569  * with i_mutex held on the inode (@pages[0]->mapping->host).  There are
570  * @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  */
586 static 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;
606         bool rl_write_locked, was_hole, is_retry;
607         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 "
622                         "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
623                         vi->i_ino, ni->type, pages[0]->index, nr_pages,
624                         (long long)pos, bytes);
625         blocksize = vol->sb->s_blocksize;
626         blocksize_bits = vol->sb->s_blocksize_bits;
627         u = 0;
628         do {
629                 page = pages[u];
630                 BUG_ON(!page);
631                 /*
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);
641         rl_write_locked = false;
642         rl = NULL;
643         err = 0;
644         vcn = lcn = -1;
645         vcn_len = 0;
646         lcn_block = -1;
647         was_hole = false;
648         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;
656 do_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 {
705                                         zero_user(page, bh_offset(bh),
706                                                         blocksize);
707                                         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))) {
724 map_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                                  */
762                                 if (!buffer_uptodate(bh) && bh_pos < end &&
763                                                 bh_end > pos &&
764                                                 (bh_pos < pos ||
765                                                 bh_end > end)) {
766                                         /*
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 {
781                                                 zero_user(page, bh_offset(bh),
782                                                                 blocksize);
783                                                 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)) {
800                                         zero_user(page, bh_offset(bh),
801                                                         blocksize);
802                                         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                                         
813                                 kaddr = kmap_atomic(page);
814                                 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                                 }
822                                 kunmap_atomic(kaddr);
823                                 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)) {
840                                 zero_user(page, bh_offset(bh), blocksize);
841                                 set_buffer_uptodate(bh);
842                         }
843                         continue;
844                 }
845                 is_retry = false;
846                 if (!rl) {
847                         down_read(&ni->runlist.lock);
848 retry_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                                  */
861                                 was_hole = false;
862                                 vcn = bh_cpos;
863                                 vcn_len = rl[1].vcn - vcn;
864                                 lcn_block = lcn << (vol->cluster_size_bits -
865                                                 blocksize_bits);
866                                 cdelta = 0;
867                                 /*
868                                  * 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.
873                                  */
874                                 if (likely(vcn + vcn_len >= cend)) {
875                                         if (rl_write_locked) {
876                                                 up_write(&ni->runlist.lock);
877                                                 rl_write_locked = false;
878                                         } 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);
903                                         rl_write_locked = true;
904                                         goto retry_remap;
905                                 }
906                                 err = ntfs_map_runlist_nolock(ni, bh_cpos,
907                                                 NULL);
908                                 if (likely(!err)) {
909                                         is_retry = true;
910                                         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                 }
939 rl_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)) {
964                                         zero_user(page, bh_offset(bh),
965                                                 blocksize);
966                                         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);
985                         rl_write_locked = true;
986                         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,
999                                 false);
1000                 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;
1024                 ntfs_debug("Allocated cluster, lcn 0x%llx.",
1025                                 (unsigned long long)lcn);
1026                 /* 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. */
1175                 was_hole = true;
1176                 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);
1187                         rl_write_locked = false;
1188                         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);
1199                         rl_write_locked = false;
1200                 } 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)) {
1220                                 int ofs = 0;
1221
1222                                 if (likely(bh_pos < initialized_size))
1223                                         ofs = initialized_size - bh_pos;
1224                                 zero_user_segment(page, bh_offset(bh) + ofs,
1225                                                 blocksize);
1226                         }
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.");
1284                         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.");
1314                         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.");
1326                                 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 {
1365                                         zero_user(page, bh_offset(bh),
1366                                                         blocksize);
1367                                         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
1377 static inline void ntfs_flush_dcache_pages(struct page **pages,
1378                 unsigned nr_pages)
1379 {
1380         BUG_ON(!nr_pages);
1381         /*
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          */
1386         do {
1387                 --nr_pages;
1388                 flush_dcache_page(pages[nr_pages]);
1389         } while (nr_pages > 0);
1390 }
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  */
1401 static 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);
1418         blocksize = vi->i_sb->s_blocksize;
1419         end = pos + bytes;
1420         u = 0;
1421         do {
1422                 s64 bh_pos;
1423                 struct page *page;
1424                 bool partial;
1425
1426                 page = pages[u];
1427                 bh_pos = (s64)page->index << PAGE_CACHE_SHIFT;
1428                 bh = head = page_buffers(page);
1429                 partial = false;
1430                 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))
1436                                         partial = true;
1437                         } 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;
1508 err_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);
1515         if (err != -ENOMEM)
1516                 NVolSetErrors(ni->vol);
1517         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  *
1527  * This is called from ntfs_file_buffered_write() with i_mutex held on the inode
1528  * (@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  */
1556 static 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 "
1579                         "index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
1580                         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);
1626         kaddr = kmap_atomic(page);
1627         /* 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         }
1648         kunmap_atomic(kaddr);
1649         /* 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) {
1656                 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;
1668 err_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);
1689         }
1690         if (ctx)
1691                 ntfs_attr_put_search_ctx(ctx);
1692         if (m)
1693                 unmap_mft_record(base_ni);
1694         return err;
1695 }
1696
1697 /*
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  */
1702 static size_t ntfs_copy_from_user_iter(struct page **pages, unsigned nr_pages,
1703                 unsigned ofs, struct iov_iter *i, size_t bytes)
1704 {
1705         struct page **last_page = pages + nr_pages;
1706         size_t total = 0;
1707         struct iov_iter data = *i;
1708         unsigned len, copied;
1709
1710         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);
1725 out:
1726         return total;
1727 err:
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;
1739 }
1740
1741 /**
1742  * 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
1746  */
1747 static ssize_t ntfs_perform_write(struct file *file, struct iov_iter *i,
1748                 loff_t pos)
1749 {
1750         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;
1756         VCN last_vcn;
1757         LCN lcn;
1758         size_t bytes;
1759         ssize_t status, written = 0;
1760         unsigned nr_pages;
1761
1762         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));
1767         /*
1768          * If a previous ntfs_truncate() failed, repeat it and abort if it
1769          * fails again.
1770          */
1771         if (unlikely(NInoTruncateFailed(ni))) {
1772                 int err;
1773
1774                 inode_dio_wait(vi);
1775                 err = ntfs_truncate(vi);
1776                 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         }
1787         /*
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;
1794         last_vcn = -1;
1795         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 >>
1816                                                 vol->cluster_size_bits, false);
1817                                 up_read(&ni->runlist.lock);
1818                                 if (unlikely(lcn < LCN_HOLE)) {
1819                                         if (lcn == LCN_ENOMEM)
1820                                                 status = -ENOMEM;
1821                                         else {
1822                                                 status = -EIO;
1823                                                 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));
1831                                         }
1832                                         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                 }
1844                 if (bytes > iov_iter_count(i))
1845                         bytes = iov_iter_count(i);
1846 again:
1847                 /*
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                  */
1855                 if (unlikely(iov_iter_fault_in_multipages_readable(i, bytes))) {
1856                         status = -EFAULT;
1857                         break;
1858                 }
1859                 /* Get and lock @do_pages starting at index @start_idx. */
1860                 status = __ntfs_grab_cache_pages(mapping, start_idx, do_pages,
1861                                 pages, &cached_page);
1862                 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)) {
1874                                 do {
1875                                         unlock_page(pages[--do_pages]);
1876                                         page_cache_release(pages[do_pages]);
1877                                 } while (do_pages);
1878                                 break;
1879                         }
1880                 }
1881                 u = (pos >> PAGE_CACHE_SHIFT) - pages[0]->index;
1882                 copied = ntfs_copy_from_user_iter(pages + u, do_pages - u, ofs,
1883                                         i, bytes);
1884                 ntfs_flush_dcache_pages(pages + u, do_pages - u);
1885                 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;
1891                 }
1892                 do {
1893                         unlock_page(pages[--do_pages]);
1894                         page_cache_release(pages[do_pages]);
1895                 } while (do_pages);
1896                 if (unlikely(status < 0))
1897                         break;
1898                 copied = status;
1899                 cond_resched();
1900                 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));
1925         if (cached_page)
1926                 page_cache_release(cached_page);
1927         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 /**
1934  * 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
1939  * up calling ntfs_perform_write() instead of generic_perform_write() and that
1940  * O_DIRECT is not implemented.
1941  */
1942 static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
1943 {
1944         struct file *file = iocb->ki_filp;
1945         struct inode *vi = file_inode(file);
1946         ssize_t written = 0;
1947         ssize_t err;
1948
1949         mutex_lock(&vi->i_mutex);
1950         /* 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;
1956         mutex_unlock(&vi->i_mutex);
1957         if (likely(written > 0)) {
1958                 err = generic_write_sync(file, iocb->ki_pos, written);
1959                 if (err < 0)
1960                         written = 0;
1961         }
1962         iocb->ki_pos += written;
1963         return written ? written : err;
1964 }
1965
1966 /**
1967  * ntfs_file_fsync - sync a file to disk
1968  * @filp:       file to be synced
1969  * @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  *
1984  * Locking: Caller must hold i_mutex on the inode.
1985  *
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  */
1990 static int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end,
1991                            int datasync)
1992 {
1993         struct inode *vi = filp->f_mapping->host;
1994         int err, ret = 0;
1995
1996         ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
1997
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
2003         BUG_ON(S_ISDIR(vi->i_mode));
2004         if (!datasync || !NInoNonResident(NTFS_I(vi)))
2005                 ret = __ntfs_write_inode(vi, 1);
2006         write_inode_now(vi, !datasync);
2007         /*
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          */
2012         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);
2020         mutex_unlock(&vi->i_mutex);
2021         return ret;
2022 }
2023
2024 #endif /* NTFS_RW */
2025
2026 const struct file_operations ntfs_file_ops = {
2027         .llseek         = generic_file_llseek,
2028         .read_iter      = generic_file_read_iter,
2029 #ifdef NTFS_RW
2030         .write_iter     = ntfs_file_write_iter,
2031         .fsync          = ntfs_file_fsync,
2032 #endif /* NTFS_RW */
2033         .mmap           = generic_file_mmap,
2034         .open           = ntfs_file_open,
2035         .splice_read    = generic_file_splice_read,
2036 };
2037
2038 const struct inode_operations ntfs_file_inode_ops = {
2039 #ifdef NTFS_RW
2040         .setattr        = ntfs_setattr,
2041 #endif /* NTFS_RW */
2042 };
2043
2044 const struct file_operations ntfs_empty_file_ops = {};
2045
2046 const struct inode_operations ntfs_empty_inode_ops = {};