Automatic merge with /usr/src/ntfs-2.6.git.
[linux-2.6] / fs / ntfs / aops.c
1 /**
2  * aops.c - NTFS kernel address space operations and page cache handling.
3  *          Part of the Linux-NTFS project.
4  *
5  * Copyright (c) 2001-2005 Anton Altaparmakov
6  * Copyright (c) 2002 Richard Russon
7  *
8  * This program/include file is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as published
10  * by the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program/include file is distributed in the hope that it will be
14  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty
15  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program (in the main directory of the Linux-NTFS
20  * distribution in the file COPYING); if not, write to the Free Software
21  * Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  */
23
24 #include <linux/errno.h>
25 #include <linux/mm.h>
26 #include <linux/pagemap.h>
27 #include <linux/swap.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
30
31 #include "aops.h"
32 #include "attrib.h"
33 #include "debug.h"
34 #include "inode.h"
35 #include "mft.h"
36 #include "runlist.h"
37 #include "types.h"
38 #include "ntfs.h"
39
40 /**
41  * ntfs_end_buffer_async_read - async io completion for reading attributes
42  * @bh:         buffer head on which io is completed
43  * @uptodate:   whether @bh is now uptodate or not
44  *
45  * Asynchronous I/O completion handler for reading pages belonging to the
46  * attribute address space of an inode.  The inodes can either be files or
47  * directories or they can be fake inodes describing some attribute.
48  *
49  * If NInoMstProtected(), perform the post read mst fixups when all IO on the
50  * page has been completed and mark the page uptodate or set the error bit on
51  * the page.  To determine the size of the records that need fixing up, we
52  * cheat a little bit by setting the index_block_size in ntfs_inode to the ntfs
53  * record size, and index_block_size_bits, to the log(base 2) of the ntfs
54  * record size.
55  */
56 static void ntfs_end_buffer_async_read(struct buffer_head *bh, int uptodate)
57 {
58         static DEFINE_SPINLOCK(page_uptodate_lock);
59         unsigned long flags;
60         struct buffer_head *tmp;
61         struct page *page;
62         ntfs_inode *ni;
63         int page_uptodate = 1;
64
65         page = bh->b_page;
66         ni = NTFS_I(page->mapping->host);
67
68         if (likely(uptodate)) {
69                 s64 file_ofs, initialized_size;
70
71                 set_buffer_uptodate(bh);
72
73                 file_ofs = ((s64)page->index << PAGE_CACHE_SHIFT) +
74                                 bh_offset(bh);
75                 read_lock_irqsave(&ni->size_lock, flags);
76                 initialized_size = ni->initialized_size;
77                 read_unlock_irqrestore(&ni->size_lock, flags);
78                 /* Check for the current buffer head overflowing. */
79                 if (file_ofs + bh->b_size > initialized_size) {
80                         char *addr;
81                         int ofs = 0;
82
83                         if (file_ofs < initialized_size)
84                                 ofs = initialized_size - file_ofs;
85                         addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
86                         memset(addr + bh_offset(bh) + ofs, 0, bh->b_size - ofs);
87                         flush_dcache_page(page);
88                         kunmap_atomic(addr, KM_BIO_SRC_IRQ);
89                 }
90         } else {
91                 clear_buffer_uptodate(bh);
92                 ntfs_error(ni->vol->sb, "Buffer I/O error, logical block %llu.",
93                                 (unsigned long long)bh->b_blocknr);
94                 SetPageError(page);
95         }
96         spin_lock_irqsave(&page_uptodate_lock, flags);
97         clear_buffer_async_read(bh);
98         unlock_buffer(bh);
99         tmp = bh;
100         do {
101                 if (!buffer_uptodate(tmp))
102                         page_uptodate = 0;
103                 if (buffer_async_read(tmp)) {
104                         if (likely(buffer_locked(tmp)))
105                                 goto still_busy;
106                         /* Async buffers must be locked. */
107                         BUG();
108                 }
109                 tmp = tmp->b_this_page;
110         } while (tmp != bh);
111         spin_unlock_irqrestore(&page_uptodate_lock, flags);
112         /*
113          * If none of the buffers had errors then we can set the page uptodate,
114          * but we first have to perform the post read mst fixups, if the
115          * attribute is mst protected, i.e. if NInoMstProteced(ni) is true.
116          * Note we ignore fixup errors as those are detected when
117          * map_mft_record() is called which gives us per record granularity
118          * rather than per page granularity.
119          */
120         if (!NInoMstProtected(ni)) {
121                 if (likely(page_uptodate && !PageError(page)))
122                         SetPageUptodate(page);
123         } else {
124                 char *addr;
125                 unsigned int i, recs;
126                 u32 rec_size;
127
128                 rec_size = ni->itype.index.block_size;
129                 recs = PAGE_CACHE_SIZE / rec_size;
130                 /* Should have been verified before we got here... */
131                 BUG_ON(!recs);
132                 addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
133                 for (i = 0; i < recs; i++)
134                         post_read_mst_fixup((NTFS_RECORD*)(addr +
135                                         i * rec_size), rec_size);
136                 flush_dcache_page(page);
137                 kunmap_atomic(addr, KM_BIO_SRC_IRQ);
138                 if (likely(page_uptodate && !PageError(page)))
139                         SetPageUptodate(page);
140         }
141         unlock_page(page);
142         return;
143 still_busy:
144         spin_unlock_irqrestore(&page_uptodate_lock, flags);
145         return;
146 }
147
148 /**
149  * ntfs_read_block - fill a @page of an address space with data
150  * @page:       page cache page to fill with data
151  *
152  * Fill the page @page of the address space belonging to the @page->host inode.
153  * We read each buffer asynchronously and when all buffers are read in, our io
154  * completion handler ntfs_end_buffer_read_async(), if required, automatically
155  * applies the mst fixups to the page before finally marking it uptodate and
156  * unlocking it.
157  *
158  * We only enforce allocated_size limit because i_size is checked for in
159  * generic_file_read().
160  *
161  * Return 0 on success and -errno on error.
162  *
163  * Contains an adapted version of fs/buffer.c::block_read_full_page().
164  */
165 static int ntfs_read_block(struct page *page)
166 {
167         VCN vcn;
168         LCN lcn;
169         ntfs_inode *ni;
170         ntfs_volume *vol;
171         runlist_element *rl;
172         struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
173         sector_t iblock, lblock, zblock;
174         unsigned long flags;
175         unsigned int blocksize, vcn_ofs;
176         int i, nr;
177         unsigned char blocksize_bits;
178
179         ni = NTFS_I(page->mapping->host);
180         vol = ni->vol;
181
182         /* $MFT/$DATA must have its complete runlist in memory at all times. */
183         BUG_ON(!ni->runlist.rl && !ni->mft_no && !NInoAttr(ni));
184
185         blocksize_bits = VFS_I(ni)->i_blkbits;
186         blocksize = 1 << blocksize_bits;
187
188         if (!page_has_buffers(page))
189                 create_empty_buffers(page, blocksize, 0);
190         bh = head = page_buffers(page);
191         if (unlikely(!bh)) {
192                 unlock_page(page);
193                 return -ENOMEM;
194         }
195
196         iblock = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
197         read_lock_irqsave(&ni->size_lock, flags);
198         lblock = (ni->allocated_size + blocksize - 1) >> blocksize_bits;
199         zblock = (ni->initialized_size + blocksize - 1) >> blocksize_bits;
200         read_unlock_irqrestore(&ni->size_lock, flags);
201
202         /* Loop through all the buffers in the page. */
203         rl = NULL;
204         nr = i = 0;
205         do {
206                 u8 *kaddr;
207
208                 if (unlikely(buffer_uptodate(bh)))
209                         continue;
210                 if (unlikely(buffer_mapped(bh))) {
211                         arr[nr++] = bh;
212                         continue;
213                 }
214                 bh->b_bdev = vol->sb->s_bdev;
215                 /* Is the block within the allowed limits? */
216                 if (iblock < lblock) {
217                         BOOL is_retry = FALSE;
218
219                         /* Convert iblock into corresponding vcn and offset. */
220                         vcn = (VCN)iblock << blocksize_bits >>
221                                         vol->cluster_size_bits;
222                         vcn_ofs = ((VCN)iblock << blocksize_bits) &
223                                         vol->cluster_size_mask;
224                         if (!rl) {
225 lock_retry_remap:
226                                 down_read(&ni->runlist.lock);
227                                 rl = ni->runlist.rl;
228                         }
229                         if (likely(rl != NULL)) {
230                                 /* Seek to element containing target vcn. */
231                                 while (rl->length && rl[1].vcn <= vcn)
232                                         rl++;
233                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
234                         } else
235                                 lcn = LCN_RL_NOT_MAPPED;
236                         /* Successful remap. */
237                         if (lcn >= 0) {
238                                 /* Setup buffer head to correct block. */
239                                 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
240                                                 + vcn_ofs) >> blocksize_bits;
241                                 set_buffer_mapped(bh);
242                                 /* Only read initialized data blocks. */
243                                 if (iblock < zblock) {
244                                         arr[nr++] = bh;
245                                         continue;
246                                 }
247                                 /* Fully non-initialized data block, zero it. */
248                                 goto handle_zblock;
249                         }
250                         /* It is a hole, need to zero it. */
251                         if (lcn == LCN_HOLE)
252                                 goto handle_hole;
253                         /* If first try and runlist unmapped, map and retry. */
254                         if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
255                                 int err;
256                                 is_retry = TRUE;
257                                 /*
258                                  * Attempt to map runlist, dropping lock for
259                                  * the duration.
260                                  */
261                                 up_read(&ni->runlist.lock);
262                                 err = ntfs_map_runlist(ni, vcn);
263                                 if (likely(!err))
264                                         goto lock_retry_remap;
265                                 rl = NULL;
266                                 lcn = err;
267                         }
268                         /* Hard error, zero out region. */
269                         bh->b_blocknr = -1;
270                         SetPageError(page);
271                         ntfs_error(vol->sb, "Failed to read from inode 0x%lx, "
272                                         "attribute type 0x%x, vcn 0x%llx, "
273                                         "offset 0x%x because its location on "
274                                         "disk could not be determined%s "
275                                         "(error code %lli).", ni->mft_no,
276                                         ni->type, (unsigned long long)vcn,
277                                         vcn_ofs, is_retry ? " even after "
278                                         "retrying" : "", (long long)lcn);
279                 }
280                 /*
281                  * Either iblock was outside lblock limits or
282                  * ntfs_rl_vcn_to_lcn() returned error.  Just zero that portion
283                  * of the page and set the buffer uptodate.
284                  */
285 handle_hole:
286                 bh->b_blocknr = -1UL;
287                 clear_buffer_mapped(bh);
288 handle_zblock:
289                 kaddr = kmap_atomic(page, KM_USER0);
290                 memset(kaddr + i * blocksize, 0, blocksize);
291                 flush_dcache_page(page);
292                 kunmap_atomic(kaddr, KM_USER0);
293                 set_buffer_uptodate(bh);
294         } while (i++, iblock++, (bh = bh->b_this_page) != head);
295
296         /* Release the lock if we took it. */
297         if (rl)
298                 up_read(&ni->runlist.lock);
299
300         /* Check we have at least one buffer ready for i/o. */
301         if (nr) {
302                 struct buffer_head *tbh;
303
304                 /* Lock the buffers. */
305                 for (i = 0; i < nr; i++) {
306                         tbh = arr[i];
307                         lock_buffer(tbh);
308                         tbh->b_end_io = ntfs_end_buffer_async_read;
309                         set_buffer_async_read(tbh);
310                 }
311                 /* Finally, start i/o on the buffers. */
312                 for (i = 0; i < nr; i++) {
313                         tbh = arr[i];
314                         if (likely(!buffer_uptodate(tbh)))
315                                 submit_bh(READ, tbh);
316                         else
317                                 ntfs_end_buffer_async_read(tbh, 1);
318                 }
319                 return 0;
320         }
321         /* No i/o was scheduled on any of the buffers. */
322         if (likely(!PageError(page)))
323                 SetPageUptodate(page);
324         else /* Signal synchronous i/o error. */
325                 nr = -EIO;
326         unlock_page(page);
327         return nr;
328 }
329
330 /**
331  * ntfs_readpage - fill a @page of a @file with data from the device
332  * @file:       open file to which the page @page belongs or NULL
333  * @page:       page cache page to fill with data
334  *
335  * For non-resident attributes, ntfs_readpage() fills the @page of the open
336  * file @file by calling the ntfs version of the generic block_read_full_page()
337  * function, ntfs_read_block(), which in turn creates and reads in the buffers
338  * associated with the page asynchronously.
339  *
340  * For resident attributes, OTOH, ntfs_readpage() fills @page by copying the
341  * data from the mft record (which at this stage is most likely in memory) and
342  * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
343  * even if the mft record is not cached at this point in time, we need to wait
344  * for it to be read in before we can do the copy.
345  *
346  * Return 0 on success and -errno on error.
347  */
348 static int ntfs_readpage(struct file *file, struct page *page)
349 {
350         ntfs_inode *ni, *base_ni;
351         u8 *kaddr;
352         ntfs_attr_search_ctx *ctx;
353         MFT_RECORD *mrec;
354         unsigned long flags;
355         u32 attr_len;
356         int err = 0;
357
358 retry_readpage:
359         BUG_ON(!PageLocked(page));
360         /*
361          * This can potentially happen because we clear PageUptodate() during
362          * ntfs_writepage() of MstProtected() attributes.
363          */
364         if (PageUptodate(page)) {
365                 unlock_page(page);
366                 return 0;
367         }
368         ni = NTFS_I(page->mapping->host);
369
370         /* NInoNonResident() == NInoIndexAllocPresent() */
371         if (NInoNonResident(ni)) {
372                 /*
373                  * Only unnamed $DATA attributes can be compressed or
374                  * encrypted.
375                  */
376                 if (ni->type == AT_DATA && !ni->name_len) {
377                         /* If file is encrypted, deny access, just like NT4. */
378                         if (NInoEncrypted(ni)) {
379                                 err = -EACCES;
380                                 goto err_out;
381                         }
382                         /* Compressed data streams are handled in compress.c. */
383                         if (NInoCompressed(ni))
384                                 return ntfs_read_compressed_block(page);
385                 }
386                 /* Normal data stream. */
387                 return ntfs_read_block(page);
388         }
389         /*
390          * Attribute is resident, implying it is not compressed or encrypted.
391          * This also means the attribute is smaller than an mft record and
392          * hence smaller than a page, so can simply zero out any pages with
393          * index above 0.
394          */
395         if (unlikely(page->index > 0)) {
396                 kaddr = kmap_atomic(page, KM_USER0);
397                 memset(kaddr, 0, PAGE_CACHE_SIZE);
398                 flush_dcache_page(page);
399                 kunmap_atomic(kaddr, KM_USER0);
400                 goto done;
401         }
402         if (!NInoAttr(ni))
403                 base_ni = ni;
404         else
405                 base_ni = ni->ext.base_ntfs_ino;
406         /* Map, pin, and lock the mft record. */
407         mrec = map_mft_record(base_ni);
408         if (IS_ERR(mrec)) {
409                 err = PTR_ERR(mrec);
410                 goto err_out;
411         }
412         /*
413          * If a parallel write made the attribute non-resident, drop the mft
414          * record and retry the readpage.
415          */
416         if (unlikely(NInoNonResident(ni))) {
417                 unmap_mft_record(base_ni);
418                 goto retry_readpage;
419         }
420         ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
421         if (unlikely(!ctx)) {
422                 err = -ENOMEM;
423                 goto unm_err_out;
424         }
425         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
426                         CASE_SENSITIVE, 0, NULL, 0, ctx);
427         if (unlikely(err))
428                 goto put_unm_err_out;
429         attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
430         read_lock_irqsave(&ni->size_lock, flags);
431         if (unlikely(attr_len > ni->initialized_size))
432                 attr_len = ni->initialized_size;
433         read_unlock_irqrestore(&ni->size_lock, flags);
434         kaddr = kmap_atomic(page, KM_USER0);
435         /* Copy the data to the page. */
436         memcpy(kaddr, (u8*)ctx->attr +
437                         le16_to_cpu(ctx->attr->data.resident.value_offset),
438                         attr_len);
439         /* Zero the remainder of the page. */
440         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
441         flush_dcache_page(page);
442         kunmap_atomic(kaddr, KM_USER0);
443 put_unm_err_out:
444         ntfs_attr_put_search_ctx(ctx);
445 unm_err_out:
446         unmap_mft_record(base_ni);
447 done:
448         SetPageUptodate(page);
449 err_out:
450         unlock_page(page);
451         return err;
452 }
453
454 #ifdef NTFS_RW
455
456 /**
457  * ntfs_write_block - write a @page to the backing store
458  * @page:       page cache page to write out
459  * @wbc:        writeback control structure
460  *
461  * This function is for writing pages belonging to non-resident, non-mst
462  * protected attributes to their backing store.
463  *
464  * For a page with buffers, map and write the dirty buffers asynchronously
465  * under page writeback. For a page without buffers, create buffers for the
466  * page, then proceed as above.
467  *
468  * If a page doesn't have buffers the page dirty state is definitive. If a page
469  * does have buffers, the page dirty state is just a hint, and the buffer dirty
470  * state is definitive. (A hint which has rules: dirty buffers against a clean
471  * page is illegal. Other combinations are legal and need to be handled. In
472  * particular a dirty page containing clean buffers for example.)
473  *
474  * Return 0 on success and -errno on error.
475  *
476  * Based on ntfs_read_block() and __block_write_full_page().
477  */
478 static int ntfs_write_block(struct page *page, struct writeback_control *wbc)
479 {
480         VCN vcn;
481         LCN lcn;
482         s64 initialized_size;
483         loff_t i_size;
484         sector_t block, dblock, iblock;
485         struct inode *vi;
486         ntfs_inode *ni;
487         ntfs_volume *vol;
488         runlist_element *rl;
489         struct buffer_head *bh, *head;
490         unsigned long flags;
491         unsigned int blocksize, vcn_ofs;
492         int err;
493         BOOL need_end_writeback;
494         unsigned char blocksize_bits;
495
496         vi = page->mapping->host;
497         ni = NTFS_I(vi);
498         vol = ni->vol;
499
500         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
501                         "0x%lx.", ni->mft_no, ni->type, page->index);
502
503         BUG_ON(!NInoNonResident(ni));
504         BUG_ON(NInoMstProtected(ni));
505
506         blocksize_bits = vi->i_blkbits;
507         blocksize = 1 << blocksize_bits;
508
509         if (!page_has_buffers(page)) {
510                 BUG_ON(!PageUptodate(page));
511                 create_empty_buffers(page, blocksize,
512                                 (1 << BH_Uptodate) | (1 << BH_Dirty));
513         }
514         bh = head = page_buffers(page);
515         if (unlikely(!bh)) {
516                 ntfs_warning(vol->sb, "Error allocating page buffers. "
517                                 "Redirtying page so we try again later.");
518                 /*
519                  * Put the page back on mapping->dirty_pages, but leave its
520                  * buffer's dirty state as-is.
521                  */
522                 redirty_page_for_writepage(wbc, page);
523                 unlock_page(page);
524                 return 0;
525         }
526
527         /* NOTE: Different naming scheme to ntfs_read_block()! */
528
529         /* The first block in the page. */
530         block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
531
532         read_lock_irqsave(&ni->size_lock, flags);
533         i_size = i_size_read(vi);
534         initialized_size = ni->initialized_size;
535         read_unlock_irqrestore(&ni->size_lock, flags);
536
537         /* The first out of bounds block for the data size. */
538         dblock = (i_size + blocksize - 1) >> blocksize_bits;
539
540         /* The last (fully or partially) initialized block. */
541         iblock = initialized_size >> blocksize_bits;
542
543         /*
544          * Be very careful.  We have no exclusion from __set_page_dirty_buffers
545          * here, and the (potentially unmapped) buffers may become dirty at
546          * any time.  If a buffer becomes dirty here after we've inspected it
547          * then we just miss that fact, and the page stays dirty.
548          *
549          * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
550          * handle that here by just cleaning them.
551          */
552
553         /*
554          * Loop through all the buffers in the page, mapping all the dirty
555          * buffers to disk addresses and handling any aliases from the
556          * underlying block device's mapping.
557          */
558         rl = NULL;
559         err = 0;
560         do {
561                 BOOL is_retry = FALSE;
562
563                 if (unlikely(block >= dblock)) {
564                         /*
565                          * Mapped buffers outside i_size will occur, because
566                          * this page can be outside i_size when there is a
567                          * truncate in progress. The contents of such buffers
568                          * were zeroed by ntfs_writepage().
569                          *
570                          * FIXME: What about the small race window where
571                          * ntfs_writepage() has not done any clearing because
572                          * the page was within i_size but before we get here,
573                          * vmtruncate() modifies i_size?
574                          */
575                         clear_buffer_dirty(bh);
576                         set_buffer_uptodate(bh);
577                         continue;
578                 }
579
580                 /* Clean buffers are not written out, so no need to map them. */
581                 if (!buffer_dirty(bh))
582                         continue;
583
584                 /* Make sure we have enough initialized size. */
585                 if (unlikely((block >= iblock) &&
586                                 (initialized_size < i_size))) {
587                         /*
588                          * If this page is fully outside initialized size, zero
589                          * out all pages between the current initialized size
590                          * and the current page. Just use ntfs_readpage() to do
591                          * the zeroing transparently.
592                          */
593                         if (block > iblock) {
594                                 // TODO:
595                                 // For each page do:
596                                 // - read_cache_page()
597                                 // Again for each page do:
598                                 // - wait_on_page_locked()
599                                 // - Check (PageUptodate(page) &&
600                                 //                      !PageError(page))
601                                 // Update initialized size in the attribute and
602                                 // in the inode.
603                                 // Again, for each page do:
604                                 //      __set_page_dirty_buffers();
605                                 // page_cache_release()
606                                 // We don't need to wait on the writes.
607                                 // Update iblock.
608                         }
609                         /*
610                          * The current page straddles initialized size. Zero
611                          * all non-uptodate buffers and set them uptodate (and
612                          * dirty?). Note, there aren't any non-uptodate buffers
613                          * if the page is uptodate.
614                          * FIXME: For an uptodate page, the buffers may need to
615                          * be written out because they were not initialized on
616                          * disk before.
617                          */
618                         if (!PageUptodate(page)) {
619                                 // TODO:
620                                 // Zero any non-uptodate buffers up to i_size.
621                                 // Set them uptodate and dirty.
622                         }
623                         // TODO:
624                         // Update initialized size in the attribute and in the
625                         // inode (up to i_size).
626                         // Update iblock.
627                         // FIXME: This is inefficient. Try to batch the two
628                         // size changes to happen in one go.
629                         ntfs_error(vol->sb, "Writing beyond initialized size "
630                                         "is not supported yet. Sorry.");
631                         err = -EOPNOTSUPP;
632                         break;
633                         // Do NOT set_buffer_new() BUT DO clear buffer range
634                         // outside write request range.
635                         // set_buffer_uptodate() on complete buffers as well as
636                         // set_buffer_dirty().
637                 }
638
639                 /* No need to map buffers that are already mapped. */
640                 if (buffer_mapped(bh))
641                         continue;
642
643                 /* Unmapped, dirty buffer. Need to map it. */
644                 bh->b_bdev = vol->sb->s_bdev;
645
646                 /* Convert block into corresponding vcn and offset. */
647                 vcn = (VCN)block << blocksize_bits;
648                 vcn_ofs = vcn & vol->cluster_size_mask;
649                 vcn >>= vol->cluster_size_bits;
650                 if (!rl) {
651 lock_retry_remap:
652                         down_read(&ni->runlist.lock);
653                         rl = ni->runlist.rl;
654                 }
655                 if (likely(rl != NULL)) {
656                         /* Seek to element containing target vcn. */
657                         while (rl->length && rl[1].vcn <= vcn)
658                                 rl++;
659                         lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
660                 } else
661                         lcn = LCN_RL_NOT_MAPPED;
662                 /* Successful remap. */
663                 if (lcn >= 0) {
664                         /* Setup buffer head to point to correct block. */
665                         bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
666                                         vcn_ofs) >> blocksize_bits;
667                         set_buffer_mapped(bh);
668                         continue;
669                 }
670                 /* It is a hole, need to instantiate it. */
671                 if (lcn == LCN_HOLE) {
672                         // TODO: Instantiate the hole.
673                         // clear_buffer_new(bh);
674                         // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
675                         ntfs_error(vol->sb, "Writing into sparse regions is "
676                                         "not supported yet. Sorry.");
677                         err = -EOPNOTSUPP;
678                         break;
679                 }
680                 /* If first try and runlist unmapped, map and retry. */
681                 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
682                         is_retry = TRUE;
683                         /*
684                          * Attempt to map runlist, dropping lock for
685                          * the duration.
686                          */
687                         up_read(&ni->runlist.lock);
688                         err = ntfs_map_runlist(ni, vcn);
689                         if (likely(!err))
690                                 goto lock_retry_remap;
691                         rl = NULL;
692                         lcn = err;
693                 }
694                 /* Failed to map the buffer, even after retrying. */
695                 bh->b_blocknr = -1;
696                 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
697                                 "attribute type 0x%x, vcn 0x%llx, offset 0x%x "
698                                 "because its location on disk could not be "
699                                 "determined%s (error code %lli).", ni->mft_no,
700                                 ni->type, (unsigned long long)vcn,
701                                 vcn_ofs, is_retry ? " even after "
702                                 "retrying" : "", (long long)lcn);
703                 if (!err)
704                         err = -EIO;
705                 break;
706         } while (block++, (bh = bh->b_this_page) != head);
707
708         /* Release the lock if we took it. */
709         if (rl)
710                 up_read(&ni->runlist.lock);
711
712         /* For the error case, need to reset bh to the beginning. */
713         bh = head;
714
715         /* Just an optimization, so ->readpage() isn't called later. */
716         if (unlikely(!PageUptodate(page))) {
717                 int uptodate = 1;
718                 do {
719                         if (!buffer_uptodate(bh)) {
720                                 uptodate = 0;
721                                 bh = head;
722                                 break;
723                         }
724                 } while ((bh = bh->b_this_page) != head);
725                 if (uptodate)
726                         SetPageUptodate(page);
727         }
728
729         /* Setup all mapped, dirty buffers for async write i/o. */
730         do {
731                 get_bh(bh);
732                 if (buffer_mapped(bh) && buffer_dirty(bh)) {
733                         lock_buffer(bh);
734                         if (test_clear_buffer_dirty(bh)) {
735                                 BUG_ON(!buffer_uptodate(bh));
736                                 mark_buffer_async_write(bh);
737                         } else
738                                 unlock_buffer(bh);
739                 } else if (unlikely(err)) {
740                         /*
741                          * For the error case. The buffer may have been set
742                          * dirty during attachment to a dirty page.
743                          */
744                         if (err != -ENOMEM)
745                                 clear_buffer_dirty(bh);
746                 }
747         } while ((bh = bh->b_this_page) != head);
748
749         if (unlikely(err)) {
750                 // TODO: Remove the -EOPNOTSUPP check later on...
751                 if (unlikely(err == -EOPNOTSUPP))
752                         err = 0;
753                 else if (err == -ENOMEM) {
754                         ntfs_warning(vol->sb, "Error allocating memory. "
755                                         "Redirtying page so we try again "
756                                         "later.");
757                         /*
758                          * Put the page back on mapping->dirty_pages, but
759                          * leave its buffer's dirty state as-is.
760                          */
761                         redirty_page_for_writepage(wbc, page);
762                         err = 0;
763                 } else
764                         SetPageError(page);
765         }
766
767         BUG_ON(PageWriteback(page));
768         set_page_writeback(page);       /* Keeps try_to_free_buffers() away. */
769         unlock_page(page);
770
771         /*
772          * Submit the prepared buffers for i/o. Note the page is unlocked,
773          * and the async write i/o completion handler can end_page_writeback()
774          * at any time after the *first* submit_bh(). So the buffers can then
775          * disappear...
776          */
777         need_end_writeback = TRUE;
778         do {
779                 struct buffer_head *next = bh->b_this_page;
780                 if (buffer_async_write(bh)) {
781                         submit_bh(WRITE, bh);
782                         need_end_writeback = FALSE;
783                 }
784                 put_bh(bh);
785                 bh = next;
786         } while (bh != head);
787
788         /* If no i/o was started, need to end_page_writeback(). */
789         if (unlikely(need_end_writeback))
790                 end_page_writeback(page);
791
792         ntfs_debug("Done.");
793         return err;
794 }
795
796 /**
797  * ntfs_write_mst_block - write a @page to the backing store
798  * @page:       page cache page to write out
799  * @wbc:        writeback control structure
800  *
801  * This function is for writing pages belonging to non-resident, mst protected
802  * attributes to their backing store.  The only supported attributes are index
803  * allocation and $MFT/$DATA.  Both directory inodes and index inodes are
804  * supported for the index allocation case.
805  *
806  * The page must remain locked for the duration of the write because we apply
807  * the mst fixups, write, and then undo the fixups, so if we were to unlock the
808  * page before undoing the fixups, any other user of the page will see the
809  * page contents as corrupt.
810  *
811  * We clear the page uptodate flag for the duration of the function to ensure
812  * exclusion for the $MFT/$DATA case against someone mapping an mft record we
813  * are about to apply the mst fixups to.
814  *
815  * Return 0 on success and -errno on error.
816  *
817  * Based on ntfs_write_block(), ntfs_mft_writepage(), and
818  * write_mft_record_nolock().
819  */
820 static int ntfs_write_mst_block(struct page *page,
821                 struct writeback_control *wbc)
822 {
823         sector_t block, dblock, rec_block;
824         struct inode *vi = page->mapping->host;
825         ntfs_inode *ni = NTFS_I(vi);
826         ntfs_volume *vol = ni->vol;
827         u8 *kaddr;
828         unsigned int rec_size = ni->itype.index.block_size;
829         ntfs_inode *locked_nis[PAGE_CACHE_SIZE / rec_size];
830         struct buffer_head *bh, *head, *tbh, *rec_start_bh;
831         struct buffer_head *bhs[MAX_BUF_PER_PAGE];
832         runlist_element *rl;
833         int i, nr_locked_nis, nr_recs, nr_bhs, max_bhs, bhs_per_rec, err, err2;
834         unsigned bh_size, rec_size_bits;
835         BOOL sync, is_mft, page_is_dirty, rec_is_dirty;
836         unsigned char bh_size_bits;
837
838         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
839                         "0x%lx.", vi->i_ino, ni->type, page->index);
840         BUG_ON(!NInoNonResident(ni));
841         BUG_ON(!NInoMstProtected(ni));
842         is_mft = (S_ISREG(vi->i_mode) && !vi->i_ino);
843         /*
844          * NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page
845          * in its page cache were to be marked dirty.  However this should
846          * never happen with the current driver and considering we do not
847          * handle this case here we do want to BUG(), at least for now.
848          */
849         BUG_ON(!(is_mft || S_ISDIR(vi->i_mode) ||
850                         (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
851         bh_size_bits = vi->i_blkbits;
852         bh_size = 1 << bh_size_bits;
853         max_bhs = PAGE_CACHE_SIZE / bh_size;
854         BUG_ON(!max_bhs);
855         BUG_ON(max_bhs > MAX_BUF_PER_PAGE);
856
857         /* Were we called for sync purposes? */
858         sync = (wbc->sync_mode == WB_SYNC_ALL);
859
860         /* Make sure we have mapped buffers. */
861         BUG_ON(!page_has_buffers(page));
862         bh = head = page_buffers(page);
863         BUG_ON(!bh);
864
865         rec_size_bits = ni->itype.index.block_size_bits;
866         BUG_ON(!(PAGE_CACHE_SIZE >> rec_size_bits));
867         bhs_per_rec = rec_size >> bh_size_bits;
868         BUG_ON(!bhs_per_rec);
869
870         /* The first block in the page. */
871         rec_block = block = (sector_t)page->index <<
872                         (PAGE_CACHE_SHIFT - bh_size_bits);
873
874         /* The first out of bounds block for the data size. */
875         dblock = (i_size_read(vi) + bh_size - 1) >> bh_size_bits;
876
877         rl = NULL;
878         err = err2 = nr_bhs = nr_recs = nr_locked_nis = 0;
879         page_is_dirty = rec_is_dirty = FALSE;
880         rec_start_bh = NULL;
881         do {
882                 BOOL is_retry = FALSE;
883
884                 if (likely(block < rec_block)) {
885                         if (unlikely(block >= dblock)) {
886                                 clear_buffer_dirty(bh);
887                                 set_buffer_uptodate(bh);
888                                 continue;
889                         }
890                         /*
891                          * This block is not the first one in the record.  We
892                          * ignore the buffer's dirty state because we could
893                          * have raced with a parallel mark_ntfs_record_dirty().
894                          */
895                         if (!rec_is_dirty)
896                                 continue;
897                         if (unlikely(err2)) {
898                                 if (err2 != -ENOMEM)
899                                         clear_buffer_dirty(bh);
900                                 continue;
901                         }
902                 } else /* if (block == rec_block) */ {
903                         BUG_ON(block > rec_block);
904                         /* This block is the first one in the record. */
905                         rec_block += bhs_per_rec;
906                         err2 = 0;
907                         if (unlikely(block >= dblock)) {
908                                 clear_buffer_dirty(bh);
909                                 continue;
910                         }
911                         if (!buffer_dirty(bh)) {
912                                 /* Clean records are not written out. */
913                                 rec_is_dirty = FALSE;
914                                 continue;
915                         }
916                         rec_is_dirty = TRUE;
917                         rec_start_bh = bh;
918                 }
919                 /* Need to map the buffer if it is not mapped already. */
920                 if (unlikely(!buffer_mapped(bh))) {
921                         VCN vcn;
922                         LCN lcn;
923                         unsigned int vcn_ofs;
924
925                         /* Obtain the vcn and offset of the current block. */
926                         vcn = (VCN)block << bh_size_bits;
927                         vcn_ofs = vcn & vol->cluster_size_mask;
928                         vcn >>= vol->cluster_size_bits;
929                         if (!rl) {
930 lock_retry_remap:
931                                 down_read(&ni->runlist.lock);
932                                 rl = ni->runlist.rl;
933                         }
934                         if (likely(rl != NULL)) {
935                                 /* Seek to element containing target vcn. */
936                                 while (rl->length && rl[1].vcn <= vcn)
937                                         rl++;
938                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
939                         } else
940                                 lcn = LCN_RL_NOT_MAPPED;
941                         /* Successful remap. */
942                         if (likely(lcn >= 0)) {
943                                 /* Setup buffer head to correct block. */
944                                 bh->b_blocknr = ((lcn <<
945                                                 vol->cluster_size_bits) +
946                                                 vcn_ofs) >> bh_size_bits;
947                                 set_buffer_mapped(bh);
948                         } else {
949                                 /*
950                                  * Remap failed.  Retry to map the runlist once
951                                  * unless we are working on $MFT which always
952                                  * has the whole of its runlist in memory.
953                                  */
954                                 if (!is_mft && !is_retry &&
955                                                 lcn == LCN_RL_NOT_MAPPED) {
956                                         is_retry = TRUE;
957                                         /*
958                                          * Attempt to map runlist, dropping
959                                          * lock for the duration.
960                                          */
961                                         up_read(&ni->runlist.lock);
962                                         err2 = ntfs_map_runlist(ni, vcn);
963                                         if (likely(!err2))
964                                                 goto lock_retry_remap;
965                                         if (err2 == -ENOMEM)
966                                                 page_is_dirty = TRUE;
967                                         lcn = err2;
968                                 } else
969                                         err2 = -EIO;
970                                 /* Hard error.  Abort writing this record. */
971                                 if (!err || err == -ENOMEM)
972                                         err = err2;
973                                 bh->b_blocknr = -1;
974                                 ntfs_error(vol->sb, "Cannot write ntfs record "
975                                                 "0x%llx (inode 0x%lx, "
976                                                 "attribute type 0x%x) because "
977                                                 "its location on disk could "
978                                                 "not be determined (error "
979                                                 "code %lli).",
980                                                 (long long)block <<
981                                                 bh_size_bits >>
982                                                 vol->mft_record_size_bits,
983                                                 ni->mft_no, ni->type,
984                                                 (long long)lcn);
985                                 /*
986                                  * If this is not the first buffer, remove the
987                                  * buffers in this record from the list of
988                                  * buffers to write and clear their dirty bit
989                                  * if not error -ENOMEM.
990                                  */
991                                 if (rec_start_bh != bh) {
992                                         while (bhs[--nr_bhs] != rec_start_bh)
993                                                 ;
994                                         if (err2 != -ENOMEM) {
995                                                 do {
996                                                         clear_buffer_dirty(
997                                                                 rec_start_bh);
998                                                 } while ((rec_start_bh =
999                                                                 rec_start_bh->
1000                                                                 b_this_page) !=
1001                                                                 bh);
1002                                         }
1003                                 }
1004                                 continue;
1005                         }
1006                 }
1007                 BUG_ON(!buffer_uptodate(bh));
1008                 BUG_ON(nr_bhs >= max_bhs);
1009                 bhs[nr_bhs++] = bh;
1010         } while (block++, (bh = bh->b_this_page) != head);
1011         if (unlikely(rl))
1012                 up_read(&ni->runlist.lock);
1013         /* If there were no dirty buffers, we are done. */
1014         if (!nr_bhs)
1015                 goto done;
1016         /* Map the page so we can access its contents. */
1017         kaddr = kmap(page);
1018         /* Clear the page uptodate flag whilst the mst fixups are applied. */
1019         BUG_ON(!PageUptodate(page));
1020         ClearPageUptodate(page);
1021         for (i = 0; i < nr_bhs; i++) {
1022                 unsigned int ofs;
1023
1024                 /* Skip buffers which are not at the beginning of records. */
1025                 if (i % bhs_per_rec)
1026                         continue;
1027                 tbh = bhs[i];
1028                 ofs = bh_offset(tbh);
1029                 if (is_mft) {
1030                         ntfs_inode *tni;
1031                         unsigned long mft_no;
1032
1033                         /* Get the mft record number. */
1034                         mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1035                                         >> rec_size_bits;
1036                         /* Check whether to write this mft record. */
1037                         tni = NULL;
1038                         if (!ntfs_may_write_mft_record(vol, mft_no,
1039                                         (MFT_RECORD*)(kaddr + ofs), &tni)) {
1040                                 /*
1041                                  * The record should not be written.  This
1042                                  * means we need to redirty the page before
1043                                  * returning.
1044                                  */
1045                                 page_is_dirty = TRUE;
1046                                 /*
1047                                  * Remove the buffers in this mft record from
1048                                  * the list of buffers to write.
1049                                  */
1050                                 do {
1051                                         bhs[i] = NULL;
1052                                 } while (++i % bhs_per_rec);
1053                                 continue;
1054                         }
1055                         /*
1056                          * The record should be written.  If a locked ntfs
1057                          * inode was returned, add it to the array of locked
1058                          * ntfs inodes.
1059                          */
1060                         if (tni)
1061                                 locked_nis[nr_locked_nis++] = tni;
1062                 }
1063                 /* Apply the mst protection fixups. */
1064                 err2 = pre_write_mst_fixup((NTFS_RECORD*)(kaddr + ofs),
1065                                 rec_size);
1066                 if (unlikely(err2)) {
1067                         if (!err || err == -ENOMEM)
1068                                 err = -EIO;
1069                         ntfs_error(vol->sb, "Failed to apply mst fixups "
1070                                         "(inode 0x%lx, attribute type 0x%x, "
1071                                         "page index 0x%lx, page offset 0x%x)!"
1072                                         "  Unmount and run chkdsk.", vi->i_ino,
1073                                         ni->type, page->index, ofs);
1074                         /*
1075                          * Mark all the buffers in this record clean as we do
1076                          * not want to write corrupt data to disk.
1077                          */
1078                         do {
1079                                 clear_buffer_dirty(bhs[i]);
1080                                 bhs[i] = NULL;
1081                         } while (++i % bhs_per_rec);
1082                         continue;
1083                 }
1084                 nr_recs++;
1085         }
1086         /* If no records are to be written out, we are done. */
1087         if (!nr_recs)
1088                 goto unm_done;
1089         flush_dcache_page(page);
1090         /* Lock buffers and start synchronous write i/o on them. */
1091         for (i = 0; i < nr_bhs; i++) {
1092                 tbh = bhs[i];
1093                 if (!tbh)
1094                         continue;
1095                 if (unlikely(test_set_buffer_locked(tbh)))
1096                         BUG();
1097                 /* The buffer dirty state is now irrelevant, just clean it. */
1098                 clear_buffer_dirty(tbh);
1099                 BUG_ON(!buffer_uptodate(tbh));
1100                 BUG_ON(!buffer_mapped(tbh));
1101                 get_bh(tbh);
1102                 tbh->b_end_io = end_buffer_write_sync;
1103                 submit_bh(WRITE, tbh);
1104         }
1105         /* Synchronize the mft mirror now if not @sync. */
1106         if (is_mft && !sync)
1107                 goto do_mirror;
1108 do_wait:
1109         /* Wait on i/o completion of buffers. */
1110         for (i = 0; i < nr_bhs; i++) {
1111                 tbh = bhs[i];
1112                 if (!tbh)
1113                         continue;
1114                 wait_on_buffer(tbh);
1115                 if (unlikely(!buffer_uptodate(tbh))) {
1116                         ntfs_error(vol->sb, "I/O error while writing ntfs "
1117                                         "record buffer (inode 0x%lx, "
1118                                         "attribute type 0x%x, page index "
1119                                         "0x%lx, page offset 0x%lx)!  Unmount "
1120                                         "and run chkdsk.", vi->i_ino, ni->type,
1121                                         page->index, bh_offset(tbh));
1122                         if (!err || err == -ENOMEM)
1123                                 err = -EIO;
1124                         /*
1125                          * Set the buffer uptodate so the page and buffer
1126                          * states do not become out of sync.
1127                          */
1128                         set_buffer_uptodate(tbh);
1129                 }
1130         }
1131         /* If @sync, now synchronize the mft mirror. */
1132         if (is_mft && sync) {
1133 do_mirror:
1134                 for (i = 0; i < nr_bhs; i++) {
1135                         unsigned long mft_no;
1136                         unsigned int ofs;
1137
1138                         /*
1139                          * Skip buffers which are not at the beginning of
1140                          * records.
1141                          */
1142                         if (i % bhs_per_rec)
1143                                 continue;
1144                         tbh = bhs[i];
1145                         /* Skip removed buffers (and hence records). */
1146                         if (!tbh)
1147                                 continue;
1148                         ofs = bh_offset(tbh);
1149                         /* Get the mft record number. */
1150                         mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1151                                         >> rec_size_bits;
1152                         if (mft_no < vol->mftmirr_size)
1153                                 ntfs_sync_mft_mirror(vol, mft_no,
1154                                                 (MFT_RECORD*)(kaddr + ofs),
1155                                                 sync);
1156                 }
1157                 if (!sync)
1158                         goto do_wait;
1159         }
1160         /* Remove the mst protection fixups again. */
1161         for (i = 0; i < nr_bhs; i++) {
1162                 if (!(i % bhs_per_rec)) {
1163                         tbh = bhs[i];
1164                         if (!tbh)
1165                                 continue;
1166                         post_write_mst_fixup((NTFS_RECORD*)(kaddr +
1167                                         bh_offset(tbh)));
1168                 }
1169         }
1170         flush_dcache_page(page);
1171 unm_done:
1172         /* Unlock any locked inodes. */
1173         while (nr_locked_nis-- > 0) {
1174                 ntfs_inode *tni, *base_tni;
1175                 
1176                 tni = locked_nis[nr_locked_nis];
1177                 /* Get the base inode. */
1178                 down(&tni->extent_lock);
1179                 if (tni->nr_extents >= 0)
1180                         base_tni = tni;
1181                 else {
1182                         base_tni = tni->ext.base_ntfs_ino;
1183                         BUG_ON(!base_tni);
1184                 }
1185                 up(&tni->extent_lock);
1186                 ntfs_debug("Unlocking %s inode 0x%lx.",
1187                                 tni == base_tni ? "base" : "extent",
1188                                 tni->mft_no);
1189                 up(&tni->mrec_lock);
1190                 atomic_dec(&tni->count);
1191                 iput(VFS_I(base_tni));
1192         }
1193         SetPageUptodate(page);
1194         kunmap(page);
1195 done:
1196         if (unlikely(err && err != -ENOMEM)) {
1197                 /*
1198                  * Set page error if there is only one ntfs record in the page.
1199                  * Otherwise we would loose per-record granularity.
1200                  */
1201                 if (ni->itype.index.block_size == PAGE_CACHE_SIZE)
1202                         SetPageError(page);
1203                 NVolSetErrors(vol);
1204         }
1205         if (page_is_dirty) {
1206                 ntfs_debug("Page still contains one or more dirty ntfs "
1207                                 "records.  Redirtying the page starting at "
1208                                 "record 0x%lx.", page->index <<
1209                                 (PAGE_CACHE_SHIFT - rec_size_bits));
1210                 redirty_page_for_writepage(wbc, page);
1211                 unlock_page(page);
1212         } else {
1213                 /*
1214                  * Keep the VM happy.  This must be done otherwise the
1215                  * radix-tree tag PAGECACHE_TAG_DIRTY remains set even though
1216                  * the page is clean.
1217                  */
1218                 BUG_ON(PageWriteback(page));
1219                 set_page_writeback(page);
1220                 unlock_page(page);
1221                 end_page_writeback(page);
1222         }
1223         if (likely(!err))
1224                 ntfs_debug("Done.");
1225         return err;
1226 }
1227
1228 /**
1229  * ntfs_writepage - write a @page to the backing store
1230  * @page:       page cache page to write out
1231  * @wbc:        writeback control structure
1232  *
1233  * This is called from the VM when it wants to have a dirty ntfs page cache
1234  * page cleaned.  The VM has already locked the page and marked it clean.
1235  *
1236  * For non-resident attributes, ntfs_writepage() writes the @page by calling
1237  * the ntfs version of the generic block_write_full_page() function,
1238  * ntfs_write_block(), which in turn if necessary creates and writes the
1239  * buffers associated with the page asynchronously.
1240  *
1241  * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1242  * the data to the mft record (which at this stage is most likely in memory).
1243  * The mft record is then marked dirty and written out asynchronously via the
1244  * vfs inode dirty code path for the inode the mft record belongs to or via the
1245  * vm page dirty code path for the page the mft record is in.
1246  *
1247  * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1248  *
1249  * Return 0 on success and -errno on error.
1250  */
1251 static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1252 {
1253         loff_t i_size;
1254         struct inode *vi = page->mapping->host;
1255         ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1256         char *kaddr;
1257         ntfs_attr_search_ctx *ctx = NULL;
1258         MFT_RECORD *m = NULL;
1259         u32 attr_len;
1260         int err;
1261
1262 retry_writepage:
1263         BUG_ON(!PageLocked(page));
1264         i_size = i_size_read(vi);
1265         /* Is the page fully outside i_size? (truncate in progress) */
1266         if (unlikely(page->index >= (i_size + PAGE_CACHE_SIZE - 1) >>
1267                         PAGE_CACHE_SHIFT)) {
1268                 /*
1269                  * The page may have dirty, unmapped buffers.  Make them
1270                  * freeable here, so the page does not leak.
1271                  */
1272                 block_invalidatepage(page, 0);
1273                 unlock_page(page);
1274                 ntfs_debug("Write outside i_size - truncated?");
1275                 return 0;
1276         }
1277         /* NInoNonResident() == NInoIndexAllocPresent() */
1278         if (NInoNonResident(ni)) {
1279                 /*
1280                  * Only unnamed $DATA attributes can be compressed, encrypted,
1281                  * and/or sparse.
1282                  */
1283                 if (ni->type == AT_DATA && !ni->name_len) {
1284                         /* If file is encrypted, deny access, just like NT4. */
1285                         if (NInoEncrypted(ni)) {
1286                                 unlock_page(page);
1287                                 ntfs_debug("Denying write access to encrypted "
1288                                                 "file.");
1289                                 return -EACCES;
1290                         }
1291                         /* Compressed data streams are handled in compress.c. */
1292                         if (NInoCompressed(ni)) {
1293                                 // TODO: Implement and replace this check with
1294                                 // return ntfs_write_compressed_block(page);
1295                                 unlock_page(page);
1296                                 ntfs_error(vi->i_sb, "Writing to compressed "
1297                                                 "files is not supported yet. "
1298                                                 "Sorry.");
1299                                 return -EOPNOTSUPP;
1300                         }
1301                         // TODO: Implement and remove this check.
1302                         if (NInoSparse(ni)) {
1303                                 unlock_page(page);
1304                                 ntfs_error(vi->i_sb, "Writing to sparse files "
1305                                                 "is not supported yet. Sorry.");
1306                                 return -EOPNOTSUPP;
1307                         }
1308                 }
1309                 /* We have to zero every time due to mmap-at-end-of-file. */
1310                 if (page->index >= (i_size >> PAGE_CACHE_SHIFT)) {
1311                         /* The page straddles i_size. */
1312                         unsigned int ofs = i_size & ~PAGE_CACHE_MASK;
1313                         kaddr = kmap_atomic(page, KM_USER0);
1314                         memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1315                         flush_dcache_page(page);
1316                         kunmap_atomic(kaddr, KM_USER0);
1317                 }
1318                 /* Handle mst protected attributes. */
1319                 if (NInoMstProtected(ni))
1320                         return ntfs_write_mst_block(page, wbc);
1321                 /* Normal data stream. */
1322                 return ntfs_write_block(page, wbc);
1323         }
1324         /*
1325          * Attribute is resident, implying it is not compressed, encrypted,
1326          * sparse, or mst protected.  This also means the attribute is smaller
1327          * than an mft record and hence smaller than a page, so can simply
1328          * return error on any pages with index above 0.
1329          */
1330         BUG_ON(page_has_buffers(page));
1331         BUG_ON(!PageUptodate(page));
1332         if (unlikely(page->index > 0)) {
1333                 ntfs_error(vi->i_sb, "BUG()! page->index (0x%lx) > 0.  "
1334                                 "Aborting write.", page->index);
1335                 BUG_ON(PageWriteback(page));
1336                 set_page_writeback(page);
1337                 unlock_page(page);
1338                 end_page_writeback(page);
1339                 return -EIO;
1340         }
1341         if (!NInoAttr(ni))
1342                 base_ni = ni;
1343         else
1344                 base_ni = ni->ext.base_ntfs_ino;
1345         /* Map, pin, and lock the mft record. */
1346         m = map_mft_record(base_ni);
1347         if (IS_ERR(m)) {
1348                 err = PTR_ERR(m);
1349                 m = NULL;
1350                 ctx = NULL;
1351                 goto err_out;
1352         }
1353         /*
1354          * If a parallel write made the attribute non-resident, drop the mft
1355          * record and retry the writepage.
1356          */
1357         if (unlikely(NInoNonResident(ni))) {
1358                 unmap_mft_record(base_ni);
1359                 goto retry_writepage;
1360         }
1361         ctx = ntfs_attr_get_search_ctx(base_ni, m);
1362         if (unlikely(!ctx)) {
1363                 err = -ENOMEM;
1364                 goto err_out;
1365         }
1366         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1367                         CASE_SENSITIVE, 0, NULL, 0, ctx);
1368         if (unlikely(err))
1369                 goto err_out;
1370         /*
1371          * Keep the VM happy.  This must be done otherwise the radix-tree tag
1372          * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1373          */
1374         BUG_ON(PageWriteback(page));
1375         set_page_writeback(page);
1376         unlock_page(page);
1377
1378         /*
1379          * Here, we don't need to zero the out of bounds area everytime because
1380          * the below memcpy() already takes care of the mmap-at-end-of-file
1381          * requirements. If the file is converted to a non-resident one, then
1382          * the code path use is switched to the non-resident one where the
1383          * zeroing happens on each ntfs_writepage() invocation.
1384          *
1385          * The above also applies nicely when i_size is decreased.
1386          *
1387          * When i_size is increased, the memory between the old and new i_size
1388          * _must_ be zeroed (or overwritten with new data). Otherwise we will
1389          * expose data to userspace/disk which should never have been exposed.
1390          *
1391          * FIXME: Ensure that i_size increases do the zeroing/overwriting and
1392          * if we cannot guarantee that, then enable the zeroing below.  If the
1393          * zeroing below is enabled, we MUST move the unlock_page() from above
1394          * to after the kunmap_atomic(), i.e. just before the
1395          * end_page_writeback().
1396          * UPDATE: ntfs_prepare/commit_write() do the zeroing on i_size
1397          * increases for resident attributes so those are ok.
1398          * TODO: ntfs_truncate(), others?
1399          */
1400
1401         attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
1402         i_size = i_size_read(vi);
1403         if (unlikely(attr_len > i_size)) {
1404                 attr_len = i_size;
1405                 ctx->attr->data.resident.value_length = cpu_to_le32(attr_len);
1406         }
1407         kaddr = kmap_atomic(page, KM_USER0);
1408         /* Copy the data from the page to the mft record. */
1409         memcpy((u8*)ctx->attr +
1410                         le16_to_cpu(ctx->attr->data.resident.value_offset),
1411                         kaddr, attr_len);
1412         flush_dcache_mft_record_page(ctx->ntfs_ino);
1413         /* Zero out of bounds area in the page cache page. */
1414         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1415         flush_dcache_page(page);
1416         kunmap_atomic(kaddr, KM_USER0);
1417
1418         end_page_writeback(page);
1419
1420         /* Mark the mft record dirty, so it gets written back. */
1421         mark_mft_record_dirty(ctx->ntfs_ino);
1422         ntfs_attr_put_search_ctx(ctx);
1423         unmap_mft_record(base_ni);
1424         return 0;
1425 err_out:
1426         if (err == -ENOMEM) {
1427                 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1428                                 "page so we try again later.");
1429                 /*
1430                  * Put the page back on mapping->dirty_pages, but leave its
1431                  * buffers' dirty state as-is.
1432                  */
1433                 redirty_page_for_writepage(wbc, page);
1434                 err = 0;
1435         } else {
1436                 ntfs_error(vi->i_sb, "Resident attribute write failed with "
1437                                 "error %i.", err);
1438                 SetPageError(page);
1439                 NVolSetErrors(ni->vol);
1440                 make_bad_inode(vi);
1441         }
1442         unlock_page(page);
1443         if (ctx)
1444                 ntfs_attr_put_search_ctx(ctx);
1445         if (m)
1446                 unmap_mft_record(base_ni);
1447         return err;
1448 }
1449
1450 /**
1451  * ntfs_prepare_nonresident_write -
1452  *
1453  */
1454 static int ntfs_prepare_nonresident_write(struct page *page,
1455                 unsigned from, unsigned to)
1456 {
1457         VCN vcn;
1458         LCN lcn;
1459         s64 initialized_size;
1460         loff_t i_size;
1461         sector_t block, ablock, iblock;
1462         struct inode *vi;
1463         ntfs_inode *ni;
1464         ntfs_volume *vol;
1465         runlist_element *rl;
1466         struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1467         unsigned long flags;
1468         unsigned int vcn_ofs, block_start, block_end, blocksize;
1469         int err;
1470         BOOL is_retry;
1471         unsigned char blocksize_bits;
1472
1473         vi = page->mapping->host;
1474         ni = NTFS_I(vi);
1475         vol = ni->vol;
1476
1477         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1478                         "0x%lx, from = %u, to = %u.", ni->mft_no, ni->type,
1479                         page->index, from, to);
1480
1481         BUG_ON(!NInoNonResident(ni));
1482
1483         blocksize_bits = vi->i_blkbits;
1484         blocksize = 1 << blocksize_bits;
1485
1486         /*
1487          * create_empty_buffers() will create uptodate/dirty buffers if the
1488          * page is uptodate/dirty.
1489          */
1490         if (!page_has_buffers(page))
1491                 create_empty_buffers(page, blocksize, 0);
1492         bh = head = page_buffers(page);
1493         if (unlikely(!bh))
1494                 return -ENOMEM;
1495
1496         /* The first block in the page. */
1497         block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
1498
1499         read_lock_irqsave(&ni->size_lock, flags);
1500         /*
1501          * The first out of bounds block for the allocated size.  No need to
1502          * round up as allocated_size is in multiples of cluster size and the
1503          * minimum cluster size is 512 bytes, which is equal to the smallest
1504          * blocksize.
1505          */
1506         ablock = ni->allocated_size >> blocksize_bits;
1507         i_size = i_size_read(vi);
1508         initialized_size = ni->initialized_size;
1509         read_unlock_irqrestore(&ni->size_lock, flags);
1510
1511         /* The last (fully or partially) initialized block. */
1512         iblock = initialized_size >> blocksize_bits;
1513
1514         /* Loop through all the buffers in the page. */
1515         block_start = 0;
1516         rl = NULL;
1517         err = 0;
1518         do {
1519                 block_end = block_start + blocksize;
1520                 /*
1521                  * If buffer @bh is outside the write, just mark it uptodate
1522                  * if the page is uptodate and continue with the next buffer.
1523                  */
1524                 if (block_end <= from || block_start >= to) {
1525                         if (PageUptodate(page)) {
1526                                 if (!buffer_uptodate(bh))
1527                                         set_buffer_uptodate(bh);
1528                         }
1529                         continue;
1530                 }
1531                 /*
1532                  * @bh is at least partially being written to.
1533                  * Make sure it is not marked as new.
1534                  */
1535                 //if (buffer_new(bh))
1536                 //      clear_buffer_new(bh);
1537
1538                 if (block >= ablock) {
1539                         // TODO: block is above allocated_size, need to
1540                         // allocate it. Best done in one go to accommodate not
1541                         // only block but all above blocks up to and including:
1542                         // ((page->index << PAGE_CACHE_SHIFT) + to + blocksize
1543                         // - 1) >> blobksize_bits. Obviously will need to round
1544                         // up to next cluster boundary, too. This should be
1545                         // done with a helper function, so it can be reused.
1546                         ntfs_error(vol->sb, "Writing beyond allocated size "
1547                                         "is not supported yet. Sorry.");
1548                         err = -EOPNOTSUPP;
1549                         goto err_out;
1550                         // Need to update ablock.
1551                         // Need to set_buffer_new() on all block bhs that are
1552                         // newly allocated.
1553                 }
1554                 /*
1555                  * Now we have enough allocated size to fulfill the whole
1556                  * request, i.e. block < ablock is true.
1557                  */
1558                 if (unlikely((block >= iblock) &&
1559                                 (initialized_size < i_size))) {
1560                         /*
1561                          * If this page is fully outside initialized size, zero
1562                          * out all pages between the current initialized size
1563                          * and the current page. Just use ntfs_readpage() to do
1564                          * the zeroing transparently.
1565                          */
1566                         if (block > iblock) {
1567                                 // TODO:
1568                                 // For each page do:
1569                                 // - read_cache_page()
1570                                 // Again for each page do:
1571                                 // - wait_on_page_locked()
1572                                 // - Check (PageUptodate(page) &&
1573                                 //                      !PageError(page))
1574                                 // Update initialized size in the attribute and
1575                                 // in the inode.
1576                                 // Again, for each page do:
1577                                 //      __set_page_dirty_buffers();
1578                                 // page_cache_release()
1579                                 // We don't need to wait on the writes.
1580                                 // Update iblock.
1581                         }
1582                         /*
1583                          * The current page straddles initialized size. Zero
1584                          * all non-uptodate buffers and set them uptodate (and
1585                          * dirty?). Note, there aren't any non-uptodate buffers
1586                          * if the page is uptodate.
1587                          * FIXME: For an uptodate page, the buffers may need to
1588                          * be written out because they were not initialized on
1589                          * disk before.
1590                          */
1591                         if (!PageUptodate(page)) {
1592                                 // TODO:
1593                                 // Zero any non-uptodate buffers up to i_size.
1594                                 // Set them uptodate and dirty.
1595                         }
1596                         // TODO:
1597                         // Update initialized size in the attribute and in the
1598                         // inode (up to i_size).
1599                         // Update iblock.
1600                         // FIXME: This is inefficient. Try to batch the two
1601                         // size changes to happen in one go.
1602                         ntfs_error(vol->sb, "Writing beyond initialized size "
1603                                         "is not supported yet. Sorry.");
1604                         err = -EOPNOTSUPP;
1605                         goto err_out;
1606                         // Do NOT set_buffer_new() BUT DO clear buffer range
1607                         // outside write request range.
1608                         // set_buffer_uptodate() on complete buffers as well as
1609                         // set_buffer_dirty().
1610                 }
1611
1612                 /* Need to map unmapped buffers. */
1613                 if (!buffer_mapped(bh)) {
1614                         /* Unmapped buffer. Need to map it. */
1615                         bh->b_bdev = vol->sb->s_bdev;
1616
1617                         /* Convert block into corresponding vcn and offset. */
1618                         vcn = (VCN)block << blocksize_bits >>
1619                                         vol->cluster_size_bits;
1620                         vcn_ofs = ((VCN)block << blocksize_bits) &
1621                                         vol->cluster_size_mask;
1622
1623                         is_retry = FALSE;
1624                         if (!rl) {
1625 lock_retry_remap:
1626                                 down_read(&ni->runlist.lock);
1627                                 rl = ni->runlist.rl;
1628                         }
1629                         if (likely(rl != NULL)) {
1630                                 /* Seek to element containing target vcn. */
1631                                 while (rl->length && rl[1].vcn <= vcn)
1632                                         rl++;
1633                                 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1634                         } else
1635                                 lcn = LCN_RL_NOT_MAPPED;
1636                         if (unlikely(lcn < 0)) {
1637                                 /*
1638                                  * We extended the attribute allocation above.
1639                                  * If we hit an ENOENT here it means that the
1640                                  * allocation was insufficient which is a bug.
1641                                  */
1642                                 BUG_ON(lcn == LCN_ENOENT);
1643
1644                                 /* It is a hole, need to instantiate it. */
1645                                 if (lcn == LCN_HOLE) {
1646                                         // TODO: Instantiate the hole.
1647                                         // clear_buffer_new(bh);
1648                                         // unmap_underlying_metadata(bh->b_bdev,
1649                                         //              bh->b_blocknr);
1650                                         // For non-uptodate buffers, need to
1651                                         // zero out the region outside the
1652                                         // request in this bh or all bhs,
1653                                         // depending on what we implemented
1654                                         // above.
1655                                         // Need to flush_dcache_page().
1656                                         // Or could use set_buffer_new()
1657                                         // instead?
1658                                         ntfs_error(vol->sb, "Writing into "
1659                                                         "sparse regions is "
1660                                                         "not supported yet. "
1661                                                         "Sorry.");
1662                                         err = -EOPNOTSUPP;
1663                                         goto err_out;
1664                                 } else if (!is_retry &&
1665                                                 lcn == LCN_RL_NOT_MAPPED) {
1666                                         is_retry = TRUE;
1667                                         /*
1668                                          * Attempt to map runlist, dropping
1669                                          * lock for the duration.
1670                                          */
1671                                         up_read(&ni->runlist.lock);
1672                                         err = ntfs_map_runlist(ni, vcn);
1673                                         if (likely(!err))
1674                                                 goto lock_retry_remap;
1675                                         rl = NULL;
1676                                         lcn = err;
1677                                 }
1678                                 /*
1679                                  * Failed to map the buffer, even after
1680                                  * retrying.
1681                                  */
1682                                 bh->b_blocknr = -1;
1683                                 ntfs_error(vol->sb, "Failed to write to inode "
1684                                                 "0x%lx, attribute type 0x%x, "
1685                                                 "vcn 0x%llx, offset 0x%x "
1686                                                 "because its location on disk "
1687                                                 "could not be determined%s "
1688                                                 "(error code %lli).",
1689                                                 ni->mft_no, ni->type,
1690                                                 (unsigned long long)vcn,
1691                                                 vcn_ofs, is_retry ? " even "
1692                                                 "after retrying" : "",
1693                                                 (long long)lcn);
1694                                 if (!err)
1695                                         err = -EIO;
1696                                 goto err_out;
1697                         }
1698                         /* We now have a successful remap, i.e. lcn >= 0. */
1699
1700                         /* Setup buffer head to correct block. */
1701                         bh->b_blocknr = ((lcn << vol->cluster_size_bits)
1702                                         + vcn_ofs) >> blocksize_bits;
1703                         set_buffer_mapped(bh);
1704
1705                         // FIXME: Something analogous to this is needed for
1706                         // each newly allocated block, i.e. BH_New.
1707                         // FIXME: Might need to take this out of the
1708                         // if (!buffer_mapped(bh)) {}, depending on how we
1709                         // implement things during the allocated_size and
1710                         // initialized_size extension code above.
1711                         if (buffer_new(bh)) {
1712                                 clear_buffer_new(bh);
1713                                 unmap_underlying_metadata(bh->b_bdev,
1714                                                 bh->b_blocknr);
1715                                 if (PageUptodate(page)) {
1716                                         set_buffer_uptodate(bh);
1717                                         continue;
1718                                 }
1719                                 /*
1720                                  * Page is _not_ uptodate, zero surrounding
1721                                  * region. NOTE: This is how we decide if to
1722                                  * zero or not!
1723                                  */
1724                                 if (block_end > to || block_start < from) {
1725                                         void *kaddr;
1726
1727                                         kaddr = kmap_atomic(page, KM_USER0);
1728                                         if (block_end > to)
1729                                                 memset(kaddr + to, 0,
1730                                                                 block_end - to);
1731                                         if (block_start < from)
1732                                                 memset(kaddr + block_start, 0,
1733                                                                 from -
1734                                                                 block_start);
1735                                         flush_dcache_page(page);
1736                                         kunmap_atomic(kaddr, KM_USER0);
1737                                 }
1738                                 continue;
1739                         }
1740                 }
1741                 /* @bh is mapped, set it uptodate if the page is uptodate. */
1742                 if (PageUptodate(page)) {
1743                         if (!buffer_uptodate(bh))
1744                                 set_buffer_uptodate(bh);
1745                         continue;
1746                 }
1747                 /*
1748                  * The page is not uptodate. The buffer is mapped. If it is not
1749                  * uptodate, and it is only partially being written to, we need
1750                  * to read the buffer in before the write, i.e. right now.
1751                  */
1752                 if (!buffer_uptodate(bh) &&
1753                                 (block_start < from || block_end > to)) {
1754                         ll_rw_block(READ, 1, &bh);
1755                         *wait_bh++ = bh;
1756                 }
1757         } while (block++, block_start = block_end,
1758                         (bh = bh->b_this_page) != head);
1759
1760         /* Release the lock if we took it. */
1761         if (rl) {
1762                 up_read(&ni->runlist.lock);
1763                 rl = NULL;
1764         }
1765
1766         /* If we issued read requests, let them complete. */
1767         while (wait_bh > wait) {
1768                 wait_on_buffer(*--wait_bh);
1769                 if (!buffer_uptodate(*wait_bh))
1770                         return -EIO;
1771         }
1772
1773         ntfs_debug("Done.");
1774         return 0;
1775 err_out:
1776         /*
1777          * Zero out any newly allocated blocks to avoid exposing stale data.
1778          * If BH_New is set, we know that the block was newly allocated in the
1779          * above loop.
1780          * FIXME: What about initialized_size increments? Have we done all the
1781          * required zeroing above? If not this error handling is broken, and
1782          * in particular the if (block_end <= from) check is completely bogus.
1783          */
1784         bh = head;
1785         block_start = 0;
1786         is_retry = FALSE;
1787         do {
1788                 block_end = block_start + blocksize;
1789                 if (block_end <= from)
1790                         continue;
1791                 if (block_start >= to)
1792                         break;
1793                 if (buffer_new(bh)) {
1794                         void *kaddr;
1795
1796                         clear_buffer_new(bh);
1797                         kaddr = kmap_atomic(page, KM_USER0);
1798                         memset(kaddr + block_start, 0, bh->b_size);
1799                         kunmap_atomic(kaddr, KM_USER0);
1800                         set_buffer_uptodate(bh);
1801                         mark_buffer_dirty(bh);
1802                         is_retry = TRUE;
1803                 }
1804         } while (block_start = block_end, (bh = bh->b_this_page) != head);
1805         if (is_retry)
1806                 flush_dcache_page(page);
1807         if (rl)
1808                 up_read(&ni->runlist.lock);
1809         return err;
1810 }
1811
1812 /**
1813  * ntfs_prepare_write - prepare a page for receiving data
1814  *
1815  * This is called from generic_file_write() with i_sem held on the inode
1816  * (@page->mapping->host).  The @page is locked but not kmap()ped.  The source
1817  * data has not yet been copied into the @page.
1818  *
1819  * Need to extend the attribute/fill in holes if necessary, create blocks and
1820  * make partially overwritten blocks uptodate,
1821  *
1822  * i_size is not to be modified yet.
1823  *
1824  * Return 0 on success or -errno on error.
1825  *
1826  * Should be using block_prepare_write() [support for sparse files] or
1827  * cont_prepare_write() [no support for sparse files].  Cannot do that due to
1828  * ntfs specifics but can look at them for implementation guidance.
1829  *
1830  * Note: In the range, @from is inclusive and @to is exclusive, i.e. @from is
1831  * the first byte in the page that will be written to and @to is the first byte
1832  * after the last byte that will be written to.
1833  */
1834 static int ntfs_prepare_write(struct file *file, struct page *page,
1835                 unsigned from, unsigned to)
1836 {
1837         s64 new_size;
1838         loff_t i_size;
1839         struct inode *vi = page->mapping->host;
1840         ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1841         ntfs_volume *vol = ni->vol;
1842         ntfs_attr_search_ctx *ctx = NULL;
1843         MFT_RECORD *m = NULL;
1844         ATTR_RECORD *a;
1845         u8 *kaddr;
1846         u32 attr_len;
1847         int err;
1848
1849         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1850                         "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1851                         page->index, from, to);
1852         BUG_ON(!PageLocked(page));
1853         BUG_ON(from > PAGE_CACHE_SIZE);
1854         BUG_ON(to > PAGE_CACHE_SIZE);
1855         BUG_ON(from > to);
1856         BUG_ON(NInoMstProtected(ni));
1857         /*
1858          * If a previous ntfs_truncate() failed, repeat it and abort if it
1859          * fails again.
1860          */
1861         if (unlikely(NInoTruncateFailed(ni))) {
1862                 down_write(&vi->i_alloc_sem);
1863                 err = ntfs_truncate(vi);
1864                 up_write(&vi->i_alloc_sem);
1865                 if (err || NInoTruncateFailed(ni)) {
1866                         if (!err)
1867                                 err = -EIO;
1868                         goto err_out;
1869                 }
1870         }
1871         /* If the attribute is not resident, deal with it elsewhere. */
1872         if (NInoNonResident(ni)) {
1873                 /*
1874                  * Only unnamed $DATA attributes can be compressed, encrypted,
1875                  * and/or sparse.
1876                  */
1877                 if (ni->type == AT_DATA && !ni->name_len) {
1878                         /* If file is encrypted, deny access, just like NT4. */
1879                         if (NInoEncrypted(ni)) {
1880                                 ntfs_debug("Denying write access to encrypted "
1881                                                 "file.");
1882                                 return -EACCES;
1883                         }
1884                         /* Compressed data streams are handled in compress.c. */
1885                         if (NInoCompressed(ni)) {
1886                                 // TODO: Implement and replace this check with
1887                                 // return ntfs_write_compressed_block(page);
1888                                 ntfs_error(vi->i_sb, "Writing to compressed "
1889                                                 "files is not supported yet. "
1890                                                 "Sorry.");
1891                                 return -EOPNOTSUPP;
1892                         }
1893                         // TODO: Implement and remove this check.
1894                         if (NInoSparse(ni)) {
1895                                 ntfs_error(vi->i_sb, "Writing to sparse files "
1896                                                 "is not supported yet. Sorry.");
1897                                 return -EOPNOTSUPP;
1898                         }
1899                 }
1900                 /* Normal data stream. */
1901                 return ntfs_prepare_nonresident_write(page, from, to);
1902         }
1903         /*
1904          * Attribute is resident, implying it is not compressed, encrypted, or
1905          * sparse.
1906          */
1907         BUG_ON(page_has_buffers(page));
1908         new_size = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
1909         /* If we do not need to resize the attribute allocation we are done. */
1910         if (new_size <= i_size_read(vi))
1911                 goto done;
1912         /* Map, pin, and lock the (base) mft record. */
1913         if (!NInoAttr(ni))
1914                 base_ni = ni;
1915         else
1916                 base_ni = ni->ext.base_ntfs_ino;
1917         m = map_mft_record(base_ni);
1918         if (IS_ERR(m)) {
1919                 err = PTR_ERR(m);
1920                 m = NULL;
1921                 ctx = NULL;
1922                 goto err_out;
1923         }
1924         ctx = ntfs_attr_get_search_ctx(base_ni, m);
1925         if (unlikely(!ctx)) {
1926                 err = -ENOMEM;
1927                 goto err_out;
1928         }
1929         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1930                         CASE_SENSITIVE, 0, NULL, 0, ctx);
1931         if (unlikely(err)) {
1932                 if (err == -ENOENT)
1933                         err = -EIO;
1934                 goto err_out;
1935         }
1936         m = ctx->mrec;
1937         a = ctx->attr;
1938         /* The total length of the attribute value. */
1939         attr_len = le32_to_cpu(a->data.resident.value_length);
1940         /* Fix an eventual previous failure of ntfs_commit_write(). */
1941         i_size = i_size_read(vi);
1942         if (unlikely(attr_len > i_size)) {
1943                 attr_len = i_size;
1944                 a->data.resident.value_length = cpu_to_le32(attr_len);
1945         }
1946         /* If we do not need to resize the attribute allocation we are done. */
1947         if (new_size <= attr_len)
1948                 goto done_unm;
1949         /* Check if new size is allowed in $AttrDef. */
1950         err = ntfs_attr_size_bounds_check(vol, ni->type, new_size);
1951         if (unlikely(err)) {
1952                 if (err == -ERANGE) {
1953                         ntfs_error(vol->sb, "Write would cause the inode "
1954                                         "0x%lx to exceed the maximum size for "
1955                                         "its attribute type (0x%x).  Aborting "
1956                                         "write.", vi->i_ino,
1957                                         le32_to_cpu(ni->type));
1958                 } else {
1959                         ntfs_error(vol->sb, "Inode 0x%lx has unknown "
1960                                         "attribute type 0x%x.  Aborting "
1961                                         "write.", vi->i_ino,
1962                                         le32_to_cpu(ni->type));
1963                         err = -EIO;
1964                 }
1965                 goto err_out2;
1966         }
1967         /*
1968          * Extend the attribute record to be able to store the new attribute
1969          * size.
1970          */
1971         if (new_size >= vol->mft_record_size || ntfs_attr_record_resize(m, a,
1972                         le16_to_cpu(a->data.resident.value_offset) +
1973                         new_size)) {
1974                 /* Not enough space in the mft record. */
1975                 ntfs_error(vol->sb, "Not enough space in the mft record for "
1976                                 "the resized attribute value.  This is not "
1977                                 "supported yet.  Aborting write.");
1978                 err = -EOPNOTSUPP;
1979                 goto err_out2;
1980         }
1981         /*
1982          * We have enough space in the mft record to fit the write.  This
1983          * implies the attribute is smaller than the mft record and hence the
1984          * attribute must be in a single page and hence page->index must be 0.
1985          */
1986         BUG_ON(page->index);
1987         /*
1988          * If the beginning of the write is past the old size, enlarge the
1989          * attribute value up to the beginning of the write and fill it with
1990          * zeroes.
1991          */
1992         if (from > attr_len) {
1993                 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
1994                                 attr_len, 0, from - attr_len);
1995                 a->data.resident.value_length = cpu_to_le32(from);
1996                 /* Zero the corresponding area in the page as well. */
1997                 if (PageUptodate(page)) {
1998                         kaddr = kmap_atomic(page, KM_USER0);
1999                         memset(kaddr + attr_len, 0, from - attr_len);
2000                         kunmap_atomic(kaddr, KM_USER0);
2001                         flush_dcache_page(page);
2002                 }
2003         }
2004         flush_dcache_mft_record_page(ctx->ntfs_ino);
2005         mark_mft_record_dirty(ctx->ntfs_ino);
2006 done_unm:
2007         ntfs_attr_put_search_ctx(ctx);
2008         unmap_mft_record(base_ni);
2009         /*
2010          * Because resident attributes are handled by memcpy() to/from the
2011          * corresponding MFT record, and because this form of i/o is byte
2012          * aligned rather than block aligned, there is no need to bring the
2013          * page uptodate here as in the non-resident case where we need to
2014          * bring the buffers straddled by the write uptodate before
2015          * generic_file_write() does the copying from userspace.
2016          *
2017          * We thus defer the uptodate bringing of the page region outside the
2018          * region written to to ntfs_commit_write(), which makes the code
2019          * simpler and saves one atomic kmap which is good.
2020          */
2021 done:
2022         ntfs_debug("Done.");
2023         return 0;
2024 err_out:
2025         if (err == -ENOMEM)
2026                 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2027                                 "prepare the write.");
2028         else {
2029                 ntfs_error(vi->i_sb, "Resident attribute prepare write failed "
2030                                 "with error %i.", err);
2031                 NVolSetErrors(vol);
2032                 make_bad_inode(vi);
2033         }
2034 err_out2:
2035         if (ctx)
2036                 ntfs_attr_put_search_ctx(ctx);
2037         if (m)
2038                 unmap_mft_record(base_ni);
2039         return err;
2040 }
2041
2042 /**
2043  * ntfs_commit_nonresident_write -
2044  *
2045  */
2046 static int ntfs_commit_nonresident_write(struct page *page,
2047                 unsigned from, unsigned to)
2048 {
2049         s64 pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
2050         struct inode *vi = page->mapping->host;
2051         struct buffer_head *bh, *head;
2052         unsigned int block_start, block_end, blocksize;
2053         BOOL partial;
2054
2055         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2056                         "0x%lx, from = %u, to = %u.", vi->i_ino,
2057                         NTFS_I(vi)->type, page->index, from, to);
2058         blocksize = 1 << vi->i_blkbits;
2059
2060         // FIXME: We need a whole slew of special cases in here for compressed
2061         // files for example...
2062         // For now, we know ntfs_prepare_write() would have failed so we can't
2063         // get here in any of the cases which we have to special case, so we
2064         // are just a ripped off, unrolled generic_commit_write().
2065
2066         bh = head = page_buffers(page);
2067         block_start = 0;
2068         partial = FALSE;
2069         do {
2070                 block_end = block_start + blocksize;
2071                 if (block_end <= from || block_start >= to) {
2072                         if (!buffer_uptodate(bh))
2073                                 partial = TRUE;
2074                 } else {
2075                         set_buffer_uptodate(bh);
2076                         mark_buffer_dirty(bh);
2077                 }
2078         } while (block_start = block_end, (bh = bh->b_this_page) != head);
2079         /*
2080          * If this is a partial write which happened to make all buffers
2081          * uptodate then we can optimize away a bogus ->readpage() for the next
2082          * read().  Here we 'discover' whether the page went uptodate as a
2083          * result of this (potentially partial) write.
2084          */
2085         if (!partial)
2086                 SetPageUptodate(page);
2087         /*
2088          * Not convinced about this at all.  See disparity comment above.  For
2089          * now we know ntfs_prepare_write() would have failed in the write
2090          * exceeds i_size case, so this will never trigger which is fine.
2091          */
2092         if (pos > i_size_read(vi)) {
2093                 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
2094                                 "not supported yet.  Sorry.");
2095                 return -EOPNOTSUPP;
2096                 // vi->i_size = pos;
2097                 // mark_inode_dirty(vi);
2098         }
2099         ntfs_debug("Done.");
2100         return 0;
2101 }
2102
2103 /**
2104  * ntfs_commit_write - commit the received data
2105  *
2106  * This is called from generic_file_write() with i_sem held on the inode
2107  * (@page->mapping->host).  The @page is locked but not kmap()ped.  The source
2108  * data has already been copied into the @page.  ntfs_prepare_write() has been
2109  * called before the data copied and it returned success so we can take the
2110  * results of various BUG checks and some error handling for granted.
2111  *
2112  * Need to mark modified blocks dirty so they get written out later when
2113  * ntfs_writepage() is invoked by the VM.
2114  *
2115  * Return 0 on success or -errno on error.
2116  *
2117  * Should be using generic_commit_write().  This marks buffers uptodate and
2118  * dirty, sets the page uptodate if all buffers in the page are uptodate, and
2119  * updates i_size if the end of io is beyond i_size.  In that case, it also
2120  * marks the inode dirty.
2121  *
2122  * Cannot use generic_commit_write() due to ntfs specialities but can look at
2123  * it for implementation guidance.
2124  *
2125  * If things have gone as outlined in ntfs_prepare_write(), then we do not
2126  * need to do any page content modifications here at all, except in the write
2127  * to resident attribute case, where we need to do the uptodate bringing here
2128  * which we combine with the copying into the mft record which means we save
2129  * one atomic kmap.
2130  */
2131 static int ntfs_commit_write(struct file *file, struct page *page,
2132                 unsigned from, unsigned to)
2133 {
2134         struct inode *vi = page->mapping->host;
2135         ntfs_inode *base_ni, *ni = NTFS_I(vi);
2136         char *kaddr, *kattr;
2137         ntfs_attr_search_ctx *ctx;
2138         MFT_RECORD *m;
2139         ATTR_RECORD *a;
2140         u32 attr_len;
2141         int err;
2142
2143         ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2144                         "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
2145                         page->index, from, to);
2146         /* If the attribute is not resident, deal with it elsewhere. */
2147         if (NInoNonResident(ni)) {
2148                 /* Only unnamed $DATA attributes can be compressed/encrypted. */
2149                 if (ni->type == AT_DATA && !ni->name_len) {
2150                         /* Encrypted files need separate handling. */
2151                         if (NInoEncrypted(ni)) {
2152                                 // We never get here at present!
2153                                 BUG();
2154                         }
2155                         /* Compressed data streams are handled in compress.c. */
2156                         if (NInoCompressed(ni)) {
2157                                 // TODO: Implement this!
2158                                 // return ntfs_write_compressed_block(page);
2159                                 // We never get here at present!
2160                                 BUG();
2161                         }
2162                 }
2163                 /* Normal data stream. */
2164                 return ntfs_commit_nonresident_write(page, from, to);
2165         }
2166         /*
2167          * Attribute is resident, implying it is not compressed, encrypted, or
2168          * sparse.
2169          */
2170         if (!NInoAttr(ni))
2171                 base_ni = ni;
2172         else
2173                 base_ni = ni->ext.base_ntfs_ino;
2174         /* Map, pin, and lock the mft record. */
2175         m = map_mft_record(base_ni);
2176         if (IS_ERR(m)) {
2177                 err = PTR_ERR(m);
2178                 m = NULL;
2179                 ctx = NULL;
2180                 goto err_out;
2181         }
2182         ctx = ntfs_attr_get_search_ctx(base_ni, m);
2183         if (unlikely(!ctx)) {
2184                 err = -ENOMEM;
2185                 goto err_out;
2186         }
2187         err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2188                         CASE_SENSITIVE, 0, NULL, 0, ctx);
2189         if (unlikely(err)) {
2190                 if (err == -ENOENT)
2191                         err = -EIO;
2192                 goto err_out;
2193         }
2194         a = ctx->attr;
2195         /* The total length of the attribute value. */
2196         attr_len = le32_to_cpu(a->data.resident.value_length);
2197         BUG_ON(from > attr_len);
2198         kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
2199         kaddr = kmap_atomic(page, KM_USER0);
2200         /* Copy the received data from the page to the mft record. */
2201         memcpy(kattr + from, kaddr + from, to - from);
2202         /* Update the attribute length if necessary. */
2203         if (to > attr_len) {
2204                 attr_len = to;
2205                 a->data.resident.value_length = cpu_to_le32(attr_len);
2206         }
2207         /*
2208          * If the page is not uptodate, bring the out of bounds area(s)
2209          * uptodate by copying data from the mft record to the page.
2210          */
2211         if (!PageUptodate(page)) {
2212                 if (from > 0)
2213                         memcpy(kaddr, kattr, from);
2214                 if (to < attr_len)
2215                         memcpy(kaddr + to, kattr + to, attr_len - to);
2216                 /* Zero the region outside the end of the attribute value. */
2217                 if (attr_len < PAGE_CACHE_SIZE)
2218                         memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
2219                 /*
2220                  * The probability of not having done any of the above is
2221                  * extremely small, so we just flush unconditionally.
2222                  */
2223                 flush_dcache_page(page);
2224                 SetPageUptodate(page);
2225         }
2226         kunmap_atomic(kaddr, KM_USER0);
2227         /* Update i_size if necessary. */
2228         if (i_size_read(vi) < attr_len) {
2229                 unsigned long flags;
2230
2231                 write_lock_irqsave(&ni->size_lock, flags);
2232                 ni->allocated_size = ni->initialized_size = attr_len;
2233                 i_size_write(vi, attr_len);
2234                 write_unlock_irqrestore(&ni->size_lock, flags);
2235         }
2236         /* Mark the mft record dirty, so it gets written back. */
2237         flush_dcache_mft_record_page(ctx->ntfs_ino);
2238         mark_mft_record_dirty(ctx->ntfs_ino);
2239         ntfs_attr_put_search_ctx(ctx);
2240         unmap_mft_record(base_ni);
2241         ntfs_debug("Done.");
2242         return 0;
2243 err_out:
2244         if (err == -ENOMEM) {
2245                 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2246                                 "commit the write.");
2247                 if (PageUptodate(page)) {
2248                         ntfs_warning(vi->i_sb, "Page is uptodate, setting "
2249                                         "dirty so the write will be retried "
2250                                         "later on by the VM.");
2251                         /*
2252                          * Put the page on mapping->dirty_pages, but leave its
2253                          * buffers' dirty state as-is.
2254                          */
2255                         __set_page_dirty_nobuffers(page);
2256                         err = 0;
2257                 } else
2258                         ntfs_error(vi->i_sb, "Page is not uptodate.  Written "
2259                                         "data has been lost.");
2260         } else {
2261                 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
2262                                 "with error %i.", err);
2263                 NVolSetErrors(ni->vol);
2264                 make_bad_inode(vi);
2265         }
2266         if (ctx)
2267                 ntfs_attr_put_search_ctx(ctx);
2268         if (m)
2269                 unmap_mft_record(base_ni);
2270         return err;
2271 }
2272
2273 #endif  /* NTFS_RW */
2274
2275 /**
2276  * ntfs_aops - general address space operations for inodes and attributes
2277  */
2278 struct address_space_operations ntfs_aops = {
2279         .readpage       = ntfs_readpage,        /* Fill page with data. */
2280         .sync_page      = block_sync_page,      /* Currently, just unplugs the
2281                                                    disk request queue. */
2282 #ifdef NTFS_RW
2283         .writepage      = ntfs_writepage,       /* Write dirty page to disk. */
2284         .prepare_write  = ntfs_prepare_write,   /* Prepare page and buffers
2285                                                    ready to receive data. */
2286         .commit_write   = ntfs_commit_write,    /* Commit received data. */
2287 #endif /* NTFS_RW */
2288 };
2289
2290 /**
2291  * ntfs_mst_aops - general address space operations for mst protecteed inodes
2292  *                 and attributes
2293  */
2294 struct address_space_operations ntfs_mst_aops = {
2295         .readpage       = ntfs_readpage,        /* Fill page with data. */
2296         .sync_page      = block_sync_page,      /* Currently, just unplugs the
2297                                                    disk request queue. */
2298 #ifdef NTFS_RW
2299         .writepage      = ntfs_writepage,       /* Write dirty page to disk. */
2300         .set_page_dirty = __set_page_dirty_nobuffers,   /* Set the page dirty
2301                                                    without touching the buffers
2302                                                    belonging to the page. */
2303 #endif /* NTFS_RW */
2304 };
2305
2306 #ifdef NTFS_RW
2307
2308 /**
2309  * mark_ntfs_record_dirty - mark an ntfs record dirty
2310  * @page:       page containing the ntfs record to mark dirty
2311  * @ofs:        byte offset within @page at which the ntfs record begins
2312  *
2313  * Set the buffers and the page in which the ntfs record is located dirty.
2314  *
2315  * The latter also marks the vfs inode the ntfs record belongs to dirty
2316  * (I_DIRTY_PAGES only).
2317  *
2318  * If the page does not have buffers, we create them and set them uptodate.
2319  * The page may not be locked which is why we need to handle the buffers under
2320  * the mapping->private_lock.  Once the buffers are marked dirty we no longer
2321  * need the lock since try_to_free_buffers() does not free dirty buffers.
2322  */
2323 void mark_ntfs_record_dirty(struct page *page, const unsigned int ofs) {
2324         struct address_space *mapping = page->mapping;
2325         ntfs_inode *ni = NTFS_I(mapping->host);
2326         struct buffer_head *bh, *head, *buffers_to_free = NULL;
2327         unsigned int end, bh_size, bh_ofs;
2328
2329         BUG_ON(!PageUptodate(page));
2330         end = ofs + ni->itype.index.block_size;
2331         bh_size = 1 << VFS_I(ni)->i_blkbits;
2332         spin_lock(&mapping->private_lock);
2333         if (unlikely(!page_has_buffers(page))) {
2334                 spin_unlock(&mapping->private_lock);
2335                 bh = head = alloc_page_buffers(page, bh_size, 1);
2336                 spin_lock(&mapping->private_lock);
2337                 if (likely(!page_has_buffers(page))) {
2338                         struct buffer_head *tail;
2339
2340                         do {
2341                                 set_buffer_uptodate(bh);
2342                                 tail = bh;
2343                                 bh = bh->b_this_page;
2344                         } while (bh);
2345                         tail->b_this_page = head;
2346                         attach_page_buffers(page, head);
2347                 } else
2348                         buffers_to_free = bh;
2349         }
2350         bh = head = page_buffers(page);
2351         do {
2352                 bh_ofs = bh_offset(bh);
2353                 if (bh_ofs + bh_size <= ofs)
2354                         continue;
2355                 if (unlikely(bh_ofs >= end))
2356                         break;
2357                 set_buffer_dirty(bh);
2358         } while ((bh = bh->b_this_page) != head);
2359         spin_unlock(&mapping->private_lock);
2360         __set_page_dirty_nobuffers(page);
2361         if (unlikely(buffers_to_free)) {
2362                 do {
2363                         bh = buffers_to_free->b_this_page;
2364                         free_buffer_head(buffers_to_free);
2365                         buffers_to_free = bh;
2366                 } while (buffers_to_free);
2367         }
2368 }
2369
2370 #endif /* NTFS_RW */