2 * aops.c - NTFS kernel address space operations and page cache handling.
3 * Part of the Linux-NTFS project.
5 * Copyright (c) 2001-2005 Anton Altaparmakov
6 * Copyright (c) 2002 Richard Russon
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.
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.
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
24 #include <linux/errno.h>
26 #include <linux/pagemap.h>
27 #include <linux/swap.h>
28 #include <linux/buffer_head.h>
29 #include <linux/writeback.h>
41 * ntfs_end_buffer_async_read - async io completion for reading attributes
42 * @bh: buffer head on which io is completed
43 * @uptodate: whether @bh is now uptodate or not
45 * Asynchronous I/O completion handler for reading pages belonging to the
46 * attribute address space of an inode. The inodes can either be files or
47 * directories or they can be fake inodes describing some attribute.
49 * If NInoMstProtected(), perform the post read mst fixups when all IO on the
50 * page has been completed and mark the page uptodate or set the error bit on
51 * the page. To determine the size of the records that need fixing up, we
52 * cheat a little bit by setting the index_block_size in ntfs_inode to the ntfs
53 * record size, and index_block_size_bits, to the log(base 2) of the ntfs
56 static void ntfs_end_buffer_async_read(struct buffer_head *bh, int uptodate)
58 static DEFINE_SPINLOCK(page_uptodate_lock);
60 struct buffer_head *tmp;
63 int page_uptodate = 1;
66 ni = NTFS_I(page->mapping->host);
68 if (likely(uptodate)) {
69 s64 file_ofs, initialized_size;
71 set_buffer_uptodate(bh);
73 file_ofs = ((s64)page->index << PAGE_CACHE_SHIFT) +
75 read_lock_irqsave(&ni->size_lock, flags);
76 initialized_size = ni->initialized_size;
77 read_unlock_irqrestore(&ni->size_lock, flags);
78 /* Check for the current buffer head overflowing. */
79 if (file_ofs + bh->b_size > initialized_size) {
83 if (file_ofs < initialized_size)
84 ofs = initialized_size - file_ofs;
85 addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
86 memset(addr + bh_offset(bh) + ofs, 0, bh->b_size - ofs);
87 flush_dcache_page(page);
88 kunmap_atomic(addr, KM_BIO_SRC_IRQ);
91 clear_buffer_uptodate(bh);
92 ntfs_error(ni->vol->sb, "Buffer I/O error, logical block %llu.",
93 (unsigned long long)bh->b_blocknr);
96 spin_lock_irqsave(&page_uptodate_lock, flags);
97 clear_buffer_async_read(bh);
101 if (!buffer_uptodate(tmp))
103 if (buffer_async_read(tmp)) {
104 if (likely(buffer_locked(tmp)))
106 /* Async buffers must be locked. */
109 tmp = tmp->b_this_page;
111 spin_unlock_irqrestore(&page_uptodate_lock, flags);
113 * If none of the buffers had errors then we can set the page uptodate,
114 * but we first have to perform the post read mst fixups, if the
115 * attribute is mst protected, i.e. if NInoMstProteced(ni) is true.
116 * Note we ignore fixup errors as those are detected when
117 * map_mft_record() is called which gives us per record granularity
118 * rather than per page granularity.
120 if (!NInoMstProtected(ni)) {
121 if (likely(page_uptodate && !PageError(page)))
122 SetPageUptodate(page);
125 unsigned int i, recs;
128 rec_size = ni->itype.index.block_size;
129 recs = PAGE_CACHE_SIZE / rec_size;
130 /* Should have been verified before we got here... */
132 addr = kmap_atomic(page, KM_BIO_SRC_IRQ);
133 for (i = 0; i < recs; i++)
134 post_read_mst_fixup((NTFS_RECORD*)(addr +
135 i * rec_size), rec_size);
136 flush_dcache_page(page);
137 kunmap_atomic(addr, KM_BIO_SRC_IRQ);
138 if (likely(page_uptodate && !PageError(page)))
139 SetPageUptodate(page);
144 spin_unlock_irqrestore(&page_uptodate_lock, flags);
149 * ntfs_read_block - fill a @page of an address space with data
150 * @page: page cache page to fill with data
152 * Fill the page @page of the address space belonging to the @page->host inode.
153 * We read each buffer asynchronously and when all buffers are read in, our io
154 * completion handler ntfs_end_buffer_read_async(), if required, automatically
155 * applies the mst fixups to the page before finally marking it uptodate and
158 * We only enforce allocated_size limit because i_size is checked for in
159 * generic_file_read().
161 * Return 0 on success and -errno on error.
163 * Contains an adapted version of fs/buffer.c::block_read_full_page().
165 static int ntfs_read_block(struct page *page)
172 struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
173 sector_t iblock, lblock, zblock;
175 unsigned int blocksize, vcn_ofs;
177 unsigned char blocksize_bits;
179 ni = NTFS_I(page->mapping->host);
182 /* $MFT/$DATA must have its complete runlist in memory at all times. */
183 BUG_ON(!ni->runlist.rl && !ni->mft_no && !NInoAttr(ni));
185 blocksize_bits = VFS_I(ni)->i_blkbits;
186 blocksize = 1 << blocksize_bits;
188 if (!page_has_buffers(page))
189 create_empty_buffers(page, blocksize, 0);
190 bh = head = page_buffers(page);
196 iblock = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
197 read_lock_irqsave(&ni->size_lock, flags);
198 lblock = (ni->allocated_size + blocksize - 1) >> blocksize_bits;
199 zblock = (ni->initialized_size + blocksize - 1) >> blocksize_bits;
200 read_unlock_irqrestore(&ni->size_lock, flags);
202 /* Loop through all the buffers in the page. */
208 if (unlikely(buffer_uptodate(bh)))
210 if (unlikely(buffer_mapped(bh))) {
214 bh->b_bdev = vol->sb->s_bdev;
215 /* Is the block within the allowed limits? */
216 if (iblock < lblock) {
217 BOOL is_retry = FALSE;
219 /* Convert iblock into corresponding vcn and offset. */
220 vcn = (VCN)iblock << blocksize_bits >>
221 vol->cluster_size_bits;
222 vcn_ofs = ((VCN)iblock << blocksize_bits) &
223 vol->cluster_size_mask;
226 down_read(&ni->runlist.lock);
229 if (likely(rl != NULL)) {
230 /* Seek to element containing target vcn. */
231 while (rl->length && rl[1].vcn <= vcn)
233 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
235 lcn = LCN_RL_NOT_MAPPED;
236 /* Successful remap. */
238 /* Setup buffer head to correct block. */
239 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
240 + vcn_ofs) >> blocksize_bits;
241 set_buffer_mapped(bh);
242 /* Only read initialized data blocks. */
243 if (iblock < zblock) {
247 /* Fully non-initialized data block, zero it. */
250 /* It is a hole, need to zero it. */
253 /* If first try and runlist unmapped, map and retry. */
254 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
258 * Attempt to map runlist, dropping lock for
261 up_read(&ni->runlist.lock);
262 err = ntfs_map_runlist(ni, vcn);
264 goto lock_retry_remap;
268 up_read(&ni->runlist.lock);
269 /* Hard error, zero out region. */
272 ntfs_error(vol->sb, "Failed to read from inode 0x%lx, "
273 "attribute type 0x%x, vcn 0x%llx, "
274 "offset 0x%x because its location on "
275 "disk could not be determined%s "
276 "(error code %lli).", ni->mft_no,
277 ni->type, (unsigned long long)vcn,
278 vcn_ofs, is_retry ? " even after "
279 "retrying" : "", (long long)lcn);
282 * Either iblock was outside lblock limits or
283 * ntfs_rl_vcn_to_lcn() returned error. Just zero that portion
284 * of the page and set the buffer uptodate.
287 bh->b_blocknr = -1UL;
288 clear_buffer_mapped(bh);
290 kaddr = kmap_atomic(page, KM_USER0);
291 memset(kaddr + i * blocksize, 0, blocksize);
292 flush_dcache_page(page);
293 kunmap_atomic(kaddr, KM_USER0);
294 set_buffer_uptodate(bh);
295 } while (i++, iblock++, (bh = bh->b_this_page) != head);
297 /* Release the lock if we took it. */
299 up_read(&ni->runlist.lock);
301 /* Check we have at least one buffer ready for i/o. */
303 struct buffer_head *tbh;
305 /* Lock the buffers. */
306 for (i = 0; i < nr; i++) {
309 tbh->b_end_io = ntfs_end_buffer_async_read;
310 set_buffer_async_read(tbh);
312 /* Finally, start i/o on the buffers. */
313 for (i = 0; i < nr; i++) {
315 if (likely(!buffer_uptodate(tbh)))
316 submit_bh(READ, tbh);
318 ntfs_end_buffer_async_read(tbh, 1);
322 /* No i/o was scheduled on any of the buffers. */
323 if (likely(!PageError(page)))
324 SetPageUptodate(page);
325 else /* Signal synchronous i/o error. */
332 * ntfs_readpage - fill a @page of a @file with data from the device
333 * @file: open file to which the page @page belongs or NULL
334 * @page: page cache page to fill with data
336 * For non-resident attributes, ntfs_readpage() fills the @page of the open
337 * file @file by calling the ntfs version of the generic block_read_full_page()
338 * function, ntfs_read_block(), which in turn creates and reads in the buffers
339 * associated with the page asynchronously.
341 * For resident attributes, OTOH, ntfs_readpage() fills @page by copying the
342 * data from the mft record (which at this stage is most likely in memory) and
343 * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
344 * even if the mft record is not cached at this point in time, we need to wait
345 * for it to be read in before we can do the copy.
347 * Return 0 on success and -errno on error.
349 static int ntfs_readpage(struct file *file, struct page *page)
351 ntfs_inode *ni, *base_ni;
353 ntfs_attr_search_ctx *ctx;
360 BUG_ON(!PageLocked(page));
362 * This can potentially happen because we clear PageUptodate() during
363 * ntfs_writepage() of MstProtected() attributes.
365 if (PageUptodate(page)) {
369 ni = NTFS_I(page->mapping->host);
371 /* NInoNonResident() == NInoIndexAllocPresent() */
372 if (NInoNonResident(ni)) {
374 * Only unnamed $DATA attributes can be compressed or
377 if (ni->type == AT_DATA && !ni->name_len) {
378 /* If file is encrypted, deny access, just like NT4. */
379 if (NInoEncrypted(ni)) {
383 /* Compressed data streams are handled in compress.c. */
384 if (NInoCompressed(ni))
385 return ntfs_read_compressed_block(page);
387 /* Normal data stream. */
388 return ntfs_read_block(page);
391 * Attribute is resident, implying it is not compressed or encrypted.
392 * This also means the attribute is smaller than an mft record and
393 * hence smaller than a page, so can simply zero out any pages with
396 if (unlikely(page->index > 0)) {
397 kaddr = kmap_atomic(page, KM_USER0);
398 memset(kaddr, 0, PAGE_CACHE_SIZE);
399 flush_dcache_page(page);
400 kunmap_atomic(kaddr, KM_USER0);
406 base_ni = ni->ext.base_ntfs_ino;
407 /* Map, pin, and lock the mft record. */
408 mrec = map_mft_record(base_ni);
414 * If a parallel write made the attribute non-resident, drop the mft
415 * record and retry the readpage.
417 if (unlikely(NInoNonResident(ni))) {
418 unmap_mft_record(base_ni);
421 ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
422 if (unlikely(!ctx)) {
426 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
427 CASE_SENSITIVE, 0, NULL, 0, ctx);
429 goto put_unm_err_out;
430 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
431 read_lock_irqsave(&ni->size_lock, flags);
432 if (unlikely(attr_len > ni->initialized_size))
433 attr_len = ni->initialized_size;
434 read_unlock_irqrestore(&ni->size_lock, flags);
435 kaddr = kmap_atomic(page, KM_USER0);
436 /* Copy the data to the page. */
437 memcpy(kaddr, (u8*)ctx->attr +
438 le16_to_cpu(ctx->attr->data.resident.value_offset),
440 /* Zero the remainder of the page. */
441 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
442 flush_dcache_page(page);
443 kunmap_atomic(kaddr, KM_USER0);
445 ntfs_attr_put_search_ctx(ctx);
447 unmap_mft_record(base_ni);
449 SetPageUptodate(page);
458 * ntfs_write_block - write a @page to the backing store
459 * @page: page cache page to write out
460 * @wbc: writeback control structure
462 * This function is for writing pages belonging to non-resident, non-mst
463 * protected attributes to their backing store.
465 * For a page with buffers, map and write the dirty buffers asynchronously
466 * under page writeback. For a page without buffers, create buffers for the
467 * page, then proceed as above.
469 * If a page doesn't have buffers the page dirty state is definitive. If a page
470 * does have buffers, the page dirty state is just a hint, and the buffer dirty
471 * state is definitive. (A hint which has rules: dirty buffers against a clean
472 * page is illegal. Other combinations are legal and need to be handled. In
473 * particular a dirty page containing clean buffers for example.)
475 * Return 0 on success and -errno on error.
477 * Based on ntfs_read_block() and __block_write_full_page().
479 static int ntfs_write_block(struct page *page, struct writeback_control *wbc)
483 s64 initialized_size;
485 sector_t block, dblock, iblock;
490 struct buffer_head *bh, *head;
492 unsigned int blocksize, vcn_ofs;
494 BOOL need_end_writeback;
495 unsigned char blocksize_bits;
497 vi = page->mapping->host;
501 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
502 "0x%lx.", ni->mft_no, ni->type, page->index);
504 BUG_ON(!NInoNonResident(ni));
505 BUG_ON(NInoMstProtected(ni));
507 blocksize_bits = vi->i_blkbits;
508 blocksize = 1 << blocksize_bits;
510 if (!page_has_buffers(page)) {
511 BUG_ON(!PageUptodate(page));
512 create_empty_buffers(page, blocksize,
513 (1 << BH_Uptodate) | (1 << BH_Dirty));
515 bh = head = page_buffers(page);
517 ntfs_warning(vol->sb, "Error allocating page buffers. "
518 "Redirtying page so we try again later.");
520 * Put the page back on mapping->dirty_pages, but leave its
521 * buffer's dirty state as-is.
523 redirty_page_for_writepage(wbc, page);
528 /* NOTE: Different naming scheme to ntfs_read_block()! */
530 /* The first block in the page. */
531 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
533 read_lock_irqsave(&ni->size_lock, flags);
534 i_size = i_size_read(vi);
535 initialized_size = ni->initialized_size;
536 read_unlock_irqrestore(&ni->size_lock, flags);
538 /* The first out of bounds block for the data size. */
539 dblock = (i_size + blocksize - 1) >> blocksize_bits;
541 /* The last (fully or partially) initialized block. */
542 iblock = initialized_size >> blocksize_bits;
545 * Be very careful. We have no exclusion from __set_page_dirty_buffers
546 * here, and the (potentially unmapped) buffers may become dirty at
547 * any time. If a buffer becomes dirty here after we've inspected it
548 * then we just miss that fact, and the page stays dirty.
550 * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
551 * handle that here by just cleaning them.
555 * Loop through all the buffers in the page, mapping all the dirty
556 * buffers to disk addresses and handling any aliases from the
557 * underlying block device's mapping.
562 BOOL is_retry = FALSE;
564 if (unlikely(block >= dblock)) {
566 * Mapped buffers outside i_size will occur, because
567 * this page can be outside i_size when there is a
568 * truncate in progress. The contents of such buffers
569 * were zeroed by ntfs_writepage().
571 * FIXME: What about the small race window where
572 * ntfs_writepage() has not done any clearing because
573 * the page was within i_size but before we get here,
574 * vmtruncate() modifies i_size?
576 clear_buffer_dirty(bh);
577 set_buffer_uptodate(bh);
581 /* Clean buffers are not written out, so no need to map them. */
582 if (!buffer_dirty(bh))
585 /* Make sure we have enough initialized size. */
586 if (unlikely((block >= iblock) &&
587 (initialized_size < i_size))) {
589 * If this page is fully outside initialized size, zero
590 * out all pages between the current initialized size
591 * and the current page. Just use ntfs_readpage() to do
592 * the zeroing transparently.
594 if (block > iblock) {
597 // - read_cache_page()
598 // Again for each page do:
599 // - wait_on_page_locked()
600 // - Check (PageUptodate(page) &&
602 // Update initialized size in the attribute and
604 // Again, for each page do:
605 // __set_page_dirty_buffers();
606 // page_cache_release()
607 // We don't need to wait on the writes.
611 * The current page straddles initialized size. Zero
612 * all non-uptodate buffers and set them uptodate (and
613 * dirty?). Note, there aren't any non-uptodate buffers
614 * if the page is uptodate.
615 * FIXME: For an uptodate page, the buffers may need to
616 * be written out because they were not initialized on
619 if (!PageUptodate(page)) {
621 // Zero any non-uptodate buffers up to i_size.
622 // Set them uptodate and dirty.
625 // Update initialized size in the attribute and in the
626 // inode (up to i_size).
628 // FIXME: This is inefficient. Try to batch the two
629 // size changes to happen in one go.
630 ntfs_error(vol->sb, "Writing beyond initialized size "
631 "is not supported yet. Sorry.");
634 // Do NOT set_buffer_new() BUT DO clear buffer range
635 // outside write request range.
636 // set_buffer_uptodate() on complete buffers as well as
637 // set_buffer_dirty().
640 /* No need to map buffers that are already mapped. */
641 if (buffer_mapped(bh))
644 /* Unmapped, dirty buffer. Need to map it. */
645 bh->b_bdev = vol->sb->s_bdev;
647 /* Convert block into corresponding vcn and offset. */
648 vcn = (VCN)block << blocksize_bits;
649 vcn_ofs = vcn & vol->cluster_size_mask;
650 vcn >>= vol->cluster_size_bits;
653 down_read(&ni->runlist.lock);
656 if (likely(rl != NULL)) {
657 /* Seek to element containing target vcn. */
658 while (rl->length && rl[1].vcn <= vcn)
660 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
662 lcn = LCN_RL_NOT_MAPPED;
663 /* Successful remap. */
665 /* Setup buffer head to point to correct block. */
666 bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
667 vcn_ofs) >> blocksize_bits;
668 set_buffer_mapped(bh);
671 /* It is a hole, need to instantiate it. */
672 if (lcn == LCN_HOLE) {
674 unsigned long *bpos, *bend;
676 /* Check if the buffer is zero. */
677 kaddr = kmap_atomic(page, KM_USER0);
678 bpos = (unsigned long *)(kaddr + bh_offset(bh));
679 bend = (unsigned long *)((u8*)bpos + blocksize);
683 } while (likely(++bpos < bend));
684 kunmap_atomic(kaddr, KM_USER0);
687 * Buffer is zero and sparse, no need to write
691 clear_buffer_dirty(bh);
694 // TODO: Instantiate the hole.
695 // clear_buffer_new(bh);
696 // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
697 ntfs_error(vol->sb, "Writing into sparse regions is "
698 "not supported yet. Sorry.");
702 /* If first try and runlist unmapped, map and retry. */
703 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
706 * Attempt to map runlist, dropping lock for
709 up_read(&ni->runlist.lock);
710 err = ntfs_map_runlist(ni, vcn);
712 goto lock_retry_remap;
716 up_read(&ni->runlist.lock);
717 /* Failed to map the buffer, even after retrying. */
719 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
720 "attribute type 0x%x, vcn 0x%llx, offset 0x%x "
721 "because its location on disk could not be "
722 "determined%s (error code %lli).", ni->mft_no,
723 ni->type, (unsigned long long)vcn,
724 vcn_ofs, is_retry ? " even after "
725 "retrying" : "", (long long)lcn);
729 } while (block++, (bh = bh->b_this_page) != head);
731 /* Release the lock if we took it. */
733 up_read(&ni->runlist.lock);
735 /* For the error case, need to reset bh to the beginning. */
738 /* Just an optimization, so ->readpage() is not called later. */
739 if (unlikely(!PageUptodate(page))) {
742 if (!buffer_uptodate(bh)) {
747 } while ((bh = bh->b_this_page) != head);
749 SetPageUptodate(page);
752 /* Setup all mapped, dirty buffers for async write i/o. */
754 if (buffer_mapped(bh) && buffer_dirty(bh)) {
756 if (test_clear_buffer_dirty(bh)) {
757 BUG_ON(!buffer_uptodate(bh));
758 mark_buffer_async_write(bh);
761 } else if (unlikely(err)) {
763 * For the error case. The buffer may have been set
764 * dirty during attachment to a dirty page.
767 clear_buffer_dirty(bh);
769 } while ((bh = bh->b_this_page) != head);
772 // TODO: Remove the -EOPNOTSUPP check later on...
773 if (unlikely(err == -EOPNOTSUPP))
775 else if (err == -ENOMEM) {
776 ntfs_warning(vol->sb, "Error allocating memory. "
777 "Redirtying page so we try again "
780 * Put the page back on mapping->dirty_pages, but
781 * leave its buffer's dirty state as-is.
783 redirty_page_for_writepage(wbc, page);
789 BUG_ON(PageWriteback(page));
790 set_page_writeback(page); /* Keeps try_to_free_buffers() away. */
792 /* Submit the prepared buffers for i/o. */
793 need_end_writeback = TRUE;
795 struct buffer_head *next = bh->b_this_page;
796 if (buffer_async_write(bh)) {
797 submit_bh(WRITE, bh);
798 need_end_writeback = FALSE;
801 } while (bh != head);
804 /* If no i/o was started, need to end_page_writeback(). */
805 if (unlikely(need_end_writeback))
806 end_page_writeback(page);
813 * ntfs_write_mst_block - write a @page to the backing store
814 * @page: page cache page to write out
815 * @wbc: writeback control structure
817 * This function is for writing pages belonging to non-resident, mst protected
818 * attributes to their backing store. The only supported attributes are index
819 * allocation and $MFT/$DATA. Both directory inodes and index inodes are
820 * supported for the index allocation case.
822 * The page must remain locked for the duration of the write because we apply
823 * the mst fixups, write, and then undo the fixups, so if we were to unlock the
824 * page before undoing the fixups, any other user of the page will see the
825 * page contents as corrupt.
827 * We clear the page uptodate flag for the duration of the function to ensure
828 * exclusion for the $MFT/$DATA case against someone mapping an mft record we
829 * are about to apply the mst fixups to.
831 * Return 0 on success and -errno on error.
833 * Based on ntfs_write_block(), ntfs_mft_writepage(), and
834 * write_mft_record_nolock().
836 static int ntfs_write_mst_block(struct page *page,
837 struct writeback_control *wbc)
839 sector_t block, dblock, rec_block;
840 struct inode *vi = page->mapping->host;
841 ntfs_inode *ni = NTFS_I(vi);
842 ntfs_volume *vol = ni->vol;
844 unsigned int rec_size = ni->itype.index.block_size;
845 ntfs_inode *locked_nis[PAGE_CACHE_SIZE / rec_size];
846 struct buffer_head *bh, *head, *tbh, *rec_start_bh;
847 struct buffer_head *bhs[MAX_BUF_PER_PAGE];
849 int i, nr_locked_nis, nr_recs, nr_bhs, max_bhs, bhs_per_rec, err, err2;
850 unsigned bh_size, rec_size_bits;
851 BOOL sync, is_mft, page_is_dirty, rec_is_dirty;
852 unsigned char bh_size_bits;
854 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
855 "0x%lx.", vi->i_ino, ni->type, page->index);
856 BUG_ON(!NInoNonResident(ni));
857 BUG_ON(!NInoMstProtected(ni));
858 is_mft = (S_ISREG(vi->i_mode) && !vi->i_ino);
860 * NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page
861 * in its page cache were to be marked dirty. However this should
862 * never happen with the current driver and considering we do not
863 * handle this case here we do want to BUG(), at least for now.
865 BUG_ON(!(is_mft || S_ISDIR(vi->i_mode) ||
866 (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
867 bh_size_bits = vi->i_blkbits;
868 bh_size = 1 << bh_size_bits;
869 max_bhs = PAGE_CACHE_SIZE / bh_size;
871 BUG_ON(max_bhs > MAX_BUF_PER_PAGE);
873 /* Were we called for sync purposes? */
874 sync = (wbc->sync_mode == WB_SYNC_ALL);
876 /* Make sure we have mapped buffers. */
877 BUG_ON(!page_has_buffers(page));
878 bh = head = page_buffers(page);
881 rec_size_bits = ni->itype.index.block_size_bits;
882 BUG_ON(!(PAGE_CACHE_SIZE >> rec_size_bits));
883 bhs_per_rec = rec_size >> bh_size_bits;
884 BUG_ON(!bhs_per_rec);
886 /* The first block in the page. */
887 rec_block = block = (sector_t)page->index <<
888 (PAGE_CACHE_SHIFT - bh_size_bits);
890 /* The first out of bounds block for the data size. */
891 dblock = (i_size_read(vi) + bh_size - 1) >> bh_size_bits;
894 err = err2 = nr_bhs = nr_recs = nr_locked_nis = 0;
895 page_is_dirty = rec_is_dirty = FALSE;
898 BOOL is_retry = FALSE;
900 if (likely(block < rec_block)) {
901 if (unlikely(block >= dblock)) {
902 clear_buffer_dirty(bh);
903 set_buffer_uptodate(bh);
907 * This block is not the first one in the record. We
908 * ignore the buffer's dirty state because we could
909 * have raced with a parallel mark_ntfs_record_dirty().
913 if (unlikely(err2)) {
915 clear_buffer_dirty(bh);
918 } else /* if (block == rec_block) */ {
919 BUG_ON(block > rec_block);
920 /* This block is the first one in the record. */
921 rec_block += bhs_per_rec;
923 if (unlikely(block >= dblock)) {
924 clear_buffer_dirty(bh);
927 if (!buffer_dirty(bh)) {
928 /* Clean records are not written out. */
929 rec_is_dirty = FALSE;
935 /* Need to map the buffer if it is not mapped already. */
936 if (unlikely(!buffer_mapped(bh))) {
939 unsigned int vcn_ofs;
941 bh->b_bdev = vol->sb->s_bdev;
942 /* Obtain the vcn and offset of the current block. */
943 vcn = (VCN)block << bh_size_bits;
944 vcn_ofs = vcn & vol->cluster_size_mask;
945 vcn >>= vol->cluster_size_bits;
948 down_read(&ni->runlist.lock);
951 if (likely(rl != NULL)) {
952 /* Seek to element containing target vcn. */
953 while (rl->length && rl[1].vcn <= vcn)
955 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
957 lcn = LCN_RL_NOT_MAPPED;
958 /* Successful remap. */
959 if (likely(lcn >= 0)) {
960 /* Setup buffer head to correct block. */
961 bh->b_blocknr = ((lcn <<
962 vol->cluster_size_bits) +
963 vcn_ofs) >> bh_size_bits;
964 set_buffer_mapped(bh);
967 * Remap failed. Retry to map the runlist once
968 * unless we are working on $MFT which always
969 * has the whole of its runlist in memory.
971 if (!is_mft && !is_retry &&
972 lcn == LCN_RL_NOT_MAPPED) {
975 * Attempt to map runlist, dropping
976 * lock for the duration.
978 up_read(&ni->runlist.lock);
979 err2 = ntfs_map_runlist(ni, vcn);
981 goto lock_retry_remap;
983 page_is_dirty = TRUE;
988 up_read(&ni->runlist.lock);
990 /* Hard error. Abort writing this record. */
991 if (!err || err == -ENOMEM)
994 ntfs_error(vol->sb, "Cannot write ntfs record "
995 "0x%llx (inode 0x%lx, "
996 "attribute type 0x%x) because "
997 "its location on disk could "
998 "not be determined (error "
1002 vol->mft_record_size_bits,
1003 ni->mft_no, ni->type,
1006 * If this is not the first buffer, remove the
1007 * buffers in this record from the list of
1008 * buffers to write and clear their dirty bit
1009 * if not error -ENOMEM.
1011 if (rec_start_bh != bh) {
1012 while (bhs[--nr_bhs] != rec_start_bh)
1014 if (err2 != -ENOMEM) {
1018 } while ((rec_start_bh =
1027 BUG_ON(!buffer_uptodate(bh));
1028 BUG_ON(nr_bhs >= max_bhs);
1030 } while (block++, (bh = bh->b_this_page) != head);
1032 up_read(&ni->runlist.lock);
1033 /* If there were no dirty buffers, we are done. */
1036 /* Map the page so we can access its contents. */
1038 /* Clear the page uptodate flag whilst the mst fixups are applied. */
1039 BUG_ON(!PageUptodate(page));
1040 ClearPageUptodate(page);
1041 for (i = 0; i < nr_bhs; i++) {
1044 /* Skip buffers which are not at the beginning of records. */
1045 if (i % bhs_per_rec)
1048 ofs = bh_offset(tbh);
1051 unsigned long mft_no;
1053 /* Get the mft record number. */
1054 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1056 /* Check whether to write this mft record. */
1058 if (!ntfs_may_write_mft_record(vol, mft_no,
1059 (MFT_RECORD*)(kaddr + ofs), &tni)) {
1061 * The record should not be written. This
1062 * means we need to redirty the page before
1065 page_is_dirty = TRUE;
1067 * Remove the buffers in this mft record from
1068 * the list of buffers to write.
1072 } while (++i % bhs_per_rec);
1076 * The record should be written. If a locked ntfs
1077 * inode was returned, add it to the array of locked
1081 locked_nis[nr_locked_nis++] = tni;
1083 /* Apply the mst protection fixups. */
1084 err2 = pre_write_mst_fixup((NTFS_RECORD*)(kaddr + ofs),
1086 if (unlikely(err2)) {
1087 if (!err || err == -ENOMEM)
1089 ntfs_error(vol->sb, "Failed to apply mst fixups "
1090 "(inode 0x%lx, attribute type 0x%x, "
1091 "page index 0x%lx, page offset 0x%x)!"
1092 " Unmount and run chkdsk.", vi->i_ino,
1093 ni->type, page->index, ofs);
1095 * Mark all the buffers in this record clean as we do
1096 * not want to write corrupt data to disk.
1099 clear_buffer_dirty(bhs[i]);
1101 } while (++i % bhs_per_rec);
1106 /* If no records are to be written out, we are done. */
1109 flush_dcache_page(page);
1110 /* Lock buffers and start synchronous write i/o on them. */
1111 for (i = 0; i < nr_bhs; i++) {
1115 if (unlikely(test_set_buffer_locked(tbh)))
1117 /* The buffer dirty state is now irrelevant, just clean it. */
1118 clear_buffer_dirty(tbh);
1119 BUG_ON(!buffer_uptodate(tbh));
1120 BUG_ON(!buffer_mapped(tbh));
1122 tbh->b_end_io = end_buffer_write_sync;
1123 submit_bh(WRITE, tbh);
1125 /* Synchronize the mft mirror now if not @sync. */
1126 if (is_mft && !sync)
1129 /* Wait on i/o completion of buffers. */
1130 for (i = 0; i < nr_bhs; i++) {
1134 wait_on_buffer(tbh);
1135 if (unlikely(!buffer_uptodate(tbh))) {
1136 ntfs_error(vol->sb, "I/O error while writing ntfs "
1137 "record buffer (inode 0x%lx, "
1138 "attribute type 0x%x, page index "
1139 "0x%lx, page offset 0x%lx)! Unmount "
1140 "and run chkdsk.", vi->i_ino, ni->type,
1141 page->index, bh_offset(tbh));
1142 if (!err || err == -ENOMEM)
1145 * Set the buffer uptodate so the page and buffer
1146 * states do not become out of sync.
1148 set_buffer_uptodate(tbh);
1151 /* If @sync, now synchronize the mft mirror. */
1152 if (is_mft && sync) {
1154 for (i = 0; i < nr_bhs; i++) {
1155 unsigned long mft_no;
1159 * Skip buffers which are not at the beginning of
1162 if (i % bhs_per_rec)
1165 /* Skip removed buffers (and hence records). */
1168 ofs = bh_offset(tbh);
1169 /* Get the mft record number. */
1170 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1172 if (mft_no < vol->mftmirr_size)
1173 ntfs_sync_mft_mirror(vol, mft_no,
1174 (MFT_RECORD*)(kaddr + ofs),
1180 /* Remove the mst protection fixups again. */
1181 for (i = 0; i < nr_bhs; i++) {
1182 if (!(i % bhs_per_rec)) {
1186 post_write_mst_fixup((NTFS_RECORD*)(kaddr +
1190 flush_dcache_page(page);
1192 /* Unlock any locked inodes. */
1193 while (nr_locked_nis-- > 0) {
1194 ntfs_inode *tni, *base_tni;
1196 tni = locked_nis[nr_locked_nis];
1197 /* Get the base inode. */
1198 down(&tni->extent_lock);
1199 if (tni->nr_extents >= 0)
1202 base_tni = tni->ext.base_ntfs_ino;
1205 up(&tni->extent_lock);
1206 ntfs_debug("Unlocking %s inode 0x%lx.",
1207 tni == base_tni ? "base" : "extent",
1209 up(&tni->mrec_lock);
1210 atomic_dec(&tni->count);
1211 iput(VFS_I(base_tni));
1213 SetPageUptodate(page);
1216 if (unlikely(err && err != -ENOMEM)) {
1218 * Set page error if there is only one ntfs record in the page.
1219 * Otherwise we would loose per-record granularity.
1221 if (ni->itype.index.block_size == PAGE_CACHE_SIZE)
1225 if (page_is_dirty) {
1226 ntfs_debug("Page still contains one or more dirty ntfs "
1227 "records. Redirtying the page starting at "
1228 "record 0x%lx.", page->index <<
1229 (PAGE_CACHE_SHIFT - rec_size_bits));
1230 redirty_page_for_writepage(wbc, page);
1234 * Keep the VM happy. This must be done otherwise the
1235 * radix-tree tag PAGECACHE_TAG_DIRTY remains set even though
1236 * the page is clean.
1238 BUG_ON(PageWriteback(page));
1239 set_page_writeback(page);
1241 end_page_writeback(page);
1244 ntfs_debug("Done.");
1249 * ntfs_writepage - write a @page to the backing store
1250 * @page: page cache page to write out
1251 * @wbc: writeback control structure
1253 * This is called from the VM when it wants to have a dirty ntfs page cache
1254 * page cleaned. The VM has already locked the page and marked it clean.
1256 * For non-resident attributes, ntfs_writepage() writes the @page by calling
1257 * the ntfs version of the generic block_write_full_page() function,
1258 * ntfs_write_block(), which in turn if necessary creates and writes the
1259 * buffers associated with the page asynchronously.
1261 * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1262 * the data to the mft record (which at this stage is most likely in memory).
1263 * The mft record is then marked dirty and written out asynchronously via the
1264 * vfs inode dirty code path for the inode the mft record belongs to or via the
1265 * vm page dirty code path for the page the mft record is in.
1267 * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1269 * Return 0 on success and -errno on error.
1271 static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1274 struct inode *vi = page->mapping->host;
1275 ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1277 ntfs_attr_search_ctx *ctx = NULL;
1278 MFT_RECORD *m = NULL;
1283 BUG_ON(!PageLocked(page));
1284 i_size = i_size_read(vi);
1285 /* Is the page fully outside i_size? (truncate in progress) */
1286 if (unlikely(page->index >= (i_size + PAGE_CACHE_SIZE - 1) >>
1287 PAGE_CACHE_SHIFT)) {
1289 * The page may have dirty, unmapped buffers. Make them
1290 * freeable here, so the page does not leak.
1292 block_invalidatepage(page, 0);
1294 ntfs_debug("Write outside i_size - truncated?");
1298 * Only $DATA attributes can be encrypted and only unnamed $DATA
1299 * attributes can be compressed. Index root can have the flags set but
1300 * this means to create compressed/encrypted files, not that the
1301 * attribute is compressed/encrypted.
1303 if (ni->type != AT_INDEX_ROOT) {
1304 /* If file is encrypted, deny access, just like NT4. */
1305 if (NInoEncrypted(ni)) {
1307 BUG_ON(ni->type != AT_DATA);
1308 ntfs_debug("Denying write access to encrypted "
1312 /* Compressed data streams are handled in compress.c. */
1313 if (NInoNonResident(ni) && NInoCompressed(ni)) {
1314 BUG_ON(ni->type != AT_DATA);
1315 BUG_ON(ni->name_len);
1316 // TODO: Implement and replace this with
1317 // return ntfs_write_compressed_block(page);
1319 ntfs_error(vi->i_sb, "Writing to compressed files is "
1320 "not supported yet. Sorry.");
1323 // TODO: Implement and remove this check.
1324 if (NInoNonResident(ni) && NInoSparse(ni)) {
1326 ntfs_error(vi->i_sb, "Writing to sparse files is not "
1327 "supported yet. Sorry.");
1331 /* NInoNonResident() == NInoIndexAllocPresent() */
1332 if (NInoNonResident(ni)) {
1333 /* We have to zero every time due to mmap-at-end-of-file. */
1334 if (page->index >= (i_size >> PAGE_CACHE_SHIFT)) {
1335 /* The page straddles i_size. */
1336 unsigned int ofs = i_size & ~PAGE_CACHE_MASK;
1337 kaddr = kmap_atomic(page, KM_USER0);
1338 memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1339 flush_dcache_page(page);
1340 kunmap_atomic(kaddr, KM_USER0);
1342 /* Handle mst protected attributes. */
1343 if (NInoMstProtected(ni))
1344 return ntfs_write_mst_block(page, wbc);
1345 /* Normal, non-resident data stream. */
1346 return ntfs_write_block(page, wbc);
1349 * Attribute is resident, implying it is not compressed, encrypted, or
1350 * mst protected. This also means the attribute is smaller than an mft
1351 * record and hence smaller than a page, so can simply return error on
1352 * any pages with index above 0. Note the attribute can actually be
1353 * marked compressed but if it is resident the actual data is not
1354 * compressed so we are ok to ignore the compressed flag here.
1356 BUG_ON(page_has_buffers(page));
1357 BUG_ON(!PageUptodate(page));
1358 if (unlikely(page->index > 0)) {
1359 ntfs_error(vi->i_sb, "BUG()! page->index (0x%lx) > 0. "
1360 "Aborting write.", page->index);
1361 BUG_ON(PageWriteback(page));
1362 set_page_writeback(page);
1364 end_page_writeback(page);
1370 base_ni = ni->ext.base_ntfs_ino;
1371 /* Map, pin, and lock the mft record. */
1372 m = map_mft_record(base_ni);
1380 * If a parallel write made the attribute non-resident, drop the mft
1381 * record and retry the writepage.
1383 if (unlikely(NInoNonResident(ni))) {
1384 unmap_mft_record(base_ni);
1385 goto retry_writepage;
1387 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1388 if (unlikely(!ctx)) {
1392 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1393 CASE_SENSITIVE, 0, NULL, 0, ctx);
1397 * Keep the VM happy. This must be done otherwise the radix-tree tag
1398 * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1400 BUG_ON(PageWriteback(page));
1401 set_page_writeback(page);
1404 * Here, we do not need to zero the out of bounds area everytime
1405 * because the below memcpy() already takes care of the
1406 * mmap-at-end-of-file requirements. If the file is converted to a
1407 * non-resident one, then the code path use is switched to the
1408 * non-resident one where the zeroing happens on each ntfs_writepage()
1411 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
1412 i_size = i_size_read(vi);
1413 if (unlikely(attr_len > i_size)) {
1415 ctx->attr->data.resident.value_length = cpu_to_le32(attr_len);
1417 kaddr = kmap_atomic(page, KM_USER0);
1418 /* Copy the data from the page to the mft record. */
1419 memcpy((u8*)ctx->attr +
1420 le16_to_cpu(ctx->attr->data.resident.value_offset),
1422 flush_dcache_mft_record_page(ctx->ntfs_ino);
1423 /* Zero out of bounds area in the page cache page. */
1424 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1425 flush_dcache_page(page);
1426 kunmap_atomic(kaddr, KM_USER0);
1428 end_page_writeback(page);
1430 /* Mark the mft record dirty, so it gets written back. */
1431 mark_mft_record_dirty(ctx->ntfs_ino);
1432 ntfs_attr_put_search_ctx(ctx);
1433 unmap_mft_record(base_ni);
1436 if (err == -ENOMEM) {
1437 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1438 "page so we try again later.");
1440 * Put the page back on mapping->dirty_pages, but leave its
1441 * buffers' dirty state as-is.
1443 redirty_page_for_writepage(wbc, page);
1446 ntfs_error(vi->i_sb, "Resident attribute write failed with "
1449 NVolSetErrors(ni->vol);
1454 ntfs_attr_put_search_ctx(ctx);
1456 unmap_mft_record(base_ni);
1461 * ntfs_prepare_nonresident_write -
1464 static int ntfs_prepare_nonresident_write(struct page *page,
1465 unsigned from, unsigned to)
1469 s64 initialized_size;
1471 sector_t block, ablock, iblock;
1475 runlist_element *rl;
1476 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1477 unsigned long flags;
1478 unsigned int vcn_ofs, block_start, block_end, blocksize;
1481 unsigned char blocksize_bits;
1483 vi = page->mapping->host;
1487 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1488 "0x%lx, from = %u, to = %u.", ni->mft_no, ni->type,
1489 page->index, from, to);
1491 BUG_ON(!NInoNonResident(ni));
1493 blocksize_bits = vi->i_blkbits;
1494 blocksize = 1 << blocksize_bits;
1497 * create_empty_buffers() will create uptodate/dirty buffers if the
1498 * page is uptodate/dirty.
1500 if (!page_has_buffers(page))
1501 create_empty_buffers(page, blocksize, 0);
1502 bh = head = page_buffers(page);
1506 /* The first block in the page. */
1507 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
1509 read_lock_irqsave(&ni->size_lock, flags);
1511 * The first out of bounds block for the allocated size. No need to
1512 * round up as allocated_size is in multiples of cluster size and the
1513 * minimum cluster size is 512 bytes, which is equal to the smallest
1516 ablock = ni->allocated_size >> blocksize_bits;
1517 i_size = i_size_read(vi);
1518 initialized_size = ni->initialized_size;
1519 read_unlock_irqrestore(&ni->size_lock, flags);
1521 /* The last (fully or partially) initialized block. */
1522 iblock = initialized_size >> blocksize_bits;
1524 /* Loop through all the buffers in the page. */
1529 block_end = block_start + blocksize;
1531 * If buffer @bh is outside the write, just mark it uptodate
1532 * if the page is uptodate and continue with the next buffer.
1534 if (block_end <= from || block_start >= to) {
1535 if (PageUptodate(page)) {
1536 if (!buffer_uptodate(bh))
1537 set_buffer_uptodate(bh);
1542 * @bh is at least partially being written to.
1543 * Make sure it is not marked as new.
1545 //if (buffer_new(bh))
1546 // clear_buffer_new(bh);
1548 if (block >= ablock) {
1549 // TODO: block is above allocated_size, need to
1550 // allocate it. Best done in one go to accommodate not
1551 // only block but all above blocks up to and including:
1552 // ((page->index << PAGE_CACHE_SHIFT) + to + blocksize
1553 // - 1) >> blobksize_bits. Obviously will need to round
1554 // up to next cluster boundary, too. This should be
1555 // done with a helper function, so it can be reused.
1556 ntfs_error(vol->sb, "Writing beyond allocated size "
1557 "is not supported yet. Sorry.");
1560 // Need to update ablock.
1561 // Need to set_buffer_new() on all block bhs that are
1565 * Now we have enough allocated size to fulfill the whole
1566 * request, i.e. block < ablock is true.
1568 if (unlikely((block >= iblock) &&
1569 (initialized_size < i_size))) {
1571 * If this page is fully outside initialized size, zero
1572 * out all pages between the current initialized size
1573 * and the current page. Just use ntfs_readpage() to do
1574 * the zeroing transparently.
1576 if (block > iblock) {
1578 // For each page do:
1579 // - read_cache_page()
1580 // Again for each page do:
1581 // - wait_on_page_locked()
1582 // - Check (PageUptodate(page) &&
1583 // !PageError(page))
1584 // Update initialized size in the attribute and
1586 // Again, for each page do:
1587 // __set_page_dirty_buffers();
1588 // page_cache_release()
1589 // We don't need to wait on the writes.
1593 * The current page straddles initialized size. Zero
1594 * all non-uptodate buffers and set them uptodate (and
1595 * dirty?). Note, there aren't any non-uptodate buffers
1596 * if the page is uptodate.
1597 * FIXME: For an uptodate page, the buffers may need to
1598 * be written out because they were not initialized on
1601 if (!PageUptodate(page)) {
1603 // Zero any non-uptodate buffers up to i_size.
1604 // Set them uptodate and dirty.
1607 // Update initialized size in the attribute and in the
1608 // inode (up to i_size).
1610 // FIXME: This is inefficient. Try to batch the two
1611 // size changes to happen in one go.
1612 ntfs_error(vol->sb, "Writing beyond initialized size "
1613 "is not supported yet. Sorry.");
1616 // Do NOT set_buffer_new() BUT DO clear buffer range
1617 // outside write request range.
1618 // set_buffer_uptodate() on complete buffers as well as
1619 // set_buffer_dirty().
1622 /* Need to map unmapped buffers. */
1623 if (!buffer_mapped(bh)) {
1624 /* Unmapped buffer. Need to map it. */
1625 bh->b_bdev = vol->sb->s_bdev;
1627 /* Convert block into corresponding vcn and offset. */
1628 vcn = (VCN)block << blocksize_bits >>
1629 vol->cluster_size_bits;
1630 vcn_ofs = ((VCN)block << blocksize_bits) &
1631 vol->cluster_size_mask;
1636 down_read(&ni->runlist.lock);
1637 rl = ni->runlist.rl;
1639 if (likely(rl != NULL)) {
1640 /* Seek to element containing target vcn. */
1641 while (rl->length && rl[1].vcn <= vcn)
1643 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1645 lcn = LCN_RL_NOT_MAPPED;
1646 if (unlikely(lcn < 0)) {
1648 * We extended the attribute allocation above.
1649 * If we hit an ENOENT here it means that the
1650 * allocation was insufficient which is a bug.
1652 BUG_ON(lcn == LCN_ENOENT);
1654 /* It is a hole, need to instantiate it. */
1655 if (lcn == LCN_HOLE) {
1656 // TODO: Instantiate the hole.
1657 // clear_buffer_new(bh);
1658 // unmap_underlying_metadata(bh->b_bdev,
1660 // For non-uptodate buffers, need to
1661 // zero out the region outside the
1662 // request in this bh or all bhs,
1663 // depending on what we implemented
1665 // Need to flush_dcache_page().
1666 // Or could use set_buffer_new()
1668 ntfs_error(vol->sb, "Writing into "
1669 "sparse regions is "
1670 "not supported yet. "
1674 up_read(&ni->runlist.lock);
1676 } else if (!is_retry &&
1677 lcn == LCN_RL_NOT_MAPPED) {
1680 * Attempt to map runlist, dropping
1681 * lock for the duration.
1683 up_read(&ni->runlist.lock);
1684 err = ntfs_map_runlist(ni, vcn);
1686 goto lock_retry_remap;
1690 up_read(&ni->runlist.lock);
1692 * Failed to map the buffer, even after
1696 ntfs_error(vol->sb, "Failed to write to inode "
1697 "0x%lx, attribute type 0x%x, "
1698 "vcn 0x%llx, offset 0x%x "
1699 "because its location on disk "
1700 "could not be determined%s "
1701 "(error code %lli).",
1702 ni->mft_no, ni->type,
1703 (unsigned long long)vcn,
1704 vcn_ofs, is_retry ? " even "
1705 "after retrying" : "",
1711 /* We now have a successful remap, i.e. lcn >= 0. */
1713 /* Setup buffer head to correct block. */
1714 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
1715 + vcn_ofs) >> blocksize_bits;
1716 set_buffer_mapped(bh);
1718 // FIXME: Something analogous to this is needed for
1719 // each newly allocated block, i.e. BH_New.
1720 // FIXME: Might need to take this out of the
1721 // if (!buffer_mapped(bh)) {}, depending on how we
1722 // implement things during the allocated_size and
1723 // initialized_size extension code above.
1724 if (buffer_new(bh)) {
1725 clear_buffer_new(bh);
1726 unmap_underlying_metadata(bh->b_bdev,
1728 if (PageUptodate(page)) {
1729 set_buffer_uptodate(bh);
1733 * Page is _not_ uptodate, zero surrounding
1734 * region. NOTE: This is how we decide if to
1737 if (block_end > to || block_start < from) {
1740 kaddr = kmap_atomic(page, KM_USER0);
1742 memset(kaddr + to, 0,
1744 if (block_start < from)
1745 memset(kaddr + block_start, 0,
1748 flush_dcache_page(page);
1749 kunmap_atomic(kaddr, KM_USER0);
1754 /* @bh is mapped, set it uptodate if the page is uptodate. */
1755 if (PageUptodate(page)) {
1756 if (!buffer_uptodate(bh))
1757 set_buffer_uptodate(bh);
1761 * The page is not uptodate. The buffer is mapped. If it is not
1762 * uptodate, and it is only partially being written to, we need
1763 * to read the buffer in before the write, i.e. right now.
1765 if (!buffer_uptodate(bh) &&
1766 (block_start < from || block_end > to)) {
1767 ll_rw_block(READ, 1, &bh);
1770 } while (block++, block_start = block_end,
1771 (bh = bh->b_this_page) != head);
1773 /* Release the lock if we took it. */
1775 up_read(&ni->runlist.lock);
1779 /* If we issued read requests, let them complete. */
1780 while (wait_bh > wait) {
1781 wait_on_buffer(*--wait_bh);
1782 if (!buffer_uptodate(*wait_bh))
1786 ntfs_debug("Done.");
1790 * Zero out any newly allocated blocks to avoid exposing stale data.
1791 * If BH_New is set, we know that the block was newly allocated in the
1793 * FIXME: What about initialized_size increments? Have we done all the
1794 * required zeroing above? If not this error handling is broken, and
1795 * in particular the if (block_end <= from) check is completely bogus.
1801 block_end = block_start + blocksize;
1802 if (block_end <= from)
1804 if (block_start >= to)
1806 if (buffer_new(bh)) {
1809 clear_buffer_new(bh);
1810 kaddr = kmap_atomic(page, KM_USER0);
1811 memset(kaddr + block_start, 0, bh->b_size);
1812 kunmap_atomic(kaddr, KM_USER0);
1813 set_buffer_uptodate(bh);
1814 mark_buffer_dirty(bh);
1817 } while (block_start = block_end, (bh = bh->b_this_page) != head);
1819 flush_dcache_page(page);
1821 up_read(&ni->runlist.lock);
1826 * ntfs_prepare_write - prepare a page for receiving data
1828 * This is called from generic_file_write() with i_sem held on the inode
1829 * (@page->mapping->host). The @page is locked but not kmap()ped. The source
1830 * data has not yet been copied into the @page.
1832 * Need to extend the attribute/fill in holes if necessary, create blocks and
1833 * make partially overwritten blocks uptodate,
1835 * i_size is not to be modified yet.
1837 * Return 0 on success or -errno on error.
1839 * Should be using block_prepare_write() [support for sparse files] or
1840 * cont_prepare_write() [no support for sparse files]. Cannot do that due to
1841 * ntfs specifics but can look at them for implementation guidance.
1843 * Note: In the range, @from is inclusive and @to is exclusive, i.e. @from is
1844 * the first byte in the page that will be written to and @to is the first byte
1845 * after the last byte that will be written to.
1847 static int ntfs_prepare_write(struct file *file, struct page *page,
1848 unsigned from, unsigned to)
1852 struct inode *vi = page->mapping->host;
1853 ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1854 ntfs_volume *vol = ni->vol;
1855 ntfs_attr_search_ctx *ctx = NULL;
1856 MFT_RECORD *m = NULL;
1862 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1863 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1864 page->index, from, to);
1865 BUG_ON(!PageLocked(page));
1866 BUG_ON(from > PAGE_CACHE_SIZE);
1867 BUG_ON(to > PAGE_CACHE_SIZE);
1869 BUG_ON(NInoMstProtected(ni));
1871 * If a previous ntfs_truncate() failed, repeat it and abort if it
1874 if (unlikely(NInoTruncateFailed(ni))) {
1875 down_write(&vi->i_alloc_sem);
1876 err = ntfs_truncate(vi);
1877 up_write(&vi->i_alloc_sem);
1878 if (err || NInoTruncateFailed(ni)) {
1884 /* If the attribute is not resident, deal with it elsewhere. */
1885 if (NInoNonResident(ni)) {
1887 * Only unnamed $DATA attributes can be compressed, encrypted,
1890 if (ni->type == AT_DATA && !ni->name_len) {
1891 /* If file is encrypted, deny access, just like NT4. */
1892 if (NInoEncrypted(ni)) {
1893 ntfs_debug("Denying write access to encrypted "
1897 /* Compressed data streams are handled in compress.c. */
1898 if (NInoCompressed(ni)) {
1899 // TODO: Implement and replace this check with
1900 // return ntfs_write_compressed_block(page);
1901 ntfs_error(vi->i_sb, "Writing to compressed "
1902 "files is not supported yet. "
1906 // TODO: Implement and remove this check.
1907 if (NInoSparse(ni)) {
1908 ntfs_error(vi->i_sb, "Writing to sparse files "
1909 "is not supported yet. Sorry.");
1913 /* Normal data stream. */
1914 return ntfs_prepare_nonresident_write(page, from, to);
1917 * Attribute is resident, implying it is not compressed, encrypted, or
1920 BUG_ON(page_has_buffers(page));
1921 new_size = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
1922 /* If we do not need to resize the attribute allocation we are done. */
1923 if (new_size <= i_size_read(vi))
1925 /* Map, pin, and lock the (base) mft record. */
1929 base_ni = ni->ext.base_ntfs_ino;
1930 m = map_mft_record(base_ni);
1937 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1938 if (unlikely(!ctx)) {
1942 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1943 CASE_SENSITIVE, 0, NULL, 0, ctx);
1944 if (unlikely(err)) {
1951 /* The total length of the attribute value. */
1952 attr_len = le32_to_cpu(a->data.resident.value_length);
1953 /* Fix an eventual previous failure of ntfs_commit_write(). */
1954 i_size = i_size_read(vi);
1955 if (unlikely(attr_len > i_size)) {
1957 a->data.resident.value_length = cpu_to_le32(attr_len);
1959 /* If we do not need to resize the attribute allocation we are done. */
1960 if (new_size <= attr_len)
1962 /* Check if new size is allowed in $AttrDef. */
1963 err = ntfs_attr_size_bounds_check(vol, ni->type, new_size);
1964 if (unlikely(err)) {
1965 if (err == -ERANGE) {
1966 ntfs_error(vol->sb, "Write would cause the inode "
1967 "0x%lx to exceed the maximum size for "
1968 "its attribute type (0x%x). Aborting "
1969 "write.", vi->i_ino,
1970 le32_to_cpu(ni->type));
1972 ntfs_error(vol->sb, "Inode 0x%lx has unknown "
1973 "attribute type 0x%x. Aborting "
1974 "write.", vi->i_ino,
1975 le32_to_cpu(ni->type));
1981 * Extend the attribute record to be able to store the new attribute
1984 if (new_size >= vol->mft_record_size || ntfs_attr_record_resize(m, a,
1985 le16_to_cpu(a->data.resident.value_offset) +
1987 /* Not enough space in the mft record. */
1988 ntfs_error(vol->sb, "Not enough space in the mft record for "
1989 "the resized attribute value. This is not "
1990 "supported yet. Aborting write.");
1995 * We have enough space in the mft record to fit the write. This
1996 * implies the attribute is smaller than the mft record and hence the
1997 * attribute must be in a single page and hence page->index must be 0.
1999 BUG_ON(page->index);
2001 * If the beginning of the write is past the old size, enlarge the
2002 * attribute value up to the beginning of the write and fill it with
2005 if (from > attr_len) {
2006 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
2007 attr_len, 0, from - attr_len);
2008 a->data.resident.value_length = cpu_to_le32(from);
2009 /* Zero the corresponding area in the page as well. */
2010 if (PageUptodate(page)) {
2011 kaddr = kmap_atomic(page, KM_USER0);
2012 memset(kaddr + attr_len, 0, from - attr_len);
2013 kunmap_atomic(kaddr, KM_USER0);
2014 flush_dcache_page(page);
2017 flush_dcache_mft_record_page(ctx->ntfs_ino);
2018 mark_mft_record_dirty(ctx->ntfs_ino);
2020 ntfs_attr_put_search_ctx(ctx);
2021 unmap_mft_record(base_ni);
2023 * Because resident attributes are handled by memcpy() to/from the
2024 * corresponding MFT record, and because this form of i/o is byte
2025 * aligned rather than block aligned, there is no need to bring the
2026 * page uptodate here as in the non-resident case where we need to
2027 * bring the buffers straddled by the write uptodate before
2028 * generic_file_write() does the copying from userspace.
2030 * We thus defer the uptodate bringing of the page region outside the
2031 * region written to to ntfs_commit_write(), which makes the code
2032 * simpler and saves one atomic kmap which is good.
2035 ntfs_debug("Done.");
2039 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2040 "prepare the write.");
2042 ntfs_error(vi->i_sb, "Resident attribute prepare write failed "
2043 "with error %i.", err);
2049 ntfs_attr_put_search_ctx(ctx);
2051 unmap_mft_record(base_ni);
2056 * ntfs_commit_nonresident_write -
2059 static int ntfs_commit_nonresident_write(struct page *page,
2060 unsigned from, unsigned to)
2062 s64 pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
2063 struct inode *vi = page->mapping->host;
2064 struct buffer_head *bh, *head;
2065 unsigned int block_start, block_end, blocksize;
2068 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2069 "0x%lx, from = %u, to = %u.", vi->i_ino,
2070 NTFS_I(vi)->type, page->index, from, to);
2071 blocksize = 1 << vi->i_blkbits;
2073 // FIXME: We need a whole slew of special cases in here for compressed
2074 // files for example...
2075 // For now, we know ntfs_prepare_write() would have failed so we can't
2076 // get here in any of the cases which we have to special case, so we
2077 // are just a ripped off, unrolled generic_commit_write().
2079 bh = head = page_buffers(page);
2083 block_end = block_start + blocksize;
2084 if (block_end <= from || block_start >= to) {
2085 if (!buffer_uptodate(bh))
2088 set_buffer_uptodate(bh);
2089 mark_buffer_dirty(bh);
2091 } while (block_start = block_end, (bh = bh->b_this_page) != head);
2093 * If this is a partial write which happened to make all buffers
2094 * uptodate then we can optimize away a bogus ->readpage() for the next
2095 * read(). Here we 'discover' whether the page went uptodate as a
2096 * result of this (potentially partial) write.
2099 SetPageUptodate(page);
2101 * Not convinced about this at all. See disparity comment above. For
2102 * now we know ntfs_prepare_write() would have failed in the write
2103 * exceeds i_size case, so this will never trigger which is fine.
2105 if (pos > i_size_read(vi)) {
2106 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
2107 "not supported yet. Sorry.");
2109 // vi->i_size = pos;
2110 // mark_inode_dirty(vi);
2112 ntfs_debug("Done.");
2117 * ntfs_commit_write - commit the received data
2119 * This is called from generic_file_write() with i_sem held on the inode
2120 * (@page->mapping->host). The @page is locked but not kmap()ped. The source
2121 * data has already been copied into the @page. ntfs_prepare_write() has been
2122 * called before the data copied and it returned success so we can take the
2123 * results of various BUG checks and some error handling for granted.
2125 * Need to mark modified blocks dirty so they get written out later when
2126 * ntfs_writepage() is invoked by the VM.
2128 * Return 0 on success or -errno on error.
2130 * Should be using generic_commit_write(). This marks buffers uptodate and
2131 * dirty, sets the page uptodate if all buffers in the page are uptodate, and
2132 * updates i_size if the end of io is beyond i_size. In that case, it also
2133 * marks the inode dirty.
2135 * Cannot use generic_commit_write() due to ntfs specialities but can look at
2136 * it for implementation guidance.
2138 * If things have gone as outlined in ntfs_prepare_write(), then we do not
2139 * need to do any page content modifications here at all, except in the write
2140 * to resident attribute case, where we need to do the uptodate bringing here
2141 * which we combine with the copying into the mft record which means we save
2144 static int ntfs_commit_write(struct file *file, struct page *page,
2145 unsigned from, unsigned to)
2147 struct inode *vi = page->mapping->host;
2148 ntfs_inode *base_ni, *ni = NTFS_I(vi);
2149 char *kaddr, *kattr;
2150 ntfs_attr_search_ctx *ctx;
2156 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2157 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
2158 page->index, from, to);
2159 /* If the attribute is not resident, deal with it elsewhere. */
2160 if (NInoNonResident(ni)) {
2161 /* Only unnamed $DATA attributes can be compressed/encrypted. */
2162 if (ni->type == AT_DATA && !ni->name_len) {
2163 /* Encrypted files need separate handling. */
2164 if (NInoEncrypted(ni)) {
2165 // We never get here at present!
2168 /* Compressed data streams are handled in compress.c. */
2169 if (NInoCompressed(ni)) {
2170 // TODO: Implement this!
2171 // return ntfs_write_compressed_block(page);
2172 // We never get here at present!
2176 /* Normal data stream. */
2177 return ntfs_commit_nonresident_write(page, from, to);
2180 * Attribute is resident, implying it is not compressed, encrypted, or
2186 base_ni = ni->ext.base_ntfs_ino;
2187 /* Map, pin, and lock the mft record. */
2188 m = map_mft_record(base_ni);
2195 ctx = ntfs_attr_get_search_ctx(base_ni, m);
2196 if (unlikely(!ctx)) {
2200 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2201 CASE_SENSITIVE, 0, NULL, 0, ctx);
2202 if (unlikely(err)) {
2208 /* The total length of the attribute value. */
2209 attr_len = le32_to_cpu(a->data.resident.value_length);
2210 BUG_ON(from > attr_len);
2211 kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
2212 kaddr = kmap_atomic(page, KM_USER0);
2213 /* Copy the received data from the page to the mft record. */
2214 memcpy(kattr + from, kaddr + from, to - from);
2215 /* Update the attribute length if necessary. */
2216 if (to > attr_len) {
2218 a->data.resident.value_length = cpu_to_le32(attr_len);
2221 * If the page is not uptodate, bring the out of bounds area(s)
2222 * uptodate by copying data from the mft record to the page.
2224 if (!PageUptodate(page)) {
2226 memcpy(kaddr, kattr, from);
2228 memcpy(kaddr + to, kattr + to, attr_len - to);
2229 /* Zero the region outside the end of the attribute value. */
2230 if (attr_len < PAGE_CACHE_SIZE)
2231 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
2233 * The probability of not having done any of the above is
2234 * extremely small, so we just flush unconditionally.
2236 flush_dcache_page(page);
2237 SetPageUptodate(page);
2239 kunmap_atomic(kaddr, KM_USER0);
2240 /* Update i_size if necessary. */
2241 if (i_size_read(vi) < attr_len) {
2242 unsigned long flags;
2244 write_lock_irqsave(&ni->size_lock, flags);
2245 ni->allocated_size = ni->initialized_size = attr_len;
2246 i_size_write(vi, attr_len);
2247 write_unlock_irqrestore(&ni->size_lock, flags);
2249 /* Mark the mft record dirty, so it gets written back. */
2250 flush_dcache_mft_record_page(ctx->ntfs_ino);
2251 mark_mft_record_dirty(ctx->ntfs_ino);
2252 ntfs_attr_put_search_ctx(ctx);
2253 unmap_mft_record(base_ni);
2254 ntfs_debug("Done.");
2257 if (err == -ENOMEM) {
2258 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2259 "commit the write.");
2260 if (PageUptodate(page)) {
2261 ntfs_warning(vi->i_sb, "Page is uptodate, setting "
2262 "dirty so the write will be retried "
2263 "later on by the VM.");
2265 * Put the page on mapping->dirty_pages, but leave its
2266 * buffers' dirty state as-is.
2268 __set_page_dirty_nobuffers(page);
2271 ntfs_error(vi->i_sb, "Page is not uptodate. Written "
2272 "data has been lost.");
2274 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
2275 "with error %i.", err);
2276 NVolSetErrors(ni->vol);
2280 ntfs_attr_put_search_ctx(ctx);
2282 unmap_mft_record(base_ni);
2286 #endif /* NTFS_RW */
2289 * ntfs_aops - general address space operations for inodes and attributes
2291 struct address_space_operations ntfs_aops = {
2292 .readpage = ntfs_readpage, /* Fill page with data. */
2293 .sync_page = block_sync_page, /* Currently, just unplugs the
2294 disk request queue. */
2296 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2297 .prepare_write = ntfs_prepare_write, /* Prepare page and buffers
2298 ready to receive data. */
2299 .commit_write = ntfs_commit_write, /* Commit received data. */
2300 #endif /* NTFS_RW */
2304 * ntfs_mst_aops - general address space operations for mst protecteed inodes
2307 struct address_space_operations ntfs_mst_aops = {
2308 .readpage = ntfs_readpage, /* Fill page with data. */
2309 .sync_page = block_sync_page, /* Currently, just unplugs the
2310 disk request queue. */
2312 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2313 .set_page_dirty = __set_page_dirty_nobuffers, /* Set the page dirty
2314 without touching the buffers
2315 belonging to the page. */
2316 #endif /* NTFS_RW */
2322 * mark_ntfs_record_dirty - mark an ntfs record dirty
2323 * @page: page containing the ntfs record to mark dirty
2324 * @ofs: byte offset within @page at which the ntfs record begins
2326 * Set the buffers and the page in which the ntfs record is located dirty.
2328 * The latter also marks the vfs inode the ntfs record belongs to dirty
2329 * (I_DIRTY_PAGES only).
2331 * If the page does not have buffers, we create them and set them uptodate.
2332 * The page may not be locked which is why we need to handle the buffers under
2333 * the mapping->private_lock. Once the buffers are marked dirty we no longer
2334 * need the lock since try_to_free_buffers() does not free dirty buffers.
2336 void mark_ntfs_record_dirty(struct page *page, const unsigned int ofs) {
2337 struct address_space *mapping = page->mapping;
2338 ntfs_inode *ni = NTFS_I(mapping->host);
2339 struct buffer_head *bh, *head, *buffers_to_free = NULL;
2340 unsigned int end, bh_size, bh_ofs;
2342 BUG_ON(!PageUptodate(page));
2343 end = ofs + ni->itype.index.block_size;
2344 bh_size = 1 << VFS_I(ni)->i_blkbits;
2345 spin_lock(&mapping->private_lock);
2346 if (unlikely(!page_has_buffers(page))) {
2347 spin_unlock(&mapping->private_lock);
2348 bh = head = alloc_page_buffers(page, bh_size, 1);
2349 spin_lock(&mapping->private_lock);
2350 if (likely(!page_has_buffers(page))) {
2351 struct buffer_head *tail;
2354 set_buffer_uptodate(bh);
2356 bh = bh->b_this_page;
2358 tail->b_this_page = head;
2359 attach_page_buffers(page, head);
2361 buffers_to_free = bh;
2363 bh = head = page_buffers(page);
2365 bh_ofs = bh_offset(bh);
2366 if (bh_ofs + bh_size <= ofs)
2368 if (unlikely(bh_ofs >= end))
2370 set_buffer_dirty(bh);
2371 } while ((bh = bh->b_this_page) != head);
2372 spin_unlock(&mapping->private_lock);
2373 __set_page_dirty_nobuffers(page);
2374 if (unlikely(buffers_to_free)) {
2376 bh = buffers_to_free->b_this_page;
2377 free_buffer_head(buffers_to_free);
2378 buffers_to_free = bh;
2379 } while (buffers_to_free);
2383 #endif /* NTFS_RW */