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>
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(!PageError(page) && page_uptodate))
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 /* Hard error, zero out region. */
271 ntfs_error(vol->sb, "Failed to read from inode 0x%lx, "
272 "attribute type 0x%x, vcn 0x%llx, "
273 "offset 0x%x because its location on "
274 "disk could not be determined%s "
275 "(error code %lli).", ni->mft_no,
276 ni->type, (unsigned long long)vcn,
277 vcn_ofs, is_retry ? " even after "
278 "retrying" : "", (long long)lcn);
281 * Either iblock was outside lblock limits or
282 * ntfs_rl_vcn_to_lcn() returned error. Just zero that portion
283 * of the page and set the buffer uptodate.
286 bh->b_blocknr = -1UL;
287 clear_buffer_mapped(bh);
289 kaddr = kmap_atomic(page, KM_USER0);
290 memset(kaddr + i * blocksize, 0, blocksize);
291 flush_dcache_page(page);
292 kunmap_atomic(kaddr, KM_USER0);
293 set_buffer_uptodate(bh);
294 } while (i++, iblock++, (bh = bh->b_this_page) != head);
296 /* Release the lock if we took it. */
298 up_read(&ni->runlist.lock);
300 /* Check we have at least one buffer ready for i/o. */
302 struct buffer_head *tbh;
304 /* Lock the buffers. */
305 for (i = 0; i < nr; i++) {
308 tbh->b_end_io = ntfs_end_buffer_async_read;
309 set_buffer_async_read(tbh);
311 /* Finally, start i/o on the buffers. */
312 for (i = 0; i < nr; i++) {
314 if (likely(!buffer_uptodate(tbh)))
315 submit_bh(READ, tbh);
317 ntfs_end_buffer_async_read(tbh, 1);
321 /* No i/o was scheduled on any of the buffers. */
322 if (likely(!PageError(page)))
323 SetPageUptodate(page);
324 else /* Signal synchronous i/o error. */
331 * ntfs_readpage - fill a @page of a @file with data from the device
332 * @file: open file to which the page @page belongs or NULL
333 * @page: page cache page to fill with data
335 * For non-resident attributes, ntfs_readpage() fills the @page of the open
336 * file @file by calling the ntfs version of the generic block_read_full_page()
337 * function, ntfs_read_block(), which in turn creates and reads in the buffers
338 * associated with the page asynchronously.
340 * For resident attributes, OTOH, ntfs_readpage() fills @page by copying the
341 * data from the mft record (which at this stage is most likely in memory) and
342 * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
343 * even if the mft record is not cached at this point in time, we need to wait
344 * for it to be read in before we can do the copy.
346 * Return 0 on success and -errno on error.
348 static int ntfs_readpage(struct file *file, struct page *page)
351 ntfs_inode *ni, *base_ni;
353 ntfs_attr_search_ctx *ctx;
358 BUG_ON(!PageLocked(page));
360 * This can potentially happen because we clear PageUptodate() during
361 * ntfs_writepage() of MstProtected() attributes.
363 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);
389 * Attribute is resident, implying it is not compressed or encrypted.
390 * This also means the attribute is smaller than an mft record and
391 * hence smaller than a page, so can simply zero out any pages with
392 * index above 0. We can also do this if the file size is 0.
394 if (unlikely(page->index > 0 || !i_size_read(VFS_I(ni)))) {
395 kaddr = kmap_atomic(page, KM_USER0);
396 memset(kaddr, 0, PAGE_CACHE_SIZE);
397 flush_dcache_page(page);
398 kunmap_atomic(kaddr, KM_USER0);
404 base_ni = ni->ext.base_ntfs_ino;
405 /* Map, pin, and lock the mft record. */
406 mrec = map_mft_record(base_ni);
411 ctx = ntfs_attr_get_search_ctx(base_ni, mrec);
412 if (unlikely(!ctx)) {
416 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
417 CASE_SENSITIVE, 0, NULL, 0, ctx);
419 goto put_unm_err_out;
420 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
421 i_size = i_size_read(VFS_I(ni));
422 if (unlikely(attr_len > i_size))
424 kaddr = kmap_atomic(page, KM_USER0);
425 /* Copy the data to the page. */
426 memcpy(kaddr, (u8*)ctx->attr +
427 le16_to_cpu(ctx->attr->data.resident.value_offset),
429 /* Zero the remainder of the page. */
430 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
431 flush_dcache_page(page);
432 kunmap_atomic(kaddr, KM_USER0);
434 ntfs_attr_put_search_ctx(ctx);
436 unmap_mft_record(base_ni);
438 SetPageUptodate(page);
447 * ntfs_write_block - write a @page to the backing store
448 * @page: page cache page to write out
449 * @wbc: writeback control structure
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 page *page, struct writeback_control *wbc)
472 s64 initialized_size;
474 sector_t block, dblock, iblock;
479 struct buffer_head *bh, *head;
481 unsigned int blocksize, vcn_ofs;
483 BOOL need_end_writeback;
484 unsigned char blocksize_bits;
486 vi = page->mapping->host;
490 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
491 "0x%lx.", ni->mft_no, ni->type, page->index);
493 BUG_ON(!NInoNonResident(ni));
494 BUG_ON(NInoMstProtected(ni));
496 blocksize_bits = vi->i_blkbits;
497 blocksize = 1 << blocksize_bits;
499 if (!page_has_buffers(page)) {
500 BUG_ON(!PageUptodate(page));
501 create_empty_buffers(page, blocksize,
502 (1 << BH_Uptodate) | (1 << BH_Dirty));
504 bh = head = page_buffers(page);
506 ntfs_warning(vol->sb, "Error allocating page buffers. "
507 "Redirtying page so we try again later.");
509 * Put the page back on mapping->dirty_pages, but leave its
510 * buffer's dirty state as-is.
512 redirty_page_for_writepage(wbc, page);
517 /* NOTE: Different naming scheme to ntfs_read_block()! */
519 /* The first block in the page. */
520 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
522 read_lock_irqsave(&ni->size_lock, flags);
523 i_size = i_size_read(vi);
524 initialized_size = ni->initialized_size;
525 read_unlock_irqrestore(&ni->size_lock, flags);
527 /* The first out of bounds block for the data size. */
528 dblock = (i_size + blocksize - 1) >> blocksize_bits;
530 /* The last (fully or partially) initialized block. */
531 iblock = initialized_size >> blocksize_bits;
534 * Be very careful. We have no exclusion from __set_page_dirty_buffers
535 * here, and the (potentially unmapped) buffers may become dirty at
536 * any time. If a buffer becomes dirty here after we've inspected it
537 * then we just miss that fact, and the page stays dirty.
539 * Buffers outside i_size may be dirtied by __set_page_dirty_buffers;
540 * handle that here by just cleaning them.
544 * Loop through all the buffers in the page, mapping all the dirty
545 * buffers to disk addresses and handling any aliases from the
546 * underlying block device's mapping.
551 BOOL is_retry = FALSE;
553 if (unlikely(block >= dblock)) {
555 * Mapped buffers outside i_size will occur, because
556 * this page can be outside i_size when there is a
557 * truncate in progress. The contents of such buffers
558 * were zeroed by ntfs_writepage().
560 * FIXME: What about the small race window where
561 * ntfs_writepage() has not done any clearing because
562 * the page was within i_size but before we get here,
563 * vmtruncate() modifies i_size?
565 clear_buffer_dirty(bh);
566 set_buffer_uptodate(bh);
570 /* Clean buffers are not written out, so no need to map them. */
571 if (!buffer_dirty(bh))
574 /* Make sure we have enough initialized size. */
575 if (unlikely((block >= iblock) &&
576 (initialized_size < i_size))) {
578 * If this page is fully outside initialized size, zero
579 * out all pages between the current initialized size
580 * and the current page. Just use ntfs_readpage() to do
581 * the zeroing transparently.
583 if (block > iblock) {
586 // - read_cache_page()
587 // Again for each page do:
588 // - wait_on_page_locked()
589 // - Check (PageUptodate(page) &&
591 // Update initialized size in the attribute and
593 // Again, for each page do:
594 // __set_page_dirty_buffers();
595 // page_cache_release()
596 // We don't need to wait on the writes.
600 * The current page straddles initialized size. Zero
601 * all non-uptodate buffers and set them uptodate (and
602 * dirty?). Note, there aren't any non-uptodate buffers
603 * if the page is uptodate.
604 * FIXME: For an uptodate page, the buffers may need to
605 * be written out because they were not initialized on
608 if (!PageUptodate(page)) {
610 // Zero any non-uptodate buffers up to i_size.
611 // Set them uptodate and dirty.
614 // Update initialized size in the attribute and in the
615 // inode (up to i_size).
617 // FIXME: This is inefficient. Try to batch the two
618 // size changes to happen in one go.
619 ntfs_error(vol->sb, "Writing beyond initialized size "
620 "is not supported yet. Sorry.");
623 // Do NOT set_buffer_new() BUT DO clear buffer range
624 // outside write request range.
625 // set_buffer_uptodate() on complete buffers as well as
626 // set_buffer_dirty().
629 /* No need to map buffers that are already mapped. */
630 if (buffer_mapped(bh))
633 /* Unmapped, dirty buffer. Need to map it. */
634 bh->b_bdev = vol->sb->s_bdev;
636 /* Convert block into corresponding vcn and offset. */
637 vcn = (VCN)block << blocksize_bits;
638 vcn_ofs = vcn & vol->cluster_size_mask;
639 vcn >>= vol->cluster_size_bits;
642 down_read(&ni->runlist.lock);
645 if (likely(rl != NULL)) {
646 /* Seek to element containing target vcn. */
647 while (rl->length && rl[1].vcn <= vcn)
649 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
651 lcn = LCN_RL_NOT_MAPPED;
652 /* Successful remap. */
654 /* Setup buffer head to point to correct block. */
655 bh->b_blocknr = ((lcn << vol->cluster_size_bits) +
656 vcn_ofs) >> blocksize_bits;
657 set_buffer_mapped(bh);
660 /* It is a hole, need to instantiate it. */
661 if (lcn == LCN_HOLE) {
662 // TODO: Instantiate the hole.
663 // clear_buffer_new(bh);
664 // unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr);
665 ntfs_error(vol->sb, "Writing into sparse regions is "
666 "not supported yet. Sorry.");
670 /* If first try and runlist unmapped, map and retry. */
671 if (!is_retry && lcn == LCN_RL_NOT_MAPPED) {
674 * Attempt to map runlist, dropping lock for
677 up_read(&ni->runlist.lock);
678 err = ntfs_map_runlist(ni, vcn);
680 goto lock_retry_remap;
684 /* Failed to map the buffer, even after retrying. */
686 ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
687 "attribute type 0x%x, vcn 0x%llx, offset 0x%x "
688 "because its location on disk could not be "
689 "determined%s (error code %lli).", ni->mft_no,
690 ni->type, (unsigned long long)vcn,
691 vcn_ofs, is_retry ? " even after "
692 "retrying" : "", (long long)lcn);
696 } while (block++, (bh = bh->b_this_page) != head);
698 /* Release the lock if we took it. */
700 up_read(&ni->runlist.lock);
702 /* For the error case, need to reset bh to the beginning. */
705 /* Just an optimization, so ->readpage() isn't called later. */
706 if (unlikely(!PageUptodate(page))) {
709 if (!buffer_uptodate(bh)) {
714 } while ((bh = bh->b_this_page) != head);
716 SetPageUptodate(page);
719 /* Setup all mapped, dirty buffers for async write i/o. */
722 if (buffer_mapped(bh) && buffer_dirty(bh)) {
724 if (test_clear_buffer_dirty(bh)) {
725 BUG_ON(!buffer_uptodate(bh));
726 mark_buffer_async_write(bh);
729 } else if (unlikely(err)) {
731 * For the error case. The buffer may have been set
732 * dirty during attachment to a dirty page.
735 clear_buffer_dirty(bh);
737 } while ((bh = bh->b_this_page) != head);
740 // TODO: Remove the -EOPNOTSUPP check later on...
741 if (unlikely(err == -EOPNOTSUPP))
743 else if (err == -ENOMEM) {
744 ntfs_warning(vol->sb, "Error allocating memory. "
745 "Redirtying page so we try again "
748 * Put the page back on mapping->dirty_pages, but
749 * leave its buffer's dirty state as-is.
751 redirty_page_for_writepage(wbc, page);
757 BUG_ON(PageWriteback(page));
758 set_page_writeback(page); /* Keeps try_to_free_buffers() away. */
762 * Submit the prepared buffers for i/o. Note the page is unlocked,
763 * and the async write i/o completion handler can end_page_writeback()
764 * at any time after the *first* submit_bh(). So the buffers can then
767 need_end_writeback = TRUE;
769 struct buffer_head *next = bh->b_this_page;
770 if (buffer_async_write(bh)) {
771 submit_bh(WRITE, bh);
772 need_end_writeback = FALSE;
776 } while (bh != head);
778 /* If no i/o was started, need to end_page_writeback(). */
779 if (unlikely(need_end_writeback))
780 end_page_writeback(page);
787 * ntfs_write_mst_block - write a @page to the backing store
788 * @page: page cache page to write out
789 * @wbc: writeback control structure
791 * This function is for writing pages belonging to non-resident, mst protected
792 * attributes to their backing store. The only supported attributes are index
793 * allocation and $MFT/$DATA. Both directory inodes and index inodes are
794 * supported for the index allocation case.
796 * The page must remain locked for the duration of the write because we apply
797 * the mst fixups, write, and then undo the fixups, so if we were to unlock the
798 * page before undoing the fixups, any other user of the page will see the
799 * page contents as corrupt.
801 * We clear the page uptodate flag for the duration of the function to ensure
802 * exclusion for the $MFT/$DATA case against someone mapping an mft record we
803 * are about to apply the mst fixups to.
805 * Return 0 on success and -errno on error.
807 * Based on ntfs_write_block(), ntfs_mft_writepage(), and
808 * write_mft_record_nolock().
810 static int ntfs_write_mst_block(struct page *page,
811 struct writeback_control *wbc)
813 sector_t block, dblock, rec_block;
814 struct inode *vi = page->mapping->host;
815 ntfs_inode *ni = NTFS_I(vi);
816 ntfs_volume *vol = ni->vol;
818 unsigned char bh_size_bits = vi->i_blkbits;
819 unsigned int bh_size = 1 << bh_size_bits;
820 unsigned int rec_size = ni->itype.index.block_size;
821 ntfs_inode *locked_nis[PAGE_CACHE_SIZE / rec_size];
822 struct buffer_head *bh, *head, *tbh, *rec_start_bh;
823 int max_bhs = PAGE_CACHE_SIZE / bh_size;
824 struct buffer_head *bhs[max_bhs];
826 int i, nr_locked_nis, nr_recs, nr_bhs, bhs_per_rec, err, err2;
827 unsigned rec_size_bits;
828 BOOL sync, is_mft, page_is_dirty, rec_is_dirty;
830 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
831 "0x%lx.", vi->i_ino, ni->type, page->index);
832 BUG_ON(!NInoNonResident(ni));
833 BUG_ON(!NInoMstProtected(ni));
834 is_mft = (S_ISREG(vi->i_mode) && !vi->i_ino);
836 * NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page
837 * in its page cache were to be marked dirty. However this should
838 * never happen with the current driver and considering we do not
839 * handle this case here we do want to BUG(), at least for now.
841 BUG_ON(!(is_mft || S_ISDIR(vi->i_mode) ||
842 (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
845 /* Were we called for sync purposes? */
846 sync = (wbc->sync_mode == WB_SYNC_ALL);
848 /* Make sure we have mapped buffers. */
849 BUG_ON(!page_has_buffers(page));
850 bh = head = page_buffers(page);
853 rec_size_bits = ni->itype.index.block_size_bits;
854 BUG_ON(!(PAGE_CACHE_SIZE >> rec_size_bits));
855 bhs_per_rec = rec_size >> bh_size_bits;
856 BUG_ON(!bhs_per_rec);
858 /* The first block in the page. */
859 rec_block = block = (sector_t)page->index <<
860 (PAGE_CACHE_SHIFT - bh_size_bits);
862 /* The first out of bounds block for the data size. */
863 dblock = (i_size_read(vi) + bh_size - 1) >> bh_size_bits;
866 err = err2 = nr_bhs = nr_recs = nr_locked_nis = 0;
867 page_is_dirty = rec_is_dirty = FALSE;
870 BOOL is_retry = FALSE;
872 if (likely(block < rec_block)) {
873 if (unlikely(block >= dblock)) {
874 clear_buffer_dirty(bh);
878 * This block is not the first one in the record. We
879 * ignore the buffer's dirty state because we could
880 * have raced with a parallel mark_ntfs_record_dirty().
884 if (unlikely(err2)) {
886 clear_buffer_dirty(bh);
889 } else /* if (block == rec_block) */ {
890 BUG_ON(block > rec_block);
891 /* This block is the first one in the record. */
892 rec_block += bhs_per_rec;
894 if (unlikely(block >= dblock)) {
895 clear_buffer_dirty(bh);
898 if (!buffer_dirty(bh)) {
899 /* Clean records are not written out. */
900 rec_is_dirty = FALSE;
906 /* Need to map the buffer if it is not mapped already. */
907 if (unlikely(!buffer_mapped(bh))) {
910 unsigned int vcn_ofs;
912 /* Obtain the vcn and offset of the current block. */
913 vcn = (VCN)block << bh_size_bits;
914 vcn_ofs = vcn & vol->cluster_size_mask;
915 vcn >>= vol->cluster_size_bits;
918 down_read(&ni->runlist.lock);
921 if (likely(rl != NULL)) {
922 /* Seek to element containing target vcn. */
923 while (rl->length && rl[1].vcn <= vcn)
925 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
927 lcn = LCN_RL_NOT_MAPPED;
928 /* Successful remap. */
929 if (likely(lcn >= 0)) {
930 /* Setup buffer head to correct block. */
931 bh->b_blocknr = ((lcn <<
932 vol->cluster_size_bits) +
933 vcn_ofs) >> bh_size_bits;
934 set_buffer_mapped(bh);
937 * Remap failed. Retry to map the runlist once
938 * unless we are working on $MFT which always
939 * has the whole of its runlist in memory.
941 if (!is_mft && !is_retry &&
942 lcn == LCN_RL_NOT_MAPPED) {
945 * Attempt to map runlist, dropping
946 * lock for the duration.
948 up_read(&ni->runlist.lock);
949 err2 = ntfs_map_runlist(ni, vcn);
951 goto lock_retry_remap;
953 page_is_dirty = TRUE;
957 /* Hard error. Abort writing this record. */
958 if (!err || err == -ENOMEM)
961 ntfs_error(vol->sb, "Cannot write ntfs record "
962 "0x%llx (inode 0x%lx, "
963 "attribute type 0x%x) because "
964 "its location on disk could "
965 "not be determined (error "
966 "code %lli).", (s64)block <<
968 vol->mft_record_size_bits,
969 ni->mft_no, ni->type,
972 * If this is not the first buffer, remove the
973 * buffers in this record from the list of
974 * buffers to write and clear their dirty bit
975 * if not error -ENOMEM.
977 if (rec_start_bh != bh) {
978 while (bhs[--nr_bhs] != rec_start_bh)
980 if (err2 != -ENOMEM) {
984 } while ((rec_start_bh =
993 BUG_ON(!buffer_uptodate(bh));
994 BUG_ON(nr_bhs >= max_bhs);
996 } while (block++, (bh = bh->b_this_page) != head);
998 up_read(&ni->runlist.lock);
999 /* If there were no dirty buffers, we are done. */
1002 /* Map the page so we can access its contents. */
1004 /* Clear the page uptodate flag whilst the mst fixups are applied. */
1005 BUG_ON(!PageUptodate(page));
1006 ClearPageUptodate(page);
1007 for (i = 0; i < nr_bhs; i++) {
1010 /* Skip buffers which are not at the beginning of records. */
1011 if (i % bhs_per_rec)
1014 ofs = bh_offset(tbh);
1017 unsigned long mft_no;
1019 /* Get the mft record number. */
1020 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1022 /* Check whether to write this mft record. */
1024 if (!ntfs_may_write_mft_record(vol, mft_no,
1025 (MFT_RECORD*)(kaddr + ofs), &tni)) {
1027 * The record should not be written. This
1028 * means we need to redirty the page before
1031 page_is_dirty = TRUE;
1033 * Remove the buffers in this mft record from
1034 * the list of buffers to write.
1038 } while (++i % bhs_per_rec);
1042 * The record should be written. If a locked ntfs
1043 * inode was returned, add it to the array of locked
1047 locked_nis[nr_locked_nis++] = tni;
1049 /* Apply the mst protection fixups. */
1050 err2 = pre_write_mst_fixup((NTFS_RECORD*)(kaddr + ofs),
1052 if (unlikely(err2)) {
1053 if (!err || err == -ENOMEM)
1055 ntfs_error(vol->sb, "Failed to apply mst fixups "
1056 "(inode 0x%lx, attribute type 0x%x, "
1057 "page index 0x%lx, page offset 0x%x)!"
1058 " Unmount and run chkdsk.", vi->i_ino,
1059 ni->type, page->index, ofs);
1061 * Mark all the buffers in this record clean as we do
1062 * not want to write corrupt data to disk.
1065 clear_buffer_dirty(bhs[i]);
1067 } while (++i % bhs_per_rec);
1072 /* If no records are to be written out, we are done. */
1075 flush_dcache_page(page);
1076 /* Lock buffers and start synchronous write i/o on them. */
1077 for (i = 0; i < nr_bhs; i++) {
1081 if (unlikely(test_set_buffer_locked(tbh)))
1083 /* The buffer dirty state is now irrelevant, just clean it. */
1084 clear_buffer_dirty(tbh);
1085 BUG_ON(!buffer_uptodate(tbh));
1086 BUG_ON(!buffer_mapped(tbh));
1088 tbh->b_end_io = end_buffer_write_sync;
1089 submit_bh(WRITE, tbh);
1091 /* Synchronize the mft mirror now if not @sync. */
1092 if (is_mft && !sync)
1095 /* Wait on i/o completion of buffers. */
1096 for (i = 0; i < nr_bhs; i++) {
1100 wait_on_buffer(tbh);
1101 if (unlikely(!buffer_uptodate(tbh))) {
1102 ntfs_error(vol->sb, "I/O error while writing ntfs "
1103 "record buffer (inode 0x%lx, "
1104 "attribute type 0x%x, page index "
1105 "0x%lx, page offset 0x%lx)! Unmount "
1106 "and run chkdsk.", vi->i_ino, ni->type,
1107 page->index, bh_offset(tbh));
1108 if (!err || err == -ENOMEM)
1111 * Set the buffer uptodate so the page and buffer
1112 * states do not become out of sync.
1114 set_buffer_uptodate(tbh);
1117 /* If @sync, now synchronize the mft mirror. */
1118 if (is_mft && sync) {
1120 for (i = 0; i < nr_bhs; i++) {
1121 unsigned long mft_no;
1125 * Skip buffers which are not at the beginning of
1128 if (i % bhs_per_rec)
1131 /* Skip removed buffers (and hence records). */
1134 ofs = bh_offset(tbh);
1135 /* Get the mft record number. */
1136 mft_no = (((s64)page->index << PAGE_CACHE_SHIFT) + ofs)
1138 if (mft_no < vol->mftmirr_size)
1139 ntfs_sync_mft_mirror(vol, mft_no,
1140 (MFT_RECORD*)(kaddr + ofs),
1146 /* Remove the mst protection fixups again. */
1147 for (i = 0; i < nr_bhs; i++) {
1148 if (!(i % bhs_per_rec)) {
1152 post_write_mst_fixup((NTFS_RECORD*)(kaddr +
1156 flush_dcache_page(page);
1158 /* Unlock any locked inodes. */
1159 while (nr_locked_nis-- > 0) {
1160 ntfs_inode *tni, *base_tni;
1162 tni = locked_nis[nr_locked_nis];
1163 /* Get the base inode. */
1164 down(&tni->extent_lock);
1165 if (tni->nr_extents >= 0)
1168 base_tni = tni->ext.base_ntfs_ino;
1171 up(&tni->extent_lock);
1172 ntfs_debug("Unlocking %s inode 0x%lx.",
1173 tni == base_tni ? "base" : "extent",
1175 up(&tni->mrec_lock);
1176 atomic_dec(&tni->count);
1177 iput(VFS_I(base_tni));
1179 SetPageUptodate(page);
1182 if (unlikely(err && err != -ENOMEM)) {
1184 * Set page error if there is only one ntfs record in the page.
1185 * Otherwise we would loose per-record granularity.
1187 if (ni->itype.index.block_size == PAGE_CACHE_SIZE)
1191 if (page_is_dirty) {
1192 ntfs_debug("Page still contains one or more dirty ntfs "
1193 "records. Redirtying the page starting at "
1194 "record 0x%lx.", page->index <<
1195 (PAGE_CACHE_SHIFT - rec_size_bits));
1196 redirty_page_for_writepage(wbc, page);
1200 * Keep the VM happy. This must be done otherwise the
1201 * radix-tree tag PAGECACHE_TAG_DIRTY remains set even though
1202 * the page is clean.
1204 BUG_ON(PageWriteback(page));
1205 set_page_writeback(page);
1207 end_page_writeback(page);
1210 ntfs_debug("Done.");
1215 * ntfs_writepage - write a @page to the backing store
1216 * @page: page cache page to write out
1217 * @wbc: writeback control structure
1219 * This is called from the VM when it wants to have a dirty ntfs page cache
1220 * page cleaned. The VM has already locked the page and marked it clean.
1222 * For non-resident attributes, ntfs_writepage() writes the @page by calling
1223 * the ntfs version of the generic block_write_full_page() function,
1224 * ntfs_write_block(), which in turn if necessary creates and writes the
1225 * buffers associated with the page asynchronously.
1227 * For resident attributes, OTOH, ntfs_writepage() writes the @page by copying
1228 * the data to the mft record (which at this stage is most likely in memory).
1229 * The mft record is then marked dirty and written out asynchronously via the
1230 * vfs inode dirty code path for the inode the mft record belongs to or via the
1231 * vm page dirty code path for the page the mft record is in.
1233 * Based on ntfs_readpage() and fs/buffer.c::block_write_full_page().
1235 * Return 0 on success and -errno on error.
1237 static int ntfs_writepage(struct page *page, struct writeback_control *wbc)
1240 struct inode *vi = page->mapping->host;
1241 ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1243 ntfs_attr_search_ctx *ctx = NULL;
1244 MFT_RECORD *m = NULL;
1248 BUG_ON(!PageLocked(page));
1250 * If a previous ntfs_truncate() failed, repeat it and abort if it
1253 if (unlikely(NInoTruncateFailed(ni))) {
1254 down_write(&vi->i_alloc_sem);
1255 err = ntfs_truncate(vi);
1256 up_write(&vi->i_alloc_sem);
1257 if (err || NInoTruncateFailed(ni)) {
1263 i_size = i_size_read(vi);
1264 /* Is the page fully outside i_size? (truncate in progress) */
1265 if (unlikely(page->index >= (i_size + PAGE_CACHE_SIZE - 1) >>
1266 PAGE_CACHE_SHIFT)) {
1268 * The page may have dirty, unmapped buffers. Make them
1269 * freeable here, so the page does not leak.
1271 block_invalidatepage(page, 0);
1273 ntfs_debug("Write outside i_size - truncated?");
1276 /* NInoNonResident() == NInoIndexAllocPresent() */
1277 if (NInoNonResident(ni)) {
1279 * Only unnamed $DATA attributes can be compressed, encrypted,
1282 if (ni->type == AT_DATA && !ni->name_len) {
1283 /* If file is encrypted, deny access, just like NT4. */
1284 if (NInoEncrypted(ni)) {
1286 ntfs_debug("Denying write access to encrypted "
1290 /* Compressed data streams are handled in compress.c. */
1291 if (NInoCompressed(ni)) {
1292 // TODO: Implement and replace this check with
1293 // return ntfs_write_compressed_block(page);
1295 ntfs_error(vi->i_sb, "Writing to compressed "
1296 "files is not supported yet. "
1300 // TODO: Implement and remove this check.
1301 if (NInoSparse(ni)) {
1303 ntfs_error(vi->i_sb, "Writing to sparse files "
1304 "is not supported yet. Sorry.");
1308 /* We have to zero every time due to mmap-at-end-of-file. */
1309 if (page->index >= (i_size >> PAGE_CACHE_SHIFT)) {
1310 /* The page straddles i_size. */
1311 unsigned int ofs = i_size & ~PAGE_CACHE_MASK;
1312 kaddr = kmap_atomic(page, KM_USER0);
1313 memset(kaddr + ofs, 0, PAGE_CACHE_SIZE - ofs);
1314 flush_dcache_page(page);
1315 kunmap_atomic(kaddr, KM_USER0);
1317 /* Handle mst protected attributes. */
1318 if (NInoMstProtected(ni))
1319 return ntfs_write_mst_block(page, wbc);
1320 /* Normal data stream. */
1321 return ntfs_write_block(page, wbc);
1324 * Attribute is resident, implying it is not compressed, encrypted,
1325 * sparse, or mst protected. This also means the attribute is smaller
1326 * than an mft record and hence smaller than a page, so can simply
1327 * return error on any pages with index above 0.
1329 BUG_ON(page_has_buffers(page));
1330 BUG_ON(!PageUptodate(page));
1331 if (unlikely(page->index > 0)) {
1332 ntfs_error(vi->i_sb, "BUG()! page->index (0x%lx) > 0. "
1333 "Aborting write.", page->index);
1334 BUG_ON(PageWriteback(page));
1335 set_page_writeback(page);
1337 end_page_writeback(page);
1343 base_ni = ni->ext.base_ntfs_ino;
1344 /* Map, pin, and lock the mft record. */
1345 m = map_mft_record(base_ni);
1352 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1353 if (unlikely(!ctx)) {
1357 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1358 CASE_SENSITIVE, 0, NULL, 0, ctx);
1362 * Keep the VM happy. This must be done otherwise the radix-tree tag
1363 * PAGECACHE_TAG_DIRTY remains set even though the page is clean.
1365 BUG_ON(PageWriteback(page));
1366 set_page_writeback(page);
1370 * Here, we don't need to zero the out of bounds area everytime because
1371 * the below memcpy() already takes care of the mmap-at-end-of-file
1372 * requirements. If the file is converted to a non-resident one, then
1373 * the code path use is switched to the non-resident one where the
1374 * zeroing happens on each ntfs_writepage() invocation.
1376 * The above also applies nicely when i_size is decreased.
1378 * When i_size is increased, the memory between the old and new i_size
1379 * _must_ be zeroed (or overwritten with new data). Otherwise we will
1380 * expose data to userspace/disk which should never have been exposed.
1382 * FIXME: Ensure that i_size increases do the zeroing/overwriting and
1383 * if we cannot guarantee that, then enable the zeroing below. If the
1384 * zeroing below is enabled, we MUST move the unlock_page() from above
1385 * to after the kunmap_atomic(), i.e. just before the
1386 * end_page_writeback().
1387 * UPDATE: ntfs_prepare/commit_write() do the zeroing on i_size
1388 * increases for resident attributes so those are ok.
1389 * TODO: ntfs_truncate(), others?
1392 attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
1393 i_size = i_size_read(vi);
1394 kaddr = kmap_atomic(page, KM_USER0);
1395 if (unlikely(attr_len > i_size)) {
1396 /* Zero out of bounds area in the mft record. */
1397 memset((u8*)ctx->attr + le16_to_cpu(
1398 ctx->attr->data.resident.value_offset) +
1399 i_size, 0, attr_len - i_size);
1402 /* Copy the data from the page to the mft record. */
1403 memcpy((u8*)ctx->attr +
1404 le16_to_cpu(ctx->attr->data.resident.value_offset),
1406 flush_dcache_mft_record_page(ctx->ntfs_ino);
1407 /* Zero out of bounds area in the page cache page. */
1408 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
1409 flush_dcache_page(page);
1410 kunmap_atomic(kaddr, KM_USER0);
1412 end_page_writeback(page);
1414 /* Mark the mft record dirty, so it gets written back. */
1415 mark_mft_record_dirty(ctx->ntfs_ino);
1416 ntfs_attr_put_search_ctx(ctx);
1417 unmap_mft_record(base_ni);
1420 if (err == -ENOMEM) {
1421 ntfs_warning(vi->i_sb, "Error allocating memory. Redirtying "
1422 "page so we try again later.");
1424 * Put the page back on mapping->dirty_pages, but leave its
1425 * buffers' dirty state as-is.
1427 redirty_page_for_writepage(wbc, page);
1430 ntfs_error(vi->i_sb, "Resident attribute write failed with "
1433 NVolSetErrors(ni->vol);
1438 ntfs_attr_put_search_ctx(ctx);
1440 unmap_mft_record(base_ni);
1445 * ntfs_prepare_nonresident_write -
1448 static int ntfs_prepare_nonresident_write(struct page *page,
1449 unsigned from, unsigned to)
1453 s64 initialized_size;
1455 sector_t block, ablock, iblock;
1459 runlist_element *rl;
1460 struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
1461 unsigned long flags;
1462 unsigned int vcn_ofs, block_start, block_end, blocksize;
1465 unsigned char blocksize_bits;
1467 vi = page->mapping->host;
1471 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1472 "0x%lx, from = %u, to = %u.", ni->mft_no, ni->type,
1473 page->index, from, to);
1475 BUG_ON(!NInoNonResident(ni));
1477 blocksize_bits = vi->i_blkbits;
1478 blocksize = 1 << blocksize_bits;
1481 * create_empty_buffers() will create uptodate/dirty buffers if the
1482 * page is uptodate/dirty.
1484 if (!page_has_buffers(page))
1485 create_empty_buffers(page, blocksize, 0);
1486 bh = head = page_buffers(page);
1490 /* The first block in the page. */
1491 block = (s64)page->index << (PAGE_CACHE_SHIFT - blocksize_bits);
1493 read_lock_irqsave(&ni->size_lock, flags);
1495 * The first out of bounds block for the allocated size. No need to
1496 * round up as allocated_size is in multiples of cluster size and the
1497 * minimum cluster size is 512 bytes, which is equal to the smallest
1500 ablock = ni->allocated_size >> blocksize_bits;
1502 i_size = i_size_read(vi);
1503 initialized_size = ni->initialized_size;
1504 read_unlock_irqrestore(&ni->size_lock, flags);
1506 /* The last (fully or partially) initialized block. */
1507 iblock = initialized_size >> blocksize_bits;
1509 /* Loop through all the buffers in the page. */
1514 block_end = block_start + blocksize;
1516 * If buffer @bh is outside the write, just mark it uptodate
1517 * if the page is uptodate and continue with the next buffer.
1519 if (block_end <= from || block_start >= to) {
1520 if (PageUptodate(page)) {
1521 if (!buffer_uptodate(bh))
1522 set_buffer_uptodate(bh);
1527 * @bh is at least partially being written to.
1528 * Make sure it is not marked as new.
1530 //if (buffer_new(bh))
1531 // clear_buffer_new(bh);
1533 if (block >= ablock) {
1534 // TODO: block is above allocated_size, need to
1535 // allocate it. Best done in one go to accommodate not
1536 // only block but all above blocks up to and including:
1537 // ((page->index << PAGE_CACHE_SHIFT) + to + blocksize
1538 // - 1) >> blobksize_bits. Obviously will need to round
1539 // up to next cluster boundary, too. This should be
1540 // done with a helper function, so it can be reused.
1541 ntfs_error(vol->sb, "Writing beyond allocated size "
1542 "is not supported yet. Sorry.");
1545 // Need to update ablock.
1546 // Need to set_buffer_new() on all block bhs that are
1550 * Now we have enough allocated size to fulfill the whole
1551 * request, i.e. block < ablock is true.
1553 if (unlikely((block >= iblock) &&
1554 (initialized_size < i_size))) {
1556 * If this page is fully outside initialized size, zero
1557 * out all pages between the current initialized size
1558 * and the current page. Just use ntfs_readpage() to do
1559 * the zeroing transparently.
1561 if (block > iblock) {
1563 // For each page do:
1564 // - read_cache_page()
1565 // Again for each page do:
1566 // - wait_on_page_locked()
1567 // - Check (PageUptodate(page) &&
1568 // !PageError(page))
1569 // Update initialized size in the attribute and
1571 // Again, for each page do:
1572 // __set_page_dirty_buffers();
1573 // page_cache_release()
1574 // We don't need to wait on the writes.
1578 * The current page straddles initialized size. Zero
1579 * all non-uptodate buffers and set them uptodate (and
1580 * dirty?). Note, there aren't any non-uptodate buffers
1581 * if the page is uptodate.
1582 * FIXME: For an uptodate page, the buffers may need to
1583 * be written out because they were not initialized on
1586 if (!PageUptodate(page)) {
1588 // Zero any non-uptodate buffers up to i_size.
1589 // Set them uptodate and dirty.
1592 // Update initialized size in the attribute and in the
1593 // inode (up to i_size).
1595 // FIXME: This is inefficient. Try to batch the two
1596 // size changes to happen in one go.
1597 ntfs_error(vol->sb, "Writing beyond initialized size "
1598 "is not supported yet. Sorry.");
1601 // Do NOT set_buffer_new() BUT DO clear buffer range
1602 // outside write request range.
1603 // set_buffer_uptodate() on complete buffers as well as
1604 // set_buffer_dirty().
1607 /* Need to map unmapped buffers. */
1608 if (!buffer_mapped(bh)) {
1609 /* Unmapped buffer. Need to map it. */
1610 bh->b_bdev = vol->sb->s_bdev;
1612 /* Convert block into corresponding vcn and offset. */
1613 vcn = (VCN)block << blocksize_bits >>
1614 vol->cluster_size_bits;
1615 vcn_ofs = ((VCN)block << blocksize_bits) &
1616 vol->cluster_size_mask;
1621 down_read(&ni->runlist.lock);
1622 rl = ni->runlist.rl;
1624 if (likely(rl != NULL)) {
1625 /* Seek to element containing target vcn. */
1626 while (rl->length && rl[1].vcn <= vcn)
1628 lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
1630 lcn = LCN_RL_NOT_MAPPED;
1631 if (unlikely(lcn < 0)) {
1633 * We extended the attribute allocation above.
1634 * If we hit an ENOENT here it means that the
1635 * allocation was insufficient which is a bug.
1637 BUG_ON(lcn == LCN_ENOENT);
1639 /* It is a hole, need to instantiate it. */
1640 if (lcn == LCN_HOLE) {
1641 // TODO: Instantiate the hole.
1642 // clear_buffer_new(bh);
1643 // unmap_underlying_metadata(bh->b_bdev,
1645 // For non-uptodate buffers, need to
1646 // zero out the region outside the
1647 // request in this bh or all bhs,
1648 // depending on what we implemented
1650 // Need to flush_dcache_page().
1651 // Or could use set_buffer_new()
1653 ntfs_error(vol->sb, "Writing into "
1654 "sparse regions is "
1655 "not supported yet. "
1659 } else if (!is_retry &&
1660 lcn == LCN_RL_NOT_MAPPED) {
1663 * Attempt to map runlist, dropping
1664 * lock for the duration.
1666 up_read(&ni->runlist.lock);
1667 err = ntfs_map_runlist(ni, vcn);
1669 goto lock_retry_remap;
1674 * Failed to map the buffer, even after
1678 ntfs_error(vol->sb, "Failed to write to inode "
1679 "0x%lx, attribute type 0x%x, "
1680 "vcn 0x%llx, offset 0x%x "
1681 "because its location on disk "
1682 "could not be determined%s "
1683 "(error code %lli).",
1684 ni->mft_no, ni->type,
1685 (unsigned long long)vcn,
1686 vcn_ofs, is_retry ? " even "
1687 "after retrying" : "",
1693 /* We now have a successful remap, i.e. lcn >= 0. */
1695 /* Setup buffer head to correct block. */
1696 bh->b_blocknr = ((lcn << vol->cluster_size_bits)
1697 + vcn_ofs) >> blocksize_bits;
1698 set_buffer_mapped(bh);
1700 // FIXME: Something analogous to this is needed for
1701 // each newly allocated block, i.e. BH_New.
1702 // FIXME: Might need to take this out of the
1703 // if (!buffer_mapped(bh)) {}, depending on how we
1704 // implement things during the allocated_size and
1705 // initialized_size extension code above.
1706 if (buffer_new(bh)) {
1707 clear_buffer_new(bh);
1708 unmap_underlying_metadata(bh->b_bdev,
1710 if (PageUptodate(page)) {
1711 set_buffer_uptodate(bh);
1715 * Page is _not_ uptodate, zero surrounding
1716 * region. NOTE: This is how we decide if to
1719 if (block_end > to || block_start < from) {
1722 kaddr = kmap_atomic(page, KM_USER0);
1724 memset(kaddr + to, 0,
1726 if (block_start < from)
1727 memset(kaddr + block_start, 0,
1730 flush_dcache_page(page);
1731 kunmap_atomic(kaddr, KM_USER0);
1736 /* @bh is mapped, set it uptodate if the page is uptodate. */
1737 if (PageUptodate(page)) {
1738 if (!buffer_uptodate(bh))
1739 set_buffer_uptodate(bh);
1743 * The page is not uptodate. The buffer is mapped. If it is not
1744 * uptodate, and it is only partially being written to, we need
1745 * to read the buffer in before the write, i.e. right now.
1747 if (!buffer_uptodate(bh) &&
1748 (block_start < from || block_end > to)) {
1749 ll_rw_block(READ, 1, &bh);
1752 } while (block++, block_start = block_end,
1753 (bh = bh->b_this_page) != head);
1755 /* Release the lock if we took it. */
1757 up_read(&ni->runlist.lock);
1761 /* If we issued read requests, let them complete. */
1762 while (wait_bh > wait) {
1763 wait_on_buffer(*--wait_bh);
1764 if (!buffer_uptodate(*wait_bh))
1768 ntfs_debug("Done.");
1772 * Zero out any newly allocated blocks to avoid exposing stale data.
1773 * If BH_New is set, we know that the block was newly allocated in the
1775 * FIXME: What about initialized_size increments? Have we done all the
1776 * required zeroing above? If not this error handling is broken, and
1777 * in particular the if (block_end <= from) check is completely bogus.
1783 block_end = block_start + blocksize;
1784 if (block_end <= from)
1786 if (block_start >= to)
1788 if (buffer_new(bh)) {
1791 clear_buffer_new(bh);
1792 kaddr = kmap_atomic(page, KM_USER0);
1793 memset(kaddr + block_start, 0, bh->b_size);
1794 kunmap_atomic(kaddr, KM_USER0);
1795 set_buffer_uptodate(bh);
1796 mark_buffer_dirty(bh);
1799 } while (block_start = block_end, (bh = bh->b_this_page) != head);
1801 flush_dcache_page(page);
1803 up_read(&ni->runlist.lock);
1808 * ntfs_prepare_write - prepare a page for receiving data
1810 * This is called from generic_file_write() with i_sem held on the inode
1811 * (@page->mapping->host). The @page is locked but not kmap()ped. The source
1812 * data has not yet been copied into the @page.
1814 * Need to extend the attribute/fill in holes if necessary, create blocks and
1815 * make partially overwritten blocks uptodate,
1817 * i_size is not to be modified yet.
1819 * Return 0 on success or -errno on error.
1821 * Should be using block_prepare_write() [support for sparse files] or
1822 * cont_prepare_write() [no support for sparse files]. Cannot do that due to
1823 * ntfs specifics but can look at them for implementation guidance.
1825 * Note: In the range, @from is inclusive and @to is exclusive, i.e. @from is
1826 * the first byte in the page that will be written to and @to is the first byte
1827 * after the last byte that will be written to.
1829 static int ntfs_prepare_write(struct file *file, struct page *page,
1830 unsigned from, unsigned to)
1833 struct inode *vi = page->mapping->host;
1834 ntfs_inode *base_ni = NULL, *ni = NTFS_I(vi);
1835 ntfs_volume *vol = ni->vol;
1836 ntfs_attr_search_ctx *ctx = NULL;
1837 MFT_RECORD *m = NULL;
1843 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
1844 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
1845 page->index, from, to);
1846 BUG_ON(!PageLocked(page));
1847 BUG_ON(from > PAGE_CACHE_SIZE);
1848 BUG_ON(to > PAGE_CACHE_SIZE);
1850 BUG_ON(NInoMstProtected(ni));
1852 * If a previous ntfs_truncate() failed, repeat it and abort if it
1855 if (unlikely(NInoTruncateFailed(ni))) {
1856 down_write(&vi->i_alloc_sem);
1857 err = ntfs_truncate(vi);
1858 up_write(&vi->i_alloc_sem);
1859 if (err || NInoTruncateFailed(ni)) {
1865 /* If the attribute is not resident, deal with it elsewhere. */
1866 if (NInoNonResident(ni)) {
1868 * Only unnamed $DATA attributes can be compressed, encrypted,
1871 if (ni->type == AT_DATA && !ni->name_len) {
1872 /* If file is encrypted, deny access, just like NT4. */
1873 if (NInoEncrypted(ni)) {
1874 ntfs_debug("Denying write access to encrypted "
1878 /* Compressed data streams are handled in compress.c. */
1879 if (NInoCompressed(ni)) {
1880 // TODO: Implement and replace this check with
1881 // return ntfs_write_compressed_block(page);
1882 ntfs_error(vi->i_sb, "Writing to compressed "
1883 "files is not supported yet. "
1887 // TODO: Implement and remove this check.
1888 if (NInoSparse(ni)) {
1889 ntfs_error(vi->i_sb, "Writing to sparse files "
1890 "is not supported yet. Sorry.");
1894 /* Normal data stream. */
1895 return ntfs_prepare_nonresident_write(page, from, to);
1898 * Attribute is resident, implying it is not compressed, encrypted, or
1901 BUG_ON(page_has_buffers(page));
1902 new_size = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
1903 /* If we do not need to resize the attribute allocation we are done. */
1904 if (new_size <= i_size_read(vi))
1907 // FIXME: We abort for now as this code is not safe.
1908 ntfs_error(vi->i_sb, "Changing the file size is not supported yet. "
1912 /* Map, pin, and lock the (base) mft record. */
1916 base_ni = ni->ext.base_ntfs_ino;
1917 m = map_mft_record(base_ni);
1924 ctx = ntfs_attr_get_search_ctx(base_ni, m);
1925 if (unlikely(!ctx)) {
1929 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
1930 CASE_SENSITIVE, 0, NULL, 0, ctx);
1931 if (unlikely(err)) {
1938 /* The total length of the attribute value. */
1939 attr_len = le32_to_cpu(a->data.resident.value_length);
1940 BUG_ON(i_size_read(vi) != attr_len);
1941 /* Check if new size is allowed in $AttrDef. */
1942 err = ntfs_attr_size_bounds_check(vol, ni->type, new_size);
1943 if (unlikely(err)) {
1944 if (err == -ERANGE) {
1945 ntfs_error(vol->sb, "Write would cause the inode "
1946 "0x%lx to exceed the maximum size for "
1947 "its attribute type (0x%x). Aborting "
1948 "write.", vi->i_ino,
1949 le32_to_cpu(ni->type));
1951 ntfs_error(vol->sb, "Inode 0x%lx has unknown "
1952 "attribute type 0x%x. Aborting "
1953 "write.", vi->i_ino,
1954 le32_to_cpu(ni->type));
1960 * Extend the attribute record to be able to store the new attribute
1963 if (new_size >= vol->mft_record_size || ntfs_attr_record_resize(m, a,
1964 le16_to_cpu(a->data.resident.value_offset) +
1966 /* Not enough space in the mft record. */
1967 ntfs_error(vol->sb, "Not enough space in the mft record for "
1968 "the resized attribute value. This is not "
1969 "supported yet. Aborting write.");
1974 * We have enough space in the mft record to fit the write. This
1975 * implies the attribute is smaller than the mft record and hence the
1976 * attribute must be in a single page and hence page->index must be 0.
1978 BUG_ON(page->index);
1980 * If the beginning of the write is past the old size, enlarge the
1981 * attribute value up to the beginning of the write and fill it with
1984 if (from > attr_len) {
1985 memset((u8*)a + le16_to_cpu(a->data.resident.value_offset) +
1986 attr_len, 0, from - attr_len);
1987 a->data.resident.value_length = cpu_to_le32(from);
1988 /* Zero the corresponding area in the page as well. */
1989 if (PageUptodate(page)) {
1990 kaddr = kmap_atomic(page, KM_USER0);
1991 memset(kaddr + attr_len, 0, from - attr_len);
1992 kunmap_atomic(kaddr, KM_USER0);
1993 flush_dcache_page(page);
1996 flush_dcache_mft_record_page(ctx->ntfs_ino);
1997 mark_mft_record_dirty(ctx->ntfs_ino);
1998 ntfs_attr_put_search_ctx(ctx);
1999 unmap_mft_record(base_ni);
2001 * Because resident attributes are handled by memcpy() to/from the
2002 * corresponding MFT record, and because this form of i/o is byte
2003 * aligned rather than block aligned, there is no need to bring the
2004 * page uptodate here as in the non-resident case where we need to
2005 * bring the buffers straddled by the write uptodate before
2006 * generic_file_write() does the copying from userspace.
2008 * We thus defer the uptodate bringing of the page region outside the
2009 * region written to to ntfs_commit_write(), which makes the code
2010 * simpler and saves one atomic kmap which is good.
2013 ntfs_debug("Done.");
2017 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2018 "prepare the write.");
2020 ntfs_error(vi->i_sb, "Resident attribute prepare write failed "
2021 "with error %i.", err);
2027 ntfs_attr_put_search_ctx(ctx);
2029 unmap_mft_record(base_ni);
2034 * ntfs_commit_nonresident_write -
2037 static int ntfs_commit_nonresident_write(struct page *page,
2038 unsigned from, unsigned to)
2040 s64 pos = ((s64)page->index << PAGE_CACHE_SHIFT) + to;
2041 struct inode *vi = page->mapping->host;
2042 struct buffer_head *bh, *head;
2043 unsigned int block_start, block_end, blocksize;
2046 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2047 "0x%lx, from = %u, to = %u.", vi->i_ino,
2048 NTFS_I(vi)->type, page->index, from, to);
2049 blocksize = 1 << vi->i_blkbits;
2051 // FIXME: We need a whole slew of special cases in here for compressed
2052 // files for example...
2053 // For now, we know ntfs_prepare_write() would have failed so we can't
2054 // get here in any of the cases which we have to special case, so we
2055 // are just a ripped off, unrolled generic_commit_write().
2057 bh = head = page_buffers(page);
2061 block_end = block_start + blocksize;
2062 if (block_end <= from || block_start >= to) {
2063 if (!buffer_uptodate(bh))
2066 set_buffer_uptodate(bh);
2067 mark_buffer_dirty(bh);
2069 } while (block_start = block_end, (bh = bh->b_this_page) != head);
2071 * If this is a partial write which happened to make all buffers
2072 * uptodate then we can optimize away a bogus ->readpage() for the next
2073 * read(). Here we 'discover' whether the page went uptodate as a
2074 * result of this (potentially partial) write.
2077 SetPageUptodate(page);
2079 * Not convinced about this at all. See disparity comment above. For
2080 * now we know ntfs_prepare_write() would have failed in the write
2081 * exceeds i_size case, so this will never trigger which is fine.
2083 if (pos > i_size_read(vi)) {
2084 ntfs_error(vi->i_sb, "Writing beyond the existing file size is "
2085 "not supported yet. Sorry.");
2087 // vi->i_size = pos;
2088 // mark_inode_dirty(vi);
2090 ntfs_debug("Done.");
2095 * ntfs_commit_write - commit the received data
2097 * This is called from generic_file_write() with i_sem held on the inode
2098 * (@page->mapping->host). The @page is locked but not kmap()ped. The source
2099 * data has already been copied into the @page. ntfs_prepare_write() has been
2100 * called before the data copied and it returned success so we can take the
2101 * results of various BUG checks and some error handling for granted.
2103 * Need to mark modified blocks dirty so they get written out later when
2104 * ntfs_writepage() is invoked by the VM.
2106 * Return 0 on success or -errno on error.
2108 * Should be using generic_commit_write(). This marks buffers uptodate and
2109 * dirty, sets the page uptodate if all buffers in the page are uptodate, and
2110 * updates i_size if the end of io is beyond i_size. In that case, it also
2111 * marks the inode dirty.
2113 * Cannot use generic_commit_write() due to ntfs specialities but can look at
2114 * it for implementation guidance.
2116 * If things have gone as outlined in ntfs_prepare_write(), then we do not
2117 * need to do any page content modifications here at all, except in the write
2118 * to resident attribute case, where we need to do the uptodate bringing here
2119 * which we combine with the copying into the mft record which means we save
2122 static int ntfs_commit_write(struct file *file, struct page *page,
2123 unsigned from, unsigned to)
2125 struct inode *vi = page->mapping->host;
2126 ntfs_inode *base_ni, *ni = NTFS_I(vi);
2127 char *kaddr, *kattr;
2128 ntfs_attr_search_ctx *ctx;
2134 ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, page index "
2135 "0x%lx, from = %u, to = %u.", vi->i_ino, ni->type,
2136 page->index, from, to);
2137 /* If the attribute is not resident, deal with it elsewhere. */
2138 if (NInoNonResident(ni)) {
2139 /* Only unnamed $DATA attributes can be compressed/encrypted. */
2140 if (ni->type == AT_DATA && !ni->name_len) {
2141 /* Encrypted files need separate handling. */
2142 if (NInoEncrypted(ni)) {
2143 // We never get here at present!
2146 /* Compressed data streams are handled in compress.c. */
2147 if (NInoCompressed(ni)) {
2148 // TODO: Implement this!
2149 // return ntfs_write_compressed_block(page);
2150 // We never get here at present!
2154 /* Normal data stream. */
2155 return ntfs_commit_nonresident_write(page, from, to);
2158 * Attribute is resident, implying it is not compressed, encrypted, or
2164 base_ni = ni->ext.base_ntfs_ino;
2165 /* Map, pin, and lock the mft record. */
2166 m = map_mft_record(base_ni);
2173 ctx = ntfs_attr_get_search_ctx(base_ni, m);
2174 if (unlikely(!ctx)) {
2178 err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
2179 CASE_SENSITIVE, 0, NULL, 0, ctx);
2180 if (unlikely(err)) {
2186 /* The total length of the attribute value. */
2187 attr_len = le32_to_cpu(a->data.resident.value_length);
2188 BUG_ON(from > attr_len);
2189 kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
2190 kaddr = kmap_atomic(page, KM_USER0);
2191 /* Copy the received data from the page to the mft record. */
2192 memcpy(kattr + from, kaddr + from, to - from);
2193 /* Update the attribute length if necessary. */
2194 if (to > attr_len) {
2196 a->data.resident.value_length = cpu_to_le32(attr_len);
2199 * If the page is not uptodate, bring the out of bounds area(s)
2200 * uptodate by copying data from the mft record to the page.
2202 if (!PageUptodate(page)) {
2204 memcpy(kaddr, kattr, from);
2206 memcpy(kaddr + to, kattr + to, attr_len - to);
2207 /* Zero the region outside the end of the attribute value. */
2208 if (attr_len < PAGE_CACHE_SIZE)
2209 memset(kaddr + attr_len, 0, PAGE_CACHE_SIZE - attr_len);
2211 * The probability of not having done any of the above is
2212 * extremely small, so we just flush unconditionally.
2214 flush_dcache_page(page);
2215 SetPageUptodate(page);
2217 kunmap_atomic(kaddr, KM_USER0);
2218 /* Update i_size if necessary. */
2219 if (i_size_read(vi) < attr_len) {
2220 unsigned long flags;
2222 write_lock_irqsave(&ni->size_lock, flags);
2223 ni->allocated_size = ni->initialized_size = attr_len;
2224 i_size_write(vi, attr_len);
2225 write_unlock_irqrestore(&ni->size_lock, flags);
2227 /* Mark the mft record dirty, so it gets written back. */
2228 flush_dcache_mft_record_page(ctx->ntfs_ino);
2229 mark_mft_record_dirty(ctx->ntfs_ino);
2230 ntfs_attr_put_search_ctx(ctx);
2231 unmap_mft_record(base_ni);
2232 ntfs_debug("Done.");
2235 if (err == -ENOMEM) {
2236 ntfs_warning(vi->i_sb, "Error allocating memory required to "
2237 "commit the write.");
2238 if (PageUptodate(page)) {
2239 ntfs_warning(vi->i_sb, "Page is uptodate, setting "
2240 "dirty so the write will be retried "
2241 "later on by the VM.");
2243 * Put the page on mapping->dirty_pages, but leave its
2244 * buffers' dirty state as-is.
2246 __set_page_dirty_nobuffers(page);
2249 ntfs_error(vi->i_sb, "Page is not uptodate. Written "
2250 "data has been lost.");
2252 ntfs_error(vi->i_sb, "Resident attribute commit write failed "
2253 "with error %i.", err);
2254 NVolSetErrors(ni->vol);
2258 ntfs_attr_put_search_ctx(ctx);
2260 unmap_mft_record(base_ni);
2264 #endif /* NTFS_RW */
2267 * ntfs_aops - general address space operations for inodes and attributes
2269 struct address_space_operations ntfs_aops = {
2270 .readpage = ntfs_readpage, /* Fill page with data. */
2271 .sync_page = block_sync_page, /* Currently, just unplugs the
2272 disk request queue. */
2274 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2275 .prepare_write = ntfs_prepare_write, /* Prepare page and buffers
2276 ready to receive data. */
2277 .commit_write = ntfs_commit_write, /* Commit received data. */
2278 #endif /* NTFS_RW */
2282 * ntfs_mst_aops - general address space operations for mst protecteed inodes
2285 struct address_space_operations ntfs_mst_aops = {
2286 .readpage = ntfs_readpage, /* Fill page with data. */
2287 .sync_page = block_sync_page, /* Currently, just unplugs the
2288 disk request queue. */
2290 .writepage = ntfs_writepage, /* Write dirty page to disk. */
2291 .set_page_dirty = __set_page_dirty_nobuffers, /* Set the page dirty
2292 without touching the buffers
2293 belonging to the page. */
2294 #endif /* NTFS_RW */
2300 * mark_ntfs_record_dirty - mark an ntfs record dirty
2301 * @page: page containing the ntfs record to mark dirty
2302 * @ofs: byte offset within @page at which the ntfs record begins
2304 * Set the buffers and the page in which the ntfs record is located dirty.
2306 * The latter also marks the vfs inode the ntfs record belongs to dirty
2307 * (I_DIRTY_PAGES only).
2309 * If the page does not have buffers, we create them and set them uptodate.
2310 * The page may not be locked which is why we need to handle the buffers under
2311 * the mapping->private_lock. Once the buffers are marked dirty we no longer
2312 * need the lock since try_to_free_buffers() does not free dirty buffers.
2314 void mark_ntfs_record_dirty(struct page *page, const unsigned int ofs) {
2315 struct address_space *mapping = page->mapping;
2316 ntfs_inode *ni = NTFS_I(mapping->host);
2317 struct buffer_head *bh, *head, *buffers_to_free = NULL;
2318 unsigned int end, bh_size, bh_ofs;
2320 BUG_ON(!PageUptodate(page));
2321 end = ofs + ni->itype.index.block_size;
2322 bh_size = 1 << VFS_I(ni)->i_blkbits;
2323 spin_lock(&mapping->private_lock);
2324 if (unlikely(!page_has_buffers(page))) {
2325 spin_unlock(&mapping->private_lock);
2326 bh = head = alloc_page_buffers(page, bh_size, 1);
2327 spin_lock(&mapping->private_lock);
2328 if (likely(!page_has_buffers(page))) {
2329 struct buffer_head *tail;
2332 set_buffer_uptodate(bh);
2334 bh = bh->b_this_page;
2336 tail->b_this_page = head;
2337 attach_page_buffers(page, head);
2339 buffers_to_free = bh;
2341 bh = head = page_buffers(page);
2343 bh_ofs = bh_offset(bh);
2344 if (bh_ofs + bh_size <= ofs)
2346 if (unlikely(bh_ofs >= end))
2348 set_buffer_dirty(bh);
2349 } while ((bh = bh->b_this_page) != head);
2350 spin_unlock(&mapping->private_lock);
2351 __set_page_dirty_nobuffers(page);
2352 if (unlikely(buffers_to_free)) {
2354 bh = buffers_to_free->b_this_page;
2355 free_buffer_head(buffers_to_free);
2356 buffers_to_free = bh;
2357 } while (buffers_to_free);
2361 #endif /* NTFS_RW */