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