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