2 * aops.c - NTFS kernel address space operations and page cache handling.
3 * Part of the Linux-NTFS project.
5 * Copyright (c) 2001-2004 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>
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
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.
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
48 static void ntfs_end_buffer_async_read(struct buffer_head *bh, int uptodate)
50 static spinlock_t page_uptodate_lock = SPIN_LOCK_UNLOCKED;
52 struct buffer_head *tmp;
55 int page_uptodate = 1;
58 ni = NTFS_I(page->mapping->host);
60 if (likely(uptodate)) {
63 set_buffer_uptodate(bh);
65 file_ofs = ((s64)page->index << PAGE_CACHE_SHIFT) +
67 /* Check for the current buffer head overflowing. */
68 if (file_ofs + bh->b_size > ni->initialized_size) {
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);
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);
86 spin_lock_irqsave(&page_uptodate_lock, flags);
87 clear_buffer_async_read(bh);
91 if (!buffer_uptodate(tmp))
93 if (buffer_async_read(tmp)) {
94 if (likely(buffer_locked(tmp)))
96 /* Async buffers must be locked. */
99 tmp = tmp->b_this_page;
101 spin_unlock_irqrestore(&page_uptodate_lock, flags);
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.
107 if (!NInoMstProtected(ni)) {
108 if (likely(page_uptodate && !PageError(page)))
109 SetPageUptodate(page);
112 unsigned int i, recs, nr_err;
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)))
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));
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);
137 ntfs_error(ni->vol->sb, "Setting page error, "
138 "index 0x%lx.", page->index);
146 spin_unlock_irqrestore(&page_uptodate_lock, flags);
151 * ntfs_read_block - fill a @page of an address space with data
152 * @page: page cache page to fill with data
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
160 * We only enforce allocated_size limit because i_size is checked for in
161 * generic_file_read().
163 * Return 0 on success and -errno on error.
165 * Contains an adapted version of fs/buffer.c::block_read_full_page().
167 static int ntfs_read_block(struct page *page)
173 run_list_element *rl;
174 struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE];
175 sector_t iblock, lblock, zblock;
176 unsigned int blocksize, vcn_ofs;
178 unsigned char blocksize_bits;
180 ni = NTFS_I(page->mapping->host);
183 blocksize_bits = VFS_I(ni)->i_blkbits;
184 blocksize = 1 << blocksize_bits;
186 if (!page_has_buffers(page))
187 create_empty_buffers(page, blocksize, 0);
188 bh = head = page_buffers(page);
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;
199 if (unlikely(!ni->run_list.rl && !ni->mft_no && !NInoAttr(ni)))
200 panic("NTFS: $MFT/$DATA run list has been unmapped! This is a "
201 "very serious bug! Cannot continue...");
204 /* Loop through all the buffers in the page. */
210 if (unlikely(buffer_uptodate(bh)))
212 if (unlikely(buffer_mapped(bh))) {
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;
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;
228 down_read(&ni->run_list.lock);
229 rl = ni->run_list.rl;
231 if (likely(rl != NULL)) {
232 /* Seek to element containing target vcn. */
233 while (rl->length && rl[1].vcn <= vcn)
235 lcn = vcn_to_lcn(rl, vcn);
237 lcn = (LCN)LCN_RL_NOT_MAPPED;
238 /* Successful remap. */
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) {
249 /* Fully non-initialized data block, zero it. */
252 /* It is a hole, need to zero it. */
255 /* If first try and run list unmapped, map and retry. */
256 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
259 * Attempt to map run list, dropping lock for
262 up_read(&ni->run_list.lock);
263 if (!map_run_list(ni, vcn))
264 goto lock_retry_remap;
267 /* Hard error, zero out region. */
269 ntfs_error(vol->sb, "vcn_to_lcn(vcn = 0x%llx) failed "
270 "with error code 0x%llx%s.",
271 (unsigned long long)vcn,
272 (unsigned long long)-lcn,
273 is_retry ? " even after retrying" : "");
274 // FIXME: Depending on vol->on_errors, do something.
277 * Either iblock was outside lblock limits or vcn_to_lcn()
278 * returned error. Just zero that portion of the page and set
279 * the buffer uptodate.
282 bh->b_blocknr = -1UL;
283 clear_buffer_mapped(bh);
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);
292 /* Release the lock if we took it. */
294 up_read(&ni->run_list.lock);
296 /* Check we have at least one buffer ready for i/o. */
298 struct buffer_head *tbh;
300 /* Lock the buffers. */
301 for (i = 0; i < nr; i++) {
304 tbh->b_end_io = ntfs_end_buffer_async_read;
305 set_buffer_async_read(tbh);
307 /* Finally, start i/o on the buffers. */
308 for (i = 0; i < nr; i++) {
310 if (likely(!buffer_uptodate(tbh)))
311 submit_bh(READ, tbh);
313 ntfs_end_buffer_async_read(tbh, 1);
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. */
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
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.
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.
342 * Return 0 on success and -errno on error.
344 * WARNING: Do not make this function static! It is used by mft.c!
346 int ntfs_readpage(struct file *file, struct page *page)
349 ntfs_inode *ni, *base_ni;
351 attr_search_context *ctx;
356 BUG_ON(!PageLocked(page));
359 * This can potentially happen because we clear PageUptodate() during
360 * ntfs_writepage() of MstProtected() attributes.
362 if (PageUptodate(page)) {
367 ni = NTFS_I(page->mapping->host);
369 /* NInoNonResident() == NInoIndexAllocPresent() */
370 if (NInoNonResident(ni)) {
372 * Only unnamed $DATA attributes can be compressed or
375 if (ni->type == AT_DATA && !ni->name_len) {
376 /* If file is encrypted, deny access, just like NT4. */
377 if (NInoEncrypted(ni)) {
381 /* Compressed data streams are handled in compress.c. */
382 if (NInoCompressed(ni))
383 return ntfs_read_compressed_block(page);
385 /* Normal data stream. */
386 return ntfs_read_block(page);
388 /* Attribute is resident, implying it is not compressed or encrypted. */
392 base_ni = ni->ext.base_ntfs_ino;
394 /* Map, pin, and lock the mft record. */
395 mrec = map_mft_record(base_ni);
396 if (unlikely(IS_ERR(mrec))) {
400 ctx = get_attr_search_ctx(base_ni, mrec);
401 if (unlikely(!ctx)) {
405 if (unlikely(!lookup_attr(ni->type, ni->name, ni->name_len,
406 CASE_SENSITIVE, 0, NULL, 0, ctx))) {
408 goto put_unm_err_out;
411 /* Starting position of the page within the attribute value. */
412 attr_pos = page->index << PAGE_CACHE_SHIFT;
414 /* The total length of the attribute value. */
415 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
417 kaddr = kmap_atomic(page, KM_USER0);
418 /* Copy over in bounds data, zeroing the remainder of the page. */
419 if (attr_pos < attr_len) {
420 u32 bytes = attr_len - attr_pos;
421 if (bytes > PAGE_CACHE_SIZE)
422 bytes = PAGE_CACHE_SIZE;
423 else if (bytes < PAGE_CACHE_SIZE)
424 memset(kaddr + bytes, 0, PAGE_CACHE_SIZE - bytes);
425 /* Copy the data to the page. */
426 memcpy(kaddr, attr_pos + (char*)ctx->attr +
428 ctx->attr->data.resident.value_offset), bytes);
430 memset(kaddr, 0, PAGE_CACHE_SIZE);
431 flush_dcache_page(page);
432 kunmap_atomic(kaddr, KM_USER0);
434 SetPageUptodate(page);
436 put_attr_search_ctx(ctx);
438 unmap_mft_record(base_ni);
447 * ntfs_write_block - write a @page to the backing store
448 * @wbc: writeback control structure
449 * @page: page cache page to write out
451 * This function is for writing pages belonging to non-resident, non-mst
452 * protected attributes to their backing store.
454 * For a page with buffers, map and write the dirty buffers asynchronously
455 * under page writeback. For a page without buffers, create buffers for the
456 * page, then proceed as above.
458 * If a page doesn't have buffers the page dirty state is definitive. If a page
459 * does have buffers, the page dirty state is just a hint, and the buffer dirty
460 * state is definitive. (A hint which has rules: dirty buffers against a clean
461 * page is illegal. Other combinations are legal and need to be handled. In
462 * particular a dirty page containing clean buffers for example.)
464 * Return 0 on success and -errno on error.
466 * Based on ntfs_read_block() and __block_write_full_page().
468 static int ntfs_write_block(struct writeback_control *wbc, struct page *page)
472 sector_t block, dblock, iblock;
476 run_list_element *rl;
477 struct buffer_head *bh, *head;
478 unsigned int blocksize, vcn_ofs;
480 BOOL need_end_writeback;
481 unsigned char blocksize_bits;
483 vi = page->mapping->host;
487 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
488 "0x%lx.", vi->i_ino, ni->type, page->index);
490 BUG_ON(!NInoNonResident(ni));
491 BUG_ON(NInoMstProtected(ni));
493 blocksize_bits = vi->i_blkbits;
494 blocksize = 1 << blocksize_bits;
496 if (!page_has_buffers(page)) {
497 BUG_ON(!PageUptodate(page));
498 create_empty_buffers(page, blocksize,
499 (1 << BH_Uptodate) | (1 << BH_Dirty));
501 bh = head = page_buffers(page);
503 ntfs_warning(vol->sb, "Error allocating page buffers. "
504 "Redirtying page so we try again later.");
506 * Put the page back on mapping->dirty_pages, but leave its
507 * buffer's dirty state as-is.
509 redirty_page_for_writepage(wbc, page);
514 /* NOTE: Different naming scheme to ntfs_read_block()! */
516 /* The first block in the page. */
517 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
519 /* The first out of bounds block for the data size. */
520 dblock = (vi->i_size + blocksize - 1) >> blocksize_bits;
522 /* The last (fully or partially) initialized block. */
523 iblock = ni->initialized_size >> blocksize_bits;
526 * Be very careful. We have no exclusion from __set_page_dirty_buffers
527 * here, and the (potentially unmapped) buffers may become dirty at
528 * any time. If a buffer becomes dirty here after we've inspected it
529 * then we just miss that fact, and the page stays dirty.
531 * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
532 * handle that here by just cleaning them.
536 * Loop through all the buffers in the page, mapping all the dirty
537 * buffers to disk addresses and handling any aliases from the
538 * underlying block device's mapping.
543 BOOL is_retry = FALSE;
545 if (unlikely(block >= dblock)) {
547 * Mapped buffers outside i_size will occur, because
548 * this page can be outside i_size when there is a
549 * truncate in progress. The contents of such buffers
550 * were zeroed by ntfs_writepage().
552 * FIXME: What about the small race window where
553 * ntfs_writepage() has not done any clearing because
554 * the page was within i_size but before we get here,
555 * vmtruncate() modifies i_size?
557 clear_buffer_dirty(bh);
558 set_buffer_uptodate(bh);
562 /* Clean buffers are not written out, so no need to map them. */
563 if (!buffer_dirty(bh))
566 /* Make sure we have enough initialized size. */
567 if (unlikely((block >= iblock) &&
568 (ni->initialized_size < vi->i_size))) {
570 * If this page is fully outside initialized size, zero
571 * out all pages between the current initialized size
572 * and the current page. Just use ntfs_readpage() to do
573 * the zeroing transparently.
575 if (block > iblock) {
578 // - read_cache_page()
579 // Again for each page do:
580 // - wait_on_page_locked()
581 // - Check (PageUptodate(page) &&
583 // Update initialized size in the attribute and
585 // Again, for each page do:
586 // __set_page_dirty_buffers();
587 // page_cache_release()
588 // We don't need to wait on the writes.
592 * The current page straddles initialized size. Zero
593 * all non-uptodate buffers and set them uptodate (and
594 * dirty?). Note, there aren't any non-uptodate buffers
595 * if the page is uptodate.
596 * FIXME: For an uptodate page, the buffers may need to
597 * be written out because they were not initialized on
600 if (!PageUptodate(page)) {
602 // Zero any non-uptodate buffers up to i_size.
603 // Set them uptodate and dirty.
606 // Update initialized size in the attribute and in the
607 // inode (up to i_size).
609 // FIXME: This is inefficient. Try to batch the two
610 // size changes to happen in one go.
611 ntfs_error(vol->sb, "Writing beyond initialized size "
612 "is not supported yet. Sorry.");
615 // Do NOT set_buffer_new() BUT DO clear buffer range
616 // outside write request range.
617 // set_buffer_uptodate() on complete buffers as well as
618 // set_buffer_dirty().
621 /* No need to map buffers that are already mapped. */
622 if (buffer_mapped(bh))
625 /* Unmapped, dirty buffer. Need to map it. */
626 bh->b_bdev = vol->sb->s_bdev;
628 /* Convert block into corresponding vcn and offset. */
629 vcn = (VCN)block << blocksize_bits >> vol->cluster_size_bits;
630 vcn_ofs = ((VCN)block << blocksize_bits) &
631 vol->cluster_size_mask;
634 down_read(&ni->run_list.lock);
635 rl = ni->run_list.rl;
637 if (likely(rl != NULL)) {
638 /* Seek to element containing target vcn. */
639 while (rl->length && rl[1].vcn <= vcn)
641 lcn = vcn_to_lcn(rl, vcn);
643 lcn = (LCN)LCN_RL_NOT_MAPPED;
644 /* Successful remap. */
646 /* Setup buffer head to point to correct block. */
647 bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
648 vcn_ofs) >> blocksize_bits;
649 set_buffer_mapped(bh);
652 /* It is a hole, need to instantiate it. */
653 if (lcn == LCN_HOLE) {
654 // TODO: Instantiate the hole.
655 // clear_buffer_new(bh);
656 // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
657 ntfs_error(vol->sb, "Writing into sparse regions is "
658 "not supported yet. Sorry.");
662 /* If first try and run list unmapped, map and retry. */
663 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
666 * Attempt to map run list, dropping lock for
669 up_read(&ni->run_list.lock);
670 err = map_run_list(ni, vcn);
672 goto lock_retry_remap;
675 /* Failed to map the buffer, even after retrying. */
676 bh->b_blocknr = -1UL;
677 ntfs_error(vol->sb, "vcn_to_lcn(vcn = 0x%llx) failed "
678 "with error code 0x%llx%s.",
679 (unsigned long long)vcn,
680 (unsigned long long)-lcn,
681 is_retry ? " even after retrying" : "");
682 // FIXME: Depending on vol->on_errors, do something.
686 } while (block++, (bh = bh->b_this_page) != head);
688 /* Release the lock if we took it. */
690 up_read(&ni->run_list.lock);
692 /* For the error case, need to reset bh to the beginning. */
695 /* Just an optimization, so ->readpage() isn't called later. */
696 if (unlikely(!PageUptodate(page))) {
699 if (!buffer_uptodate(bh)) {
704 } while ((bh = bh->b_this_page) != head);
706 SetPageUptodate(page);
709 /* Setup all mapped, dirty buffers for async write i/o. */
712 if (buffer_mapped(bh) && buffer_dirty(bh)) {
714 if (test_clear_buffer_dirty(bh)) {
715 BUG_ON(!buffer_uptodate(bh));
716 mark_buffer_async_write(bh);
719 } else if (unlikely(err)) {
721 * For the error case. The buffer may have been set
722 * dirty during attachment to a dirty page.
725 clear_buffer_dirty(bh);
727 } while ((bh = bh->b_this_page) != head);
730 // TODO: Remove the -EOPNOTSUPP check later on...
731 if (unlikely(err == -EOPNOTSUPP))
733 else if (err == -ENOMEM) {
734 ntfs_warning(vol->sb, "Error allocating memory. "
735 "Redirtying page so we try again "
738 * Put the page back on mapping->dirty_pages, but
739 * leave its buffer's dirty state as-is.
741 redirty_page_for_writepage(wbc, page);
747 BUG_ON(PageWriteback(page));
748 set_page_writeback(page); /* Keeps try_to_free_buffers() away. */
752 * Submit the prepared buffers for i/o. Note the page is unlocked,
753 * and the async write i/o completion handler can end_page_writeback()
754 * at any time after the *first* submit_bh(). So the buffers can then
757 need_end_writeback = TRUE;
759 struct buffer_head *next = bh->b_this_page;
760 if (buffer_async_write(bh)) {
761 submit_bh(WRITE, bh);
762 need_end_writeback = FALSE;
766 } while (bh != head);
768 /* If no i/o was started, need to end_page_writeback(). */
769 if (unlikely(need_end_writeback))
770 end_page_writeback(page);
776 static const char *ntfs_please_email = "Please email "
777 "linux-ntfs-dev@lists.sourceforge.net and say that you saw "
778 "this message. Thank you.";
781 * ntfs_write_mst_block - write a @page to the backing store
782 * @wbc: writeback control structure
783 * @page: page cache page to write out
785 * This function is for writing pages belonging to non-resident, mst protected
786 * attributes to their backing store. The only supported attribute is the
787 * index allocation attribute. Both directory inodes and index inodes are
790 * The page must remain locked for the duration of the write because we apply
791 * the mst fixups, write, and then undo the fixups, so if we were to unlock the
792 * page before undoing the fixups, any other user of the page will see the
793 * page contents as corrupt.
795 * Return 0 on success and -errno on error.
797 * Based on ntfs_write_block(), ntfs_mft_writepage(), and
798 * write_mft_record_nolock().
800 static int ntfs_write_mst_block(struct writeback_control *wbc,
803 sector_t block, dblock, rec_block;
804 struct inode *vi = page->mapping->host;
805 ntfs_inode *ni = NTFS_I(vi);
806 ntfs_volume *vol = ni->vol;
808 unsigned int bh_size = 1 << vi->i_blkbits;
809 unsigned int rec_size;
810 struct buffer_head *bh, *head;
811 int max_bhs = PAGE_CACHE_SIZE / bh_size;
812 struct buffer_head *bhs[max_bhs];
813 int i, nr_recs, nr_bhs, bhs_per_rec, err;
814 unsigned char bh_size_bits;
817 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
818 "0x%lx.", vi->i_ino, ni->type, page->index);
819 BUG_ON(!NInoNonResident(ni));
820 BUG_ON(!NInoMstProtected(ni));
821 BUG_ON(!(S_ISDIR(vi->i_mode) ||
822 (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
823 BUG_ON(PageWriteback(page));
824 BUG_ON(!PageUptodate(page));
827 /* Make sure we have mapped buffers. */
828 if (unlikely(!page_has_buffers(page))) {
830 ntfs_error(vol->sb, "Writing ntfs records without existing "
831 "buffers is not implemented yet. %s",
836 bh = head = page_buffers(page);
838 goto no_buffers_err_out;
840 bh_size_bits = vi->i_blkbits;
841 rec_size = ni->itype.index.block_size;
842 nr_recs = PAGE_CACHE_SIZE / rec_size;
844 bhs_per_rec = rec_size >> bh_size_bits;
845 BUG_ON(!bhs_per_rec);
847 /* The first block in the page. */
848 rec_block = block = (s64)page->index <<
849 (PAGE_CACHE_SHIFT - bh_size_bits);
851 /* The first out of bounds block for the data size. */
852 dblock = (vi->i_size + bh_size - 1) >> bh_size_bits;
855 /* Need this to silence a stupid gcc warning. */
856 rec_is_dirty = FALSE;
858 if (unlikely(block >= dblock)) {
860 * Mapped buffers outside i_size will occur, because
861 * this page can be outside i_size when there is a
862 * truncate in progress. The contents of such buffers
863 * were zeroed by ntfs_writepage().
865 * FIXME: What about the small race window where
866 * ntfs_writepage() has not done any clearing because
867 * the page was within i_size but before we get here,
868 * vmtruncate() modifies i_size?
870 clear_buffer_dirty(bh);
873 if (rec_block == block) {
874 /* This block is the first one in the record. */
875 rec_block += rec_size >> bh_size_bits;
876 if (!buffer_dirty(bh)) {
877 /* Clean buffers are not written out. */
878 rec_is_dirty = FALSE;
883 /* This block is not the first one in the record. */
884 if (!buffer_dirty(bh)) {
885 /* Clean buffers are not written out. */
886 BUG_ON(rec_is_dirty);
889 BUG_ON(!rec_is_dirty);
891 /* Attempting to write outside the initialized size is a bug. */
892 BUG_ON(((block + 1) << bh_size_bits) > ni->initialized_size);
893 if (!buffer_mapped(bh)) {
894 ntfs_error(vol->sb, "Writing ntfs records without "
895 "existing mapped buffers is not "
896 "implemented yet. %s",
898 clear_buffer_dirty(bh);
902 if (!buffer_uptodate(bh)) {
903 ntfs_error(vol->sb, "Writing ntfs records without "
904 "existing uptodate buffers is not "
905 "implemented yet. %s",
907 clear_buffer_dirty(bh);
912 BUG_ON(nr_bhs > max_bhs);
913 } while (block++, (bh = bh->b_this_page) != head);
914 /* If there were no dirty buffers, we are done. */
917 /* Apply the mst protection fixups. */
918 kaddr = page_address(page);
919 for (i = 0; i < nr_bhs; i++) {
920 if (!(i % bhs_per_rec)) {
921 err = pre_write_mst_fixup((NTFS_RECORD*)(kaddr +
922 bh_offset(bhs[i])), rec_size);
924 ntfs_error(vol->sb, "Failed to apply mst "
925 "fixups (inode 0x%lx, "
926 "attribute type 0x%x, page "
927 "index 0x%lx)! Umount and "
928 "run chkdsk.", vi->i_ino,
932 goto mst_cleanup_out;
936 flush_dcache_page(page);
937 /* Lock buffers and start synchronous write i/o on them. */
938 for (i = 0; i < nr_bhs; i++) {
939 struct buffer_head *tbh = bhs[i];
941 if (unlikely(test_set_buffer_locked(tbh)))
943 if (unlikely(!test_clear_buffer_dirty(tbh))) {
947 BUG_ON(!buffer_uptodate(tbh));
948 BUG_ON(!buffer_mapped(tbh));
950 tbh->b_end_io = end_buffer_write_sync;
951 submit_bh(WRITE, tbh);
953 /* Wait on i/o completion of buffers. */
954 for (i = 0; i < nr_bhs; i++) {
955 struct buffer_head *tbh = bhs[i];
958 if (unlikely(!buffer_uptodate(tbh))) {
961 * Set the buffer uptodate so the page & buffer states
962 * don't become out of sync.
964 if (PageUptodate(page))
965 set_buffer_uptodate(tbh);
968 /* Remove the mst protection fixups again. */
969 for (i = 0; i < nr_bhs; i++) {
970 if (!(i % bhs_per_rec))
971 post_write_mst_fixup((NTFS_RECORD*)(kaddr +
974 flush_dcache_page(page);
976 /* I/O error during writing. This is really bad! */
977 ntfs_error(vol->sb, "I/O error while writing ntfs record "
978 "(inode 0x%lx, attribute type 0x%x, page "
979 "index 0x%lx)! Umount and run chkdsk.",
980 vi->i_ino, ni->type, page->index);
984 set_page_writeback(page);
986 end_page_writeback(page);
991 /* Remove the mst protection fixups again. */
992 for (i = 0; i < nr_bhs; i++) {
993 if (!(i % bhs_per_rec))
994 post_write_mst_fixup((NTFS_RECORD*)(kaddr +
998 /* Clean the buffers. */
999 for (i = 0; i < nr_bhs; i++)
1000 clear_buffer_dirty(bhs[i]);
1007 * ntfs_writepage - write a @page to the backing store
1008 * @page: page cache page to write out
1009 * @wbc: writeback control structure
1011 * For non-resident attributes, ntfs_writepage() writes the @page by calling
1012 * the ntfs version of the generic block_write_full_page() function,
1013 * ntfs_write_block(), which in turn if necessary creates and writes the
1014 * buffers associated with the page asynchronously.
1016 * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1017 * the data to the mft record (which at this stage is most likely in memory).
1018 * The mft record is then marked dirty and written out asynchronously via the
1019 * vfs inode dirty code path.
1021 * Note the caller clears the page dirty flag before calling ntfs_writepage().
1023 * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1025 * Return 0 on success and -errno on error.
1027 static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1031 ntfs_inode *ni, *base_ni;
1033 attr_search_context *ctx;
1035 u32 attr_len, bytes;
1038 BUG_ON(!PageLocked(page));
1040 vi = page->mapping->host;
1042 /* Is the page fully outside i_size? (truncate in progress) */
1043 if (unlikely(page->index >= (vi->i_size + PAGE_CACHE_SIZE - 1) >>
1044 PAGE_CACHE_SHIFT)) {
1046 ntfs_debug("Write outside i_size - truncated?");
1052 /* NInoNonResident() == NInoIndexAllocPresent() */
1053 if (NInoNonResident(ni)) {
1055 * Only unnamed $DATA attributes can be compressed, encrypted,
1058 if (ni->type == AT_DATA && !ni->name_len) {
1059 /* If file is encrypted, deny access, just like NT4. */
1060 if (NInoEncrypted(ni)) {
1062 ntfs_debug("Denying write access to encrypted "
1066 /* Compressed data streams are handled in compress.c. */
1067 if (NInoCompressed(ni)) {
1068 // TODO: Implement and replace this check with
1069 // return ntfs_write_compressed_block(page);
1071 ntfs_error(vi->i_sb, "Writing to compressed "
1072 "files is not supported yet. "
1076 // TODO: Implement and remove this check.
1077 if (NInoSparse(ni)) {
1079 ntfs_error(vi->i_sb, "Writing to sparse files "
1080 "is not supported yet. Sorry.");
1084 /* We have to zero every time due to mmap-at-end-of-file. */
1085 if (page->index >= (vi->i_size >> PAGE_CACHE_SHIFT)) {
1086 /* The page straddles i_size. */
1087 unsigned int ofs = vi->i_size & ~PAGE_CACHE_MASK;
1088 kaddr = kmap_atomic(page, KM_USER0);
1089 memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1090 flush_dcache_page(page);
1091 kunmap_atomic(kaddr, KM_USER0);
1093 /* Handle mst protected attributes. */
1094 if (NInoMstProtected(ni))
1095 return ntfs_write_mst_block(wbc, page);
1096 /* Normal data stream. */
1097 return ntfs_write_block(wbc, page);
1101 * Attribute is resident, implying it is not compressed, encrypted, or
1104 BUG_ON(page_has_buffers(page));
1105 BUG_ON(!PageUptodate(page));
1110 base_ni = ni->ext.base_ntfs_ino;
1112 /* Map, pin, and lock the mft record. */
1113 m = map_mft_record(base_ni);
1114 if (unlikely(IS_ERR(m))) {
1120 ctx = get_attr_search_ctx(base_ni, m);
1121 if (unlikely(!ctx)) {
1125 if (unlikely(!lookup_attr(ni->type, ni->name, ni->name_len,
1126 CASE_SENSITIVE, 0, NULL, 0, ctx))) {
1131 /* Starting position of the page within the attribute value. */
1132 attr_pos = page->index << PAGE_CACHE_SHIFT;
1134 /* The total length of the attribute value. */
1135 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
1137 if (unlikely(vi->i_size != attr_len)) {
1138 ntfs_error(vi->i_sb, "BUG()! i_size (0x%llx) doesn't match "
1139 "attr_len (0x%x). Aborting write.", vi->i_size,
1144 if (unlikely(attr_pos >= attr_len)) {
1145 ntfs_error(vi->i_sb, "BUG()! attr_pos (0x%llx) > attr_len "
1146 "(0x%x). Aborting write.",
1147 (unsigned long long)attr_pos, attr_len);
1152 bytes = attr_len - attr_pos;
1153 if (unlikely(bytes > PAGE_CACHE_SIZE))
1154 bytes = PAGE_CACHE_SIZE;
1157 * Keep the VM happy. This must be done otherwise the radix-tree tag
1158 * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1160 BUG_ON(PageWriteback(page));
1161 set_page_writeback(page);
1165 * Here, we don't need to zero the out of bounds area everytime because
1166 * the below memcpy() already takes care of the mmap-at-end-of-file
1167 * requirements. If the file is converted to a non-resident one, then
1168 * the code path use is switched to the non-resident one where the
1169 * zeroing happens on each ntfs_writepage() invocation.
1171 * The above also applies nicely when i_size is decreased.
1173 * When i_size is increased, the memory between the old and new i_size
1174 * _must_ be zeroed (or overwritten with new data). Otherwise we will
1175 * expose data to userspace/disk which should never have been exposed.
1177 * FIXME: Ensure that i_size increases do the zeroing/overwriting and
1178 * if we cannot guarantee that, then enable the zeroing below. If the
1179 * zeroing below is enabled, we MUST move the unlock_page() from above
1180 * to after the kunmap_atomic(), i.e. just before the
1181 * end_page_writeback().
1184 kaddr = kmap_atomic(page, KM_USER0);
1185 /* Copy the data from the page to the mft record. */
1186 memcpy((u8*)ctx->attr + le16_to_cpu(
1187 ctx->attr->data.resident.value_offset) + attr_pos,
1189 flush_dcache_mft_record_page(ctx->ntfs_ino);
1191 /* Zero out of bounds area. */
1192 if (likely(bytes < PAGE_CACHE_SIZE)) {
1193 memset(kaddr + bytes, 0, PAGE_CACHE_SIZE - bytes);
1194 flush_dcache_page(page);
1197 kunmap_atomic(kaddr, KM_USER0);
1199 end_page_writeback(page);
1201 /* Mark the mft record dirty, so it gets written back. */
1202 mark_mft_record_dirty(ctx->ntfs_ino);
1204 put_attr_search_ctx(ctx);
1205 unmap_mft_record(base_ni);
1208 if (err == -ENOMEM) {
1209 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1210 "page so we try again later.");
1212 * Put the page back on mapping->dirty_pages, but leave its
1213 * buffer's dirty state as-is.
1215 redirty_page_for_writepage(wbc, page);
1218 ntfs_error(vi->i_sb, "Resident attribute write failed with "
1219 "error %i. Setting page error flag.", -err);
1224 put_attr_search_ctx(ctx);
1226 unmap_mft_record(base_ni);
1231 * ntfs_prepare_nonresident_write -
1234 static int ntfs_prepare_nonresident_write(struct page *page,
1235 unsigned from, unsigned to)
1239 sector_t block, ablock, iblock;
1243 run_list_element *rl;
1244 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1245 unsigned int vcn_ofs, block_start, block_end, blocksize;
1248 unsigned char blocksize_bits;
1250 vi = page->mapping->host;
1254 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1255 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1256 page->index, from, to);
1258 BUG_ON(!NInoNonResident(ni));
1259 BUG_ON(NInoMstProtected(ni));
1261 blocksize_bits = vi->i_blkbits;
1262 blocksize = 1 << blocksize_bits;
1265 * create_empty_buffers() will create uptodate/dirty buffers if the
1266 * page is uptodate/dirty.
1268 if (!page_has_buffers(page))
1269 create_empty_buffers(page, blocksize, 0);
1270 bh = head = page_buffers(page);
1274 /* The first block in the page. */
1275 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
1278 * The first out of bounds block for the allocated size. No need to
1279 * round up as allocated_size is in multiples of cluster size and the
1280 * minimum cluster size is 512 bytes, which is equal to the smallest
1283 ablock = ni->allocated_size >> blocksize_bits;
1285 /* The last (fully or partially) initialized block. */
1286 iblock = ni->initialized_size >> blocksize_bits;
1288 /* Loop through all the buffers in the page. */
1293 block_end = block_start + blocksize;
1295 * If buffer @bh is outside the write, just mark it uptodate
1296 * if the page is uptodate and continue with the next buffer.
1298 if (block_end <= from || block_start >= to) {
1299 if (PageUptodate(page)) {
1300 if (!buffer_uptodate(bh))
1301 set_buffer_uptodate(bh);
1306 * @bh is at least partially being written to.
1307 * Make sure it is not marked as new.
1309 //if (buffer_new(bh))
1310 // clear_buffer_new(bh);
1312 if (block >= ablock) {
1313 // TODO: block is above allocated_size, need to
1314 // allocate it. Best done in one go to accommodate not
1315 // only block but all above blocks up to and including:
1316 // ((page->index << PAGE_CACHE_SHIFT) + to + blocksize
1317 // - 1) >> blobksize_bits. Obviously will need to round
1318 // up to next cluster boundary, too. This should be
1319 // done with a helper function, so it can be reused.
1320 ntfs_error(vol->sb, "Writing beyond allocated size "
1321 "is not supported yet. Sorry.");
1324 // Need to update ablock.
1325 // Need to set_buffer_new() on all block bhs that are
1329 * Now we have enough allocated size to fulfill the whole
1330 * request, i.e. block < ablock is true.
1332 if (unlikely((block >= iblock) &&
1333 (ni->initialized_size < vi->i_size))) {
1335 * If this page is fully outside initialized size, zero
1336 * out all pages between the current initialized size
1337 * and the current page. Just use ntfs_readpage() to do
1338 * the zeroing transparently.
1340 if (block > iblock) {
1342 // For each page do:
1343 // - read_cache_page()
1344 // Again for each page do:
1345 // - wait_on_page_locked()
1346 // - Check (PageUptodate(page) &&
1347 // !PageError(page))
1348 // Update initialized size in the attribute and
1350 // Again, for each page do:
1351 // __set_page_dirty_buffers();
1352 // page_cache_release()
1353 // We don't need to wait on the writes.
1357 * The current page straddles initialized size. Zero
1358 * all non-uptodate buffers and set them uptodate (and
1359 * dirty?). Note, there aren't any non-uptodate buffers
1360 * if the page is uptodate.
1361 * FIXME: For an uptodate page, the buffers may need to
1362 * be written out because they were not initialized on
1365 if (!PageUptodate(page)) {
1367 // Zero any non-uptodate buffers up to i_size.
1368 // Set them uptodate and dirty.
1371 // Update initialized size in the attribute and in the
1372 // inode (up to i_size).
1374 // FIXME: This is inefficient. Try to batch the two
1375 // size changes to happen in one go.
1376 ntfs_error(vol->sb, "Writing beyond initialized size "
1377 "is not supported yet. Sorry.");
1380 // Do NOT set_buffer_new() BUT DO clear buffer range
1381 // outside write request range.
1382 // set_buffer_uptodate() on complete buffers as well as
1383 // set_buffer_dirty().
1386 /* Need to map unmapped buffers. */
1387 if (!buffer_mapped(bh)) {
1388 /* Unmapped buffer. Need to map it. */
1389 bh->b_bdev = vol->sb->s_bdev;
1391 /* Convert block into corresponding vcn and offset. */
1392 vcn = (VCN)block << blocksize_bits >>
1393 vol->cluster_size_bits;
1394 vcn_ofs = ((VCN)block << blocksize_bits) &
1395 vol->cluster_size_mask;
1400 down_read(&ni->run_list.lock);
1401 rl = ni->run_list.rl;
1403 if (likely(rl != NULL)) {
1404 /* Seek to element containing target vcn. */
1405 while (rl->length && rl[1].vcn <= vcn)
1407 lcn = vcn_to_lcn(rl, vcn);
1409 lcn = (LCN)LCN_RL_NOT_MAPPED;
1410 if (unlikely(lcn < 0)) {
1412 * We extended the attribute allocation above.
1413 * If we hit an ENOENT here it means that the
1414 * allocation was insufficient which is a bug.
1416 BUG_ON(lcn == LCN_ENOENT);
1418 /* It is a hole, need to instantiate it. */
1419 if (lcn == LCN_HOLE) {
1420 // TODO: Instantiate the hole.
1421 // clear_buffer_new(bh);
1422 // unmap_underlying_metadata(bh->b_bdev,
1424 // For non-uptodate buffers, need to
1425 // zero out the region outside the
1426 // request in this bh or all bhs,
1427 // depending on what we implemented
1429 // Need to flush_dcache_page().
1430 // Or could use set_buffer_new()
1432 ntfs_error(vol->sb, "Writing into "
1433 "sparse regions is "
1434 "not supported yet. "
1438 } else if (!is_retry &&
1439 lcn == LCN_RL_NOT_MAPPED) {
1442 * Attempt to map run list, dropping
1443 * lock for the duration.
1445 up_read(&ni->run_list.lock);
1446 err = map_run_list(ni, vcn);
1448 goto lock_retry_remap;
1452 * Failed to map the buffer, even after
1455 bh->b_blocknr = -1UL;
1456 ntfs_error(vol->sb, "vcn_to_lcn(vcn = 0x%llx) "
1457 "failed with error code "
1459 (unsigned long long)vcn,
1460 (unsigned long long)-lcn,
1461 is_retry ? " even after "
1463 // FIXME: Depending on vol->on_errors, do
1469 /* We now have a successful remap, i.e. lcn >= 0. */
1471 /* Setup buffer head to correct block. */
1472 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
1473 + vcn_ofs) >> blocksize_bits;
1474 set_buffer_mapped(bh);
1476 // FIXME: Something analogous to this is needed for
1477 // each newly allocated block, i.e. BH_New.
1478 // FIXME: Might need to take this out of the
1479 // if (!buffer_mapped(bh)) {}, depending on how we
1480 // implement things during the allocated_size and
1481 // initialized_size extension code above.
1482 if (buffer_new(bh)) {
1483 clear_buffer_new(bh);
1484 unmap_underlying_metadata(bh->b_bdev,
1486 if (PageUptodate(page)) {
1487 set_buffer_uptodate(bh);
1491 * Page is _not_ uptodate, zero surrounding
1492 * region. NOTE: This is how we decide if to
1495 if (block_end > to || block_start < from) {
1498 kaddr = kmap_atomic(page, KM_USER0);
1500 memset(kaddr + to, 0,
1502 if (block_start < from)
1503 memset(kaddr + block_start, 0,
1506 flush_dcache_page(page);
1507 kunmap_atomic(kaddr, KM_USER0);
1512 /* @bh is mapped, set it uptodate if the page is uptodate. */
1513 if (PageUptodate(page)) {
1514 if (!buffer_uptodate(bh))
1515 set_buffer_uptodate(bh);
1519 * The page is not uptodate. The buffer is mapped. If it is not
1520 * uptodate, and it is only partially being written to, we need
1521 * to read the buffer in before the write, i.e. right now.
1523 if (!buffer_uptodate(bh) &&
1524 (block_start < from || block_end > to)) {
1525 ll_rw_block(READ, 1, &bh);
1528 } while (block++, block_start = block_end,
1529 (bh = bh->b_this_page) != head);
1531 /* Release the lock if we took it. */
1533 up_read(&ni->run_list.lock);
1537 /* If we issued read requests, let them complete. */
1538 while (wait_bh > wait) {
1539 wait_on_buffer(*--wait_bh);
1540 if (!buffer_uptodate(*wait_bh))
1544 ntfs_debug("Done.");
1548 * Zero out any newly allocated blocks to avoid exposing stale data.
1549 * If BH_New is set, we know that the block was newly allocated in the
1551 * FIXME: What about initialized_size increments? Have we done all the
1552 * required zeroing above? If not this error handling is broken, and
1553 * in particular the if (block_end <= from) check is completely bogus.
1559 block_end = block_start + blocksize;
1560 if (block_end <= from)
1562 if (block_start >= to)
1564 if (buffer_new(bh)) {
1567 clear_buffer_new(bh);
1568 kaddr = kmap_atomic(page, KM_USER0);
1569 memset(kaddr + block_start, 0, bh->b_size);
1570 kunmap_atomic(kaddr, KM_USER0);
1571 set_buffer_uptodate(bh);
1572 mark_buffer_dirty(bh);
1575 } while (block_start = block_end, (bh = bh->b_this_page) != head);
1577 flush_dcache_page(page);
1579 up_read(&ni->run_list.lock);
1584 * ntfs_prepare_write - prepare a page for receiving data
1586 * This is called from generic_file_write() with i_sem held on the inode
1587 * (@page->mapping->host). The @page is locked and kmap()ped so page_address()
1588 * can simply be used. The source data has not yet been copied into the @page.
1590 * Need to extend the attribute/fill in holes if necessary, create blocks and
1591 * make partially overwritten blocks uptodate,
1593 * i_size is not to be modified yet.
1595 * Return 0 on success or -errno on error.
1597 * Should be using block_prepare_write() [support for sparse files] or
1598 * cont_prepare_write() [no support for sparse files]. Can't do that due to
1599 * ntfs specifics but can look at them for implementation guidancea.
1601 * Note: In the range, @from is inclusive and @to is exclusive, i.e. @from is
1602 * the first byte in the page that will be written to and @to is the first byte
1603 * after the last byte that will be written to.
1605 static int ntfs_prepare_write(struct file *file, struct page *page,
1606 unsigned from, unsigned to)
1608 struct inode *vi = page->mapping->host;
1609 ntfs_inode *ni = NTFS_I(vi);
1611 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1612 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1613 page->index, from, to);
1615 BUG_ON(!PageLocked(page));
1616 BUG_ON(from > PAGE_CACHE_SIZE);
1617 BUG_ON(to > PAGE_CACHE_SIZE);
1620 if (NInoNonResident(ni)) {
1622 * Only unnamed $DATA attributes can be compressed, encrypted,
1625 if (ni->type == AT_DATA && !ni->name_len) {
1626 /* If file is encrypted, deny access, just like NT4. */
1627 if (NInoEncrypted(ni)) {
1628 ntfs_debug("Denying write access to encrypted "
1632 /* Compressed data streams are handled in compress.c. */
1633 if (NInoCompressed(ni)) {
1634 // TODO: Implement and replace this check with
1635 // return ntfs_write_compressed_block(page);
1636 ntfs_error(vi->i_sb, "Writing to compressed "
1637 "files is not supported yet. "
1641 // TODO: Implement and remove this check.
1642 if (NInoSparse(ni)) {
1643 ntfs_error(vi->i_sb, "Writing to sparse files "
1644 "is not supported yet. Sorry.");
1649 // TODO: Implement and remove this check.
1650 if (NInoMstProtected(ni)) {
1651 ntfs_error(vi->i_sb, "Writing to MST protected "
1652 "attributes is not supported yet. "
1657 /* Normal data stream. */
1658 return ntfs_prepare_nonresident_write(page, from, to);
1662 * Attribute is resident, implying it is not compressed, encrypted, or
1665 BUG_ON(page_has_buffers(page));
1667 /* Do we need to resize the attribute? */
1668 if (((s64)page->index << PAGE_CACHE_SHIFT) + to > vi->i_size) {
1669 // TODO: Implement resize...
1670 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
1671 "not supported yet. Sorry.");
1676 * Because resident attributes are handled by memcpy() to/from the
1677 * corresponding MFT record, and because this form of i/o is byte
1678 * aligned rather than block aligned, there is no need to bring the
1679 * page uptodate here as in the non-resident case where we need to
1680 * bring the buffers straddled by the write uptodate before
1681 * generic_file_write() does the copying from userspace.
1683 * We thus defer the uptodate bringing of the page region outside the
1684 * region written to to ntfs_commit_write(). The reason for doing this
1685 * is that we save one round of:
1686 * map_mft_record(), get_attr_search_ctx(), lookup_attr(),
1687 * kmap_atomic(), kunmap_atomic(), put_attr_search_ctx(),
1688 * unmap_mft_record().
1689 * Which is obviously a very worthwhile save.
1691 * Thus we just return success now...
1693 ntfs_debug("Done.");
1698 * NOTES: There is a disparity between the apparent need to extend the
1699 * attribute in prepare write but to update i_size only in commit write.
1700 * Need to make sure i_sem protection is sufficient. And if not will need to
1701 * handle this in some way or another.
1705 * ntfs_commit_nonresident_write -
1708 static int ntfs_commit_nonresident_write(struct page *page,
1709 unsigned from, unsigned to)
1711 s64 pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
1713 struct buffer_head *bh, *head;
1714 unsigned int block_start, block_end, blocksize;
1717 vi = page->mapping->host;
1719 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1720 "0x%lx, from = %u, to = %u.", vi->i_ino,
1721 NTFS_I(vi)->type, page->index, from, to);
1723 blocksize = 1 << vi->i_blkbits;
1725 // FIXME: We need a whole slew of special cases in here for MST
1726 // protected attributes for example. For compressed files, too...
1727 // For now, we know ntfs_prepare_write() would have failed so we can't
1728 // get here in any of the cases which we have to special case, so we
1729 // are just a ripped off unrolled generic_commit_write() at present.
1731 bh = head = page_buffers(page);
1735 block_end = block_start + blocksize;
1736 if (block_end <= from || block_start >= to) {
1737 if (!buffer_uptodate(bh))
1740 set_buffer_uptodate(bh);
1741 mark_buffer_dirty(bh);
1743 } while (block_start = block_end, (bh = bh->b_this_page) != head);
1746 * If this is a partial write which happened to make all buffers
1747 * uptodate then we can optimize away a bogus ->readpage() for the next
1748 * read(). Here we 'discover' whether the page went uptodate as a
1749 * result of this (potentially partial) write.
1752 SetPageUptodate(page);
1755 * Not convinced about this at all. See disparity comment above. For
1756 * now we know ntfs_prepare_write() would have failed in the write
1757 * exceeds i_size case, so this will never trigger which is fine.
1759 if (pos > vi->i_size) {
1760 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
1761 "not supported yet. Sorry.");
1763 // vi->i_size = pos;
1764 // mark_inode_dirty(vi);
1766 ntfs_debug("Done.");
1771 * ntfs_commit_write - commit the received data
1773 * This is called from generic_file_write() with i_sem held on the inode
1774 * (@page->mapping->host). The @page is locked and kmap()ped so page_address()
1775 * can simply be used. The source data has already been copied into the @page.
1777 * Need to mark modified blocks dirty so they get written out later when
1778 * ntfs_writepage() is invoked by the VM.
1780 * Return 0 on success or -errno on error.
1782 * Should be using generic_commit_write(). This marks buffers uptodate and
1783 * dirty, sets the page uptodate if all buffers in the page are uptodate, and
1784 * updates i_size if the end of io is beyond i_size. In that case, it also
1785 * marks the inode dirty. - We could still use this (obviously except for
1786 * NInoMstProtected() attributes, where we will need to duplicate the core code
1787 * because we need our own async_io completion handler) but we could just do
1788 * the i_size update in prepare write, when we resize the attribute. Then
1789 * we would avoid the i_size update and mark_inode_dirty() happening here.
1791 * Can't use generic_commit_write() due to ntfs specialities but can look at
1792 * it for implementation guidance.
1794 * If things have gone as outlined in ntfs_prepare_write(), then we do not
1795 * need to do any page content modifications here at all, except in the write
1796 * to resident attribute case, where we need to do the uptodate bringing here
1797 * which we combine with the copying into the mft record which means we only
1798 * need to map the mft record and find the attribute record in it only once.
1800 static int ntfs_commit_write(struct file *file, struct page *page,
1801 unsigned from, unsigned to)
1805 ntfs_inode *ni, *base_ni;
1806 char *kaddr, *kattr;
1807 attr_search_context *ctx;
1809 u32 attr_len, bytes;
1812 vi = page->mapping->host;
1815 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1816 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1817 page->index, from, to);
1819 if (NInoNonResident(ni)) {
1821 * Only unnamed $DATA attributes can be compressed, encrypted,
1824 if (ni->type == AT_DATA && !ni->name_len) {
1825 /* If file is encrypted, deny access, just like NT4. */
1826 if (NInoEncrypted(ni)) {
1827 // Should never get here!
1828 ntfs_debug("Denying write access to encrypted "
1832 /* Compressed data streams are handled in compress.c. */
1833 if (NInoCompressed(ni)) {
1834 // TODO: Implement and replace this check with
1835 // return ntfs_write_compressed_block(page);
1836 // Should never get here!
1837 ntfs_error(vi->i_sb, "Writing to compressed "
1838 "files is not supported yet. "
1842 // TODO: Implement and remove this check.
1843 if (NInoSparse(ni)) {
1844 // Should never get here!
1845 ntfs_error(vi->i_sb, "Writing to sparse files "
1846 "is not supported yet. Sorry.");
1851 // TODO: Implement and remove this check.
1852 if (NInoMstProtected(ni)) {
1853 // Should never get here!
1854 ntfs_error(vi->i_sb, "Writing to MST protected "
1855 "attributes is not supported yet. "
1860 /* Normal data stream. */
1861 return ntfs_commit_nonresident_write(page, from, to);
1865 * Attribute is resident, implying it is not compressed, encrypted, or
1869 /* Do we need to resize the attribute? */
1870 if (((s64)page->index << PAGE_CACHE_SHIFT) + to > vi->i_size) {
1871 // TODO: Implement resize...
1872 // pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
1873 // vi->i_size = pos;
1874 // mark_inode_dirty(vi);
1875 // Should never get here!
1876 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
1877 "not supported yet. Sorry.");
1884 base_ni = ni->ext.base_ntfs_ino;
1886 /* Map, pin, and lock the mft record. */
1887 m = map_mft_record(base_ni);
1888 if (unlikely(IS_ERR(m))) {
1894 ctx = get_attr_search_ctx(base_ni, m);
1895 if (unlikely(!ctx)) {
1899 if (unlikely(!lookup_attr(ni->type, ni->name, ni->name_len,
1900 CASE_SENSITIVE, 0, NULL, 0, ctx))) {
1905 /* Starting position of the page within the attribute value. */
1906 attr_pos = page->index << PAGE_CACHE_SHIFT;
1908 /* The total length of the attribute value. */
1909 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
1911 if (unlikely(vi->i_size != attr_len)) {
1912 ntfs_error(vi->i_sb, "BUG()! i_size (0x%llx) doesn't match "
1913 "attr_len (0x%x). Aborting write.", vi->i_size,
1918 if (unlikely(attr_pos >= attr_len)) {
1919 ntfs_error(vi->i_sb, "BUG()! attr_pos (0x%llx) > attr_len "
1920 "(0x%x). Aborting write.",
1921 (unsigned long long)attr_pos, attr_len);
1926 bytes = attr_len - attr_pos;
1927 if (unlikely(bytes > PAGE_CACHE_SIZE))
1928 bytes = PAGE_CACHE_SIZE;
1931 * Calculate the address of the attribute value corresponding to the
1932 * beginning of the current data @page.
1934 kattr = (u8*)ctx->attr + le16_to_cpu(
1935 ctx->attr->data.resident.value_offset) + attr_pos;
1937 kaddr = kmap_atomic(page, KM_USER0);
1939 /* Copy the received data from the page to the mft record. */
1940 memcpy(kattr + from, kaddr + from, to - from);
1941 flush_dcache_mft_record_page(ctx->ntfs_ino);
1943 if (!PageUptodate(page)) {
1945 * Bring the out of bounds area(s) uptodate by copying data
1946 * from the mft record to the page.
1949 memcpy(kaddr, kattr, from);
1951 memcpy(kaddr + to, kattr + to, bytes - to);
1953 /* Zero the region outside the end of the attribute value. */
1954 if (likely(bytes < PAGE_CACHE_SIZE))
1955 memset(kaddr + bytes, 0, PAGE_CACHE_SIZE - bytes);
1958 * The probability of not having done any of the above is
1959 * extremely small, so we just flush unconditionally.
1961 flush_dcache_page(page);
1962 SetPageUptodate(page);
1964 kunmap_atomic(kaddr, KM_USER0);
1966 /* Mark the mft record dirty, so it gets written back. */
1967 mark_mft_record_dirty(ctx->ntfs_ino);
1969 put_attr_search_ctx(ctx);
1970 unmap_mft_record(base_ni);
1971 ntfs_debug("Done.");
1974 if (err == -ENOMEM) {
1975 ntfs_warning(vi->i_sb, "Error allocating memory required to "
1976 "commit the write.");
1977 if (PageUptodate(page)) {
1978 ntfs_warning(vi->i_sb, "Page is uptodate, setting "
1979 "dirty so the write will be retried "
1980 "later on by the VM.");
1982 * Put the page on mapping->dirty_pages, but leave its
1983 * buffer's dirty state as-is.
1985 __set_page_dirty_nobuffers(page);
1988 ntfs_error(vi->i_sb, "Page is not uptodate. Written "
1989 "data has been lost. )-:");
1991 ntfs_error(vi->i_sb, "Resident attribute write failed with "
1992 "error %i. Setting page error flag.", -err);
1996 put_attr_search_ctx(ctx);
1998 unmap_mft_record(base_ni);
2002 #endif /* NTFS_RW */
2005 * ntfs_aops - general address space operations for inodes and attributes
2007 struct address_space_operations ntfs_aops = {
2008 .readpage = ntfs_readpage, /* Fill page with data. */
2009 .sync_page = block_sync_page, /* Currently, just unplugs the
2010 disk request queue. */
2012 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2013 .prepare_write = ntfs_prepare_write, /* Prepare page and buffers
2014 ready to receive data. */
2015 .commit_write = ntfs_commit_write, /* Commit received data. */
2016 #endif /* NTFS_RW */
2020 * ntfs_mst_aops - general address space operations for mst protecteed inodes
2023 struct address_space_operations ntfs_mst_aops = {
2024 .readpage = ntfs_readpage, /* Fill page with data. */
2025 .sync_page = block_sync_page, /* Currently, just unplugs the
2026 disk request queue. */
2028 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2029 .set_page_dirty = __set_page_dirty_nobuffers, /* Set the page dirty
2030 without touching the buffers
2031 belonging to the page. */
2032 #endif /* NTFS_RW */