ntfs filesystem remake
Subsystems (4)
Namjae Jeon
maintainerv3 cover ntfs filesystem remake
Introduction
============
The NTFS filesystem[1] still remains the default filesystem for Windows and The well-maintained NTFS driver in the Linux kernel enhances interoperability with Windows devices, making it easier for Linux users to work with NTFS-formatted drives. Currently, ntfs support in Linux was the long-neglected NTFS Classic (read-only), which has been removed from the Linux kernel, leaving the poorly maintained ntfs3. ntfs3 still has many problems and is poorly maintained, so users and distributions are still using the old legacy ntfs-3g.
The remade ntfs is an implementation that supports write and the essential requirements(iomap, no buffer-head, utilities, xfstests test result) based on read-only classic NTFS.
The old read-only ntfs code is much cleaner, with extensive comments, offers readability that makes understanding NTFS easier. This is why new ntfs was developed on old read-only NTFS base.
The target is to provide current trends(iomap, no buffer head, folio), enhanced performance, stable maintenance, utility support including fsck.
Key Features
============
- Write support:
Implement write support on classic read-only NTFS. Additionally, integrate delayed allocation to enhance write performance through multi-cluster allocation and minimized fragmentation of cluster bitmap.
- Switch to using iomap:
Use iomap for buffered IO writes, reads, direct IO, file extent mapping, readpages, writepages operations.
- Stop using the buffer head:
The use of buffer head in old ntfs and switched to use folio instead. As a result, CONFIG_BUFFER_HEAD option enable is removed in Kconfig also.
- Public utilities include fsck[2]:
While ntfs-3g includes ntfsprogs as a component, it notably lacks the fsck implementation. So we have launched a new ntfs utilitiies project called ntfsprogs-plus by forking from ntfs-3g after removing unnecessary ntfs fuse implementation. fsck.ntfs can be used for ntfs testing with xfstests as well as for recovering corrupted NTFS device.
- Performance Enhancements:
- ntfs vs. ntfs3:
* Performance was benchmarked using iozone with various chunk size.
- In single-thread(1T) write tests, ntfs show approximately 3~5% better performance.
- In multi-thread(4T) write tests, ntfs show approximately 35~110% better performance.
- Read throughput is identical for both ntfs implementations.
1GB file size:4096 size:16384 size:65536
MB/sec ntfs | ntfs3 ntfs | ntfs3 ntfs | ntfs3
─────────────────────────────────────────────────────────────────
read 399 | 399 426 | 424 429 | 430
─────────────────────────────────────────────────────────────────
write(1T) 291 | 276 325 | 305 333 | 317
write(4T) 105 | 50 113 | 78 114 | 99.6
* File list browsing performance. (about 12~14% faster)
files:100000 files:200000 files:400000
Sec ntfs | ntfs3 ntfs | ntfs3 ntfs | ntfs3
─────────────────────────────────────────────────────────────────
ls -lR 7.07 | 8.10 14.03 | 16.35 28.27 | 32.86
* mount time.
parti_size:1TB parti_size:2TB parti_size:4TB
Sec ntfs | ntfs3 ntfs | ntfs3 ntfs | ntfs3
─────────────────────────────────────────────────────────────────
mount 0.38 | 2.03 0.39 | 2.25 0.70 | 4.51
The following are the reasons why ntfs performance is higher
compared to ntfs3:
- Use iomap aops.
- Delayed allocation support.
- Optimize zero out for newly allocated clusters.
- Optimize runlist merge overhead with small chunck size.
- pre-load mft(inode) blocks and index(dentry) blocks to improve readdir + stat performance.
- Load lcn bitmap on background.
- Stability improvement:
a. Pass more xfstests tests:
ntfs passed 287 tests, significantly higher than ntfs3's 218. ntfs implement fallocate, idmapped mount and permission, etc, resulting in a significantly high number of xfstests passing compared to ntfs3.
b. Bonnie++ issue[3]:
The Bonnie++ benchmark fails on ntfs3 with a "Directory not empty" error during file deletion. ntfs3 currently iterates directory entries by reading index blocks one by one. When entries are deleted concurrently, index block merging or entry relocation can cause readdir() to skip some entries, leaving files undeleted in workloads(bonnie++) that mix unlink and directory scans. ntfs implement leaf chain traversal in readdir to avoid entry skip on deletion.
- Journaling support:
ntfs3 does not provide full journaling support. It only implement journal replay[4], which in our testing did not function correctly. My next task after upstreaming will be to add full journal support to ntfs.
The feature comparison summary
==============================
Feature ntfs ntfs3 =================================== ======== =========== Write support Yes Yes iomap support Yes No No buffer head Yes No Public utilities(mkfs, fsck, etc.) Yes No xfstests passed 287 218 Idmapped mount Yes No Delayed allocation Yes No Bonnie++ Pass Fail Journaling Planned Inoperative =================================== ======== ===========
References
==========
[1] https://en.wikipedia.org/wiki/NTFS
[2] https://github.com/ntfsprogs-plus/ntfsprogs-plus
[3] https://lore.kernel.org/ntfs3/CAOZgwEd7NDkGEpdF6UQTcbYuupDavaHBoj4WwTy3Qe4Bqm6V0g@mail.gmail.com/
[4] https://marc.info/?l=linux-fsdevel&m=161738417018673&q=mbox
Available in the Git repository at:
===================================git://git.kernel.org/pub/scm/linux/kernel/git/linkinjeon/ntfs.git ntfs-next
v3:
- Add generic helpers to convert cluster to folio index, cluster to byte, byte to sector, etc.
- Remove bio null check and ntfs_setup_bio().
- Remove unneeded extra handling from old ntfs leftover.
- Allow readahead for $MFT file.
- Change memcpy to memcpy_from_folio or memcpy_to_folio.
- Never switche between compressed and non-compressed for live inodes.
- Add the comments for iomap_valid and iomap_put_folio.
- Split the resident and non-resident cases into separate helpers.
- Use kmalloc instead of page allocation for iomap inline data.
- Use iomap_zero_range instead of ntfs_buffered_zero_clusters.
- Use blkdev_issue_zeroout instead of ntfs_zero_clusters.
- Remove 2TB limitation on 32-bit system.
- Rename ntfsplus to ntfs.
- Remove -EINTR handing for read_mapping_folio.
- Rename ntfs_iomap.c to iomap.c
- Revert alias for the legacy ntfs driver in ntfs3.
- Restrict built-in NTFS seclection to one driver, allow both as modules.
- Use static_assert() instead of the sizeof comments.
- Update the wrong iocharset comments in ntfs.rst.
v2:
- Add ntfs3-compatible mount options(sys_immutable, nohidden, hide_dot_files, nocase, acl, windows_names, disable_sparse, discard).
- Add iocharset mount option.
- Add ntfs3-compatible dos attribute and ntfs attribute load/store in setxattr/getattr().
- Add support for FS_IOC_{GET,SET}FSLABEL ioctl.
- Add support for FITRIM ioctl.
- Fix the warnings(duplicate symbol, __divdi3, etc) from kernel test robot.
- Prefix pr_xxx() with ntfsplus.
- Add support for $MFT File extension.
- Add Documentation/filesystems/ntfsplus.rst.
- Mark experimental.
- Remove BUG traps warnings from checkpatch.pl.
Namjae Jeon (14):
Revert "fs: Remove NTFS classic"
ntfs: update in-memory, on-disk structures and headers
ntfs: update super block operations
ntfs: update inode operations
ntfs: update directory operations
ntfs: update file operations
ntfs: update iomap and address space operations
ntfs: update attrib operations
ntfs: update runlist handling and cluster allocator
ntfs: add reparse and ea operations
ntfs: update misc operations
Revert: ntfs3: serve as alias for the legacy ntfs driver
ntfs: add Kconfig and Makefile
MAINTAINERS: add ntfs filesystem
Documentation/filesystems/index.rst | 1 + Documentation/filesystems/ntfs.rst | 203 + MAINTAINERS | 9 + fs/Kconfig | 18 + fs/Makefile | 1 + fs/ntfs/Kconfig | 46 + fs/ntfs/Makefile | 18 + fs/ntfs/aops.c | 543 +++ fs/ntfs/aops.h | 24 + fs/ntfs/attrib.c | 5384 +++++++++++++++++++++++++++ fs/ntfs/attrib.h | 159 + fs/ntfs/attrlist.c | 285 ++ fs/ntfs/attrlist.h | 21 + fs/ntfs/bitmap.c | 292 ++ fs/ntfs/bitmap.h | 93 + fs/ntfs/collate.c | 178 + fs/ntfs/collate.h | 37 + fs/ntfs/compress.c | 1559 ++++++++ fs/ntfs/debug.c | 171 + fs/ntfs/debug.h | 63 + fs/ntfs/dir.c | 1229 ++++++ fs/ntfs/dir.h | 33 + fs/ntfs/ea.c | 933 +++++ fs/ntfs/ea.h | 25 + fs/ntfs/endian.h | 79 + fs/ntfs/file.c | 1142 ++++++ fs/ntfs/index.c | 2115 +++++++++++ fs/ntfs/index.h | 127 + fs/ntfs/inode.c | 3793 +++++++++++++++++++ fs/ntfs/inode.h | 354 ++ fs/ntfs/iomap.c | 755 ++++ fs/ntfs/iomap.h | 22 + fs/ntfs/layout.h | 2291 ++++++++++++ fs/ntfs/lcnalloc.c | 1014 +++++ fs/ntfs/lcnalloc.h | 127 + fs/ntfs/logfile.c | 775 ++++ fs/ntfs/logfile.h | 316 ++ fs/ntfs/malloc.h | 100 + fs/ntfs/mft.c | 2691 +++++++++++++ fs/ntfs/mft.h | 92 + fs/ntfs/mst.c | 195 + fs/ntfs/namei.c | 1678 +++++++++ fs/ntfs/ntfs.h | 200 + fs/ntfs/quota.c | 97 + fs/ntfs/quota.h | 16 + fs/ntfs/reparse.c | 550 +++ fs/ntfs/reparse.h | 15 + fs/ntfs/runlist.c | 1983 ++++++++++ fs/ntfs/runlist.h | 93 + fs/ntfs/super.c | 2777 ++++++++++++++ fs/ntfs/sysctl.c | 56 + fs/ntfs/sysctl.h | 27 + fs/ntfs/time.h | 87 + fs/ntfs/types.h | 55 + fs/ntfs/unistr.c | 473 +++ fs/ntfs/upcase.c | 73 + fs/ntfs/volume.h | 254 ++ fs/ntfs3/Kconfig | 9 - fs/ntfs3/dir.c | 9 - fs/ntfs3/file.c | 10 - fs/ntfs3/inode.c | 16 +- fs/ntfs3/ntfs_fs.h | 11 - fs/ntfs3/super.c | 52 - include/uapi/linux/ntfs.h | 23 + 64 files changed, 35774 insertions(+), 103 deletions(-) create mode 100644 Documentation/filesystems/ntfs.rst create mode 100644 fs/ntfs/Kconfig create mode 100644 fs/ntfs/Makefile create mode 100644 fs/ntfs/aops.c create mode 100644 fs/ntfs/aops.h create mode 100644 fs/ntfs/attrib.c create mode 100644 fs/ntfs/attrib.h create mode 100644 fs/ntfs/attrlist.c create mode 100644 fs/ntfs/attrlist.h create mode 100644 fs/ntfs/bitmap.c create mode 100644 fs/ntfs/bitmap.h create mode 100644 fs/ntfs/collate.c create mode 100644 fs/ntfs/collate.h create mode 100644 fs/ntfs/compress.c create mode 100644 fs/ntfs/debug.c create mode 100644 fs/ntfs/debug.h create mode 100644 fs/ntfs/dir.c create mode 100644 fs/ntfs/dir.h create mode 100644 fs/ntfs/ea.c create mode 100644 fs/ntfs/ea.h create mode 100644 fs/ntfs/endian.h create mode 100644 fs/ntfs/file.c create mode 100644 fs/ntfs/index.c create mode 100644 fs/ntfs/index.h create mode 100644 fs/ntfs/inode.c create mode 100644 fs/ntfs/inode.h create mode 100644 fs/ntfs/iomap.c create mode 100644 fs/ntfs/iomap.h create mode 100644 fs/ntfs/layout.h create mode 100644 fs/ntfs/lcnalloc.c create mode 100644 fs/ntfs/lcnalloc.h create mode 100644 fs/ntfs/logfile.c create mode 100644 fs/ntfs/logfile.h create mode 100644 fs/ntfs/malloc.h create mode 100644 fs/ntfs/mft.c create mode 100644 fs/ntfs/mft.h create mode 100644 fs/ntfs/mst.c create mode 100644 fs/ntfs/namei.c create mode 100644 fs/ntfs/ntfs.h create mode 100644 fs/ntfs/quota.c create mode 100644 fs/ntfs/quota.h create mode 100644 fs/ntfs/reparse.c create mode 100644 fs/ntfs/reparse.h create mode 100644 fs/ntfs/runlist.c create mode 100644 fs/ntfs/runlist.h create mode 100644 fs/ntfs/super.c create mode 100644 fs/ntfs/sysctl.c create mode 100644 fs/ntfs/sysctl.h create mode 100644 fs/ntfs/time.h create mode 100644 fs/ntfs/types.h create mode 100644 fs/ntfs/unistr.c create mode 100644 fs/ntfs/upcase.c create mode 100644 fs/ntfs/volume.h create mode 100644 include/uapi/linux/ntfs.h
Signature · 1 line
2.25.1
Namjae Jeon
maintainerPATCH v3 1/14 Revert "fs: Remove NTFS classic"
This reverts commit 7ffa8f3d30236e0ab897c30bdb01224ff1fe1c89.
--- fs/ntfs/aops.c | 1744 ++++++++++++++++++++++++ fs/ntfs/aops.h | 88 ++ fs/ntfs/attrib.c | 2624 ++++++++++++++++++++++++++++++++++++ fs/ntfs/attrib.h | 102 ++ fs/ntfs/bitmap.c | 179 +++ fs/ntfs/bitmap.h | 104 ++ fs/ntfs/collate.c | 110 ++ fs/ntfs/collate.h | 36 + fs/ntfs/compress.c | 950 +++++++++++++ fs/ntfs/debug.c | 159 +++ fs/ntfs/debug.h | 57 + fs/ntfs/dir.c | 1540 +++++++++++++++++++++ fs/ntfs/dir.h | 34 + fs/ntfs/endian.h | 79 ++ fs/ntfs/file.c | 1997 +++++++++++++++++++++++++++ fs/ntfs/index.c | 440 ++++++ fs/ntfs/index.h | 134 ++ fs/ntfs/inode.c | 3102 ++++++++++++++++++++++++++++++++++++++++++ fs/ntfs/inode.h | 310 +++++ fs/ntfs/layout.h | 2421 +++++++++++++++++++++++++++++++++ fs/ntfs/lcnalloc.c | 1000 ++++++++++++++ fs/ntfs/lcnalloc.h | 131 ++ fs/ntfs/logfile.c | 849 ++++++++++++ fs/ntfs/logfile.h | 295 ++++ fs/ntfs/malloc.h | 77 ++ fs/ntfs/mft.c | 2907 ++++++++++++++++++++++++++++++++++++++++ fs/ntfs/mft.h | 110 ++ fs/ntfs/mst.c | 189 +++ fs/ntfs/namei.c | 392 ++++++ fs/ntfs/ntfs.h | 150 +++ fs/ntfs/quota.c | 103 ++ fs/ntfs/quota.h | 21 + fs/ntfs/runlist.c | 1893 ++++++++++++++++++++++++++ fs/ntfs/runlist.h | 88 ++ fs/ntfs/super.c | 3202 ++++++++++++++++++++++++++++++++++++++++++++ fs/ntfs/sysctl.c | 58 + fs/ntfs/sysctl.h | 27 + fs/ntfs/time.h | 89 ++ fs/ntfs/types.h | 55 + fs/ntfs/unistr.c | 384 ++++++ fs/ntfs/upcase.c | 73 + fs/ntfs/volume.h | 164 +++ 42 files changed, 28467 insertions(+) create mode 100644 fs/ntfs/aops.c create mode 100644 fs/ntfs/aops.h create mode 100644 fs/ntfs/attrib.c create mode 100644 fs/ntfs/attrib.h create mode 100644 fs/ntfs/bitmap.c create mode 100644 fs/ntfs/bitmap.h create mode 100644 fs/ntfs/collate.c create mode 100644 fs/ntfs/collate.h create mode 100644 fs/ntfs/compress.c create mode 100644 fs/ntfs/debug.c create mode 100644 fs/ntfs/debug.h create mode 100644 fs/ntfs/dir.c create mode 100644 fs/ntfs/dir.h create mode 100644 fs/ntfs/endian.h create mode 100644 fs/ntfs/file.c create mode 100644 fs/ntfs/index.c create mode 100644 fs/ntfs/index.h create mode 100644 fs/ntfs/inode.c create mode 100644 fs/ntfs/inode.h create mode 100644 fs/ntfs/layout.h create mode 100644 fs/ntfs/lcnalloc.c create mode 100644 fs/ntfs/lcnalloc.h create mode 100644 fs/ntfs/logfile.c create mode 100644 fs/ntfs/logfile.h create mode 100644 fs/ntfs/malloc.h create mode 100644 fs/ntfs/mft.c create mode 100644 fs/ntfs/mft.h create mode 100644 fs/ntfs/mst.c create mode 100644 fs/ntfs/namei.c create mode 100644 fs/ntfs/ntfs.h create mode 100644 fs/ntfs/quota.c create mode 100644 fs/ntfs/quota.h create mode 100644 fs/ntfs/runlist.c create mode 100644 fs/ntfs/runlist.h create mode 100644 fs/ntfs/super.c create mode 100644 fs/ntfs/sysctl.c create mode 100644 fs/ntfs/sysctl.h create mode 100644 fs/ntfs/time.h create mode 100644 fs/ntfs/types.h create mode 100644 fs/ntfs/unistr.c create mode 100644 fs/ntfs/upcase.c create mode 100644 fs/ntfs/volume.h
fs/ntfs/aops.c new file +1744 -0
@@ -0,0 +1,1744 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* +* aops.c - NTFS kernel address space operations and page cache handling. +* +* Copyright (c) 2001-2014 Anton Altaparmakov and Tuxera Inc. +* Copyright (c) 2002 Richard Russon +*/ + +#include <linux/errno.h> +#include <linux/fs.h> +#include <linux/gfp.h> +#include <linux/mm.h> +#include <linux/pagemap.h> +#include <linux/swap.h> +#include <linux/buffer_head.h> +#include <linux/writeback.h> +#include <linux/bit_spinlock.h> +#include <linux/bio.h> + +#include "aops.h" +#include "attrib.h" +#include "debug.h" +#include "inode.h" +#include "mft.h" +#include "runlist.h" +#include "types.h" +#include "ntfs.h" + +/** +* ntfs_end_buffer_async_read - async io completion for reading attributes +* @bh: buffer head on which io is completed +* @uptodate: whether @bh is now uptodate or not +* +* Asynchronous I/O completion handler for reading pages belonging to the +* attribute address space of an inode. The inodes can either be files or +* directories or they can be fake inodes describing some attribute. +* +* If NInoMstProtected(), perform the post read mst fixups when all IO on the +* page has been completed and mark the page uptodate or set the error bit on +* the page. To determine the size of the records that need fixing up, we +* cheat a little bit by setting the index_block_size in ntfs_inode to the ntfs +* record size, and index_block_size_bits, to the log(base 2) of the ntfs +* record size. +*/ +static void ntfs_end_buffer_async_read (struct buffer_head *bh,int uptodate) +{ +unsigned long flags; +struct buffer_head *first, *tmp; +struct page *page; +struct inode *vi; +ntfs_inode *ni; +int page_uptodate =1 ; + + page = bh->b_page; + vi = page->mapping->host; + ni =NTFS_I (vi); + +if (likely (uptodate)) { +loff_t i_size; +s64 file_ofs, init_size; + +set_buffer_uptodate (bh); + + file_ofs = ((s64 )page->index <<PAGE_SHIFT ) + +bh_offset (bh); +read_lock_irqsave (&ni->size_lock, flags); + init_size = ni->initialized_size; + i_size =i_size_read (vi); +read_unlock_irqrestore (&ni->size_lock, flags); +if (unlikely (init_size > i_size)) { +/* Race with shrinking truncate. */ + init_size = i_size; + } +/* Check for the current buffer head overflowing. */ +if (unlikely (file_ofs + bh->b_size > init_size)) { +int ofs; +void *kaddr; + + ofs =0 ; +if (file_ofs < init_size) + ofs = init_size - file_ofs; + kaddr =kmap_atomic (page); +memset (kaddr +bh_offset (bh) + ofs,0 , + bh->b_size - ofs); +flush_dcache_page (page); +kunmap_atomic (kaddr); + } + }else { +clear_buffer_uptodate (bh); +SetPageError (page); +ntfs_error (ni->vol->sb,"Buffer I/O error, logical block " +"0x%llx." , (unsigned long long )bh->b_blocknr); + } + first =page_buffers (page); +spin_lock_irqsave (&first->b_uptodate_lock, flags); +clear_buffer_async_read (bh); +unlock_buffer (bh); + tmp = bh; +do { +if (!buffer_uptodate (tmp)) + page_uptodate =0 ; +if (buffer_async_read (tmp)) { +if (likely (buffer_locked (tmp))) + goto still_busy; +/* Async buffers must be locked. */ +BUG (); + } + tmp = tmp->b_this_page; + }while (tmp != bh); +spin_unlock_irqrestore (&first->b_uptodate_lock, flags); +/* +* If none of the buffers had errors then we can set the page uptodate, +* but we first have to perform the post read mst fixups, if the +* attribute is mst protected, i.e. if NInoMstProteced(ni) is true. +* Note we ignore fixup errors as those are detected when +* map_mft_record() is called which gives us per record granularity +* rather than per page granularity. +*/ +if (!NInoMstProtected (ni)) { +if (likely (page_uptodate && !PageError (page))) +SetPageUptodate (page); + }else { +u8 *kaddr; +unsigned int i, recs; +u32 rec_size; + + rec_size = ni->itype.index.block_size; + recs =PAGE_SIZE / rec_size; +/* Should have been verified before we got here... */ +BUG_ON (!recs); + kaddr =kmap_atomic (page); +for (i =0 ; i < recs; i++) +post_read_mst_fixup ((NTFS_RECORD *)(kaddr + + i * rec_size), rec_size); +kunmap_atomic (kaddr); +flush_dcache_page (page); +if (likely (page_uptodate && !PageError (page))) +SetPageUptodate (page); + } +unlock_page (page); +return ; +still_busy: +spin_unlock_irqrestore (&first->b_uptodate_lock, flags); +return ; +} + +/** +* ntfs_read_block - fill a @folio of an address space with data +* @folio: page cache folio to fill with data +* +* We read each buffer asynchronously and when all buffers are read in, our io +* completion handler ntfs_end_buffer_read_async(), if required, automatically +* applies the mst fixups to the folio before finally marking it uptodate and +* unlocking it. +* +* We only enforce allocated_size limit because i_size is checked for in +* generic_file_read(). +* +* Return 0 on success and -errno on error. +* +* Contains an adapted version of fs/buffer.c::block_read_full_folio(). +*/ +static int ntfs_read_block (struct folio *folio) +{ +loff_t i_size; +VCN vcn; +LCN lcn; +s64 init_size; +struct inode *vi; +ntfs_inode *ni; +ntfs_volume *vol; +runlist_element *rl; +struct buffer_head *bh, *head, *arr[MAX_BUF_PER_PAGE ]; +sector_t iblock, lblock, zblock; +unsigned long flags; +unsigned int blocksize, vcn_ofs; +int i, nr; +unsigned char blocksize_bits; + + vi = folio->mapping->host; + ni =NTFS_I (vi); + vol = ni->vol; + +/* $MFT/$DATA must have its complete runlist in memory at all times. */ +BUG_ON (!ni->runlist.rl && !ni->mft_no && !NInoAttr (ni)); + + blocksize = vol->sb->s_blocksize; + blocksize_bits = vol->sb->s_blocksize_bits; + + head =folio_buffers (folio); +if (!head) + head =create_empty_buffers (folio, blocksize,0 ); + bh = head; + +/* +* We may be racing with truncate. To avoid some of the problems we +* now take a snapshot of the various sizes and use those for the whole +* of the function. In case of an extending truncate it just means we +* may leave some buffers unmapped which are now allocated. This is +* not a problem since these buffers will just get mapped when a write +* occurs. In case of a shrinking truncate, we will detect this later +* on due to the runlist being incomplete and if the folio is being +* fully truncated, truncate will throw it away as soon as we unlock +* it so no need to worry what we do with it. +*/ + iblock = (s64 )folio->index << (PAGE_SHIFT - blocksize_bits); +read_lock_irqsave (&ni->size_lock, flags); + lblock = (ni->allocated_size + blocksize -1 ) >> blocksize_bits; + init_size = ni->initialized_size; + i_size =i_size_read (vi); +read_unlock_irqrestore (&ni->size_lock, flags); +if (unlikely (init_size > i_size)) { +/* Race with shrinking truncate. */ + init_size = i_size; + } + zblock = (init_size + blocksize -1 ) >> blocksize_bits; + +/* Loop through all the buffers in the folio. */ + rl =NULL ; + nr = i =0 ; +do { +int err =0 ; + +if (unlikely (buffer_uptodate (bh))) +continue ; +if (unlikely (buffer_mapped (bh))) { + arr[nr++] = bh; +continue ; + } + bh->b_bdev = vol->sb->s_bdev; +/* Is the block within the allowed limits? */ +if (iblock < lblock) { +bool is_retry = false; + +/* Convert iblock into corresponding vcn and offset. */ + vcn = (VCN )iblock << blocksize_bits >> + vol->cluster_size_bits; + vcn_ofs = ((VCN )iblock << blocksize_bits) & + vol->cluster_size_mask; +if (!rl) { +lock_retry_remap: +down_read (&ni->runlist.lock); + rl = ni->runlist.rl; + } +if (likely (rl !=NULL )) { +/* Seek to element containing target vcn. */ +while (rl->length && rl[1 ].vcn <= vcn) + rl++; + lcn =ntfs_rl_vcn_to_lcn (rl, vcn); + }else + lcn =LCN_RL_NOT_MAPPED ; +/* Successful remap. */ +if (lcn >=0 ) { +/* Setup buffer head to correct block. */ + bh->b_blocknr = ((lcn << vol->cluster_size_bits) + + vcn_ofs) >> blocksize_bits; +set_buffer_mapped (bh); +/* Only read initialized data blocks. */ +if (iblock < zblock) { + arr[nr++] = bh; +continue ; + } +/* Fully non-initialized data block, zero it. */ + goto handle_zblock; + } +/* It is a hole, need to zero it. */ +if (lcn ==LCN_HOLE ) + goto handle_hole; +/* If first try and runlist unmapped, map and retry. */ +if (!is_retry && lcn ==LCN_RL_NOT_MAPPED ) { + is_retry = true; +/* +* Attempt to map runlist, dropping lock for +* the duration. +*/ +up_read (&ni->runlist.lock); + err =ntfs_map_runlist (ni, vcn); +if (likely (!err)) + goto lock_retry_remap; + rl =NULL ; + }else if (!rl) +up_read (&ni->runlist.lock); +/* +* If buffer is outside the runlist, treat it as a +* hole. This can happen due to concurrent truncate +* for example. +*/ +if (err == -ENOENT || lcn ==LCN_ENOENT ) { + err =0 ; + goto handle_hole; + } +/* Hard error, zero out region. */ +if (!err) + err = -EIO ; + bh->b_blocknr =-1 ; +folio_set_error (folio); +ntfs_error (vol->sb,"Failed to read from inode 0x%lx, " +"attribute type 0x%x, vcn 0x%llx, " +"offset 0x%x because its location on " +"disk could not be determined%s " +"(error code %i)." , ni->mft_no, + ni->type, (unsigned long long )vcn, + vcn_ofs, is_retry ?" even after " +"retrying" :"" , err); + } +/* +* Either iblock was outside lblock limits or +* ntfs_rl_vcn_to_lcn() returned error. Just zero that portion +* of the folio and set the buffer uptodate. +*/ +handle_hole: + bh->b_blocknr =-1UL ; +clear_buffer_mapped (bh); +handle_zblock: +folio_zero_range (folio, i * blocksize, blocksize); +if (likely (!err)) +set_buffer_uptodate (bh); + }while (i++, iblock++, (bh = bh->b_this_page) != head); + +/* Release the lock if we took it. */ +if (rl) +up_read (&ni->runlist.lock); + +/* Check we have at least one buffer ready for i/o. */ +if (nr) { +struct buffer_head *tbh; + +/* Lock the buffers. */ +for (i =0 ; i < nr; i++) { + tbh = arr[i]; +lock_buffer (tbh); + tbh->b_end_io = ntfs_end_buffer_async_read; +set_buffer_async_read (tbh); + } +/* Finally, start i/o on the buffers. */ +for (i =0 ; i < nr; i++) { + tbh = arr[i]; +if (likely (!buffer_uptodate (tbh))) +submit_bh (REQ_OP_READ , tbh); +else +ntfs_end_buffer_async_read (tbh,1 ); + } +return 0 ; + } +/* No i/o was scheduled on any of the buffers. */ +if (likely (!folio_test_error (folio))) +folio_mark_uptodate (folio); +else /* Signal synchronous i/o error. */ + nr = -EIO ; +folio_unlock (folio); +return nr; +} + +/** +* ntfs_read_folio - fill a @folio of a @file with data from the device +* @file: open file to which the folio @folio belongs or NULL +* @folio: page cache folio to fill with data +* +* For non-resident attributes, ntfs_read_folio() fills the @folio of the open +* file @file by calling the ntfs version of the generic block_read_full_folio() +* function, ntfs_read_block(), which in turn creates and reads in the buffers +* associated with the folio asynchronously. +* +* For resident attributes, OTOH, ntfs_read_folio() fills @folio by copying the +* data from the mft record (which at this stage is most likely in memory) and +* fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as +* even if the mft record is not cached at this point in time, we need to wait +* for it to be read in before we can do the copy. +* +* Return 0 on success and -errno on error. +*/ +static int ntfs_read_folio (struct file *file,struct folio *folio) +{ +struct page *page = &folio->page; +loff_t i_size; +struct inode *vi; +ntfs_inode *ni, *base_ni; +u8 *addr; +ntfs_attr_search_ctx *ctx; +MFT_RECORD *mrec; +unsigned long flags; +u32 attr_len; +int err =0 ; + +retry_readpage: +BUG_ON (!PageLocked (page)); + vi = page->mapping->host; + i_size =i_size_read (vi); +/* Is the page fully outside i_size? (truncate in progress) */ +if (unlikely (page->index >= (i_size +PAGE_SIZE -1 ) >> +PAGE_SHIFT )) { +zero_user (page,0 ,PAGE_SIZE ); +ntfs_debug ("Read outside i_size - truncated?" ); + goto done; + } +/* +* This can potentially happen because we clear PageUptodate() during +* ntfs_writepage() of MstProtected() attributes. +*/ +if (PageUptodate (page)) { +unlock_page (page); +return 0 ; + } + ni =NTFS_I (vi); +/* +* Only $DATA attributes can be encrypted and only unnamed $DATA +* attributes can be compressed. Index root can have the flags set but +* this means to create compressed/encrypted files, not that the +* attribute is compressed/encrypted. Note we need to check for +* AT_INDEX_ALLOCATION since this is the type of both directory and +* index inodes. +*/ +if (ni->type !=AT_INDEX_ALLOCATION ) { +/* If attribute is encrypted, deny access, just like NT4. */ +if (NInoEncrypted (ni)) { +BUG_ON (ni->type !=AT_DATA ); + err = -EACCES ; + goto err_out; + } +/* Compressed data streams are handled in compress.c. */ +if (NInoNonResident (ni) &&NInoCompressed (ni)) { +BUG_ON (ni->type !=AT_DATA ); +BUG_ON (ni->name_len); +return ntfs_read_compressed_block (page); + } + } +/* NInoNonResident() == NInoIndexAllocPresent() */ +if (NInoNonResident (ni)) { +/* Normal, non-resident data stream. */ +return ntfs_read_block (folio); + } +/* +* Attribute is resident, implying it is not compressed or encrypted. +* This also means the attribute is smaller than an mft record and +* hence smaller than a page, so can simply zero out any pages with +* index above 0. Note the attribute can actually be marked compressed +* but if it is resident the actual data is not compressed so we are +* ok to ignore the compressed flag here. +*/ +if (unlikely (page->index >0 )) { +zero_user (page,0 ,PAGE_SIZE ); + goto done; + } +if (!NInoAttr (ni)) + base_ni = ni; +else + base_ni = ni->ext.base_ntfs_ino; +/* Map, pin, and lock the mft record. */ + mrec =map_mft_record (base_ni); +if (IS_ERR (mrec)) { + err =PTR_ERR (mrec); + goto err_out; + } +/* +* If a parallel write made the attribute non-resident, drop the mft +* record and retry the read_folio. +*/ +if (unlikely (NInoNonResident (ni))) { +unmap_mft_record (base_ni); + goto retry_readpage; + } + ctx =ntfs_attr_get_search_ctx (base_ni, mrec); +if (unlikely (!ctx)) { + err = -ENOMEM ; + goto unm_err_out; + } + err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, +CASE_SENSITIVE ,0 ,NULL ,0 , ctx); +if (unlikely (err)) + goto put_unm_err_out; + attr_len =le32_to_cpu (ctx->attr->data.resident.value_length); +read_lock_irqsave (&ni->size_lock, flags); +if (unlikely (attr_len > ni->initialized_size)) + attr_len = ni->initialized_size; + i_size =i_size_read (vi); +read_unlock_irqrestore (&ni->size_lock, flags); +if (unlikely (attr_len > i_size)) { +/* Race with shrinking truncate. */ + attr_len = i_size; + } + addr =kmap_atomic (page); +/* Copy the data to the page. */ +memcpy (addr, (u8 *)ctx->attr + +le16_to_cpu (ctx->attr->data.resident.value_offset), + attr_len); +/* Zero the remainder of the page. */ +memset (addr + attr_len,0 ,PAGE_SIZE - attr_len); +flush_dcache_page (page); +kunmap_atomic (addr); +put_unm_err_out: +ntfs_attr_put_search_ctx (ctx); +unm_err_out: +unmap_mft_record (base_ni); +done: +SetPageUptodate (page); +err_out: +unlock_page (page); +return err; +} + +#ifdef NTFS_RW + +/** +* ntfs_write_block - write a @folio to the backing store +* @folio: page cache folio to write out +* @wbc: writeback control structure +* +* This function is for writing folios belonging to non-resident, non-mst +* protected attributes to their backing store. +* +* For a folio with buffers, map and write the dirty buffers asynchronously +* under folio writeback. For a folio without buffers, create buffers for the +* folio, then proceed as above. +* +* If a folio doesn't have buffers the folio dirty state is definitive. If +* a folio does have buffers, the folio dirty state is just a hint, +* and the buffer dirty state is definitive. (A hint which has rules: +* dirty buffers against a clean folio is illegal. Other combinations are +* legal and need to be handled. In particular a dirty folio containing +* clean buffers for example.) +* +* Return 0 on success and -errno on error. +* +* Based on ntfs_read_block() and __block_write_full_folio(). +*/ +static int ntfs_write_block (struct folio *folio,struct writeback_control *wbc) +{ +VCN vcn; +LCN lcn; +s64 initialized_size; +loff_t i_size; +sector_t block, dblock, iblock; +struct inode *vi; +ntfs_inode *ni; +ntfs_volume *vol; +runlist_element *rl; +struct buffer_head *bh, *head; +unsigned long flags; +unsigned int blocksize, vcn_ofs; +int err; +bool need_end_writeback; +unsigned char blocksize_bits; + + vi = folio->mapping->host; + ni =NTFS_I (vi); + vol = ni->vol; + +ntfs_debug ("Entering for inode 0x%lx, attribute type 0x%x, page index " +"0x%lx." , ni->mft_no, ni->type, folio->index); + +BUG_ON (!NInoNonResident (ni)); +BUG_ON (NInoMstProtected (ni)); + blocksize = vol->sb->s_blocksize; + blocksize_bits = vol->sb->s_blocksize_bits; + head =folio_buffers (folio); +if (!head) { +BUG_ON (!folio_test_uptodate (folio)); + head =create_empty_buffers (folio, blocksize, + (1 << BH_Uptodate) | (1 << BH_Dirty)); + } + bh = head; + +/* NOTE: Different naming scheme to ntfs_read_block()! */ + +/* The first block in the folio. */ + block = (s64 )folio->index << (PAGE_SHIFT - blocksize_bits); + +read_lock_irqsave (&ni->size_lock, flags); + i_size =i_size_read (vi); + initialized_size = ni->initialized_size; +read_unlock_irqrestore (&ni->size_lock, flags); + +/* The first out of bounds block for the data size. */ + dblock = (i_size + blocksize -1 ) >> blocksize_bits; + +/* The last (fully or partially) initialized block. */ + iblock = initialized_size >> blocksize_bits; + +/* +* Be very careful. We have no exclusion from block_dirty_folio +* here, and the (potentially unmapped) buffers may become dirty at +* any time. If a buffer becomes dirty here after we've inspected it +* then we just miss that fact, and the folio stays dirty. +* +* Buffers outside i_size may be dirtied by block_dirty_folio; +* handle that here by just cleaning them. +*/ + +/* +* Loop through all the buffers in the folio, mapping all the dirty +* buffers to disk addresses and handling any aliases from the +* underlying block device's mapping. +*/ + rl =NULL ; + err =0 ; +do { +bool is_retry = false; + +if (unlikely (block >= dblock)) { +/* +* Mapped buffers outside i_size will occur, because +* this folio can be outside i_size when there is a +* truncate in progress. The contents of such buffers +* were zeroed by ntfs_writepage(). +* +* FIXME: What about the small race window where +* ntfs_writepage() has not done any clearing because +* the folio was within i_size but before we get here, +* vmtruncate() modifies i_size? +*/ +clear_buffer_dirty (bh); +set_buffer_uptodate (bh); +continue ; + } + +/* Clean buffers are not written out, so no need to map them. */ +if (!buffer_dirty (bh)) +continue ; + +/* Make sure we have enough initialized size. */ +if (unlikely ((block >= iblock) && + (initialized_size < i_size))) { +/* +* If this folio is fully outside initialized +* size, zero out all folios between the current +* initialized size and the current folio. Just +* use ntfs_read_folio() to do the zeroing +* transparently. +*/ +if (block > iblock) { +// TODO: +// For each folio do: +// - read_cache_folio() +// Again for each folio do: +// - wait_on_folio_locked() +// - Check (folio_test_uptodate(folio) && +// !folio_test_error(folio)) +// Update initialized size in the attribute and +// in the inode. +// Again, for each folio do: +// block_dirty_folio(); +// folio_put() +// We don't need to wait on the writes. +// Update iblock. + } +/* +* The current folio straddles initialized size. Zero +* all non-uptodate buffers and set them uptodate (and +* dirty?). Note, there aren't any non-uptodate buffers +* if the folio is uptodate. +* FIXME: For an uptodate folio, the buffers may need to +* be written out because they were not initialized on +* disk before. +*/ +if (!folio_test_uptodate (folio)) { +// TODO: +// Zero any non-uptodate buffers up to i_size. +// Set them uptodate and dirty. + } +// TODO: +// Update initialized size in the attribute and in the +// inode (up to i_size). +// Update iblock. +// FIXME: This is inefficient. Try to batch the two +// size changes to happen in one go. +ntfs_error (vol->sb,"Writing beyond initialized size " +"is not supported yet. Sorry." ); + err = -EOPNOTSUPP ; +break ; +// Do NOT set_buffer_new() BUT DO clear buffer range +// outside write request range. +// set_buffer_uptodate() on complete buffers as well as +// set_buffer_dirty(). + } + +/* No need to map buffers that are already mapped. */ +if (buffer_mapped (bh)) +continue ; + +/* Unmapped, dirty buffer. Need to map it. */ + bh->b_bdev = vol->sb->s_bdev; + +/* Convert block into corresponding vcn and offset. */ + vcn = (VCN )block << blocksize_bits; + vcn_ofs = vcn & vol->cluster_size_mask; + vcn >>= vol->cluster_size_bits; +if (!rl) { +lock_retry_remap: +down_read (&ni->runlist.lock); + rl = ni->runlist.rl; + } +if (likely (rl !=NULL )) { +/* Seek to element containing target vcn. */ +while (rl->length && rl[1 ].vcn <= vcn) + rl++; + lcn =ntfs_rl_vcn_to_lcn (rl, vcn); + }else + lcn =LCN_RL_NOT_MAPPED ; +/* Successful remap. */ +if (lcn >=0 ) { +/* Setup buffer head to point to correct block. */ + bh->b_blocknr = ((lcn << vol->cluster_size_bits) + + vcn_ofs) >> blocksize_bits; +set_buffer_mapped (bh); +continue ; + } +/* It is a hole, need to instantiate it. */ +if (lcn ==LCN_HOLE ) { +u8 *kaddr; +unsigned long *bpos, *bend; + +/* Check if the buffer is zero. */ + kaddr =kmap_local_folio (folio,bh_offset (bh)); + bpos = (unsigned long *)kaddr; + bend = (unsigned long *)(kaddr + blocksize); +do { +if (unlikely (*bpos)) +break ; + }while (likely (++bpos < bend)); +kunmap_local (kaddr); +if (bpos == bend) { +/* +* Buffer is zero and sparse, no need to write +* it. +*/ + bh->b_blocknr =-1 ; +clear_buffer_dirty (bh); +continue ; + } +// TODO: Instantiate the hole. +// clear_buffer_new(bh); +// clean_bdev_bh_alias(bh); +ntfs_error (vol->sb,"Writing into sparse regions is " +"not supported yet. Sorry." ); + err = -EOPNOTSUPP ; +break ; + } +/* If first try and runlist unmapped, map and retry. */ +if (!is_retry && lcn ==LCN_RL_NOT_MAPPED ) { + is_retry = true; +/* +* Attempt to map runlist, dropping lock for +* the duration. +*/ +up_read (&ni->runlist.lock); + err =ntfs_map_runlist (ni, vcn); +if (likely (!err)) + goto lock_retry_remap; + rl =NULL ; + }else if (!rl) +up_read (&ni->runlist.lock); +/* +* If buffer is outside the runlist, truncate has cut it out +* of the runlist. Just clean and clear the buffer and set it +* uptodate so it can get discarded by the VM. +*/ +if (err == -ENOENT || lcn ==LCN_ENOENT ) { + bh->b_blocknr =-1 ; +clear_buffer_dirty (bh); +folio_zero_range (folio,bh_offset (bh), blocksize); +set_buffer_uptodate (bh); + err =0 ; +continue ; + } +/* Failed to map the buffer, even after retrying. */ +if (!err) + err = -EIO ; + bh->b_blocknr =-1 ; +ntfs_error (vol->sb,"Failed to write to inode 0x%lx, " +"attribute type 0x%x, vcn 0x%llx, offset 0x%x " +"because its location on disk could not be " +"determined%s (error code %i)." , ni->mft_no, + ni->type, (unsigned long long )vcn, + vcn_ofs, is_retry ?" even after " +"retrying" :"" , err); +break ; + }while (block++, (bh = bh->b_this_page) != head); + +/* Release the lock if we took it. */ +if (rl) +up_read (&ni->runlist.lock); + +/* For the error case, need to reset bh to the beginning. */ + bh = head; + +/* Just an optimization, so ->read_folio() is not called later. */ +if (unlikely (!folio_test_uptodate (folio))) { +int uptodate =1 ; +do { +if (!buffer_uptodate (bh)) { + uptodate =0 ; + bh = head; +break ; + } + }while ((bh = bh->b_this_page) != head); +if (uptodate) +folio_mark_uptodate (folio); + } + +/* Setup all mapped, dirty buffers for async write i/o. */ +do { +if (buffer_mapped (bh) &&buffer_dirty (bh)) { +lock_buffer (bh); +if (test_clear_buffer_dirty (bh)) { +BUG_ON (!buffer_uptodate (bh)); +mark_buffer_async_write (bh); + }else +unlock_buffer (bh); + }else if (unlikely (err)) { +/* +* For the error case. The buffer may have been set +* dirty during attachment to a dirty folio. +*/ +if (err != -ENOMEM ) +clear_buffer_dirty (bh); + } + }while ((bh = bh->b_this_page) != head); + +if (unlikely (err)) { +// TODO: Remove the -EOPNOTSUPP check later on... +if (unlikely (err == -EOPNOTSUPP )) + err =0 ; +else if (err == -ENOMEM ) { +ntfs_warning (vol->sb,"Error allocating memory. " +"Redirtying folio so we try again " +"later." ); +/* +* Put the folio back on mapping->dirty_pages, but +* leave its buffer's dirty state as-is. +*/ +folio_redirty_for_writepage (wbc, folio); + err =0 ; + }else +folio_set_error (folio); + } + +BUG_ON (folio_test_writeback (folio)); +folio_start_writeback (folio);/* Keeps try_to_free_buffers() away. */ + +/* Submit the prepared buffers for i/o. */ + need_end_writeback = true; +do { +struct buffer_head *next = bh->b_this_page; +if (buffer_async_write (bh)) { +submit_bh (REQ_OP_WRITE , bh); + need_end_writeback = false; + } + bh = next; + }while (bh != head); +folio_unlock (folio); + +/* If no i/o was started, need to end writeback here. */ +if (unlikely (need_end_writeback)) +folio_end_writeback (folio); + +ntfs_debug ("Done." ); +return err; +} + +/** +* ntfs_write_mst_block - write a @page to the backing store +* @page: page cache page to write out +* @wbc: writeback control structure +* +* This function is for writing pages belonging to non-resident, mst protected +* attributes to their backing store. The only supported attributes are index +* allocation and $MFT/$DATA. Both directory inodes and index inodes are +* supported for the index allocation case. +* +* The page must remain locked for the duration of the write because we apply +* the mst fixups, write, and then undo the fixups, so if we were to unlock the +* page before undoing the fixups, any other user of the page will see the +* page contents as corrupt. +* +* We clear the page uptodate flag for the duration of the function to ensure +* exclusion for the $MFT/$DATA case against someone mapping an mft record we +* are about to apply the mst fixups to. +* +* Return 0 on success and -errno on error. +* +* Based on ntfs_write_block(), ntfs_mft_writepage(), and +* write_mft_record_nolock(). +*/ +static int ntfs_write_mst_block (struct page *page, +struct writeback_control *wbc) +{ +sector_t block, dblock, rec_block; +struct inode *vi = page->mapping->host; +ntfs_inode *ni =NTFS_I (vi); +ntfs_volume *vol = ni->vol; +u8 *kaddr; +unsigned int rec_size = ni->itype.index.block_size; +ntfs_inode *locked_nis[PAGE_SIZE /NTFS_BLOCK_SIZE ]; +struct buffer_head *bh, *head, *tbh, *rec_start_bh; +struct buffer_head *bhs[MAX_BUF_PER_PAGE ]; +runlist_element *rl; +int i, nr_locked_nis, nr_recs, nr_bhs, max_bhs, bhs_per_rec, err, err2; +unsigned bh_size, rec_size_bits; +bool sync, is_mft, page_is_dirty, rec_is_dirty; +unsigned char bh_size_bits; + +if (WARN_ON (rec_size <NTFS_BLOCK_SIZE )) +return -EINVAL ; + +ntfs_debug ("Entering for inode 0x%lx, attribute type 0x%x, page index " +"0x%lx." , vi->i_ino, ni->type, page->index); +BUG_ON (!NInoNonResident (ni)); +BUG_ON (!NInoMstProtected (ni)); + is_mft = (S_ISREG (vi->i_mode) && !vi->i_ino); +/* +* NOTE: ntfs_write_mst_block() would be called for $MFTMirr if a page +* in its page cache were to be marked dirty. However this should +* never happen with the current driver and considering we do not +* handle this case here we do want to BUG(), at least for now. +*/ +BUG_ON (!(is_mft ||S_ISDIR (vi->i_mode) || + (NInoAttr (ni) && ni->type ==AT_INDEX_ALLOCATION ))); + bh_size = vol->sb->s_blocksize; + bh_size_bits = vol->sb->s_blocksize_bits; + max_bhs =PAGE_SIZE / bh_size; +BUG_ON (!max_bhs); +BUG_ON (max_bhs >MAX_BUF_PER_PAGE ); + +/* Were we called for sync purposes? */ + sync = (wbc->sync_mode ==WB_SYNC_ALL ); + +/* Make sure we have mapped buffers. */ + bh = head =page_buffers (page); +BUG_ON (!bh); + + rec_size_bits = ni->itype.index.block_size_bits; +BUG_ON (!(PAGE_SIZE >> rec_size_bits)); + bhs_per_rec = rec_size >> bh_size_bits; +BUG_ON (!bhs_per_rec); + +/* The first block in the page. */ + rec_block = block = (sector_t )page->index << + (PAGE_SHIFT - bh_size_bits); + +/* The first out of bounds block for the data size. */ + dblock = (i_size_read (vi) + bh_size -1 ) >> bh_size_bits; + + rl =NULL ; + err = err2 = nr_bhs = nr_recs = nr_locked_nis =0 ; + page_is_dirty = rec_is_dirty = false; + rec_start_bh =NULL ; +do { +bool is_retry = false; + +if (likely (block < rec_block)) { +if (unlikely (block >= dblock)) { +clear_buffer_dirty (bh); +set_buffer_uptodate (bh); +continue ; + } +/* +* This block is not the first one in the record. We +* ignore the buffer's dirty state because we could +* have raced with a parallel mark_ntfs_record_dirty(). +*/ +if (!rec_is_dirty) +continue ; +if (unlikely (err2)) { +if (err2 != -ENOMEM ) +clear_buffer_dirty (bh); +continue ; + } + }else /* if (block == rec_block) */ { +BUG_ON (block > rec_block); +/* This block is the first one in the record. */ + rec_block += bhs_per_rec; + err2 =0 ; +if (unlikely (block >= dblock)) { +clear_buffer_dirty (bh); +continue ; + } +if (!buffer_dirty (bh)) { +/* Clean records are not written out. */ + rec_is_dirty = false; +continue ; + } + rec_is_dirty = true; + rec_start_bh = bh; + } +/* Need to map the buffer if it is not mapped already. */ +if (unlikely (!buffer_mapped (bh))) { +VCN vcn; +LCN lcn; +unsigned int vcn_ofs; + + bh->b_bdev = vol->sb->s_bdev; +/* Obtain the vcn and offset of the current block. */ + vcn = (VCN )block << bh_size_bits; + vcn_ofs = vcn & vol->cluster_size_mask; + vcn >>= vol->cluster_size_bits; +if (!rl) { +lock_retry_remap: +down_read (&ni->runlist.lock); + rl = ni->runlist.rl; + } +if (likely (rl !=NULL )) { +/* Seek to element containing target vcn. */ +while (rl->length && rl[1 ].vcn <= vcn) + rl++; + lcn =ntfs_rl_vcn_to_lcn (rl, vcn); + }else + lcn =LCN_RL_NOT_MAPPED ; +/* Successful remap. */ +if (likely (lcn >=0 )) { +/* Setup buffer head to correct block. */ + bh->b_blocknr = ((lcn << + vol->cluster_size_bits) + + vcn_ofs) >> bh_size_bits; +set_buffer_mapped (bh); + }else { +/* +* Remap failed. Retry to map the runlist once +* unless we are working on $MFT which always +* has the whole of its runlist in memory. +*/ +if (!is_mft && !is_retry && + lcn ==LCN_RL_NOT_MAPPED ) { + is_retry = true; +/* +* Attempt to map runlist, dropping +* lock for the duration. +*/ +up_read (&ni->runlist.lock); + err2 =ntfs_map_runlist (ni, vcn); +if (likely (!err2)) + goto lock_retry_remap; +if (err2 == -ENOMEM ) + page_is_dirty = true; + lcn = err2; + }else { + err2 = -EIO ; +if (!rl) +up_read (&ni->runlist.lock); + } +/* Hard error. Abort writing this record. */ +if (!err || err == -ENOMEM ) + err = err2; + bh->b_blocknr =-1 ; +ntfs_error (vol->sb,"Cannot write ntfs record " +"0x%llx (inode 0x%lx, " +"attribute type 0x%x) because " +"its location on disk could " +"not be determined (error " +"code %lli)." , + (long long )block << + bh_size_bits >> + vol->mft_record_size_bits, + ni->mft_no, ni->type, + (long long )lcn); +/* +* If this is not the first buffer, remove the +* buffers in this record from the list of +* buffers to write and clear their dirty bit +* if not error -ENOMEM. +*/ +if (rec_start_bh != bh) { +while (bhs[--nr_bhs] != rec_start_bh) + ; +if (err2 != -ENOMEM ) { +do { +clear_buffer_dirty ( + rec_start_bh); + }while ((rec_start_bh = + rec_start_bh-> + b_this_page) != + bh); + } + } +continue ; + } + } +BUG_ON (!buffer_uptodate (bh)); +BUG_ON (nr_bhs >= max_bhs); + bhs[nr_bhs++] = bh; + }while (block++, (bh = bh->b_this_page) != head); +if (unlikely (rl)) +up_read (&ni->runlist.lock); +/* If there were no dirty buffers, we are done. */ +if (!nr_bhs) + goto done; +/* Map the page so we can access its contents. */ + kaddr =kmap (page); +/* Clear the page uptodate flag whilst the mst fixups are applied. */ +BUG_ON (!PageUptodate (page)); +ClearPageUptodate (page); +for (i =0 ; i < nr_bhs; i++) { +unsigned int ofs; + +/* Skip buffers which are not at the beginning of records. */ +if (i % bhs_per_rec) +continue ; + tbh = bhs[i]; + ofs =bh_offset (tbh); +if (is_mft) { +ntfs_inode *tni; +unsigned long mft_no; + +/* Get the mft record number. */ + mft_no = (((s64 )page->index <<PAGE_SHIFT ) + ofs) + >> rec_size_bits; +/* Check whether to write this mft record. */ + tni =NULL ; +if (!ntfs_may_write_mft_record (vol, mft_no, + (MFT_RECORD *)(kaddr + ofs), &tni)) { +/* +* The record should not be written. This +* means we need to redirty the page before +* returning. +*/ + page_is_dirty = true; +/* +* Remove the buffers in this mft record from +* the list of buffers to write. +*/ +do { + bhs[i] =NULL ; + }while (++i % bhs_per_rec); +continue ; + } +/* +* The record should be written. If a locked ntfs +* inode was returned, add it to the array of locked +* ntfs inodes. +*/ +if (tni) + locked_nis[nr_locked_nis++] = tni; + } +/* Apply the mst protection fixups. */ + err2 =pre_write_mst_fixup ((NTFS_RECORD *)(kaddr + ofs), + rec_size); +if (unlikely (err2)) { +if (!err || err == -ENOMEM ) + err = -EIO ; +ntfs_error (vol->sb,"Failed to apply mst fixups " +"(inode 0x%lx, attribute type 0x%x, " +"page index 0x%lx, page offset 0x%x)!" +" Unmount and run chkdsk." , vi->i_ino, + ni->type, page->index, ofs); +/* +* Mark all the buffers in this record clean as we do +* not want to write corrupt data to disk. +*/ +do { +clear_buffer_dirty (bhs[i]); + bhs[i] =NULL ; + }while (++i % bhs_per_rec); +continue ; + } + nr_recs++; + } +/* If no records are to be written out, we are done. */ +if (!nr_recs) + goto unm_done; +flush_dcache_page (page); +/* Lock buffers and start synchronous write i/o on them. */ +for (i =0 ; i < nr_bhs; i++) { + tbh = bhs[i]; +if (!tbh) +continue ; +if (!trylock_buffer (tbh)) +BUG (); +/* The buffer dirty state is now irrelevant, just clean it. */ +clear_buffer_dirty (tbh); +BUG_ON (!buffer_uptodate (tbh)); +BUG_ON (!buffer_mapped (tbh)); +get_bh (tbh); + tbh->b_end_io = end_buffer_write_sync; +submit_bh (REQ_OP_WRITE , tbh); + } +/* Synchronize the mft mirror now if not @sync. */ +if (is_mft && !sync) + goto do_mirror; +do_wait: +/* Wait on i/o completion of buffers. */ +for (i =0 ; i < nr_bhs; i++) { + tbh = bhs[i]; +if (!tbh) +continue ; +wait_on_buffer (tbh); +if (unlikely (!buffer_uptodate (tbh))) { +ntfs_error (vol->sb,"I/O error while writing ntfs " +"record buffer (inode 0x%lx, " +"attribute type 0x%x, page index " +"0x%lx, page offset 0x%lx)! Unmount " +"and run chkdsk." , vi->i_ino, ni->type, + page->index,bh_offset (tbh)); +if (!err || err == -ENOMEM ) + err = -EIO ; +/* +* Set the buffer uptodate so the page and buffer +* states do not become out of sync. +*/ +set_buffer_uptodate (tbh); + } + } +/* If @sync, now synchronize the mft mirror. */ +if (is_mft && sync) { +do_mirror: +for (i =0 ; i < nr_bhs; i++) { +unsigned long mft_no; +unsigned int ofs; + +/* +* Skip buffers which are not at the beginning of +* records. +*/ +if (i % bhs_per_rec) +continue ; + tbh = bhs[i]; +/* Skip removed buffers (and hence records). */ +if (!tbh) +continue ; + ofs =bh_offset (tbh); +/* Get the mft record number. */ + mft_no = (((s64 )page->index <<PAGE_SHIFT ) + ofs) + >> rec_size_bits; +if (mft_no < vol->mftmirr_size) +ntfs_sync_mft_mirror (vol, mft_no, + (MFT_RECORD *)(kaddr + ofs), + sync); + } +if (!sync) + goto do_wait; + } +/* Remove the mst protection fixups again. */ +for (i =0 ; i < nr_bhs; i++) { +if (!(i % bhs_per_rec)) { + tbh = bhs[i]; +if (!tbh) +continue ; +post_write_mst_fixup ((NTFS_RECORD *)(kaddr + +bh_offset (tbh))); + } + } +flush_dcache_page (page); +unm_done: +/* Unlock any locked inodes. */ +while (nr_locked_nis-- >0 ) { +ntfs_inode *tni, *base_tni; + + tni = locked_nis[nr_locked_nis]; +/* Get the base inode. */ +mutex_lock (&tni->extent_lock); +if (tni->nr_extents >=0 ) + base_tni = tni; +else { + base_tni = tni->ext.base_ntfs_ino; +BUG_ON (!base_tni); + } +mutex_unlock (&tni->extent_lock); +ntfs_debug ("Unlocking %s inode 0x%lx." , + tni == base_tni ?"base" :"extent" , + tni->mft_no); +mutex_unlock (&tni->mrec_lock); +atomic_dec (&tni->count); +iput (VFS_I (base_tni)); + } +SetPageUptodate (page); +kunmap (page); +done: +if (unlikely (err && err != -ENOMEM )) { +/* +* Set page error if there is only one ntfs record in the page. +* Otherwise we would loose per-record granularity. +*/ +if (ni->itype.index.block_size ==PAGE_SIZE ) +SetPageError (page); +NVolSetErrors (vol); + } +if (page_is_dirty) { +ntfs_debug ("Page still contains one or more dirty ntfs " +"records. Redirtying the page starting at " +"record 0x%lx." , page->index << + (PAGE_SHIFT - rec_size_bits)); +redirty_page_for_writepage (wbc, page); +unlock_page (page); + }else { +/* +* Keep the VM happy. This must be done otherwise the +* radix-tree tag PAGECACHE_TAG_DIRTY remains set even though +* the page is clean. +*/ +BUG_ON (PageWriteback (page)); +set_page_writeback (page); +unlock_page (page); +end_page_writeback (page); + } +if (likely (!err)) +ntfs_debug ("Done." ); +return err; +} + +/** +* ntfs_writepage - write a @page to the backing store +* @page: page cache page to write out +* @wbc: writeback control structure +* +* This is called from the VM when it wants to have a dirty ntfs page cache +* page cleaned. The VM has already locked the page and marked it clean. +* +* For non-resident attributes, ntfs_writepage() writes the @page by calling +* the ntfs version of the generic block_write_full_folio() function, +* ntfs_write_block(), which in turn if necessary creates and writes the +* buffers associated with the page asynchronously. +* +* For resident attributes, OTOH, ntfs_writepage() writes the @page by copying +* the data to the mft record (which at this stage is most likely in memory). +* The mft record is then marked dirty and written out asynchronously via the +* vfs inode dirty code path for the inode the mft record belongs to or via the +* vm page dirty code path for the page the mft record is in. +* +* Based on ntfs_read_folio() and fs/buffer.c::block_write_full_folio(). +* +* Return 0 on success and -errno on error. +*/ +static int ntfs_writepage (struct page *page,struct writeback_control *wbc) +{ +struct folio *folio =page_folio (page); +loff_t i_size; +struct inode *vi = folio->mapping->host; +ntfs_inode *base_ni =NULL , *ni =NTFS_I (vi); +char *addr; +ntfs_attr_search_ctx *ctx =NULL ; +MFT_RECORD *m =NULL ; +u32 attr_len; +int err; + +retry_writepage: +BUG_ON (!folio_test_locked (folio)); + i_size =i_size_read (vi); +/* Is the folio fully outside i_size? (truncate in progress) */ +if (unlikely (folio->index >= (i_size +PAGE_SIZE -1 ) >> +PAGE_SHIFT )) { +/* +* The folio may have dirty, unmapped buffers. Make them +* freeable here, so the page does not leak. +*/ +block_invalidate_folio (folio,0 ,folio_size (folio)); +folio_unlock (folio); +ntfs_debug ("Write outside i_size - truncated?" ); +return 0 ; + } +/* +* Only $DATA attributes can be encrypted and only unnamed $DATA +* attributes can be compressed. Index root can have the flags set but +* this means to create compressed/encrypted files, not that the +* attribute is compressed/encrypted. Note we need to check for +* AT_INDEX_ALLOCATION since this is the type of both directory and +* index inodes. +*/ +if (ni->type !=AT_INDEX_ALLOCATION ) { +/* If file is encrypted, deny access, just like NT4. */ +if (NInoEncrypted (ni)) { +folio_unlock (folio); +BUG_ON (ni->type !=AT_DATA ); +ntfs_debug ("Denying write access to encrypted file." ); +return -EACCES ; + } +/* Compressed data streams are handled in compress.c. */ +if (NInoNonResident (ni) &&NInoCompressed (ni)) { +BUG_ON (ni->type !=AT_DATA ); +BUG_ON (ni->name_len); +// TODO: Implement and replace this with +// return ntfs_write_compressed_block(page); +folio_unlock (folio); +ntfs_error (vi->i_sb,"Writing to compressed files is " +"not supported yet. Sorry." ); +return -EOPNOTSUPP ; + } +// TODO: Implement and remove this check. +if (NInoNonResident (ni) &&NInoSparse (ni)) { +folio_unlock (folio); +ntfs_error (vi->i_sb,"Writing to sparse files is not " +"supported yet. Sorry." ); +return -EOPNOTSUPP ; + } + } +/* NInoNonResident() == NInoIndexAllocPresent() */ +if (NInoNonResident (ni)) { +/* We have to zero every time due to mmap-at-end-of-file. */ +if (folio->index >= (i_size >>PAGE_SHIFT )) { +/* The folio straddles i_size. */ +unsigned int ofs = i_size & (folio_size (folio) -1 ); +folio_zero_segment (folio, ofs,folio_size (folio)); + } +/* Handle mst protected attributes. */ +if (NInoMstProtected (ni)) +return ntfs_write_mst_block (page, wbc); +/* Normal, non-resident data stream. */ +return ntfs_write_block (folio, wbc); + } +/* +* Attribute is resident, implying it is not compressed, encrypted, or +* mst protected. This also means the attribute is smaller than an mft +* record and hence smaller than a folio, so can simply return error on +* any folios with index above 0. Note the attribute can actually be +* marked compressed but if it is resident the actual data is not +* compressed so we are ok to ignore the compressed flag here. +*/ +BUG_ON (folio_buffers (folio)); +BUG_ON (!folio_test_uptodate (folio)); +if (unlikely (folio->index >0 )) { +ntfs_error (vi->i_sb,"BUG()! folio->index (0x%lx) > 0. " +"Aborting write." , folio->index); +BUG_ON (folio_test_writeback (folio)); +folio_start_writeback (folio); +folio_unlock (folio); +folio_end_writeback (folio); +return -EIO ; + } +if (!NInoAttr (ni)) + base_ni = ni; +else + base_ni = ni->ext.base_ntfs_ino; +/* Map, pin, and lock the mft record. */ + m =map_mft_record (base_ni); +if (IS_ERR (m)) { + err =PTR_ERR (m); + m =NULL ; + ctx =NULL ; + goto err_out; + } +/* +* If a parallel write made the attribute non-resident, drop the mft +* record and retry the writepage. +*/ +if (unlikely (NInoNonResident (ni))) { +unmap_mft_record (base_ni); + goto retry_writepage; + } + ctx =ntfs_attr_get_search_ctx (base_ni, m); +if (unlikely (!ctx)) { + err = -ENOMEM ; + goto err_out; + } + err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, +CASE_SENSITIVE ,0 ,NULL ,0 , ctx); +if (unlikely (err)) + goto err_out; +/* +* Keep the VM happy. This must be done otherwise +* PAGECACHE_TAG_DIRTY remains set even though the folio is clean. +*/ +BUG_ON (folio_test_writeback (folio)); +folio_start_writeback (folio); +folio_unlock (folio); + attr_len =le32_to_cpu (ctx->attr->data.resident.value_length); + i_size =i_size_read (vi); +if (unlikely (attr_len > i_size)) { +/* Race with shrinking truncate or a failed truncate. */ + attr_len = i_size; +/* +* If the truncate failed, fix it up now. If a concurrent +* truncate, we do its job, so it does not have to do anything. +*/ + err =ntfs_resident_attr_value_resize (ctx->mrec, ctx->attr, + attr_len); +/* Shrinking cannot fail. */ +BUG_ON (err); + } + addr =kmap_local_folio (folio,0 ); +/* Copy the data from the folio to the mft record. */ +memcpy ((u8 *)ctx->attr + +le16_to_cpu (ctx->attr->data.resident.value_offset), + addr, attr_len); +/* Zero out of bounds area in the page cache folio. */ +memset (addr + attr_len,0 ,folio_size (folio) - attr_len); +kunmap_local (addr); +flush_dcache_folio (folio); +flush_dcache_mft_record_page (ctx->ntfs_ino); +/* We are done with the folio. */ +folio_end_writeback (folio); +/* Finally, mark the mft record dirty, so it gets written back. */ +mark_mft_record_dirty (ctx->ntfs_ino); +ntfs_attr_put_search_ctx (ctx); +unmap_mft_record (base_ni); +return 0 ; +err_out: +if (err == -ENOMEM ) { +ntfs_warning (vi->i_sb,"Error allocating memory. Redirtying " +"page so we try again later." ); +/* +* Put the folio back on mapping->dirty_pages, but leave its +* buffers' dirty state as-is. +*/ +folio_redirty_for_writepage (wbc, folio); + err =0 ; + }else { +ntfs_error (vi->i_sb,"Resident attribute write failed with " +"error %i." , err); +folio_set_error (folio); +NVolSetErrors (ni->vol); + } +folio_unlock (folio); +if (ctx) +ntfs_attr_put_search_ctx (ctx); +if (m) +unmap_mft_record (base_ni); +return err; +} + +#endif /* NTFS_RW */ + +/** +* ntfs_bmap - map logical file block to physical device block +* @mapping: address space mapping to which the block to be mapped belongs +* @block: logical block to map to its physical device block +* +* For regular, non-resident files (i.e. not compressed and not encrypted), map +* the logical @block belonging to the file described by the address space +* mapping @mapping to its physical device block. +* +* The size of the block is equal to the @s_blocksize field of the super block +* of the mounted file system which is guaranteed to be smaller than or equal +* to the cluster size thus the block is guaranteed to fit entirely inside the +* cluster which means we do not need to care how many contiguous bytes are +* available after the beginning of the block. +* +* Return the physical device block if the mapping succeeded or 0 if the block +* is sparse or there was an error. +* +* Note: This is a problem if someone tries to run bmap() on $Boot system file +* as that really is in block zero but there is nothing we can do. bmap() is +* just broken in that respect (just like it cannot distinguish sparse from +* not available or error). +*/ +static sector_t ntfs_bmap (struct address_space *mapping,sector_t block) +{ +s64 ofs, size; +loff_t i_size; +LCN lcn; +unsigned long blocksize, flags; +ntfs_inode *ni =NTFS_I (mapping->host); +ntfs_volume *vol = ni->vol; +unsigned delta; +unsigned char blocksize_bits, cluster_size_shift; + +ntfs_debug ("Entering for mft_no 0x%lx, logical block 0x%llx." , + ni->mft_no, (unsigned long long )block); +if (ni->type !=AT_DATA || !NInoNonResident (ni) ||NInoEncrypted (ni)) { +ntfs_error (vol->sb,"BMAP does not make sense for %s " +"attributes, returning 0." , + (ni->type !=AT_DATA ) ?"non-data" : + (!NInoNonResident (ni) ?"resident" : +"encrypted" )); +return 0 ; + } +/* None of these can happen. */ +BUG_ON (NInoCompressed (ni)); +BUG_ON (NInoMstProtected (ni)); + blocksize = vol->sb->s_blocksize; + blocksize_bits = vol->sb->s_blocksize_bits; + ofs = (s64 )block << blocksize_bits; +read_lock_irqsave (&ni->size_lock, flags); + size = ni->initialized_size; + i_size =i_size_read (VFS_I (ni)); +read_unlock_irqrestore (&ni->size_lock, flags); +/* +* If the offset is outside the initialized size or the block straddles +* the initialized size then pretend it is a hole unless the +* initialized size equals the file size. +*/ +if (unlikely (ofs >= size || (ofs + blocksize > size && size < i_size))) + goto hole; + cluster_size_shift = vol->cluster_size_bits; +down_read (&ni->runlist.lock); + lcn =ntfs_attr_vcn_to_lcn_nolock (ni, ofs >> cluster_size_shift, false); +up_read (&ni->runlist.lock); +if (unlikely (lcn <LCN_HOLE )) { +/* +* Step down to an integer to avoid gcc doing a long long +* comparision in the switch when we know @lcn is between +* LCN_HOLE and LCN_EIO (i.e. -1 to -5). +* +* Otherwise older gcc (at least on some architectures) will +* try to use __cmpdi2() which is of course not available in +* the kernel. +*/ +switch ((int )lcn) { +case LCN_ENOENT : +/* +* If the offset is out of bounds then pretend it is a +* hole. +*/ + goto hole; +case LCN_ENOMEM : +ntfs_error (vol->sb,"Not enough memory to complete " +"mapping for inode 0x%lx. " +"Returning 0." , ni->mft_no); +break ; +default : +ntfs_error (vol->sb,"Failed to complete mapping for " +"inode 0x%lx. Run chkdsk. " +"Returning 0." , ni->mft_no); +break ; + } +return 0 ; + } +if (lcn <0 ) { +/* It is a hole. */ +hole: +ntfs_debug ("Done (returning hole)." ); +return 0 ; + } +/* +* The block is really allocated and fullfils all our criteria. +* Convert the cluster to units of block size and return the result. +*/ + delta = ofs & vol->cluster_size_mask; +if (unlikely (sizeof (block) <sizeof (lcn))) { + block = lcn = ((lcn << cluster_size_shift) + delta) >> + blocksize_bits; +/* If the block number was truncated return 0. */ +if (unlikely (block != lcn)) { +ntfs_error (vol->sb,"Physical block 0x%llx is too " +"large to be returned, returning 0." , + (long long )lcn); +return 0 ; + } + }else + block = ((lcn << cluster_size_shift) + delta) >> + blocksize_bits; +ntfs_debug ("Done (returning block 0x%llx)." , (unsigned long long )lcn); +return block; +} + +/* +* ntfs_normal_aops - address space operations for normal inodes and attributes +* +* Note these are not used for compressed or mst protected inodes and +* attributes. +*/ +const struct address_space_operations ntfs_normal_aops = { + .read_folio = ntfs_read_folio, +#ifdef NTFS_RW + .writepage = ntfs_writepage, + .dirty_folio = block_dirty_folio, +#endif /* NTFS_RW */ + .bmap = ntfs_bmap, + .migrate_folio = buffer_migrate_folio, + .is_partially_uptodate = block_is_partially_uptodate, + .error_remove_folio = generic_error_remove_folio, +}; + +/* +* ntfs_compressed_aops - address space operations for compressed inodes +*/ +const struct address_space_operations ntfs_compressed_aops = { + .read_folio = ntfs_read_folio, +#ifdef NTFS_RW + .writepage = ntfs_writepage, + .dirty_folio = block_dirty_folio, +#endif /* NTFS_RW */ + .migrate_folio = buffer_migrate_folio, + .is_partially_uptodate = block_is_partially_uptodate, + .error_remove_folio = generic_error_remove_folio, +}; + +/* +* ntfs_mst_aops - general address space operations for mst protecteed inodes +* and attributes +*/ +const struct address_space_operations ntfs_mst_aops = { + .read_folio = ntfs_read_folio,/* Fill page with data. */ +#ifdef NTFS_RW + .writepage = ntfs_writepage,/* Write dirty page to disk. */ + .dirty_folio = filemap_dirty_folio, +#endif /* NTFS_RW */ + .migrate_folio = buffer_migrate_folio, + .is_partially_uptodate = block_is_partially_uptodate, + .error_remove_folio = generic_error_remove_folio, +}; + +#ifdef NTFS_RW + +/** +* mark_ntfs_record_dirty - mark an ntfs record dirty +* @page: page containing the ntfs record to mark dirty +* @ofs: byte offset within @page at which the ntfs record begins +* +* Set the buffers and the page in which the ntfs record is located dirty. +* +* The latter also marks the vfs inode the ntfs record belongs to dirty +* (I_DIRTY_PAGES only). +* +* If the page does not have buffers, we create them and set them uptodate. +* The page may not be locked which is why we need to handle the buffers under +* the mapping->i_private_lock. Once the buffers are marked dirty we no longer +* need the lock since try_to_free_buffers() does not free dirty buffers. +*/ +void mark_ntfs_record_dirty (struct page *page,const unsigned int ofs) { +struct address_space *mapping = page->mapping; +ntfs_inode *ni =NTFS_I (mapping->host); +struct buffer_head *bh, *head, *buffers_to_free =NULL ; +unsigned int end, bh_size, bh_ofs; + +BUG_ON (!PageUptodate (page)); + end = ofs + ni->itype.index.block_size; + bh_size =VFS_I (ni)->i_sb->s_blocksize; +spin_lock (&mapping->i_private_lock); +if (unlikely (!page_has_buffers (page))) { +spin_unlock (&mapping->i_private_lock); + bh = head =alloc_page_buffers (page, bh_size, true); +spin_lock (&mapping->i_private_lock); +if (likely (!page_has_buffers (page))) { +struct buffer_head *tail; + +do { +set_buffer_uptodate (bh); + tail = bh; + bh = bh->b_this_page; + }while (bh); + tail->b_this_page = head; +attach_page_private (page, head); + }else + buffers_to_free = bh; + } + bh = head =page_buffers (page); +BUG_ON (!bh); +do { + bh_ofs =bh_offset (bh); +if (bh_ofs + bh_size <= ofs) +continue ; +if (unlikely (bh_ofs >= end)) +break ; +set_buffer_dirty (bh); + }while ((bh = bh->b_this_page) != head); +spin_unlock (&mapping->i_private_lock); +filemap_dirty_folio (mapping,page_folio (page)); +if (unlikely (buffers_to_free)) { +do { + bh = buffers_to_free->b_this_page; +free_buffer_head (buffers_to_free); + buffers_to_free = bh; + }while (buffers_to_free); + } +} + +#endif /* NTFS_RW */
fs/ntfs/aops.h new file +88 -0
88 lines not on this page · raw message
fs/ntfs/attrib.c new file +2624 -0
1,168 lines not on this page · raw message
fs/ntfs/attrib.h new file +102 -0
102 lines not on this page · raw message
fs/ntfs/bitmap.c new file +179 -0
179 lines not on this page · raw message
fs/ntfs/bitmap.h new file +104 -0
104 lines not on this page · raw message
fs/ntfs/collate.c new file +110 -0
110 lines not on this page · raw message
fs/ntfs/compress.c new file +950 -0
950 lines not on this page · raw message
fs/ntfs/debug.c new file +159 -0
159 lines not on this page · raw message
fs/ntfs/debug.h new file +57 -0
57 lines not on this page · raw message
fs/ntfs/dir.c new file +1540 -0
1,540 lines not on this page · raw message
fs/ntfs/endian.h new file +79 -0
79 lines not on this page · raw message
fs/ntfs/file.c new file +1997 -0
1,997 lines not on this page · raw message
fs/ntfs/index.c new file +440 -0
440 lines not on this page · raw message
fs/ntfs/index.h new file +134 -0
134 lines not on this page · raw message
fs/ntfs/inode.c new file +3102 -0
3,102 lines not on this page · raw message
fs/ntfs/inode.h new file +310 -0
310 lines not on this page · raw message
fs/ntfs/layout.h new file +2421 -0
2,421 lines not on this page · raw message
fs/ntfs/lcnalloc.c new file +1000 -0
1,000 lines not on this page · raw message
fs/ntfs/lcnalloc.h new file +131 -0
131 lines not on this page · raw message
fs/ntfs/logfile.c new file +849 -0
849 lines not on this page · raw message
fs/ntfs/logfile.h new file +295 -0
295 lines not on this page · raw message
fs/ntfs/malloc.h new file +77 -0
77 lines not on this page · raw message
fs/ntfs/mft.c new file +2907 -0
2,907 lines not on this page · raw message
fs/ntfs/mft.h new file +110 -0
110 lines not on this page · raw message
fs/ntfs/mst.c new file +189 -0
189 lines not on this page · raw message
fs/ntfs/namei.c new file +392 -0
392 lines not on this page · raw message
fs/ntfs/ntfs.h new file +150 -0
150 lines not on this page · raw message
fs/ntfs/quota.c new file +103 -0
103 lines not on this page · raw message
fs/ntfs/runlist.c new file +1893 -0
1,893 lines not on this page · raw message
fs/ntfs/runlist.h new file +88 -0
88 lines not on this page · raw message
fs/ntfs/super.c new file +3202 -0
3,202 lines not on this page · raw message
fs/ntfs/sysctl.c new file +58 -0
58 lines not on this page · raw message
fs/ntfs/time.h new file +89 -0
89 lines not on this page · raw message
fs/ntfs/types.h new file +55 -0
55 lines not on this page · raw message
fs/ntfs/unistr.c new file +384 -0
384 lines not on this page · raw message
fs/ntfs/upcase.c new file +73 -0
73 lines not on this page · raw message
fs/ntfs/volume.h new file +164 -0
164 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.25.1
Part of the diff is not shown here. View the raw message.
Namjae Jeon
maintainerPATCH v3 2/14 ntfs: update in-memory, on-disk structures and headers
In reply to Namjae JeonThis updates in-memory, on-disk structures, headers and documentation.
--- Documentation/filesystems/index.rst | 1 + Documentation/filesystems/ntfs.rst | 203 +++ fs/ntfs/aops.h | 84 +- fs/ntfs/attrib.h | 181 +- fs/ntfs/attrlist.h | 21 + fs/ntfs/bitmap.h | 21 +- fs/ntfs/collate.h | 23 +- fs/ntfs/debug.h | 14 +- fs/ntfs/dir.h | 23 +- fs/ntfs/ea.h | 25 + fs/ntfs/index.h | 97 +- fs/ntfs/inode.h | 378 +++-- fs/ntfs/iomap.h | 22 + fs/ntfs/layout.h | 2436 +++++++++++++-------------- fs/ntfs/lcnalloc.h | 48 +- fs/ntfs/logfile.h | 461 ++--- fs/ntfs/malloc.h | 33 +- fs/ntfs/mft.h | 74 +- fs/ntfs/ntfs.h | 142 +- fs/ntfs/quota.h | 11 +- fs/ntfs/reparse.h | 15 + fs/ntfs/runlist.h | 105 +- fs/ntfs/sysctl.h | 8 +- fs/ntfs/time.h | 16 +- fs/ntfs/volume.h | 248 ++- include/uapi/linux/ntfs.h | 23 + 26 files changed, 2539 insertions(+), 2174 deletions(-) create mode 100644 Documentation/filesystems/ntfs.rst create mode 100644 fs/ntfs/attrlist.h create mode 100644 fs/ntfs/ea.h create mode 100644 fs/ntfs/iomap.h create mode 100644 fs/ntfs/reparse.h create mode 100644 include/uapi/linux/ntfs.h
Documentation/filesystems/index.rst +1 -0
@@ -98,6 +98,7 @@ Documentation for filesystem implementations. isofs nilfs2 nfs/index + ntfs ntfs3 ocfs2 ocfs2-online-filecheck
Documentation/filesystems/ntfs.rst new file +203 -0
203 lines not on this page · raw message
fs/ntfs/aops.h +10 -74
98 lines not on this page · raw message
fs/ntfs/attrib.h +119 -62
208 lines not on this page · raw message
fs/ntfs/attrlist.h new file +21 -0
@@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* Exports for attribute list attribute handling. +* Originated from Linux-NTFS project. +* +* Copyright (c) 2004 Anton Altaparmakov +* Copyright (c) 2004 Yura Pakhuchiy +* Copyright (c) 2025 LG Electronics Co., Ltd. +*/ + +#ifndef _NTFS_ATTRLIST_H +#define _NTFS_ATTRLIST_H + +#include "attrib.h" + +int ntfs_attrlist_need (struct ntfs_inode *ni); +int ntfs_attrlist_entry_add (struct ntfs_inode *ni,struct attr_record *attr); +int ntfs_attrlist_entry_rm (struct ntfs_attr_search_ctx *ctx); +int ntfs_attrlist_update (struct ntfs_inode *base_ni); + +#endif /* defined _NTFS_ATTRLIST_H */
fs/ntfs/bitmap.h +5 -16
@@ -1,7 +1,7 @@/* SPDX-License-Identifier: GPL-2.0-or-later */ /* -* bitmap.h - Defines for NTFS kernel bitmap handling. Part of the Linux-NTFS -* project. +* Defines for NTFS kernel bitmap handling. Part of the Linux-NTFS +* project. * * Copyright (c) 2004 Anton Altaparmakov */
@@ -9,13 +9,12 @@#ifndef _LINUX_NTFS_BITMAP_H#define _LINUX_NTFS_BITMAP_H -#ifdef NTFS_RW -#include <linux/fs.h> -#include "types.h" +#include "volume.h" -extern int __ntfs_bitmap_set_bits_in_run (struct inode *vi,const s64 start_bit, +int ntfsp_trim_fs (struct ntfs_volume *vol,struct fstrim_range *range); +int __ntfs_bitmap_set_bits_in_run (struct inode *vi,const s64 start_bit,const s64 count,const u8 value,const bool is_rollback);/**
@@ -27,8 +26,6 @@ extern int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,* * Set @count bits starting at bit @start_bit in the bitmap described by the * vfs inode @vi to @value, where @value is either 0 or 1. -* -* Return 0 on success and -errno on error. */ static inline int ntfs_bitmap_set_bits_in_run (struct inode *vi,const s64 start_bit,const s64 count,const u8 value)
@@ -62,8 +59,6 @@ static inline int ntfs_bitmap_set_run(struct inode *vi, const s64 start_bit,* * Clear @count bits starting at bit @start_bit in the bitmap described by the * vfs inode @vi. -* -* Return 0 on success and -errno on error. */ static inline int ntfs_bitmap_clear_run (struct inode *vi,const s64 start_bit,const s64 count)
@@ -77,8 +72,6 @@ static inline int ntfs_bitmap_clear_run(struct inode *vi, const s64 start_bit,* @bit: bit to set * * Set bit @bit in the bitmap described by the vfs inode @vi. -* -* Return 0 on success and -errno on error. */ static inline int ntfs_bitmap_set_bit (struct inode *vi,const s64 bit) {
@@ -91,14 +84,10 @@ static inline int ntfs_bitmap_set_bit(struct inode *vi, const s64 bit)* @bit: bit to clear * * Clear bit @bit in the bitmap described by the vfs inode @vi. -* -* Return 0 on success and -errno on error. */ static inline int ntfs_bitmap_clear_bit (struct inode *vi,const s64 bit) {return ntfs_bitmap_clear_run (vi, bit,1 ); } -#endif /* NTFS_RW */ -#endif /* defined _LINUX_NTFS_BITMAP_H */
fs/ntfs/collate.h +12 -11
@@ -1,26 +1,27 @@/* SPDX-License-Identifier: GPL-2.0-or-later */ /* -* collate.h - Defines for NTFS kernel collation handling. Part of the -* Linux-NTFS project. +* Defines for NTFS kernel collation handling. +* Part of the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov +* +* Part of this file is based on code from the NTFS-3G project. +* and is copyrighted by the respective authors below: +* Copyright (c) 2004 Anton Altaparmakov +* Copyright (c) 2005 Yura Pakhuchiy */ #ifndef _LINUX_NTFS_COLLATE_H#define _LINUX_NTFS_COLLATE_H -#include "types.h" #include "volume.h" -static inline bool ntfs_is_collation_rule_supported (COLLATION_RULE cr) { +static inline bool ntfs_is_collation_rule_supported (__le32 cr) +{int i; -/* -* FIXME: At the moment we only support COLLATION_BINARY and -* COLLATION_NTOFS_ULONG, so we return false for everything else for -* now. -*/ -if (unlikely (cr !=COLLATION_BINARY && cr !=COLLATION_NTOFS_ULONG )) +if (unlikely (cr !=COLLATION_BINARY && cr !=COLLATION_NTOFS_ULONG && + cr !=COLLATION_FILE_NAME ) && cr !=COLLATION_NTOFS_ULONGS )return false; i =le32_to_cpu (cr); if (likely(((i >= 0) && (i <= 0x02)) ||
@@ -29,7 +30,7 @@ static inline bool ntfs_is_collation_rule_supported(COLLATION_RULE cr) {return false; } -extern int ntfs_collate (ntfs_volume *vol,COLLATION_RULE cr, +int ntfs_collate (struct ntfs_volume *vol,__le32 cr,const void *data1,const int data1_len,const void *data2,const int data2_len);
fs/ntfs/debug.h +10 -4
@@ -1,6 +1,6 @@/* SPDX-License-Identifier: GPL-2.0-or-later */ /* -* debug.h - NTFS kernel debug support. Part of the Linux-NTFS project. +* NTFS kernel debug support. Part of the Linux-NTFS project. * * Copyright (c) 2001-2004 Anton Altaparmakov */
@@ -30,7 +30,7 @@ void __ntfs_debug(const char *file, int line, const char *function, #define ntfs_debug(f, a...) \ __ntfs_debug(__FILE__, __LINE__, __func__, f, ##a) -extern void ntfs_debug_dump_runlist (const runlist_element *rl); +void ntfs_debug_dump_runlist (const struct runlist_element *rl);#else /* !DEBUG */
@@ -40,7 +40,11 @@ do { \ no_printk(fmt, ##__VA_ARGS__); \ } while (0) -#define ntfs_debug_dump_runlist (rl) do {} while (0) +#define ntfs_debug_dump_runlist (rl) \ +do { \ + if (0) \ + (void)rl; \ +} while (0)#endif /* !DEBUG */
@@ -50,8 +54,10 @@ void __ntfs_warning(const char *function, const struct super_block *sb, #define ntfs_warning(sb, f, a...) __ntfs_warning(__func__, sb, f, ##a) extern __printf(3, 4) -void __ntfs_error(const char *function, const struct super_block *sb, +void __ntfs_error(const char *function, struct super_block *sb, const char *fmt, ...); #define ntfs_error(sb, f, a...) __ntfs_error(__func__, sb, f, ##a) +void ntfs_handle_error(struct super_block *sb); +#endif /* _LINUX_NTFS_DEBUG_H */
fs/ntfs/dir.h +11 -12
@@ -1,7 +1,7 @@/* SPDX-License-Identifier: GPL-2.0-or-later */ /* -* dir.h - Defines for directory handling in NTFS Linux kernel driver. Part of -* the Linux-NTFS project. +* Defines for directory handling in NTFS Linux kernel driver. +* Part of the Linux-NTFS project. * * Copyright (c) 2002-2004 Anton Altaparmakov */
@@ -9,26 +9,25 @@#ifndef _LINUX_NTFS_DIR_H#define _LINUX_NTFS_DIR_H -#include "layout.h" #include "inode.h" -#include "types.h" /* * ntfs_name is used to return the file name to the caller of * ntfs_lookup_inode_by_name() in order for the caller (namei.c::ntfs_lookup()) * to be able to deal with dcache aliasing issues. */ -typedef struct { -MFT_REF mref; -FILE_NAME_TYPE_FLAGS type; +struct ntfs_name { +u64 mref; +u8 type;u8 len; -ntfschar name[0 ]; -} __attribute__ ((__packed__ ))ntfs_name ; +__le16 name[]; +} __packed;/* The little endian Unicode string $I30 as a global constant. */ -extern ntfschar I30 [5 ]; +extern __le16 I30 [5 ]; -extern MFT_REF ntfs_lookup_inode_by_name (ntfs_inode *dir_ni, -const ntfschar *uname,const int uname_len,ntfs_name **res); +u64 ntfs_lookup_inode_by_name (struct ntfs_inode *dir_ni, +const __le16 *uname,const int uname_len,struct ntfs_name **res); +int ntfs_check_empty_dir (struct ntfs_inode *ni,struct mft_record *ni_mrec);#endif /* _LINUX_NTFS_FS_DIR_H */
fs/ntfs/ea.h new file +25 -0
@@ -0,0 +1,25 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#define NTFS_EA_UID BIT(1) +#define NTFS_EA_GID BIT(2) +#define NTFS_EA_MODE BIT(3) + +extern const struct xattr_handler *const ntfsp_xattr_handlers[]; + +int ntfs_ea_set_wsl_not_symlink (struct ntfs_inode *ni,mode_t mode,dev_t dev); +int ntfs_ea_get_wsl_inode (struct inode *inode,dev_t *rdevp,unsigned int flags); +int ntfs_ea_set_wsl_inode (struct inode *inode,dev_t rdev,__le16 *ea_size, +unsigned int flags); +ssize_t ntfsp_listxattr (struct dentry *dentry,char *buffer,size_t size); + +#ifdef CONFIG_NTFS_FS_POSIX_ACL +struct posix_acl *ntfsp_get_acl (struct mnt_idmap *idmap,struct dentry *dentry, +int type); +int ntfsp_set_acl (struct mnt_idmap *idmap,struct dentry *dentry, +struct posix_acl *acl,int type); +int ntfsp_init_acl (struct mnt_idmap *idmap,struct inode *inode, +struct inode *dir); +#else +#define ntfsp_get_acl NULL +#define ntfsp_set_acl NULL +#endif
fs/ntfs/index.h +45 -52
132 lines not on this page · raw message
fs/ntfs/inode.h +211 -167
508 lines not on this page · raw message
fs/ntfs/iomap.h new file +22 -0
@@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/** +* Copyright (c) 2025 LG Electronics Co., Ltd. +*/ + +#ifndef _LINUX_NTFS_IOMAP_H +#define _LINUX_NTFS_IOMAP_H + +#include <linux/pagemap.h> +#include <linux/iomap.h> + +#include "volume.h" +#include "inode.h" + +extern const struct iomap_ops ntfs_write_iomap_ops; +extern const struct iomap_ops ntfs_read_iomap_ops; +extern const struct iomap_ops ntfs_page_mkwrite_iomap_ops; +extern const struct iomap_ops ntfs_dio_iomap_ops; +extern const struct iomap_writeback_ops ntfs_writeback_ops; +extern const struct iomap_write_ops ntfs_iomap_folio_ops; +extern int ntfs_zero_range (struct inode *inode,loff_t offset,loff_t length,bool bdirect); +#endif /* _LINUX_NTFS_IOMAP_H */
fs/ntfs/layout.h +1153 -1283
1,586 lines not on this page · raw message
fs/ntfs/lcnalloc.h +22 -26
48 lines not on this page · raw message
fs/ntfs/logfile.h +241 -220
461 lines not on this page · raw message
fs/ntfs/mft.h +28 -46
74 lines not on this page · raw message
fs/ntfs/ntfs.h +96 -46
142 lines not on this page · raw message
fs/ntfs/runlist.h +55 -50
105 lines not on this page · raw message
fs/ntfs/volume.h +169 -79
248 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.25.1
Part of the diff is not shown here. View the raw message.
Re: [PATCH v3 02/14] ntfs: update in-memory, on-disk structures and headers
Quoted 7 lines · Namjae Jeon
This updates in-memory, on-disk structures, headers and documentation.
Signed-off-by Namjae Jeon <[email protected]>--- Documentation/filesystems/index.rst | 1 + Documentation/filesystems/ntfs.rst | 203 +++
This does not belong in this patch.
Should have been part of the revert patch.
Thanks
Amir.
Namjae Jeon
maintainerRe: [PATCH v3 02/14] ntfs: update in-memory, on-disk structures and headers
Quoted 5 lines · Amir Goldstein
Quoted 3 lines · Namjae Jeon
This updates in-memory, on-disk structures, headers and documentation.
Quoted 7 lines
Quoted 4 lines
Signed-off-by Namjae Jeon <[email protected]>--- Documentation/filesystems/index.rst | 1 + Documentation/filesystems/ntfs.rst | 203 +++This does not belong in this patch.
Should have been part of the revert patch.
Okay, I will add it to the revert patch.
Thanks!
Quoted 3 lines
Thanks
Amir.
Namjae Jeon
maintainerPATCH v3 3/14 ntfs: update super block operations
In reply to Namjae JeonThis updates the implementation of superblock operations.
--- fs/ntfs/super.c | 2505 ++++++++++++++++++++--------------------------- 1 file changed, 1040 insertions(+), 1465 deletions(-)
fs/ntfs/super.c +1040 -1465
@@ -1,355 +1,324 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* super.c - NTFS kernel super block handling. Part of the Linux-NTFS project. +* NTFS kernel super block handling. Part of the Linux-NTFS project. * * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc. * Copyright (c) 2001,2002 Richard Russon +* Copyright (c) 2025 LG Electronics Co., Ltd. */ -#define pr_fmt (fmt) KBUILD_MODNAME ": " fmt -#include <linux/stddef.h> -#include <linux/init.h> -#include <linux/slab.h> -#include <linux/string.h> -#include <linux/spinlock.h> #include <linux/blkdev.h> /* For bdev_logical_block_size(). */ #include <linux/backing-dev.h> -#include <linux/buffer_head.h> #include <linux/vfs.h> -#include <linux/moduleparam.h> -#include <linux/bitmap.h> +#include <linux/fs_struct.h> +#include <linux/sched/mm.h> +#include <linux/fs_context.h> +#include <linux/fs_parser.h> +#include <uapi/linux/ntfs.h> #include "sysctl.h" #include "logfile.h" #include "quota.h" -#include "usnjrnl.h" -#include "dir.h" -#include "debug.h" #include "index.h" -#include "inode.h" -#include "aops.h" -#include "layout.h" -#include "malloc.h" #include "ntfs.h" - -/* Number of mounted filesystems which have compression enabled. */ -static unsigned long ntfs_nr_compression_users; +#include "ea.h" +#include "volume.h" +#include "malloc.h" /* A global default upcase table and a corresponding reference count. */ -static ntfschar *default_upcase; +static __le16 *default_upcase;static unsigned long ntfs_nr_upcase_users; +static struct workqueue_struct *ntfs_wq; +/* Error constants/strings used in inode.c::ntfs_show_options(). */ -typedef enum { +enum {/* One of these must be present, default is ON_ERRORS_CONTINUE. */ -ON_ERRORS_PANIC =0x01 , -ON_ERRORS_REMOUNT_RO =0x02 , -ON_ERRORS_CONTINUE =0x04 , -/* Optional, can be combined with any of the above. */ -ON_ERRORS_RECOVER =0x10 , -}ON_ERRORS_ACTIONS ; - -const option_t on_errors_arr[] = { - {ON_ERRORS_PANIC ,"panic" }, - {ON_ERRORS_REMOUNT_RO ,"remount-ro" , }, - {ON_ERRORS_CONTINUE ,"continue" , }, - {ON_ERRORS_RECOVER ,"recover" }, - {0 ,NULL } +ON_ERRORS_PANIC =0x01 , +ON_ERRORS_REMOUNT_RO =0x02 , +ON_ERRORS_CONTINUE =0x04 , }; -/** -* simple_getbool - convert input string to a boolean value -* @s: input string to convert -* @setval: where to store the output boolean value -* -* Copied from old ntfs driver (which copied from vfat driver). -* -* "1", "yes", "true", or an empty string are converted to %true. -* "0", "no", and "false" are converted to %false. -* -* Return: %1 if the string is converted or was empty and *setval contains it; -* %0 if the string was not valid. -*/ -static int simple_getbool (char *s,bool *setval) -{ -if (s) { -if (!strcmp (s,"1" ) || !strcmp (s,"yes" ) || !strcmp (s,"true" )) - *setval = true; -else if (!strcmp (s,"0" ) || !strcmp (s,"no" ) || - !strcmp (s,"false" )) - *setval = false; -else -return 0 ; - }else - *setval = true; -return 1 ; -} +static const struct constant_table ntfs_param_enums[] = { + {"panic" ,ON_ERRORS_PANIC }, + {"remount-ro" ,ON_ERRORS_REMOUNT_RO }, + {"continue" ,ON_ERRORS_CONTINUE }, + {} +}; -/** -* parse_options - parse the (re)mount options -* @vol: ntfs volume -* @opt: string containing the (re)mount options -* -* Parse the recognized options in @opt for the ntfs volume described by @vol. -*/ -static bool parse_options (ntfs_volume *vol,char *opt) +enum { + Opt_uid, + Opt_gid, + Opt_umask, + Opt_dmask, + Opt_fmask, + Opt_errors, + Opt_nls, + Opt_charset, + Opt_show_sys_files, + Opt_show_meta, + Opt_case_sensitive, + Opt_disable_sparse, + Opt_sparse, + Opt_mft_zone_multiplier, + Opt_preallocated_size, + Opt_sys_immutable, + Opt_nohidden, + Opt_hide_dot_files, + Opt_check_windows_names, + Opt_acl, + Opt_discard, + Opt_nocase, +}; + +static const struct fs_parameter_spec ntfs_parameters[] = { +fsparam_u32 ("uid" , Opt_uid), +fsparam_u32 ("gid" , Opt_gid), +fsparam_u32oct ("umask" , Opt_umask), +fsparam_u32oct ("dmask" , Opt_dmask), +fsparam_u32oct ("fmask" , Opt_fmask), +fsparam_string ("nls" , Opt_nls), +fsparam_string ("iocharset" , Opt_charset), +fsparam_enum ("errors" , Opt_errors, ntfs_param_enums), +fsparam_flag ("show_sys_files" , Opt_show_sys_files), +fsparam_flag ("showmeta" , Opt_show_meta), +fsparam_flag ("case_sensitive" , Opt_case_sensitive), +fsparam_flag ("disable_sparse" , Opt_disable_sparse), +fsparam_s32 ("mft_zone_multiplier" , Opt_mft_zone_multiplier), +fsparam_u64 ("preallocated_size" , Opt_preallocated_size), +fsparam_flag ("sys_immutable" , Opt_sys_immutable), +fsparam_flag ("nohidden" , Opt_nohidden), +fsparam_flag ("hide_dot_files" , Opt_hide_dot_files), +fsparam_flag ("windows_names" , Opt_check_windows_names), +fsparam_flag ("acl" , Opt_acl), +fsparam_flag ("discard" , Opt_discard), +fsparam_flag ("sparse" , Opt_sparse), +fsparam_flag ("nocase" , Opt_nocase), + {} +}; + +static int ntfs_parse_param (struct fs_context *fc,struct fs_parameter *param) { -char *p, *v, *ov; -static char *utf8 ="utf8" ; -int errors =0 , sloppy =0 ; -kuid_t uid =INVALID_UID ; -kgid_t gid =INVALID_GID ; -umode_t fmask = (umode_t)-1 , dmask = (umode_t)-1 ; -int mft_zone_multiplier =-1 , on_errors =-1 ; -int show_sys_files =-1 , case_sensitive =-1 , disable_sparse =-1 ; -struct nls_table *nls_map =NULL , *old_nls; - -/* I am lazy... (-8 */ -#define NTFS_GETOPT_WITH_DEFAULT (option, variable, default_value) \ - if (!strcmp(p, option)) { \ - if (!v || !*v) \ - variable = default_value; \ - else { \ - variable = simple_strtoul(ov = v, &v, 0); \ - if (*v) \ - goto needs_val; \ - } \ - } -#define NTFS_GETOPT (option, variable) \ - if (!strcmp(p, option)) { \ - if (!v || !*v) \ - goto needs_arg; \ - variable = simple_strtoul(ov = v, &v, 0); \ - if (*v) \ - goto needs_val; \ - } -#define NTFS_GETOPT_UID (option, variable) \ - if (!strcmp(p, option)) { \ - uid_t uid_value; \ - if (!v || !*v) \ - goto needs_arg; \ - uid_value = simple_strtoul(ov = v, &v, 0); \ - if (*v) \ - goto needs_val; \ - variable = make_kuid(current_user_ns(), uid_value); \ - if (!uid_valid(variable)) \ - goto needs_val; \ - } -#define NTFS_GETOPT_GID (option, variable) \ - if (!strcmp(p, option)) { \ - gid_t gid_value; \ - if (!v || !*v) \ - goto needs_arg; \ - gid_value = simple_strtoul(ov = v, &v, 0); \ - if (*v) \ - goto needs_val; \ - variable = make_kgid(current_user_ns(), gid_value); \ - if (!gid_valid(variable)) \ - goto needs_val; \ - } -#define NTFS_GETOPT_OCTAL (option, variable) \ - if (!strcmp(p, option)) { \ - if (!v || !*v) \ - goto needs_arg; \ - variable = simple_strtoul(ov = v, &v, 8); \ - if (*v) \ - goto needs_val; \ - } -#define NTFS_GETOPT_BOOL (option, variable) \ - if (!strcmp(p, option)) { \ - bool val; \ - if (!simple_getbool(v, &val)) \ - goto needs_bool; \ - variable = val; \ - } -#define NTFS_GETOPT_OPTIONS_ARRAY (option, variable, opt_array) \ - if (!strcmp(p, option)) { \ - int _i; \ - if (!v || !*v) \ - goto needs_arg; \ - ov = v; \ - if (variable == -1) \ - variable = 0; \ - for (_i = 0; opt_array[_i].str && *opt_array[_i].str; _i++) \ - if (!strcmp(opt_array[_i].str, v)) { \ - variable |= opt_array[_i].val; \ - break; \ - } \ - if (!opt_array[_i].str || !*opt_array[_i].str) \ - goto needs_val; \ - } -if (!opt || !*opt) - goto no_mount_options; -ntfs_debug ("Entering with mount options string: %s" , opt); -while ((p =strsep (&opt,"," ))) { -if ((v =strchr (p,'=' ))) - *v++ =0 ; - NTFS_GETOPT_UID("uid", uid) - else NTFS_GETOPT_GID("gid", gid) - else NTFS_GETOPT_OCTAL("umask", fmask = dmask) - else NTFS_GETOPT_OCTAL("fmask", fmask) - else NTFS_GETOPT_OCTAL("dmask", dmask) - else NTFS_GETOPT("mft_zone_multiplier", mft_zone_multiplier) - else NTFS_GETOPT_WITH_DEFAULT("sloppy", sloppy, true) - else NTFS_GETOPT_BOOL("show_sys_files", show_sys_files) - else NTFS_GETOPT_BOOL("case_sensitive", case_sensitive) - else NTFS_GETOPT_BOOL("disable_sparse", disable_sparse) - else NTFS_GETOPT_OPTIONS_ARRAY("errors", on_errors, - on_errors_arr) - else if (!strcmp(p, "posix") || !strcmp(p, "show_inodes")) -ntfs_warning (vol->sb,"Ignoring obsolete option %s." , - p); -else if (!strcmp (p,"nls" ) || !strcmp (p,"iocharset" )) { -if (!strcmp (p,"iocharset" )) -ntfs_warning (vol->sb,"Option iocharset is " -"deprecated. Please use " -"option nls=<charsetname> in " -"the future." ); -if (!v || !*v) - goto needs_arg; -use_utf8: - old_nls = nls_map; - nls_map =load_nls (v); -if (!nls_map) { -if (!old_nls) { -ntfs_error (vol->sb,"NLS character set " -"%s not found." , v); -return false; - } -ntfs_error (vol->sb,"NLS character set %s not " -"found. Using previous one %s." , - v, old_nls->charset); - nls_map = old_nls; - }else /* nls_map */ { -unload_nls (old_nls); - } - }else if (!strcmp (p,"utf8" )) { -bool val = false; -ntfs_warning (vol->sb,"Option utf8 is no longer " -"supported, using option nls=utf8. Please " -"use option nls=utf8 in the future and " -"make sure utf8 is compiled either as a " -"module or into the kernel." ); -if (!v || !*v) - val = true; -else if (!simple_getbool (v, &val)) - goto needs_bool; -if (val) { - v = utf8; - goto use_utf8; - } - }else { -ntfs_error (vol->sb,"Unrecognized mount option %s." , p); -if (errors <INT_MAX ) - errors++; - } -#undef NTFS_GETOPT_OPTIONS_ARRAY -#undef NTFS_GETOPT_BOOL -#undef NTFS_GETOPT -#undef NTFS_GETOPT_WITH_DEFAULT - } -no_mount_options: -if (errors && !sloppy) -return false; -if (sloppy) -ntfs_warning (vol->sb,"Sloppy option given. Ignoring " -"unrecognized mount option(s) and continuing." ); -/* Keep this first! */ -if (on_errors !=-1 ) { -if (!on_errors) { -ntfs_error (vol->sb,"Invalid errors option argument " -"or bug in options parser." ); -return false; - } - } -if (nls_map) { -if (vol->nls_map && vol->nls_map != nls_map) { -ntfs_error (vol->sb,"Cannot change NLS character set " -"on remount." ); -return false; - }/* else (!vol->nls_map) */ -ntfs_debug ("Using NLS character set %s." , nls_map->charset); - vol->nls_map = nls_map; - }else /* (!nls_map) */ { +struct ntfs_volume *vol = fc->s_fs_info; +struct fs_parse_result result; +int opt; + + opt =fs_parse (fc, ntfs_parameters, param, &result); +if (opt <0 ) +return opt; + +switch (opt) { +case Opt_uid: + vol->uid =make_kuid (current_user_ns (), result.uint_32); +break ; +case Opt_gid: + vol->gid =make_kgid (current_user_ns (), result.uint_32); +break ; +case Opt_umask: + vol->fmask = vol->dmask = result.uint_32; +break ; +case Opt_dmask: + vol->dmask = result.uint_32; +break ; +case Opt_fmask: + vol->fmask = result.uint_32; +break ; +case Opt_errors: + vol->on_errors = result.uint_32; +break ; +case Opt_nls: +case Opt_charset: +if (vol->nls_map) +unload_nls (vol->nls_map); + vol->nls_map =load_nls (param->string);if (!vol->nls_map) { - vol->nls_map =load_nls_default (); -if (!vol->nls_map) { -ntfs_error (vol->sb,"Failed to load default " -"NLS character set." ); -return false; - } -ntfs_debug ("Using default NLS character set (%s)." , - vol->nls_map->charset); +ntfs_error (vol->sb,"Failed to load NLS table '%s'." , + param->string); +return -EINVAL ; } - } -if (mft_zone_multiplier !=-1 ) { +break ; +case Opt_mft_zone_multiplier:if (vol->mft_zone_multiplier && vol->mft_zone_multiplier != - mft_zone_multiplier) { -ntfs_error (vol->sb,"Cannot change mft_zone_multiplier " -"on remount." ); -return false; - } -if (mft_zone_multiplier <1 || mft_zone_multiplier >4 ) { -ntfs_error (vol->sb,"Invalid mft_zone_multiplier. " -"Using default value, i.e. 1." ); - mft_zone_multiplier =1 ; + result.int_32) { +ntfs_error (vol->sb,"Cannot change mft_zone_multiplier on remount." ); +return -EINVAL ; } - vol->mft_zone_multiplier = mft_zone_multiplier; - } -if (!vol->mft_zone_multiplier) - vol->mft_zone_multiplier =1 ; -if (on_errors !=-1 ) - vol->on_errors = on_errors; -if (!vol->on_errors || vol->on_errors ==ON_ERRORS_RECOVER ) - vol->on_errors |=ON_ERRORS_CONTINUE ; -if (uid_valid (uid)) - vol->uid = uid; -if (gid_valid (gid)) - vol->gid = gid; -if (fmask != (umode_t)-1 ) - vol->fmask = fmask; -if (dmask != (umode_t)-1 ) - vol->dmask = dmask; -if (show_sys_files !=-1 ) { -if (show_sys_files) +if (result.int_32 <1 || result.int_32 >4 ) { +ntfs_error (vol->sb, +"Invalid mft_zone_multiplier. Using default value, i.e. 1." ); + vol->mft_zone_multiplier =1 ; + }else + vol->mft_zone_multiplier = result.int_32; +break ; +case Opt_show_sys_files: +case Opt_show_meta: +if (result.boolean)NVolSetShowSystemFiles (vol);else NVolClearShowSystemFiles (vol); - } -if (case_sensitive !=-1 ) { -if (case_sensitive) +break ; +case Opt_case_sensitive: +if (result.boolean)NVolSetCaseSensitive (vol);else NVolClearCaseSensitive (vol); +break ; +case Opt_nocase: +if (result.boolean) +NVolClearCaseSensitive (vol); +else +NVolSetCaseSensitive (vol); +break ; +case Opt_preallocated_size: + vol->preallocated_size = (loff_t )result.uint_64; +break ; +case Opt_sys_immutable: +if (result.boolean) +NVolSetSysImmutable (vol); +else +NVolClearSysImmutable (vol); +break ; +case Opt_nohidden: +if (result.boolean) +NVolClearShowHiddenFiles (vol); +else +NVolSetShowHiddenFiles (vol); +break ; +case Opt_hide_dot_files: +if (result.boolean) +NVolSetHideDotFiles (vol); +else +NVolClearHideDotFiles (vol); +break ; +case Opt_check_windows_names: +if (result.boolean) +NVolSetCheckWindowsNames (vol); +else +NVolClearCheckWindowsNames (vol); +break ; +case Opt_acl: +if (result.boolean) + fc->sb_flags |=SB_POSIXACL ; +else + fc->sb_flags &= ~SB_POSIXACL ; +break ; +case Opt_discard: +if (result.boolean) +NVolSetDiscard (vol); +else +NVolClearDiscard (vol); +break ; +case Opt_disable_sparse: +if (result.boolean) +NVolSetDisableSparse (vol); +else +NVolClearDisableSparse (vol); +break ; +case Opt_sparse: +break ; +default : +return -EINVAL ; } -if (disable_sparse !=-1 ) { -if (disable_sparse) -NVolClearSparseEnabled (vol); -else { -if (!NVolSparseEnabled (vol) && - vol->major_ver && vol->major_ver <3 ) -ntfs_warning (vol->sb,"Not enabling sparse " -"support due to NTFS volume " -"version %i.%i (need at least " -"version 3.0)." , vol->major_ver, - vol->minor_ver); -else -NVolSetSparseEnabled (vol); + +return 0 ; +} + +static int ntfs_reconfigure (struct fs_context *fc) +{ +struct super_block *sb = fc->root->d_sb; +struct ntfs_volume *vol =NTFS_SB (sb); + +ntfs_debug ("Entering with remount" ); + +sync_filesystem (sb); + +/* +* For the read-write compiled driver, if we are remounting read-write, +* make sure there are no volume errors and that no unsupported volume +* flags are set. Also, empty the logfile journal as it would become +* stale as soon as something is written to the volume and mark the +* volume dirty so that chkdsk is run if the volume is not umounted +* cleanly. Finally, mark the quotas out of date so Windows rescans +* the volume on boot and updates them. +* +* When remounting read-only, mark the volume clean if no volume errors +* have occurred. +*/ +if (sb_rdonly (sb) && !(fc->sb_flags &SB_RDONLY )) { +static const char *es =". Cannot remount read-write." ; + +/* Remounting read-write. */ +if (NVolErrors (vol)) { +ntfs_error (sb,"Volume has errors and is read-only%s" , + es); +return -EROFS ; + } +if (vol->vol_flags &VOLUME_IS_DIRTY ) { +ntfs_error (sb,"Volume is dirty and read-only%s" , es); +return -EROFS ; + } +if (vol->vol_flags &VOLUME_MODIFIED_BY_CHKDSK ) { +ntfs_error (sb,"Volume has been modified by chkdsk and is read-only%s" , es); +return -EROFS ; + } +if (vol->vol_flags &VOLUME_MUST_MOUNT_RO_MASK ) { +ntfs_error (sb,"Volume has unsupported flags set (0x%x) and is read-only%s" , +le16_to_cpu (vol->vol_flags), es); +return -EROFS ; + } +if (vol->logfile_ino && !ntfs_empty_logfile (vol->logfile_ino)) { +ntfs_error (sb,"Failed to empty journal LogFile%s" , + es); +NVolSetErrors (vol); +return -EROFS ; + } +if (!ntfs_mark_quotas_out_of_date (vol)) { +ntfs_error (sb,"Failed to mark quotas out of date%s" , + es); +NVolSetErrors (vol); +return -EROFS ; + } + }else if (!sb_rdonly (sb) && (fc->sb_flags &SB_RDONLY )) { +/* Remounting read-only. */ +if (!NVolErrors (vol)) { +if (ntfs_clear_volume_flags (vol,VOLUME_IS_DIRTY )) +ntfs_warning (sb, +"Failed to clear dirty bit in volume information flags. Run chkdsk." ); } } -return true; -needs_arg: -ntfs_error (vol->sb,"The %s option requires an argument." , p); -return false; -needs_bool: -ntfs_error (vol->sb,"The %s option requires a boolean argument." , p); -return false; -needs_val: -ntfs_error (vol->sb,"Invalid %s option argument: %s" , p, ov); -return false; + +ntfs_debug ("Done." ); +return 0 ; } -#ifdef NTFS_RW +const struct option_t on_errors_arr[] = { + {ON_ERRORS_PANIC ,"panic" }, + {ON_ERRORS_REMOUNT_RO ,"remount-ro" , }, + {ON_ERRORS_CONTINUE ,"continue" , }, + {0 ,NULL } +}; + +void ntfs_handle_error (struct super_block *sb) +{ +struct ntfs_volume *vol =NTFS_SB (sb); + +if (sb_rdonly (sb)) +return ; + +if (vol->on_errors ==ON_ERRORS_REMOUNT_RO ) { + sb->s_flags |=SB_RDONLY ; +pr_crit ("(device %s): Filesystem has been set read-only\n" , + sb->s_id); + }else if (vol->on_errors ==ON_ERRORS_PANIC ) { +panic ("ntfs: (device %s): panic from previous error\n" , + sb->s_id); + }else if (vol->on_errors ==ON_ERRORS_CONTINUE ) { +if (errseq_check (&sb->s_wb_err, vol->wb_err) == -ENODEV ) { +NVolSetShutdown (vol); + vol->wb_err = sb->s_wb_err; + } + } +}/** * ntfs_write_volume_flags - write new flags to the volume information flags
@@ -366,48 +335,43 @@ static bool parse_options(ntfs_volume *vol, char *opt)* * Return 0 on success and -errno on error. */ -static int ntfs_write_volume_flags (ntfs_volume *vol,const VOLUME_FLAGS flags) +static int ntfs_write_volume_flags (struct ntfs_volume *vol,const __le16 flags) { -ntfs_inode *ni =NTFS_I (vol->vol_ino); -MFT_RECORD *m; -VOLUME_INFORMATION *vi; -ntfs_attr_search_ctx *ctx; +struct ntfs_inode *ni =NTFS_I (vol->vol_ino); +struct volume_information *vi; +struct ntfs_attr_search_ctx *ctx;int err;ntfs_debug ("Entering, old flags = 0x%x, new flags = 0x%x." ,le16_to_cpu (vol->vol_flags),le16_to_cpu (flags)); +mutex_lock (&ni->mrec_lock);if (vol->vol_flags == flags) goto done; -BUG_ON (!ni); - m =map_mft_record (ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); - goto err_out; - } - ctx =ntfs_attr_get_search_ctx (ni, m); + + ctx =ntfs_attr_get_search_ctx (ni,NULL );if (!ctx) { err = -ENOMEM ; goto put_unm_err_out; } + err =ntfs_attr_lookup (AT_VOLUME_INFORMATION ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx);if (err) goto put_unm_err_out; - vi = (VOLUME_INFORMATION *)((u8 *)ctx->attr + + + vi = (struct volume_information *)((u8 *)ctx->attr +le16_to_cpu (ctx->attr->data.resident.value_offset)); vol->vol_flags = vi->flags = flags; -flush_dcache_mft_record_page (ctx->ntfs_ino);mark_mft_record_dirty (ctx->ntfs_ino);ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (ni); done: +mutex_unlock (&ni->mrec_lock);ntfs_debug ("Done." );return 0 ; put_unm_err_out:if (ctx)ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (ni); -err_out: +mutex_unlock (&ni->mrec_lock);ntfs_error (vol->sb,"Failed with error code %i." , -err);return err; }
@@ -421,7 +385,7 @@ static int ntfs_write_volume_flags(ntfs_volume *vol, const VOLUME_FLAGS flags)* * Return 0 on success and -errno on error. */ -static inline int ntfs_set_volume_flags (ntfs_volume *vol,VOLUME_FLAGS flags) +int ntfs_set_volume_flags (struct ntfs_volume *vol,__le16 flags) { flags &=VOLUME_FLAGS_MASK ;return ntfs_write_volume_flags (vol, vol->vol_flags | flags);
@@ -436,130 +400,62 @@ static inline int ntfs_set_volume_flags(ntfs_volume *vol, VOLUME_FLAGS flags)* * Return 0 on success and -errno on error. */ -static inline int ntfs_clear_volume_flags (ntfs_volume *vol,VOLUME_FLAGS flags) +int ntfs_clear_volume_flags (struct ntfs_volume *vol,__le16 flags) { flags &=VOLUME_FLAGS_MASK ; flags = vol->vol_flags &cpu_to_le16 (~le16_to_cpu (flags));return ntfs_write_volume_flags (vol, flags); } -#endif /* NTFS_RW */ - -/** -* ntfs_remount - change the mount options of a mounted ntfs filesystem -* @sb: superblock of mounted ntfs filesystem -* @flags: remount flags -* @opt: remount options string -* -* Change the mount options of an already mounted ntfs filesystem. -* -* NOTE: The VFS sets the @sb->s_flags remount flags to @flags after -* ntfs_remount() returns successfully (i.e. returns 0). Otherwise, -* @sb->s_flags are not changed. -*/ -static int ntfs_remount (struct super_block *sb,int *flags,char *opt) +int ntfs_write_volume_label (struct ntfs_volume *vol,char *label) { -ntfs_volume *vol =NTFS_SB (sb); - -ntfs_debug ("Entering with remount options string: %s" , opt); - -sync_filesystem (sb); - -#ifndef NTFS_RW -/* For read-only compiled driver, enforce read-only flag. */ - *flags |=SB_RDONLY ; -#else /* NTFS_RW */ -/* -* For the read-write compiled driver, if we are remounting read-write, -* make sure there are no volume errors and that no unsupported volume -* flags are set. Also, empty the logfile journal as it would become -* stale as soon as something is written to the volume and mark the -* volume dirty so that chkdsk is run if the volume is not umounted -* cleanly. Finally, mark the quotas out of date so Windows rescans -* the volume on boot and updates them. -* -* When remounting read-only, mark the volume clean if no volume errors -* have occurred. -*/ -if (sb_rdonly (sb) && !(*flags &SB_RDONLY )) { -static const char *es =". Cannot remount read-write." ; +struct ntfs_inode *vol_ni =NTFS_I (vol->vol_ino); +struct ntfs_attr_search_ctx *ctx; +__le16 *uname; +int uname_len, ret; + + uname_len =ntfs_nlstoucs (vol, label,strlen (label), + &uname,FSLABEL_MAX ); +if (uname_len <0 ) { +ntfs_error (vol->sb, +"Failed to convert volume label '%s' to Unicode." , + label); +return uname_len; + } + +if (uname_len >NTFS_MAX_LABEL_LEN ) { +ntfs_error (vol->sb, +"Volume label is too long (max %d characters)." , +NTFS_MAX_LABEL_LEN ); +kvfree (uname); +return -EINVAL ; + } -/* Remounting read-write. */ -if (NVolErrors (vol)) { -ntfs_error (sb,"Volume has errors and is read-only%s" , - es); -return -EROFS ; - } -if (vol->vol_flags &VOLUME_IS_DIRTY ) { -ntfs_error (sb,"Volume is dirty and read-only%s" , es); -return -EROFS ; - } -if (vol->vol_flags &VOLUME_MODIFIED_BY_CHKDSK ) { -ntfs_error (sb,"Volume has been modified by chkdsk " -"and is read-only%s" , es); -return -EROFS ; - } -if (vol->vol_flags &VOLUME_MUST_MOUNT_RO_MASK ) { -ntfs_error (sb,"Volume has unsupported flags set " -"(0x%x) and is read-only%s" , - (unsigned )le16_to_cpu (vol->vol_flags), - es); -return -EROFS ; - } -if (ntfs_set_volume_flags (vol,VOLUME_IS_DIRTY )) { -ntfs_error (sb,"Failed to set dirty bit in volume " -"information flags%s" , es); -return -EROFS ; - } -#if 0 -// TODO: Enable this code once we start modifying anything that -// is different between NTFS 1.2 and 3.x... -/* Set NT4 compatibility flag on newer NTFS version volumes. */ -if ((vol->major_ver >1 )) { -if (ntfs_set_volume_flags (vol,VOLUME_MOUNTED_ON_NT4 )) { -ntfs_error (sb,"Failed to set NT4 " -"compatibility flag%s" , es); -NVolSetErrors (vol); -return -EROFS ; - } - } -#endif -if (!ntfs_empty_logfile (vol->logfile_ino)) { -ntfs_error (sb,"Failed to empty journal $LogFile%s" , - es); -NVolSetErrors (vol); -return -EROFS ; - } -if (!ntfs_mark_quotas_out_of_date (vol)) { -ntfs_error (sb,"Failed to mark quotas out of date%s" , - es); -NVolSetErrors (vol); -return -EROFS ; - } -if (!ntfs_stamp_usnjrnl (vol)) { -ntfs_error (sb,"Failed to stamp transaction log " -"($UsnJrnl)%s" , es); -NVolSetErrors (vol); -return -EROFS ; - } - }else if (!sb_rdonly (sb) && (*flags &SB_RDONLY )) { -/* Remounting read-only. */ -if (!NVolErrors (vol)) { -if (ntfs_clear_volume_flags (vol,VOLUME_IS_DIRTY )) -ntfs_warning (sb,"Failed to clear dirty bit " -"in volume information " -"flags. Run chkdsk." ); - } +mutex_lock (&vol_ni->mrec_lock); + ctx =ntfs_attr_get_search_ctx (vol_ni,NULL ); +if (!ctx) { + ret = -ENOMEM ; + goto out; } -#endif /* NTFS_RW */ -// TODO: Deal with *flags. +if (!ntfs_attr_lookup (AT_VOLUME_NAME ,NULL ,0 ,0 ,0 ,NULL ,0 , + ctx)) +ntfs_attr_record_rm (ctx); +ntfs_attr_put_search_ctx (ctx); -if (!parse_options (vol, opt)) -return -EINVAL ; + ret =ntfs_resident_attr_record_add (vol_ni,AT_VOLUME_NAME ,AT_UNNAMED ,0 , + (u8 *)uname, uname_len *sizeof (__le16),0 ); +out: +mutex_unlock (&vol_ni->mrec_lock); +kvfree (uname); +mark_inode_dirty_sync (vol->vol_ino); -ntfs_debug ("Done." ); -return 0 ; +if (ret >=0 ) { +kfree (vol->volume_label); + vol->volume_label =kstrdup (label,GFP_KERNEL ); + ret =0 ; + } +return ret; }/**
@@ -575,7 +471,7 @@ static int ntfs_remount(struct super_block *sb, int *flags, char *opt)* is 'true'. */ static bool is_boot_sector_ntfs (const struct super_block *sb, -const NTFS_BOOT_SECTOR *b,const bool silent) +const struct ntfs_boot_sector *b,const bool silent) {/* * Check that checksum == sum of u32 values from b to the checksum
@@ -584,11 +480,11 @@ static bool is_boot_sector_ntfs(const struct super_block *sb,* ignoring the checksum which leaves the checksum out-of-date. We * report a warning if this is the case. */ -if ((void *)b < (void *)&b->checksum && b->checksum && !silent) { -le32 *u; +if ((void *)b < (void *)&b->checksum && b->checksum && !silent) { +__le32 *u;u32 i; -for (i =0 , u = (le32 *)b; u < (le32 *)(&b->checksum); ++u) +for (i =0 , u = (__le32 *)b; u < (__le32 *)(&b->checksum); ++u) i +=le32_to_cpup (u);if (le32_to_cpu (b->checksum) != i)ntfs_warning (sb,"Invalid boot sector checksum." );
@@ -598,19 +494,16 @@ static bool is_boot_sector_ntfs(const struct super_block *sb, goto not_ntfs;/* Check bytes per sector value is between 256 and 4096. */ if (le16_to_cpu (b->bpb.bytes_per_sector) <0x100 || -le16_to_cpu (b->bpb.bytes_per_sector) >0x1000 ) - goto not_ntfs; -/* Check sectors per cluster value is valid. */ -switch (b->bpb.sectors_per_cluster) { -case 1 :case 2 :case 4 :case 8 :case 16 :case 32 :case 64 :case 128 : -break ; -default : +le16_to_cpu (b->bpb.bytes_per_sector) >0x1000 ) goto not_ntfs; - } -/* Check the cluster size is not above the maximum (64kiB). */ -if ((u32 )le16_to_cpu (b->bpb.bytes_per_sector) * - b->bpb.sectors_per_cluster >NTFS_MAX_CLUSTER_SIZE ) +/* +* Check sectors per cluster value is valid and the cluster size +* is not above the maximum (2MB). +*/ +if (b->bpb.sectors_per_cluster >0x80 && + b->bpb.sectors_per_cluster <0xf4 ) goto not_ntfs; +/* Check reserved/unused fields are really zero. */ if (le16_to_cpu(b->bpb.reserved_sectors) || le16_to_cpu(b->bpb.root_entries) ||
@@ -653,100 +546,33 @@ static bool is_boot_sector_ntfs(const struct super_block *sb,* @sb: super block of device to read the boot sector from * @silent: if true, suppress all output * -* Reads the boot sector from the device and validates it. If that fails, tries -* to read the backup boot sector, first from the end of the device a-la NT4 and -* later and then from the middle of the device a-la NT3.51 and before. -* -* If a valid boot sector is found but it is not the primary boot sector, we -* repair the primary boot sector silently (unless the device is read-only or -* the primary boot sector is not accessible). -* -* NOTE: To call this function, @sb must have the fields s_dev, the ntfs super -* block (u.ntfs_sb), nr_blocks and the device flags (s_flags) initialized -* to their respective values. -* -* Return the unlocked buffer head containing the boot sector or NULL on error. +* Reads the boot sector from the device and validates it. */ -static struct buffer_head *read_ntfs_boot_sector (struct super_block *sb, +static char *read_ntfs_boot_sector (struct super_block *sb,const int silent) { -const char *read_err_str ="Unable to read %s boot sector." ; -struct buffer_head *bh_primary, *bh_backup; -sector_t nr_blocks =NTFS_SB (sb)->nr_blocks; - -/* Try to read primary boot sector. */ -if ((bh_primary =sb_bread (sb,0 ))) { -if (is_boot_sector_ntfs (sb, (NTFS_BOOT_SECTOR *) - bh_primary->b_data, silent)) -return bh_primary; -if (!silent) -ntfs_error (sb,"Primary boot sector is invalid." ); - }else if (!silent) -ntfs_error (sb, read_err_str,"primary" ); -if (!(NTFS_SB (sb)->on_errors &ON_ERRORS_RECOVER )) { -if (bh_primary) -brelse (bh_primary); +char *boot_sector; + + boot_sector =ntfs_malloc_nofs (PAGE_SIZE ); +if (!boot_sector) +return NULL ; + +if (ntfs_dev_read (sb, boot_sector,0 ,PAGE_SIZE )) {if (!silent) -ntfs_error (sb,"Mount option errors=recover not used. " -"Aborting without trying to recover." ); +ntfs_error (sb,"Unable to read primary boot sector." ); +kfree (boot_sector);return NULL ; } -/* Try to read NT4+ backup boot sector. */ -if ((bh_backup =sb_bread (sb, nr_blocks -1 ))) { -if (is_boot_sector_ntfs (sb, (NTFS_BOOT_SECTOR *) - bh_backup->b_data, silent)) - goto hotfix_primary_boot_sector; -brelse (bh_backup); - }else if (!silent) -ntfs_error (sb, read_err_str,"backup" ); -/* Try to read NT3.51- backup boot sector. */ -if ((bh_backup =sb_bread (sb, nr_blocks >>1 ))) { -if (is_boot_sector_ntfs (sb, (NTFS_BOOT_SECTOR *) - bh_backup->b_data, silent)) - goto hotfix_primary_boot_sector; + +if (!is_boot_sector_ntfs (sb, (struct ntfs_boot_sector *)boot_sector, + silent)) {if (!silent) -ntfs_error (sb,"Could not find a valid backup boot " -"sector." ); -brelse (bh_backup); - }else if (!silent) -ntfs_error (sb, read_err_str,"backup" ); -/* We failed. Cleanup and return. */ -if (bh_primary) -brelse (bh_primary); -return NULL ; -hotfix_primary_boot_sector: -if (bh_primary) { -/* -* If we managed to read sector zero and the volume is not -* read-only, copy the found, valid backup boot sector to the -* primary boot sector. Note we only copy the actual boot -* sector structure, not the actual whole device sector as that -* may be bigger and would potentially damage the $Boot system -* file (FIXME: Would be nice to know if the backup boot sector -* on a large sector device contains the whole boot loader or -* just the first 512 bytes). -*/ -if (!sb_rdonly (sb)) { -ntfs_warning (sb,"Hot-fix: Recovering invalid primary " -"boot sector from backup copy." ); -memcpy (bh_primary->b_data, bh_backup->b_data, -NTFS_BLOCK_SIZE ); -mark_buffer_dirty (bh_primary); -sync_dirty_buffer (bh_primary); -if (buffer_uptodate (bh_primary)) { -brelse (bh_backup); -return bh_primary; - } -ntfs_error (sb,"Hot-fix: Device write error while " -"recovering primary boot sector." ); - }else { -ntfs_warning (sb,"Hot-fix: Recovery of primary boot " -"sector failed: Read-only mount." ); - } -brelse (bh_primary); +ntfs_error (sb,"Primary boot sector is invalid." ); +kfree (boot_sector); +return NULL ; } -ntfs_warning (sb,"Using backup boot sector." ); -return bh_backup; + +return boot_sector; }/**
@@ -757,9 +583,10 @@ static struct buffer_head *read_ntfs_boot_sector(struct super_block *sb,* Parse the ntfs boot sector @b and store all imporant information therein in * the ntfs super block @vol. Return 'true' on success and 'false' on error. */ -static bool parse_ntfs_boot_sector (ntfs_volume *vol,const NTFS_BOOT_SECTOR *b) +static bool parse_ntfs_boot_sector (struct ntfs_volume *vol, +const struct ntfs_boot_sector *b) { -unsigned int sectors_per_cluster_bits, nr_hidden_sects; +unsigned int sectors_per_cluster, sectors_per_cluster_bits, nr_hidden_sects;int clusters_per_mft_record, clusters_per_index_record;s64 ll;
@@ -770,14 +597,18 @@ static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)ntfs_debug ("vol->sector_size_bits = %i (0x%x)" , vol->sector_size_bits, vol->sector_size_bits);if (vol->sector_size < vol->sb->s_blocksize) { -ntfs_error (vol->sb,"Sector size (%i) is smaller than the " -"device block size (%lu). This is not " -"supported. Sorry." , vol->sector_size, - vol->sb->s_blocksize); +ntfs_error (vol->sb, +"Sector size (%i) is smaller than the device block size (%lu). This is not supported." , + vol->sector_size, vol->sb->s_blocksize);return false; } + +if (b->bpb.sectors_per_cluster >=0xf4 ) + sectors_per_cluster =1U << -(s8 )b->bpb.sectors_per_cluster; +else + sectors_per_cluster = b->bpb.sectors_per_cluster;ntfs_debug ("sectors_per_cluster = 0x%x" , b->bpb.sectors_per_cluster); - sectors_per_cluster_bits =ffs (b->bpb.sectors_per_cluster) -1 ; + sectors_per_cluster_bits =ffs (sectors_per_cluster) -1 ;ntfs_debug ("sectors_per_cluster_bits = 0x%x" , sectors_per_cluster_bits); nr_hidden_sects =le32_to_cpu (b->bpb.hidden_sectors);
@@ -790,9 +621,9 @@ static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)ntfs_debug ("vol->cluster_size_mask = 0x%x" , vol->cluster_size_mask);ntfs_debug ("vol->cluster_size_bits = %i" , vol->cluster_size_bits);if (vol->cluster_size < vol->sector_size) { -ntfs_error (vol->sb,"Cluster size (%i) is smaller than the " -"sector size (%i). This is not supported. " -"Sorry." , vol->cluster_size, vol->sector_size); +ntfs_error (vol->sb, +"Cluster size (%i) is smaller than the sector size (%i). This is not supported." , + vol->cluster_size, vol->sector_size);return false; } clusters_per_mft_record = b->clusters_per_mft_record;
@@ -821,19 +652,15 @@ static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)* we store $MFT/$DATA, the table of mft records in the page cache. */ if (vol->mft_record_size >PAGE_SIZE ) { -ntfs_error (vol->sb,"Mft record size (%i) exceeds the " -"PAGE_SIZE on your system (%lu). " -"This is not supported. Sorry." , - vol->mft_record_size,PAGE_SIZE ); +ntfs_error (vol->sb, +"Mft record size (%i) exceeds the PAGE_SIZE on your system (%lu). This is not supported." , + vol->mft_record_size,PAGE_SIZE );return false; }/* We cannot support mft record sizes below the sector size. */ if (vol->mft_record_size < vol->sector_size) { -ntfs_error (vol->sb,"Mft record size (%i) is smaller than the " -"sector size (%i). This is not supported. " -"Sorry." , vol->mft_record_size, - vol->sector_size); -return false; +ntfs_warning (vol->sb,"Mft record size (%i) is smaller than the sector size (%i)." , + vol->mft_record_size, vol->sector_size); } clusters_per_index_record = b->clusters_per_index_record; ntfs_debug("clusters_per_index_record = %i (0x%x)",
@@ -860,10 +687,9 @@ static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b) vol->index_record_size_bits);/* We cannot support index record sizes below the sector size. */ if (vol->index_record_size < vol->sector_size) { -ntfs_error (vol->sb,"Index record size (%i) is smaller than " -"the sector size (%i). This is not " -"supported. Sorry." , vol->index_record_size, - vol->sector_size); +ntfs_error (vol->sb, +"Index record size (%i) is smaller than the sector size (%i). This is not supported." , + vol->index_record_size, vol->sector_size);return false; }/*
@@ -871,47 +697,29 @@ static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)* Windows currently only uses 32 bits to save the clusters so we do * the same as it is much faster on 32-bit CPUs. */ - ll =sle64_to_cpu (b->number_of_sectors) >> sectors_per_cluster_bits; + ll =le64_to_cpu (b->number_of_sectors) >> sectors_per_cluster_bits;if ((u64 )ll >=1ULL <<32 ) { -ntfs_error (vol->sb,"Cannot handle 64-bit clusters. Sorry." ); +ntfs_error (vol->sb,"Cannot handle 64-bit clusters." );return false; } vol->nr_clusters = ll; -ntfs_debug ("vol->nr_clusters = 0x%llx" , (long long )vol->nr_clusters); -/* -* On an architecture where unsigned long is 32-bits, we restrict the -* volume size to 2TiB (2^41). On a 64-bit architecture, the compiler -* will hopefully optimize the whole check away. -*/ -if (sizeof (unsigned long ) <8 ) { -if ((ll << vol->cluster_size_bits) >= (1ULL <<41 )) { -ntfs_error (vol->sb,"Volume size (%lluTiB) is too " -"large for this architecture. " -"Maximum supported is 2TiB. Sorry." , - (unsigned long long )ll >> (40 - - vol->cluster_size_bits)); -return false; - } - } - ll =sle64_to_cpu (b->mft_lcn); +ntfs_debug ("vol->nr_clusters = 0x%llx" , vol->nr_clusters); + ll =le64_to_cpu (b->mft_lcn);if (ll >= vol->nr_clusters) { -ntfs_error (vol->sb,"MFT LCN (%lli, 0x%llx) is beyond end of " -"volume. Weird." , (unsigned long long )ll, - (unsigned long long )ll); +ntfs_error (vol->sb,"MFT LCN (%lli, 0x%llx) is beyond end of volume. Weird." , + ll, ll);return false; } vol->mft_lcn = ll; -ntfs_debug ("vol->mft_lcn = 0x%llx" , (long long )vol->mft_lcn); - ll =sle64_to_cpu (b->mftmirr_lcn); +ntfs_debug ("vol->mft_lcn = 0x%llx" , vol->mft_lcn); + ll =le64_to_cpu (b->mftmirr_lcn);if (ll >= vol->nr_clusters) { -ntfs_error (vol->sb,"MFTMirr LCN (%lli, 0x%llx) is beyond end " -"of volume. Weird." , (unsigned long long )ll, - (unsigned long long )ll); +ntfs_error (vol->sb,"MFTMirr LCN (%lli, 0x%llx) is beyond end of volume. Weird." , + ll, ll);return false; } vol->mftmirr_lcn = ll; -ntfs_debug ("vol->mftmirr_lcn = 0x%llx" , (long long )vol->mftmirr_lcn); -#ifdef NTFS_RW +ntfs_debug ("vol->mftmirr_lcn = 0x%llx" , vol->mftmirr_lcn);/* * Work out the size of the mft mirror in number of mft records. If the * cluster size is less than or equal to the size taken by four mft
@@ -926,10 +734,27 @@ static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b) vol->mftmirr_size = vol->cluster_size >> vol->mft_record_size_bits;ntfs_debug ("vol->mftmirr_size = %i" , vol->mftmirr_size); -#endif /* NTFS_RW */ vol->serial_no =le64_to_cpu (b->volume_serial_number); -ntfs_debug ("vol->serial_no = 0x%llx" , - (unsigned long long )vol->serial_no); +ntfs_debug ("vol->serial_no = 0x%llx" , vol->serial_no); + + vol->sparse_compression_unit =4 ; +if (vol->cluster_size >4096 ) { +switch (vol->cluster_size) { +case 65536 : + vol->sparse_compression_unit =0 ; +break ; +case 32768 : + vol->sparse_compression_unit =1 ; +break ; +case 16384 : + vol->sparse_compression_unit =2 ; +break ; +case 8192 : + vol->sparse_compression_unit =3 ; +break ; + } + } +return true; }
@@ -939,15 +764,12 @@ static bool parse_ntfs_boot_sector(ntfs_volume *vol, const NTFS_BOOT_SECTOR *b)* * Setup the cluster (lcn) and mft allocators to the starting values. */ -static void ntfs_setup_allocators (ntfs_volume *vol) +static void ntfs_setup_allocators (struct ntfs_volume *vol) { -#ifdef NTFS_RW -LCN mft_zone_size, mft_lcn; -#endif /* NTFS_RW */ +s64 mft_zone_size, mft_lcn;ntfs_debug ("vol->mft_zone_multiplier = 0x%x" , vol->mft_zone_multiplier); -#ifdef NTFS_RW /* Determine the size of the MFT zone. */ mft_zone_size = vol->nr_clusters;switch (vol->mft_zone_multiplier) {/* % of volume size in clusters */
@@ -968,8 +790,7 @@ static void ntfs_setup_allocators(ntfs_volume *vol) }/* Setup the mft zone. */ vol->mft_zone_start = vol->mft_zone_pos = vol->mft_lcn; -ntfs_debug ("vol->mft_zone_pos = 0x%llx" , - (unsigned long long )vol->mft_zone_pos); +ntfs_debug ("vol->mft_zone_pos = 0x%llx" , vol->mft_zone_pos);/* * Calculate the mft_lcn for an unmodified NTFS volume (see mkntfs * source) and if the actual mft_lcn is in the expected place or even
@@ -979,14 +800,13 @@ static void ntfs_setup_allocators(ntfs_volume *vol)* On non-standard volumes we do not protect it as the overhead would * be higher than the speed increase we would get by doing it. */ - mft_lcn = (8192 +2 * vol->cluster_size -1 ) / vol->cluster_size; + mft_lcn =NTFS_B_TO_CLU (vol,8192 +2 * vol->cluster_size -1 );if (mft_lcn * vol->cluster_size <16 *1024 ) - mft_lcn = (16 *1024 + vol->cluster_size -1 ) / - vol->cluster_size; + mft_lcn = (16 *1024 + vol->cluster_size -1 ) >> + vol->cluster_size_bits;if (vol->mft_zone_start <= mft_lcn) vol->mft_zone_start =0 ; -ntfs_debug ("vol->mft_zone_start = 0x%llx" , - (unsigned long long )vol->mft_zone_start); +ntfs_debug ("vol->mft_zone_start = 0x%llx" , vol->mft_zone_start);/* * Need to cap the mft zone on non-standard volumes so that it does * not point outside the boundaries of the volume. We do this by
@@ -997,48 +817,47 @@ static void ntfs_setup_allocators(ntfs_volume *vol) mft_zone_size >>=1 ; vol->mft_zone_end = vol->mft_lcn + mft_zone_size; } -ntfs_debug ("vol->mft_zone_end = 0x%llx" , - (unsigned long long )vol->mft_zone_end); +ntfs_debug ("vol->mft_zone_end = 0x%llx" , vol->mft_zone_end);/* * Set the current position within each data zone to the start of the * respective zone. */ vol->data1_zone_pos = vol->mft_zone_end; -ntfs_debug ("vol->data1_zone_pos = 0x%llx" , - (unsigned long long )vol->data1_zone_pos); +ntfs_debug ("vol->data1_zone_pos = 0x%llx" , vol->data1_zone_pos); vol->data2_zone_pos =0 ; -ntfs_debug ("vol->data2_zone_pos = 0x%llx" , - (unsigned long long )vol->data2_zone_pos); +ntfs_debug ("vol->data2_zone_pos = 0x%llx" , vol->data2_zone_pos);/* Set the mft data allocation position to mft record 24. */ vol->mft_data_pos =24 ; -ntfs_debug ("vol->mft_data_pos = 0x%llx" , - (unsigned long long )vol->mft_data_pos); -#endif /* NTFS_RW */ +ntfs_debug ("vol->mft_data_pos = 0x%llx" , vol->mft_data_pos); } -#ifdef NTFS_RW - +static struct lock_class_key mftmirr_runlist_lock_key, + mftmirr_mrec_lock_key;/** * load_and_init_mft_mirror - load and setup the mft mirror inode for a volume * @vol: ntfs super block describing device whose mft mirror to load * * Return 'true' on success or 'false' on error. */ -static bool load_and_init_mft_mirror (ntfs_volume *vol) +static bool load_and_init_mft_mirror (struct ntfs_volume *vol) {struct inode *tmp_ino; -ntfs_inode *tmp_ni; +struct ntfs_inode *tmp_ni;ntfs_debug ("Entering." );/* Get mft mirror inode. */ tmp_ino =ntfs_iget (vol->sb, FILE_MFTMirr); -if (IS_ERR (tmp_ino) ||is_bad_inode (tmp_ino)) { +if (IS_ERR (tmp_ino)) {if (!IS_ERR (tmp_ino))iput (tmp_ino);/* Caller will display error message. */ return false; } +lockdep_set_class (&NTFS_I (tmp_ino)->runlist.lock, + &mftmirr_runlist_lock_key); +lockdep_set_class (&NTFS_I (tmp_ino)->mrec_lock, + &mftmirr_mrec_lock_key);/* * Re-initialize some specifics about $MFTMirr's inode as * ntfs_read_inode() will have set up the default ones.
@@ -1052,7 +871,7 @@ static bool load_and_init_mft_mirror(ntfs_volume *vol) tmp_ino->i_op = &ntfs_empty_inode_ops; tmp_ino->i_fop = &ntfs_empty_file_ops;/* Put in our special address space operations. */ - tmp_ino->i_mapping->a_ops = &ntfs_mst_aops; + tmp_ino->i_mapping->a_ops = &ntfs_aops; tmp_ni =NTFS_I (tmp_ino);/* The $MFTMirr, like the $MFT is multi sector transfer protected. */ NInoSetMstProtected (tmp_ni);
@@ -1078,23 +897,19 @@ static bool load_and_init_mft_mirror(ntfs_volume *vol)* mapped into memory. The mft mirror write code requires this and will BUG() * should it find an unmapped runlist element. */ -static bool check_mft_mirror (ntfs_volume *vol) +static bool check_mft_mirror (struct ntfs_volume *vol) {struct super_block *sb = vol->sb; -ntfs_inode *mirr_ni; -struct page *mft_page, *mirr_page; -u8 *kmft, *kmirr; -runlist_element *rl, rl2[2 ]; +struct ntfs_inode *mirr_ni; +struct folio *mft_folio =NULL , *mirr_folio =NULL ; +u8 *kmft =NULL , *kmirr =NULL ; +struct runlist_element *rl, rl2[2 ];pgoff_t index;int mrecs_per_page, i;ntfs_debug ("Entering." );/* Compare contents of $MFT and $MFTMirr. */ mrecs_per_page =PAGE_SIZE / vol->mft_record_size; -BUG_ON (!mrecs_per_page); -BUG_ON (!vol->mftmirr_size); - mft_page = mirr_page =NULL ; - kmft = kmirr =NULL ; index = i =0 ; do { u32 bytes;
@@ -1102,79 +917,80 @@ static bool check_mft_mirror(ntfs_volume *vol)/* Switch pages if necessary. */ if (!(i % mrecs_per_page)) {if (index) { -ntfs_unmap_page (mft_page); -ntfs_unmap_page (mirr_page); +kunmap_local (kmirr); +folio_put (mirr_folio); +kunmap_local (kmft); +folio_put (mft_folio); }/* Get the $MFT page. */ - mft_page =ntfs_map_page (vol->mft_ino->i_mapping, - index); -if (IS_ERR (mft_page)) { + mft_folio =read_mapping_folio (vol->mft_ino->i_mapping, + index,NULL ); +if (IS_ERR (mft_folio)) {ntfs_error (sb,"Failed to read $MFT." );return false; } - kmft =page_address (mft_page); + kmft =kmap_local_folio (mft_folio,0 );/* Get the $MFTMirr page. */ - mirr_page =ntfs_map_page (vol->mftmirr_ino->i_mapping, - index); -if (IS_ERR (mirr_page)) { + mirr_folio =read_mapping_folio (vol->mftmirr_ino->i_mapping, + index,NULL ); +if (IS_ERR (mirr_folio)) {ntfs_error (sb,"Failed to read $MFTMirr." ); goto mft_unmap_out; } - kmirr =page_address (mirr_page); + kmirr =kmap_local_folio (mirr_folio,0 ); ++index; } +/* Do not check the record if it is not in use. */ -if (((MFT_RECORD *)kmft)->flags &MFT_RECORD_IN_USE ) { +if (((struct mft_record *)kmft)->flags &MFT_RECORD_IN_USE ) {/* Make sure the record is ok. */ -if (ntfs_is_baad_recordp ((le32 *)kmft)) { -ntfs_error (sb,"Incomplete multi sector " -"transfer detected in mft " -"record %i." , i); +if (ntfs_is_baad_recordp ((__le32 *)kmft)) { +ntfs_error (sb, +"Incomplete multi sector transfer detected in mft record %i." , + i); mm_unmap_out: -ntfs_unmap_page (mirr_page); +kunmap_local (kmirr); +folio_put (mirr_folio); mft_unmap_out: -ntfs_unmap_page (mft_page); +kunmap_local (kmft); +folio_put (mft_folio);return false; } }/* Do not check the mirror record if it is not in use. */ -if (((MFT_RECORD *)kmirr)->flags &MFT_RECORD_IN_USE ) { -if (ntfs_is_baad_recordp ((le32 *)kmirr)) { -ntfs_error (sb,"Incomplete multi sector " -"transfer detected in mft " -"mirror record %i." , i); +if (((struct mft_record *)kmirr)->flags &MFT_RECORD_IN_USE ) { +if (ntfs_is_baad_recordp ((__le32 *)kmirr)) { +ntfs_error (sb, +"Incomplete multi sector transfer detected in mft mirror record %i." , + i); goto mm_unmap_out; } }/* Get the amount of data in the current record. */ - bytes =le32_to_cpu (((MFT_RECORD *)kmft)->bytes_in_use); -if (bytes <sizeof (MFT_RECORD_OLD ) || - bytes > vol->mft_record_size || -ntfs_is_baad_recordp ((le32 *)kmft)) { - bytes =le32_to_cpu (((MFT_RECORD *)kmirr)->bytes_in_use); -if (bytes <sizeof (MFT_RECORD_OLD ) || - bytes > vol->mft_record_size || -ntfs_is_baad_recordp ((le32 *)kmirr)) + bytes =le32_to_cpu (((struct mft_record *)kmft)->bytes_in_use); +if (bytes <sizeof (struct mft_record_old ) || + bytes > vol->mft_record_size || +ntfs_is_baad_recordp ((__le32 *)kmft)) { + bytes =le32_to_cpu (((struct mft_record *)kmirr)->bytes_in_use); +if (bytes <sizeof (struct mft_record_old ) || + bytes > vol->mft_record_size || +ntfs_is_baad_recordp ((__le32 *)kmirr)) bytes = vol->mft_record_size; } -/* Compare the two records. */ -if (memcmp (kmft, kmirr, bytes)) { -ntfs_error (sb,"$MFT and $MFTMirr (record %i) do not " -"match. Run ntfsfix or chkdsk." , i); - goto mm_unmap_out; - } kmft += vol->mft_record_size; kmirr += vol->mft_record_size; }while (++i < vol->mftmirr_size); -/* Release the last pages. */ -ntfs_unmap_page (mft_page); -ntfs_unmap_page (mirr_page); +/* Release the last folios. */ +kunmap_local (kmirr); +folio_put (mirr_folio); +kunmap_local (kmft); +folio_put (mft_folio);/* Construct the mft mirror runlist by hand. */ rl2[0 ].vcn =0 ; rl2[0 ].lcn = vol->mftmirr_lcn; - rl2[0 ].length = (vol->mftmirr_size * vol->mft_record_size + - vol->cluster_size -1 ) / vol->cluster_size; + rl2[0 ].length =NTFS_B_TO_CLU (vol, vol->mftmirr_size * vol->mft_record_size + + vol->cluster_size -1 ); rl2[1 ].vcn = rl2[0 ].length; rl2[1 ].lcn =LCN_ENOENT ; rl2[1 ].length =0 ;
@@ -1190,8 +1006,7 @@ static bool check_mft_mirror(ntfs_volume *vol) do { if (rl2[i].vcn != rl[i].vcn || rl2[i].lcn != rl[i].lcn || rl2[i].length != rl[i].length) { - ntfs_error(sb, "$MFTMirr location mismatch. " - "Run chkdsk."); + ntfs_error(sb, "$MFTMirr location mismatch. Run chkdsk."); up_read(&mirr_ni->runlist.lock); return false; }
@@ -1203,32 +1018,29 @@ static bool check_mft_mirror(ntfs_volume *vol)/** * load_and_check_logfile - load and check the logfile inode for a volume -* @vol: ntfs super block describing device whose logfile to load * -* Return 'true' on success or 'false' on error. +* Return 0 on success or errno on error. */ -static bool load_and_check_logfile (ntfs_volume *vol, -RESTART_PAGE_HEADER **rp) +static int load_and_check_logfile (struct ntfs_volume *vol, +struct restart_page_header **rp) {struct inode *tmp_ino; +int err =0 ;ntfs_debug ("Entering." ); tmp_ino =ntfs_iget (vol->sb, FILE_LogFile); -if (IS_ERR (tmp_ino) ||is_bad_inode (tmp_ino)) { +if (IS_ERR (tmp_ino)) {if (!IS_ERR (tmp_ino))iput (tmp_ino);/* Caller will display error message. */ -return false; - } -if (!ntfs_check_logfile (tmp_ino, rp)) { -iput (tmp_ino); -/* ntfs_check_logfile() will have displayed error output. */ -return false; +return -ENOENT ; } +if (!ntfs_check_logfile (tmp_ino, rp)) + err = -EINVAL ;NInoSetSparseDisabled (NTFS_I (tmp_ino)); vol->logfile_ino = tmp_ino;ntfs_debug ("Done." ); -return true; +return err; }#define NTFS_HIBERFIL_HEADER_SIZE 4096
@@ -1257,21 +1069,21 @@ static bool load_and_check_logfile(ntfs_volume *vol,* Return 0 if Windows is not hibernated on the volume, >0 if Windows is * hibernated on the volume, and -errno on error. */ -static int check_windows_hibernation_status (ntfs_volume *vol) +static int check_windows_hibernation_status (struct ntfs_volume *vol) { -MFT_REF mref; -struct inode *vi; -struct page *page; -u32 *kaddr, *kend; -ntfs_name *name =NULL ; -int ret =1 ; -static const ntfschar hiberfil[13 ] = {cpu_to_le16 ('h' ), +static const __le16 hiberfil[13 ] = {cpu_to_le16 ('h' ),cpu_to_le16 ('i' ),cpu_to_le16 ('b' ),cpu_to_le16 ('e' ),cpu_to_le16 ('r' ),cpu_to_le16 ('f' ),cpu_to_le16 ('i' ),cpu_to_le16 ('l' ),cpu_to_le16 ('.' ),cpu_to_le16 ('s' ),cpu_to_le16 ('y' ),cpu_to_le16 ('s' ),0 }; +u64 mref; +struct inode *vi; +struct folio *folio; +u32 *kaddr, *kend, *start_addr =NULL ; +struct ntfs_name *name =NULL ; +int ret =1 ;ntfs_debug ("Entering." );/*
@@ -1282,66 +1094,57 @@ static int check_windows_hibernation_status(ntfs_volume *vol) mref =ntfs_lookup_inode_by_name (NTFS_I (vol->root_ino), hiberfil,12 , &name);inode_unlock (vol->root_ino); +kfree (name);if (IS_ERR_MREF (mref)) { ret =MREF_ERR (mref);/* If the file does not exist, Windows is not hibernated. */ if (ret == -ENOENT ) { -ntfs_debug ("hiberfil.sys not present. Windows is not " -"hibernated on the volume." ); +ntfs_debug ("hiberfil.sys not present. Windows is not hibernated on the volume." );return 0 ; }/* A real error occurred. */ -ntfs_error (vol->sb,"Failed to find inode number for " -"hiberfil.sys." ); +ntfs_error (vol->sb,"Failed to find inode number for hiberfil.sys." );return ret; } -/* We do not care for the type of match that was found. */ -kfree (name);/* Get the inode. */ vi =ntfs_iget (vol->sb,MREF (mref)); -if (IS_ERR (vi) ||is_bad_inode (vi)) { +if (IS_ERR (vi)) {if (!IS_ERR (vi))iput (vi);ntfs_error (vol->sb,"Failed to load hiberfil.sys." );return IS_ERR (vi) ?PTR_ERR (vi) : -EIO ; }if (unlikely (i_size_read (vi) <NTFS_HIBERFIL_HEADER_SIZE )) { -ntfs_debug ("hiberfil.sys is smaller than 4kiB (0x%llx). " -"Windows is hibernated on the volume. This " -"is not the system volume." ,i_size_read (vi)); +ntfs_debug ("hiberfil.sys is smaller than 4kiB (0x%llx). Windows is hibernated on the volume. This is not the system volume." , +i_size_read (vi)); goto iput_out; } - page =ntfs_map_page (vi->i_mapping,0 ); -if (IS_ERR (page)) { + + folio =read_mapping_folio (vi->i_mapping,0 ,NULL ); +if (IS_ERR (folio)) {ntfs_error (vol->sb,"Failed to read from hiberfil.sys." ); - ret =PTR_ERR (page); + ret =PTR_ERR (folio); goto iput_out; } - kaddr = (u32 *)page_address (page); -if (*(le32 *)kaddr ==cpu_to_le32 (0x72626968 )/*'hibr'*/ ) { -ntfs_debug ("Magic \"hibr\" found in hiberfil.sys. Windows is " -"hibernated on the volume. This is the " -"system volume." ); + start_addr = (u32 *)kmap_local_folio (folio,0 ); + kaddr = start_addr; +if (*(__le32 *)kaddr ==cpu_to_le32 (0x72626968 )/*'hibr'*/ ) { +ntfs_debug ("Magic \"hibr\" found in hiberfil.sys. Windows is hibernated on the volume. This is the system volume." ); goto unm_iput_out; } kend = kaddr +NTFS_HIBERFIL_HEADER_SIZE /sizeof (*kaddr);do {if (unlikely (*kaddr)) { -ntfs_debug ("hiberfil.sys is larger than 4kiB " -"(0x%llx), does not contain the " -"\"hibr\" magic, and does not have a " -"zero header. Windows is hibernated " -"on the volume. This is not the " -"system volume." ,i_size_read (vi)); +ntfs_debug ("hiberfil.sys is larger than 4kiB (0x%llx), does not contain the \"hibr\" magic, and does not have a zero header. Windows is hibernated on the volume. This is not the system volume." , +i_size_read (vi)); goto unm_iput_out; } }while (++kaddr < kend); -ntfs_debug ("hiberfil.sys contains a zero header. Windows is not " -"hibernated on the volume. This is the system " -"volume." ); +ntfs_debug ("hiberfil.sys contains a zero header. Windows is not hibernated on the volume. This is the system volume." ); ret =0 ; unm_iput_out: -ntfs_unmap_page (page); +kunmap_local (start_addr); +folio_put (folio); iput_out:iput (vi);return ret;
@@ -1354,17 +1157,17 @@ static int check_windows_hibernation_status(ntfs_volume *vol)* Return 'true' on success or 'false' on error. If $Quota is not present, we * leave vol->quota_ino as NULL and return success. */ -static bool load_and_init_quota (ntfs_volume *vol) +static bool load_and_init_quota (struct ntfs_volume *vol) { -MFT_REF mref; -struct inode *tmp_ino; -ntfs_name *name =NULL ; -static const ntfschar Quota[7 ] = {cpu_to_le16 ('$' ), +static const __le16 Quota[7 ] = {cpu_to_le16 ('$' ),cpu_to_le16 ('Q' ),cpu_to_le16 ('u' ),cpu_to_le16 ('o' ),cpu_to_le16 ('t' ),cpu_to_le16 ('a' ),0 }; -static ntfschar Q [3 ] = {cpu_to_le16 ('$' ), +static __le16 Q [3 ] = {cpu_to_le16 ('$' ),cpu_to_le16 ('Q' ),0 }; +struct ntfs_name *name =NULL ; +u64 mref; +struct inode *tmp_ino;ntfs_debug ("Entering." );/*
@@ -1375,14 +1178,14 @@ static bool load_and_init_quota(ntfs_volume *vol) mref =ntfs_lookup_inode_by_name (NTFS_I (vol->extend_ino), Quota,6 , &name);inode_unlock (vol->extend_ino); +kfree (name);if (IS_ERR_MREF (mref)) {/* * If the file does not exist, quotas are disabled and have * never been enabled on this volume, just return success. */ if (MREF_ERR (mref) == -ENOENT ) { -ntfs_debug ("$Quota not present. Volume does not have " -"quotas enabled." ); +ntfs_debug ("$Quota not present. Volume does not have quotas enabled." );/* * No need to try to set quotas out of date if they are * not enabled.
@@ -1394,11 +1197,9 @@ static bool load_and_init_quota(ntfs_volume *vol)ntfs_error (vol->sb,"Failed to find inode number for $Quota." );return false; } -/* We do not care for the type of match that was found. */ -kfree (name);/* Get the inode. */ tmp_ino =ntfs_iget (vol->sb,MREF (mref)); -if (IS_ERR (tmp_ino) ||is_bad_inode (tmp_ino)) { +if (IS_ERR (tmp_ino)) {if (!IS_ERR (tmp_ino))iput (tmp_ino);ntfs_error (vol->sb,"Failed to load $Quota." );
@@ -1416,186 +1217,26 @@ static bool load_and_init_quota(ntfs_volume *vol)return true; } -/** -* load_and_init_usnjrnl - load and setup the transaction log if present -* @vol: ntfs super block describing device whose usnjrnl file to load -* -* Return 'true' on success or 'false' on error. -* -* If $UsnJrnl is not present or in the process of being disabled, we set -* NVolUsnJrnlStamped() and return success. -* -* If the $UsnJrnl $DATA/$J attribute has a size equal to the lowest valid usn, -* i.e. transaction logging has only just been enabled or the journal has been -* stamped and nothing has been logged since, we also set NVolUsnJrnlStamped() -* and return success. -*/ -static bool load_and_init_usnjrnl (ntfs_volume *vol) -{ -MFT_REF mref; -struct inode *tmp_ino; -ntfs_inode *tmp_ni; -struct page *page; -ntfs_name *name =NULL ; -USN_HEADER *uh; -static const ntfschar UsnJrnl[9 ] = {cpu_to_le16 ('$' ), -cpu_to_le16 ('U' ),cpu_to_le16 ('s' ), -cpu_to_le16 ('n' ),cpu_to_le16 ('J' ), -cpu_to_le16 ('r' ),cpu_to_le16 ('n' ), -cpu_to_le16 ('l' ),0 }; -static ntfschar Max[5 ] = {cpu_to_le16 ('$' ), -cpu_to_le16 ('M' ),cpu_to_le16 ('a' ), -cpu_to_le16 ('x' ),0 }; -static ntfschar J [3 ] = {cpu_to_le16 ('$' ), -cpu_to_le16 ('J' ),0 }; - -ntfs_debug ("Entering." ); -/* -* Find the inode number for the transaction log file by looking up the -* filename $UsnJrnl in the extended system files directory $Extend. -*/ -inode_lock (vol->extend_ino); - mref =ntfs_lookup_inode_by_name (NTFS_I (vol->extend_ino), UsnJrnl,8 , - &name); -inode_unlock (vol->extend_ino); -if (IS_ERR_MREF (mref)) { -/* -* If the file does not exist, transaction logging is disabled, -* just return success. -*/ -if (MREF_ERR (mref) == -ENOENT ) { -ntfs_debug ("$UsnJrnl not present. Volume does not " -"have transaction logging enabled." ); -not_enabled: -/* -* No need to try to stamp the transaction log if -* transaction logging is not enabled. -*/ -NVolSetUsnJrnlStamped (vol); -return true; - } -/* A real error occurred. */ -ntfs_error (vol->sb,"Failed to find inode number for " -"$UsnJrnl." ); -return false; - } -/* We do not care for the type of match that was found. */ -kfree (name); -/* Get the inode. */ - tmp_ino =ntfs_iget (vol->sb,MREF (mref)); -if (IS_ERR (tmp_ino) ||unlikely (is_bad_inode (tmp_ino))) { -if (!IS_ERR (tmp_ino)) -iput (tmp_ino); -ntfs_error (vol->sb,"Failed to load $UsnJrnl." ); -return false; - } - vol->usnjrnl_ino = tmp_ino; -/* -* If the transaction log is in the process of being deleted, we can -* ignore it. -*/ -if (unlikely (vol->vol_flags &VOLUME_DELETE_USN_UNDERWAY )) { -ntfs_debug ("$UsnJrnl in the process of being disabled. " -"Volume does not have transaction logging " -"enabled." ); - goto not_enabled; - } -/* Get the $DATA/$Max attribute. */ - tmp_ino =ntfs_attr_iget (vol->usnjrnl_ino,AT_DATA , Max,4 ); -if (IS_ERR (tmp_ino)) { -ntfs_error (vol->sb,"Failed to load $UsnJrnl/$DATA/$Max " -"attribute." ); -return false; - } - vol->usnjrnl_max_ino = tmp_ino; -if (unlikely (i_size_read (tmp_ino) <sizeof (USN_HEADER ))) { -ntfs_error (vol->sb,"Found corrupt $UsnJrnl/$DATA/$Max " -"attribute (size is 0x%llx but should be at " -"least 0x%zx bytes)." ,i_size_read (tmp_ino), -sizeof (USN_HEADER )); -return false; - } -/* Get the $DATA/$J attribute. */ - tmp_ino =ntfs_attr_iget (vol->usnjrnl_ino,AT_DATA ,J ,2 ); -if (IS_ERR (tmp_ino)) { -ntfs_error (vol->sb,"Failed to load $UsnJrnl/$DATA/$J " -"attribute." ); -return false; - } - vol->usnjrnl_j_ino = tmp_ino; -/* Verify $J is non-resident and sparse. */ - tmp_ni =NTFS_I (vol->usnjrnl_j_ino); -if (unlikely (!NInoNonResident (tmp_ni) || !NInoSparse (tmp_ni))) { -ntfs_error (vol->sb,"$UsnJrnl/$DATA/$J attribute is resident " -"and/or not sparse." ); -return false; - } -/* Read the USN_HEADER from $DATA/$Max. */ - page =ntfs_map_page (vol->usnjrnl_max_ino->i_mapping,0 ); -if (IS_ERR (page)) { -ntfs_error (vol->sb,"Failed to read from $UsnJrnl/$DATA/$Max " -"attribute." ); -return false; - } - uh = (USN_HEADER *)page_address (page); -/* Sanity check the $Max. */ -if (unlikely (sle64_to_cpu (uh->allocation_delta) > -sle64_to_cpu (uh->maximum_size))) { -ntfs_error (vol->sb,"Allocation delta (0x%llx) exceeds " -"maximum size (0x%llx). $UsnJrnl is corrupt." , - (long long )sle64_to_cpu (uh->allocation_delta), - (long long )sle64_to_cpu (uh->maximum_size)); -ntfs_unmap_page (page); -return false; - } -/* -* If the transaction log has been stamped and nothing has been written -* to it since, we do not need to stamp it. -*/ -if (unlikely (sle64_to_cpu (uh->lowest_valid_usn) >= -i_size_read (vol->usnjrnl_j_ino))) { -if (likely (sle64_to_cpu (uh->lowest_valid_usn) == -i_size_read (vol->usnjrnl_j_ino))) { -ntfs_unmap_page (page); -ntfs_debug ("$UsnJrnl is enabled but nothing has been " -"logged since it was last stamped. " -"Treating this as if the volume does " -"not have transaction logging " -"enabled." ); - goto not_enabled; - } -ntfs_error (vol->sb,"$UsnJrnl has lowest valid usn (0x%llx) " -"which is out of bounds (0x%llx). $UsnJrnl " -"is corrupt." , - (long long )sle64_to_cpu (uh->lowest_valid_usn), -i_size_read (vol->usnjrnl_j_ino)); -ntfs_unmap_page (page); -return false; - } -ntfs_unmap_page (page); -ntfs_debug ("Done." ); -return true; -} -/** * load_and_init_attrdef - load the attribute definitions table for a volume * @vol: ntfs super block describing device whose attrdef to load * * Return 'true' on success or 'false' on error. */ -static bool load_and_init_attrdef (ntfs_volume *vol) +static bool load_and_init_attrdef (struct ntfs_volume *vol) {loff_t i_size;struct super_block *sb = vol->sb;struct inode *ino; -struct page *page; +struct folio *folio; +u8 *addr;pgoff_t index, max_index;unsigned int size;ntfs_debug ("Entering." );/* Read attrdef table and setup vol->attrdef and vol->attrdef_size. */ ino =ntfs_iget (sb, FILE_AttrDef); -if (IS_ERR (ino) ||is_bad_inode (ino)) { +if (IS_ERR (ino)) {if (!IS_ERR (ino))iput (ino); goto failed;
@@ -1605,7 +1246,7 @@ static bool load_and_init_attrdef(ntfs_volume *vol) i_size =i_size_read (ino);if (i_size <=0 || i_size >0x7fffffff ) goto iput_failed; - vol->attrdef = (ATTR_DEF *)ntfs_malloc_nofs (i_size); + vol->attrdef = (struct attr_def *)ntfs_malloc_nofs (i_size);if (!vol->attrdef) goto iput_failed; index =0 ;
@@ -1614,12 +1255,14 @@ static bool load_and_init_attrdef(ntfs_volume *vol)while (index < max_index) {/* Read the attrdef table and copy it into the linear buffer. */ read_partial_attrdef_page: - page =ntfs_map_page (ino->i_mapping, index); -if (IS_ERR (page)) + folio =read_mapping_folio (ino->i_mapping, index,NULL ); +if (IS_ERR (folio)) goto free_iput_failed; -memcpy ((u8 *)vol->attrdef + (index++ <<PAGE_SHIFT ), -page_address (page), size); -ntfs_unmap_page (page); + addr =kmap_local_folio (folio,0 ); +memcpy ((u8 *)vol->attrdef + (index++ <<PAGE_SHIFT ), + addr, size); +kunmap_local (addr); +folio_put (folio); }if (size ==PAGE_SIZE ) { size = i_size & ~PAGE_MASK ;
@@ -1640,20 +1283,19 @@ static bool load_and_init_attrdef(ntfs_volume *vol)return false; } -#endif /* NTFS_RW */ -/** * load_and_init_upcase - load the upcase table for an ntfs volume * @vol: ntfs super block describing device whose upcase to load * * Return 'true' on success or 'false' on error. */ -static bool load_and_init_upcase (ntfs_volume *vol) +static bool load_and_init_upcase (struct ntfs_volume *vol) {loff_t i_size;struct super_block *sb = vol->sb;struct inode *ino; -struct page *page; +struct folio *folio; +u8 *addr;pgoff_t index, max_index;unsigned int size;int i, max;
@@ -1661,20 +1303,20 @@ static bool load_and_init_upcase(ntfs_volume *vol)ntfs_debug ("Entering." );/* Read upcase table and setup vol->upcase and vol->upcase_len. */ ino =ntfs_iget (sb, FILE_UpCase); -if (IS_ERR (ino) ||is_bad_inode (ino)) { +if (IS_ERR (ino)) {if (!IS_ERR (ino))iput (ino); goto upcase_failed; }/* * The upcase size must not be above 64k Unicode characters, must not -* be zero and must be a multiple of sizeof(ntfschar). +* be zero and must be a multiple of sizeof(__le16). */ i_size =i_size_read (ino); -if (!i_size || i_size & (sizeof (ntfschar) -1 ) || - i_size >64ULL *1024 *sizeof (ntfschar)) +if (!i_size || i_size & (sizeof (__le16) -1 ) || + i_size >64ULL *1024 *sizeof (__le16)) goto iput_upcase_failed; - vol->upcase = (ntfschar *)ntfs_malloc_nofs (i_size); + vol->upcase = (__le16 *)ntfs_malloc_nofs (i_size);if (!vol->upcase) goto iput_upcase_failed; index =0 ;
@@ -1683,13 +1325,15 @@ static bool load_and_init_upcase(ntfs_volume *vol)while (index < max_index) {/* Read the upcase table and copy it into the linear buffer. */ read_partial_upcase_page: - page =ntfs_map_page (ino->i_mapping, index); -if (IS_ERR (page)) + folio =read_mapping_folio (ino->i_mapping, index,NULL ); +if (IS_ERR (folio)) goto iput_upcase_failed; -memcpy ((char *)vol->upcase + (index++ <<PAGE_SHIFT ), -page_address (page), size); -ntfs_unmap_page (page); - } + addr =kmap_local_folio (folio,0 ); +memcpy ((char *)vol->upcase + (index++ <<PAGE_SHIFT ), + addr, size); +kunmap_local (addr); +folio_put (folio); + };if (size ==PAGE_SIZE ) { size = i_size & ~PAGE_MASK ;if (size)
@@ -1697,12 +1341,11 @@ static bool load_and_init_upcase(ntfs_volume *vol) } vol->upcase_len = i_size >>UCHAR_T_SIZE_BITS ;ntfs_debug ("Read %llu bytes from $UpCase (expected %zu bytes)." , - i_size,64 *1024 *sizeof (ntfschar)); + i_size,64 *1024 *sizeof (__le16));iput (ino);mutex_lock (&ntfs_lock);if (!default_upcase) { -ntfs_debug ("Using volume specified $UpCase since default is " -"not present." ); +ntfs_debug ("Using volume specified $UpCase since default is not present." );mutex_unlock (&ntfs_lock);return true; }
@@ -1718,13 +1361,11 @@ static bool load_and_init_upcase(ntfs_volume *vol) vol->upcase_len = max; ntfs_nr_upcase_users++;mutex_unlock (&ntfs_lock); -ntfs_debug ("Volume specified $UpCase matches default. Using " -"default." ); +ntfs_debug ("Volume specified $UpCase matches default. Using default." );return true; }mutex_unlock (&ntfs_lock); -ntfs_debug ("Using volume specified $UpCase since it does not match " -"the default." ); +ntfs_debug ("Using volume specified $UpCase since it does not match the default." );return true; iput_upcase_failed:iput (ino);
@@ -1737,8 +1378,7 @@ static bool load_and_init_upcase(ntfs_volume *vol) vol->upcase_len = default_upcase_len; ntfs_nr_upcase_users++;mutex_unlock (&ntfs_lock); -ntfs_error (sb,"Failed to load $UpCase from the volume. Using " -"default." ); +ntfs_error (sb,"Failed to load $UpCase from the volume. Using default." );return true; }mutex_unlock (&ntfs_lock);
@@ -1763,47 +1403,30 @@ static struct lock_class_key* * Return 'true' on success or 'false' on error. */ -static bool load_system_files (ntfs_volume *vol) +static bool load_system_files (struct ntfs_volume *vol) {struct super_block *sb = vol->sb; -MFT_RECORD *m; -VOLUME_INFORMATION *vi; -ntfs_attr_search_ctx *ctx; -#ifdef NTFS_RW -RESTART_PAGE_HEADER *rp; +struct mft_record *m; +struct volume_information *vi; +struct ntfs_attr_search_ctx *ctx; +struct restart_page_header *rp;int err; -#endif /* NTFS_RW */ ntfs_debug ("Entering." ); -#ifdef NTFS_RW /* Get mft mirror inode compare the contents of $MFT and $MFTMirr. */ if (!load_and_init_mft_mirror (vol) || !check_mft_mirror (vol)) { -static const char *es1 ="Failed to load $MFTMirr" ; -static const char *es2 ="$MFTMirr does not match $MFT" ; -static const char *es3 =". Run ntfsfix and/or chkdsk." ; -/* If a read-write mount, convert it to a read-only mount. */ -if (!sb_rdonly (sb)) { -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=" -"continue nor on_errors=" -"remount-ro was specified%s" , - !vol->mftmirr_ino ? es1 : es2, - es3); - goto iput_mirr_err_out; - } +if (!sb_rdonly (sb) && vol->on_errors ==ON_ERRORS_REMOUNT_RO ) { +static const char *es1 ="Failed to load $MFTMirr" ; +static const char *es2 ="$MFTMirr does not match $MFT" ; +static const char *es3 =". Run ntfsck and/or chkdsk." ; + sb->s_flags |=SB_RDONLY ;ntfs_error (sb,"%s. Mounting read-only%s" , !vol->mftmirr_ino ? es1 : es2, es3); - }else -ntfs_warning (sb,"%s. Will not be able to remount " -"read-write%s" , - !vol->mftmirr_ino ? es1 : es2, es3); -/* This will prevent a read-write remount. */ + }NVolSetErrors (vol); } -#endif /* NTFS_RW */ /* Get mft bitmap attribute inode. */ vol->mftbmp_ino =ntfs_attr_iget (vol->mft_ino,AT_BITMAP ,NULL ,0 );if (IS_ERR (vol->mftbmp_ino)) {
@@ -1817,21 +1440,19 @@ static bool load_system_files(ntfs_volume *vol)/* Read upcase table and setup @vol->upcase and @vol->upcase_len. */ if (!load_and_init_upcase (vol)) goto iput_mftbmp_err_out; -#ifdef NTFS_RW /* * Read attribute definitions table and setup @vol->attrdef and * @vol->attrdef_size. */ if (!load_and_init_attrdef (vol)) goto iput_upcase_err_out; -#endif /* NTFS_RW */ /* * Get the cluster allocation bitmap inode and verify the size, no * need for any locking at this stage as we are already running * exclusively as we are mount in progress task. */ vol->lcnbmp_ino =ntfs_iget (sb, FILE_Bitmap); -if (IS_ERR (vol->lcnbmp_ino) ||is_bad_inode (vol->lcnbmp_ino)) { +if (IS_ERR (vol->lcnbmp_ino)) {if (!IS_ERR (vol->lcnbmp_ino))iput (vol->lcnbmp_ino); goto bitmap_failed;
@@ -1853,7 +1474,7 @@ static bool load_system_files(ntfs_volume *vol)* version. */ vol->vol_ino =ntfs_iget (sb, FILE_Volume); -if (IS_ERR (vol->vol_ino) ||is_bad_inode (vol->vol_ino)) { +if (IS_ERR (vol->vol_ino)) {if (!IS_ERR (vol->vol_ino))iput (vol->vol_ino); volume_failed:
@@ -1866,10 +1487,25 @@ static bool load_system_files(ntfs_volume *vol)iput (vol->vol_ino); goto volume_failed; } -if (!(ctx =ntfs_attr_get_search_ctx (NTFS_I (vol->vol_ino), m))) { + + ctx =ntfs_attr_get_search_ctx (NTFS_I (vol->vol_ino), m); +if (!ctx) {ntfs_error (sb,"Failed to get attribute search context." ); goto get_ctx_vol_failed; } + +if (!ntfs_attr_lookup (AT_VOLUME_NAME ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx) && + !ctx->attr->non_resident && + !(ctx->attr->flags & (ATTR_IS_SPARSE |ATTR_IS_COMPRESSED )) && +le32_to_cpu (ctx->attr->data.resident.value_length) >0 ) { + err =ntfs_ucstonls (vol, (__le16 *)((u8 *)ctx->attr + +le16_to_cpu (ctx->attr->data.resident.value_offset)), +le32_to_cpu (ctx->attr->data.resident.value_length) /2 , + &vol->volume_label,NTFS_MAX_LABEL_LEN ); +if (err <0 ) + vol->volume_label =NULL ; + } +if (ntfs_attr_lookup (AT_VOLUME_INFORMATION ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx) || ctx->attr->non_resident || ctx->attr->flags) { err_put_vol:
@@ -1878,28 +1514,22 @@ static bool load_system_files(ntfs_volume *vol)unmap_mft_record (NTFS_I (vol->vol_ino)); goto iput_volume_failed; } - vi = (VOLUME_INFORMATION *)((char *)ctx->attr + + vi = (struct volume_information *)((char *)ctx->attr +le16_to_cpu (ctx->attr->data.resident.value_offset));/* Some bounds checks. */ -if ((u8 *)vi < (u8 *)ctx->attr || (u8 *)vi + +if ((u8 *)vi < (u8 *)ctx->attr || (u8 *)vi +le32_to_cpu (ctx->attr->data.resident.value_length) > - (u8 *)ctx->attr +le32_to_cpu (ctx->attr->length)) + (u8 *)ctx->attr +le32_to_cpu (ctx->attr->length)) goto err_put_vol; -/* Copy the volume flags and version to the ntfs_volume structure. */ +/* Copy the volume flags and version to the struct ntfs_volume structure. */ vol->vol_flags = vi->flags; vol->major_ver = vi->major_ver; vol->minor_ver = vi->minor_ver;ntfs_attr_put_search_ctx (ctx);unmap_mft_record (NTFS_I (vol->vol_ino)); -pr_info ("volume version %i.%i.\n" , vol->major_ver, - vol->minor_ver); -if (vol->major_ver <3 &&NVolSparseEnabled (vol)) { -ntfs_warning (vol->sb,"Disabling sparse support due to NTFS " -"volume version %i.%i (need at least version " -"3.0)." , vol->major_ver, vol->minor_ver); -NVolClearSparseEnabled (vol); - } -#ifdef NTFS_RW +pr_info ("volume version %i.%i, dev %s, cluster size %d\n" , + vol->major_ver, vol->minor_ver, sb->s_id, vol->cluster_size); +/* Make sure that no unsupported volume flags are set. */ if (vol->vol_flags &VOLUME_MUST_MOUNT_RO_MASK ) {static const char *es1a ="Volume is dirty" ;
@@ -1917,25 +1547,14 @@ static bool load_system_files(ntfs_volume *vol) es2 = es2b; }else { es1 = es1c; -ntfs_warning (sb,"Unsupported volume flags 0x%x " -"encountered." , - (unsigned )le16_to_cpu (vol->vol_flags)); +ntfs_warning (sb,"Unsupported volume flags 0x%x encountered." , + (unsigned int )le16_to_cpu (vol->vol_flags)); }/* If a read-write mount, convert it to a read-only mount. */ -if (!sb_rdonly (sb)) { -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=" -"continue nor on_errors=" -"remount-ro was specified%s" , - es1, es2); - goto iput_vol_err_out; - } +if (!sb_rdonly (sb) && vol->on_errors ==ON_ERRORS_REMOUNT_RO ) { sb->s_flags |=SB_RDONLY ;ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - }else -ntfs_warning (sb,"%s. Will not be able to remount " -"read-write%s" , es1, es2); + }/* * Do not set NVolErrors() because ntfs_remount() re-checks the * flags which we need to do in case any flags have changed.
@@ -1946,47 +1565,25 @@ static bool load_system_files(ntfs_volume *vol)* was shutdown cleanly. */ rp =NULL ; -if (!load_and_check_logfile (vol, &rp) || - !ntfs_is_logfile_clean (vol->logfile_ino, rp)) { -static const char *es1a ="Failed to load $LogFile" ; -static const char *es1b ="$LogFile is not clean" ; -static const char *es2 =". Mount in Windows." ; -const char *es1; - - es1 = !vol->logfile_ino ? es1a : es1b; + err =load_and_check_logfile (vol, &rp); +if (err) {/* If a read-write mount, convert it to a read-only mount. */ -if (!sb_rdonly (sb)) { -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=" -"continue nor on_errors=" -"remount-ro was specified%s" , - es1, es2); -if (vol->logfile_ino) { -BUG_ON (!rp); -ntfs_free (rp); - } - goto iput_logfile_err_out; - } +if (!sb_rdonly (sb) && vol->on_errors ==ON_ERRORS_REMOUNT_RO ) { sb->s_flags |=SB_RDONLY ; -ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - }else -ntfs_warning (sb,"%s. Will not be able to remount " -"read-write%s" , es1, es2); -/* This will prevent a read-write remount. */ +ntfs_error (sb,"Failed to load LogFile. Mounting read-only." ); + }NVolSetErrors (vol); } +ntfs_free (rp); -#endif /* NTFS_RW */ /* Get the root directory inode so we can do path lookups. */ vol->root_ino =ntfs_iget (sb, FILE_root); -if (IS_ERR (vol->root_ino) ||is_bad_inode (vol->root_ino)) { +if (IS_ERR (vol->root_ino)) {if (!IS_ERR (vol->root_ino))iput (vol->root_ino);ntfs_error (sb,"Failed to load root directory." ); goto iput_logfile_err_out; } -#ifdef NTFS_RW /* * Check if Windows is suspended to disk on the target volume. If it * is hibernated, we must not write *anything* to the disk so set
@@ -1996,223 +1593,74 @@ static bool load_system_files(ntfs_volume *vol)*/ err =check_windows_hibernation_status (vol);if (unlikely (err)) { -static const char *es1a ="Failed to determine if Windows is " -"hibernated" ; +static const char *es1a ="Failed to determine if Windows is hibernated" ;static const char *es1b ="Windows is hibernated" ;static const char *es2 =". Run chkdsk." ;const char *es1; es1 = err <0 ? es1a : es1b;/* If a read-write mount, convert it to a read-only mount. */ -if (!sb_rdonly (sb)) { -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=" -"continue nor on_errors=" -"remount-ro was specified%s" , - es1, es2); - goto iput_root_err_out; - } +if (!sb_rdonly (sb) && vol->on_errors ==ON_ERRORS_REMOUNT_RO ) { sb->s_flags |=SB_RDONLY ;ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - }else -ntfs_warning (sb,"%s. Will not be able to remount " -"read-write%s" , es1, es2); -/* This will prevent a read-write remount. */ -NVolSetErrors (vol); - } -/* If (still) a read-write mount, mark the volume dirty. */ -if (!sb_rdonly (sb) &&ntfs_set_volume_flags (vol,VOLUME_IS_DIRTY )) { -static const char *es1 ="Failed to set dirty bit in volume " -"information flags" ; -static const char *es2 =". Run chkdsk." ; - -/* Convert to a read-only mount. */ -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=continue nor " -"on_errors=remount-ro was specified%s" , - es1, es2); - goto iput_root_err_out; } -ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - sb->s_flags |=SB_RDONLY ; -/* -* Do not set NVolErrors() because ntfs_remount() might manage -* to set the dirty flag in which case all would be well. -*/ - } -#if 0 -// TODO: Enable this code once we start modifying anything that is -// different between NTFS 1.2 and 3.x... -/* -* If (still) a read-write mount, set the NT4 compatibility flag on -* newer NTFS version volumes. -*/ -if (!(sb->s_flags &SB_RDONLY ) && (vol->major_ver >1 ) && -ntfs_set_volume_flags (vol,VOLUME_MOUNTED_ON_NT4 )) { -static const char *es1 ="Failed to set NT4 compatibility flag" ; -static const char *es2 =". Run chkdsk." ; - -/* Convert to a read-only mount. */ -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=continue nor " -"on_errors=remount-ro was specified%s" , - es1, es2); - goto iput_root_err_out; - } -ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - sb->s_flags |=SB_RDONLY ;NVolSetErrors (vol); } -#endif +/* If (still) a read-write mount, empty the logfile. */ -if (!sb_rdonly (sb) && !ntfs_empty_logfile (vol->logfile_ino)) { -static const char *es1 ="Failed to empty $LogFile" ; +if (!sb_rdonly (sb) && + vol->logfile_ino && !ntfs_empty_logfile (vol->logfile_ino) && + vol->on_errors ==ON_ERRORS_REMOUNT_RO ) { +static const char *es1 ="Failed to empty LogFile" ;static const char *es2 =". Mount in Windows." ;/* Convert to a read-only mount. */ -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=continue nor " -"on_errors=remount-ro was specified%s" , - es1, es2); - goto iput_root_err_out; - }ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); sb->s_flags |=SB_RDONLY ;NVolSetErrors (vol); } -#endif /* NTFS_RW */ /* If on NTFS versions before 3.0, we are done. */ if (unlikely (vol->major_ver <3 ))return true;/* NTFS 3.0+ specific initialization. */ /* Get the security descriptors inode. */ vol->secure_ino =ntfs_iget (sb, FILE_Secure); -if (IS_ERR (vol->secure_ino) ||is_bad_inode (vol->secure_ino)) { +if (IS_ERR (vol->secure_ino)) {if (!IS_ERR (vol->secure_ino))iput (vol->secure_ino);ntfs_error (sb,"Failed to load $Secure." ); goto iput_root_err_out; } -// TODO: Initialize security. /* Get the extended system files' directory inode. */ vol->extend_ino =ntfs_iget (sb, FILE_Extend); -if (IS_ERR (vol->extend_ino) ||is_bad_inode (vol->extend_ino) || +if (IS_ERR (vol->extend_ino) || !S_ISDIR (vol->extend_ino->i_mode)) {if (!IS_ERR (vol->extend_ino))iput (vol->extend_ino);ntfs_error (sb,"Failed to load $Extend." ); goto iput_sec_err_out; } -#ifdef NTFS_RW /* Find the quota file, load it if present, and set it up. */ -if (!load_and_init_quota (vol)) { +if (!load_and_init_quota (vol) && + vol->on_errors ==ON_ERRORS_REMOUNT_RO ) {static const char *es1 ="Failed to load $Quota" ;static const char *es2 =". Run chkdsk." ; -/* If a read-write mount, convert it to a read-only mount. */ -if (!sb_rdonly (sb)) { -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=" -"continue nor on_errors=" -"remount-ro was specified%s" , - es1, es2); - goto iput_quota_err_out; - } - sb->s_flags |=SB_RDONLY ; -ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - }else -ntfs_warning (sb,"%s. Will not be able to remount " -"read-write%s" , es1, es2); -/* This will prevent a read-write remount. */ -NVolSetErrors (vol); - } -/* If (still) a read-write mount, mark the quotas out of date. */ -if (!sb_rdonly (sb) && !ntfs_mark_quotas_out_of_date (vol)) { -static const char *es1 ="Failed to mark quotas out of date" ; -static const char *es2 =". Run chkdsk." ; - -/* Convert to a read-only mount. */ -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=continue nor " -"on_errors=remount-ro was specified%s" , - es1, es2); - goto iput_quota_err_out; - } -ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); sb->s_flags |=SB_RDONLY ; -NVolSetErrors (vol); - } -/* -* Find the transaction log file ($UsnJrnl), load it if present, check -* it, and set it up. -*/ -if (!load_and_init_usnjrnl (vol)) { -static const char *es1 ="Failed to load $UsnJrnl" ; -static const char *es2 =". Run chkdsk." ; - -/* If a read-write mount, convert it to a read-only mount. */ -if (!sb_rdonly (sb)) { -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=" -"continue nor on_errors=" -"remount-ro was specified%s" , - es1, es2); - goto iput_usnjrnl_err_out; - } - sb->s_flags |=SB_RDONLY ; -ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - }else -ntfs_warning (sb,"%s. Will not be able to remount " -"read-write%s" , es1, es2); +ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2);/* This will prevent a read-write remount. */ NVolSetErrors (vol); } -/* If (still) a read-write mount, stamp the transaction log. */ -if (!sb_rdonly (sb) && !ntfs_stamp_usnjrnl (vol)) { -static const char *es1 ="Failed to stamp transaction log " -"($UsnJrnl)" ; -static const char *es2 =". Run chkdsk." ; -/* Convert to a read-only mount. */ -if (!(vol->on_errors & (ON_ERRORS_REMOUNT_RO | -ON_ERRORS_CONTINUE ))) { -ntfs_error (sb,"%s and neither on_errors=continue nor " -"on_errors=remount-ro was specified%s" , - es1, es2); - goto iput_usnjrnl_err_out; - } -ntfs_error (sb,"%s. Mounting read-only%s" , es1, es2); - sb->s_flags |=SB_RDONLY ; -NVolSetErrors (vol); - } -#endif /* NTFS_RW */ return true; -#ifdef NTFS_RW -iput_usnjrnl_err_out: -iput (vol->usnjrnl_j_ino); -iput (vol->usnjrnl_max_ino); -iput (vol->usnjrnl_ino); -iput_quota_err_out: -iput (vol->quota_q_ino); -iput (vol->quota_ino); -iput (vol->extend_ino); -#endif /* NTFS_RW */ + iput_sec_err_out:iput (vol->secure_ino); iput_root_err_out:iput (vol->root_ino); iput_logfile_err_out: -#ifdef NTFS_RW -iput (vol->logfile_ino); -iput_vol_err_out: -#endif /* NTFS_RW */ +if (vol->logfile_ino) +iput (vol->logfile_ino);iput (vol->vol_ino); iput_lcnbmp_err_out:iput (vol->lcnbmp_ino);
@@ -2222,9 +1670,7 @@ static bool load_system_files(ntfs_volume *vol)ntfs_free (vol->attrdef); vol->attrdef =NULL ; } -#ifdef NTFS_RW iput_upcase_err_out: -#endif /* NTFS_RW */ vol->upcase_len =0 ;mutex_lock (&ntfs_lock);if (vol->upcase == default_upcase) {
@@ -2239,28 +1685,62 @@ static bool load_system_files(ntfs_volume *vol) iput_mftbmp_err_out:iput (vol->mftbmp_ino); iput_mirr_err_out: -#ifdef NTFS_RW iput (vol->mftmirr_ino); -#endif /* NTFS_RW */ return false; } +static void ntfs_volume_free (struct ntfs_volume *vol) +{ +/* Throw away the table of attribute definitions. */ + vol->attrdef_size =0 ; +if (vol->attrdef) { +ntfs_free (vol->attrdef); + vol->attrdef =NULL ; + } + vol->upcase_len =0 ; +/* +* Destroy the global default upcase table if necessary. Also decrease +* the number of upcase users if we are a user. +*/ +mutex_lock (&ntfs_lock); +if (vol->upcase == default_upcase) { + ntfs_nr_upcase_users--; + vol->upcase =NULL ; + } + +if (!ntfs_nr_upcase_users && default_upcase) { +ntfs_free (default_upcase); + default_upcase =NULL ; + } + +free_compression_buffers (); + +mutex_unlock (&ntfs_lock); +if (vol->upcase) { +ntfs_free (vol->upcase); + vol->upcase =NULL ; + } + +unload_nls (vol->nls_map); + +if (vol->lcn_empty_bits_per_page) +kvfree (vol->lcn_empty_bits_per_page); +kfree (vol->volume_label); +kfree (vol); +} +/** * ntfs_put_super - called by the vfs to unmount a volume * @sb: vfs superblock of volume to unmount -* -* ntfs_put_super() is called by the VFS (from fs/super.c::do_umount()) when -* the volume is being unmounted (umount system call has been invoked) and it -* releases all inodes and memory belonging to the NTFS specific part of the -* super block. */ static void ntfs_put_super (struct super_block *sb) { -ntfs_volume *vol =NTFS_SB (sb); +struct ntfs_volume *vol =NTFS_SB (sb); -ntfs_debug ("Entering." ); +pr_info ("Entering %s, dev %s\n" , __func__, sb->s_id); + +cancel_work_sync (&vol->precalc_work); -#ifdef NTFS_RW /* * Commit all inodes while they are still open in case some of them * cause others to be dirtied.
@@ -2269,12 +1749,6 @@ static void ntfs_put_super(struct super_block *sb)/* NTFS 3.0+ specific. */ if (vol->major_ver >=3 ) { -if (vol->usnjrnl_j_ino) -ntfs_commit_inode (vol->usnjrnl_j_ino); -if (vol->usnjrnl_max_ino) -ntfs_commit_inode (vol->usnjrnl_max_ino); -if (vol->usnjrnl_ino) -ntfs_commit_inode (vol->usnjrnl_ino);if (vol->quota_q_ino)ntfs_commit_inode (vol->quota_q_ino);if (vol->quota_ino)
@@ -2287,13 +1761,13 @@ static void ntfs_put_super(struct super_block *sb)ntfs_commit_inode (vol->root_ino); -down_write (&vol->lcnbmp_lock);ntfs_commit_inode (vol->lcnbmp_ino); -up_write (&vol->lcnbmp_lock); -down_write (&vol->mftbmp_lock); +/* +* the GFP_NOFS scope is not needed because ntfs_commit_inode +* does nothing +*/ ntfs_commit_inode (vol->mftbmp_ino); -up_write (&vol->mftbmp_lock);if (vol->logfile_ino)ntfs_commit_inode (vol->logfile_ino);
@@ -2309,39 +1783,24 @@ static void ntfs_put_super(struct super_block *sb)if (!sb_rdonly (sb)) {if (!NVolErrors (vol)) {if (ntfs_clear_volume_flags (vol,VOLUME_IS_DIRTY )) -ntfs_warning (sb,"Failed to clear dirty bit " -"in volume information " -"flags. Run chkdsk." ); +ntfs_warning (sb, +"Failed to clear dirty bit in volume information flags. Run chkdsk." );ntfs_commit_inode (vol->vol_ino);ntfs_commit_inode (vol->root_ino);if (vol->mftmirr_ino)ntfs_commit_inode (vol->mftmirr_ino);ntfs_commit_inode (vol->mft_ino); }else { -ntfs_warning (sb,"Volume has errors. Leaving volume " -"marked dirty. Run chkdsk." ); +ntfs_warning (sb, +"Volume has errors. Leaving volume marked dirty. Run chkdsk." ); } } -#endif /* NTFS_RW */ iput (vol->vol_ino); vol->vol_ino =NULL ;/* NTFS 3.0+ specific clean up. */ if (vol->major_ver >=3 ) { -#ifdef NTFS_RW -if (vol->usnjrnl_j_ino) { -iput (vol->usnjrnl_j_ino); - vol->usnjrnl_j_ino =NULL ; - } -if (vol->usnjrnl_max_ino) { -iput (vol->usnjrnl_max_ino); - vol->usnjrnl_max_ino =NULL ; - } -if (vol->usnjrnl_ino) { -iput (vol->usnjrnl_ino); - vol->usnjrnl_ino =NULL ; - }if (vol->quota_q_ino) {iput (vol->quota_q_ino); vol->quota_q_ino =NULL ;
@@ -2350,7 +1809,6 @@ static void ntfs_put_super(struct super_block *sb)iput (vol->quota_ino); vol->quota_ino =NULL ; } -#endif /* NTFS_RW */ if (vol->extend_ino) {iput (vol->extend_ino); vol->extend_ino =NULL ;
@@ -2364,17 +1822,12 @@ static void ntfs_put_super(struct super_block *sb)iput (vol->root_ino); vol->root_ino =NULL ; -down_write (&vol->lcnbmp_lock);iput (vol->lcnbmp_ino); vol->lcnbmp_ino =NULL ; -up_write (&vol->lcnbmp_lock); -down_write (&vol->mftbmp_lock);iput (vol->mftbmp_ino); vol->mftbmp_ino =NULL ; -up_write (&vol->mftbmp_lock); -#ifdef NTFS_RW if (vol->logfile_ino) {iput (vol->logfile_ino); vol->logfile_ino =NULL ;
@@ -2393,43 +1846,66 @@ static void ntfs_put_super(struct super_block *sb)*/ ntfs_commit_inode (vol->mft_ino);write_inode_now (vol->mft_ino,1 ); -#endif /* NTFS_RW */ iput (vol->mft_ino); vol->mft_ino =NULL ; -/* Throw away the table of attribute definitions. */ - vol->attrdef_size =0 ; -if (vol->attrdef) { -ntfs_free (vol->attrdef); - vol->attrdef =NULL ; - } - vol->upcase_len =0 ; -/* -* Destroy the global default upcase table if necessary. Also decrease -* the number of upcase users if we are a user. -*/ -mutex_lock (&ntfs_lock); -if (vol->upcase == default_upcase) { - ntfs_nr_upcase_users--; - vol->upcase =NULL ; - } -if (!ntfs_nr_upcase_users && default_upcase) { -ntfs_free (default_upcase); - default_upcase =NULL ; - } -if (vol->cluster_size <=4096 && !--ntfs_nr_compression_users) -free_compression_buffers (); -mutex_unlock (&ntfs_lock); -if (vol->upcase) { -ntfs_free (vol->upcase); - vol->upcase =NULL ; +ntfs_volume_free (vol); +} + +int ntfs_force_shutdown (struct super_block *sb,u32 flags) +{ +struct ntfs_volume *vol =NTFS_SB (sb); +int ret; + +if (NVolShutdown (vol)) +return 0 ; + +switch (flags) { +case NTFS_GOING_DOWN_DEFAULT : +case NTFS_GOING_DOWN_FULLSYNC : + ret =bdev_freeze (sb->s_bdev); +if (ret) +return ret; +bdev_thaw (sb->s_bdev); +NVolSetShutdown (vol); +break ; +case NTFS_GOING_DOWN_NOSYNC : +NVolSetShutdown (vol); +break ; +default : +return -EINVAL ; } -unload_nls (vol->nls_map); +return 0 ; +} - sb->s_fs_info =NULL ; -kfree (vol); +static void ntfs_shutdown (struct super_block *sb) +{ +ntfs_force_shutdown (sb,NTFS_GOING_DOWN_NOSYNC ); + +} + +static int ntfs_sync_fs (struct super_block *sb,int wait) +{ +struct ntfs_volume *vol =NTFS_SB (sb); +int err =0 ; + +if (NVolShutdown (vol)) +return -EIO ; + +if (!wait) +return 0 ; + +/* If there are some dirty buffers in the bdev inode */ +if (ntfs_clear_volume_flags (vol,VOLUME_IS_DIRTY )) { +ntfs_warning (sb,"Failed to clear dirty bit in volume information flags. Run chkdsk." ); + err = -EIO ; + } +sync_inodes_sb (sb); +sync_blockdev (sb->s_bdev); +blkdev_issue_flush (sb->s_bdev); +return err; }/**
@@ -2451,16 +1927,27 @@ static void ntfs_put_super(struct super_block *sb)* in use. This means we return an underestimate on errors which is better than * an overestimate. */ -static s64 get_nr_free_clusters (ntfs_volume *vol) +s64 get_nr_free_clusters (struct ntfs_volume *vol) {s64 nr_free = vol->nr_clusters; +u32 nr_used;struct address_space *mapping = vol->lcnbmp_ino->i_mapping; -struct page *page; +struct folio *folio;pgoff_t index, max_index; +struct file_ra_state *ra;ntfs_debug ("Entering." );/* Serialize accesses to the cluster bitmap. */ -down_read (&vol->lcnbmp_lock); + +if (NVolFreeClusterKnown (vol)) +return atomic64_read (&vol->free_clusters); + + ra =kzalloc (sizeof (*ra),GFP_NOFS ); +if (!ra) +return 0 ; + +file_ra_state_init (ra, mapping); +/* * Convert the number of bits into bytes rounded up, then convert into * multiples of PAGE_SIZE, rounding up so that if we have one
@@ -2475,18 +1962,27 @@ static s64 get_nr_free_clusters(ntfs_volume *vol)unsigned long *kaddr;/* -* Read the page from page cache, getting it from backing store +* Get folio from page cache, getting it from backing store * if necessary, and increment the use count. */ - page =read_mapping_page (mapping, index,NULL ); + folio =filemap_lock_folio (mapping, index); +if (IS_ERR (folio)) { +page_cache_sync_readahead (mapping, ra,NULL , + index, max_index - index); + folio =read_mapping_folio (mapping, index,NULL ); +if (!IS_ERR (folio)) +folio_lock (folio); + } +/* Ignore pages which errored synchronously. */ -if (IS_ERR (page)) { -ntfs_debug ("read_mapping_page() error. Skipping " -"page (index 0x%lx)." , index); +if (IS_ERR (folio)) { +ntfs_debug ("Skipping page (index 0x%lx)." , index); nr_free -=PAGE_SIZE *8 ; + vol->lcn_empty_bits_per_page[index] =0 ;continue ; } - kaddr =kmap_atomic (page); + + kaddr =kmap_local_folio (folio,0 );/* * Subtract the number of set bits. If this * is the last page and it is partial we don't really care as
@@ -2494,10 +1990,12 @@ static s64 get_nr_free_clusters(ntfs_volume *vol)* the result as all out of range bytes are set to zero by * ntfs_readpage(). */ - nr_free -=bitmap_weight (kaddr, -PAGE_SIZE *BITS_PER_BYTE ); -kunmap_atomic (kaddr); -put_page (page); + nr_used =bitmap_weight (kaddr,PAGE_SIZE *BITS_PER_BYTE ); + nr_free -= nr_used; + vol->lcn_empty_bits_per_page[index] =PAGE_SIZE *BITS_PER_BYTE - nr_used; +kunmap_local (kaddr); +folio_unlock (folio); +folio_put (folio); }ntfs_debug ("Finished reading $Bitmap, last index = 0x%lx." , index -1 );/*
@@ -2506,14 +2004,45 @@ static s64 get_nr_free_clusters(ntfs_volume *vol)*/ if (vol->nr_clusters &63 ) nr_free +=64 - (vol->nr_clusters &63 ); -up_read (&vol->lcnbmp_lock); +/* If errors occurred we may well have gone below zero, fix this. */ if (nr_free <0 ) nr_free =0 ; +else +atomic64_set (&vol->free_clusters, nr_free); + +kfree (ra); +NVolSetFreeClusterKnown (vol); +wake_up_all (&vol->free_waitq);ntfs_debug ("Exiting." );return nr_free; } +/* +* @nr_clusters is the number of clusters requested for allocation. +* +* Return the number of clusters available for allocation within +* the range of @nr_clusters, which is counts that considered +* for delayed allocation. +*/ +s64 ntfs_available_clusters_count (struct ntfs_volume *vol,s64 nr_clusters) +{ +s64 free_clusters; + +/* wait event */ +if (!NVolFreeClusterKnown (vol)) +wait_event (vol->free_waitq,NVolFreeClusterKnown (vol)); + + free_clusters =atomic64_read (&vol->free_clusters) - +atomic64_read (&vol->dirty_clusters); +if (free_clusters <=0 ) +return -ENOSPC ; +else if (free_clusters < nr_clusters) + nr_clusters = free_clusters; + +return nr_clusters; +} +/** * __get_nr_free_mft_records - return the number of free inodes on a volume * @vol: ntfs volume for which to obtain free inode count
@@ -2531,33 +2060,50 @@ static s64 get_nr_free_clusters(ntfs_volume *vol)* * NOTE: Caller must hold mftbmp_lock rw_semaphore for reading or writing. */ -static unsigned long __get_nr_free_mft_records (ntfs_volume *vol, +static unsigned long __get_nr_free_mft_records (struct ntfs_volume *vol,s64 nr_free,const pgoff_t max_index) {struct address_space *mapping = vol->mftbmp_ino->i_mapping; -struct page *page; +struct folio *folio;pgoff_t index; +struct file_ra_state *ra;ntfs_debug ("Entering." ); + + ra =kzalloc (sizeof (*ra),GFP_NOFS ); +if (!ra) +return 0 ; + +file_ra_state_init (ra, mapping); +/* Use multiples of 4 bytes, thus max_size is PAGE_SIZE / 4. */ -ntfs_debug ("Reading $MFT/$BITMAP, max_index = 0x%lx, max_size = " -"0x%lx." , max_index,PAGE_SIZE /4 ); +ntfs_debug ("Reading $MFT/$BITMAP, max_index = 0x%lx, max_size = 0x%lx." , + max_index,PAGE_SIZE /4 );for (index =0 ; index < max_index; index++) {unsigned long *kaddr;/* -* Read the page from page cache, getting it from backing store +* Get folio from page cache, getting it from backing store * if necessary, and increment the use count. */ - page =read_mapping_page (mapping, index,NULL ); + folio =filemap_lock_folio (mapping, index); +if (IS_ERR (folio)) { +page_cache_sync_readahead (mapping, ra,NULL , + index, max_index - index); + folio =read_mapping_folio (mapping, index,NULL ); +if (!IS_ERR (folio)) +folio_lock (folio); + } +/* Ignore pages which errored synchronously. */ -if (IS_ERR (page)) { -ntfs_debug ("read_mapping_page() error. Skipping " -"page (index 0x%lx)." , index); +if (IS_ERR (folio)) { +ntfs_debug ("read_mapping_page() error. Skipping page (index 0x%lx)." , + index); nr_free -=PAGE_SIZE *8 ;continue ; } - kaddr =kmap_atomic (page); + + kaddr =kmap_local_folio (folio,0 );/* * Subtract the number of set bits. If this * is the last page and it is partial we don't really care as
@@ -2567,14 +2113,19 @@ static unsigned long __get_nr_free_mft_records(ntfs_volume *vol,*/ nr_free -=bitmap_weight (kaddr,PAGE_SIZE *BITS_PER_BYTE ); -kunmap_atomic (kaddr); -put_page (page); +kunmap_local (kaddr); +folio_unlock (folio); +folio_put (folio); }ntfs_debug ("Finished reading $MFT/$BITMAP, last index = 0x%lx." , index -1 );/* If errors occurred we may well have gone below zero, fix this. */ if (nr_free <0 ) nr_free =0 ; +else +atomic64_set (&vol->free_mft_records, nr_free); + +kfree (ra);ntfs_debug ("Exiting." );return nr_free; }
@@ -2601,47 +2152,46 @@ static int ntfs_statfs(struct dentry *dentry, struct kstatfs *sfs) {struct super_block *sb = dentry->d_sb;s64 size; -ntfs_volume *vol =NTFS_SB (sb); -ntfs_inode *mft_ni =NTFS_I (vol->mft_ino); -pgoff_t max_index; +struct ntfs_volume *vol =NTFS_SB (sb); +struct ntfs_inode *mft_ni =NTFS_I (vol->mft_ino);unsigned long flags;ntfs_debug ("Entering." );/* Type of filesystem. */ sfs->f_type =NTFS_SB_MAGIC ;/* Optimal transfer block size. */ - sfs->f_bsize =PAGE_SIZE ; + sfs->f_bsize = vol->cluster_size; +/* Fundamental file system block size, used as the unit. */ + sfs->f_frsize = vol->cluster_size; +/* * Total data blocks in filesystem in units of f_bsize and since * inodes are also stored in data blocs ($MFT is a file) this is just * the total clusters. */ - sfs->f_blocks = vol->nr_clusters << vol->cluster_size_bits >> -PAGE_SHIFT ; + sfs->f_blocks = vol->nr_clusters; + +/* wait event */ +if (!NVolFreeClusterKnown (vol)) +wait_event (vol->free_waitq,NVolFreeClusterKnown (vol)); +/* Free data blocks in filesystem in units of f_bsize. */
Lines of this file are not shown. View the raw message.
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.25.1
Part of the diff is not shown here. View the raw message.
Namjae Jeon
maintainerPATCH v3 5/14 ntfs: update directory operations
In reply to Namjae JeonThis updates the implementation of directory operations.
--- fs/ntfs/dir.c | 1639 +++++++++++++------------------- fs/ntfs/index.c | 2397 ++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 2700 insertions(+), 1336 deletions(-)
fs/ntfs/dir.c +664 -975
@@ -1,26 +1,24 @@// SPDX-License-Identifier: GPL-2.0-or-later -/* -* dir.c - NTFS kernel directory operations. Part of the Linux-NTFS project. +/** +* NTFS kernel directory operations. Part of the Linux-NTFS project. * * Copyright (c) 2001-2007 Anton Altaparmakov * Copyright (c) 2002 Richard Russon +* Copyright (c) 2025 LG Electronics Co., Ltd. */ -#include <linux/buffer_head.h> -#include <linux/slab.h> #include <linux/blkdev.h> #include "dir.h" -#include "aops.h" -#include "attrib.h" #include "mft.h" -#include "debug.h" #include "ntfs.h" +#include "index.h" +#include "reparse.h" -/* +/** * The little endian Unicode string $I30 as a global constant. */ -ntfschar I30 [5 ] = {cpu_to_le16 ('$' ),cpu_to_le16 ('I' ), +__le16 I30 [5 ] = {cpu_to_le16 ('$' ),cpu_to_le16 ('I' ),cpu_to_le16 ('3' ),cpu_to_le16 ('0' ),0 };/**
@@ -61,30 +59,29 @@ ntfschar I30[5] = { cpu_to_le16('$'), cpu_to_le16('I'),* locked whilst being accessed otherwise we may find a corrupt * page due to it being under ->writepage at the moment which * applies the mst protection fixups before writing out and then -* removes them again after the write is complete after which it +* removes them again after the write is complete after which it * unlocks the page. */ -MFT_REF ntfs_lookup_inode_by_name (ntfs_inode *dir_ni,const ntfschar *uname, -const int uname_len,ntfs_name **res) +u64 ntfs_lookup_inode_by_name (struct ntfs_inode *dir_ni,const __le16 *uname, +const int uname_len,struct ntfs_name **res) { -ntfs_volume *vol = dir_ni->vol; +struct ntfs_volume *vol = dir_ni->vol;struct super_block *sb = vol->sb; -MFT_RECORD *m; -INDEX_ROOT *ir; -INDEX_ENTRY *ie; -INDEX_ALLOCATION *ia; +struct inode *ia_vi =NULL ; +struct mft_record *m; +struct index_root *ir; +struct index_entry *ie; +struct index_block *ia;u8 *index_end;u64 mref; -ntfs_attr_search_ctx *ctx; +struct ntfs_attr_search_ctx *ctx;int err, rc; -VCN vcn, old_vcn; +s64 vcn, old_vcn;struct address_space *ia_mapping; -struct page *page; -u8 *kaddr; -ntfs_name *name =NULL ; +struct folio *folio; +u8 *kaddr =NULL ; +struct ntfs_name *name =NULL ; -BUG_ON (!S_ISDIR (VFS_I (dir_ni)->i_mode)); -BUG_ON (NInoAttr (dir_ni));/* Get hold of the mft record for the directory. */ m =map_mft_record (dir_ni);if (IS_ERR (m)) {
@@ -102,30 +99,30 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname, 0, ctx);if (unlikely (err)) {if (err == -ENOENT ) { -ntfs_error (sb,"Index root attribute missing in " -"directory inode 0x%lx." , - dir_ni->mft_no); +ntfs_error (sb, +"Index root attribute missing in directory inode 0x%lx." , + dir_ni->mft_no); err = -EIO ; } goto err_out; }/* Get to the index root value (it's been verified in read_inode). */ - ir = (INDEX_ROOT *)((u8 *)ctx->attr + + ir = (struct index_root *)((u8 *)ctx->attr +le16_to_cpu (ctx->attr->data.resident.value_offset)); - index_end = (u8 *)&ir->index +le32_to_cpu (ir->index.index_length); + index_end = (u8 *)&ir->index +le32_to_cpu (ir->index.index_length);/* The first index entry. */ - ie = (INDEX_ENTRY *)((u8 *)&ir->index + + ie = (struct index_entry *)((u8 *)&ir->index +le32_to_cpu (ir->index.entries_offset));/* * Loop until we exceed valid memory (corruption case) or until we * reach the last entry. */ -for (;; ie = (INDEX_ENTRY *)((u8 *)ie +le16_to_cpu (ie->length))) { +for (;; ie = (struct index_entry *)((u8 *)ie +le16_to_cpu (ie->length))) {/* Bounds checks. */ -if ((u8 *)ie < (u8 *)ctx->mrec || (u8 *)ie + -sizeof (INDEX_ENTRY_HEADER ) > index_end || - (u8 *)ie +le16_to_cpu (ie->key_length) > - index_end) +if ((u8 *)ie < (u8 *)ctx->mrec || + (u8 *)ie +sizeof (struct index_entry_header ) > index_end || + (u8 *)ie +sizeof (struct index_entry_header ) +le16_to_cpu (ie->key_length) > + index_end || (u8 *)ie +le16_to_cpu (ie->length) > index_end) goto dir_err_out;/* * The last entry cannot contain a name. It can however contain
@@ -133,6 +130,13 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,*/ if (ie->flags &INDEX_ENTRY_END )break ; +/* Key length should not be zero if it is not last entry. */ +if (!ie->key_length) + goto dir_err_out; +/* Check the consistency of an index entry */ +if (ntfs_index_entry_inconsistent (NULL , vol, ie,COLLATION_FILE_NAME , + dir_ni->mft_no)) + goto dir_err_out;/* * We perform a case sensitive comparison and if that matches * we are done and return the mft reference of the inode (i.e.
@@ -141,7 +145,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* returning. */ if (ntfs_are_names_equal (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, + (__le16 *)&ie->key.file_name.file_name, ie->key.file_name.file_name_length,CASE_SENSITIVE , vol->upcase, vol->upcase_len)) { found_it:
@@ -157,7 +161,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,*/ if (ie->key.file_name.file_name_type ==FILE_NAME_DOS ) {if (!name) { - name =kmalloc (sizeof (ntfs_name), + name =kmalloc (sizeof (struct ntfs_name ),GFP_NOFS );if (!name) { err = -ENOMEM ;
@@ -188,30 +192,26 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* only cache the mft reference and the file name type (we set * the name length to zero for simplicity). */ -if (!NVolCaseSensitive (vol) && - ie->key.file_name.file_name_type && -ntfs_are_names_equal (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, -IGNORE_CASE , vol->upcase, vol->upcase_len)) { -int name_size =sizeof (ntfs_name); +if ((!NVolCaseSensitive (vol) || + ie->key.file_name.file_name_type ==FILE_NAME_DOS ) && +ntfs_are_names_equal (uname, uname_len, + (__le16 *)&ie->key.file_name.file_name, + ie->key.file_name.file_name_length, +IGNORE_CASE , vol->upcase, + vol->upcase_len)) { +int name_size =sizeof (struct ntfs_name );u8 type = ie->key.file_name.file_name_type;u8 len = ie->key.file_name.file_name_length;/* Only one case insensitive matching name allowed. */ if (name) { -ntfs_error (sb,"Found already allocated name " -"in phase 1. Please run chkdsk " -"and if that doesn't find any " -"errors please report you saw " -"this message to " -"linux-ntfs-dev@lists." -"sourceforge.net." ); +ntfs_error (sb, +"Found already allocated name in phase 1. Please run chkdsk" ); goto dir_err_out; }if (type !=FILE_NAME_DOS ) - name_size += len *sizeof (ntfschar); + name_size += len *sizeof (__le16); name =kmalloc (name_size,GFP_NOFS );if (!name) { err = -ENOMEM ;
@@ -222,7 +222,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,if (type !=FILE_NAME_DOS ) { name->len = len;memcpy (name->name, ie->key.file_name.file_name, - len *sizeof (ntfschar)); + len *sizeof (__le16)); }else name->len =0 ; *res = name;
@@ -232,7 +232,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* know which way in the B+tree we have to go. */ rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, + (__le16 *)&ie->key.file_name.file_name, ie->key.file_name.file_name_length,1 ,IGNORE_CASE , vol->upcase, vol->upcase_len);/*
@@ -251,7 +251,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* collation. */ rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, + (__le16 *)&ie->key.file_name.file_name, ie->key.file_name.file_name_length,1 ,CASE_SENSITIVE , vol->upcase, vol->upcase_len);if (rc ==-1 )
@@ -281,109 +281,117 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname, err = -ENOENT ; goto err_out; }/* Child node present, descend into it. */ -/* Consistency check: Verify that an index allocation exists. */ -if (!NInoIndexAllocPresent (dir_ni)) { -ntfs_error (sb,"No index allocation attribute but index entry " -"requires one. Directory inode 0x%lx is " -"corrupt or driver bug." , dir_ni->mft_no); - goto err_out; - } +/* Get the starting vcn of the index_block holding the child node. */ - vcn =sle64_to_cpup ((sle64 *)((u8 *)ie +le16_to_cpu (ie->length) -8 )); - ia_mapping =VFS_I (dir_ni)->i_mapping; + vcn =le64_to_cpup ((__le64 *)((u8 *)ie +le16_to_cpu (ie->length) -8 )); +/* * We are done with the index root and the mft record. Release them, -* otherwise we deadlock with ntfs_map_page(). +* otherwise we deadlock with read_mapping_folio(). */ ntfs_attr_put_search_ctx (ctx);unmap_mft_record (dir_ni); m =NULL ; ctx =NULL ; + + ia_vi =ntfs_index_iget (VFS_I (dir_ni),I30 ,4 ); +if (IS_ERR (ia_vi)) { + err =PTR_ERR (ia_vi); + goto err_out; + } + + ia_mapping = ia_vi->i_mapping; descend_into_child_node:/* * Convert vcn to index into the index allocation attribute in units * of PAGE_SIZE and map the page cache page, reading it from * disk if necessary. */ - page =ntfs_map_page (ia_mapping, vcn << - dir_ni->itype.index.vcn_size_bits >>PAGE_SHIFT ); -if (IS_ERR (page)) { + folio =read_mapping_folio (ia_mapping, vcn << + dir_ni->itype.index.vcn_size_bits >>PAGE_SHIFT ,NULL ); +if (IS_ERR (folio)) {ntfs_error (sb,"Failed to map directory index page, error %ld." , - -PTR_ERR (page)); - err =PTR_ERR (page); + -PTR_ERR (folio)); + err =PTR_ERR (folio); goto err_out; } -lock_page (page); - kaddr = (u8 *)page_address (page); + +folio_lock (folio); + kaddr =kmalloc (PAGE_SIZE ,GFP_NOFS ); +if (!kaddr) { + err = -ENOMEM ; +folio_unlock (folio); +folio_put (folio); + goto unm_err_out; + } + +memcpy_from_folio (kaddr, folio,0 ,PAGE_SIZE ); +post_read_mst_fixup ((struct ntfs_record *)kaddr,PAGE_SIZE ); +folio_unlock (folio); +folio_put (folio); fast_descend_into_child_node:/* Get to the index allocation block. */ - ia = (INDEX_ALLOCATION *)(kaddr + ((vcn << + ia = (struct index_block *)(kaddr + ((vcn << dir_ni->itype.index.vcn_size_bits) & ~PAGE_MASK ));/* Bounds checks. */ -if ((u8 *)ia < kaddr || (u8 *)ia > kaddr +PAGE_SIZE ) { -ntfs_error (sb,"Out of bounds check failed. Corrupt directory " -"inode 0x%lx or driver bug." , dir_ni->mft_no); +if ((u8 *)ia < kaddr || (u8 *)ia > kaddr +PAGE_SIZE ) { +ntfs_error (sb, +"Out of bounds check failed. Corrupt directory inode 0x%lx or driver bug." , + dir_ni->mft_no); goto unm_err_out; }/* Catch multi sector transfer fixup errors. */ if (unlikely (!ntfs_is_indx_record (ia->magic))) { -ntfs_error (sb,"Directory index record with vcn 0x%llx is " -"corrupt. Corrupt inode 0x%lx. Run chkdsk." , - (unsigned long long )vcn, dir_ni->mft_no); +ntfs_error (sb, +"Directory index record with vcn 0x%llx is corrupt. Corrupt inode 0x%lx. Run chkdsk." , + (unsigned long long )vcn, dir_ni->mft_no); goto unm_err_out; } -if (sle64_to_cpu (ia->index_block_vcn) != vcn) { -ntfs_error (sb,"Actual VCN (0x%llx) of index buffer is " -"different from expected VCN (0x%llx). " -"Directory inode 0x%lx is corrupt or driver " -"bug." , (unsigned long long ) -sle64_to_cpu (ia->index_block_vcn), - (unsigned long long )vcn, dir_ni->mft_no); +if (le64_to_cpu (ia->index_block_vcn) != vcn) { +ntfs_error (sb, +"Actual VCN (0x%llx) of index buffer is different from expected VCN (0x%llx). Directory inode 0x%lx is corrupt or driver bug." , + (unsigned long long )le64_to_cpu (ia->index_block_vcn), + (unsigned long long )vcn, dir_ni->mft_no); goto unm_err_out; }if (le32_to_cpu (ia->index.allocated_size) +0x18 != dir_ni->itype.index.block_size) { -ntfs_error (sb,"Index buffer (VCN 0x%llx) of directory inode " -"0x%lx has a size (%u) differing from the " -"directory specified size (%u). Directory " -"inode is corrupt or driver bug." , - (unsigned long long )vcn, dir_ni->mft_no, -le32_to_cpu (ia->index.allocated_size) +0x18 , - dir_ni->itype.index.block_size); +ntfs_error (sb, +"Index buffer (VCN 0x%llx) of directory inode 0x%lx has a size (%u) differing from the directory specified size (%u). Directory inode is corrupt or driver bug." , + (unsigned long long )vcn, dir_ni->mft_no, +le32_to_cpu (ia->index.allocated_size) +0x18 , + dir_ni->itype.index.block_size); goto unm_err_out; } - index_end = (u8 *)ia + dir_ni->itype.index.block_size; + index_end = (u8 *)ia + dir_ni->itype.index.block_size;if (index_end > kaddr +PAGE_SIZE ) { -ntfs_error (sb,"Index buffer (VCN 0x%llx) of directory inode " -"0x%lx crosses page boundary. Impossible! " -"Cannot access! This is probably a bug in the " -"driver." , (unsigned long long )vcn, - dir_ni->mft_no); +ntfs_error (sb, +"Index buffer (VCN 0x%llx) of directory inode 0x%lx crosses page boundary. Impossible! Cannot access! This is probably a bug in the driver." , + (unsigned long long )vcn, dir_ni->mft_no); goto unm_err_out; } - index_end = (u8 *)&ia->index +le32_to_cpu (ia->index.index_length); -if (index_end > (u8 *)ia + dir_ni->itype.index.block_size) { -ntfs_error (sb,"Size of index buffer (VCN 0x%llx) of directory " -"inode 0x%lx exceeds maximum size." , - (unsigned long long )vcn, dir_ni->mft_no); + index_end = (u8 *)&ia->index +le32_to_cpu (ia->index.index_length); +if (index_end > (u8 *)ia + dir_ni->itype.index.block_size) { +ntfs_error (sb, +"Size of index buffer (VCN 0x%llx) of directory inode 0x%lx exceeds maximum size." , + (unsigned long long )vcn, dir_ni->mft_no); goto unm_err_out; }/* The first index entry. */ - ie = (INDEX_ENTRY *)((u8 *)&ia->index + + ie = (struct index_entry *)((u8 *)&ia->index +le32_to_cpu (ia->index.entries_offset));/* * Iterate similar to above big loop but applied to index buffer, thus * loop until we exceed valid memory (corruption case) or until we * reach the last entry. */ -for (;; ie = (INDEX_ENTRY *)((u8 *)ie +le16_to_cpu (ie->length))) { -/* Bounds check. */ -if ((u8 *)ie < (u8 *)ia || (u8 *)ie + -sizeof (INDEX_ENTRY_HEADER ) > index_end || - (u8 *)ie +le16_to_cpu (ie->key_length) > - index_end) { -ntfs_error (sb,"Index entry out of bounds in " -"directory inode 0x%lx." , +for (;; ie = (struct index_entry *)((u8 *)ie +le16_to_cpu (ie->length))) { +/* Bounds checks. */ +if ((u8 *)ie < (u8 *)ia || + (u8 *)ie +sizeof (struct index_entry_header ) > index_end || + (u8 *)ie +sizeof (struct index_entry_header ) +le16_to_cpu (ie->key_length) > + index_end || (u8 *)ie +le16_to_cpu (ie->length) > index_end) { +ntfs_error (sb,"Index entry out of bounds in directory inode 0x%lx." , dir_ni->mft_no); goto unm_err_out; }
@@ -393,6 +401,13 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,*/ if (ie->flags &INDEX_ENTRY_END )break ; +/* Key length should not be zero if it is not last entry. */ +if (!ie->key_length) + goto unm_err_out; +/* Check the consistency of an index entry */ +if (ntfs_index_entry_inconsistent (NULL , vol, ie,COLLATION_FILE_NAME , + dir_ni->mft_no)) + goto unm_err_out;/* * We perform a case sensitive comparison and if that matches * we are done and return the mft reference of the inode (i.e.
@@ -401,7 +416,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* returning. */ if (ntfs_are_names_equal (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, + (__le16 *)&ie->key.file_name.file_name, ie->key.file_name.file_name_length,CASE_SENSITIVE , vol->upcase, vol->upcase_len)) { found_it2:
@@ -417,7 +432,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,*/ if (ie->key.file_name.file_name_type ==FILE_NAME_DOS ) {if (!name) { - name =kmalloc (sizeof (ntfs_name), + name =kmalloc (sizeof (struct ntfs_name ),GFP_NOFS );if (!name) { err = -ENOMEM ;
@@ -434,8 +449,8 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname, *res =NULL ; } mref =le64_to_cpu (ie->data.dir.indexed_file); -unlock_page (page); -ntfs_unmap_page (page); +kfree (kaddr); +iput (ia_vi);return mref; }/*
@@ -448,32 +463,27 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* only cache the mft reference and the file name type (we set * the name length to zero for simplicity). */ -if (!NVolCaseSensitive (vol) && - ie->key.file_name.file_name_type && -ntfs_are_names_equal (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, -IGNORE_CASE , vol->upcase, vol->upcase_len)) { -int name_size =sizeof (ntfs_name); +if ((!NVolCaseSensitive (vol) || + ie->key.file_name.file_name_type ==FILE_NAME_DOS ) && +ntfs_are_names_equal (uname, uname_len, + (__le16 *)&ie->key.file_name.file_name, + ie->key.file_name.file_name_length, +IGNORE_CASE , vol->upcase, + vol->upcase_len)) { +int name_size =sizeof (struct ntfs_name );u8 type = ie->key.file_name.file_name_type;u8 len = ie->key.file_name.file_name_length;/* Only one case insensitive matching name allowed. */ if (name) { -ntfs_error (sb,"Found already allocated name " -"in phase 2. Please run chkdsk " -"and if that doesn't find any " -"errors please report you saw " -"this message to " -"linux-ntfs-dev@lists." -"sourceforge.net." ); -unlock_page (page); -ntfs_unmap_page (page); +ntfs_error (sb, +"Found already allocated name in phase 2. Please run chkdsk" ); +kfree (kaddr); goto dir_err_out; }if (type !=FILE_NAME_DOS ) - name_size += len *sizeof (ntfschar); + name_size += len *sizeof (__le16); name =kmalloc (name_size,GFP_NOFS );if (!name) { err = -ENOMEM ;
@@ -484,7 +494,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,if (type !=FILE_NAME_DOS ) { name->len = len;memcpy (name->name, ie->key.file_name.file_name, - len *sizeof (ntfschar)); + len *sizeof (__le16)); }else name->len =0 ; *res = name;
@@ -494,7 +504,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* know which way in the B+tree we have to go. */ rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, + (__le16 *)&ie->key.file_name.file_name, ie->key.file_name.file_name_length,1 ,IGNORE_CASE , vol->upcase, vol->upcase_len);/*
@@ -513,7 +523,7 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* collation. */ rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, + (__le16 *)&ie->key.file_name.file_name, ie->key.file_name.file_name_length,1 ,CASE_SENSITIVE , vol->upcase, vol->upcase_len);if (rc ==-1 )
@@ -533,29 +543,29 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,*/ if (ie->flags &INDEX_ENTRY_NODE ) {if ((ia->index.flags &NODE_MASK ) ==LEAF_NODE ) { -ntfs_error (sb,"Index entry with child node found in " -"a leaf node in directory inode 0x%lx." , - dir_ni->mft_no); +ntfs_error (sb, +"Index entry with child node found in a leaf node in directory inode 0x%lx." , + dir_ni->mft_no); goto unm_err_out; }/* Child node present, descend into it. */ old_vcn = vcn; - vcn =sle64_to_cpup ((sle64 *)((u8 *)ie + + vcn =le64_to_cpup ((__le64 *)((u8 *)ie +le16_to_cpu (ie->length) -8 ));if (vcn >=0 ) { -/* If vcn is in the same page cache page as old_vcn we -* recycle the mapped page. */ -if (old_vcn << vol->cluster_size_bits >> -PAGE_SHIFT == vcn << - vol->cluster_size_bits >> -PAGE_SHIFT ) +/* +* If vcn is in the same page cache page as old_vcn we +* recycle the mapped page. +*/ +if (NTFS_CLU_TO_PIDX (vol, old_vcn) == +NTFS_CLU_TO_PIDX (vol, vcn)) goto fast_descend_into_child_node; -unlock_page (page); -ntfs_unmap_page (page); +kfree (kaddr); + kaddr =NULL ; goto descend_into_child_node; } -ntfs_error (sb,"Negative child node vcn in directory inode " -"0x%lx." , dir_ni->mft_no); +ntfs_error (sb,"Negative child node vcn in directory inode 0x%lx." , + dir_ni->mft_no); goto unm_err_out; }/*
@@ -564,15 +574,14 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,* associated with it. */ if (name) { -unlock_page (page); -ntfs_unmap_page (page); +kfree (kaddr); +iput (ia_vi);return name->mref; }ntfs_debug ("Entry not found." ); err = -ENOENT ; unm_err_out: -unlock_page (page); -ntfs_unmap_page (page); +kfree (kaddr); err_out:if (!err) err = -EIO ;
@@ -580,858 +589,495 @@ MFT_REF ntfs_lookup_inode_by_name(ntfs_inode *dir_ni, const ntfschar *uname,ntfs_attr_put_search_ctx (ctx);if (m)unmap_mft_record (dir_ni); -if (name) { -kfree (name); - *res =NULL ; - } +kfree (name); + *res =NULL ; +if (ia_vi && !IS_ERR (ia_vi)) +iput (ia_vi);return ERR_MREF (err); dir_err_out:ntfs_error (sb,"Corrupt directory. Aborting lookup." ); goto err_out; } -#if 0 - -// TODO: (AIA) -// The algorithm embedded in this code will be required for the time when we -// want to support adding of entries to directories, where we require correct -// collation of file names in order not to cause corruption of the filesystem. -/** -* ntfs_lookup_inode_by_name - find an inode in a directory given its name -* @dir_ni: ntfs inode of the directory in which to search for the name -* @uname: Unicode name for which to search in the directory -* @uname_len: length of the name @uname in Unicode characters +* ntfs_filldir - ntfs specific filldir method +* @vol: current ntfs volume +* @ndir: ntfs inode of current directory +* @ia_page: page in which the index allocation buffer @ie is in resides +* @ie: current index entry +* @name: buffer to use for the converted name +* @actor: what to feed the entries to * -* Look for an inode with name @uname in the directory with inode @dir_ni. -* ntfs_lookup_inode_by_name() walks the contents of the directory looking for -* the Unicode name. If the name is found in the directory, the corresponding -* inode number (>= 0) is returned as a mft reference in cpu format, i.e. it -* is a 64-bit number containing the sequence number. +* Convert the Unicode @name to the loaded NLS and pass it to the @filldir +* callback. * -* On error, a negative value is returned corresponding to the error code. In -* particular if the inode is not found -ENOENT is returned. Note that you -* can't just check the return value for being negative, you have to check the -* inode number for being negative which you can extract using MREC(return -* value). +* If @ia_page is not NULL it is the locked page containing the index +* allocation block containing the index entry @ie. * -* Note, @uname_len does not include the (optional) terminating NULL character. +* Note, we drop (and then reacquire) the page lock on @ia_page across the +* @filldir() call otherwise we would deadlock with NFSd when it calls ->lookup +* since ntfs_lookup() will lock the same page. As an optimization, we do not +* retake the lock if we are returning a non-zero value as ntfs_readdir() +* would need to drop the lock immediately anyway. */ -u64 ntfs_lookup_inode_by_name (ntfs_inode *dir_ni,const ntfschar *uname, -const int uname_len) +static inline int ntfs_filldir (struct ntfs_volume *vol, +struct ntfs_inode *ndir,struct page *ia_page,struct index_entry *ie, +u8 *name,struct dir_context *actor) { -ntfs_volume *vol = dir_ni->vol; -struct super_block *sb = vol->sb; -MFT_RECORD *m; -INDEX_ROOT *ir; -INDEX_ENTRY *ie; -INDEX_ALLOCATION *ia; -u8 *index_end; -u64 mref; -ntfs_attr_search_ctx *ctx; -int err, rc; -IGNORE_CASE_BOOL ic; -VCN vcn, old_vcn; -struct address_space *ia_mapping; -struct page *page; -u8 *kaddr; +unsigned long mref; +int name_len; +unsigned int dt_type; +u8 name_type; -/* Get hold of the mft record for the directory. */ - m =map_mft_record (dir_ni); -if (IS_ERR (m)) { -ntfs_error (sb,"map_mft_record() failed with error code %ld." , - -PTR_ERR (m)); -return ERR_MREF (PTR_ERR (m)); + name_type = ie->key.file_name.file_name_type; +if (name_type ==FILE_NAME_DOS ) { +ntfs_debug ("Skipping DOS name space entry." ); +return 0 ; } - ctx =ntfs_attr_get_search_ctx (dir_ni, m); -if (!ctx) { - err = -ENOMEM ; - goto err_out; +if (MREF_LE (ie->data.dir.indexed_file) == FILE_root) { +ntfs_debug ("Skipping root directory self reference entry." ); +return 0 ; } -/* Find the index root attribute in the mft record. */ - err =ntfs_attr_lookup (AT_INDEX_ROOT ,I30 ,4 ,CASE_SENSITIVE ,0 ,NULL , -0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) { -ntfs_error (sb,"Index root attribute missing in " -"directory inode 0x%lx." , - dir_ni->mft_no); - err = -EIO ; - } - goto err_out; +if (MREF_LE (ie->data.dir.indexed_file) < FILE_first_user && + !NVolShowSystemFiles (vol)) { +ntfs_debug ("Skipping system file." ); +return 0 ; } -/* Get to the index root value (it's been verified in read_inode). */ - ir = (INDEX_ROOT *)((u8 *)ctx->attr + -le16_to_cpu (ctx->attr->data.resident.value_offset)); - index_end = (u8 *)&ir->index +le32_to_cpu (ir->index.index_length); -/* The first index entry. */ - ie = (INDEX_ENTRY *)((u8 *)&ir->index + -le32_to_cpu (ir->index.entries_offset)); +if (!NVolShowHiddenFiles (vol) && + (ie->key.file_name.file_attributes &FILE_ATTR_HIDDEN )) { +ntfs_debug ("Skipping hidden file." ); +return 0 ; + } + + name_len =ntfs_ucstonls (vol, (__le16 *)&ie->key.file_name.file_name, + ie->key.file_name.file_name_length, &name, +NTFS_MAX_NAME_LEN *NLS_MAX_CHARSET_SIZE +1 ); +if (name_len <=0 ) { +ntfs_warning (vol->sb,"Skipping unrepresentable inode 0x%llx." , + (long long )MREF_LE (ie->data.dir.indexed_file)); +return 0 ; + } + + mref =MREF_LE (ie->data.dir.indexed_file); +if (ie->key.file_name.file_attributes & +FILE_ATTR_DUP_FILE_NAME_INDEX_PRESENT ) + dt_type =DT_DIR ; +else if (ie->key.file_name.file_attributes &FILE_ATTR_REPARSE_POINT ) + dt_type =ntfs_reparse_tag_dt_types (vol, mref); +else + dt_type =DT_REG ; +/* -* Loop until we exceed valid memory (corruption case) or until we -* reach the last entry. +* Drop the page lock otherwise we deadlock with NFS when it calls +* ->lookup since ntfs_lookup() will lock the same page. */ -for (;; ie = (INDEX_ENTRY *)((u8 *)ie +le16_to_cpu (ie->length))) { -/* Bounds checks. */ -if ((u8 *)ie < (u8 *)ctx->mrec || (u8 *)ie + -sizeof (INDEX_ENTRY_HEADER ) > index_end || - (u8 *)ie +le16_to_cpu (ie->key_length) > - index_end) - goto dir_err_out; -/* -* The last entry cannot contain a name. It can however contain -* a pointer to a child node in the B+tree so we just break out. -*/ -if (ie->flags &INDEX_ENTRY_END ) -break ; -/* -* If the current entry has a name type of POSIX, the name is -* case sensitive and not otherwise. This has the effect of us -* not being able to access any POSIX file names which collate -* after the non-POSIX one when they only differ in case, but -* anyone doing screwy stuff like that deserves to burn in -* hell... Doing that kind of stuff on NT4 actually causes -* corruption on the partition even when using SP6a and Linux -* is not involved at all. -*/ - ic = ie->key.file_name.file_name_type ?IGNORE_CASE : -CASE_SENSITIVE ; -/* -* If the names match perfectly, we are done and return the -* mft reference of the inode (i.e. the inode number together -* with the sequence number for consistency checking. We -* convert it to cpu format before returning. -*/ -if (ntfs_are_names_equal (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, ic, - vol->upcase, vol->upcase_len)) { -found_it: - mref =le64_to_cpu (ie->data.dir.indexed_file); -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (dir_ni); -return mref; +if (ia_page) +unlock_page (ia_page); +ntfs_debug ("Calling filldir for %s with len %i, fpos 0x%llx, inode 0x%lx, DT_%s." , + name, name_len, actor->pos, mref, dt_type ==DT_DIR ?"DIR" :"REG" ); +if (!dir_emit (actor, name, name_len, mref, dt_type)) +return 1 ; +/* Relock the page but not if we are aborting ->readdir. */ +if (ia_page) +lock_page (ia_page); +return 0 ; +} + +struct ntfs_file_private { +void *key; +__le16 key_length; +bool end_in_iterate; +loff_t curr_pos; +}; + +struct ntfs_index_ra { +unsigned long start_index; +unsigned int count; +struct rb_node rb_node; +}; + +static void ntfs_insert_rb (struct ntfs_index_ra *nir,struct rb_root *root) +{ +struct rb_node **new = &root->rb_node, *parent =NULL ; +struct ntfs_index_ra *cnir; + +while (*new) { + parent = *new; + cnir = rb_entry(parent, struct ntfs_index_ra, rb_node); +if (nir->start_index < cnir->start_index) + new = &parent->rb_left; +else if (nir->start_index >= cnir->start_index + cnir->count) + new = &parent->rb_right; +else { +pr_err ("nir start index : %ld, count : %d, cnir start_index : %ld, count : %d\n" , + nir->start_index, nir->count, cnir->start_index, cnir->count); +return ; } -/* -* Not a perfect match, need to do full blown collation so we -* know which way in the B+tree we have to go. -*/ - rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length,1 , -IGNORE_CASE , vol->upcase, vol->upcase_len); -/* -* If uname collates before the name of the current entry, there -* is definitely no such name in this index but we might need to -* descend into the B+tree so we just break out of the loop. -*/ -if (rc ==-1 ) -break ; -/* The names are not equal, continue the search. */ -if (rc) -continue ; -/* -* Names match with case insensitive comparison, now try the -* case sensitive comparison, which is required for proper -* collation. -*/ - rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length,1 , -CASE_SENSITIVE , vol->upcase, vol->upcase_len); -if (rc ==-1 ) -break ; -if (rc) -continue ; -/* -* Perfect match, this will never happen as the -* ntfs_are_names_equal() call will have gotten a match but we -* still treat it correctly. -*/ - goto found_it; } -/* -* We have finished with this index without success. Check for the -* presence of a child node. -*/ -if (!(ie->flags &INDEX_ENTRY_NODE )) { -/* No child node, return -ENOENT. */ - err = -ENOENT ; - goto err_out; - }/* Child node present, descend into it. */ -/* Consistency check: Verify that an index allocation exists. */ -if (!NInoIndexAllocPresent (dir_ni)) { -ntfs_error (sb,"No index allocation attribute but index entry " -"requires one. Directory inode 0x%lx is " -"corrupt or driver bug." , dir_ni->mft_no); - goto err_out; + +rb_link_node (&nir->rb_node, parent, new); +rb_insert_color (&nir->rb_node, root); +} + +static int ntfs_ia_blocks_readahead (struct ntfs_inode *ia_ni,loff_t pos) +{ +unsigned long dir_start_index, dir_end_index; +struct inode *ia_vi =VFS_I (ia_ni); +struct file_ra_state *dir_ra; + + dir_end_index = (i_size_read (ia_vi) +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + dir_start_index = (pos +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + +if (dir_start_index >= dir_end_index) +return 0 ; + + dir_ra =kzalloc (sizeof (*dir_ra),GFP_NOFS ); +if (!dir_ra) +return -ENOMEM ; + +file_ra_state_init (dir_ra, ia_vi->i_mapping); + dir_end_index = (i_size_read (ia_vi) +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + dir_start_index = (pos +PAGE_SIZE -1 ) >>PAGE_SHIFT ; + dir_ra->ra_pages = dir_end_index - dir_start_index; +page_cache_sync_readahead (ia_vi->i_mapping, dir_ra,NULL , + dir_start_index, dir_end_index - dir_start_index); +kfree (dir_ra); + +return 0 ; +} + +static int ntfs_readdir (struct file *file,struct dir_context *actor) +{ +struct inode *vdir =file_inode (file); +struct super_block *sb = vdir->i_sb; +struct ntfs_inode *ndir =NTFS_I (vdir); +struct ntfs_volume *vol =NTFS_SB (sb); +struct ntfs_attr_search_ctx *ctx =NULL ; +struct ntfs_index_context *ictx =NULL ; +u8 *name; +struct index_root *ir; +struct index_entry *next =NULL ; +struct ntfs_file_private *private =NULL ; +int err =0 ; +loff_t ie_pos =2 ;/* initialize it with dot and dotdot size */ +struct ntfs_index_ra *nir =NULL ; +unsigned long index; +struct rb_root ra_root =RB_ROOT ; +struct file_ra_state *ra; + +ntfs_debug ("Entering for inode 0x%lx, fpos 0x%llx." , + vdir->i_ino, actor->pos); + +if (file->private_data) { + private = file->private_data; + +if (actor->pos != private->curr_pos) { +/* +* If actor->pos is different from the previous passed +* one, Discard the private->key and fill dirent buffer +* with linear lookup. +*/ +kfree (private->key); + private->key =NULL ; + private->end_in_iterate = false; + }else if (private->end_in_iterate) { +kfree (private->key); +kfree (file->private_data); + file->private_data =NULL ; +return 0 ; + } } -/* Get the starting vcn of the index_block holding the child node. */ - vcn =sle64_to_cpup ((u8 *)ie +le16_to_cpu (ie->length) -8 ); - ia_mapping =VFS_I (dir_ni)->i_mapping; -/* -* We are done with the index root and the mft record. Release them, -* otherwise we deadlock with ntfs_map_page(). -*/ -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (dir_ni); - m =NULL ; - ctx =NULL ; -descend_into_child_node: + +/* Emulate . and .. for all directories. */ +if (!dir_emit_dots (file, actor)) +return 0 ; +/* -* Convert vcn to index into the index allocation attribute in units -* of PAGE_SIZE and map the page cache page, reading it from -* disk if necessary. +* Allocate a buffer to store the current name being processed +* converted to format determined by current NLS. */ - page =ntfs_map_page (ia_mapping, vcn << - dir_ni->itype.index.vcn_size_bits >>PAGE_SHIFT ); -if (IS_ERR (page)) { -ntfs_error (sb,"Failed to map directory index page, error %ld." , - -PTR_ERR (page)); - err =PTR_ERR (page); - goto err_out; + name =kmalloc (NTFS_MAX_NAME_LEN *NLS_MAX_CHARSET_SIZE +1 ,GFP_NOFS ); +if (unlikely (!name)) +return -ENOMEM ; + +mutex_lock_nested (&ndir->mrec_lock,NTFS_INODE_MUTEX_PARENT ); + ictx =ntfs_index_ctx_get (ndir,I30 ,4 ); +if (!ictx) { +kfree (name); +mutex_unlock (&ndir->mrec_lock); +return -ENOMEM ; } -lock_page (page); - kaddr = (u8 *)page_address (page); -fast_descend_into_child_node: -/* Get to the index allocation block. */ - ia = (INDEX_ALLOCATION *)(kaddr + ((vcn << - dir_ni->itype.index.vcn_size_bits) & ~PAGE_MASK )); -/* Bounds checks. */ -if ((u8 *)ia < kaddr || (u8 *)ia > kaddr +PAGE_SIZE ) { -ntfs_error (sb,"Out of bounds check failed. Corrupt directory " -"inode 0x%lx or driver bug." , dir_ni->mft_no); - goto unm_err_out; - } -/* Catch multi sector transfer fixup errors. */ -if (unlikely (!ntfs_is_indx_record (ia->magic))) { -ntfs_error (sb,"Directory index record with vcn 0x%llx is " -"corrupt. Corrupt inode 0x%lx. Run chkdsk." , - (unsigned long long )vcn, dir_ni->mft_no); - goto unm_err_out; - } -if (sle64_to_cpu (ia->index_block_vcn) != vcn) { -ntfs_error (sb,"Actual VCN (0x%llx) of index buffer is " -"different from expected VCN (0x%llx). " -"Directory inode 0x%lx is corrupt or driver " -"bug." , (unsigned long long ) -sle64_to_cpu (ia->index_block_vcn), - (unsigned long long )vcn, dir_ni->mft_no); - goto unm_err_out; - } -if (le32_to_cpu (ia->index.allocated_size) +0x18 != - dir_ni->itype.index.block_size) { -ntfs_error (sb,"Index buffer (VCN 0x%llx) of directory inode " -"0x%lx has a size (%u) differing from the " -"directory specified size (%u). Directory " -"inode is corrupt or driver bug." , - (unsigned long long )vcn, dir_ni->mft_no, -le32_to_cpu (ia->index.allocated_size) +0x18 , - dir_ni->itype.index.block_size); - goto unm_err_out; - } - index_end = (u8 *)ia + dir_ni->itype.index.block_size; -if (index_end > kaddr +PAGE_SIZE ) { -ntfs_error (sb,"Index buffer (VCN 0x%llx) of directory inode " -"0x%lx crosses page boundary. Impossible! " -"Cannot access! This is probably a bug in the " -"driver." , (unsigned long long )vcn, - dir_ni->mft_no); - goto unm_err_out; - } - index_end = (u8 *)&ia->index +le32_to_cpu (ia->index.index_length); -if (index_end > (u8 *)ia + dir_ni->itype.index.block_size) { -ntfs_error (sb,"Size of index buffer (VCN 0x%llx) of directory " -"inode 0x%lx exceeds maximum size." , - (unsigned long long )vcn, dir_ni->mft_no); - goto unm_err_out; + + ra =kzalloc (sizeof (struct file_ra_state ),GFP_NOFS ); +if (!ra) { +kfree (name); +ntfs_index_ctx_put (ictx); +mutex_unlock (&ndir->mrec_lock); +return -ENOMEM ; } -/* The first index entry. */ - ie = (INDEX_ENTRY *)((u8 *)&ia->index + -le32_to_cpu (ia->index.entries_offset)); -/* -* Iterate similar to above big loop but applied to index buffer, thus -* loop until we exceed valid memory (corruption case) or until we -* reach the last entry. -*/ -for (;; ie = (INDEX_ENTRY *)((u8 *)ie +le16_to_cpu (ie->length))) { -/* Bounds check. */ -if ((u8 *)ie < (u8 *)ia || (u8 *)ie + -sizeof (INDEX_ENTRY_HEADER ) > index_end || - (u8 *)ie +le16_to_cpu (ie->key_length) > - index_end) { -ntfs_error (sb,"Index entry out of bounds in " -"directory inode 0x%lx." , - dir_ni->mft_no); - goto unm_err_out; - } -/* -* The last entry cannot contain a name. It can however contain -* a pointer to a child node in the B+tree so we just break out. -*/ -if (ie->flags &INDEX_ENTRY_END ) -break ; -/* -* If the current entry has a name type of POSIX, the name is -* case sensitive and not otherwise. This has the effect of us -* not being able to access any POSIX file names which collate -* after the non-POSIX one when they only differ in case, but -* anyone doing screwy stuff like that deserves to burn in -* hell... Doing that kind of stuff on NT4 actually causes -* corruption on the partition even when using SP6a and Linux -* is not involved at all. -*/ - ic = ie->key.file_name.file_name_type ?IGNORE_CASE : -CASE_SENSITIVE ; -/* -* If the names match perfectly, we are done and return the -* mft reference of the inode (i.e. the inode number together -* with the sequence number for consistency checking. We -* convert it to cpu format before returning. -*/ -if (ntfs_are_names_equal (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, ic, - vol->upcase, vol->upcase_len)) { -found_it2: - mref =le64_to_cpu (ie->data.dir.indexed_file); -unlock_page (page); -ntfs_unmap_page (page); -return mref; - } -/* -* Not a perfect match, need to do full blown collation so we -* know which way in the B+tree we have to go. -*/ - rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length,1 , -IGNORE_CASE , vol->upcase, vol->upcase_len); -/* -* If uname collates before the name of the current entry, there -* is definitely no such name in this index but we might need to -* descend into the B+tree so we just break out of the loop. -*/ -if (rc ==-1 ) -break ; -/* The names are not equal, continue the search. */ -if (rc) -continue ; -/* -* Names match with case insensitive comparison, now try the -* case sensitive comparison, which is required for proper -* collation. -*/ - rc =ntfs_collate_names (uname, uname_len, - (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length,1 , -CASE_SENSITIVE , vol->upcase, vol->upcase_len); -if (rc ==-1 ) -break ; -if (rc) -continue ; +file_ra_state_init (ra, vol->mft_ino->i_mapping); + +if (private && private->key) {/* -* Perfect match, this will never happen as the -* ntfs_are_names_equal() call will have gotten a match but we -* still treat it correctly. +* Find index witk private->key using ntfs_index_lookup() +* instead of linear index lookup. */ - goto found_it2; - } -/* -* We have finished with this index buffer without success. Check for -* the presence of a child node. -*/ -if (ie->flags &INDEX_ENTRY_NODE ) { -if ((ia->index.flags &NODE_MASK ) ==LEAF_NODE ) { -ntfs_error (sb,"Index entry with child node found in " -"a leaf node in directory inode 0x%lx." , - dir_ni->mft_no); - goto unm_err_out; + err =ntfs_index_lookup (private->key, +le16_to_cpu (private->key_length), + ictx); +if (!err) { + next = ictx->entry; +/* +* Update ie_pos with private->curr_pos +* to make next d_off of dirent correct. +*/ + ie_pos = private->curr_pos; + +if (actor->pos > vol->mft_record_size && ictx->ia_ni) { + err =ntfs_ia_blocks_readahead (ictx->ia_ni, actor->pos); +if (err) + goto out; + } + + goto nextdir; + }else { + goto out; } -/* Child node present, descend into it. */ - old_vcn = vcn; - vcn =sle64_to_cpup ((u8 *)ie +le16_to_cpu (ie->length) -8 ); -if (vcn >=0 ) { -/* If vcn is in the same page cache page as old_vcn we -* recycle the mapped page. */ -if (old_vcn << vol->cluster_size_bits >> -PAGE_SHIFT == vcn << - vol->cluster_size_bits >> -PAGE_SHIFT ) - goto fast_descend_into_child_node; -unlock_page (page); -ntfs_unmap_page (page); - goto descend_into_child_node; + }else if (!private) { + private =kzalloc (sizeof (struct ntfs_file_private ),GFP_KERNEL ); +if (!private) { + err = -ENOMEM ; + goto out; } -ntfs_error (sb,"Negative child node vcn in directory inode " -"0x%lx." , dir_ni->mft_no); - goto unm_err_out; + file->private_data = private; } -/* No child node, return -ENOENT. */ -ntfs_debug ("Entry not found." ); - err = -ENOENT ; -unm_err_out: -unlock_page (page); -ntfs_unmap_page (page); -err_out: -if (!err) - err = -EIO ; -if (ctx) + + ctx =ntfs_attr_get_search_ctx (ndir,NULL ); +if (!ctx) { + err = -ENOMEM ; + goto out; + } + +/* Find the index root attribute in the mft record. */ +if (ntfs_attr_lookup (AT_INDEX_ROOT ,I30 ,4 ,CASE_SENSITIVE ,0 ,NULL ,0 , + ctx)) { +ntfs_error (sb,"Index root attribute missing in directory inode %ld" , + ndir->mft_no);ntfs_attr_put_search_ctx (ctx); -if (m) -unmap_mft_record (dir_ni); -return ERR_MREF (err); -dir_err_out: -ntfs_error (sb,"Corrupt directory. Aborting lookup." ); - goto err_out; -} + err = -ENOMEM ; + goto out; + } -#endif +/* Get to the index root value. */ + ir = (struct index_root *)((u8 *)ctx->attr + +le16_to_cpu (ctx->attr->data.resident.value_offset)); -/** -* ntfs_filldir - ntfs specific filldir method -* @vol: current ntfs volume -* @ndir: ntfs inode of current directory -* @ia_page: page in which the index allocation buffer @ie is in resides -* @ie: current index entry -* @name: buffer to use for the converted name -* @actor: what to feed the entries to -* -* Convert the Unicode @name to the loaded NLS and pass it to the @filldir -* callback. -* -* If @ia_page is not NULL it is the locked page containing the index -* allocation block containing the index entry @ie. -* -* Note, we drop (and then reacquire) the page lock on @ia_page across the -* @filldir() call otherwise we would deadlock with NFSd when it calls ->lookup -* since ntfs_lookup() will lock the same page. As an optimization, we do not -* retake the lock if we are returning a non-zero value as ntfs_readdir() -* would need to drop the lock immediately anyway. -*/ -static inline int ntfs_filldir (ntfs_volume *vol, -ntfs_inode *ndir,struct page *ia_page,INDEX_ENTRY *ie, -u8 *name,struct dir_context *actor) -{ -unsigned long mref; -int name_len; -unsigned dt_type; -FILE_NAME_TYPE_FLAGS name_type; + ictx->ir = ir; + ictx->actx = ctx; + ictx->parent_vcn[ictx->pindex] =VCN_INDEX_ROOT_PARENT ; + ictx->is_in_root = true; + ictx->parent_pos[ictx->pindex] =0 ; - name_type = ie->key.file_name.file_name_type; -if (name_type ==FILE_NAME_DOS ) { -ntfs_debug ("Skipping DOS name space entry." ); -return 0 ; - } -if (MREF_LE (ie->data.dir.indexed_file) == FILE_root) { -ntfs_debug ("Skipping root directory self reference entry." ); -return 0 ; - } -if (MREF_LE (ie->data.dir.indexed_file) < FILE_first_user && - !NVolShowSystemFiles (vol)) { -ntfs_debug ("Skipping system file." ); -return 0 ; - } - name_len =ntfs_ucstonls (vol, (ntfschar *)&ie->key.file_name.file_name, - ie->key.file_name.file_name_length, &name, -NTFS_MAX_NAME_LEN *NLS_MAX_CHARSET_SIZE +1 ); -if (name_len <=0 ) { -ntfs_warning (vol->sb,"Skipping unrepresentable inode 0x%llx." , - (long long )MREF_LE (ie->data.dir.indexed_file)); -return 0 ; + ictx->block_size =le32_to_cpu (ir->index_block_size); +if (ictx->block_size <NTFS_BLOCK_SIZE ) { +ntfs_error (sb,"Index block size (%d) is smaller than the sector size (%d)" , + ictx->block_size,NTFS_BLOCK_SIZE ); + err = -EIO ; + goto out; } -if (ie->key.file_name.file_attributes & -FILE_ATTR_DUP_FILE_NAME_INDEX_PRESENT ) - dt_type =DT_DIR ; -else - dt_type =DT_REG ; - mref =MREF_LE (ie->data.dir.indexed_file); -/* -* Drop the page lock otherwise we deadlock with NFS when it calls -* ->lookup since ntfs_lookup() will lock the same page. -*/ -if (ia_page) -unlock_page (ia_page); -ntfs_debug ("Calling filldir for %s with len %i, fpos 0x%llx, inode " -"0x%lx, DT_%s." , name, name_len, actor->pos, mref, - dt_type ==DT_DIR ?"DIR" :"REG" ); -if (!dir_emit (actor, name, name_len, mref, dt_type)) -return 1 ; -/* Relock the page but not if we are aborting ->readdir. */ -if (ia_page) -lock_page (ia_page); -return 0 ; -} -/* -* We use the same basic approach as the old NTFS driver, i.e. we parse the -* index root entries and then the index allocation entries that are marked -* as in use in the index bitmap. -* -* While this will return the names in random order this doesn't matter for -* ->readdir but OTOH results in a faster ->readdir. -* -* VFS calls ->readdir without BKL but with i_mutex held. This protects the VFS -* parts (e.g. ->f_pos and ->i_size, and it also protects against directory -* modifications). -* -* Locking: - Caller must hold i_mutex on the directory. -* - Each page cache page in the index allocation mapping must be -* locked whilst being accessed otherwise we may find a corrupt -* page due to it being under ->writepage at the moment which -* applies the mst protection fixups before writing out and then -* removes them again after the write is complete after which it -* unlocks the page. -*/ -static int ntfs_readdir (struct file *file,struct dir_context *actor) -{ -s64 ia_pos, ia_start, prev_ia_pos, bmp_pos; -loff_t i_size; -struct inode *bmp_vi, *vdir =file_inode (file); -struct super_block *sb = vdir->i_sb; -ntfs_inode *ndir =NTFS_I (vdir); -ntfs_volume *vol =NTFS_SB (sb); -MFT_RECORD *m; -INDEX_ROOT *ir =NULL ; -INDEX_ENTRY *ie; -INDEX_ALLOCATION *ia; -u8 *name =NULL ; -int rc, err, ir_pos, cur_bmp_pos; -struct address_space *ia_mapping, *bmp_mapping; -struct page *bmp_page =NULL , *ia_page =NULL ; -u8 *kaddr, *bmp, *index_end; -ntfs_attr_search_ctx *ctx; +if (vol->cluster_size <= ictx->block_size) + ictx->vcn_size_bits = vol->cluster_size_bits; +else + ictx->vcn_size_bits =NTFS_BLOCK_SIZE_BITS ; -ntfs_debug ("Entering for inode 0x%lx, fpos 0x%llx." , - vdir->i_ino, actor->pos); - rc = err =0 ; -/* Are we at end of dir yet? */ - i_size =i_size_read (vdir); -if (actor->pos >= i_size + vol->mft_record_size) -return 0 ; -/* Emulate . and .. for all directories. */ -if (!dir_emit_dots (file, actor)) -return 0 ; - m =NULL ; - ctx =NULL ; -/* -* Allocate a buffer to store the current name being processed -* converted to format determined by current NLS. -*/ - name =kmalloc (NTFS_MAX_NAME_LEN *NLS_MAX_CHARSET_SIZE +1 ,GFP_NOFS ); -if (unlikely (!name)) { - err = -ENOMEM ; - goto err_out; - } -/* Are we jumping straight into the index allocation attribute? */ -if (actor->pos >= vol->mft_record_size) - goto skip_index_root; -/* Get hold of the mft record for the directory. */ - m =map_mft_record (ndir); -if (IS_ERR (m)) { - err =PTR_ERR (m); - m =NULL ; - goto err_out; - } - ctx =ntfs_attr_get_search_ctx (ndir, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; - goto err_out; - } -/* Get the offset into the index root attribute. */ - ir_pos = (s64 )actor->pos; -/* Find the index root attribute in the mft record. */ - err =ntfs_attr_lookup (AT_INDEX_ROOT ,I30 ,4 ,CASE_SENSITIVE ,0 ,NULL , -0 , ctx); -if (unlikely (err)) { -ntfs_error (sb,"Index root attribute missing in directory " -"inode 0x%lx." , vdir->i_ino); - goto err_out; - } -/* -* Copy the index root attribute value to a buffer so that we can put -* the search context and unmap the mft record before calling the -* filldir() callback. We need to do this because of NFSd which calls -* ->lookup() from its filldir callback() and this causes NTFS to -* deadlock as ntfs_lookup() maps the mft record of the directory and -* we have got it mapped here already. The only solution is for us to -* unmap the mft record here so that a call to ntfs_lookup() is able to -* map the mft record without deadlocking. -*/ - rc =le32_to_cpu (ctx->attr->data.resident.value_length); - ir =kmalloc (rc,GFP_NOFS ); -if (unlikely (!ir)) { - err = -ENOMEM ; - goto err_out; - } -/* Copy the index root value (it has been verified in read_inode). */ -memcpy (ir, (u8 *)ctx->attr + -le16_to_cpu (ctx->attr->data.resident.value_offset), rc); -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (ndir); - ctx =NULL ; - m =NULL ; - index_end = (u8 *)&ir->index +le32_to_cpu (ir->index.index_length);/* The first index entry. */ - ie = (INDEX_ENTRY *)((u8 *)&ir->index + + next = (struct index_entry *)((u8 *)&ir->index +le32_to_cpu (ir->index.entries_offset)); -/* -* Loop until we exceed valid memory (corruption case) or until we -* reach the last entry or until filldir tells us it has had enough -* or signals an error (both covered by the rc test). -*/ -for (;; ie = (INDEX_ENTRY *)((u8 *)ie +le16_to_cpu (ie->length))) { -ntfs_debug ("In index root, offset 0x%zx." , (u8 *)ie - (u8 *)ir); -/* Bounds checks. */ -if (unlikely ((u8 *)ie < (u8 *)ir || (u8 *)ie + -sizeof (INDEX_ENTRY_HEADER ) > index_end || - (u8 *)ie +le16_to_cpu (ie->key_length) > - index_end)) - goto err_out; -/* The last entry cannot contain a name. */ -if (ie->flags &INDEX_ENTRY_END ) -break ; -/* Skip index root entry if continuing previous readdir. */ -if (ir_pos > (u8 *)ie - (u8 *)ir) -continue ; -/* Advance the position even if going to skip the entry. */ - actor->pos = (u8 *)ie - (u8 *)ir; -/* Submit the name to the filldir callback. */ - rc =ntfs_filldir (vol, ndir,NULL , ie, name, actor); -if (rc) { -kfree (ir); - goto abort; + +if (next->flags &INDEX_ENTRY_NODE ) { + ictx->ia_ni =ntfs_ia_open (ictx, ictx->idx_ni); +if (!ictx->ia_ni) { + err = -EINVAL ; + goto out; } + + err =ntfs_ia_blocks_readahead (ictx->ia_ni, actor->pos); +if (err) + goto out; } -/* We are done with the index root and can free the buffer. */ -kfree (ir); - ir =NULL ; -/* If there is no index allocation attribute we are finished. */ -if (!NInoIndexAllocPresent (ndir)) - goto EOD; -/* Advance fpos to the beginning of the index allocation. */ - actor->pos = vol->mft_record_size; -skip_index_root: - kaddr =NULL ; - prev_ia_pos =-1LL ; -/* Get the offset into the index allocation attribute. */ - ia_pos = (s64 )actor->pos - vol->mft_record_size; - ia_mapping = vdir->i_mapping; -ntfs_debug ("Inode 0x%lx, getting index bitmap." , vdir->i_ino); - bmp_vi =ntfs_attr_iget (vdir,AT_BITMAP ,I30 ,4 ); -if (IS_ERR (bmp_vi)) { -ntfs_error (sb,"Failed to get bitmap attribute." ); - err =PTR_ERR (bmp_vi); - goto err_out; - } - bmp_mapping = bmp_vi->i_mapping; -/* Get the starting bitmap bit position and sanity check it. */ - bmp_pos = ia_pos >> ndir->itype.index.block_size_bits; -if (unlikely (bmp_pos >>3 >=i_size_read (bmp_vi))) { -ntfs_error (sb,"Current index allocation position exceeds " -"index bitmap size." ); - goto iput_err_out; - } -/* Get the starting bit position in the current bitmap page. */ - cur_bmp_pos = bmp_pos & ((PAGE_SIZE *8 ) -1 ); - bmp_pos &= ~(u64)((PAGE_SIZE *8 ) -1 ); -get_next_bmp_page: -ntfs_debug ("Reading bitmap with page index 0x%llx, bit ofs 0x%llx" , - (unsigned long long )bmp_pos >> (3 +PAGE_SHIFT ), - (unsigned long long )bmp_pos & - (unsigned long long )((PAGE_SIZE *8 ) -1 )); - bmp_page =ntfs_map_page (bmp_mapping, - bmp_pos >> (3 +PAGE_SHIFT )); -if (IS_ERR (bmp_page)) { -ntfs_error (sb,"Reading index bitmap failed." ); - err =PTR_ERR (bmp_page); - bmp_page =NULL ; - goto iput_err_out; - } - bmp = (u8 *)page_address (bmp_page); -/* Find next index block in use. */ -while (!(bmp[cur_bmp_pos >>3 ] & (1 << (cur_bmp_pos &7 )))) { -find_next_index_buffer: - cur_bmp_pos++; -/* -* If we have reached the end of the bitmap page, get the next -* page, and put away the old one. -*/ -if (unlikely ((cur_bmp_pos >>3 ) >=PAGE_SIZE )) { -ntfs_unmap_page (bmp_page); - bmp_pos +=PAGE_SIZE *8 ; - cur_bmp_pos =0 ; - goto get_next_bmp_page; + +if (next->flags &INDEX_ENTRY_NODE ) { + next =ntfs_index_walk_down (next, ictx); +if (!next) { + err = -EIO ; + goto out; } -/* If we have reached the end of the bitmap, we are done. */ -if (unlikely (((bmp_pos + cur_bmp_pos) >>3 ) >= i_size)) - goto unm_EOD; - ia_pos = (bmp_pos + cur_bmp_pos) << - ndir->itype.index.block_size_bits; } -ntfs_debug ("Handling index buffer 0x%llx." , - (unsigned long long )bmp_pos + cur_bmp_pos); -/* If the current index buffer is in the same page we reuse the page. */ -if ((prev_ia_pos & (s64 )PAGE_MASK ) != - (ia_pos & (s64 )PAGE_MASK )) { - prev_ia_pos = ia_pos; -if (likely (ia_page !=NULL )) { -unlock_page (ia_page); -ntfs_unmap_page (ia_page); + +if (next && !(next->flags &INDEX_ENTRY_END )) + goto nextdir; + +while ((next =ntfs_index_next (next, ictx)) !=NULL ) { +nextdir: +/* Check the consistency of an index entry */ +if (ntfs_index_entry_inconsistent (ictx, vol, next,COLLATION_FILE_NAME , + ndir->mft_no)) { + err = -EIO ; + goto out; } -/* -* Map the page cache page containing the current ia_pos, -* reading it from disk if necessary. -*/ - ia_page =ntfs_map_page (ia_mapping, ia_pos >>PAGE_SHIFT ); -if (IS_ERR (ia_page)) { -ntfs_error (sb,"Reading index allocation data failed." ); - err =PTR_ERR (ia_page); - ia_page =NULL ; - goto err_out; + +if (ie_pos < actor->pos) { + ie_pos += next->length; +continue ; } -lock_page (ia_page); - kaddr = (u8 *)page_address (ia_page); - } -/* Get the current index buffer. */ - ia = (INDEX_ALLOCATION *)(kaddr + (ia_pos & ~PAGE_MASK & - ~(s64)(ndir->itype.index.block_size -1 ))); -/* Bounds checks. */ -if (unlikely ((u8 *)ia < kaddr || (u8 *)ia > kaddr +PAGE_SIZE )) { -ntfs_error (sb,"Out of bounds check failed. Corrupt directory " -"inode 0x%lx or driver bug." , vdir->i_ino); - goto err_out; - } -/* Catch multi sector transfer fixup errors. */ -if (unlikely (!ntfs_is_indx_record (ia->magic))) { -ntfs_error (sb,"Directory index record with vcn 0x%llx is " -"corrupt. Corrupt inode 0x%lx. Run chkdsk." , - (unsigned long long )ia_pos >> - ndir->itype.index.vcn_size_bits, vdir->i_ino); - goto err_out; - } -if (unlikely (sle64_to_cpu (ia->index_block_vcn) != (ia_pos & - ~(s64)(ndir->itype.index.block_size -1 )) >> - ndir->itype.index.vcn_size_bits)) { -ntfs_error (sb,"Actual VCN (0x%llx) of index buffer is " -"different from expected VCN (0x%llx). " -"Directory inode 0x%lx is corrupt or driver " -"bug. " , (unsigned long long ) -sle64_to_cpu (ia->index_block_vcn), - (unsigned long long )ia_pos >> - ndir->itype.index.vcn_size_bits, vdir->i_ino); - goto err_out; - } -if (unlikely (le32_to_cpu (ia->index.allocated_size) +0x18 != - ndir->itype.index.block_size)) { -ntfs_error (sb,"Index buffer (VCN 0x%llx) of directory inode " -"0x%lx has a size (%u) differing from the " -"directory specified size (%u). Directory " -"inode is corrupt or driver bug." , - (unsigned long long )ia_pos >> - ndir->itype.index.vcn_size_bits, vdir->i_ino, -le32_to_cpu (ia->index.allocated_size) +0x18 , - ndir->itype.index.block_size); - goto err_out; - } - index_end = (u8 *)ia + ndir->itype.index.block_size; -if (unlikely (index_end > kaddr +PAGE_SIZE )) { -ntfs_error (sb,"Index buffer (VCN 0x%llx) of directory inode " -"0x%lx crosses page boundary. Impossible! " -"Cannot access! This is probably a bug in the " -"driver." , (unsigned long long )ia_pos >> - ndir->itype.index.vcn_size_bits, vdir->i_ino); - goto err_out; - } - ia_start = ia_pos & ~(s64)(ndir->itype.index.block_size -1 ); - index_end = (u8 *)&ia->index +le32_to_cpu (ia->index.index_length); -if (unlikely (index_end > (u8 *)ia + ndir->itype.index.block_size)) { -ntfs_error (sb,"Size of index buffer (VCN 0x%llx) of directory " -"inode 0x%lx exceeds maximum size." , - (unsigned long long )ia_pos >> - ndir->itype.index.vcn_size_bits, vdir->i_ino); - goto err_out; - } -/* The first index entry in this index buffer. */ - ie = (INDEX_ENTRY *)((u8 *)&ia->index + -le32_to_cpu (ia->index.entries_offset)); -/* -* Loop until we exceed valid memory (corruption case) or until we -* reach the last entry or until filldir tells us it has had enough -* or signals an error (both covered by the rc test). -*/ -for (;; ie = (INDEX_ENTRY *)((u8 *)ie +le16_to_cpu (ie->length))) { -ntfs_debug ("In index allocation, offset 0x%llx." , - (unsigned long long )ia_start + - (unsigned long long )((u8 *)ie - (u8 *)ia)); -/* Bounds checks. */ -if (unlikely ((u8 *)ie < (u8 *)ia || (u8 *)ie + -sizeof (INDEX_ENTRY_HEADER ) > index_end || - (u8 *)ie +le16_to_cpu (ie->key_length) > - index_end)) - goto err_out; -/* The last entry cannot contain a name. */ -if (ie->flags &INDEX_ENTRY_END ) + + actor->pos = ie_pos; + + index =NTFS_MFT_NR_TO_PIDX (vol,MREF_LE (next->data.dir.indexed_file)); +if (nir) { +struct ntfs_index_ra *cnir; +struct rb_node *node = ra_root.rb_node; + +if (nir->start_index <= index && + index < nir->start_index + nir->count) { +/* No behavior */ + goto filldir; + } + +while (node) { + cnir = rb_entry(node, struct ntfs_index_ra, rb_node); +if (cnir->start_index <= index && + index < cnir->start_index + cnir->count) { + goto filldir; + }else if (cnir->start_index + cnir->count == index) { + cnir->count++; + goto filldir; + }else if (!cnir->start_index && cnir->start_index -1 == index) { + cnir->start_index = index; + goto filldir; + } + +if (index < cnir->start_index) + node = node->rb_left; +else if (index >= cnir->start_index + cnir->count) + node = node->rb_right; + } + +if (nir->start_index + nir->count == index) { + nir->count++; + }else if (!nir->start_index && nir->start_index -1 == index) { + nir->start_index = index; + }else if (nir->count >2 ) { +ntfs_insert_rb (nir, &ra_root); + nir =NULL ; + }else { + nir->start_index = index; + nir->count =1 ; + } + } + +if (!nir) { + nir =kzalloc (sizeof (struct ntfs_index_ra ),GFP_KERNEL ); +if (nir) { + nir->start_index = index; + nir->count =1 ; + } + } + +filldir: +/* Submit the name to the filldir callback. */ + err =ntfs_filldir (vol, ndir,NULL , next, name, actor); +if (err) { +/* +* Store index key value to file private_data to start +* from current index offset on next round. +*/ + private = file->private_data; +kfree (private->key); + private->key =kmalloc (le16_to_cpu (next->key_length),GFP_KERNEL ); +if (!private->key) { + err = -ENOMEM ; + goto out; + } + +memcpy (private->key, &next->key.file_name,le16_to_cpu (next->key_length)); + private->key_length = next->key_length;break ; -/* Skip index block entry if continuing previous readdir. */ -if (ia_pos - ia_start > (u8 *)ie - (u8 *)ia) -continue ; -/* Advance the position even if going to skip the entry. */ - actor->pos = (u8 *)ie - (u8 *)ia + - (sle64_to_cpu (ia->index_block_vcn) << - ndir->itype.index.vcn_size_bits) + - vol->mft_record_size; -/* -* Submit the name to the @filldir callback. Note, -* ntfs_filldir() drops the lock on @ia_page but it retakes it -* before returning, unless a non-zero value is returned in -* which case the page is left unlocked. -*/ - rc =ntfs_filldir (vol, ndir, ia_page, ie, name, actor); -if (rc) { -/* @ia_page is already unlocked in this case. */ -ntfs_unmap_page (ia_page); -ntfs_unmap_page (bmp_page); -iput (bmp_vi); - goto abort; } + ie_pos += next->length; } - goto find_next_index_buffer; -unm_EOD: -if (ia_page) { -unlock_page (ia_page); -ntfs_unmap_page (ia_page); - } -ntfs_unmap_page (bmp_page); -iput (bmp_vi); -EOD: -/* We are finished, set fpos to EOD. */ - actor->pos = i_size + vol->mft_record_size; -abort: -kfree (name); -return 0 ; -err_out: -if (bmp_page) { -ntfs_unmap_page (bmp_page); -iput_err_out: -iput (bmp_vi); + +if (!err) + private->end_in_iterate = true; +else + err =0 ; + + private->curr_pos = actor->pos = ie_pos; +out: +while (!RB_EMPTY_ROOT (&ra_root)) { +struct ntfs_index_ra *cnir; +struct rb_node *node; + + node =rb_first (&ra_root); + cnir = rb_entry(node, struct ntfs_index_ra, rb_node); + ra->ra_pages = cnir->count; +page_cache_sync_readahead (vol->mft_ino->i_mapping, ra,NULL , + cnir->start_index, cnir->count); +rb_erase (node, &ra_root); +kfree (cnir); } -if (ia_page) { -unlock_page (ia_page); -ntfs_unmap_page (ia_page); + +if (err) { + private->curr_pos = actor->pos; + private->end_in_iterate = true; + err =0 ; } -kfree (ir); +ntfs_index_ctx_put (ictx);kfree (name); -if (ctx) -ntfs_attr_put_search_ctx (ctx); -if (m) -unmap_mft_record (ndir); -if (!err) - err = -EIO ; -ntfs_debug ("Failed. Returning error code %i." , -err); +kfree (nir); +kfree (ra); +mutex_unlock (&ndir->mrec_lock);return err; } +int ntfs_check_empty_dir (struct ntfs_inode *ni,struct mft_record *ni_mrec) +{ +struct ntfs_attr_search_ctx *ctx; +int ret =0 ; + +if (!(ni_mrec->flags &MFT_RECORD_IS_DIRECTORY )) +return 0 ; + + ctx =ntfs_attr_get_search_ctx (ni,NULL ); +if (!ctx) { +ntfs_error (ni->vol->sb,"Failed to get search context" ); +return -ENOMEM ; + } + +/* Find the index root attribute in the mft record. */ + ret =ntfs_attr_lookup (AT_INDEX_ROOT ,I30 ,4 ,CASE_SENSITIVE ,0 ,NULL , +0 , ctx); +if (ret) { +ntfs_error (ni->vol->sb,"Index root attribute missing in directory inode %lld" , + (unsigned long long )ni->mft_no); +ntfs_attr_put_search_ctx (ctx); +return ret; + } + +/* Non-empty directory? */ +if (ctx->attr->data.resident.value_length != +sizeof (struct index_root ) +sizeof (struct index_entry_header )) { +/* Both ENOTEMPTY and EEXIST are ok. We use the more common. */ + ret = -ENOTEMPTY ; +ntfs_debug ("Directory is not empty\n" ); + } + +ntfs_attr_put_search_ctx (ctx); + +return ret; +} +/** * ntfs_dir_open - called when an inode is about to be opened * @vi: inode to be opened
@@ -1457,13 +1103,21 @@ static int ntfs_dir_open(struct inode *vi, struct file *filp)return 0 ; } -#ifdef NTFS_RW +static int ntfs_dir_release (struct inode *vi,struct file *filp) +{ +if (filp->private_data) { +kfree (((struct ntfs_file_private *)filp->private_data)->key); +kfree (filp->private_data); + filp->private_data =NULL ; + } +return 0 ; +}/** * ntfs_dir_fsync - sync a directory to disk -* @filp: directory to be synced -* @start: offset in bytes of the beginning of data range to sync -* @end: offset in bytes of the end of data range (inclusive) +* @filp: file describing the directory to be synced +* @start: start offset to be synced +* @end: end offset to be synced * @datasync: if non-zero only flush user data and not metadata * * Data integrity sync of a directory to disk. Used for fsync, fdatasync, and
@@ -1479,27 +1133,55 @@ static int ntfs_dir_open(struct inode *vi, struct file *filp)* anyway. * * Locking: Caller must hold i_mutex on the inode. -* -* TODO: We should probably also write all attribute/index inodes associated -* with this inode but since we have no simple way of getting to them we ignore -* this problem for now. We do write the $BITMAP attribute if it is present -* which is the important one for a directory so things are not too bad. */ static int ntfs_dir_fsync (struct file *filp,loff_t start,loff_t end,int datasync) {struct inode *bmp_vi, *vi = filp->f_mapping->host; +struct ntfs_volume *vol =NTFS_I (vi)->vol; +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_attr_search_ctx *ctx; +struct inode *parent_vi, *ia_vi;int err, ret; -ntfs_attr na; +struct ntfs_attr na;ntfs_debug ("Entering for inode 0x%lx." , vi->i_ino); +if (NVolShutdown (vol)) +return -EIO ; + + ctx =ntfs_attr_get_search_ctx (ni,NULL ); +if (!ctx) +return -ENOMEM ; + +mutex_lock_nested (&ni->mrec_lock,NTFS_INODE_MUTEX_NORMAL_2 ); +while (!(err =ntfs_attr_lookup (AT_FILE_NAME ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx))) { +struct file_name_attr *fn = (struct file_name_attr *)((u8 *)ctx->attr + +le16_to_cpu (ctx->attr->data.resident.value_offset)); + + parent_vi =ntfs_iget (vi->i_sb,MREF_LE (fn->parent_directory)); +if (IS_ERR (parent_vi)) +continue ; +mutex_lock_nested (&NTFS_I (parent_vi)->mrec_lock,NTFS_INODE_MUTEX_PARENT_2 ); + ia_vi =ntfs_index_iget (parent_vi,I30 ,4 ); +mutex_unlock (&NTFS_I (parent_vi)->mrec_lock); +if (IS_ERR (ia_vi)) { +iput (parent_vi); +continue ; + } +write_inode_now (ia_vi,1 ); +iput (ia_vi); +write_inode_now (parent_vi,1 ); +iput (parent_vi); + } +mutex_unlock (&ni->mrec_lock); +ntfs_attr_put_search_ctx (ctx); + err =file_write_and_wait_range (filp, start, end);if (err)return err;inode_lock (vi); -BUG_ON (!S_ISDIR (vi->i_mode));/* If the bitmap attribute inode is in memory sync it, too. */ na.mft_no = vi->i_ino; na.type =AT_BITMAP ;
@@ -1507,34 +1189,41 @@ static int ntfs_dir_fsync(struct file *filp, loff_t start, loff_t end, na.name_len =4 ; bmp_vi =ilookup5 (vi->i_sb, vi->i_ino, ntfs_test_inode, &na);if (bmp_vi) { -write_inode_now (bmp_vi, !datasync); +write_inode_now (bmp_vi, !datasync);iput (bmp_vi); } ret =__ntfs_write_inode (vi,1 ); +write_inode_now (vi, !datasync); + +write_inode_now (vol->mftbmp_ino,1 ); +down_write (&vol->lcnbmp_lock); +write_inode_now (vol->lcnbmp_ino,1 ); +up_write (&vol->lcnbmp_lock); +write_inode_now (vol->mft_ino,1 ); + err =sync_blockdev (vi->i_sb->s_bdev);if (unlikely (err && !ret)) ret = err;if (likely (!ret))ntfs_debug ("Done." );else -ntfs_warning (vi->i_sb,"Failed to f%ssync inode 0x%lx. Error " -"%u." , datasync ?"data" :"" , vi->i_ino, -ret); +ntfs_warning (vi->i_sb, +"Failed to f%ssync inode 0x%lx. Error %u." , + datasync ?"data" :"" , vi->i_ino, -ret);inode_unlock (vi);return ret; } -#endif /* NTFS_RW */ - -WRAP_DIR_ITER (ntfs_readdir)// FIXME! const struct file_operations ntfs_dir_ops = { .llseek = generic_file_llseek,/* Seek inside directory. */ .read = generic_read_dir,/* Return -EISDIR. */ - .iterate_shared = shared_ntfs_readdir,/* Read directory contents. */ -#ifdef NTFS_RW + .iterate_shared = ntfs_readdir,/* Read directory contents. */ .fsync = ntfs_dir_fsync,/* Sync a directory to disk. */ -#endif /* NTFS_RW */ -/*.ioctl = ,*/ /* Perform function on the -mounted filesystem. */ .open = ntfs_dir_open,/* Open directory. */ + .release = ntfs_dir_release, + .unlocked_ioctl = ntfsp_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = ntfsp_compat_ioctl, +#endif };
fs/ntfs/index.c +2036 -361
1,013 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.25.1
Part of the diff is not shown here. View the raw message.
Namjae Jeon
maintainerPATCH v3 6/14 ntfs: update file operations
In reply to Namjae JeonThis updates the implementation of file operations
--- fs/ntfs/file.c | 2855 +++++++++++++++++------------------------------- 1 file changed, 1000 insertions(+), 1855 deletions(-)
fs/ntfs/file.c +1000 -1855
@@ -1,32 +1,30 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* file.c - NTFS kernel file operations. Part of the Linux-NTFS project. +* NTFS kernel file operations. Part of the Linux-NTFS project. * * Copyright (c) 2001-2015 Anton Altaparmakov and Tuxera Inc. +* Copyright (c) 2025 LG Electronics Co., Ltd. */ +#include <linux/writeback.h> #include <linux/blkdev.h> -#include <linux/backing-dev.h> -#include <linux/buffer_head.h> -#include <linux/gfp.h> -#include <linux/pagemap.h> -#include <linux/pagevec.h> -#include <linux/sched/signal.h> -#include <linux/swap.h> +#include <linux/fs.h> +#include <linux/iomap.h> #include <linux/uio.h> -#include <linux/writeback.h> +#include <linux/posix_acl.h> +#include <linux/posix_acl_xattr.h> +#include <linux/compat.h> +#include <linux/falloc.h> +#include <uapi/linux/ntfs.h> -#include <asm/page.h> -#include <linux/uaccess.h> - -#include "attrib.h" -#include "bitmap.h" -#include "inode.h" -#include "debug.h" #include "lcnalloc.h" -#include "malloc.h" -#include "mft.h" #include "ntfs.h" +#include "aops.h" +#include "reparse.h" +#include "ea.h" +#include "iomap.h" +#include "bitmap.h" +#include "malloc.h" /** * ntfs_file_open - called when an inode is about to be opened
@@ -48,1948 +46,1095 @@*/ static int ntfs_file_open (struct inode *vi,struct file *filp) { +struct ntfs_inode *ni =NTFS_I (vi); + +if (NVolShutdown (ni->vol)) +return -EIO ; +if (sizeof (unsigned long ) <8 ) {if (i_size_read (vi) >MAX_LFS_FILESIZE )return -EOVERFLOW ; } + +if (filp->f_flags &O_TRUNC &&NInoNonResident (ni)) { +int err; + +mutex_lock (&ni->mrec_lock); +down_read (&ni->runlist.lock); +if (!ni->runlist.rl) { + err =ntfs_attr_map_whole_runlist (ni); +if (err) { +up_read (&ni->runlist.lock); +mutex_unlock (&ni->mrec_lock); +return err; + } + } + ni->lcn_seek_trunc = ni->runlist.rl->lcn; +up_read (&ni->runlist.lock); +mutex_unlock (&ni->mrec_lock); + } + + filp->f_mode |=FMODE_NOWAIT ; +return generic_file_open (vi, filp); } -#ifdef NTFS_RW +static int ntfs_file_release (struct inode *vi,struct file *filp) +{ +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; +s64 aligned_data_size =round_up (ni->data_size, vol->cluster_size); + +if (NInoCompressed (ni)) +return 0 ; + +inode_lock (vi); +mutex_lock (&ni->mrec_lock); +down_write (&ni->runlist.lock); +if (aligned_data_size < ni->allocated_size) { +int err; +s64 vcn_ds =NTFS_B_TO_CLU (vol, aligned_data_size); +s64 vcn_tr =-1 ; +struct runlist_element *rl = ni->runlist.rl; +ssize_t rc = ni->runlist.count -2 ; + +while (rc >=0 && rl[rc].lcn ==LCN_HOLE && vcn_ds <= rl[rc].vcn) { + vcn_tr = rl[rc].vcn; + rc--; + } + +if (vcn_tr >=0 ) { + err =ntfs_rl_truncate_nolock (vol, &ni->runlist, vcn_tr); +if (err) { +ntfs_free (ni->runlist.rl); + ni->runlist.rl =NULL ; +ntfs_error (vol->sb,"Preallocated block rollback failed" ); + }else { + ni->allocated_size =NTFS_CLU_TO_B (vol, vcn_tr); + err =ntfs_attr_update_mapping_pairs (ni,0 ); +if (err) +ntfs_error (vol->sb, +"Failed to rollback mapping pairs for prealloc" ); + } + } + } +up_write (&ni->runlist.lock); +mutex_unlock (&ni->mrec_lock); +inode_unlock (vi); + +return 0 ; +}/** -* ntfs_attr_extend_initialized - extend the initialized size of an attribute -* @ni: ntfs inode of the attribute to extend -* @new_init_size: requested new initialized size in bytes -* -* Extend the initialized size of an attribute described by the ntfs inode @ni -* to @new_init_size bytes. This involves zeroing any non-sparse space between -* the old initialized size and @new_init_size both in the page cache and on -* disk (if relevant complete pages are already uptodate in the page cache then -* these are simply marked dirty). +* ntfs_file_fsync - sync a file to disk +* @filp: file to be synced +* @start: start offset to be synced +* @end: end offset to be synced +* @datasync: if non-zero only flush user data and not metadata * -* As a side-effect, the file size (vfs inode->i_size) may be incremented as, -* in the resident attribute case, it is tied to the initialized size and, in -* the non-resident attribute case, it may not fall below the initialized size. +* Data integrity sync of a file to disk. Used for fsync, fdatasync, and msync +* system calls. This function is inspired by fs/buffer.c::file_fsync(). * -* Note that if the attribute is resident, we do not need to touch the page -* cache at all. This is because if the page cache page is not uptodate we -* bring it uptodate later, when doing the write to the mft record since we -* then already have the page mapped. And if the page is uptodate, the -* non-initialized region will already have been zeroed when the page was -* brought uptodate and the region may in fact already have been overwritten -* with new data via mmap() based writes, so we cannot just zero it. And since -* POSIX specifies that the behaviour of resizing a file whilst it is mmap()ped -* is unspecified, we choose not to do zeroing and thus we do not need to touch -* the page at all. For a more detailed explanation see ntfs_truncate() in -* fs/ntfs/inode.c. +* If @datasync is false, write the mft record and all associated extent mft +* records as well as the $DATA attribute and then sync the block device. * -* Return 0 on success and -errno on error. In the case that an error is -* encountered it is possible that the initialized size will already have been -* incremented some way towards @new_init_size but it is guaranteed that if -* this is the case, the necessary zeroing will also have happened and that all -* metadata is self-consistent. +* If @datasync is true and the attribute is non-resident, we skip the writing +* of the mft record and all associated extent mft records (this might still +* happen due to the write_inode_now() call). * -* Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be -* held by the caller. +* Also, if @datasync is true, we do not wait on the inode to be written out +* but we always wait on the page cache pages to be written out. */ -static int ntfs_attr_extend_initialized (ntfs_inode *ni,const s64 new_init_size) +static int ntfs_file_fsync (struct file *filp,loff_t start,loff_t end, +int datasync) { -s64 old_init_size; -loff_t old_i_size; -pgoff_t index, end_index; -unsigned long flags; -struct inode *vi =VFS_I (ni); -ntfs_inode *base_ni; -MFT_RECORD *m =NULL ; -ATTR_RECORD *a; -ntfs_attr_search_ctx *ctx =NULL ; -struct address_space *mapping; -struct page *page =NULL ; -u8 *kattr; -int err; -u32 attr_len; +struct inode *vi = filp->f_mapping->host; +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; +int err, ret =0 ; +struct inode *parent_vi, *ia_vi; +struct ntfs_attr_search_ctx *ctx; -read_lock_irqsave (&ni->size_lock, flags); - old_init_size = ni->initialized_size; - old_i_size =i_size_read (vi); -BUG_ON (new_init_size > ni->allocated_size); -read_unlock_irqrestore (&ni->size_lock, flags); -ntfs_debug ("Entering for i_ino 0x%lx, attribute type 0x%x, " -"old_initialized_size 0x%llx, " -"new_initialized_size 0x%llx, i_size 0x%llx." , - vi->i_ino, (unsigned )le32_to_cpu (ni->type), - (unsigned long long )old_init_size, - (unsigned long long )new_init_size, old_i_size); -if (!NInoAttr (ni)) - base_ni = ni; -else - base_ni = ni->ext.base_ntfs_ino; -/* Use goto to reduce indentation and we need the label below anyway. */ -if (NInoNonResident (ni)) - goto do_non_resident_extend; -BUG_ON (old_init_size != old_i_size); - m =map_mft_record (base_ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); - m =NULL ; - goto err_out; - } - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; - goto err_out; - } - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) - err = -EIO ; - goto err_out; - } - m = ctx->mrec; - a = ctx->attr; -BUG_ON (a->non_resident); -/* The total length of the attribute value. */ - attr_len =le32_to_cpu (a->data.resident.value_length); -BUG_ON (old_i_size != (loff_t )attr_len); -/* -* Do the zeroing in the mft record and update the attribute size in -* the mft record. -*/ - kattr = (u8 *)a +le16_to_cpu (a->data.resident.value_offset); -memset (kattr + attr_len,0 , new_init_size - attr_len); - a->data.resident.value_length =cpu_to_le32 ((u32 )new_init_size); -/* Finally, update the sizes in the vfs and ntfs inodes. */ -write_lock_irqsave (&ni->size_lock, flags); -i_size_write (vi, new_init_size); - ni->initialized_size = new_init_size; -write_unlock_irqrestore (&ni->size_lock, flags); - goto done; -do_non_resident_extend: -/* -* If the new initialized size @new_init_size exceeds the current file -* size (vfs inode->i_size), we need to extend the file size to the -* new initialized size. -*/ -if (new_init_size > old_i_size) { - m =map_mft_record (base_ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); - m =NULL ; - goto err_out; - } - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; - goto err_out; - } - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) - err = -EIO ; - goto err_out; - } - m = ctx->mrec; - a = ctx->attr; -BUG_ON (!a->non_resident); -BUG_ON (old_i_size != (loff_t ) -sle64_to_cpu (a->data.non_resident.data_size)); - a->data.non_resident.data_size =cpu_to_sle64 (new_init_size); -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -/* Update the file size in the vfs inode. */ -i_size_write (vi, new_init_size); -ntfs_attr_put_search_ctx (ctx); - ctx =NULL ; -unmap_mft_record (base_ni); - m =NULL ; - } - mapping = vi->i_mapping; - index = old_init_size >>PAGE_SHIFT ; - end_index = (new_init_size +PAGE_SIZE -1 ) >>PAGE_SHIFT ; -do { -/* -* Read the page. If the page is not present, this will zero -* the uninitialized regions for us. -*/ - page =read_mapping_page (mapping, index,NULL ); -if (IS_ERR (page)) { - err =PTR_ERR (page); - goto init_err_out; - } -/* -* Update the initialized size in the ntfs inode. This is -* enough to make ntfs_writepage() work. -*/ -write_lock_irqsave (&ni->size_lock, flags); - ni->initialized_size = (s64)(index +1 ) <<PAGE_SHIFT ; -if (ni->initialized_size > new_init_size) - ni->initialized_size = new_init_size; -write_unlock_irqrestore (&ni->size_lock, flags); -/* Set the page dirty so it gets written out. */ -set_page_dirty (page); -put_page (page); -/* -* Play nice with the vm and the rest of the system. This is -* very much needed as we can potentially be modifying the -* initialised size from a very small value to a really huge -* value, e.g. -* f = open(somefile, O_TRUNC); -* truncate(f, 10GiB); -* seek(f, 10GiB); -* write(f, 1); -* And this would mean we would be marking dirty hundreds of -* thousands of pages or as in the above example more than -* two and a half million pages! -* -* TODO: For sparse pages could optimize this workload by using -* the FsMisc / MiscFs page bit as a "PageIsSparse" bit. This -* would be set in read_folio for sparse pages and here we would -* not need to mark dirty any pages which have this bit set. -* The only caveat is that we have to clear the bit everywhere -* where we allocate any clusters that lie in the page or that -* contain the page. -* -* TODO: An even greater optimization would be for us to only -* call read_folio() on pages which are not in sparse regions as -* determined from the runlist. This would greatly reduce the -* number of pages we read and make dirty in the case of sparse -* files. -*/ -balance_dirty_pages_ratelimited (mapping); -cond_resched (); - }while (++index < end_index); -read_lock_irqsave (&ni->size_lock, flags); -BUG_ON (ni->initialized_size != new_init_size); -read_unlock_irqrestore (&ni->size_lock, flags); -/* Now bring in sync the initialized_size in the mft record. */ - m =map_mft_record (base_ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); - m =NULL ; - goto init_err_out; - } - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; - goto init_err_out; - } - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) - err = -EIO ; - goto init_err_out; - } - m = ctx->mrec; - a = ctx->attr; -BUG_ON (!a->non_resident); - a->data.non_resident.initialized_size =cpu_to_sle64 (new_init_size); -done: -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -if (ctx) -ntfs_attr_put_search_ctx (ctx); -if (m) -unmap_mft_record (base_ni); -ntfs_debug ("Done, initialized_size 0x%llx, i_size 0x%llx." , - (unsigned long long )new_init_size,i_size_read (vi)); -return 0 ; -init_err_out: -write_lock_irqsave (&ni->size_lock, flags); - ni->initialized_size = old_init_size; -write_unlock_irqrestore (&ni->size_lock, flags); -err_out: -if (ctx) -ntfs_attr_put_search_ctx (ctx); -if (m) -unmap_mft_record (base_ni); -ntfs_debug ("Failed. Returning error code %i." , err); -return err; -} +ntfs_debug ("Entering for inode 0x%lx." , vi->i_ino); -static ssize_t ntfs_prepare_file_for_write (struct kiocb *iocb, -struct iov_iter *from) -{ -loff_t pos; -s64 end, ll; -ssize_t err; -unsigned long flags; -struct file *file = iocb->ki_filp; -struct inode *vi =file_inode (file); -ntfs_inode *ni =NTFS_I (vi); -ntfs_volume *vol = ni->vol; - -ntfs_debug ("Entering for i_ino 0x%lx, attribute type 0x%x, pos " -"0x%llx, count 0x%zx." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), - (unsigned long long )iocb->ki_pos, -iov_iter_count (from)); - err =generic_write_checks (iocb, from); -if (unlikely (err <=0 )) - goto out; -/* -* All checks have passed. Before we start doing any writing we want -* to abort any totally illegal writes. -*/ -BUG_ON (NInoMstProtected (ni)); -BUG_ON (ni->type !=AT_DATA ); -/* If file is encrypted, deny access, just like NT4. */ -if (NInoEncrypted (ni)) { -/* Only $DATA attributes can be encrypted. */ -/* -* Reminder for later: Encrypted files are _always_ -* non-resident so that the content can always be encrypted. -*/ -ntfs_debug ("Denying write access to encrypted file." ); - err = -EACCES ; - goto out; - } -if (NInoCompressed (ni)) { -/* Only unnamed $DATA attribute can be compressed. */ -BUG_ON (ni->name_len); -/* -* Reminder for later: If resident, the data is not actually -* compressed. Only on the switch to non-resident does -* compression kick in. This is in contrast to encrypted files -* (see above). -*/ -ntfs_error (vi->i_sb,"Writing to compressed files is not " -"implemented yet. Sorry." ); - err = -EOPNOTSUPP ; - goto out; - } - err =file_remove_privs (file); -if (unlikely (err)) - goto out; -/* -* Our ->update_time method always succeeds thus file_update_time() -* cannot fail either so there is no need to check the return code. -*/ -file_update_time (file); - pos = iocb->ki_pos; -/* The first byte after the last cluster being written to. */ - end = (pos +iov_iter_count (from) + vol->cluster_size_mask) & - ~(u64 )vol->cluster_size_mask; -/* -* If the write goes beyond the allocated size, extend the allocation -* to cover the whole of the write, rounded up to the nearest cluster. -*/ -read_lock_irqsave (&ni->size_lock, flags); - ll = ni->allocated_size; -read_unlock_irqrestore (&ni->size_lock, flags); -if (end > ll) { -/* -* Extend the allocation without changing the data size. -* -* Note we ensure the allocation is big enough to at least -* write some data but we do not require the allocation to be -* complete, i.e. it may be partial. -*/ - ll =ntfs_attr_extend_allocation (ni, end,-1 , pos); -if (likely (ll >=0 )) { -BUG_ON (pos >= ll); -/* If the extension was partial truncate the write. */ -if (end > ll) { -ntfs_debug ("Truncating write to inode 0x%lx, " -"attribute type 0x%x, because " -"the allocation was only " -"partially extended." , - vi->i_ino, (unsigned ) -le32_to_cpu (ni->type)); -iov_iter_truncate (from, ll - pos); - } - }else { - err = ll; -read_lock_irqsave (&ni->size_lock, flags); - ll = ni->allocated_size; -read_unlock_irqrestore (&ni->size_lock, flags); -/* Perform a partial write if possible or fail. */ -if (pos < ll) { -ntfs_debug ("Truncating write to inode 0x%lx " -"attribute type 0x%x, because " -"extending the allocation " -"failed (error %d)." , - vi->i_ino, (unsigned ) -le32_to_cpu (ni->type), - (int )-err); -iov_iter_truncate (from, ll - pos); - }else { -if (err != -ENOSPC ) -ntfs_error (vi->i_sb,"Cannot perform " -"write to inode " -"0x%lx, attribute " -"type 0x%x, because " -"extending the " -"allocation failed " -"(error %ld)." , - vi->i_ino, (unsigned ) -le32_to_cpu (ni->type), - (long )-err); -else -ntfs_debug ("Cannot perform write to " -"inode 0x%lx, " -"attribute type 0x%x, " -"because there is not " -"space left." , - vi->i_ino, (unsigned ) -le32_to_cpu (ni->type)); - goto out; +if (NVolShutdown (vol)) +return -EIO ; + + err =file_write_and_wait_range (filp, start, end); +if (err) +return err; + +if (!datasync || !NInoNonResident (NTFS_I (vi))) + ret =__ntfs_write_inode (vi,1 ); +write_inode_now (vi, !datasync); + + ctx =ntfs_attr_get_search_ctx (ni,NULL ); +if (!ctx) +return -ENOMEM ; + +mutex_lock_nested (&ni->mrec_lock,NTFS_INODE_MUTEX_NORMAL_2 ); +while (!(err =ntfs_attr_lookup (AT_UNUSED ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx))) { +if (ctx->attr->type ==AT_FILE_NAME ) { +struct file_name_attr *fn = (struct file_name_attr *)((u8 *)ctx->attr + +le16_to_cpu (ctx->attr->data.resident.value_offset)); + + parent_vi =ntfs_iget (vi->i_sb,MREF_LE (fn->parent_directory)); +if (IS_ERR (parent_vi)) +continue ; +mutex_lock_nested (&NTFS_I (parent_vi)->mrec_lock,NTFS_INODE_MUTEX_PARENT_2 ); + ia_vi =ntfs_index_iget (parent_vi,I30 ,4 ); +mutex_unlock (&NTFS_I (parent_vi)->mrec_lock); +if (IS_ERR (ia_vi)) { +iput (parent_vi); +continue ; } +write_inode_now (ia_vi,1 ); +iput (ia_vi); +write_inode_now (parent_vi,1 ); +iput (parent_vi); + }else if (ctx->attr->non_resident) { +struct inode *attr_vi; +__le16 *name; + + name = (__le16 *)((u8 *)ctx->attr +le16_to_cpu (ctx->attr->name_offset)); +if (ctx->attr->type ==AT_DATA && ctx->attr->name_length ==0 ) +continue ; + + attr_vi =ntfs_attr_iget (vi, ctx->attr->type, + name, ctx->attr->name_length); +if (IS_ERR (attr_vi)) +continue ; +spin_lock (&attr_vi->i_lock); +if (inode_state_read_once (attr_vi) &I_DIRTY_PAGES ) { +spin_unlock (&attr_vi->i_lock); +filemap_write_and_wait (attr_vi->i_mapping); + }else +spin_unlock (&attr_vi->i_lock); +iput (attr_vi); } } +mutex_unlock (&ni->mrec_lock); +ntfs_attr_put_search_ctx (ctx); + +write_inode_now (vol->mftbmp_ino,1 ); +down_write (&vol->lcnbmp_lock); +write_inode_now (vol->lcnbmp_ino,1 ); +up_write (&vol->lcnbmp_lock); +write_inode_now (vol->mft_ino,1 ); +/* -* If the write starts beyond the initialized size, extend it up to the -* beginning of the write and initialize all non-sparse space between -* the old initialized size and the new one. This automatically also -* increments the vfs inode->i_size to keep it above or equal to the -* initialized_size. +* NOTE: If we were to use mapping->private_list (see ext2 and +* fs/buffer.c) for dirty blocks then we could optimize the below to be +* sync_mapping_buffers(vi->i_mapping). */ -read_lock_irqsave (&ni->size_lock, flags); - ll = ni->initialized_size; -read_unlock_irqrestore (&ni->size_lock, flags); -if (pos > ll) { -/* -* Wait for ongoing direct i/o to complete before proceeding. -* New direct i/o cannot start as we hold i_mutex. -*/ -inode_dio_wait (vi); - err =ntfs_attr_extend_initialized (ni, pos); -if (unlikely (err <0 )) -ntfs_error (vi->i_sb,"Cannot perform write to inode " -"0x%lx, attribute type 0x%x, because " -"extending the initialized size " -"failed (error %d)." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), - (int )-err); - } -out: -return err; + err =sync_blockdev (vi->i_sb->s_bdev); +if (unlikely (err && !ret)) + ret = err; +if (likely (!ret)) +ntfs_debug ("Done." ); +else +ntfs_warning (vi->i_sb, +"Failed to f%ssync inode 0x%lx. Error %u." , + datasync ?"data" :"" , vi->i_ino, -ret); +if (!ret) +blkdev_issue_flush (vi->i_sb->s_bdev); +return ret; }/** -* __ntfs_grab_cache_pages - obtain a number of locked pages -* @mapping: address space mapping from which to obtain page cache pages -* @index: starting index in @mapping at which to begin obtaining pages -* @nr_pages: number of page cache pages to obtain -* @pages: array of pages in which to return the obtained page cache pages -* @cached_page: allocated but as yet unused page +* ntfsp_setattr - called from notify_change() when an attribute is being changed +* @idmap: idmap of the mount the inode was found from +* @dentry: dentry whose attributes to change +* @attr: structure describing the attributes and the changes * -* Obtain @nr_pages locked page cache pages from the mapping @mapping and -* starting at index @index. +* We have to trap VFS attempts to truncate the file described by @dentry as +* soon as possible, because we do not implement changes in i_size yet. So we +* abort all i_size changes here. * -* If a page is newly created, add it to lru list -* -* Note, the page locks are obtained in ascending page index order. +* We also abort all changes of user, group, and mode as we do not implement +* the NTFS ACLs yet. */ -static inline int __ntfs_grab_cache_pages (struct address_space *mapping, -pgoff_t index,const unsigned nr_pages,struct page **pages, -struct page **cached_page) +int ntfsp_setattr (struct mnt_idmap *idmap,struct dentry *dentry, +struct iattr *attr) { -int err, nr; - -BUG_ON (!nr_pages); - err = nr =0 ; -do { - pages[nr] =find_get_page_flags (mapping, index,FGP_LOCK | -FGP_ACCESSED ); -if (!pages[nr]) { -if (!*cached_page) { - *cached_page =page_cache_alloc (mapping); -if (unlikely (!*cached_page)) { - err = -ENOMEM ; - goto err_out; - } +struct inode *vi =d_inode (dentry); +int err; +unsigned int ia_valid = attr->ia_valid; +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; + +if (NVolShutdown (vol)) +return -EIO ; + + err =setattr_prepare (idmap, dentry, attr); +if (err) + goto out; + +if (!(vol->vol_flags &VOLUME_IS_DIRTY )) +ntfs_set_volume_flags (vol,VOLUME_IS_DIRTY ); + +if (ia_valid &ATTR_SIZE ) { +if (NInoCompressed (ni) ||NInoEncrypted (ni)) { +ntfs_warning (vi->i_sb, +"Changes in inode size are not supported yet for %s files, ignoring." , +NInoCompressed (ni) ?"compressed" :"encrypted" ); + err = -EOPNOTSUPP ; + }else { +loff_t old_size = vi->i_size; + + err =inode_newsize_ok (vi, attr->ia_size); +if (err) + goto out; + +inode_dio_wait (vi); +/* Serialize against page faults */ +if (NInoNonResident (NTFS_I (vi)) && + attr->ia_size < old_size) { + err =iomap_truncate_page (vi, attr->ia_size,NULL , + &ntfs_read_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); +if (err) + goto out; + } + +truncate_setsize (vi, attr->ia_size); + err =ntfs_truncate_vfs (vi, attr->ia_size, old_size); +if (err) { +i_size_write (vi, old_size); + goto out; } - err =add_to_page_cache_lru (*cached_page, mapping, - index, -mapping_gfp_constraint (mapping,GFP_KERNEL )); -if (unlikely (err)) { -if (err == -EEXIST ) -continue ; - goto err_out; + +if (NInoNonResident (ni) && attr->ia_size > old_size && + old_size %PAGE_SIZE !=0 ) { +loff_t len =min_t (loff_t, +round_up (old_size,PAGE_SIZE ) - old_size, + attr->ia_size - old_size); + err =iomap_zero_range (vi, old_size, len, +NULL , &ntfs_read_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); } - pages[nr] = *cached_page; - *cached_page =NULL ; } - index++; - nr++; - }while (nr < nr_pages); +if (ia_valid ==ATTR_SIZE ) + goto out; + ia_valid |=ATTR_MTIME |ATTR_CTIME ; + } + +setattr_copy (idmap, vi, attr); + +if (vol->sb->s_flags &SB_POSIXACL && !S_ISLNK (vi->i_mode)) { + err =posix_acl_chmod (idmap, dentry, vi->i_mode); +if (err) + goto out; + } + +if (0222 & vi->i_mode) + ni->flags &= ~FILE_ATTR_READONLY ; +else + ni->flags |=FILE_ATTR_READONLY ; + +if (ia_valid & (ATTR_UID |ATTR_GID |ATTR_MODE )) { +unsigned int flags =0 ; + +if (ia_valid &ATTR_UID ) + flags |=NTFS_EA_UID ; +if (ia_valid &ATTR_GID ) + flags |=NTFS_EA_GID ; +if (ia_valid &ATTR_MODE ) + flags |=NTFS_EA_MODE ; + +if (S_ISDIR (vi->i_mode)) + vi->i_mode &= ~vol->dmask; +else + vi->i_mode &= ~vol->fmask; + +mutex_lock (&ni->mrec_lock); +ntfs_ea_set_wsl_inode (vi,0 ,NULL , flags); +mutex_unlock (&ni->mrec_lock); + } + +mark_inode_dirty (vi); out:return err; -err_out: -while (nr >0 ) { -unlock_page (pages[--nr]); -put_page (pages[nr]); - } - goto out; } -static inline void ntfs_submit_bh_for_read (struct buffer_head *bh) +int ntfsp_getattr (struct mnt_idmap *idmap,const struct path *path, +struct kstat *stat,unsigned int request_mask, +unsigned int query_flags) { -lock_buffer (bh); -get_bh (bh); - bh->b_end_io = end_buffer_read_sync; -submit_bh (REQ_OP_READ , bh); +struct inode *inode =d_backing_inode (path->dentry); + +generic_fillattr (idmap, request_mask, inode, stat); + + stat->blksize =NTFS_SB (inode->i_sb)->cluster_size; + stat->blocks = (((u64 )NTFS_I (inode)->i_dealloc_clusters << +NTFS_SB (inode->i_sb)->cluster_size_bits) >>9 ) + inode->i_blocks; + stat->result_mask |=STATX_BTIME ; + stat->btime =NTFS_I (inode)->i_crtime; + +return 0 ; } -/** -* ntfs_prepare_pages_for_non_resident_write - prepare pages for receiving data -* @pages: array of destination pages -* @nr_pages: number of pages in @pages -* @pos: byte position in file at which the write begins -* @bytes: number of bytes to be written -* -* This is called for non-resident attributes from ntfs_file_buffered_write() -* with i_mutex held on the inode (@pages[0]->mapping->host). There are -* @nr_pages pages in @pages which are locked but not kmap()ped. The source -* data has not yet been copied into the @pages. -* -* Need to fill any holes with actual clusters, allocate buffers if necessary, -* ensure all the buffers are mapped, and bring uptodate any buffers that are -* only partially being written to. -* -* If @nr_pages is greater than one, we are guaranteed that the cluster size is -* greater than PAGE_SIZE, that all pages in @pages are entirely inside -* the same cluster and that they are the entirety of that cluster, and that -* the cluster is sparse, i.e. we need to allocate a cluster to fill the hole. -* -* i_size is not to be modified yet. -* -* Return 0 on success or -errno on error. -*/ -static int ntfs_prepare_pages_for_non_resident_write (struct page **pages, -unsigned nr_pages,s64 pos,size_t bytes) +static loff_t ntfs_file_llseek (struct file *file,loff_t offset,int whence) { -VCN vcn, highest_vcn =0 , cpos, cend, bh_cpos, bh_cend; -LCN lcn; -s64 bh_pos, vcn_len, end, initialized_size; -sector_t lcn_block; -struct folio *folio; -struct inode *vi; -ntfs_inode *ni, *base_ni =NULL ; -ntfs_volume *vol; -runlist_element *rl, *rl2; -struct buffer_head *bh, *head, *wait[2 ], **wait_bh = wait; -ntfs_attr_search_ctx *ctx =NULL ; -MFT_RECORD *m =NULL ; -ATTR_RECORD *a =NULL ; -unsigned long flags; -u32 attr_rec_len =0 ; -unsigned blocksize, u; -int err, mp_size; -bool rl_write_locked, was_hole, is_retry; -unsigned char blocksize_bits; -struct { -u8 runlist_merged:1 ; -u8 mft_attr_mapped:1 ; -u8 mp_rebuilt:1 ; -u8 attr_switched:1 ; - } status = {0 ,0 ,0 ,0 }; - -BUG_ON (!nr_pages); -BUG_ON (!pages); -BUG_ON (!*pages); - vi = pages[0 ]->mapping->host; - ni =NTFS_I (vi); - vol = ni->vol; -ntfs_debug ("Entering for inode 0x%lx, attribute type 0x%x, start page " -"index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx." , - vi->i_ino, ni->type, pages[0 ]->index, nr_pages, - (long long )pos, bytes); - blocksize = vol->sb->s_blocksize; - blocksize_bits = vol->sb->s_blocksize_bits; - rl_write_locked = false; - rl =NULL ; - err =0 ; - vcn = lcn =-1 ; - vcn_len =0 ; - lcn_block =-1 ; - was_hole = false; - cpos = pos >> vol->cluster_size_bits; - end = pos + bytes; - cend = (end + vol->cluster_size -1 ) >> vol->cluster_size_bits; -/* -* Loop over each buffer in each folio. Use goto to -* reduce indentation. -*/ - u =0 ; -do_next_folio: - folio =page_folio (pages[u]); - bh_pos =folio_pos (folio); - head =folio_buffers (folio); -if (!head) -/* -* create_empty_buffers() will create uptodate/dirty -* buffers if the folio is uptodate/dirty. -*/ - head =create_empty_buffers (folio, blocksize,0 ); - bh = head; -do { -VCN cdelta; -s64 bh_end; -unsigned bh_cofs; - -/* Clear buffer_new on all buffers to reinitialise state. */ -if (buffer_new (bh)) -clear_buffer_new (bh); - bh_end = bh_pos + blocksize; - bh_cpos = bh_pos >> vol->cluster_size_bits; - bh_cofs = bh_pos & vol->cluster_size_mask; -if (buffer_mapped (bh)) { -/* -* The buffer is already mapped. If it is uptodate, -* ignore it. -*/ -if (buffer_uptodate (bh)) -continue ; -/* -* The buffer is not uptodate. If the folio is uptodate -* set the buffer uptodate and otherwise ignore it. -*/ -if (folio_test_uptodate (folio)) { -set_buffer_uptodate (bh); -continue ; - } -/* -* Neither the folio nor the buffer are uptodate. If -* the buffer is only partially being written to, we -* need to read it in before the write, i.e. now. -*/ -if ((bh_pos < pos && bh_end > pos) || - (bh_pos < end && bh_end > end)) { -/* -* If the buffer is fully or partially within -* the initialized size, do an actual read. -* Otherwise, simply zero the buffer. -*/ -read_lock_irqsave (&ni->size_lock, flags); - initialized_size = ni->initialized_size; -read_unlock_irqrestore (&ni->size_lock, flags); -if (bh_pos < initialized_size) { -ntfs_submit_bh_for_read (bh); - *wait_bh++ = bh; - }else { -folio_zero_range (folio,bh_offset (bh), - blocksize); -set_buffer_uptodate (bh); - } - } -continue ; - } -/* Unmapped buffer. Need to map it. */ - bh->b_bdev = vol->sb->s_bdev; -/* -* If the current buffer is in the same clusters as the map -* cache, there is no need to check the runlist again. The -* map cache is made up of @vcn, which is the first cached file -* cluster, @vcn_len which is the number of cached file -* clusters, @lcn is the device cluster corresponding to @vcn, -* and @lcn_block is the block number corresponding to @lcn. -*/ - cdelta = bh_cpos - vcn; -if (likely (!cdelta || (cdelta >0 && cdelta < vcn_len))) { -map_buffer_cached: -BUG_ON (lcn <0 ); - bh->b_blocknr = lcn_block + - (cdelta << (vol->cluster_size_bits - - blocksize_bits)) + - (bh_cofs >> blocksize_bits); -set_buffer_mapped (bh); -/* -* If the folio is uptodate so is the buffer. If the -* buffer is fully outside the write, we ignore it if -* it was already allocated and we mark it dirty so it -* gets written out if we allocated it. On the other -* hand, if we allocated the buffer but we are not -* marking it dirty we set buffer_new so we can do -* error recovery. -*/ -if (folio_test_uptodate (folio)) { -if (!buffer_uptodate (bh)) -set_buffer_uptodate (bh); -if (unlikely (was_hole)) { -/* We allocated the buffer. */ -clean_bdev_bh_alias (bh); -if (bh_end <= pos || bh_pos >= end) -mark_buffer_dirty (bh); -else -set_buffer_new (bh); - } -continue ; - } -/* Page is _not_ uptodate. */ -if (likely (!was_hole)) { -/* -* Buffer was already allocated. If it is not -* uptodate and is only partially being written -* to, we need to read it in before the write, -* i.e. now. -*/ -if (!buffer_uptodate (bh) && bh_pos < end && - bh_end > pos && - (bh_pos < pos || - bh_end > end)) { -/* -* If the buffer is fully or partially -* within the initialized size, do an -* actual read. Otherwise, simply zero -* the buffer. -*/ -read_lock_irqsave (&ni->size_lock, - flags); - initialized_size = ni->initialized_size; -read_unlock_irqrestore (&ni->size_lock, - flags); -if (bh_pos < initialized_size) { -ntfs_submit_bh_for_read (bh); - *wait_bh++ = bh; - }else { -folio_zero_range (folio, -bh_offset (bh), - blocksize); -set_buffer_uptodate (bh); - } - } -continue ; - } -/* We allocated the buffer. */ -clean_bdev_bh_alias (bh); -/* -* If the buffer is fully outside the write, zero it, -* set it uptodate, and mark it dirty so it gets -* written out. If it is partially being written to, -* zero region surrounding the write but leave it to -* commit write to do anything else. Finally, if the -* buffer is fully being overwritten, do nothing. -*/ -if (bh_end <= pos || bh_pos >= end) { -if (!buffer_uptodate (bh)) { -folio_zero_range (folio,bh_offset (bh), - blocksize); -set_buffer_uptodate (bh); - } -mark_buffer_dirty (bh); -continue ; - } -set_buffer_new (bh); -if (!buffer_uptodate (bh) && - (bh_pos < pos || bh_end > end)) { -u8 *kaddr; -unsigned pofs; - - kaddr =kmap_local_folio (folio,0 ); -if (bh_pos < pos) { - pofs = bh_pos & ~PAGE_MASK ; -memset (kaddr + pofs,0 , pos - bh_pos); - } -if (bh_end > end) { - pofs = end & ~PAGE_MASK ; -memset (kaddr + pofs,0 , bh_end - end); - } -kunmap_local (kaddr); -flush_dcache_folio (folio); - } -continue ; - } -/* -* Slow path: this is the first buffer in the cluster. If it -* is outside allocated size and is not uptodate, zero it and -* set it uptodate. -*/ +struct inode *vi = file->f_mapping->host; + +if (whence ==SEEK_DATA || whence ==SEEK_HOLE ) { +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; +struct runlist_element *rl; +s64 vcn; +unsigned int vcn_off; +loff_t end_off; +unsigned long flags; +int i; + +inode_lock_shared (vi); + +if (NInoCompressed (ni) ||NInoEncrypted (ni)) + goto error; +read_lock_irqsave (&ni->size_lock, flags); - initialized_size = ni->allocated_size; + end_off = ni->data_size;read_unlock_irqrestore (&ni->size_lock, flags); -if (bh_pos > initialized_size) { -if (folio_test_uptodate (folio)) { -if (!buffer_uptodate (bh)) -set_buffer_uptodate (bh); - }else if (!buffer_uptodate (bh)) { -folio_zero_range (folio,bh_offset (bh), - blocksize); -set_buffer_uptodate (bh); - } -continue ; - } - is_retry = false; -if (!rl) { -down_read (&ni->runlist.lock); -retry_remap: - rl = ni->runlist.rl; + +if (offset <0 || offset >= end_off) + goto error; + +if (!NInoNonResident (ni)) { +if (whence ==SEEK_HOLE ) + offset = end_off; + goto found_no_runlist_lock; } -if (likely (rl !=NULL )) { -/* Seek to element containing target cluster. */ -while (rl->length && rl[1 ].vcn <= bh_cpos) - rl++; - lcn =ntfs_rl_vcn_to_lcn (rl, bh_cpos); -if (likely (lcn >=0 )) { -/* -* Successful remap, setup the map cache and -* use that to deal with the buffer. -*/ - was_hole = false; - vcn = bh_cpos; - vcn_len = rl[1 ].vcn - vcn; - lcn_block = lcn << (vol->cluster_size_bits - - blocksize_bits); - cdelta =0 ; -/* -* If the number of remaining clusters touched -* by the write is smaller or equal to the -* number of cached clusters, unlock the -* runlist as the map cache will be used from -* now on. -*/ -if (likely (vcn + vcn_len >= cend)) { -if (rl_write_locked) { -up_write (&ni->runlist.lock); - rl_write_locked = false; - }else -up_read (&ni->runlist.lock); - rl =NULL ; - } - goto map_buffer_cached; - } - }else - lcn =LCN_RL_NOT_MAPPED ; -/* -* If it is not a hole and not out of bounds, the runlist is -* probably unmapped so try to map it now. -*/ -if (unlikely (lcn !=LCN_HOLE && lcn !=LCN_ENOENT )) { -if (likely (!is_retry && lcn ==LCN_RL_NOT_MAPPED )) { -/* Attempt to map runlist. */ -if (!rl_write_locked) { -/* -* We need the runlist locked for -* writing, so if it is locked for -* reading relock it now and retry in -* case it changed whilst we dropped -* the lock. -*/ + + vcn =NTFS_B_TO_CLU (vol, offset); + vcn_off =NTFS_B_TO_CLU_OFS (vol, offset); + +down_read (&ni->runlist.lock); + rl = ni->runlist.rl; + i =0 ; + +#ifdef DEBUG +ntfs_debug ("init:" ); +ntfs_debug_dump_runlist (rl); +#endif +while (1 ) { +if (!rl || !NInoFullyMapped (ni) || rl[i].lcn ==LCN_RL_NOT_MAPPED ) { +int ret; + +up_read (&ni->runlist.lock); + ret =ntfs_map_runlist (ni, rl ? rl[i].vcn :0 ); +if (ret) + goto error; +down_read (&ni->runlist.lock); + rl = ni->runlist.rl; +#ifdef DEBUG +ntfs_debug ("mapped:" ); +ntfs_debug_dump_runlist (ni->runlist.rl); +#endif +continue ; + }else if (rl[i].lcn ==LCN_ENOENT ) { +if (whence ==SEEK_DATA ) {up_read (&ni->runlist.lock); -down_write (&ni->runlist.lock); - rl_write_locked = true; - goto retry_remap; - } - err =ntfs_map_runlist_nolock (ni, bh_cpos, -NULL ); -if (likely (!err)) { - is_retry = true; - goto retry_remap; - } -/* -* If @vcn is out of bounds, pretend @lcn is -* LCN_ENOENT. As long as the buffer is out -* of bounds this will work fine. -*/ -if (err == -ENOENT ) { - lcn =LCN_ENOENT ; - err =0 ; - goto rl_not_mapped_enoent; - } - }else - err = -EIO ; -/* Failed to map the buffer, even after retrying. */ - bh->b_blocknr =-1 ; -ntfs_error (vol->sb,"Failed to write to inode 0x%lx, " -"attribute type 0x%x, vcn 0x%llx, " -"vcn offset 0x%x, because its " -"location on disk could not be " -"determined%s (error code %i)." , - ni->mft_no, ni->type, - (unsigned long long )bh_cpos, - (unsigned )bh_pos & - vol->cluster_size_mask, - is_retry ?" even after retrying" :"" , - err); -break ; - } -rl_not_mapped_enoent: -/* -* The buffer is in a hole or out of bounds. We need to fill -* the hole, unless the buffer is in a cluster which is not -* touched by the write, in which case we just leave the buffer -* unmapped. This can only happen when the cluster size is -* less than the page cache size. -*/ -if (unlikely (vol->cluster_size <PAGE_SIZE )) { - bh_cend = (bh_end + vol->cluster_size -1 ) >> - vol->cluster_size_bits; -if ((bh_cend <= cpos || bh_cpos >= cend)) { - bh->b_blocknr =-1 ; -/* -* If the buffer is uptodate we skip it. If it -* is not but the folio is uptodate, we can set -* the buffer uptodate. If the folio is not -* uptodate, we can clear the buffer and set it -* uptodate. Whether this is worthwhile is -* debatable and this could be removed. -*/ -if (folio_test_uptodate (folio)) { -if (!buffer_uptodate (bh)) -set_buffer_uptodate (bh); - }else if (!buffer_uptodate (bh)) { -folio_zero_range (folio,bh_offset (bh), - blocksize); -set_buffer_uptodate (bh); + goto error; + }else { + offset = end_off; + goto found; } -continue ; - } - } -/* -* Out of bounds buffer is invalid if it was not really out of -* bounds. -*/ -BUG_ON (lcn !=LCN_HOLE ); -/* -* We need the runlist locked for writing, so if it is locked -* for reading relock it now and retry in case it changed -* whilst we dropped the lock. -*/ -BUG_ON (!rl); -if (!rl_write_locked) { -up_read (&ni->runlist.lock); -down_write (&ni->runlist.lock); - rl_write_locked = true; - goto retry_remap; - } -/* Find the previous last allocated cluster. */ -BUG_ON (rl->lcn !=LCN_HOLE ); - lcn =-1 ; - rl2 = rl; -while (--rl2 >= ni->runlist.rl) { -if (rl2->lcn >=0 ) { - lcn = rl2->lcn + rl2->length; -break ; - } - } - rl2 =ntfs_cluster_alloc (vol, bh_cpos,1 , lcn,DATA_ZONE , - false); -if (IS_ERR (rl2)) { - err =PTR_ERR (rl2); -ntfs_debug ("Failed to allocate cluster, error code %i." , - err); -break ; - } - lcn = rl2->lcn; - rl =ntfs_runlists_merge (ni->runlist.rl, rl2); -if (IS_ERR (rl)) { - err =PTR_ERR (rl); -if (err != -ENOMEM ) - err = -EIO ; -if (ntfs_cluster_free_from_rl (vol, rl2)) { -ntfs_error (vol->sb,"Failed to release " -"allocated cluster in error " -"code path. Run chkdsk to " -"recover the lost cluster." ); -NVolSetErrors (vol); - } -ntfs_free (rl2); -break ; - } - ni->runlist.rl = rl; - status.runlist_merged =1 ; -ntfs_debug ("Allocated cluster, lcn 0x%llx." , - (unsigned long long )lcn); -/* Map and lock the mft record and get the attribute record. */ -if (!NInoAttr (ni)) - base_ni = ni; -else - base_ni = ni->ext.base_ntfs_ino; - m =map_mft_record (base_ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); -break ; - } - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; -unmap_mft_record (base_ni); -break ; - } - status.mft_attr_mapped =1 ; - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE , bh_cpos,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) - err = -EIO ; -break ; - } - m = ctx->mrec; - a = ctx->attr; -/* -* Find the runlist element with which the attribute extent -* starts. Note, we cannot use the _attr_ version because we -* have mapped the mft record. That is ok because we know the -* runlist fragment must be mapped already to have ever gotten -* here, so we can just use the _rl_ version. -*/ - vcn =sle64_to_cpu (a->data.non_resident.lowest_vcn); - rl2 =ntfs_rl_find_vcn_nolock (rl, vcn); -BUG_ON (!rl2); -BUG_ON (!rl2->length); -BUG_ON (rl2->lcn <LCN_HOLE ); - highest_vcn =sle64_to_cpu (a->data.non_resident.highest_vcn); -/* -* If @highest_vcn is zero, calculate the real highest_vcn -* (which can really be zero). -*/ -if (!highest_vcn) - highest_vcn = (sle64_to_cpu ( - a->data.non_resident.allocated_size) >> - vol->cluster_size_bits) -1 ; -/* -* Determine the size of the mapping pairs array for the new -* extent, i.e. the old extent with the hole filled. -*/ - mp_size =ntfs_get_size_for_mapping_pairs (vol, rl2, vcn, - highest_vcn); -if (unlikely (mp_size <=0 )) { -if (!(err = mp_size)) - err = -EIO ; -ntfs_debug ("Failed to get size for mapping pairs " -"array, error code %i." , err); -break ; - } -/* -* Resize the attribute record to fit the new mapping pairs -* array. -*/ - attr_rec_len =le32_to_cpu (a->length); - err =ntfs_attr_record_resize (m, a, mp_size +le16_to_cpu ( - a->data.non_resident.mapping_pairs_offset)); -if (unlikely (err)) { -BUG_ON (err != -ENOSPC ); -// TODO: Deal with this by using the current attribute -// and fill it with as much of the mapping pairs -// array as possible. Then loop over each attribute -// extent rewriting the mapping pairs arrays as we go -// along and if when we reach the end we have not -// enough space, try to resize the last attribute -// extent and if even that fails, add a new attribute -// extent. -// We could also try to resize at each step in the hope -// that we will not need to rewrite every single extent. -// Note, we may need to decompress some extents to fill -// the runlist as we are walking the extents... -ntfs_error (vol->sb,"Not enough space in the mft " -"record for the extended attribute " -"record. This case is not " -"implemented yet." ); - err = -EOPNOTSUPP ; -break ; - } - status.mp_rebuilt =1 ; -/* -* Generate the mapping pairs array directly into the attribute -* record. -*/ - err =ntfs_mapping_pairs_build (vol, (u8 *)a +le16_to_cpu ( - a->data.non_resident.mapping_pairs_offset), - mp_size, rl2, vcn, highest_vcn,NULL ); -if (unlikely (err)) { -ntfs_error (vol->sb,"Cannot fill hole in inode 0x%lx, " -"attribute type 0x%x, because building " -"the mapping pairs failed with error " -"code %i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); - err = -EIO ; -break ; - } -/* Update the highest_vcn but only if it was not set. */ -if (unlikely (!a->data.non_resident.highest_vcn)) - a->data.non_resident.highest_vcn = -cpu_to_sle64 (highest_vcn); -/* -* If the attribute is sparse/compressed, update the compressed -* size in the ntfs_inode structure and the attribute record. -*/ -if (likely (NInoSparse (ni) ||NInoCompressed (ni))) { -/* -* If we are not in the first attribute extent, switch -* to it, but first ensure the changes will make it to -* disk later. -*/ -if (a->data.non_resident.lowest_vcn) { -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -ntfs_attr_reinit_search_ctx (ctx); - err =ntfs_attr_lookup (ni->type, ni->name, - ni->name_len,CASE_SENSITIVE , -0 ,NULL ,0 , ctx); -if (unlikely (err)) { - status.attr_switched =1 ; -break ; + }else if (rl[i +1 ].vcn > vcn) { +if ((whence ==SEEK_DATA && (rl[i].lcn >=0 || + rl[i].lcn ==LCN_DELALLOC )) || + (whence ==SEEK_HOLE && rl[i].lcn ==LCN_HOLE )) { + offset =NTFS_CLU_TO_B (vol, vcn) + vcn_off; +if (offset < ni->data_size) + goto found; } -/* @m is not used any more so do not set it. */ - a = ctx->attr; + vcn = rl[i +1 ].vcn; + vcn_off =0 ; } -write_lock_irqsave (&ni->size_lock, flags); - ni->itype.compressed.size += vol->cluster_size; - a->data.non_resident.compressed_size = -cpu_to_sle64 (ni->itype.compressed.size); -write_unlock_irqrestore (&ni->size_lock, flags); + i++; } -/* Ensure the changes make it to disk. */ -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); -/* Successfully filled the hole. */ - status.runlist_merged =0 ; - status.mft_attr_mapped =0 ; - status.mp_rebuilt =0 ; -/* Setup the map cache and use that to deal with the buffer. */ - was_hole = true; - vcn = bh_cpos; - vcn_len =1 ; - lcn_block = lcn << (vol->cluster_size_bits - blocksize_bits); - cdelta =0 ; -/* -* If the number of remaining clusters in the @pages is smaller -* or equal to the number of cached clusters, unlock the -* runlist as the map cache will be used from now on. -*/ -if (likely (vcn + vcn_len >= cend)) { -up_write (&ni->runlist.lock); - rl_write_locked = false; - rl =NULL ; - } - goto map_buffer_cached; - }while (bh_pos += blocksize, (bh = bh->b_this_page) != head); -/* If there are no errors, do the next page. */ -if (likely (!err && ++u < nr_pages)) - goto do_next_folio; -/* If there are no errors, release the runlist lock if we took it. */ -if (likely (!err)) { -if (unlikely (rl_write_locked)) { -up_write (&ni->runlist.lock); - rl_write_locked = false; - }else if (unlikely (rl)) -up_read (&ni->runlist.lock); - rl =NULL ; - } -/* If we issued read requests, let them complete. */ -read_lock_irqsave (&ni->size_lock, flags); - initialized_size = ni->initialized_size; -read_unlock_irqrestore (&ni->size_lock, flags); -while (wait_bh > wait) { - bh = *--wait_bh; -wait_on_buffer (bh); -if (likely (buffer_uptodate (bh))) { - folio = bh->b_folio; - bh_pos =folio_pos (folio) +bh_offset (bh); -/* -* If the buffer overflows the initialized size, need -* to zero the overflowing region. -*/ -if (unlikely (bh_pos + blocksize > initialized_size)) { -int ofs =0 ; - -if (likely (bh_pos < initialized_size)) - ofs = initialized_size - bh_pos; -folio_zero_segment (folio,bh_offset (bh) + ofs, - blocksize); - } - }else /* if (unlikely(!buffer_uptodate(bh))) */ - err = -EIO ; - } -if (likely (!err)) { -/* Clear buffer_new on all buffers. */ - u =0 ; -do { - bh = head =page_buffers (pages[u]); -do { -if (buffer_new (bh)) -clear_buffer_new (bh); - }while ((bh = bh->b_this_page) != head); - }while (++u < nr_pages); -ntfs_debug ("Done." ); -return err; +up_read (&ni->runlist.lock); +inode_unlock_shared (vi); +return -EIO ; +found: +up_read (&ni->runlist.lock); +found_no_runlist_lock: +inode_unlock_shared (vi); +return vfs_setpos (file, offset, vi->i_sb->s_maxbytes); +error: +inode_unlock_shared (vi); +return -ENXIO ; + }else { +return generic_file_llseek_size (file, offset, whence, + vi->i_sb->s_maxbytes, +i_size_read (vi)); } -if (status.attr_switched) { -/* Get back to the attribute extent we modified. */ -ntfs_attr_reinit_search_ctx (ctx); -if (ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE , bh_cpos,NULL ,0 , ctx)) { -ntfs_error (vol->sb,"Failed to find required " -"attribute extent of attribute in " -"error code path. Run chkdsk to " -"recover." ); -write_lock_irqsave (&ni->size_lock, flags); - ni->itype.compressed.size += vol->cluster_size; -write_unlock_irqrestore (&ni->size_lock, flags); -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -/* -* The only thing that is now wrong is the compressed -* size of the base attribute extent which chkdsk -* should be able to fix. -*/ -NVolSetErrors (vol); - }else { - m = ctx->mrec; - a = ctx->attr; - status.attr_switched =0 ; +} + +static ssize_t ntfs_file_read_iter (struct kiocb *iocb,struct iov_iter *to) +{ +struct inode *vi =file_inode (iocb->ki_filp); +struct super_block *sb = vi->i_sb; +ssize_t ret; + +if (NVolShutdown (NTFS_SB (sb))) +return -EIO ; + +if (NInoCompressed (NTFS_I (vi)) && iocb->ki_flags &IOCB_DIRECT ) +return -EOPNOTSUPP ; + +inode_lock_shared (vi); + +if (iocb->ki_flags &IOCB_DIRECT ) { +size_t count =iov_iter_count (to); + +if ((iocb->ki_pos | count) & (sb->s_blocksize -1 )) { + ret = -EINVAL ; + goto inode_unlock; } + +file_accessed (iocb->ki_filp); + ret =iomap_dio_rw (iocb, to, &ntfs_read_iomap_ops,NULL ,IOMAP_DIO_PARTIAL , +NULL ,0 ); + }else { + ret =generic_file_read_iter (iocb, to); } -/* -* If the runlist has been modified, need to restore it by punching a -* hole into it and we then need to deallocate the on-disk cluster as -* well. Note, we only modify the runlist if we are able to generate a -* new mapping pairs array, i.e. only when the mapped attribute extent -* is not switched. -*/ -if (status.runlist_merged && !status.attr_switched) { -BUG_ON (!rl_write_locked); -/* Make the file cluster we allocated sparse in the runlist. */ -if (ntfs_rl_punch_nolock (vol, &ni->runlist, bh_cpos,1 )) { -ntfs_error (vol->sb,"Failed to punch hole into " -"attribute runlist in error code " -"path. Run chkdsk to recover the " -"lost cluster." ); -NVolSetErrors (vol); - }else /* if (success) */ { - status.runlist_merged =0 ; -/* -* Deallocate the on-disk cluster we allocated but only -* if we succeeded in punching its vcn out of the -* runlist. -*/ -down_write (&vol->lcnbmp_lock); -if (ntfs_bitmap_clear_bit (vol->lcnbmp_ino, lcn)) { -ntfs_error (vol->sb,"Failed to release " -"allocated cluster in error " -"code path. Run chkdsk to " -"recover the lost cluster." ); -NVolSetErrors (vol); - } -up_write (&vol->lcnbmp_lock); + +inode_unlock: +inode_unlock_shared (vi); + +return ret; +} + +static int ntfs_file_write_dio_end_io (struct kiocb *iocb,ssize_t size, +int error,unsigned int flags) +{ +struct inode *inode =file_inode (iocb->ki_filp); + +if (error) +return error; + +if (size) { +if (i_size_read (inode) < iocb->ki_pos + size) { +i_size_write (inode, iocb->ki_pos + size); +mark_inode_dirty (inode); } } -/* -* Resize the attribute record to its old size and rebuild the mapping -* pairs array. Note, we only can do this if the runlist has been -* restored to its old state which also implies that the mapped -* attribute extent is not switched. -*/ -if (status.mp_rebuilt && !status.runlist_merged) { -if (ntfs_attr_record_resize (m, a, attr_rec_len)) { -ntfs_error (vol->sb,"Failed to restore attribute " -"record in error code path. Run " -"chkdsk to recover." ); -NVolSetErrors (vol); - }else /* if (success) */ { -if (ntfs_mapping_pairs_build (vol, (u8 *)a + -le16_to_cpu (a->data.non_resident. - mapping_pairs_offset), attr_rec_len - -le16_to_cpu (a->data.non_resident. - mapping_pairs_offset), ni->runlist.rl, - vcn, highest_vcn,NULL )) { -ntfs_error (vol->sb,"Failed to restore " -"mapping pairs array in error " -"code path. Run chkdsk to " -"recover." ); -NVolSetErrors (vol); + +return 0 ; +} + +static const struct iomap_dio_ops ntfs_write_dio_ops = { + .end_io = ntfs_file_write_dio_end_io, +}; + +static ssize_t ntfs_file_write_iter (struct kiocb *iocb,struct iov_iter *from) +{ +struct file *file = iocb->ki_filp; +struct inode *vi = file->f_mapping->host; +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; +ssize_t ret; +ssize_t count; +loff_t pos; +int err; +loff_t old_data_size, old_init_size; + +if (NVolShutdown (vol)) +return -EIO ; + +if (NInoEncrypted (ni)) { +ntfs_error (vi->i_sb,"Writing for %s files is not supported yet" , +NInoCompressed (ni) ?"Compressed" :"Encrypted" ); +return -EOPNOTSUPP ; + } + +if (NInoCompressed (ni) && iocb->ki_flags &IOCB_DIRECT ) +return -EOPNOTSUPP ; + +if (iocb->ki_flags &IOCB_NOWAIT ) { +if (!inode_trylock (vi)) +return -EAGAIN ; + }else +inode_lock (vi); + + ret =generic_write_checks (iocb, from); +if (ret <=0 ) + goto out_lock; + +if (NInoNonResident (ni) && (iocb->ki_flags &IOCB_DIRECT ) && + ((iocb->ki_pos | ret) & (vi->i_sb->s_blocksize -1 ))) { + ret = -EINVAL ; + goto out_lock; + } + + err =file_modified (iocb->ki_filp); +if (err) { + ret = err; + goto out_lock; + } + +if (!(vol->vol_flags &VOLUME_IS_DIRTY )) +ntfs_set_volume_flags (vol,VOLUME_IS_DIRTY ); + + pos = iocb->ki_pos; + count = ret; + + old_data_size = ni->data_size; + old_init_size = ni->initialized_size; +if (iocb->ki_pos + ret > old_data_size) { +mutex_lock (&ni->mrec_lock); +if (!NInoCompressed (ni) && iocb->ki_pos + ret > ni->allocated_size && + iocb->ki_pos + ret < ni->allocated_size + vol->preallocated_size) + ret =ntfs_attr_expand (ni, iocb->ki_pos + ret, + ni->allocated_size + vol->preallocated_size); +else if (NInoCompressed (ni) && iocb->ki_pos + ret > ni->allocated_size) + ret =ntfs_attr_expand (ni, iocb->ki_pos + ret, +round_up (iocb->ki_pos + ret, ni->itype.compressed.block_size)); +else + ret =ntfs_attr_expand (ni, iocb->ki_pos + ret,0 ); +mutex_unlock (&ni->mrec_lock); +if (ret <0 ) + goto out; + } + +if (NInoNonResident (ni) && iocb->ki_pos + count > old_init_size) { + ret =ntfs_extend_initialized_size (vi, iocb->ki_pos, + iocb->ki_pos + count); +if (ret <0 ) + goto out; + } + +if (NInoNonResident (ni) &&NInoCompressed (ni)) { + ret =ntfs_compress_write (ni, pos, count, from); +if (ret >0 ) + iocb->ki_pos += ret; + goto out; + } + +if (NInoNonResident (ni) && iocb->ki_flags &IOCB_DIRECT ) { + ret =iomap_dio_rw (iocb, from, &ntfs_dio_iomap_ops, + &ntfs_write_dio_ops,0 ,NULL ,0 ); +if (ret == -ENOTBLK ) + ret =0 ; +else if (ret <0 ) + goto out; + +if (iov_iter_count (from)) { +loff_t offset, end; +ssize_t written; +int ret2; + + offset = iocb->ki_pos; + iocb->ki_flags &= ~IOCB_DIRECT ; + written =iomap_file_buffered_write (iocb, from, + &ntfs_write_iomap_ops, &ntfs_iomap_folio_ops, +NULL ); +if (written <0 ) { + err = written; + goto out; } -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); + + ret += written; + end = iocb->ki_pos + written -1 ; + ret2 =filemap_write_and_wait_range (iocb->ki_filp->f_mapping, + offset, end); +if (ret2) + goto out_err; +if (!ret2) +invalidate_mapping_pages (iocb->ki_filp->f_mapping, + offset >>PAGE_SHIFT , + end >>PAGE_SHIFT ); } + }else { + ret =iomap_file_buffered_write (iocb, from, &ntfs_write_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); } -/* Release the mft record and the attribute. */ -if (status.mft_attr_mapped) { -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); +out: +if (ret <0 && ret != -EIOCBQUEUED ) { +out_err: +if (ni->initialized_size != old_init_size) { +mutex_lock (&ni->mrec_lock); +ntfs_attr_set_initialized_size (ni, old_init_size); +mutex_unlock (&ni->mrec_lock); + } +if (ni->data_size != old_data_size) { +truncate_setsize (vi, old_data_size); +ntfs_attr_truncate (ni, old_data_size); + } } -/* Release the runlist lock. */ -if (rl_write_locked) -up_write (&ni->runlist.lock); -else if (rl) -up_read (&ni->runlist.lock); -/* -* Zero out any newly allocated blocks to avoid exposing stale data. -* If BH_New is set, we know that the block was newly allocated above -* and that it has not been fully zeroed and marked dirty yet. -*/ - nr_pages = u; - u =0 ; - end = bh_cpos << vol->cluster_size_bits; -do { - folio =page_folio (pages[u]); - bh = head =folio_buffers (folio); -do { -if (u == nr_pages && -folio_pos (folio) +bh_offset (bh) >= end) -break ; -if (!buffer_new (bh)) -continue ; -clear_buffer_new (bh); -if (!buffer_uptodate (bh)) { -if (folio_test_uptodate (folio)) -set_buffer_uptodate (bh); -else { -folio_zero_range (folio,bh_offset (bh), - blocksize); -set_buffer_uptodate (bh); - } - } -mark_buffer_dirty (bh); - }while ((bh = bh->b_this_page) != head); - }while (++u <= nr_pages); -ntfs_error (vol->sb,"Failed. Returning error code %i." , err); -return err; +out_lock: +inode_unlock (vi); +if (ret >0 ) + ret =generic_write_sync (iocb, ret); +return ret; } -static inline void ntfs_flush_dcache_pages (struct page **pages, -unsigned nr_pages) +static vm_fault_t ntfs_filemap_page_mkwrite (struct vm_fault *vmf) { -BUG_ON (!nr_pages); -/* -* Warning: Do not do the decrement at the same time as the call to -* flush_dcache_page() because it is a NULL macro on i386 and hence the -* decrement never happens so the loop never terminates. -*/ -do { - --nr_pages; -flush_dcache_page (pages[nr_pages]); - }while (nr_pages >0 ); +struct inode *inode =file_inode (vmf->vma->vm_file); +vm_fault_t ret; + +if (unlikely (IS_IMMUTABLE (inode))) +return VM_FAULT_SIGBUS ; + +sb_start_pagefault (inode->i_sb); +file_update_time (vmf->vma->vm_file); + + ret =iomap_page_mkwrite (vmf, &ntfs_page_mkwrite_iomap_ops,NULL ); +sb_end_pagefault (inode->i_sb); +return ret; } -/** -* ntfs_commit_pages_after_non_resident_write - commit the received data -* @pages: array of destination pages -* @nr_pages: number of pages in @pages -* @pos: byte position in file at which the write begins -* @bytes: number of bytes to be written -* -* See description of ntfs_commit_pages_after_write(), below. -*/ -static inline int ntfs_commit_pages_after_non_resident_write ( -struct page **pages,const unsigned nr_pages, -s64 pos,size_t bytes) +static const struct vm_operations_struct ntfs_file_vm_ops = { + .fault = filemap_fault, + .map_pages = filemap_map_pages, + .page_mkwrite = ntfs_filemap_page_mkwrite, +}; + +static int ntfs_file_mmap_prepare (struct vm_area_desc *desc) { -s64 end, initialized_size; -struct inode *vi; -ntfs_inode *ni, *base_ni; -struct buffer_head *bh, *head; -ntfs_attr_search_ctx *ctx; -MFT_RECORD *m; -ATTR_RECORD *a; -unsigned long flags; -unsigned blocksize, u; -int err; +struct file *file = desc->file; +struct inode *inode =file_inode (file); - vi = pages[0 ]->mapping->host; - ni =NTFS_I (vi); - blocksize = vi->i_sb->s_blocksize; - end = pos + bytes; - u =0 ; -do { -s64 bh_pos; -struct page *page; -bool partial; - - page = pages[u]; - bh_pos = (s64 )page->index <<PAGE_SHIFT ; - bh = head =page_buffers (page); - partial = false; -do { -s64 bh_end; - - bh_end = bh_pos + blocksize; -if (bh_end <= pos || bh_pos >= end) { -if (!buffer_uptodate (bh)) - partial = true; - }else { -set_buffer_uptodate (bh); -mark_buffer_dirty (bh); - } - }while (bh_pos += blocksize, (bh = bh->b_this_page) != head); -/* -* If all buffers are now uptodate but the page is not, set the -* page uptodate. -*/ -if (!partial && !PageUptodate (page)) -SetPageUptodate (page); - }while (++u < nr_pages); -/* -* Finally, if we do not need to update initialized_size or i_size we -* are finished. -*/ -read_lock_irqsave (&ni->size_lock, flags); - initialized_size = ni->initialized_size; -read_unlock_irqrestore (&ni->size_lock, flags); -if (end <= initialized_size) { -ntfs_debug ("Done." ); -return 0 ; - } -/* -* Update initialized_size/i_size as appropriate, both in the inode and -* the mft record. -*/ -if (!NInoAttr (ni)) - base_ni = ni; -else - base_ni = ni->ext.base_ntfs_ino; -/* Map, pin, and lock the mft record. */ - m =map_mft_record (base_ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); - m =NULL ; - ctx =NULL ; - goto err_out; - } -BUG_ON (!NInoNonResident (ni)); - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; - goto err_out; - } - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) - err = -EIO ; - goto err_out; - } - a = ctx->attr; -BUG_ON (!a->non_resident); -write_lock_irqsave (&ni->size_lock, flags); -BUG_ON (end > ni->allocated_size); - ni->initialized_size = end; - a->data.non_resident.initialized_size =cpu_to_sle64 (end); -if (end >i_size_read (vi)) { -i_size_write (vi, end); - a->data.non_resident.data_size = - a->data.non_resident.initialized_size; +if (NVolShutdown (NTFS_SB (file->f_mapping->host->i_sb))) +return -EIO ; + +if (NInoCompressed (NTFS_I (inode))) +return -EOPNOTSUPP ; + +if (desc->vm_flags &VM_WRITE ) { +struct inode *inode =file_inode (file); +loff_t from, to; +int err; + + from = ((loff_t )desc->pgoff <<PAGE_SHIFT ); + to =min_t (loff_t,i_size_read (inode), + from + desc->end - desc->start); + +if (NTFS_I (inode)->initialized_size < to) { + err =ntfs_extend_initialized_size (inode, to, to); +if (err) +return err; + } } -write_unlock_irqrestore (&ni->size_lock, flags); -/* Mark the mft record dirty, so it gets written back. */ -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); -ntfs_debug ("Done." ); + + +file_accessed (file); + desc->vm_ops = &ntfs_file_vm_ops;return 0 ; -err_out: -if (ctx) -ntfs_attr_put_search_ctx (ctx); -if (m) -unmap_mft_record (base_ni); -ntfs_error (vi->i_sb,"Failed to update initialized_size/i_size (error " -"code %i)." , err); -if (err != -ENOMEM ) -NVolSetErrors (ni->vol); -return err; } -/** -* ntfs_commit_pages_after_write - commit the received data -* @pages: array of destination pages -* @nr_pages: number of pages in @pages -* @pos: byte position in file at which the write begins -* @bytes: number of bytes to be written -* -* This is called from ntfs_file_buffered_write() with i_mutex held on the inode -* (@pages[0]->mapping->host). There are @nr_pages pages in @pages which are -* locked but not kmap()ped. The source data has already been copied into the -* @page. ntfs_prepare_pages_for_non_resident_write() has been called before -* the data was copied (for non-resident attributes only) and it returned -* success. -* -* Need to set uptodate and mark dirty all buffers within the boundary of the -* write. If all buffers in a page are uptodate we set the page uptodate, too. -* -* Setting the buffers dirty ensures that they get written out later when -* ntfs_writepage() is invoked by the VM. -* -* Finally, we need to update i_size and initialized_size as appropriate both -* in the inode and the mft record. -* -* This is modelled after fs/buffer.c::generic_commit_write(), which marks -* buffers uptodate and dirty, sets the page uptodate if all buffers in the -* page are uptodate, and updates i_size if the end of io is beyond i_size. In -* that case, it also marks the inode dirty. -* -* If things have gone as outlined in -* ntfs_prepare_pages_for_non_resident_write(), we do not need to do any page -* content modifications here for non-resident attributes. For resident -* attributes we need to do the uptodate bringing here which we combine with -* the copying into the mft record which means we save one atomic kmap. -* -* Return 0 on success or -errno on error. -*/ -static int ntfs_commit_pages_after_write (struct page **pages, -const unsigned nr_pages,s64 pos,size_t bytes) +static int ntfs_fiemap (struct inode *inode,struct fiemap_extent_info *fieinfo, +u64 start,u64 len) +{ +return iomap_fiemap (inode, fieinfo, start, len, &ntfs_read_iomap_ops); +} + +static const char *ntfs_get_link (struct dentry *dentry,struct inode *inode, +struct delayed_call *done) +{ +if (!NTFS_I (inode)->target) +return ERR_PTR (-EINVAL ); + +return NTFS_I (inode)->target; +} + +static ssize_t ntfs_file_splice_read (struct file *in,loff_t *ppos, +struct pipe_inode_info *pipe,size_t len,unsigned int flags) +{ +if (NVolShutdown (NTFS_SB (in->f_mapping->host->i_sb))) +return -EIO ; + +return filemap_splice_read (in, ppos, pipe, len, flags); +} + +static int ntfs_ioctl_shutdown (struct super_block *sb,unsigned long arg) { -s64 end, initialized_size; -loff_t i_size; -struct inode *vi; -ntfs_inode *ni, *base_ni; -struct page *page; -ntfs_attr_search_ctx *ctx; -MFT_RECORD *m; -ATTR_RECORD *a; -char *kattr, *kaddr; -unsigned long flags; -u32 attr_len; +u32 flags; + +if (!capable (CAP_SYS_ADMIN )) +return -EPERM ; + +if (get_user (flags, (__u32 __user *)arg)) +return -EFAULT ; + +return ntfs_force_shutdown (sb, flags); +} + +static int ntfs_ioctl_get_volume_label (struct file *filp,unsigned long arg) +{ +struct ntfs_volume *vol =NTFS_SB (file_inode (filp)->i_sb); +char __user *buf = (char __user *)arg; + +if (!vol->volume_label) { +if (copy_to_user (buf,"" ,1 )) +return -EFAULT ; + }else if (copy_to_user (buf, vol->volume_label, +MIN (FSLABEL_MAX ,strlen (vol->volume_label) +1 ))) +return -EFAULT ; +return 0 ; +} + +static int ntfs_ioctl_set_volume_label (struct file *filp,unsigned long arg) +{ +struct ntfs_volume *vol =NTFS_SB (file_inode (filp)->i_sb); +char *label; +int ret; + +if (!capable (CAP_SYS_ADMIN )) +return -EPERM ; + + label =strndup_user ((const char __user *)arg,FSLABEL_MAX ); +if (IS_ERR (label)) +return PTR_ERR (label); + + ret =mnt_want_write_file (filp); +if (ret) + goto out; + + ret =ntfs_write_volume_label (vol, label); +mnt_drop_write_file (filp); +out: +kfree (label); +return ret; +} + +static int ntfs_ioctl_fitrim (struct ntfs_volume *vol,unsigned long arg) +{ +struct fstrim_range __user *user_range; +struct fstrim_range range; +struct block_device *dev;int err; -BUG_ON (!nr_pages); -BUG_ON (!pages); - page = pages[0 ]; -BUG_ON (!page); - vi = page->mapping->host; - ni =NTFS_I (vi); -ntfs_debug ("Entering for inode 0x%lx, attribute type 0x%x, start page " -"index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx." , - vi->i_ino, ni->type, page->index, nr_pages, - (long long )pos, bytes); -if (NInoNonResident (ni)) -return ntfs_commit_pages_after_non_resident_write (pages, - nr_pages, pos, bytes); -BUG_ON (nr_pages >1 ); -/* -* Attribute is resident, implying it is not compressed, encrypted, or -* sparse. -*/ -if (!NInoAttr (ni)) - base_ni = ni; -else - base_ni = ni->ext.base_ntfs_ino; -BUG_ON (NInoNonResident (ni)); -/* Map, pin, and lock the mft record. */ - m =map_mft_record (base_ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); - m =NULL ; - ctx =NULL ; - goto err_out; - } - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; - goto err_out; - } - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) - err = -EIO ; - goto err_out; - } - a = ctx->attr; -BUG_ON (a->non_resident); -/* The total length of the attribute value. */ - attr_len =le32_to_cpu (a->data.resident.value_length); - i_size =i_size_read (vi); -BUG_ON (attr_len != i_size); -BUG_ON (pos > attr_len); - end = pos + bytes; -BUG_ON (end >le32_to_cpu (a->length) - -le16_to_cpu (a->data.resident.value_offset)); - kattr = (u8 *)a +le16_to_cpu (a->data.resident.value_offset); - kaddr =kmap_atomic (page); -/* Copy the received data from the page to the mft record. */ -memcpy (kattr + pos, kaddr + pos, bytes); -/* Update the attribute length if necessary. */ -if (end > attr_len) { - attr_len = end; - a->data.resident.value_length =cpu_to_le32 (attr_len); - } -/* -* If the page is not uptodate, bring the out of bounds area(s) -* uptodate by copying data from the mft record to the page. -*/ -if (!PageUptodate (page)) { -if (pos >0 ) -memcpy (kaddr, kattr, pos); -if (end < attr_len) -memcpy (kaddr + end, kattr + end, attr_len - end); -/* Zero the region outside the end of the attribute value. */ -memset (kaddr + attr_len,0 ,PAGE_SIZE - attr_len); -flush_dcache_page (page); -SetPageUptodate (page); - } -kunmap_atomic (kaddr); -/* Update initialized_size/i_size if necessary. */ -read_lock_irqsave (&ni->size_lock, flags); - initialized_size = ni->initialized_size; -BUG_ON (end > ni->allocated_size); -read_unlock_irqrestore (&ni->size_lock, flags); -BUG_ON (initialized_size != i_size); -if (end > initialized_size) { -write_lock_irqsave (&ni->size_lock, flags); - ni->initialized_size = end; -i_size_write (vi, end); -write_unlock_irqrestore (&ni->size_lock, flags); - } -/* Mark the mft record dirty, so it gets written back. */ -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); -ntfs_debug ("Done." ); +if (!capable (CAP_SYS_ADMIN )) +return -EPERM ; + + dev = vol->sb->s_bdev; +if (!bdev_max_discard_sectors (dev)) +return -EOPNOTSUPP ; + + user_range = (struct fstrim_range __user *)arg; +if (copy_from_user (&range, user_range,sizeof (range))) +return -EFAULT ; + +if (range.len ==0 ) +return -EINVAL ; + +if (range.len < vol->cluster_size) +return -EINVAL ; + + range.minlen =max_t (u32, range.minlen,bdev_discard_granularity (dev)); + + err =ntfsp_trim_fs (vol, &range); +if (err <0 ) +return err; + +if (copy_to_user (user_range, &range,sizeof (range))) +return -EFAULT ; +return 0 ; -err_out: -if (err == -ENOMEM ) { -ntfs_warning (vi->i_sb,"Error allocating memory required to " -"commit the write." ); -if (PageUptodate (page)) { -ntfs_warning (vi->i_sb,"Page is uptodate, setting " -"dirty so the write will be retried " -"later on by the VM." ); -/* -* Put the page on mapping->dirty_pages, but leave its -* buffers' dirty state as-is. -*/ -__set_page_dirty_nobuffers (page); - err =0 ; - }else -ntfs_error (vi->i_sb,"Page is not uptodate. Written " -"data has been lost." ); - }else { -ntfs_error (vi->i_sb,"Resident attribute commit write failed " -"with error %i." , err); -NVolSetErrors (ni->vol); +} + +long ntfsp_ioctl (struct file *filp,unsigned int cmd,unsigned long arg) +{ +switch (cmd) { +case NTFS_IOC_SHUTDOWN : +return ntfs_ioctl_shutdown (file_inode (filp)->i_sb, arg); +case FS_IOC_GETFSLABEL : +return ntfs_ioctl_get_volume_label (filp, arg); +case FS_IOC_SETFSLABEL : +return ntfs_ioctl_set_volume_label (filp, arg); +case FITRIM : +return ntfs_ioctl_fitrim (NTFS_SB (file_inode (filp)->i_sb), arg); +default : +return -ENOTTY ; } -if (ctx) -ntfs_attr_put_search_ctx (ctx); -if (m) -unmap_mft_record (base_ni); -return err; } -/* -* Copy as much as we can into the pages and return the number of bytes which -* were successfully copied. If a fault is encountered then clear the pages -* out to (ofs + bytes) and return the number of bytes which were copied. -*/ -static size_t ntfs_copy_from_user_iter (struct page **pages,unsigned nr_pages, -unsigned ofs,struct iov_iter *i,size_t bytes) +#ifdef CONFIG_COMPAT +long ntfsp_compat_ioctl (struct file *filp,unsigned int cmd, +unsigned long arg) { -struct page **last_page = pages + nr_pages; -size_t total =0 ; -unsigned len, copied; - -do { - len =PAGE_SIZE - ofs; -if (len > bytes) - len = bytes; - copied =copy_page_from_iter_atomic (*pages, ofs, len, i); - total += copied; - bytes -= copied; -if (!bytes) -break ; -if (copied < len) - goto err; - ofs =0 ; - }while (++pages < last_page); -out: -return total; -err: -/* Zero the rest of the target like __copy_from_user(). */ - len =PAGE_SIZE - copied; -do { -if (len > bytes) - len = bytes; -zero_user (*pages, copied, len); - bytes -= len; - copied =0 ; - len =PAGE_SIZE ; - }while (++pages < last_page); - goto out; +return ntfsp_ioctl (filp, cmd, (unsigned long )compat_ptr (arg)); } +#endif -/** -* ntfs_perform_write - perform buffered write to a file -* @file: file to write to -* @i: iov_iter with data to write -* @pos: byte offset in file at which to begin writing to -*/ -static ssize_t ntfs_perform_write (struct file *file,struct iov_iter *i, -loff_t pos) +static long ntfs_fallocate (struct file *file,int mode,loff_t offset,loff_t len) { -struct address_space *mapping = file->f_mapping; -struct inode *vi = mapping->host; -ntfs_inode *ni =NTFS_I (vi); -ntfs_volume *vol = ni->vol; -struct page *pages[NTFS_MAX_PAGES_PER_CLUSTER ]; -struct page *cached_page =NULL ; -VCN last_vcn; -LCN lcn; -size_t bytes; -ssize_t status, written =0 ; -unsigned nr_pages; - -ntfs_debug ("Entering for i_ino 0x%lx, attribute type 0x%x, pos " -"0x%llx, count 0x%lx." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), - (unsigned long long )pos, - (unsigned long )iov_iter_count (i)); -/* -* If a previous ntfs_truncate() failed, repeat it and abort if it -* fails again. -*/ -if (unlikely (NInoTruncateFailed (ni))) { -int err; +struct inode *vi =file_inode (file); +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; +int err =0 ; +loff_t end_offset = offset + len; +loff_t old_size, new_size; +s64 start_vcn, end_vcn; +bool map_locked = false; + +if (!S_ISREG (vi->i_mode)) +return -EOPNOTSUPP ; + +if (mode & ~(FALLOC_FL_KEEP_SIZE |FALLOC_FL_INSERT_RANGE | +FALLOC_FL_PUNCH_HOLE |FALLOC_FL_COLLAPSE_RANGE )) +return -EOPNOTSUPP ; + +if (!NVolFreeClusterKnown (vol)) +wait_event (vol->free_waitq,NVolFreeClusterKnown (vol)); + +if ((ni->vol->mft_zone_end - ni->vol->mft_zone_start) ==0 ) +return -ENOSPC ; -inode_dio_wait (vi); - err =ntfs_truncate (vi); -if (err ||NInoTruncateFailed (ni)) { -if (!err) - err = -EIO ; -ntfs_error (vol->sb,"Cannot perform write to inode " -"0x%lx, attribute type 0x%x, because " -"ntfs_truncate() failed (error code " -"%i)." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); +if (NInoNonResident (ni) && !NInoFullyMapped (ni)) { +down_write (&ni->runlist.lock); + err =ntfs_attr_map_whole_runlist (ni); +up_write (&ni->runlist.lock); +if (err)return err; - } } -/* -* Determine the number of pages per cluster for non-resident -* attributes. -*/ - nr_pages =1 ; -if (vol->cluster_size >PAGE_SIZE &&NInoNonResident (ni)) - nr_pages = vol->cluster_size >>PAGE_SHIFT ; - last_vcn =-1 ; -do { -VCN vcn; -pgoff_t start_idx; -unsigned ofs, do_pages, u; -size_t copied; - - start_idx = pos >>PAGE_SHIFT ; - ofs = pos & ~PAGE_MASK ; - bytes =PAGE_SIZE - ofs; - do_pages =1 ; -if (nr_pages >1 ) { - vcn = pos >> vol->cluster_size_bits; -if (vcn != last_vcn) { - last_vcn = vcn; -/* -* Get the lcn of the vcn the write is in. If -* it is a hole, need to lock down all pages in -* the cluster. -*/ -down_read (&ni->runlist.lock); - lcn =ntfs_attr_vcn_to_lcn_nolock (ni, pos >> - vol->cluster_size_bits, false); -up_read (&ni->runlist.lock); -if (unlikely (lcn <LCN_HOLE )) { -if (lcn ==LCN_ENOMEM ) - status = -ENOMEM ; -else { - status = -EIO ; -ntfs_error (vol->sb,"Cannot " -"perform write to " -"inode 0x%lx, " -"attribute type 0x%x, " -"because the attribute " -"is corrupt." , - vi->i_ino, (unsigned ) -le32_to_cpu (ni->type)); - } -break ; - } -if (lcn ==LCN_HOLE ) { - start_idx = (pos & ~(s64 ) - vol->cluster_size_mask) - >>PAGE_SHIFT ; - bytes = vol->cluster_size - (pos & - vol->cluster_size_mask); - do_pages = nr_pages; - } - } + +if (!(vol->vol_flags &VOLUME_IS_DIRTY )) { + err =ntfs_set_volume_flags (vol,VOLUME_IS_DIRTY ); +if (err) +return err; + } + + old_size =i_size_read (vi); + new_size =max_t (loff_t, old_size, end_offset); + start_vcn =NTFS_B_TO_CLU (vol, offset); + end_vcn = (NTFS_B_TO_CLU (vol, end_offset -1 )) +1 ; + +inode_lock (vi); +if (NInoCompressed (ni) ||NInoEncrypted (ni)) { + err = -EOPNOTSUPP ; + goto out; + } + +inode_dio_wait (vi); +if (mode & (FALLOC_FL_PUNCH_HOLE |FALLOC_FL_COLLAPSE_RANGE | +FALLOC_FL_INSERT_RANGE )) { +filemap_invalidate_lock (vi->i_mapping); + map_locked = true; + } + +if (mode &FALLOC_FL_INSERT_RANGE ) { +loff_t offset_down =round_down (offset, + max_t(unsigned long, vol->cluster_size, PAGE_SIZE)); +loff_t alloc_size; + +if (NVolDisableSparse (vol)) { + err = -EOPNOTSUPP ; + goto out; } -if (bytes >iov_iter_count (i)) - bytes =iov_iter_count (i); -again: -/* -* Bring in the user page(s) that we will copy from _first_. -* Otherwise there is a nasty deadlock on copying from the same -* page(s) as we are writing to, without it/them being marked -* up-to-date. Note, at present there is nothing to stop the -* pages being swapped out between us bringing them into memory -* and doing the actual copying. -*/ -if (unlikely (fault_in_iov_iter_readable (i, bytes))) { - status = -EFAULT ; -break ; + +if ((offset & vol->cluster_size_mask) || + (len & vol->cluster_size_mask) || + offset >= ni->allocated_size) { + err = -EINVAL ; + goto out; } -/* Get and lock @do_pages starting at index @start_idx. */ - status =__ntfs_grab_cache_pages (mapping, start_idx, do_pages, - pages, &cached_page); -if (unlikely (status)) -break ; -/* -* For non-resident attributes, we need to fill any holes with -* actual clusters and ensure all bufferes are mapped. We also -* need to bring uptodate any buffers that are only partially -* being written to. -*/ -if (NInoNonResident (ni)) { - status =ntfs_prepare_pages_for_non_resident_write ( - pages, do_pages, pos, bytes); -if (unlikely (status)) { -do { -unlock_page (pages[--do_pages]); -put_page (pages[do_pages]); - }while (do_pages); -break ; - } + + new_size = old_size + + (NTFS_CLU_TO_B (vol, end_vcn - start_vcn)); + alloc_size = ni->allocated_size + + (NTFS_CLU_TO_B (vol, end_vcn - start_vcn)); +if (alloc_size <0 ) { + err = -EFBIG ; + goto out; } - u = (pos >>PAGE_SHIFT ) - pages[0 ]->index; - copied =ntfs_copy_from_user_iter (pages + u, do_pages - u, ofs, - i, bytes); -ntfs_flush_dcache_pages (pages + u, do_pages - u); - status =0 ; -if (likely (copied == bytes)) { - status =ntfs_commit_pages_after_write (pages, do_pages, - pos, bytes); + err =inode_newsize_ok (vi, alloc_size); +if (err) + goto out; + + err =filemap_write_and_wait_range (vi->i_mapping, + offset_down,LLONG_MAX ); +if (err) + goto out; + +truncate_pagecache (vi, offset_down); + +mutex_lock_nested (&ni->mrec_lock,NTFS_INODE_MUTEX_NORMAL ); + err =ntfs_non_resident_attr_insert_range (ni, start_vcn, + end_vcn - start_vcn); +mutex_unlock (&ni->mrec_lock); +if (err) + goto out; + }else if (mode &FALLOC_FL_COLLAPSE_RANGE ) { +loff_t offset_down =round_down (offset, + max_t(unsigned long, vol->cluster_size, PAGE_SIZE)); + +if ((offset & vol->cluster_size_mask) || + (len & vol->cluster_size_mask) || + offset >= ni->allocated_size) { + err = -EINVAL ; + goto out; } -do { -unlock_page (pages[--do_pages]); -put_page (pages[do_pages]); - }while (do_pages); -if (unlikely (status <0 )) { -iov_iter_revert (i, copied); -break ; + +if (NTFS_CLU_TO_B (vol, end_vcn) > ni->allocated_size) + end_vcn = (round_up (ni->allocated_size -1 , vol->cluster_size) >> + vol->cluster_size_bits) +1 ; + new_size = old_size - + (NTFS_CLU_TO_B (vol, end_vcn - start_vcn)); +if (new_size <0 ) + new_size =0 ; + err =filemap_write_and_wait_range (vi->i_mapping, + offset_down,LLONG_MAX ); +if (err) + goto out; + +truncate_pagecache (vi, offset_down); + +mutex_lock_nested (&ni->mrec_lock,NTFS_INODE_MUTEX_NORMAL ); + err =ntfs_non_resident_attr_collapse_range (ni, start_vcn, + end_vcn - start_vcn); +mutex_unlock (&ni->mrec_lock); +if (err) + goto out; + }else if (mode &FALLOC_FL_PUNCH_HOLE ) { + loff_t offset_down = round_down(offset, max_t(unsigned int, + vol->cluster_size,PAGE_SIZE )); + +if (NVolDisableSparse (vol)) { + err = -EOPNOTSUPP ; + goto out; } -cond_resched (); -if (unlikely (copied < bytes)) { -iov_iter_revert (i, copied); -if (copied) - bytes = copied; -else if (bytes >PAGE_SIZE - ofs) - bytes =PAGE_SIZE - ofs; - goto again; + +if (!(mode &FALLOC_FL_KEEP_SIZE )) { + err = -EINVAL ; + goto out; } - pos += copied; - written += copied; -balance_dirty_pages_ratelimited (mapping); -if (fatal_signal_pending (current)) { - status = -EINTR ; -break ; + +if (offset >= ni->data_size) + goto out; + +if (offset + len > ni->data_size) { + end_offset = ni->data_size; + end_vcn = (NTFS_B_TO_CLU (vol, end_offset -1 )) +1 ; } - }while (iov_iter_count (i)); -if (cached_page) -put_page (cached_page); -ntfs_debug ("Done. Returning %s (written 0x%lx, status %li)." , - written ?"written" :"status" , (unsigned long )written, - (long )status); -return written ? written : status; -} -/** -* ntfs_file_write_iter - simple wrapper for ntfs_file_write_iter_nolock() -* @iocb: IO state structure -* @from: iov_iter with data to write -* -* Basically the same as generic_file_write_iter() except that it ends up -* up calling ntfs_perform_write() instead of generic_perform_write() and that -* O_DIRECT is not implemented. -*/ -static ssize_t ntfs_file_write_iter (struct kiocb *iocb,struct iov_iter *from) -{ -struct file *file = iocb->ki_filp; -struct inode *vi =file_inode (file); -ssize_t written =0 ; -ssize_t err; + err =filemap_write_and_wait_range (vi->i_mapping, offset_down,LLONG_MAX ); +if (err) + goto out; +truncate_pagecache (vi, offset_down); -inode_lock (vi); -/* We can write back this queue in page reclaim. */ - err =ntfs_prepare_file_for_write (iocb, from); -if (iov_iter_count (from) && !err) - written =ntfs_perform_write (file, from, iocb->ki_pos); -inode_unlock (vi); - iocb->ki_pos += written; -if (likely (written >0 )) - written =generic_write_sync (iocb, written); -return written ? written : err; -} +if (offset & vol->cluster_size_mask) { +loff_t to; -/** -* ntfs_file_fsync - sync a file to disk -* @filp: file to be synced -* @datasync: if non-zero only flush user data and not metadata -* -* Data integrity sync of a file to disk. Used for fsync, fdatasync, and msync -* system calls. This function is inspired by fs/buffer.c::file_fsync(). -* -* If @datasync is false, write the mft record and all associated extent mft -* records as well as the $DATA attribute and then sync the block device. -* -* If @datasync is true and the attribute is non-resident, we skip the writing -* of the mft record and all associated extent mft records (this might still -* happen due to the write_inode_now() call). -* -* Also, if @datasync is true, we do not wait on the inode to be written out -* but we always wait on the page cache pages to be written out. -* -* Locking: Caller must hold i_mutex on the inode. -* -* TODO: We should probably also write all attribute/index inodes associated -* with this inode but since we have no simple way of getting to them we ignore -* this problem for now. -*/ -static int ntfs_file_fsync (struct file *filp,loff_t start,loff_t end, -int datasync) -{ -struct inode *vi = filp->f_mapping->host; -int err, ret =0 ; + to =min_t (loff_t,NTFS_CLU_TO_B (vol, start_vcn +1 ), + end_offset); + err =iomap_zero_range (vi, offset, to - offset,NULL , + &ntfs_read_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); +if (err <0 || (end_vcn - start_vcn) ==1 ) + goto out; + start_vcn++; + } +if (end_offset & vol->cluster_size_mask) { +loff_t from; -ntfs_debug ("Entering for inode 0x%lx." , vi->i_ino); + from =NTFS_CLU_TO_B (vol, end_vcn -1 ); + err =iomap_zero_range (vi, from, end_offset - from,NULL , + &ntfs_read_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); +if (err <0 || (end_vcn - start_vcn) ==1 ) + goto out; + end_vcn--; + } - err =file_write_and_wait_range (filp, start, end); -if (err) -return err; -inode_lock (vi); +mutex_lock_nested (&ni->mrec_lock,NTFS_INODE_MUTEX_NORMAL ); + err =ntfs_non_resident_attr_punch_hole (ni, start_vcn, + end_vcn - start_vcn); +mutex_unlock (&ni->mrec_lock); +if (err) + goto out; + }else if (mode ==0 || mode ==FALLOC_FL_KEEP_SIZE ) { +s64 need_space; + + err =inode_newsize_ok (vi, new_size); +if (err) + goto out; + + need_space =NTFS_B_TO_CLU (vol, ni->allocated_size); +if (need_space > start_vcn) + need_space = end_vcn - need_space; +else + need_space = end_vcn - start_vcn; +if (need_space >0 && + need_space > (atomic64_read (&vol->free_clusters) - +atomic64_read (&vol->dirty_clusters))) { + err = -ENOSPC ; + goto out; + } + + err =ntfs_attr_fallocate (ni, offset, len, + mode &FALLOC_FL_KEEP_SIZE ? true : false); +if (err) + goto out; + } + +/* inode->i_blocks is already updated in ntfs_attr_update_mapping_pairs */ +if (!(mode &FALLOC_FL_KEEP_SIZE ) && new_size != old_size) +i_size_write (vi, ni->data_size); + +out: +if (map_locked) +filemap_invalidate_unlock (vi->i_mapping); +if (!err) { +if (mode ==0 &&NInoNonResident (ni) && + offset > old_size && old_size %PAGE_SIZE !=0 ) { +loff_t len =min_t (loff_t, +round_up (old_size,PAGE_SIZE ) - old_size, + offset - old_size); + err =iomap_zero_range (vi, old_size, len,NULL , + &ntfs_read_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); + } +NInoSetFileNameDirty (ni); +inode_set_mtime_to_ts (vi,inode_set_ctime_current (vi)); +mark_inode_dirty (vi); + } -BUG_ON (S_ISDIR (vi->i_mode)); -if (!datasync || !NInoNonResident (NTFS_I (vi))) - ret =__ntfs_write_inode (vi,1 ); -write_inode_now (vi, !datasync); -/* -* NOTE: If we were to use mapping->private_list (see ext2 and -* fs/buffer.c) for dirty blocks then we could optimize the below to be -* sync_mapping_buffers(vi->i_mapping). -*/ - err =sync_blockdev (vi->i_sb->s_bdev); -if (unlikely (err && !ret)) - ret = err; -if (likely (!ret)) -ntfs_debug ("Done." ); -else -ntfs_warning (vi->i_sb,"Failed to f%ssync inode 0x%lx. Error " -"%u." , datasync ?"data" :"" , vi->i_ino, -ret);inode_unlock (vi); -return ret; +return err; } -#endif /* NTFS_RW */ -const struct file_operations ntfs_file_ops = { - .llseek = generic_file_llseek, - .read_iter = generic_file_read_iter, -#ifdef NTFS_RW + .llseek = ntfs_file_llseek, + .read_iter = ntfs_file_read_iter, .write_iter = ntfs_file_write_iter, .fsync = ntfs_file_fsync, -#endif /* NTFS_RW */ - .mmap = generic_file_mmap, + .mmap_prepare = ntfs_file_mmap_prepare, .open = ntfs_file_open, - .splice_read = filemap_splice_read, + .release = ntfs_file_release, + .splice_read = ntfs_file_splice_read, + .splice_write = iter_file_splice_write, + .unlocked_ioctl = ntfsp_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = ntfsp_compat_ioctl, +#endif + .fallocate = ntfs_fallocate, };const struct inode_operations ntfs_file_inode_ops = { -#ifdef NTFS_RW - .setattr = ntfs_setattr, -#endif /* NTFS_RW */ + .setattr = ntfsp_setattr, + .getattr = ntfsp_getattr, + .listxattr = ntfsp_listxattr, + .get_acl = ntfsp_get_acl, + .set_acl = ntfsp_set_acl, + .fiemap = ntfs_fiemap, +}; + +const struct inode_operations ntfs_symlink_inode_operations = { + .get_link = ntfs_get_link, + .setattr = ntfsp_setattr, + .listxattr = ntfsp_listxattr, +}; + +const struct inode_operations ntfsp_special_inode_operations = { + .setattr = ntfsp_setattr, + .getattr = ntfsp_getattr, + .listxattr = ntfsp_listxattr, + .get_acl = ntfsp_get_acl, + .set_acl = ntfsp_set_acl, };const struct file_operations ntfs_empty_file_ops = {};
Signature · 1 line
2.25.1
Namjae Jeon
maintainerPATCH v3 8/14 ntfs: update attrib operations
In reply to Namjae JeonThis updates the implementation of attrib operations
--- fs/ntfs/attrib.c | 5406 +++++++++++++++++++++++++++++++++----------- fs/ntfs/attrlist.c | 285 +++ fs/ntfs/compress.c | 1023 +++++++-- 3 files changed, 5184 insertions(+), 1530 deletions(-) create mode 100644 fs/ntfs/attrlist.c
fs/ntfs/attrib.c +4083 -1323
@@ -1,25 +1,35 @@// SPDX-License-Identifier: GPL-2.0-or-later -/* -* attrib.c - NTFS attribute operations. Part of the Linux-NTFS project. +/** +* NTFS attribute operations. Part of the Linux-NTFS project. * * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc. * Copyright (c) 2002 Richard Russon +* Copyright (c) 2025 LG Electronics Co., Ltd. +* +* Part of this file is based on code from the NTFS-3G project. +* and is copyrighted by the respective authors below: +* Copyright (c) 2000-2010 Anton Altaparmakov +* Copyright (c) 2002-2005 Richard Russon +* Copyright (c) 2002-2008 Szabolcs Szakacsits +* Copyright (c) 2004-2007 Yura Pakhuchiy +* Copyright (c) 2007-2021 Jean-Pierre Andre +* Copyright (c) 2010 Erik Larsson */ -#include <linux/buffer_head.h> -#include <linux/sched.h> -#include <linux/slab.h> -#include <linux/swap.h> #include <linux/writeback.h> +#include <linux/iomap.h> #include "attrib.h" -#include "debug.h" -#include "layout.h" +#include "attrlist.h" #include "lcnalloc.h" -#include "malloc.h" +#include "debug.h" #include "mft.h" #include "ntfs.h" -#include "types.h" +#include "aops.h" +#include "iomap.h" +#include "malloc.h" + +__le16 AT_UNNAMED [] = {cpu_to_le16 ('\0' ) };/** * ntfs_map_runlist_nolock - map (a part of) a runlist of an ntfs inode
@@ -43,42 +53,22 @@* ntfs_map_runlist_nolock(), you will probably want to do: * m = ctx->mrec; * a = ctx->attr; -* Assuming you cache ctx->attr in a variable @a of type ATTR_RECORD * and that -* you cache ctx->mrec in a variable @m of type MFT_RECORD *. -* -* Return 0 on success and -errno on error. There is one special error code -* which is not an error as such. This is -ENOENT. It means that @vcn is out -* of bounds of the runlist. -* -* Note the runlist can be NULL after this function returns if @vcn is zero and -* the attribute has zero allocated size, i.e. there simply is no runlist. -* -* WARNING: If @ctx is supplied, regardless of whether success or failure is -* returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx -* is no longer valid, i.e. you need to either call -* ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it. -* In that case PTR_ERR(@ctx->mrec) will give you the error code for -* why the mapping of the old inode failed. -* -* Locking: - The runlist described by @ni must be locked for writing on entry -* and is locked on return. Note the runlist will be modified. -* - If @ctx is NULL, the base mft record of @ni must not be mapped on -* entry and it will be left unmapped on return. -* - If @ctx is not NULL, the base mft record must be mapped on entry -* and it will be left mapped on return. +* Assuming you cache ctx->attr in a variable @a of type attr_record * and that +* you cache ctx->mrec in a variable @m of type struct mft_record *. */ -int ntfs_map_runlist_nolock (ntfs_inode *ni,VCN vcn,ntfs_attr_search_ctx *ctx) +int ntfs_map_runlist_nolock (struct ntfs_inode *ni,s64 vcn,struct ntfs_attr_search_ctx *ctx) { -VCN end_vcn; +s64 end_vcn;unsigned long flags; -ntfs_inode *base_ni; -MFT_RECORD *m; -ATTR_RECORD *a; -runlist_element *rl; -struct page *put_this_page =NULL ; +struct ntfs_inode *base_ni; +struct mft_record *m; +struct attr_record *a; +struct runlist_element *rl; +struct folio *put_this_folio =NULL ;int err =0 ; -bool ctx_is_temporary, ctx_needs_reset; -ntfs_attr_search_ctx old_ctx = {NULL , }; +bool ctx_is_temporary = false, ctx_needs_reset; +struct ntfs_attr_search_ctx old_ctx = {NULL , }; +size_t new_rl_count;ntfs_debug ("Mapping runlist part containing vcn 0x%llx." , (unsigned long long )vcn);
@@ -97,16 +87,17 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx) goto err_out; } }else { -VCN allocated_size_vcn; +s64 allocated_size_vcn; -BUG_ON (IS_ERR (ctx->mrec)); +WARN_ON (IS_ERR (ctx->mrec)); a = ctx->attr; -BUG_ON (!a->non_resident); - ctx_is_temporary = false; - end_vcn =sle64_to_cpu (a->data.non_resident.highest_vcn); +if (!a->non_resident) { + err = -EIO ; + goto err_out; + } + end_vcn =le64_to_cpu (a->data.non_resident.highest_vcn);read_lock_irqsave (&ni->size_lock, flags); - allocated_size_vcn = ni->allocated_size >> - ni->vol->cluster_size_bits; + allocated_size_vcn =NTFS_B_TO_CLU (ni->vol, ni->allocated_size);read_unlock_irqrestore (&ni->size_lock, flags);if (!a->data.non_resident.lowest_vcn && end_vcn <=0 ) end_vcn = allocated_size_vcn -1 ;
@@ -119,9 +110,9 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)*/ if (vcn >= allocated_size_vcn || (a->type == ni->type && a->name_length == ni->name_len && - !memcmp ((u8 *)a +le16_to_cpu (a->name_offset), + !memcmp ((u8 *)a +le16_to_cpu (a->name_offset), ni->name, ni->name_len) && -sle64_to_cpu (a->data.non_resident.lowest_vcn) +le64_to_cpu (a->data.non_resident.lowest_vcn) <= vcn && end_vcn >= vcn)) ctx_needs_reset = false;else {
@@ -137,8 +128,8 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)*/ if (old_ctx.base_ntfs_ino && old_ctx.ntfs_ino != old_ctx.base_ntfs_ino) { - put_this_page = old_ctx.ntfs_ino->page; -get_page (put_this_page); + put_this_folio = old_ctx.ntfs_ino->folio; +folio_get (put_this_folio); }/* * Reinitialize the search context so we can lookup the
@@ -156,7 +147,7 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx) err = -EIO ; goto err_out; } -BUG_ON (!ctx->attr->non_resident); +WARN_ON (!ctx->attr->non_resident); } a = ctx->attr;/*
@@ -165,16 +156,18 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)* we then try to map the already mapped runlist fragment and * ntfs_mapping_pairs_decompress() fails. */ - end_vcn =sle64_to_cpu (a->data.non_resident.highest_vcn) +1 ; + end_vcn =le64_to_cpu (a->data.non_resident.highest_vcn) +1 ;if (unlikely (vcn && vcn >= end_vcn)) { err = -ENOENT ; goto err_out; } - rl =ntfs_mapping_pairs_decompress (ni->vol, a, ni->runlist.rl); + rl =ntfs_mapping_pairs_decompress (ni->vol, a, &ni->runlist, &new_rl_count);if (IS_ERR (rl)) err =PTR_ERR (rl); -else +else { ni->runlist.rl = rl; + ni->runlist.count = new_rl_count; + } err_out:if (ctx_is_temporary) {if (likely (ctx))
@@ -203,18 +196,16 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx) ctx->base_ntfs_ino) {unmap_extent_mft_record (ctx->ntfs_ino); ctx->mrec = ctx->base_mrec; -BUG_ON (!ctx->mrec); +WARN_ON (!ctx->mrec); }/* * If the old mapped inode is not the base * inode, map it. */ if (old_ctx.base_ntfs_ino && - old_ctx.ntfs_ino != - old_ctx.base_ntfs_ino) { + old_ctx.ntfs_ino != old_ctx.base_ntfs_ino) { retry_map: - ctx->mrec =map_mft_record ( - old_ctx.ntfs_ino); + ctx->mrec =map_mft_record (old_ctx.ntfs_ino);/* * Something bad has happened. If out * of memory retry till it succeeds.
@@ -226,24 +217,22 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)* search context safely. */ if (IS_ERR (ctx->mrec)) { -if (PTR_ERR (ctx->mrec) == - -ENOMEM ) { +if (PTR_ERR (ctx->mrec) == -ENOMEM ) {schedule (); goto retry_map; }else old_ctx.ntfs_ino = - old_ctx. - base_ntfs_ino; + old_ctx.base_ntfs_ino; } } }/* Update the changed pointers in the saved context. */ if (ctx->mrec != old_ctx.mrec) {if (!IS_ERR (ctx->mrec)) - old_ctx.attr = (ATTR_RECORD *)( - (u8 *)ctx->mrec + - ((u8 *)old_ctx.attr - - (u8 *)old_ctx.mrec)); + old_ctx.attr = (struct attr_record *)( + (u8 *)ctx->mrec + + ((u8 *)old_ctx.attr - + (u8 *)old_ctx.mrec)); old_ctx.mrec = ctx->mrec; } }
@@ -260,8 +249,8 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)* immediately and mark the volume dirty for chkdsk to pick up * the pieces anyway. */ -if (put_this_page) -put_page (put_this_page); +if (put_this_folio) +folio_put (put_this_folio); }return err; }
@@ -272,16 +261,8 @@ int ntfs_map_runlist_nolock(ntfs_inode *ni, VCN vcn, ntfs_attr_search_ctx *ctx)* @vcn: map runlist part containing this vcn * * Map the part of a runlist containing the @vcn of the ntfs inode @ni. -* -* Return 0 on success and -errno on error. There is one special error code -* which is not an error as such. This is -ENOENT. It means that @vcn is out -* of bounds of the runlist. -* -* Locking: - The runlist must be unlocked on entry and is unlocked on return. -* - This function takes the runlist lock for writing and may modify -* the runlist. */ -int ntfs_map_runlist (ntfs_inode *ni,VCN vcn) +int ntfs_map_runlist (struct ntfs_inode *ni,s64 vcn) {int err =0 ;
@@ -294,6 +275,37 @@ int ntfs_map_runlist(ntfs_inode *ni, VCN vcn)return err; } +struct runlist_element *ntfs_attr_vcn_to_rl (struct ntfs_inode *ni,s64 vcn,s64 *lcn) +{ +struct runlist_element *rl; +int err; +bool is_retry = false; + + rl = ni->runlist.rl; +if (!rl) { + err =ntfs_attr_map_whole_runlist (ni); +if (err) +return ERR_PTR (-ENOENT ); + rl = ni->runlist.rl; + } + +remap_rl: +/* Seek to element containing target vcn. */ +while (rl->length && rl[1 ].vcn <= vcn) + rl++; + *lcn =ntfs_rl_vcn_to_lcn (rl, vcn); + +if (*lcn <=LCN_RL_NOT_MAPPED && is_retry == false) { + is_retry = true; +if (!ntfs_map_runlist_nolock (ni, vcn,NULL )) { + rl = ni->runlist.rl; + goto remap_rl; + } + } + +return rl; +} +/** * ntfs_attr_vcn_to_lcn_nolock - convert a vcn into a lcn given an ntfs inode * @ni: ntfs inode of the attribute whose runlist to search
@@ -324,19 +336,16 @@ int ntfs_map_runlist(ntfs_inode *ni, VCN vcn)* the lock may be dropped inside the function so you cannot rely on * the runlist still being the same when this function returns. */ -LCN ntfs_attr_vcn_to_lcn_nolock (ntfs_inode *ni,const VCN vcn, +s64 ntfs_attr_vcn_to_lcn_nolock (struct ntfs_inode *ni,const s64 vcn,const bool write_locked) { -LCN lcn; +s64 lcn;unsigned long flags;bool is_retry = false; -BUG_ON (!ni);ntfs_debug ("Entering for i_ino 0x%lx, vcn 0x%llx, %s_locked." , ni->mft_no, (unsigned long long )vcn, write_locked ?"write" :"read" ); -BUG_ON (!NInoNonResident (ni)); -BUG_ON (vcn <0 );if (!ni->runlist.rl) {read_lock_irqsave (&ni->size_lock, flags);if (!ni->allocated_size) {
@@ -390,6 +399,61 @@ LCN ntfs_attr_vcn_to_lcn_nolock(ntfs_inode *ni, const VCN vcn,return lcn; } +struct runlist_element *__ntfs_attr_find_vcn_nolock (struct runlist *runlist,const s64 vcn) +{ +size_t lower_idx, upper_idx, idx; +struct runlist_element *run; +int rh = runlist->rl_hint; + +if (runlist->count <=1 ) +return ERR_PTR (-ENOENT ); + +if (runlist->count -1 > rh && runlist->rl[rh].vcn <= vcn) { +if (vcn < runlist->rl[rh].vcn + runlist->rl[rh].length) +return &runlist->rl[rh]; +if (runlist->count -2 == rh) +return ERR_PTR (-ENOENT ); + + lower_idx = rh +1 ; + }else { + run = &runlist->rl[0 ]; +if (vcn < run->vcn) +return ERR_PTR (-ENOENT ); +else if (vcn < run->vcn + run->length) { + runlist->rl_hint =0 ; +return run; + } + + lower_idx =1 ; + } + + run = &runlist->rl[runlist->count -2 ]; +if (vcn >= run->vcn && vcn < run->vcn + run->length) { + runlist->rl_hint = runlist->count -2 ; +return run; + } +if (vcn >= run->vcn + run->length) +return ERR_PTR (-ENOENT ); + + upper_idx = runlist->count -2 ; + +while (lower_idx <= upper_idx) { + idx = (lower_idx + upper_idx) >>1 ; + run = &runlist->rl[idx]; + +if (vcn < run->vcn) + upper_idx = idx -1 ; +else if (vcn >= run->vcn + run->length) + lower_idx = idx +1 ; +else { + runlist->rl_hint = idx; +return run; + } + } + +return ERR_PTR (-ENOENT ); +} +/** * ntfs_attr_find_vcn_nolock - find a vcn in the runlist of an ntfs inode * @ni: ntfs inode describing the runlist to search
@@ -416,50 +480,22 @@ LCN ntfs_attr_vcn_to_lcn_nolock(ntfs_inode *ni, const VCN vcn,* ntfs_attr_find_vcn_nolock(), you will probably want to do: * m = ctx->mrec; * a = ctx->attr; -* Assuming you cache ctx->attr in a variable @a of type ATTR_RECORD * and that -* you cache ctx->mrec in a variable @m of type MFT_RECORD *. +* Assuming you cache ctx->attr in a variable @a of type attr_record * and that +* you cache ctx->mrec in a variable @m of type struct mft_record *. * Note you need to distinguish between the lcn of the returned runlist element * being >= 0 and LCN_HOLE. In the later case you have to return zeroes on * read and allocate clusters on write. -* -* Return the runlist element containing the @vcn on success and -* ERR_PTR(-errno) on error. You need to test the return value with IS_ERR() -* to decide if the return is success or failure and PTR_ERR() to get to the -* error code if IS_ERR() is true. -* -* The possible error return codes are: -* -ENOENT - No such vcn in the runlist, i.e. @vcn is out of bounds. -* -ENOMEM - Not enough memory to map runlist. -* -EIO - Critical error (runlist/file is corrupt, i/o error, etc). -* -* WARNING: If @ctx is supplied, regardless of whether success or failure is -* returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx -* is no longer valid, i.e. you need to either call -* ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it. -* In that case PTR_ERR(@ctx->mrec) will give you the error code for -* why the mapping of the old inode failed. -* -* Locking: - The runlist described by @ni must be locked for writing on entry -* and is locked on return. Note the runlist may be modified when -* needed runlist fragments need to be mapped. -* - If @ctx is NULL, the base mft record of @ni must not be mapped on -* entry and it will be left unmapped on return. -* - If @ctx is not NULL, the base mft record must be mapped on entry -* and it will be left mapped on return. */ -runlist_element *ntfs_attr_find_vcn_nolock (ntfs_inode *ni,const VCN vcn, -ntfs_attr_search_ctx *ctx) +struct runlist_element *ntfs_attr_find_vcn_nolock (struct ntfs_inode *ni,const s64 vcn, +struct ntfs_attr_search_ctx *ctx) {unsigned long flags; -runlist_element *rl; +struct runlist_element *rl;int err =0 ;bool is_retry = false; -BUG_ON (!ni);ntfs_debug ("Entering for i_ino 0x%lx, vcn 0x%llx, with%s ctx." , ni->mft_no, (unsigned long long )vcn, ctx ?"" :"out" ); -BUG_ON (!NInoNonResident (ni)); -BUG_ON (vcn <0 );if (!ni->runlist.rl) {read_lock_irqsave (&ni->size_lock, flags);if (!ni->allocated_size) {
@@ -468,32 +504,24 @@ runlist_element *ntfs_attr_find_vcn_nolock(ntfs_inode *ni, const VCN vcn, }read_unlock_irqrestore (&ni->size_lock, flags); } + retry_remap: rl = ni->runlist.rl;if (likely (rl && vcn >= rl[0 ].vcn)) { -while (likely (rl->length)) { -if (unlikely (vcn < rl[1 ].vcn)) { -if (likely (rl->lcn >=LCN_HOLE )) { -ntfs_debug ("Done." ); -return rl; - } -break ; - } - rl++; - } -if (likely (rl->lcn !=LCN_RL_NOT_MAPPED )) { -if (likely (rl->lcn ==LCN_ENOENT )) - err = -ENOENT ; -else - err = -EIO ; - } + rl =__ntfs_attr_find_vcn_nolock (&ni->runlist, vcn); +if (IS_ERR (rl)) + err =PTR_ERR (rl); +else if (rl->lcn >=LCN_HOLE ) +return rl; +else if (rl->lcn <=LCN_ENOENT ) + err = -EIO ; }if (!err && !is_retry) {/* * If the search context is invalid we cannot map the unmapped * region. */ -if (IS_ERR (ctx->mrec)) +if (ctx &&IS_ERR (ctx->mrec)) err =PTR_ERR (ctx->mrec);else {/*
@@ -572,14 +600,15 @@ runlist_element *ntfs_attr_find_vcn_nolock(ntfs_inode *ni, const VCN vcn,* Warning: Never use @val when looking for attribute types which can be * non-resident as this most likely will result in a crash! */ -static int ntfs_attr_find (const ATTR_TYPE type,const ntfschar *name, -const u32 name_len,const IGNORE_CASE_BOOL ic, -const u8 *val,const u32 val_len,ntfs_attr_search_ctx *ctx) +static int ntfs_attr_find (const __le32 type,const __le16 *name, +const u32 name_len,const u32 ic, +const u8 *val,const u32 val_len,struct ntfs_attr_search_ctx *ctx) { -ATTR_RECORD *a; -ntfs_volume *vol = ctx->ntfs_ino->vol; -ntfschar *upcase = vol->upcase; +struct attr_record *a; +struct ntfs_volume *vol = ctx->ntfs_ino->vol; +__le16 *upcase = vol->upcase;u32 upcase_len = vol->upcase_len; +unsigned int space;/* * Iterate over attributes in mft record starting at @ctx->attr, or the
@@ -589,80 +618,72 @@ static int ntfs_attr_find(const ATTR_TYPE type, const ntfschar *name, a = ctx->attr; ctx->is_first = false; }else - a = (ATTR_RECORD *)((u8 *)ctx->attr + + a = (struct attr_record *)((u8 *)ctx->attr +le32_to_cpu (ctx->attr->length)); -for (;; a = (ATTR_RECORD *)((u8 *)a +le32_to_cpu (a->length))) { -u8 *mrec_end = (u8 *)ctx->mrec + -le32_to_cpu (ctx->mrec->bytes_allocated); -u8 *name_end; - -/* check whether ATTR_RECORD wrap */ -if ((u8 *)a < (u8 *)ctx->mrec) -break ; - -/* check whether Attribute Record Header is within bounds */ -if ((u8 *)a > mrec_end || - (u8 *)a +sizeof (ATTR_RECORD ) > mrec_end) +for (;; a = (struct attr_record *)((u8 *)a +le32_to_cpu (a->length))) { +if ((u8 *)a < (u8 *)ctx->mrec || (u8 *)a > (u8 *)ctx->mrec + +le32_to_cpu (ctx->mrec->bytes_allocated))break ; -/* check whether ATTR_RECORD's name is within bounds */ - name_end = (u8 *)a +le16_to_cpu (a->name_offset) + - a->name_length *sizeof (ntfschar); -if (name_end > mrec_end) + space =le32_to_cpu (ctx->mrec->bytes_in_use) - ((u8 *)a - (u8 *)ctx->mrec); + if ((space < offsetof(struct attr_record, data.resident.reserved) + 1 || + space < le32_to_cpu(a->length)) && (space < 4 || a->type != AT_END))break ; ctx->attr = a; -if (unlikely (le32_to_cpu (a->type) >le32_to_cpu (type) || - a->type ==AT_END )) +if (((type !=AT_UNUSED ) && (le32_to_cpu (a->type) >le32_to_cpu (type))) || + a->type ==AT_END )return -ENOENT ;if (unlikely (!a->length))break ; - -/* check whether ATTR_RECORD's length wrap */ -if ((u8 *)a +le32_to_cpu (a->length) < (u8 *)a) -break ; -/* check whether ATTR_RECORD's length is within bounds */ -if ((u8 *)a +le32_to_cpu (a->length) > mrec_end) -break ; - +if (type ==AT_UNUSED ) +return 0 ;if (a->type != type)continue ;/* * If @name is present, compare the two names. If @name is * missing, assume we want an unnamed attribute. */ -if (!name) { +if (!name || name ==AT_UNNAMED ) {/* The search failed if the found attribute is named. */ if (a->name_length)return -ENOENT ; - }else if (!ntfs_are_names_equal (name, name_len, - (ntfschar *)((u8 *)a +le16_to_cpu (a->name_offset)), - a->name_length, ic, upcase, upcase_len)) { - registerint rc; + }else { +if (a->name_length && ((le16_to_cpu (a->name_offset) + + a->name_length *sizeof (__le16)) > +le32_to_cpu (a->length))) { +ntfs_error (vol->sb,"Corrupt attribute name in MFT record %lld\n" , + (long long )ctx->ntfs_ino->mft_no); +break ; + } - rc =ntfs_collate_names (name, name_len, - (ntfschar *)((u8 *)a + -le16_to_cpu (a->name_offset)), - a->name_length,1 ,IGNORE_CASE , - upcase, upcase_len); -/* -* If @name collates before a->name, there is no -* matching attribute. -*/ -if (rc ==-1 ) -return -ENOENT ; -/* If the strings are not equal, continue search. */ -if (rc) -continue ; - rc =ntfs_collate_names (name, name_len, - (ntfschar *)((u8 *)a + -le16_to_cpu (a->name_offset)), - a->name_length,1 ,CASE_SENSITIVE , - upcase, upcase_len); -if (rc ==-1 ) -return -ENOENT ; -if (rc) -continue ; +if (!ntfs_are_names_equal (name, name_len, + (__le16 *)((u8 *)a +le16_to_cpu (a->name_offset)), + a->name_length, ic, upcase, upcase_len)) { + registerint rc; + + rc =ntfs_collate_names (name, name_len, + (__le16 *)((u8 *)a +le16_to_cpu (a->name_offset)), + a->name_length,1 ,IGNORE_CASE , + upcase, upcase_len); +/* +* If @name collates before a->name, there is no +* matching attribute. +*/ +if (rc ==-1 ) +return -ENOENT ; +/* If the strings are not equal, continue search. */ +if (rc) +continue ; + rc =ntfs_collate_names (name, name_len, + (__le16 *)((u8 *)a +le16_to_cpu (a->name_offset)), + a->name_length,1 ,CASE_SENSITIVE , + upcase, upcase_len); +if (rc ==-1 ) +return -ENOENT ; +if (rc) +continue ; + } }/* * The names match or @name not present and attribute is
@@ -675,7 +696,7 @@ static int ntfs_attr_find(const ATTR_TYPE type, const ntfschar *name,else { registerint rc; - rc =memcmp (val, (u8 *)a +le16_to_cpu ( + rc =memcmp (val, (u8 *)a +le16_to_cpu ( a->data.resident.value_offset),min_t (u32, val_len,le32_to_cpu ( a->data.resident.value_length)));
@@ -686,8 +707,7 @@ static int ntfs_attr_find(const ATTR_TYPE type, const ntfschar *name,if (!rc) { registeru32 avl; - avl =le32_to_cpu ( - a->data.resident.value_length); + avl =le32_to_cpu (a->data.resident.value_length);if (val_len == avl)return 0 ;if (val_len < avl)
@@ -701,117 +721,80 @@ static int ntfs_attr_find(const ATTR_TYPE type, const ntfschar *name,return -EIO ; } -/** -* load_attribute_list - load an attribute list into memory -* @vol: ntfs volume from which to read -* @runlist: runlist of the attribute list -* @al_start: destination buffer -* @size: size of the destination buffer in bytes -* @initialized_size: initialized size of the attribute list -* -* Walk the runlist @runlist and load all clusters from it copying them into -* the linear buffer @al. The maximum number of bytes copied to @al is @size -* bytes. Note, @size does not need to be a multiple of the cluster size. If -* @initialized_size is less than @size, the region in @al between -* @initialized_size and @size will be zeroed and not read from disk. -* -* Return 0 on success or -errno on error. -*/ -int load_attribute_list (ntfs_volume *vol,runlist *runlist,u8 *al_start, -const s64 size,const s64 initialized_size) +void ntfs_attr_name_free (unsigned char **name) { -LCN lcn; -u8 *al = al_start; -u8 *al_end = al + initialized_size; -runlist_element *rl; -struct buffer_head *bh; -struct super_block *sb; -unsigned long block_size; -unsigned long block, max_block; -int err =0 ; -unsigned char block_size_bits; +if (*name) { +ntfs_free (*name); + *name =NULL ; + } +} -ntfs_debug ("Entering." ); -if (!vol || !runlist || !al || size <=0 || initialized_size <0 || - initialized_size > size) +char *ntfs_attr_name_get (const struct ntfs_volume *vol,const __le16 *uname, +const int uname_len) +{ +unsigned char *name =NULL ; +int name_len; + + name_len =ntfs_ucstonls (vol, uname, uname_len, &name,0 ); +if (name_len <0 ) { +ntfs_error (vol->sb,"ntfs_ucstonls error" ); +/* This function when returns -1, memory for name might +* be allocated. So lets free this memory. +*/ +ntfs_attr_name_free (&name); +return NULL ; + + }else if (name_len >0 ) +return name; + +ntfs_attr_name_free (&name); +return NULL ; +} + +int load_attribute_list (struct ntfs_inode *base_ni,u8 *al_start,const s64 size) +{ +struct inode *attr_vi =NULL ; +u8 *al; +struct attr_list_entry *ale; + +if (!al_start || size <=0 )return -EINVAL ; -if (!initialized_size) { -memset (al,0 , size); -return 0 ; + + attr_vi =ntfs_attr_iget (VFS_I (base_ni),AT_ATTRIBUTE_LIST ,AT_UNNAMED ,0 ); +if (IS_ERR (attr_vi)) { +ntfs_error (base_ni->vol->sb, +"Failed to open an inode for Attribute list, mft = %ld" , + base_ni->mft_no); +return PTR_ERR (attr_vi); } - sb = vol->sb; - block_size = sb->s_blocksize; - block_size_bits = sb->s_blocksize_bits; -down_read (&runlist->lock); - rl = runlist->rl; -if (!rl) { -ntfs_error (sb,"Cannot read attribute list since runlist is " -"missing." ); - goto err_out; - } -/* Read all clusters specified by the runlist one run at a time. */ -while (rl->length) { - lcn =ntfs_rl_vcn_to_lcn (rl, rl->vcn); -ntfs_debug ("Reading vcn = 0x%llx, lcn = 0x%llx." , - (unsigned long long )rl->vcn, - (unsigned long long )lcn); -/* The attribute list cannot be sparse. */ -if (lcn <0 ) { -ntfs_error (sb,"ntfs_rl_vcn_to_lcn() failed. Cannot " -"read attribute list." ); - goto err_out; - } - block = lcn << vol->cluster_size_bits >> block_size_bits; -/* Read the run from device in chunks of block_size bytes. */ - max_block = block + (rl->length << vol->cluster_size_bits >> - block_size_bits); -ntfs_debug ("max_block = 0x%lx." , max_block); -do { -ntfs_debug ("Reading block = 0x%lx." , block); - bh =sb_bread (sb, block); -if (!bh) { -ntfs_error (sb,"sb_bread() failed. Cannot " -"read attribute list." ); - goto err_out; - } -if (al + block_size >= al_end) - goto do_final; -memcpy (al, bh->b_data, block_size); -brelse (bh); - al += block_size; - }while (++block < max_block); - rl++; + +if (ntfs_inode_attr_pread (attr_vi,0 , size, al_start) != size) { +iput (attr_vi); +ntfs_error (base_ni->vol->sb, +"Failed to read attribute list, mft = %ld" , + base_ni->mft_no); +return -EIO ; } -if (initialized_size < size) { -initialize: -memset (al_start + initialized_size,0 , size - initialized_size); +iput (attr_vi); + +for (al = al_start; al < al_start + size; al +=le16_to_cpu (ale->length)) { + ale = (struct attr_list_entry *)al; +if (ale->name_offset !=sizeof (struct attr_list_entry )) +break ; +if (le16_to_cpu (ale->length) <= ale->name_offset + ale->name_length || + al +le16_to_cpu (ale->length) > al_start + size) +break ; +if (ale->type ==AT_UNUSED ) +break ; +if (MSEQNO_LE (ale->mft_reference) ==0 ) +break ; } -done: -up_read (&runlist->lock); -return err; -do_final: -if (al < al_end) { -/* -* Partial block. -* -* Note: The attribute list can be smaller than its allocation -* by multiple clusters. This has been encountered by at least -* two people running Windows XP, thus we cannot do any -* truncation sanity checking here. (AIA) -*/ -memcpy (al, bh->b_data, al_end - al); -brelse (bh); -if (initialized_size < size) - goto initialize; - goto done; - } -brelse (bh); -/* Real overflow! */ -ntfs_error (sb,"Attribute list buffer overflow. Read attribute list " -"is truncated." ); -err_out: - err = -EIO ; - goto done; +if (al != al_start + size) { +ntfs_error (base_ni->vol->sb,"Corrupt attribute list, mft = %ld" , + base_ni->mft_no); +return -EIO ; + } +return 0 ; }/**
@@ -864,18 +847,19 @@ int load_attribute_list(ntfs_volume *vol, runlist *runlist, u8 *al_start,* On actual error, ntfs_external_attr_find() returns -EIO. In this case * @ctx->attr is undefined and in particular do not rely on it not changing. */ -static int ntfs_external_attr_find (const ATTR_TYPE type, -const ntfschar *name,const u32 name_len, -const IGNORE_CASE_BOOL ic,const VCN lowest_vcn, -const u8 *val,const u32 val_len,ntfs_attr_search_ctx *ctx) +static int ntfs_external_attr_find (const __le32 type, +const __le16 *name,const u32 name_len, +const u32 ic,const s64 lowest_vcn, +const u8 *val,const u32 val_len,struct ntfs_attr_search_ctx *ctx) { -ntfs_inode *base_ni, *ni; -ntfs_volume *vol; -ATTR_LIST_ENTRY *al_entry, *next_al_entry; +struct ntfs_inode *base_ni, *ni; +struct ntfs_volume *vol; +struct attr_list_entry *al_entry, *next_al_entry;u8 *al_start, *al_end; -ATTR_RECORD *a; -ntfschar *al_name; +struct attr_record *a; +__le16 *al_name;u32 al_name_len; +bool is_first_search = false;int err =0 ;static const char *es =" Unmount and run chkdsk." ;
@@ -886,6 +870,7 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,/* First call happens with the base mft record. */ base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino; ctx->base_mrec = ctx->mrec; + ctx->mapped_base_mrec = ctx->mapped_mrec; }if (ni == base_ni) ctx->base_attr = ctx->attr;
@@ -894,8 +879,10 @@ static int ntfs_external_attr_find(const ATTR_TYPE type, vol = base_ni->vol; al_start = base_ni->attr_list; al_end = al_start + base_ni->attr_list_size; -if (!ctx->al_entry) - ctx->al_entry = (ATTR_LIST_ENTRY *)al_start; +if (!ctx->al_entry) { + ctx->al_entry = (struct attr_list_entry *)al_start; + is_first_search = true; + }/* * Iterate over entries in attribute list starting at @ctx->al_entry, * or the entry following that, if @ctx->is_first is 'true'.
@@ -903,36 +890,128 @@ static int ntfs_external_attr_find(const ATTR_TYPE type, if (ctx->is_first) { al_entry = ctx->al_entry; ctx->is_first = false; - } else - al_entry = (ATTR_LIST_ENTRY*)((u8*)ctx->al_entry + + /* + * If an enumeration and the first attribute is higher than + * the attribute list itself, need to return the attribute list + * attribute. + */ + if ((type == AT_UNUSED) && is_first_search && + le32_to_cpu(al_entry->type) > + le32_to_cpu(AT_ATTRIBUTE_LIST)) + goto find_attr_list_attr; + } else { + /* Check for small entry */ + if (((al_end - (u8 *)ctx->al_entry) < + (long)offsetof(struct attr_list_entry, name)) || + (le16_to_cpu(ctx->al_entry->length) & 7) || + (le16_to_cpu(ctx->al_entry->length) < offsetof(struct attr_list_entry, name))) + goto corrupt; + + al_entry = (struct attr_list_entry *)((u8 *)ctx->al_entry + le16_to_cpu(ctx->al_entry->length)); + + if ((u8 *)al_entry == al_end) + goto not_found; + + /* Preliminary check for small entry */ + if ((al_end - (u8 *)al_entry) < + (long)offsetof(struct attr_list_entry, name)) + goto corrupt; + + /* + * If this is an enumeration and the attribute list attribute + * is the next one in the enumeration sequence, just return the + * attribute list attribute from the base mft record as it is + * not listed in the attribute list itself. + */ + if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) < + le32_to_cpu(AT_ATTRIBUTE_LIST) && + le32_to_cpu(al_entry->type) > + le32_to_cpu(AT_ATTRIBUTE_LIST)) { +find_attr_list_attr: + + /* Check for bogus calls. */ + if (name || name_len || val || val_len || lowest_vcn) + return -EINVAL; + + /* We want the base record. */ + if (ctx->ntfs_ino != base_ni) + unmap_mft_record(ctx->ntfs_ino); + ctx->ntfs_ino = base_ni; + ctx->mapped_mrec = ctx->mapped_base_mrec; + ctx->mrec = ctx->base_mrec; + ctx->is_first = true; + + /* Sanity checks are performed elsewhere. */ + ctx->attr = (struct attr_record *)((u8 *)ctx->mrec + + le16_to_cpu(ctx->mrec->attrs_offset)); + + /* Find the attribute list attribute. */ + err = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0, + IGNORE_CASE, NULL, 0, ctx); + + /* + * Setup the search context so the correct + * attribute is returned next time round. + */ + ctx->al_entry = al_entry; + ctx->is_first = true; + + /* Got it. Done. */ + if (!err) + return 0; + + /* Error! If other than not found return it. */ + if (err != -ENOENT) + return err; + + /* Not found?!? Absurd! */ + ntfs_error(ctx->ntfs_ino->vol->sb, "Attribute list wasn't found"); + return -EIO; + } + } for (;; al_entry = next_al_entry) { /* Out of bounds check. */ - if ((u8*)al_entry < base_ni->attr_list || - (u8*)al_entry > al_end) + if ((u8 *)al_entry < base_ni->attr_list || + (u8 *)al_entry > al_end) break; /* Inode is corrupt. */ ctx->al_entry = al_entry; /* Catch the end of the attribute list. */ - if ((u8*)al_entry == al_end) + if ((u8 *)al_entry == al_end) goto not_found; - if (!al_entry->length) - break; - if ((u8*)al_entry + 6 > al_end || (u8*)al_entry + - le16_to_cpu(al_entry->length) > al_end) - break; - next_al_entry = (ATTR_LIST_ENTRY*)((u8*)al_entry + + + if ((((u8 *)al_entry + offsetof(struct attr_list_entry, name)) > al_end) || + ((u8 *)al_entry + le16_to_cpu(al_entry->length) > al_end) || + (le16_to_cpu(al_entry->length) & 7) || + (le16_to_cpu(al_entry->length) < + offsetof(struct attr_list_entry, name_length)) || + (al_entry->name_length && ((u8 *)al_entry + al_entry->name_offset + + al_entry->name_length * sizeof(__le16)) > al_end)) + break; /* corrupt */ + + next_al_entry = (struct attr_list_entry *)((u8 *)al_entry + le16_to_cpu(al_entry->length)); - if (le32_to_cpu(al_entry->type) > le32_to_cpu(type)) - goto not_found; - if (type != al_entry->type) - continue; + if (type != AT_UNUSED) { + if (le32_to_cpu(al_entry->type) > le32_to_cpu(type)) + goto not_found; + if (type != al_entry->type) + continue; + } /* * If @name is present, compare the two names. If @name is * missing, assume we want an unnamed attribute. */ al_name_len = al_entry->name_length; - al_name = (ntfschar*)((u8*)al_entry + al_entry->name_offset); - if (!name) { + al_name = (__le16 *)((u8 *)al_entry + al_entry->name_offset); + + /* + * If !@type we want the attribute represented by this + * attribute list entry. + */ + if (type == AT_UNUSED) + goto is_enumeration; + + if (!name || name == AT_UNNAMED) { if (al_name_len) goto not_found; } else if (!ntfs_are_names_equal(al_name, al_name_len, name,
@@ -951,14 +1030,7 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,/* If the strings are not equal, continue search. */ if (rc)continue ; -/* -* FIXME: Reverse engineering showed 0, IGNORE_CASE but -* that is inconsistent with ntfs_attr_find(). The -* subsequent rc checks were also different. Perhaps I -* made a mistake in one of the two. Need to recheck -* which is correct or at least see what is going on... -* (AIA) -*/ + rc =ntfs_collate_names (name, name_len, al_name, al_name_len,1 ,CASE_SENSITIVE , vol->upcase, vol->upcase_len);
@@ -973,27 +1045,28 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,* next attribute list entry still fits @lowest_vcn. Otherwise * we have reached the right one or the search has failed. */ -if (lowest_vcn && (u8 *)next_al_entry >= al_start && - (u8 *)next_al_entry +6 < al_end && - (u8 *)next_al_entry +le16_to_cpu ( - next_al_entry->length) <= al_end && -sle64_to_cpu (next_al_entry->lowest_vcn) <= - lowest_vcn && - next_al_entry->type == al_entry->type && - next_al_entry->name_length == al_name_len && -ntfs_are_names_equal ((ntfschar *)((u8 *) +if (lowest_vcn && (u8 *)next_al_entry >= al_start && + (u8 *)next_al_entry +6 < al_end && + (u8 *)next_al_entry +le16_to_cpu ( + next_al_entry->length) <= al_end && +le64_to_cpu (next_al_entry->lowest_vcn) <= + lowest_vcn && + next_al_entry->type == al_entry->type && + next_al_entry->name_length == al_name_len && +ntfs_are_names_equal ((__le16 *)((u8 *) next_al_entry + next_al_entry->name_offset), next_al_entry->name_length, al_name, al_name_len,CASE_SENSITIVE , vol->upcase, vol->upcase_len))continue ; + +is_enumeration:if (MREF_LE (al_entry->mft_reference) == ni->mft_no) {if (MSEQNO_LE (al_entry->mft_reference) != ni->seq_no) { -ntfs_error (vol->sb,"Found stale mft " -"reference in attribute list " -"of base inode 0x%lx.%s" , - base_ni->mft_no, es); +ntfs_error (vol->sb, +"Found stale mft reference in attribute list of base inode 0x%lx.%s" , + base_ni->mft_no, es); err = -EIO ;break ; }
@@ -1006,18 +1079,16 @@ static int ntfs_external_attr_find(const ATTR_TYPE type, base_ni->mft_no) { ni = ctx->ntfs_ino = base_ni; ctx->mrec = ctx->base_mrec; + ctx->mapped_mrec = ctx->mapped_base_mrec; } else {/* We want an extent record. */ ctx->mrec =map_extent_mft_record (base_ni,le64_to_cpu ( al_entry->mft_reference), &ni);if (IS_ERR (ctx->mrec)) { -ntfs_error (vol->sb,"Failed to map " -"extent mft record " -"0x%lx of base inode " -"0x%lx.%s" , -MREF_LE (al_entry-> - mft_reference), +ntfs_error (vol->sb, +"Failed to map extent mft record 0x%lx of base inode 0x%lx.%s" , +MREF_LE (al_entry->mft_reference), base_ni->mft_no, es); err =PTR_ERR (ctx->mrec);if (err == -ENOENT )
@@ -1027,10 +1098,12 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,break ; } ctx->ntfs_ino = ni; + ctx->mapped_mrec = true; + } - ctx->attr = (ATTR_RECORD *)((u8 *)ctx->mrec + -le16_to_cpu (ctx->mrec->attrs_offset)); } + a = ctx->attr = (struct attr_record *)((u8 *)ctx->mrec + +le16_to_cpu (ctx->mrec->attrs_offset));/* * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the * mft record containing the attribute represented by the
@@ -1046,17 +1119,16 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,* entry above, the comparison can now be optimized. So it is * worth re-implementing a simplified ntfs_attr_find() here. */ - a = ctx->attr;/* * Use a manual loop so we can still use break and continue * with the same meanings as above. */ do_next_attr_loop: -if ((u8 *)a < (u8 *)ctx->mrec || (u8 *)a > (u8 *)ctx->mrec + +if ((u8 *)a < (u8 *)ctx->mrec || (u8 *)a > (u8 *)ctx->mrec +le32_to_cpu (ctx->mrec->bytes_allocated))break ;if (a->type ==AT_END ) -break ; +continue ;if (!a->length)break ;if (al_entry->instance != a->instance)
@@ -1068,7 +1140,7 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,*/ if (al_entry->type != a->type)break ; -if (!ntfs_are_names_equal ((ntfschar *)((u8 *)a + +if (!ntfs_are_names_equal ((__le16 *)((u8 *)a +le16_to_cpu (a->name_offset)), a->name_length, al_name, al_name_len,CASE_SENSITIVE , vol->upcase, vol->upcase_len))
@@ -1078,9 +1150,9 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,* If no @val specified or @val specified and it matches, we * have found it! */ -if (!val || (!a->non_resident &&le32_to_cpu ( +if ((type ==AT_UNUSED ) || !val || (!a->non_resident &&le32_to_cpu ( a->data.resident.value_length) == val_len && - !memcmp ((u8 *)a + + !memcmp ((u8 *)a +le16_to_cpu (a->data.resident.value_offset), val, val_len))) {ntfs_debug ("Done, found." );
@@ -1088,22 +1160,27 @@ static int ntfs_external_attr_find(const ATTR_TYPE type, } do_next_attr:/* Proceed to the next attribute in the current mft record. */ - a = (ATTR_RECORD *)((u8 *)a +le32_to_cpu (a->length)); + a = (struct attr_record *)((u8 *)a +le32_to_cpu (a->length)); goto do_next_attr_loop; } -if (!err) { -ntfs_error (vol->sb,"Base inode 0x%lx contains corrupt " -"attribute list attribute.%s" , base_ni->mft_no, - es); - err = -EIO ; - } + +corrupt:if (ni != base_ni) {if (ni)unmap_extent_mft_record (ni); ctx->ntfs_ino = base_ni; ctx->mrec = ctx->base_mrec; ctx->attr = ctx->base_attr; + ctx->mapped_mrec = ctx->mapped_base_mrec; + } + +if (!err) { +ntfs_error (vol->sb, +"Base inode 0x%lx contains corrupt attribute list attribute.%s" , + base_ni->mft_no, es); + err = -EIO ; } +if (err != -ENOMEM )NVolSetErrors (vol);return err;
@@ -1112,7 +1189,7 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,* If we were looking for AT_END, we reset the search context @ctx and * use ntfs_attr_find() to seek to the end of the base mft record. */ -if (type ==AT_END ) { +if (type ==AT_UNUSED || type ==AT_END ) {ntfs_attr_reinit_search_ctx (ctx);return ntfs_attr_find (AT_END , name, name_len, ic, val, val_len, ctx);
@@ -1133,13 +1210,14 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,if (ni != base_ni)unmap_extent_mft_record (ni); ctx->mrec = ctx->base_mrec; - ctx->attr = (ATTR_RECORD *)((u8 *)ctx->mrec + + ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +le16_to_cpu (ctx->mrec->attrs_offset)); ctx->is_first = true; ctx->ntfs_ino = base_ni; ctx->base_ntfs_ino =NULL ; ctx->base_mrec =NULL ; ctx->base_attr =NULL ; + ctx->mapped_mrec = ctx->mapped_base_mrec;/* * In case there are multiple matches in the base mft record, need to * keep enumerating until we get an attribute not found response (or
@@ -1190,26 +1268,21 @@ static int ntfs_external_attr_find(const ATTR_TYPE type,* collates just after the attribute list entry of the attribute being searched * for, i.e. if one wants to add the attribute to the mft record this is the * correct place to insert its attribute list entry into. -* -* When -errno != -ENOENT, an error occurred during the lookup. @ctx->attr is -* then undefined and in particular you should not rely on it not changing. */ -int ntfs_attr_lookup (const ATTR_TYPE type,const ntfschar *name, -const u32 name_len,const IGNORE_CASE_BOOL ic, -const VCN lowest_vcn,const u8 *val,const u32 val_len, -ntfs_attr_search_ctx *ctx) +int ntfs_attr_lookup (const __le32 type,const __le16 *name, +const u32 name_len,const u32 ic, +const s64 lowest_vcn,const u8 *val,const u32 val_len, +struct ntfs_attr_search_ctx *ctx) { -ntfs_inode *base_ni; +struct ntfs_inode *base_ni;ntfs_debug ("Entering." ); -BUG_ON (IS_ERR (ctx->mrec));if (ctx->base_ntfs_ino) base_ni = ctx->base_ntfs_ino;else base_ni = ctx->ntfs_ino;/* Sanity check, just for debugging really. */ -BUG_ON (!base_ni); -if (!NInoAttrList (base_ni) || type ==AT_ATTRIBUTE_LIST ) +if (!base_ni || !NInoAttrList (base_ni) || type ==AT_ATTRIBUTE_LIST )return ntfs_attr_find (type, name, name_len, ic, val, val_len, ctx); return ntfs_external_attr_find(type, name, name_len, ic, lowest_vcn,
@@ -1218,23 +1291,35 @@ int ntfs_attr_lookup(const ATTR_TYPE type, const ntfschar *name,/** * ntfs_attr_init_search_ctx - initialize an attribute search context -* @ctx: attribute search context to initialize -* @ni: ntfs inode with which to initialize the search context -* @mrec: mft record with which to initialize the search context +* @ctx: attribute search context to initialize +* @ni: ntfs inode with which to initialize the search context +* @mrec: mft record with which to initialize the search context * * Initialize the attribute search context @ctx with @ni and @mrec. */ -static inline void ntfs_attr_init_search_ctx (ntfs_attr_search_ctx *ctx, -ntfs_inode *ni,MFT_RECORD *mrec) +static bool ntfs_attr_init_search_ctx (struct ntfs_attr_search_ctx *ctx, +struct ntfs_inode *ni,struct mft_record *mrec) { - *ctx = (ntfs_attr_search_ctx ) { - .mrec = mrec, -/* Sanity checks are performed elsewhere. */ - .attr = (ATTR_RECORD *)((u8 *)mrec + -le16_to_cpu (mrec->attrs_offset)), - .is_first = true, - .ntfs_ino = ni, - }; +if (!mrec) { + mrec =map_mft_record (ni); +if (IS_ERR (mrec)) +return false; + ctx->mapped_mrec = true; + }else { + ctx->mapped_mrec = false; + } + + ctx->mrec = mrec; +/* Sanity checks are performed elsewhere. */ + ctx->attr = (struct attr_record *)((u8 *)mrec +le16_to_cpu (mrec->attrs_offset)); + ctx->is_first = true; + ctx->ntfs_ino = ni; + ctx->al_entry =NULL ; + ctx->base_ntfs_ino =NULL ; + ctx->base_mrec =NULL ; + ctx->base_attr =NULL ; + ctx->mapped_base_mrec = false; +return true; }/**
@@ -1247,13 +1332,15 @@ static inline void ntfs_attr_init_search_ctx(ntfs_attr_search_ctx *ctx,* This is used when a search for a new attribute is being started to reset * the search context to the beginning. */ -void ntfs_attr_reinit_search_ctx (ntfs_attr_search_ctx *ctx) +void ntfs_attr_reinit_search_ctx (struct ntfs_attr_search_ctx *ctx) { +bool mapped_mrec; +if (likely (!ctx->base_ntfs_ino)) {/* No attribute list. */ ctx->is_first = true;/* Sanity checks are performed elsewhere. */ - ctx->attr = (ATTR_RECORD *)((u8 *)ctx->mrec + + ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +le16_to_cpu (ctx->mrec->attrs_offset));/* * This needs resetting due to ntfs_external_attr_find() which
@@ -1262,10 +1349,12 @@ void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx) ctx->al_entry =NULL ;return ; }/* Attribute list. */ -if (ctx->ntfs_ino != ctx->base_ntfs_ino) +if (ctx->ntfs_ino != ctx->base_ntfs_ino && ctx->ntfs_ino)unmap_extent_mft_record (ctx->ntfs_ino); + + mapped_mrec = ctx->mapped_base_mrec;ntfs_attr_init_search_ctx (ctx, ctx->base_ntfs_ino, ctx->base_mrec); -return ; + ctx->mapped_mrec = mapped_mrec; }/**
@@ -1276,13 +1365,21 @@ void ntfs_attr_reinit_search_ctx(ntfs_attr_search_ctx *ctx)* Allocate a new attribute search context, initialize it with @ni and @mrec, * and return it. Return NULL if allocation failed. */ -ntfs_attr_search_ctx *ntfs_attr_get_search_ctx (ntfs_inode *ni,MFT_RECORD *mrec) +struct ntfs_attr_search_ctx *ntfs_attr_get_search_ctx (struct ntfs_inode *ni, +struct mft_record *mrec) { -ntfs_attr_search_ctx *ctx; +struct ntfs_attr_search_ctx *ctx; +bool init; ctx =kmem_cache_alloc (ntfs_attr_ctx_cache,GFP_NOFS ); -if (ctx) -ntfs_attr_init_search_ctx (ctx, ni, mrec); +if (ctx) { + init =ntfs_attr_init_search_ctx (ctx, ni, mrec); +if (init == false) { +kmem_cache_free (ntfs_attr_ctx_cache, ctx); + ctx =NULL ; + } + } +return ctx; }
@@ -1293,16 +1390,17 @@ ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(ntfs_inode *ni, MFT_RECORD *mrec)* Release the attribute search context @ctx, unmapping an associated extent * mft record if present. */ -void ntfs_attr_put_search_ctx (ntfs_attr_search_ctx *ctx) +void ntfs_attr_put_search_ctx (struct ntfs_attr_search_ctx *ctx) { -if (ctx->base_ntfs_ino && ctx->ntfs_ino != ctx->base_ntfs_ino) -unmap_extent_mft_record (ctx->ntfs_ino); +if (ctx->mapped_mrec) +unmap_mft_record (ctx->ntfs_ino); + +if (ctx->mapped_base_mrec && ctx->base_ntfs_ino && + ctx->ntfs_ino != ctx->base_ntfs_ino) +unmap_extent_mft_record (ctx->base_ntfs_ino);kmem_cache_free (ntfs_attr_ctx_cache, ctx); -return ; } -#ifdef NTFS_RW -/** * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file * @vol: ntfs volume to which the attribute belongs
@@ -1313,14 +1411,13 @@ void ntfs_attr_put_search_ctx(ntfs_attr_search_ctx *ctx)* * Return the attribute type definition record if found and NULL if not found. */ -static ATTR_DEF *ntfs_attr_find_in_attrdef (const ntfs_volume *vol, -const ATTR_TYPE type) +static struct attr_def *ntfs_attr_find_in_attrdef (const struct ntfs_volume *vol, +const __le32 type) { -ATTR_DEF *ad; +struct attr_def *ad; -BUG_ON (!vol->attrdef); -BUG_ON (!type); -for (ad = vol->attrdef; (u8 *)ad - (u8 *)vol->attrdef < +WARN_ON (!type); +for (ad = vol->attrdef; (u8 *)ad - (u8 *)vol->attrdef < vol->attrdef_size && ad->type; ++ad) {/* We have not found it yet, carry on searching. */ if (likely (le32_to_cpu (ad->type) <le32_to_cpu (type)))
@@ -1345,16 +1442,15 @@ static ATTR_DEF *ntfs_attr_find_in_attrdef(const ntfs_volume *vol,* * Check whether the @size in bytes is valid for an attribute of @type on the * ntfs volume @vol. This information is obtained from $AttrDef system file. -* -* Return 0 if valid, -ERANGE if not valid, or -ENOENT if the attribute is not -* listed in $AttrDef. */ -int ntfs_attr_size_bounds_check (const ntfs_volume *vol,const ATTR_TYPE type, +int ntfs_attr_size_bounds_check (const struct ntfs_volume *vol,const __le32 type,const s64 size) { -ATTR_DEF *ad; +struct attr_def *ad; + +if (size <0 ) +return -EINVAL ; -BUG_ON (size <0 );/* * $ATTRIBUTE_LIST has a maximum size of 256kiB, but this is not * listed in $AttrDef.
@@ -1366,10 +1462,10 @@ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPE type,if (unlikely (!ad))return -ENOENT ;/* Do the bounds check. */ -if (((sle64_to_cpu (ad->min_size) >0 ) && - size <sle64_to_cpu (ad->min_size)) || - ((sle64_to_cpu (ad->max_size) >0 ) && size > -sle64_to_cpu (ad->max_size))) +if (((le64_to_cpu (ad->min_size) >0 ) && + size <le64_to_cpu (ad->min_size)) || + ((le64_to_cpu (ad->max_size) >0 ) && size > +le64_to_cpu (ad->max_size)))return -ERANGE ;return 0 ; }
@@ -1381,13 +1477,11 @@ int ntfs_attr_size_bounds_check(const ntfs_volume *vol, const ATTR_TYPE type,* * Check whether the attribute of @type on the ntfs volume @vol is allowed to * be non-resident. This information is obtained from $AttrDef system file. -* -* Return 0 if the attribute is allowed to be non-resident, -EPERM if not, and -* -ENOENT if the attribute is not listed in $AttrDef. */ -int ntfs_attr_can_be_non_resident (const ntfs_volume *vol,const ATTR_TYPE type) +static int ntfs_attr_can_be_non_resident (const struct ntfs_volume *vol, +const __le32 type) { -ATTR_DEF *ad; +struct attr_def *ad;/* Find the attribute definition record in $AttrDef. */ ad =ntfs_attr_find_in_attrdef (vol, type);
@@ -1417,7 +1511,7 @@ int ntfs_attr_can_be_non_resident(const ntfs_volume *vol, const ATTR_TYPE type)* check for this here as we do not know which inode's $Bitmap is * being asked about so the caller needs to special case this. */ -int ntfs_attr_can_be_resident (const ntfs_volume *vol,const ATTR_TYPE type) +int ntfs_attr_can_be_resident (const struct ntfs_volume *vol,const __le32 type) {if (type ==AT_INDEX_ALLOCATION )return -EPERM ;
@@ -1432,37 +1526,45 @@ int ntfs_attr_can_be_resident(const ntfs_volume *vol, const ATTR_TYPE type)* * Resize the attribute record @a, i.e. the resident part of the attribute, in * the mft record @m to @new_size bytes. -* -* Return 0 on success and -errno on error. The following error codes are -* defined: -* -ENOSPC - Not enough space in the mft record @m to perform the resize. -* -* Note: On error, no modifications have been performed whatsoever. -* -* Warning: If you make a record smaller without having copied all the data you -* are interested in the data may be overwritten. */ -int ntfs_attr_record_resize (MFT_RECORD *m,ATTR_RECORD *a,u32 new_size) +int ntfs_attr_record_resize (struct mft_record *m,struct attr_record *a,u32 new_size) { -ntfs_debug ("Entering for new_size %u." , new_size); +u32 old_size, alloc_size, attr_size; + + old_size =le32_to_cpu (m->bytes_in_use); + alloc_size =le32_to_cpu (m->bytes_allocated); + attr_size =le32_to_cpu (a->length); + +ntfs_debug ("Sizes: old=%u alloc=%u attr=%u new=%u\n" , + (unsigned int )old_size, (unsigned int )alloc_size, + (unsigned int )attr_size, (unsigned int )new_size); +/* Align to 8 bytes if it is not already done. */ if (new_size &7 ) new_size = (new_size +7 ) & ~7 ;/* If the actual attribute length has changed, move things around. */ -if (new_size !=le32_to_cpu (a->length)) { +if (new_size != attr_size) {u32 new_muse =le32_to_cpu (m->bytes_in_use) - -le32_to_cpu (a->length) + new_size; + attr_size + new_size;/* Not enough space in this mft record. */ if (new_muse >le32_to_cpu (m->bytes_allocated))return -ENOSPC ; + +if (a->type ==AT_INDEX_ROOT && new_size > attr_size && + new_muse +120 > alloc_size && old_size +120 <= alloc_size) { +ntfs_debug ("Too big struct index_root (%u > %u)\n" , + new_muse, alloc_size); +return -ENOSPC ; + } +/* Move attributes following @a to their new location. */ -memmove ((u8 *)a + new_size, (u8 *)a +le32_to_cpu (a->length), -le32_to_cpu (m->bytes_in_use) - ((u8 *)a - - (u8 *)m) -le32_to_cpu (a->length)); +memmove ((u8 *)a + new_size, (u8 *)a +le32_to_cpu (a->length), +le32_to_cpu (m->bytes_in_use) - ((u8 *)a - + (u8 *)m) - attr_size);/* Adjust @m to reflect the change in used space. */ m->bytes_in_use =cpu_to_le32 (new_muse);/* Adjust @a to reflect the new size. */ -if (new_size >= offsetof(ATTR_REC , length) +sizeof (a->length)) +if (new_size >= offsetof(struct attr_record , length) +sizeof (a->length)) a->length =cpu_to_le32 (new_size); }return 0 ;
@@ -1476,17 +1578,8 @@ int ntfs_attr_record_resize(MFT_RECORD *m, ATTR_RECORD *a, u32 new_size)* * Resize the value of the attribute @a in the mft record @m to @new_size bytes. * If the value is made bigger, the newly allocated space is cleared. -* -* Return 0 on success and -errno on error. The following error codes are -* defined: -* -ENOSPC - Not enough space in the mft record @m to perform the resize. -* -* Note: On error, no modifications have been performed whatsoever. -* -* Warning: If you make a record smaller without having copied all the data you -* are interested in the data may be overwritten. */ -int ntfs_resident_attr_value_resize (MFT_RECORD *m,ATTR_RECORD *a, +int ntfs_resident_attr_value_resize (struct mft_record *m,struct attr_record *a,const u32 new_size) {u32 old_size;
@@ -1501,7 +1594,7 @@ int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a,*/ old_size =le32_to_cpu (a->data.resident.value_length);if (new_size > old_size) -memset ((u8 *)a +le16_to_cpu (a->data.resident.value_offset) + +memset ((u8 *)a +le16_to_cpu (a->data.resident.value_offset) + old_size,0 , new_size - old_size);/* Finally update the length of the attribute value. */ a->data.resident.value_length =cpu_to_le32 (new_size);
@@ -1521,100 +1614,43 @@ int ntfs_resident_attr_value_resize(MFT_RECORD *m, ATTR_RECORD *a,* always know it. The reason we cannot simply read the size from the vfs * inode i_size is that this is not necessarily uptodate. This happens when * ntfs_attr_make_non_resident() is called in the ->truncate call path(s). -* -* Return 0 on success and -errno on error. The following error return codes -* are defined: -* -EPERM - The attribute is not allowed to be non-resident. -* -ENOMEM - Not enough memory. -* -ENOSPC - Not enough disk space. -* -EINVAL - Attribute not defined on the volume. -* -EIO - I/o error or other error. -* Note that -ENOSPC is also returned in the case that there is not enough -* space in the mft record to do the conversion. This can happen when the mft -* record is already very full. The caller is responsible for trying to make -* space in the mft record and trying again. FIXME: Do we need a separate -* error return code for this kind of -ENOSPC or is it always worth trying -* again in case the attribute may then fit in a resident state so no need to -* make it non-resident at all? Ho-hum... (AIA) -* -* NOTE to self: No changes in the attribute list are required to move from -* a resident to a non-resident attribute. -* -* Locking: - The caller must hold i_mutex on the inode. */ -int ntfs_attr_make_non_resident (ntfs_inode *ni,const u32 data_size) +int ntfs_attr_make_non_resident (struct ntfs_inode *ni,const u32 data_size) {s64 new_size;struct inode *vi =VFS_I (ni); -ntfs_volume *vol = ni->vol; -ntfs_inode *base_ni; -MFT_RECORD *m; -ATTR_RECORD *a; -ntfs_attr_search_ctx *ctx; -struct page *page; -runlist_element *rl; +struct ntfs_volume *vol = ni->vol; +struct ntfs_inode *base_ni; +struct mft_record *m; +struct attr_record *a; +struct ntfs_attr_search_ctx *ctx; +struct folio *folio; +struct runlist_element *rl;u8 *kaddr;unsigned long flags;int mp_size, mp_ofs, name_ofs, arec_size, err, err2;u32 attr_size;u8 old_res_attr_flags; +if (NInoNonResident (ni)) { +ntfs_warning (vol->sb, +"Trying to make non-resident attribute non-resident. Aborting...\n" ); +return -EINVAL ; + } +/* Check that the attribute is allowed to be non-resident. */ err =ntfs_attr_can_be_non_resident (vol, ni->type);if (unlikely (err)) {if (err == -EPERM ) -ntfs_debug ("Attribute is not allowed to be " -"non-resident." ); +ntfs_debug ("Attribute is not allowed to be non-resident." );else -ntfs_debug ("Attribute not defined on the NTFS " -"volume!" ); +ntfs_debug ("Attribute not defined on the NTFS volume!" );return err; } -/* -* FIXME: Compressed and encrypted attributes are not supported when -* writing and we should never have gotten here for them. -*/ -BUG_ON (NInoCompressed (ni)); -BUG_ON (NInoEncrypted (ni)); -/* -* The size needs to be aligned to a cluster boundary for allocation -* purposes. -*/ - new_size = (data_size + vol->cluster_size -1 ) & - ~(vol->cluster_size -1 ); -if (new_size >0 ) { -/* -* Will need the page later and since the page lock nests -* outside all ntfs locks, we need to get the page now. -*/ - page =find_or_create_page (vi->i_mapping,0 , -mapping_gfp_mask (vi->i_mapping)); -if (unlikely (!page)) -return -ENOMEM ; -/* Start by allocating clusters to hold the attribute value. */ - rl =ntfs_cluster_alloc (vol,0 , new_size >> - vol->cluster_size_bits,-1 ,DATA_ZONE , true); -if (IS_ERR (rl)) { - err =PTR_ERR (rl); -ntfs_debug ("Failed to allocate cluster%s, error code " -"%i." , (new_size >> - vol->cluster_size_bits) >1 ?"s" :"" , - err); - goto page_err_out; - } - }else { - rl =NULL ; - page =NULL ; - } -/* Determine the size of the mapping pairs array. */ - mp_size =ntfs_get_size_for_mapping_pairs (vol, rl,0 ,-1 ); -if (unlikely (mp_size <0 )) { - err = mp_size; -ntfs_debug ("Failed to get size for mapping pairs array, error " -"code %i." , err); - goto rl_err_out; - } -down_write (&ni->runlist.lock); + +if (NInoEncrypted (ni)) +return -EIO ; +if (!NInoAttr (ni)) base_ni = ni;else
@@ -1640,47 +1676,105 @@ int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size) } m = ctx->mrec; a = ctx->attr; -BUG_ON (NInoNonResident (ni)); -BUG_ON (a->non_resident); + +/* +* The size needs to be aligned to a cluster boundary for allocation +* purposes. +*/ + new_size = (data_size + vol->cluster_size -1 ) & + ~(vol->cluster_size -1 ); +if (new_size >0 ) { +if ((a->flags &ATTR_COMPRESSION_MASK ) ==ATTR_IS_COMPRESSED ) { +/* must allocate full compression blocks */ + new_size = + ((new_size -1 ) | + ((1L << (STANDARD_COMPRESSION_UNIT + + vol->cluster_size_bits)) -1 )) +1 ; + } + +/* +* Will need folio later and since folio lock nests +* outside all ntfs locks, we need to get the folio now. +*/ + folio =__filemap_get_folio (vi->i_mapping,0 , +FGP_CREAT |FGP_LOCK , +mapping_gfp_mask (vi->i_mapping)); +if (IS_ERR (folio)) { + err = -ENOMEM ; + goto err_out; + } + +/* Start by allocating clusters to hold the attribute value. */ + rl =ntfs_cluster_alloc (vol,0 ,NTFS_B_TO_CLU (vol, new_size), +-1 ,DATA_ZONE , true, + false, false); +if (IS_ERR (rl)) { + err =PTR_ERR (rl); +ntfs_debug ("Failed to allocate cluster%s, error code %i." , + (NTFS_B_TO_CLU (vol, new_size)) >1 ?"s" :"" , + err); + goto folio_err_out; + } + }else { + rl =NULL ; + folio =NULL ; + } + +down_write (&ni->runlist.lock); +/* Determine the size of the mapping pairs array. */ + mp_size =ntfs_get_size_for_mapping_pairs (vol, rl,0 ,-1 ,-1 ); +if (unlikely (mp_size <0 )) { + err = mp_size; +ntfs_debug ("Failed to get size for mapping pairs array, error code %i.\n" , err); + goto rl_err_out; + } + +if (NInoNonResident (ni) || a->non_resident) { + err = -EIO ; + goto rl_err_out; + } +/* * Calculate new offsets for the name and the mapping pairs array. */ if (NInoSparse (ni) ||NInoCompressed (ni)) - name_ofs = (offsetof(ATTR_REC , + name_ofs = (offsetof(struct attr_record , data.non_resident.compressed_size) +sizeof (a->data.non_resident.compressed_size) + 7) & ~7;else - name_ofs = (offsetof(ATTR_REC , + name_ofs = (offsetof(struct attr_record , data.non_resident.compressed_size) + 7) & ~7; - mp_ofs = (name_ofs + a->name_length *sizeof (ntfschar) +7 ) & ~7 ; + mp_ofs = (name_ofs + a->name_length *sizeof (__le16) +7 ) & ~7 ;/* * Determine the size of the resident part of the now non-resident * attribute record. */ arec_size = (mp_ofs + mp_size +7 ) & ~7 ;/* -* If the page is not uptodate bring it uptodate by copying from the +* If the folio is not uptodate bring it uptodate by copying from the * attribute value. */ attr_size =le32_to_cpu (a->data.resident.value_length); -BUG_ON (attr_size != data_size); -if (page && !PageUptodate (page)) { - kaddr =kmap_atomic (page); -memcpy (kaddr, (u8 *)a + +WARN_ON (attr_size != data_size); +if (folio && !folio_test_uptodate (folio)) { + kaddr =kmap_local_folio (folio,0 ); +memcpy (kaddr, (u8 *)a +le16_to_cpu (a->data.resident.value_offset), attr_size);memset (kaddr + attr_size,0 ,PAGE_SIZE - attr_size); -kunmap_atomic (kaddr); -flush_dcache_page (page); -SetPageUptodate (page); +kunmap_local (kaddr); +flush_dcache_folio (folio); +folio_mark_uptodate (folio); } +/* Backup the attribute flag. */ old_res_attr_flags = a->data.resident.flags;/* Resize the resident part of the attribute record. */ err =ntfs_attr_record_resize (m, a, arec_size);if (unlikely (err)) - goto err_out; + goto rl_err_out; +/* * Convert the resident part of the attribute record to describe a * non-resident attribute.
@@ -1688,20 +1782,19 @@ int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size) a->non_resident =1 ;/* Move the attribute name if it exists and update the offset. */ if (a->name_length) -memmove ((u8 *)a + name_ofs, (u8 *)a +le16_to_cpu (a->name_offset), - a->name_length *sizeof (ntfschar)); +memmove ((u8 *)a + name_ofs, (u8 *)a +le16_to_cpu (a->name_offset), + a->name_length *sizeof (__le16)); a->name_offset =cpu_to_le16 (name_ofs);/* Setup the fields specific to non-resident attributes. */ a->data.non_resident.lowest_vcn =0 ; - a->data.non_resident.highest_vcn =cpu_to_sle64 ((new_size -1 ) >> - vol->cluster_size_bits); + a->data.non_resident.highest_vcn =cpu_to_le64 (NTFS_B_TO_CLU (vol, new_size -1 )); a->data.non_resident.mapping_pairs_offset =cpu_to_le16 (mp_ofs);memset (&a->data.non_resident.reserved,0 ,sizeof (a->data.non_resident.reserved)); - a->data.non_resident.allocated_size =cpu_to_sle64 (new_size); + a->data.non_resident.allocated_size =cpu_to_le64 (new_size); a->data.non_resident.data_size = a->data.non_resident.initialized_size = -cpu_to_sle64 (attr_size); +cpu_to_le64 (attr_size);if (NInoSparse (ni) ||NInoCompressed (ni)) { a->data.non_resident.compression_unit =0 ;if (NInoCompressed (ni) || vol->major_ver <3 )
@@ -1711,23 +1804,29 @@ int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size) }else a->data.non_resident.compression_unit =0 ;/* Generate the mapping pairs array into the attribute record. */ - err =ntfs_mapping_pairs_build (vol, (u8 *)a + mp_ofs, - arec_size - mp_ofs, rl,0 ,-1 ,NULL ); + err =ntfs_mapping_pairs_build (vol, (u8 *)a + mp_ofs, + arec_size - mp_ofs, rl,0 ,-1 ,NULL ,NULL ,NULL );if (unlikely (err)) { -ntfs_debug ("Failed to build mapping pairs, error code %i." , +ntfs_error (vol->sb,"Failed to build mapping pairs, error code %i." , err); goto undo_err_out; } +/* Setup the in-memory attribute structure to be non-resident. */ ni->runlist.rl = rl; +if (rl) { +for (ni->runlist.count =1 ; rl->length !=0 ; rl++) + ni->runlist.count++; + }else + ni->runlist.count =0 ;write_lock_irqsave (&ni->size_lock, flags); ni->allocated_size = new_size;if (NInoSparse (ni) ||NInoCompressed (ni)) { ni->itype.compressed.size = ni->allocated_size;if (a->data.non_resident.compression_unit) { - ni->itype.compressed.block_size =1U << (a->data. - non_resident.compression_unit + - vol->cluster_size_bits); + ni->itype.compressed.block_size =1U << + (a->data.non_resident.compression_unit + + vol->cluster_size_bits); ni->itype.compressed.block_size_bits =ffs (ni->itype.compressed.block_size) -1 ;
@@ -1749,16 +1848,16 @@ int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size)* this switch, which is another reason to do this last. */ NInoSetNonResident (ni); +NInoSetFullyMapped (ni);/* Mark the mft record dirty, so it gets written back. */ -flush_dcache_mft_record_page (ctx->ntfs_ino);mark_mft_record_dirty (ctx->ntfs_ino);ntfs_attr_put_search_ctx (ctx);unmap_mft_record (base_ni);up_write (&ni->runlist.lock); -if (page) { -set_page_dirty (page); -unlock_page (page); -put_page (page); +if (folio) { +iomap_dirty_folio (vi->i_mapping, folio); +folio_unlock (folio); +folio_put (folio); }ntfs_debug ("Done." );return 0 ;
@@ -1766,12 +1865,12 @@ int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size)/* Convert the attribute back into a resident attribute. */ a->non_resident =0 ;/* Move the attribute name if it exists and update the offset. */ - name_ofs = (offsetof(ATTR_RECORD, data.resident.reserved) + + name_ofs = (offsetof(struct attr_record, data.resident.reserved) + sizeof(a->data.resident.reserved) + 7) & ~7;if (a->name_length) -memmove ((u8 *)a + name_ofs, (u8 *)a +le16_to_cpu (a->name_offset), - a->name_length *sizeof (ntfschar)); - mp_ofs = (name_ofs + a->name_length *sizeof (ntfschar) +7 ) & ~7 ; +memmove ((u8 *)a + name_ofs, (u8 *)a +le16_to_cpu (a->name_offset), + a->name_length *sizeof (__le16)); + mp_ofs = (name_ofs + a->name_length *sizeof (__le16) +7 ) & ~7 ; a->name_offset =cpu_to_le16 (name_ofs); arec_size = (mp_ofs + attr_size +7 ) & ~7 ;/* Resize the resident part of the attribute record. */
@@ -1782,25 +1881,18 @@ int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size)* could happen in theory), but deal with it as well as we can. * If the old size is too small, truncate the attribute, * otherwise simply give it a larger allocated size. -* FIXME: Should check whether chkdsk complains when the -* allocated size is much bigger than the resident value size. */ arec_size =le32_to_cpu (a->length);if ((mp_ofs + attr_size) > arec_size) { err2 = attr_size; attr_size = arec_size - mp_ofs; -ntfs_error (vol->sb,"Failed to undo partial resident " -"to non-resident attribute " -"conversion. Truncating inode 0x%lx, " -"attribute type 0x%x from %i bytes to " -"%i bytes to maintain metadata " -"consistency. THIS MEANS YOU ARE " -"LOSING %i BYTES DATA FROM THIS %s." , +ntfs_error (vol->sb, +"Failed to undo partial resident to non-resident attribute conversion. Truncating inode 0x%lx, attribute type 0x%x from %i bytes to %i bytes to maintain metadata consistency. THIS MEANS YOU ARE LOSING %i BYTES DATA FROM THIS %s." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), + (unsigned int )le32_to_cpu (ni->type), err2, attr_size, err2 - attr_size, ((ni->type ==AT_DATA ) && - !ni->name_len) ?"FILE" :"ATTRIBUTE" ); + !ni->name_len) ?"FILE" :"ATTRIBUTE" );write_lock_irqsave (&ni->size_lock, flags); ni->initialized_size = attr_size;i_size_write (vi, attr_size);
@@ -1813,812 +1905,3480 @@ int ntfs_attr_make_non_resident(ntfs_inode *ni, const u32 data_size) a->data.resident.flags = old_res_attr_flags;memset (&a->data.resident.reserved,0 ,sizeof (a->data.resident.reserved)); -/* Copy the data from the page back to the attribute value. */ -if (page) { - kaddr =kmap_atomic (page); -memcpy ((u8 *)a + mp_ofs, kaddr, attr_size); -kunmap_atomic (kaddr); - } +/* Copy the data from folio back to the attribute value. */ +if (folio) +memcpy_from_folio ((u8 *)a + mp_ofs, folio,0 , attr_size);/* Setup the allocated size in the ntfs inode in case it changed. */ write_lock_irqsave (&ni->size_lock, flags); ni->allocated_size = arec_size - mp_ofs;write_unlock_irqrestore (&ni->size_lock, flags);/* Mark the mft record dirty, so it gets written back. */ -flush_dcache_mft_record_page (ctx->ntfs_ino);mark_mft_record_dirty (ctx->ntfs_ino); -err_out: -if (ctx) -ntfs_attr_put_search_ctx (ctx); -if (m) -unmap_mft_record (base_ni); - ni->runlist.rl =NULL ; -up_write (&ni->runlist.lock); rl_err_out: +up_write (&ni->runlist.lock);if (rl) {if (ntfs_cluster_free_from_rl (vol, rl) <0 ) { -ntfs_error (vol->sb,"Failed to release allocated " -"cluster(s) in error code path. Run " -"chkdsk to recover the lost " -"cluster(s)." ); +ntfs_error (vol->sb, +"Failed to release allocated cluster(s) in error code path. Run chkdsk to recover the lost cluster(s)." );NVolSetErrors (vol); }ntfs_free (rl); -page_err_out: -unlock_page (page); -put_page (page); +folio_err_out: +folio_unlock (folio); +folio_put (folio); } +err_out: +if (ctx) +ntfs_attr_put_search_ctx (ctx); +if (m) +unmap_mft_record (base_ni); + ni->runlist.rl =NULL ; +if (err == -EINVAL ) err = -EIO ;return err; }/** -* ntfs_attr_extend_allocation - extend the allocated space of an attribute -* @ni: ntfs inode of the attribute whose allocation to extend -* @new_alloc_size: new size in bytes to which to extend the allocation to -* @new_data_size: new size in bytes to which to extend the data to -* @data_start: beginning of region which is required to be non-sparse -* -* Extend the allocated space of an attribute described by the ntfs inode @ni -* to @new_alloc_size bytes. If @data_start is -1, the whole extension may be -* implemented as a hole in the file (as long as both the volume and the ntfs -* inode @ni have sparse support enabled). If @data_start is >= 0, then the -* region between the old allocated size and @data_start - 1 may be made sparse -* but the regions between @data_start and @new_alloc_size must be backed by -* actual clusters. -* -* If @new_data_size is -1, it is ignored. If it is >= 0, then the data size -* of the attribute is extended to @new_data_size. Note that the i_size of the -* vfs inode is not updated. Only the data size in the base attribute record -* is updated. The caller has to update i_size separately if this is required. -* WARNING: It is a BUG() for @new_data_size to be smaller than the old data -* size as well as for @new_data_size to be greater than @new_alloc_size. -* -* For resident attributes this involves resizing the attribute record and if -* necessary moving it and/or other attributes into extent mft records and/or -* converting the attribute to a non-resident attribute which in turn involves -* extending the allocation of a non-resident attribute as described below. -* -* For non-resident attributes this involves allocating clusters in the data -* zone on the volume (except for regions that are being made sparse) and -* extending the run list to describe the allocated clusters as well as -* updating the mapping pairs array of the attribute. This in turn involves -* resizing the attribute record and if necessary moving it and/or other -* attributes into extent mft records and/or splitting the attribute record -* into multiple extent attribute records. -* -* Also, the attribute list attribute is updated if present and in some of the -* above cases (the ones where extent mft records/attributes come into play), -* an attribute list attribute is created if not already present. -* -* Return the new allocated size on success and -errno on error. In the case -* that an error is encountered but a partial extension at least up to -* @data_start (if present) is possible, the allocation is partially extended -* and this is returned. This means the caller must check the returned size to -* determine if the extension was partial. If @data_start is -1 then partial -* allocations are not performed. -* -* WARNING: Do not call ntfs_attr_extend_allocation() for $MFT/$DATA. -* -* Locking: This function takes the runlist lock of @ni for writing as well as -* locking the mft record of the base ntfs inode. These locks are maintained -* throughout execution of the function. These locks are required so that the -* attribute can be resized safely and so that it can for example be converted -* from resident to non-resident safely. -* -* TODO: At present attribute list attribute handling is not implemented. -* -* TODO: At present it is not safe to call this function for anything other -* than the $DATA attribute(s) of an uncompressed and unencrypted file. +* ntfs_attr_set - fill (a part of) an attribute with a byte +* @ni: ntfs inode describing the attribute to fill +* @ofs: offset inside the attribute at which to start to fill +* @cnt: number of bytes to fill +* @val: the unsigned 8-bit value with which to fill the attribute +* +* Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at +* byte offset @ofs inside the attribute with the constant byte @val. +* +* This function is effectively like memset() applied to an ntfs attribute. +* Note thie function actually only operates on the page cache pages belonging +* to the ntfs attribute and it marks them dirty after doing the memset(). +* Thus it relies on the vm dirty page write code paths to cause the modified +* pages to be written to the mft record/disk. */ -s64 ntfs_attr_extend_allocation (ntfs_inode *ni,s64 new_alloc_size, -const s64 new_data_size,const s64 data_start) +int ntfs_attr_set (struct ntfs_inode *ni,s64 ofs,s64 cnt,const u8 val) { -VCN vcn; -s64 ll, allocated_size, start = data_start; -struct inode *vi =VFS_I (ni); -ntfs_volume *vol = ni->vol; -ntfs_inode *base_ni; -MFT_RECORD *m; -ATTR_RECORD *a; -ntfs_attr_search_ctx *ctx; -runlist_element *rl, *rl2; -unsigned long flags; -int err, mp_size; -u32 attr_len =0 ;/* Silence stupid gcc warning. */ -bool mp_rebuilt; - -#ifdef DEBUG -read_lock_irqsave (&ni->size_lock, flags); - allocated_size = ni->allocated_size; -read_unlock_irqrestore (&ni->size_lock, flags); -ntfs_debug ("Entering for i_ino 0x%lx, attribute type 0x%x, " -"old_allocated_size 0x%llx, " -"new_allocated_size 0x%llx, new_data_size 0x%llx, " -"data_start 0x%llx." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), - (unsigned long long )allocated_size, - (unsigned long long )new_alloc_size, - (unsigned long long )new_data_size, - (unsigned long long )start); -#endif -retry_extend: -/* -* For non-resident attributes, @start and @new_size need to be aligned -* to cluster boundaries for allocation purposes. -*/ -if (NInoNonResident (ni)) { -if (start >0 ) - start &= ~(s64 )vol->cluster_size_mask; - new_alloc_size = (new_alloc_size + vol->cluster_size -1 ) & - ~(s64 )vol->cluster_size_mask; - } -BUG_ON (new_data_size >=0 && new_data_size > new_alloc_size); -/* Check if new size is allowed in $AttrDef. */ - err =ntfs_attr_size_bounds_check (vol, ni->type, new_alloc_size); -if (unlikely (err)) { -/* Only emit errors when the write will fail completely. */ -read_lock_irqsave (&ni->size_lock, flags); - allocated_size = ni->allocated_size; -read_unlock_irqrestore (&ni->size_lock, flags); -if (start <0 || start >= allocated_size) { -if (err == -ERANGE ) { -ntfs_error (vol->sb,"Cannot extend allocation " -"of inode 0x%lx, attribute " -"type 0x%x, because the new " -"allocation would exceed the " -"maximum allowed size for " -"this attribute type." , - vi->i_ino, (unsigned ) -le32_to_cpu (ni->type)); - }else { -ntfs_error (vol->sb,"Cannot extend allocation " -"of inode 0x%lx, attribute " -"type 0x%x, because this " -"attribute type is not " -"defined on the NTFS volume. " -"Possible corruption! You " -"should run chkdsk!" , - vi->i_ino, (unsigned ) -le32_to_cpu (ni->type)); - } +struct address_space *mapping =VFS_I (ni)->i_mapping; +struct folio *folio; +pgoff_t index; +u8 *addr; +unsigned long offset; +size_t attr_len; +int ret =0 ; + + index = ofs >>PAGE_SHIFT ; +while (cnt) { + folio =read_mapping_folio (mapping, index,NULL ); +if (IS_ERR (folio)) { + ret =PTR_ERR (folio); +ntfs_error (VFS_I (ni)->i_sb,"Failed to read a page %lu for attr %#x: %ld" , + index, ni->type,PTR_ERR (folio)); +break ; } -/* Translate error code to be POSIX conformant for write(2). */ -if (err == -ERANGE ) - err = -EFBIG ; + + offset =offset_in_folio (folio, ofs); + attr_len =min_t (size_t, (size_t )cnt,folio_size (folio) - offset); + +folio_lock (folio); + addr =kmap_local_folio (folio, offset); +memset (addr, val, attr_len); +kunmap_local (addr); + +flush_dcache_folio (folio); +folio_mark_dirty (folio); +folio_unlock (folio); +folio_put (folio); + + ofs += attr_len; + cnt -= attr_len; + index++; +cond_resched (); + } + +return ret; +} + +int ntfs_attr_set_initialized_size (struct ntfs_inode *ni,loff_t new_size) +{ +struct ntfs_attr_search_ctx *ctx; +int err =0 ; + +if (!NInoNonResident (ni)) +return -EINVAL ; + + ctx =ntfs_attr_get_search_ctx (ni,NULL ); +if (!ctx) +return -ENOMEM ; + + err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, +CASE_SENSITIVE ,0 ,NULL ,0 , ctx); +if (err) + goto out_ctx; + + ctx->attr->data.non_resident.initialized_size =cpu_to_le64 (new_size); + ni->initialized_size = new_size; +mark_mft_record_dirty (ctx->ntfs_ino); +out_ctx: +ntfs_attr_put_search_ctx (ctx); +return err; +} + +/** +* ntfs_make_room_for_attr - make room for an attribute inside an mft record +* @m: mft record +* @pos: position at which to make space +* @size: byte size to make available at this position +* +* @pos points to the attribute in front of which we want to make space. +*/ +static int ntfs_make_room_for_attr (struct mft_record *m,u8 *pos,u32 size) +{ +u32 biu; + +ntfs_debug ("Entering for pos 0x%x, size %u.\n" , + (int )(pos - (u8 *)m), (unsigned int ) size); + +/* Make size 8-byte alignment. */ + size = (size +7 ) & ~7 ; + +/* Rigorous consistency checks. */ +if (!m || !pos || pos < (u8 *)m) { +pr_err ("%s: pos=%p m=%p" , __func__, pos, m); +return -EINVAL ; + } + +/* The -8 is for the attribute terminator. */ +if (pos - (u8 *)m > (int )le32_to_cpu (m->bytes_in_use) -8 ) +return -EINVAL ; +/* Nothing to do. */ +if (!size) +return 0 ; + + biu =le32_to_cpu (m->bytes_in_use); +/* Do we have enough space? */ +if (biu + size >le32_to_cpu (m->bytes_allocated) || + pos + size > (u8 *)m +le32_to_cpu (m->bytes_allocated)) { +ntfs_debug ("No enough space in the MFT record\n" ); +return -ENOSPC ; + } +/* Move everything after pos to pos + size. */ +memmove (pos + size, pos, biu - (pos - (u8 *)m)); +/* Update mft record. */ + m->bytes_in_use =cpu_to_le32 (biu + size); +return 0 ; +} + +/** +* ntfs_resident_attr_record_add - add resident attribute to inode +* @ni: opened ntfs inode to which MFT record add attribute +* @type: type of the new attribute +* @name: name of the new attribute +* @name_len: name length of the new attribute +* @val: value of the new attribute +* @size: size of new attribute (length of @val, if @val != NULL) +* @flags: flags of the new attribute +*/ +int ntfs_resident_attr_record_add (struct ntfs_inode *ni,__le32 type, +__le16 *name,u8 name_len,u8 *val,u32 size, +__le16 flags) +{ +struct ntfs_attr_search_ctx *ctx; +u32 length; +struct attr_record *a; +struct mft_record *m; +int err, offset; +struct ntfs_inode *base_ni; + +ntfs_debug ("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n" , + (long long ) ni->mft_no, (unsigned int )le32_to_cpu (type), + (unsigned int )le16_to_cpu (flags)); + +if (!ni || (!name && name_len)) +return -EINVAL ; + + err =ntfs_attr_can_be_resident (ni->vol, type); +if (err) { +if (err == -EPERM ) +ntfs_debug ("Attribute can't be resident.\n" );else - err = -EIO ; +ntfs_debug ("ntfs_attr_can_be_resident failed.\n" );return err; } -if (!NInoAttr (ni)) - base_ni = ni; -else - base_ni = ni->ext.base_ntfs_ino; -/* -* We will be modifying both the runlist (if non-resident) and the mft -* record so lock them both down. -*/ -down_write (&ni->runlist.lock); - m =map_mft_record (base_ni); -if (IS_ERR (m)) { - err =PTR_ERR (m); - m =NULL ; - ctx =NULL ; - goto err_out; - } - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { - err = -ENOMEM ; - goto err_out; + +/* Locate place where record should be. */ + ctx =ntfs_attr_get_search_ctx (ni,NULL ); +if (!ctx) { +ntfs_error (ni->vol->sb,"%s: Failed to get search context" , + __func__); +return -ENOMEM ; } -read_lock_irqsave (&ni->size_lock, flags); - allocated_size = ni->allocated_size; -read_unlock_irqrestore (&ni->size_lock, flags); -/* -* If non-resident, seek to the last extent. If resident, there is -* only one extent, so seek to that. -*/ - vcn =NInoNonResident (ni) ? allocated_size >> vol->cluster_size_bits : -0 ;/* -* Abort if someone did the work whilst we waited for the locks. If we -* just converted the attribute from resident to non-resident it is -* likely that exactly this has happened already. We cannot quite -* abort if we need to update the data size. +* Use ntfs_attr_find instead of ntfs_attr_lookup to find place for +* attribute in @ni->mrec, not any extent inode in case if @ni is base +* file record. */ -if (unlikely (new_alloc_size <= allocated_size)) { -ntfs_debug ("Allocated size already exceeds requested size." ); - new_alloc_size = allocated_size; -if (new_data_size <0 ) - goto done; -/* -* We want the first attribute extent so that we can update the -* data size. -*/ - vcn =0 ; + err =ntfs_attr_find (type, name, name_len,CASE_SENSITIVE , val, size, ctx); +if (!err) { + err = -EEXIST ; +ntfs_debug ("Attribute already present.\n" ); + goto put_err_out; } - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE , vcn,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) - err = -EIO ; - goto err_out; +if (err != -ENOENT ) { + err = -EIO ; + goto put_err_out; } - m = ctx->mrec; a = ctx->attr; -/* Use goto to reduce indentation. */ -if (a->non_resident) - goto do_non_resident_extend; -BUG_ON (NInoNonResident (ni)); -/* The total length of the attribute value. */ - attr_len =le32_to_cpu (a->data.resident.value_length); -/* -* Extend the attribute record to be able to store the new attribute -* size. ntfs_attr_record_resize() will not do anything if the size is -* not changing. -*/ -if (new_alloc_size < vol->mft_record_size && - !ntfs_attr_record_resize (m, a, -le16_to_cpu (a->data.resident.value_offset) + - new_alloc_size)) { -/* The resize succeeded! */ -write_lock_irqsave (&ni->size_lock, flags); - ni->allocated_size =le32_to_cpu (a->length) - -le16_to_cpu (a->data.resident.value_offset); -write_unlock_irqrestore (&ni->size_lock, flags); -if (new_data_size >=0 ) { -BUG_ON (new_data_size < attr_len); - a->data.resident.value_length = -cpu_to_le32 ((u32 )new_data_size); - } - goto flush_done; + m = ctx->mrec; + +/* Make room for attribute. */ + length = offsetof(struct attr_record, data.resident.reserved) + +sizeof (a->data.resident.reserved) + + ((name_len *sizeof (__le16) +7 ) & ~7 ) + + ((size +7 ) & ~7 ); + err =ntfs_make_room_for_attr (ctx->mrec, (u8 *) ctx->attr, length); +if (err) { +ntfs_debug ("Failed to make room for attribute.\n" ); + goto put_err_out; } -/* -* We have to drop all the locks so we can call -* ntfs_attr_make_non_resident(). This could be optimised by try- -* locking the first page cache page and only if that fails dropping -* the locks, locking the page, and redoing all the locking and -* lookups. While this would be a huge optimisation, it is not worth -* it as this is definitely a slow code path. -*/ + +/* Setup record fields. */ + offset = ((u8 *)a - (u8 *)m); + a->type = type; + a->length =cpu_to_le32 (length); + a->non_resident =0 ; + a->name_length = name_len; + a->name_offset = + name_len ? cpu_to_le16((offsetof(struct attr_record, data.resident.reserved) + + sizeof(a->data.resident.reserved))) : cpu_to_le16(0); + + a->flags = flags; + a->instance = m->next_attr_instance; + a->data.resident.value_length =cpu_to_le32 (size); + a->data.resident.value_offset =cpu_to_le16 (length - ((size +7 ) & ~7 )); +if (val) +memcpy ((u8 *)a +le16_to_cpu (a->data.resident.value_offset), val, size); +else +memset ((u8 *)a +le16_to_cpu (a->data.resident.value_offset),0 , size); +if (type ==AT_FILE_NAME ) + a->data.resident.flags =RESIDENT_ATTR_IS_INDEXED ; +else + a->data.resident.flags =0 ; +if (name_len) +memcpy ((u8 *)a +le16_to_cpu (a->name_offset), + name,sizeof (__le16) * name_len); + m->next_attr_instance = +cpu_to_le16 ((le16_to_cpu (m->next_attr_instance) +1 ) &0xffff ); +if (ni->nr_extents ==-1 ) + base_ni = ni->ext.base_ntfs_ino; +else + base_ni = ni; +if (type !=AT_ATTRIBUTE_LIST &&NInoAttrList (base_ni)) { + err =ntfs_attrlist_entry_add (ni, a); +if (err) { +ntfs_attr_record_resize (m, a,0 ); +mark_mft_record_dirty (ctx->ntfs_ino); +ntfs_debug ("Failed add attribute entry to ATTRIBUTE_LIST.\n" ); + goto put_err_out; + } + } +mark_mft_record_dirty (ni);ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); -up_write (&ni->runlist.lock); -/* -* Not enough space in the mft record, try to make the attribute -* non-resident and if successful restart the extension process. -*/ - err =ntfs_attr_make_non_resident (ni, attr_len); -if (likely (!err)) - goto retry_extend; -/* -* Could not make non-resident. If this is due to this not being -* permitted for this attribute type or there not being enough space, -* try to make other attributes non-resident. Otherwise fail. -*/ -if (unlikely (err != -EPERM && err != -ENOSPC )) { -/* Only emit errors when the write will fail completely. */ -read_lock_irqsave (&ni->size_lock, flags); - allocated_size = ni->allocated_size; -read_unlock_irqrestore (&ni->size_lock, flags); -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Cannot extend allocation of " -"inode 0x%lx, attribute type 0x%x, " -"because the conversion from resident " -"to non-resident attribute failed " -"with error code %i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); -if (err != -ENOMEM ) - err = -EIO ; - goto conv_err_out; - } -/* TODO: Not implemented from here, abort. */ -read_lock_irqsave (&ni->size_lock, flags); - allocated_size = ni->allocated_size; -read_unlock_irqrestore (&ni->size_lock, flags); -if (start <0 || start >= allocated_size) { -if (err == -ENOSPC ) -ntfs_error (vol->sb,"Not enough space in the mft " -"record/on disk for the non-resident " -"attribute value. This case is not " -"implemented yet." ); -else /* if (err == -EPERM) */ -ntfs_error (vol->sb,"This attribute type may not be " -"non-resident. This case is not " -"implemented yet." ); - } - err = -EOPNOTSUPP ; - goto conv_err_out; -#if 0 -// TODO: Attempt to make other attributes non-resident. -if (!err) - goto do_resident_extend; -/* -* Both the attribute list attribute and the standard information -* attribute must remain in the base inode. Thus, if this is one of -* these attributes, we have to try to move other attributes out into -* extent mft records instead. -*/ -if (ni->type ==AT_ATTRIBUTE_LIST || - ni->type ==AT_STANDARD_INFORMATION ) { -// TODO: Attempt to move other attributes into extent mft -// records. - err = -EOPNOTSUPP ; -if (!err) - goto do_resident_extend; - goto err_out; +return offset; +put_err_out: +ntfs_attr_put_search_ctx (ctx); +return -EIO ; +} + +/** +* ntfs_non_resident_attr_record_add - add extent of non-resident attribute +* @ni: opened ntfs inode to which MFT record add attribute +* @type: type of the new attribute extent +* @name: name of the new attribute extent +* @name_len: name length of the new attribute extent +* @lowest_vcn: lowest vcn of the new attribute extent +* @dataruns_size: dataruns size of the new attribute extent +* @flags: flags of the new attribute extent +*/ +static int ntfs_non_resident_attr_record_add (struct ntfs_inode *ni,__le32 type, +__le16 *name,u8 name_len,s64 lowest_vcn,int dataruns_size, +__le16 flags) +{ +struct ntfs_attr_search_ctx *ctx; +u32 length; +struct attr_record *a; +struct mft_record *m; +struct ntfs_inode *base_ni; +int err, offset; + +ntfs_debug ("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, dataruns_size %d, flags 0x%x.\n" , + (long long ) ni->mft_no, (unsigned int )le32_to_cpu (type), + (long long ) lowest_vcn, dataruns_size, + (unsigned int )le16_to_cpu (flags)); + +if (!ni || dataruns_size <=0 || (!name && name_len)) +return -EINVAL ; + + err =ntfs_attr_can_be_non_resident (ni->vol, type); +if (err) { +if (err == -EPERM ) +pr_err ("Attribute can't be non resident" ); +else +pr_err ("ntfs_attr_can_be_non_resident failed" ); +return err; } -// TODO: Attempt to move this attribute to an extent mft record, but -// only if it is not already the only attribute in an mft record in -// which case there would be nothing to gain. - err = -EOPNOTSUPP ; -if (!err) - goto do_resident_extend; -/* There is nothing we can do to make enough space. )-: */ - goto err_out; -#endif -do_non_resident_extend: -BUG_ON (!NInoNonResident (ni)); -if (new_alloc_size == allocated_size) { -BUG_ON (vcn); - goto alloc_done; + +/* Locate place where record should be. */ + ctx =ntfs_attr_get_search_ctx (ni,NULL ); +if (!ctx) { +pr_err ("%s: Failed to get search context" , __func__); +return -ENOMEM ; }/* -* If the data starts after the end of the old allocation, this is a -* $DATA attribute and sparse attributes are enabled on the volume and -* for this inode, then create a sparse region between the old -* allocated size and the start of the data. Otherwise simply proceed -* with filling the whole space between the old allocated size and the -* new allocated size with clusters. +* Use ntfs_attr_find instead of ntfs_attr_lookup to find place for +* attribute in @ni->mrec, not any extent inode in case if @ni is base +* file record. */ -if ((start >=0 && start <= allocated_size) || ni->type !=AT_DATA || - !NVolSparseEnabled (vol) ||NInoSparseDisabled (ni)) - goto skip_sparse; -// TODO: This is not implemented yet. We just fill in with real -// clusters for now... -ntfs_debug ("Inserting holes is not-implemented yet. Falling back to " -"allocating real clusters instead." ); -skip_sparse: - rl = ni->runlist.rl; -if (likely (rl)) { -/* Seek to the end of the runlist. */ -while (rl->length) - rl++; - } -/* If this attribute extent is not mapped, map it now. */ -if (unlikely (!rl || rl->lcn ==LCN_RL_NOT_MAPPED || - (rl->lcn ==LCN_ENOENT && rl > ni->runlist.rl && - (rl-1 )->lcn ==LCN_RL_NOT_MAPPED ))) { -if (!rl && !allocated_size) - goto first_alloc; - rl =ntfs_mapping_pairs_decompress (vol, a, ni->runlist.rl); -if (IS_ERR (rl)) { - err =PTR_ERR (rl); -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Cannot extend allocation " -"of inode 0x%lx, attribute " -"type 0x%x, because the " -"mapping of a runlist " -"fragment failed with error " -"code %i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), - err); -if (err != -ENOMEM ) - err = -EIO ; - goto err_out; - } - ni->runlist.rl = rl; -/* Seek to the end of the runlist. */ -while (rl->length) - rl++; + err =ntfs_attr_find (type, name, name_len,CASE_SENSITIVE ,NULL ,0 , ctx); +if (!err) { + err = -EEXIST ; +pr_err ("Attribute 0x%x already present" , type); + goto put_err_out; } -/* -* We now know the runlist of the last extent is mapped and @rl is at -* the end of the runlist. We want to begin allocating clusters -* starting at the last allocated cluster to reduce fragmentation. If -* there are no valid LCNs in the attribute we let the cluster -* allocator choose the starting cluster. -*/ -/* If the last LCN is a hole or simillar seek back to last real LCN. */ -while (rl->lcn <0 && rl > ni->runlist.rl) - rl--; -first_alloc: -// FIXME: Need to implement partial allocations so at least part of the -// write can be performed when start >= 0. (Needed for POSIX write(2) -// conformance.) - rl2 =ntfs_cluster_alloc (vol, allocated_size >> vol->cluster_size_bits, - (new_alloc_size - allocated_size) >> - vol->cluster_size_bits, (rl && (rl->lcn >=0 )) ? - rl->lcn + rl->length :-1 ,DATA_ZONE , true); -if (IS_ERR (rl2)) { - err =PTR_ERR (rl2); -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Cannot extend allocation of " -"inode 0x%lx, attribute type 0x%x, " -"because the allocation of clusters " -"failed with error code %i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); -if (err != -ENOMEM && err != -ENOSPC ) - err = -EIO ; - goto err_out; +if (err != -ENOENT ) { +pr_err ("ntfs_attr_find failed" ); + err = -EIO ; + goto put_err_out; } - rl =ntfs_runlists_merge (ni->runlist.rl, rl2); -if (IS_ERR (rl)) { - err =PTR_ERR (rl); -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Cannot extend allocation of " -"inode 0x%lx, attribute type 0x%x, " -"because the runlist merge failed " -"with error code %i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); -if (err != -ENOMEM ) - err = -EIO ; -if (ntfs_cluster_free_from_rl (vol, rl2)) { -ntfs_error (vol->sb,"Failed to release allocated " -"cluster(s) in error code path. Run " -"chkdsk to recover the lost " -"cluster(s)." ); -NVolSetErrors (vol); - } -ntfs_free (rl2); - goto err_out; + a = ctx->attr; + m = ctx->mrec; + +/* Make room for attribute. */ + dataruns_size = (dataruns_size +7 ) & ~7 ; + length = offsetof(struct attr_record, data.non_resident.compressed_size) + + ((sizeof (__le16) * name_len +7 ) & ~7 ) + dataruns_size + + ((flags & (ATTR_IS_COMPRESSED |ATTR_IS_SPARSE )) ? +sizeof (a->data.non_resident.compressed_size) :0 ); + err =ntfs_make_room_for_attr (ctx->mrec, (u8 *) ctx->attr, length); +if (err) { +pr_err ("Failed to make room for attribute" ); + goto put_err_out; } - ni->runlist.rl = rl; -ntfs_debug ("Allocated 0x%llx clusters." , (long long )(new_alloc_size - - allocated_size) >> vol->cluster_size_bits); -/* Find the runlist element with which the attribute extent starts. */ - ll =sle64_to_cpu (a->data.non_resident.lowest_vcn); - rl2 =ntfs_rl_find_vcn_nolock (rl, ll); -BUG_ON (!rl2); -BUG_ON (!rl2->length); -BUG_ON (rl2->lcn <LCN_HOLE ); - mp_rebuilt = false; -/* Get the size for the new mapping pairs array for this extent. */ - mp_size =ntfs_get_size_for_mapping_pairs (vol, rl2, ll,-1 ); -if (unlikely (mp_size <=0 )) { - err = mp_size; -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Cannot extend allocation of " -"inode 0x%lx, attribute type 0x%x, " -"because determining the size for the " -"mapping pairs failed with error code " -"%i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); - err = -EIO ; - goto undo_alloc; + +/* Setup record fields. */ + a->type = type; + a->length =cpu_to_le32 (length); + a->non_resident =1 ; + a->name_length = name_len; + a->name_offset =cpu_to_le16 (offsetof(struct attr_record , + data.non_resident.compressed_size) + + ((flags & (ATTR_IS_COMPRESSED |ATTR_IS_SPARSE )) ? + sizeof(a->data.non_resident.compressed_size) : 0)); + a->flags = flags; + a->instance = m->next_attr_instance; + a->data.non_resident.lowest_vcn =cpu_to_le64 (lowest_vcn); + a->data.non_resident.mapping_pairs_offset =cpu_to_le16 (length - dataruns_size); + a->data.non_resident.compression_unit = + (flags &ATTR_IS_COMPRESSED ) ?STANDARD_COMPRESSION_UNIT :0 ; +/* If @lowest_vcn == 0, than setup empty attribute. */ +if (!lowest_vcn) { + a->data.non_resident.highest_vcn =cpu_to_le64 (-1 ); + a->data.non_resident.allocated_size =0 ; + a->data.non_resident.data_size =0 ; + a->data.non_resident.initialized_size =0 ; +/* Set empty mapping pairs. */ + *((u8 *)a +le16_to_cpu (a->data.non_resident.mapping_pairs_offset)) =0 ; } -/* Extend the attribute record to fit the bigger mapping pairs array. */ - attr_len =le32_to_cpu (a->length); - err =ntfs_attr_record_resize (m, a, mp_size + -le16_to_cpu (a->data.non_resident.mapping_pairs_offset)); -if (unlikely (err)) { -BUG_ON (err != -ENOSPC ); -// TODO: Deal with this by moving this extent to a new mft -// record or by starting a new extent in a new mft record, -// possibly by extending this extent partially and filling it -// and creating a new extent for the remainder, or by making -// other attributes non-resident and/or by moving other -// attributes out of this mft record. -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Not enough space in the mft " -"record for the extended attribute " -"record. This case is not " -"implemented yet." ); - err = -EOPNOTSUPP ; - goto undo_alloc; - } - mp_rebuilt = true; -/* Generate the mapping pairs array directly into the attr record. */ - err =ntfs_mapping_pairs_build (vol, (u8 *)a + -le16_to_cpu (a->data.non_resident.mapping_pairs_offset), - mp_size, rl2, ll,-1 ,NULL ); -if (unlikely (err)) { -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Cannot extend allocation of " -"inode 0x%lx, attribute type 0x%x, " -"because building the mapping pairs " -"failed with error code %i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); - err = -EIO ; - goto undo_alloc; +if (name_len) +memcpy ((u8 *)a +le16_to_cpu (a->name_offset), + name,sizeof (__le16) * name_len); + m->next_attr_instance = +cpu_to_le16 ((le16_to_cpu (m->next_attr_instance) +1 ) &0xffff ); +if (ni->nr_extents ==-1 ) + base_ni = ni->ext.base_ntfs_ino; +else + base_ni = ni; +if (type !=AT_ATTRIBUTE_LIST &&NInoAttrList (base_ni)) { + err =ntfs_attrlist_entry_add (ni, a); +if (err) { +pr_err ("Failed add attr entry to attrlist" ); +ntfs_attr_record_resize (m, a,0 ); + goto put_err_out; + } } -/* Update the highest_vcn. */ - a->data.non_resident.highest_vcn =cpu_to_sle64 ((new_alloc_size >> - vol->cluster_size_bits) -1 ); +mark_mft_record_dirty (ni);/* -* We now have extended the allocated size of the attribute. Reflect -* this in the ntfs_inode structure and the attribute record. +* Locate offset from start of the MFT record where new attribute is +* placed. We need relookup it, because record maybe moved during +* update of attribute list. */ -if (a->data.non_resident.lowest_vcn) { -/* -* We are not in the first attribute extent, switch to it, but -* first ensure the changes will make it to disk later. -*/ -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -ntfs_attr_reinit_search_ctx (ctx); - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) - goto restore_undo_alloc; -/* @m is not used any more so no need to set it. */ - a = ctx->attr; - } -write_lock_irqsave (&ni->size_lock, flags); - ni->allocated_size = new_alloc_size; - a->data.non_resident.allocated_size =cpu_to_sle64 (new_alloc_size); -/* -* FIXME: This would fail if @ni is a directory, $MFT, or an index, -* since those can have sparse/compressed set. For example can be -* set compressed even though it is not compressed itself and in that -* case the bit means that files are to be created compressed in the -* directory... At present this is ok as this code is only called for -* regular files, and only for their $DATA attribute(s). -* FIXME: The calculation is wrong if we created a hole above. For now -* it does not matter as we never create holes. -*/ -if (NInoSparse (ni) ||NInoCompressed (ni)) { - ni->itype.compressed.size += new_alloc_size - allocated_size; - a->data.non_resident.compressed_size = -cpu_to_sle64 (ni->itype.compressed.size); - vi->i_blocks = ni->itype.compressed.size >>9 ; - }else - vi->i_blocks = new_alloc_size >>9 ; -write_unlock_irqrestore (&ni->size_lock, flags); -alloc_done: -if (new_data_size >=0 ) { -BUG_ON (new_data_size < -sle64_to_cpu (a->data.non_resident.data_size)); - a->data.non_resident.data_size =cpu_to_sle64 (new_data_size); - } -flush_done: -/* Ensure the changes make it to disk. */ -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -done: -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); -up_write (&ni->runlist.lock); -ntfs_debug ("Done, new_allocated_size 0x%llx." , - (unsigned long long )new_alloc_size); -return new_alloc_size; -restore_undo_alloc: -if (start <0 || start >= allocated_size) -ntfs_error (vol->sb,"Cannot complete extension of allocation " -"of inode 0x%lx, attribute type 0x%x, because " -"lookup of first attribute extent failed with " -"error code %i." , vi->i_ino, - (unsigned )le32_to_cpu (ni->type), err); -if (err == -ENOENT ) - err = -EIO ;ntfs_attr_reinit_search_ctx (ctx); -if (ntfs_attr_lookup (ni->type, ni->name, ni->name_len,CASE_SENSITIVE , - allocated_size >> vol->cluster_size_bits,NULL ,0 , - ctx)) { -ntfs_error (vol->sb,"Failed to find last attribute extent of " -"attribute in error code path. Run chkdsk to " -"recover." ); -write_lock_irqsave (&ni->size_lock, flags); - ni->allocated_size = new_alloc_size; -/* -* FIXME: This would fail if @ni is a directory... See above. -* FIXME: The calculation is wrong if we created a hole above. -* For now it does not matter as we never create holes. -*/ -if (NInoSparse (ni) ||NInoCompressed (ni)) { - ni->itype.compressed.size += new_alloc_size - - allocated_size; - vi->i_blocks = ni->itype.compressed.size >>9 ; - }else - vi->i_blocks = new_alloc_size >>9 ; -write_unlock_irqrestore (&ni->size_lock, flags); + err =ntfs_attr_lookup (type, name, name_len,CASE_SENSITIVE , + lowest_vcn,NULL ,0 , ctx); +if (err) { +pr_err ("%s: attribute lookup failed" , __func__);ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); -up_write (&ni->runlist.lock); -/* -* The only thing that is now wrong is the allocated size of the -* base attribute extent which chkdsk should be able to fix. -*/ -NVolSetErrors (vol);return err; + } - ctx->attr->data.non_resident.highest_vcn =cpu_to_sle64 ( - (allocated_size >> vol->cluster_size_bits) -1 ); -undo_alloc: - ll = allocated_size >> vol->cluster_size_bits; -if (ntfs_cluster_free (ni, ll,-1 , ctx) <0 ) { -ntfs_error (vol->sb,"Failed to release allocated cluster(s) " -"in error code path. Run chkdsk to recover " -"the lost cluster(s)." ); -NVolSetErrors (vol); + offset = (u8 *)ctx->attr - (u8 *)ctx->mrec; +ntfs_attr_put_search_ctx (ctx); +return offset; +put_err_out: +ntfs_attr_put_search_ctx (ctx); +return -1 ; +} + +/** +* ntfs_attr_record_rm - remove attribute extent +* @ctx: search context describing the attribute which should be removed +* +* If this function succeed, user should reinit search context if he/she wants +* use it anymore. +*/ +int ntfs_attr_record_rm (struct ntfs_attr_search_ctx *ctx) +{ +struct ntfs_inode *base_ni, *ni; +__le32 type; +int err; + +if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr) +return -EINVAL ; + +ntfs_debug ("Entering for inode 0x%llx, attr 0x%x.\n" , + (long long ) ctx->ntfs_ino->mft_no, + (unsigned int )le32_to_cpu (ctx->attr->type)); + type = ctx->attr->type; + ni = ctx->ntfs_ino; +if (ctx->base_ntfs_ino) + base_ni = ctx->base_ntfs_ino; +else + base_ni = ctx->ntfs_ino; + +/* Remove attribute itself. */ +if (ntfs_attr_record_resize (ctx->mrec, ctx->attr,0 )) { +ntfs_debug ("Couldn't remove attribute record. Bug or damaged MFT record.\n" ); +return -EIO ; } - m = ctx->mrec; - a = ctx->attr; +mark_mft_record_dirty (ni); +/* -* If the runlist truncation fails and/or the search context is no -* longer valid, we cannot resize the attribute record or build the -* mapping pairs array thus we mark the inode bad so that no access to -* the freed clusters can happen. +* Remove record from $ATTRIBUTE_LIST if present and we don't want +* delete $ATTRIBUTE_LIST itself. */ -if (ntfs_rl_truncate_nolock (vol, &ni->runlist, ll) ||IS_ERR (m)) { -ntfs_error (vol->sb,"Failed to %s in error code path. Run " -"chkdsk to recover." ,IS_ERR (m) ? -"restore attribute search context" : -"truncate attribute runlist" ); -NVolSetErrors (vol); - }else if (mp_rebuilt) { -if (ntfs_attr_record_resize (m, a, attr_len)) { -ntfs_error (vol->sb,"Failed to restore attribute " -"record in error code path. Run " -"chkdsk to recover." ); -NVolSetErrors (vol); - }else /* if (success) */ { -if (ntfs_mapping_pairs_build (vol, (u8 *)a +le16_to_cpu ( - a->data.non_resident. - mapping_pairs_offset), attr_len - -le16_to_cpu (a->data.non_resident. - mapping_pairs_offset), rl2, ll,-1 , -NULL )) { -ntfs_error (vol->sb,"Failed to restore " -"mapping pairs array in error " -"code path. Run chkdsk to " -"recover." ); -NVolSetErrors (vol); +if (NInoAttrList (base_ni) && type !=AT_ATTRIBUTE_LIST ) { + err =ntfs_attrlist_entry_rm (ctx); +if (err) { +ntfs_debug ("Couldn't delete record from $ATTRIBUTE_LIST.\n" ); +return err; + } + } + +/* Post $ATTRIBUTE_LIST delete setup. */ +if (type ==AT_ATTRIBUTE_LIST ) { +if (NInoAttrList (base_ni) && base_ni->attr_list) +ntfs_free (base_ni->attr_list); + base_ni->attr_list =NULL ; +NInoClearAttrList (base_ni); + } + +/* Free MFT record, if it doesn't contain attributes. */ +if (le32_to_cpu (ctx->mrec->bytes_in_use) - +le16_to_cpu (ctx->mrec->attrs_offset) ==8 ) { +if (ntfs_mft_record_free (ni->vol, ni)) { +ntfs_debug ("Couldn't free MFT record.\n" ); +return -EIO ; + } +/* Remove done if we freed base inode. */ +if (ni == base_ni) +return 0 ; +ntfs_inode_close (ni); + ctx->ntfs_ino = ni =NULL ; + } + +if (type ==AT_ATTRIBUTE_LIST || !NInoAttrList (base_ni)) +return 0 ; + +/* Remove attribute list if we don't need it any more. */ +if (!ntfs_attrlist_need (base_ni)) { +struct ntfs_attr na; +struct inode *attr_vi; + +ntfs_attr_reinit_search_ctx (ctx); +if (ntfs_attr_lookup (AT_ATTRIBUTE_LIST ,NULL ,0 ,CASE_SENSITIVE , +0 ,NULL ,0 , ctx)) { +ntfs_debug ("Couldn't find attribute list. Succeed anyway.\n" ); +return 0 ; + } +/* Deallocate clusters. */ +if (ctx->attr->non_resident) { +struct runlist_element *al_rl; +size_t new_rl_count; + + al_rl =ntfs_mapping_pairs_decompress (base_ni->vol, + ctx->attr,NULL , &new_rl_count); +if (IS_ERR (al_rl)) { +ntfs_debug ("Couldn't decompress attribute list runlist. Succeed anyway.\n" );
Lines of this file are not shown. View the raw message.
fs/ntfs/attrlist.c new file +285 -0
285 lines not on this page · raw message
fs/ntfs/compress.c +816 -207
1,023 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.25.1
Part of the diff is not shown here. View the raw message.
Namjae Jeon
maintainerPATCH v3 9/14 ntfs: update runlist handling and cluster allocator
In reply to Namjae JeonThis updates the implementation of runlist handling and cluster allocator.
--- fs/ntfs/bitmap.c | 201 ++++++-- fs/ntfs/lcnalloc.c | 692 +++++++++++++------------ fs/ntfs/runlist.c | 1228 ++++++++++++++++++++++++-------------------- 3 files changed, 1169 insertions(+), 952 deletions(-)
fs/ntfs/bitmap.c +157 -44
@@ -1,19 +1,111 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* bitmap.c - NTFS kernel bitmap handling. Part of the Linux-NTFS project. +* NTFS kernel bitmap handling. Part of the Linux-NTFS project. * * Copyright (c) 2004-2005 Anton Altaparmakov +* Copyright (c) 2025 LG Electronics Co., Ltd. */ -#ifdef NTFS_RW - -#include <linux/pagemap.h> +#include <linux/bitops.h> #include "bitmap.h" -#include "debug.h" #include "aops.h" #include "ntfs.h" +int ntfsp_trim_fs (struct ntfs_volume *vol,struct fstrim_range *range) +{ +size_t buf_clusters; +pgoff_t index, start_index, end_index; +struct file_ra_state *ra; +struct folio *folio; +unsigned long *bitmap; +char *kaddr; +u64 end, trimmed =0 , start_buf, end_buf, end_cluster; +u64 start_cluster =NTFS_B_TO_CLU (vol, range->start); +u32 dq =bdev_discard_granularity (vol->sb->s_bdev); +int ret =0 ; + +if (!dq) + dq = vol->cluster_size; + +if (start_cluster >= vol->nr_clusters) +return -EINVAL ; + +if (range->len == (u64)-1 ) + end_cluster = vol->nr_clusters; +else { + end_cluster =NTFS_B_TO_CLU (vol, + (range->start + range->len + vol->cluster_size -1 )); +if (end_cluster > vol->nr_clusters) + end_cluster = vol->nr_clusters; + } + + ra =kzalloc (sizeof (*ra),GFP_NOFS ); +if (!ra) +return -ENOMEM ; + + buf_clusters =PAGE_SIZE *8 ; + start_index = start_cluster >>15 ; + end_index = (end_cluster + buf_clusters -1 ) >>15 ; + +for (index = start_index; index < end_index; index++) { + folio =filemap_lock_folio (vol->lcnbmp_ino->i_mapping, index); +if (IS_ERR (folio)) { +page_cache_sync_readahead (vol->lcnbmp_ino->i_mapping, ra,NULL , + index, end_index - index); + folio =read_mapping_folio (vol->lcnbmp_ino->i_mapping, index,NULL ); +if (!IS_ERR (folio)) +folio_lock (folio); + } +if (IS_ERR (folio)) { + ret =PTR_ERR (folio); + goto out_free; + } + + kaddr =kmap_local_folio (folio,0 ); + bitmap = (unsigned long *)kaddr; + + start_buf =max_t (u64, index * buf_clusters, start_cluster); + end_buf =min_t (u64, (index +1 ) * buf_clusters, end_cluster); + + end = start_buf; +while (end < end_buf) { +u64 aligned_start, aligned_count; +u64 start =find_next_zero_bit (bitmap, end_buf - start_buf, + end - start_buf) + start_buf; +if (start >= end_buf) +break ; + + end =find_next_bit (bitmap, end_buf - start_buf, + start - start_buf) + start_buf; + + aligned_start =ALIGN (NTFS_CLU_TO_B (vol, start), dq); + aligned_count =ALIGN_DOWN (NTFS_CLU_TO_B (vol, end - start), dq); +if (aligned_count >= range->minlen) { + ret =blkdev_issue_discard (vol->sb->s_bdev, aligned_start >>9 , + aligned_count >>9 ,GFP_NOFS ); +if (ret) + goto out_unmap; + trimmed += aligned_count; + } + } + +out_unmap: +kunmap_local (kaddr); +folio_unlock (folio); +folio_put (folio); + +if (ret) + goto out_free; + } + + range->len = trimmed; + +out_free: +kfree (ra); +return ret; +} +/** * __ntfs_bitmap_set_bits_in_run - set a run of bits in a bitmap to a value * @vi: vfs inode describing the bitmap
@@ -27,8 +119,6 @@* * @is_rollback should always be 'false', it is for internal use to rollback * errors. You probably want to use ntfs_bitmap_set_bits_in_run() instead. -* -* Return 0 on success and -errno on error. */ int __ntfs_bitmap_set_bits_in_run (struct inode *vi,const s64 start_bit,const s64 count,const u8 value,const bool is_rollback)
@@ -36,19 +126,21 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,s64 cnt = count;pgoff_t index, end_index;struct address_space *mapping; -struct page *page; +struct folio *folio;u8 *kaddr;int pos, len;u8 bit; +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; -BUG_ON (!vi); -ntfs_debug ("Entering for i_ino 0x%lx, start_bit 0x%llx, count 0x%llx, " -"value %u.%s" , vi->i_ino, (unsigned long long )start_bit, +ntfs_debug ("Entering for i_ino 0x%lx, start_bit 0x%llx, count 0x%llx, value %u.%s" , + vi->i_ino, (unsigned long long )start_bit, (unsigned long long )cnt, (unsigned int )value, is_rollback ?" (rollback)" :"" ); -BUG_ON (start_bit <0 ); -BUG_ON (cnt <0 ); -BUG_ON (value >1 ); + +if (start_bit <0 || cnt <0 || value >1 ) +return -EINVAL ; +/* * Calculate the indices for the pages containing the first and last * bits, i.e. @start_bit and @start_bit + @cnt - 1, respectively.
@@ -58,14 +150,17 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,/* Get the page containing the first bit (@start_bit). */ mapping = vi->i_mapping; - page =ntfs_map_page (mapping, index); -if (IS_ERR (page)) { + folio =read_mapping_folio (mapping, index,NULL ); +if (IS_ERR (folio)) {if (!is_rollback) -ntfs_error (vi->i_sb,"Failed to map first page (error " -"%li), aborting." ,PTR_ERR (page)); -return PTR_ERR (page); +ntfs_error (vi->i_sb, +"Failed to map first page (error %li), aborting." , +PTR_ERR (folio)); +return PTR_ERR (folio); } - kaddr =page_address (page); + +folio_lock (folio); + kaddr =kmap_local_folio (folio,0 );/* Set @pos to the position of the byte containing @start_bit. */ pos = (start_bit >>3 ) & ~PAGE_MASK ;
@@ -76,6 +171,9 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,/* If the first byte is partial, modify the appropriate bits in it. */ if (bit) {u8 *byte = kaddr + pos; + +if (ni->mft_no == FILE_Bitmap) +ntfs_set_lcn_empty_bits (vol, index, value,min_t (s64,8 - bit, cnt));while ((bit &7 ) && cnt) { cnt--;if (value)
@@ -97,6 +195,8 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, len =min_t (s64, cnt >>3 ,PAGE_SIZE - pos);memset (kaddr + pos, value ?0xff :0 , len); cnt -= len <<3 ; +if (ni->mft_no == FILE_Bitmap) +ntfs_set_lcn_empty_bits (vol, index, value, len <<3 );/* Update @len to point to the first not-done byte in the page. */ if (cnt <8 )
@@ -104,16 +204,25 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,/* If we are not in the last page, deal with all subsequent pages. */ while (index < end_index) { -BUG_ON (cnt <=0 ); - -/* Update @index and get the next page. */ -flush_dcache_page (page); -set_page_dirty (page); -ntfs_unmap_page (page); - page =ntfs_map_page (mapping, ++index); -if (IS_ERR (page)) +if (cnt <=0 ) + goto rollback; + +/* Update @index and get the next folio. */ +flush_dcache_folio (folio); +folio_mark_dirty (folio); +folio_unlock (folio); +kunmap_local (kaddr); +folio_put (folio); + folio =read_mapping_folio (mapping, ++index,NULL ); +if (IS_ERR (folio)) { +ntfs_error (vi->i_sb, +"Failed to map subsequent page (error %li), aborting." , +PTR_ERR (folio)); goto rollback; - kaddr =page_address (page); + } + +folio_lock (folio); + kaddr =kmap_local_folio (folio,0 );/* * Depending on @value, modify all remaining whole bytes in the * page up to @cnt.
@@ -121,6 +230,8 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, len =min_t (s64, cnt >>3 ,PAGE_SIZE );memset (kaddr, value ?0xff :0 , len); cnt -= len <<3 ; +if (ni->mft_no == FILE_Bitmap) +ntfs_set_lcn_empty_bits (vol, index, value, len <<3 ); }/* * The currently mapped page is the last one. If the last byte is
@@ -130,10 +241,12 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,if (cnt) {u8 *byte; -BUG_ON (cnt >7 ); +WARN_ON (cnt >7 ); bit = cnt; byte = kaddr + len; +if (ni->mft_no == FILE_Bitmap) +ntfs_set_lcn_empty_bits (vol, index, value, bit);while (bit--) {if (value) *byte |=1 << bit;
@@ -142,10 +255,12 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, } } done: -/* We are done. Unmap the page and return success. */ -flush_dcache_page (page); -set_page_dirty (page); -ntfs_unmap_page (page); +/* We are done. Unmap the folio and return success. */ +flush_dcache_folio (folio); +folio_mark_dirty (folio); +folio_unlock (folio); +kunmap_local (kaddr); +folio_put (folio);ntfs_debug ("Done." );return 0 ; rollback:
@@ -155,7 +270,7 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,* - @count - @cnt is the number of bits that have been modified */ if (is_rollback) -return PTR_ERR (page); +return PTR_ERR (folio);if (count != cnt) pos =__ntfs_bitmap_set_bits_in_run (vi, start_bit, count - cnt, value ?0 :1 , true);
@@ -163,17 +278,15 @@ int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit, pos =0 ;if (!pos) {/* Rollback was successful. */ -ntfs_error (vi->i_sb,"Failed to map subsequent page (error " -"%li), aborting." ,PTR_ERR (page)); +ntfs_error (vi->i_sb, +"Failed to map subsequent page (error %li), aborting." , +PTR_ERR (folio)); }else {/* Rollback failed. */ -ntfs_error (vi->i_sb,"Failed to map subsequent page (error " -"%li) and rollback failed (error %i). " -"Aborting and leaving inconsistent metadata. " -"Unmount and run chkdsk." ,PTR_ERR (page), pos); +ntfs_error (vi->i_sb, +"Failed to map subsequent page (error %li) and rollback failed (error %i). Aborting and leaving inconsistent metadata. Unmount and run chkdsk." , +PTR_ERR (folio), pos);NVolSetErrors (NTFS_SB (vi->i_sb)); } - return PTR_ERR(page); +return PTR_ERR (folio); } - -#endif /* NTFS_RW */
fs/ntfs/lcnalloc.c +353 -339
1,084 lines not on this page · raw message
fs/ntfs/runlist.c +659 -569
1,621 lines not on this page · raw message
The rest of this diff is not shown. View the raw message.
Signature · 1 line
2.25.1
Part of the diff is not shown here. View the raw message.
Namjae Jeon
maintainerPATCH v3 10/14 ntfs: add reparse and ea operations
In reply to Namjae JeonThis adds the implementation of reparse and ea operations
--- fs/ntfs/ea.c | 933 ++++++++++++++++++++++++++++++++++++++++++++++ fs/ntfs/reparse.c | 550 +++++++++++++++++++++++++++ 2 files changed, 1483 insertions(+) create mode 100644 fs/ntfs/ea.c create mode 100644 fs/ntfs/reparse.c
fs/ntfs/ea.c new file +933 -0
@@ -0,0 +1,933 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/** +* Pocessing of EA's +* +* Part of this file is based on code from the NTFS-3G project. +* +* Copyright (c) 2014-2021 Jean-Pierre Andre +* Copyright (c) 2025 LG Electronics Co., Ltd. +*/ + +#include <linux/fs.h> +#include <linux/posix_acl.h> +#include <linux/posix_acl_xattr.h> +#include <linux/xattr.h> + +#include "layout.h" +#include "attrib.h" +#include "index.h" +#include "dir.h" +#include "ea.h" +#include "malloc.h" + +static int ntfs_write_ea (struct ntfs_inode *ni,int type,char *value,s64 ea_off, +s64 ea_size,bool need_truncate) +{ +struct inode *ea_vi; +int err =0 ; +s64 written; + + ea_vi =ntfs_attr_iget (VFS_I (ni), type,AT_UNNAMED ,0 ); +if (IS_ERR (ea_vi)) +return PTR_ERR (ea_vi); + + written =ntfs_inode_attr_pwrite (ea_vi, ea_off, ea_size, value, false); +if (written != ea_size) + err = -EIO ; +else { +struct ntfs_inode *ea_ni =NTFS_I (ea_vi); + +if (need_truncate && ea_ni->data_size > ea_off + ea_size) +ntfs_attr_truncate (ea_ni, ea_off + ea_size); +mark_mft_record_dirty (ni); + } + +iput (ea_vi); +return err; +} + +static int ntfs_ea_lookup (char *ea_buf,s64 ea_buf_size,const char *name, +int name_len,s64 *ea_offset,s64 *ea_size) +{ +const struct ea_attr *p_ea; +s64 offset; +unsigned int next; + +if (ea_buf_size <sizeof (struct ea_attr )) + goto out; + + offset =0 ; +do { + p_ea = (const struct ea_attr *)&ea_buf[offset]; + next =le32_to_cpu (p_ea->next_entry_offset); + +if (offset + next > ea_buf_size || + ((1 + p_ea->ea_name_length) > (ea_buf_size - offset))) +break ; + +if (p_ea->ea_name_length == name_len && + !memcmp (p_ea->ea_name, name, name_len)) { + *ea_offset = offset; +if (next) + *ea_size = next; +else { +unsigned int ea_len =1 + p_ea->ea_name_length + +le16_to_cpu (p_ea->ea_value_length); + +if ((ea_buf_size - offset) < ea_len) + goto out; + + *ea_size =ALIGN (struct_size (p_ea, ea_name, +1 + p_ea->ea_name_length + +le16_to_cpu (p_ea->ea_value_length)),4 ); + } + +if (ea_buf_size < *ea_offset + *ea_size) + goto out; + +return 0 ; + } + offset += next; + }while (next >0 && offset < ea_buf_size && +sizeof (struct ea_attr ) < (ea_buf_size - offset)); + +out: +return -ENOENT ; +} + +/* +* Return the existing EA +* +* The EA_INFORMATION is not examined and the consistency of the +* existing EA is not checked. +* +* If successful, the full attribute is returned unchanged +* and its size is returned. +* If the designated buffer is too small, the needed size is +* returned, and the buffer is left unchanged. +* If there is an error, a negative value is returned and errno +* is set according to the error. +*/ +static int ntfs_get_ea (struct inode *inode,const char *name,size_t name_len, +void *buffer,size_t size) +{ +struct ntfs_inode *ni =NTFS_I (inode); +const struct ea_attr *p_ea; +char *ea_buf; +s64 ea_off, ea_size, all_ea_size, ea_info_size; +int err; +unsigned short int ea_value_len, ea_info_qlen; +struct ea_information *p_ea_info; + +if (!NInoHasEA (ni)) +return -ENODATA ; + + p_ea_info =ntfs_attr_readall (ni,AT_EA_INFORMATION ,NULL ,0 , + &ea_info_size); +if (!p_ea_info || ea_info_size !=sizeof (struct ea_information )) { +ntfs_free (p_ea_info); +return -ENODATA ; + } + + ea_info_qlen =le16_to_cpu (p_ea_info->ea_query_length); +ntfs_free (p_ea_info); + + ea_buf =ntfs_attr_readall (ni,AT_EA ,NULL ,0 , &all_ea_size); +if (!ea_buf) +return -ENODATA ; + + err =ntfs_ea_lookup (ea_buf, ea_info_qlen, name, name_len, &ea_off, + &ea_size); +if (!err) { + p_ea = (struct ea_attr *)&ea_buf[ea_off]; + ea_value_len =le16_to_cpu (p_ea->ea_value_length); +if (!buffer) { +ntfs_free (ea_buf); +return ea_value_len; + } + +if (ea_value_len > size) { + err = -ERANGE ; + goto free_ea_buf; + } + +memcpy (buffer, &p_ea->ea_name[p_ea->ea_name_length +1 ], + ea_value_len); +ntfs_free (ea_buf); +return ea_value_len; + } + + err = -ENODATA ; +free_ea_buf: +ntfs_free (ea_buf); +return err; +} + +static inline int ea_packed_size (const struct ea_attr *p_ea) +{ +/* +* 4 bytes for header (flags and lengths) + name length + 1 + +* value length. +*/ +return 5 + p_ea->ea_name_length +le16_to_cpu (p_ea->ea_value_length); +} + +/* +* Set a new EA, and set EA_INFORMATION accordingly +* +* This is roughly the same as ZwSetEaFile() on Windows, however +* the "offset to next" of the last EA should not be cleared. +* +* Consistency of the new EA is first checked. +* +* EA_INFORMATION is set first, and it is restored to its former +* state if setting EA fails. +*/ +static int ntfs_set_ea (struct inode *inode,const char *name,size_t name_len, +const void *value,size_t val_size,int flags, +__le16 *packed_ea_size) +{ +struct ntfs_inode *ni =NTFS_I (inode); +struct ea_information *p_ea_info =NULL ; +int ea_packed, err =0 ; +struct ea_attr *p_ea; +unsigned short int ea_info_qsize =0 ; +char *ea_buf =NULL ; +size_t new_ea_size =ALIGN (struct_size (p_ea, ea_name,1 + name_len + val_size),4 ); +s64 ea_off, ea_info_size, all_ea_size, ea_size; + +if (name_len >255 ) +return -ENAMETOOLONG ; + +if (ntfs_attr_exist (ni,AT_EA_INFORMATION ,AT_UNNAMED ,0 )) { + p_ea_info =ntfs_attr_readall (ni,AT_EA_INFORMATION ,NULL ,0 , + &ea_info_size); +if (!p_ea_info || ea_info_size !=sizeof (struct ea_information )) + goto out; + + ea_buf =ntfs_attr_readall (ni,AT_EA ,NULL ,0 , &all_ea_size); +if (!ea_buf) { + ea_info_qsize =0 ; +ntfs_free (p_ea_info); + goto create_ea_info; + } + + ea_info_qsize =le32_to_cpu (p_ea_info->ea_query_length); + }else { +create_ea_info: + p_ea_info =ntfs_malloc_nofs (sizeof (struct ea_information )); +if (!p_ea_info) +return -ENOMEM ; + + ea_info_qsize =0 ; + err =ntfs_attr_add (ni,AT_EA_INFORMATION ,AT_UNNAMED ,0 , + (char *)p_ea_info,sizeof (struct ea_information )); +if (err) + goto out; + +if (ntfs_attr_exist (ni,AT_EA ,AT_UNNAMED ,0 )) { + err =ntfs_attr_remove (ni,AT_EA ,AT_UNNAMED ,0 ); +if (err) + goto out; + } + + goto alloc_new_ea; + } + +if (ea_info_qsize > all_ea_size) { + err = -EIO ; + goto out; + } + + err =ntfs_ea_lookup (ea_buf, ea_info_qsize, name, name_len, &ea_off, + &ea_size); +if (ea_info_qsize && !err) { +if (flags &XATTR_CREATE ) { + err = -EEXIST ; + goto out; + } + + p_ea = (struct ea_attr *)(ea_buf + ea_off); + +if (val_size && +le16_to_cpu (p_ea->ea_value_length) == val_size && + !memcmp (p_ea->ea_name + p_ea->ea_name_length +1 , value, + val_size)) + goto out; + +le16_add_cpu (&p_ea_info->ea_length,0 -ea_packed_size (p_ea)); + +if (p_ea->flags &NEED_EA ) +le16_add_cpu (&p_ea_info->need_ea_count,-1 ); + +memmove ((char *)p_ea, (char *)p_ea + ea_size, ea_info_qsize - (ea_off + ea_size)); + ea_info_qsize -= ea_size; + p_ea_info->ea_query_length =cpu_to_le16 (ea_info_qsize); + + err =ntfs_write_ea (ni,AT_EA_INFORMATION , (char *)p_ea_info,0 , +sizeof (struct ea_information ), false); +if (err) + goto out; + + err =ntfs_write_ea (ni,AT_EA , ea_buf,0 , ea_info_qsize, true); +if (err) + goto out; + +if ((flags &XATTR_REPLACE ) && !val_size) { +/* Remove xattr. */ + goto out; + } + }else { +if (flags &XATTR_REPLACE ) { + err = -ENODATA ; + goto out; + } + } +ntfs_free (ea_buf); + +alloc_new_ea: + ea_buf =kzalloc (new_ea_size,GFP_NOFS ); +if (!ea_buf) { + err = -ENOMEM ; + goto out; + } + +/* +* EA and REPARSE_POINT compatibility not checked any more, +* required by Windows 10, but having both may lead to +* problems with earlier versions. +*/ + p_ea = (struct ea_attr *)ea_buf; +memcpy (p_ea->ea_name, name, name_len); + p_ea->ea_name_length = name_len; + p_ea->ea_name[name_len] =0 ; +memcpy (p_ea->ea_name + name_len +1 , value, val_size); + p_ea->ea_value_length =cpu_to_le16 (val_size); + p_ea->next_entry_offset =cpu_to_le32 (new_ea_size); + + ea_packed =le16_to_cpu (p_ea_info->ea_length) +ea_packed_size (p_ea); + p_ea_info->ea_length =cpu_to_le16 (ea_packed); + p_ea_info->ea_query_length =cpu_to_le32 (ea_info_qsize + new_ea_size); + +if (ea_packed >0xffff || +ntfs_attr_size_bounds_check (ni->vol,AT_EA , new_ea_size)) { + err = -EFBIG ; + goto out; + } + +/* +* no EA or EA_INFORMATION : add them +*/ +if (!ntfs_attr_exist (ni,AT_EA ,AT_UNNAMED ,0 )) { + err =ntfs_attr_add (ni,AT_EA ,AT_UNNAMED ,0 , (char *)p_ea, + new_ea_size); +if (err) + goto out; + }else { + err =ntfs_write_ea (ni,AT_EA , (char *)p_ea, ea_info_qsize, + new_ea_size, false); +if (err) + goto out; + } + + err =ntfs_write_ea (ni,AT_EA_INFORMATION , (char *)p_ea_info,0 , +sizeof (struct ea_information ), false); +if (err) + goto out; + +if (packed_ea_size) + *packed_ea_size = p_ea_info->ea_length; +mark_mft_record_dirty (ni); +out: +if (ea_info_qsize >0 ) +NInoSetHasEA (ni); +else +NInoClearHasEA (ni); + +ntfs_free (ea_buf); +ntfs_free (p_ea_info); + +return err; +} + +/* +* Check for the presence of an EA "$LXDEV" (used by WSL) +* and return its value as a device address +*/ +int ntfs_ea_get_wsl_inode (struct inode *inode,dev_t *rdevp,unsigned int flags) +{ +int err; +__le32 v; + +if (!(flags &NTFS_VOL_UID )) { +/* Load uid to lxuid EA */ + err =ntfs_get_ea (inode,"$LXUID" ,sizeof ("$LXUID" ) -1 , &v, +sizeof (v)); +if (err <0 ) +return err; +i_uid_write (inode,le32_to_cpu (v)); + } + +if (!(flags &NTFS_VOL_UID )) { +/* Load gid to lxgid EA */ + err =ntfs_get_ea (inode,"$LXGID" ,sizeof ("$LXGID" ) -1 , &v, +sizeof (v)); +if (err <0 ) +return err; +i_gid_write (inode,le32_to_cpu (v)); + } + +/* Load mode to lxmod EA */ + err =ntfs_get_ea (inode,"$LXMOD" ,sizeof ("$LXMOD" ) -1 , &v,sizeof (v)); +if (err >0 ) { + inode->i_mode =le32_to_cpu (v); + }else { +/* Everyone gets all permissions. */ + inode->i_mode |=0777 ; + } + +/* Load mode to lxdev EA */ + err =ntfs_get_ea (inode,"$LXDEV" ,sizeof ("$LXDEV" ) -1 , &v,sizeof (v)); +if (err >0 ) + *rdevp =le32_to_cpu (v); + err =0 ; + +return err; +} + +int ntfs_ea_set_wsl_inode (struct inode *inode,dev_t rdev,__le16 *ea_size, +unsigned int flags) +{ +__le32 v; +int err; + +if (flags &NTFS_EA_UID ) { +/* Store uid to lxuid EA */ + v =cpu_to_le32 (i_uid_read (inode)); + err =ntfs_set_ea (inode,"$LXUID" ,sizeof ("$LXUID" ) -1 , &v, +sizeof (v),0 , ea_size); +if (err) +return err; + } + +if (flags &NTFS_EA_GID ) { +/* Store gid to lxgid EA */ + v =cpu_to_le32 (i_gid_read (inode)); + err =ntfs_set_ea (inode,"$LXGID" ,sizeof ("$LXGID" ) -1 , &v, +sizeof (v),0 , ea_size); +if (err) +return err; + } + +if (flags &NTFS_EA_MODE ) { +/* Store mode to lxmod EA */ + v =cpu_to_le32 (inode->i_mode); + err =ntfs_set_ea (inode,"$LXMOD" ,sizeof ("$LXMOD" ) -1 , &v, +sizeof (v),0 , ea_size); +if (err) +return err; + } + +if (rdev) { + v =cpu_to_le32 (rdev); + err =ntfs_set_ea (inode,"$LXDEV" ,sizeof ("$LXDEV" ) -1 , &v,sizeof (v), +0 , ea_size); + } + +return err; +} + +ssize_t ntfsp_listxattr (struct dentry *dentry,char *buffer,size_t size) +{ +struct inode *inode =d_inode (dentry); +struct ntfs_inode *ni =NTFS_I (inode); +const struct ea_attr *p_ea; +s64 offset, ea_buf_size, ea_info_size; +int next, err =0 , ea_size; +unsigned int ea_info_qsize; +char *ea_buf =NULL ; +ssize_t ret =0 ; +struct ea_information *ea_info; + +if (!NInoHasEA (ni)) +return 0 ; + +mutex_lock (&NTFS_I (inode)->mrec_lock); + ea_info =ntfs_attr_readall (ni,AT_EA_INFORMATION ,NULL ,0 , + &ea_info_size); +if (!ea_info || ea_info_size !=sizeof (struct ea_information )) + goto out; + + ea_info_qsize =le16_to_cpu (ea_info->ea_query_length); + + ea_buf =ntfs_attr_readall (ni,AT_EA ,NULL ,0 , &ea_buf_size); +if (!ea_buf) + goto out; + +if (ea_info_qsize > ea_buf_size) + goto out; + +if (ea_buf_size <sizeof (struct ea_attr )) + goto out; + + offset =0 ; +do { + p_ea = (const struct ea_attr *)&ea_buf[offset]; + next =le32_to_cpu (p_ea->next_entry_offset); +if (next) + ea_size = next; +else + ea_size =ALIGN (struct_size (p_ea, ea_name, +1 + p_ea->ea_name_length + +le16_to_cpu (p_ea->ea_value_length)), +4 ); +if (buffer) { +if (offset + ea_size > ea_info_qsize) +break ; + +if (ret + p_ea->ea_name_length +1 > size) { + err = -ERANGE ; + goto out; + } + +if (p_ea->ea_name_length +1 > (ea_info_qsize - offset)) +break ; + +memcpy (buffer + ret, p_ea->ea_name, p_ea->ea_name_length); + buffer[ret + p_ea->ea_name_length] =0 ; + } + + ret += p_ea->ea_name_length +1 ; + offset += ea_size; + }while (next >0 && offset < ea_info_qsize && +sizeof (struct ea_attr ) < (ea_info_qsize - offset)); + +out: +mutex_unlock (&NTFS_I (inode)->mrec_lock); +ntfs_free (ea_info); +ntfs_free (ea_buf); + +return err ? err : ret; +} + +// clang-format off +#define SYSTEM_DOS_ATTRIB "system.dos_attrib" +#define SYSTEM_NTFS_ATTRIB "system.ntfs_attrib" +#define SYSTEM_NTFS_ATTRIB_BE "system.ntfs_attrib_be" +// clang-format on + +static int ntfs_getxattr (const struct xattr_handler *handler, +struct dentry *unused,struct inode *inode,const char *name, +void *buffer,size_t size) +{ +struct ntfs_inode *ni =NTFS_I (inode); +int err; + +if (NVolShutdown (ni->vol)) +return -EIO ; + +if (!strcmp (name,SYSTEM_DOS_ATTRIB )) { +if (!buffer) { + err =sizeof (u8); + }else if (size <sizeof (u8)) { + err = -ENODATA ; + }else { + err =sizeof (u8); + *(u8 *)buffer = ni->flags; + } + goto out; + } + +if (!strcmp (name,SYSTEM_NTFS_ATTRIB ) || + !strcmp (name,SYSTEM_NTFS_ATTRIB_BE )) { +if (!buffer) { + err =sizeof (u32); + }else if (size <sizeof (u32)) { + err = -ENODATA ; + }else { + err =sizeof (u32); + *(u32 *)buffer =le32_to_cpu (ni->flags); +if (!strcmp (name,SYSTEM_NTFS_ATTRIB_BE )) + *(__be32 *)buffer =cpu_to_be32 (*(u32 *)buffer); + } + goto out; + } + +mutex_lock (&ni->mrec_lock); + err =ntfs_get_ea (inode, name,strlen (name), buffer, size); +mutex_unlock (&ni->mrec_lock); + +out: +return err; +} + +static int ntfs_new_attr_flags (struct ntfs_inode *ni,__le32 fattr) +{ +struct ntfs_attr_search_ctx *ctx; +struct mft_record *m; +struct attr_record *a; +__le16 new_aflags; +int mp_size, mp_ofs, name_ofs, arec_size, err; + + m =map_mft_record (ni); +if (IS_ERR (m)) +return PTR_ERR (m); + + ctx =ntfs_attr_get_search_ctx (ni, m); +if (!ctx) { + err = -ENOMEM ; + goto err_out; + } + + err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, +CASE_SENSITIVE ,0 ,NULL ,0 , ctx); +if (err) { + err = -EINVAL ; + goto err_out; + } + + a = ctx->attr; + new_aflags = ctx->attr->flags; + +if (fattr &FILE_ATTR_SPARSE_FILE ) + new_aflags |=ATTR_IS_SPARSE ; +else + new_aflags &= ~ATTR_IS_SPARSE ; + +if (fattr &FILE_ATTR_COMPRESSED ) + new_aflags |=ATTR_IS_COMPRESSED ; +else + new_aflags &= ~ATTR_IS_COMPRESSED ; + +if (new_aflags == a->flags) +return 0 ; + +if ((new_aflags & (ATTR_IS_SPARSE |ATTR_IS_COMPRESSED )) == + (ATTR_IS_SPARSE |ATTR_IS_COMPRESSED )) { +pr_err ("file can't be sparsed and compressed\n" ); + err = -EOPNOTSUPP ; + goto err_out; + } + +if (!a->non_resident) + goto out; + +if (a->data.non_resident.data_size) { +pr_err ("Can't change sparsed/compressed for non-empty file" ); + err = -EOPNOTSUPP ; + goto err_out; + } + +if (new_aflags & (ATTR_IS_SPARSE |ATTR_IS_COMPRESSED )) + name_ofs = (offsetof(struct attr_record , + data.non_resident.compressed_size) + + sizeof(a->data.non_resident.compressed_size) + 7) & ~7; +else + name_ofs = (offsetof(struct attr_record , + data.non_resident.compressed_size) + 7) & ~7; + + mp_size =ntfs_get_size_for_mapping_pairs (ni->vol, ni->runlist.rl,0 ,-1 ,-1 ); +if (unlikely (mp_size <0 )) { + err = mp_size; +ntfs_debug ("Failed to get size for mapping pairs array, error code %i.\n" , err); + goto err_out; + } + + mp_ofs = (name_ofs + a->name_length *sizeof (__le16) +7 ) & ~7 ; + arec_size = (mp_ofs + mp_size +7 ) & ~7 ; + + err =ntfs_attr_record_resize (m, a, arec_size); +if (unlikely (err)) + goto err_out; + +if (new_aflags & (ATTR_IS_SPARSE |ATTR_IS_COMPRESSED )) { + a->data.non_resident.compression_unit =0 ; +if (new_aflags &ATTR_IS_COMPRESSED || ni->vol->major_ver <3 ) + a->data.non_resident.compression_unit =4 ; + a->data.non_resident.compressed_size =0 ; + ni->itype.compressed.size =0 ; +if (a->data.non_resident.compression_unit) { + ni->itype.compressed.block_size =1U << + (a->data.non_resident.compression_unit + + ni->vol->cluster_size_bits); + ni->itype.compressed.block_size_bits = +ffs (ni->itype.compressed.block_size) - +1 ; + ni->itype.compressed.block_clusters =1U << + a->data.non_resident.compression_unit; + }else { + ni->itype.compressed.block_size =0 ; + ni->itype.compressed.block_size_bits =0 ; + ni->itype.compressed.block_clusters =0 ; + } + +if (new_aflags &ATTR_IS_SPARSE ) { +NInoSetSparse (ni); + ni->flags |=FILE_ATTR_SPARSE_FILE ; + } + +if (new_aflags &ATTR_IS_COMPRESSED ) { +NInoSetCompressed (ni); + ni->flags |=FILE_ATTR_COMPRESSED ; + } + }else { + ni->flags &= ~(FILE_ATTR_SPARSE_FILE |FILE_ATTR_COMPRESSED ); + a->data.non_resident.compression_unit =0 ; +NInoClearSparse (ni); +NInoClearCompressed (ni); + } + + a->name_offset =cpu_to_le16 (name_ofs); + a->data.non_resident.mapping_pairs_offset =cpu_to_le16 (mp_ofs); + +out: + a->flags = new_aflags; +mark_mft_record_dirty (ctx->ntfs_ino); +err_out: +ntfs_attr_put_search_ctx (ctx); +unmap_mft_record (ni); +return err; +} + +static int ntfs_setxattr (const struct xattr_handler *handler, +struct mnt_idmap *idmap,struct dentry *unused, +struct inode *inode,const char *name,const void *value, +size_t size,int flags) +{ +struct ntfs_inode *ni =NTFS_I (inode); +int err; +__le32 fattr; + +if (NVolShutdown (ni->vol)) +return -EIO ; + +if (!strcmp (name,SYSTEM_DOS_ATTRIB )) { +if (sizeof (u8) != size) { + err = -EINVAL ; + goto out; + } + fattr =cpu_to_le32 (*(u8 *)value); + goto set_fattr; + } + +if (!strcmp (name,SYSTEM_NTFS_ATTRIB ) || + !strcmp (name,SYSTEM_NTFS_ATTRIB_BE )) { +if (size !=sizeof (u32)) { + err = -EINVAL ; + goto out; + } +if (!strcmp (name,SYSTEM_NTFS_ATTRIB_BE )) + fattr =cpu_to_le32 (be32_to_cpu (*(__be32 *)value)); +else + fattr =cpu_to_le32 (*(u32 *)value); + +if (S_ISREG (inode->i_mode)) { +mutex_lock (&ni->mrec_lock); + err =ntfs_new_attr_flags (ni, fattr); +mutex_unlock (&ni->mrec_lock); +if (err) + goto out; + } + +set_fattr: +if (S_ISDIR (inode->i_mode)) + fattr |=FILE_ATTR_DIRECTORY ; +else + fattr &= ~FILE_ATTR_DIRECTORY ; + +if (ni->flags != fattr) { + ni->flags = fattr; +if (fattr &FILE_ATTR_READONLY ) + inode->i_mode &= ~0222 ; +else + inode->i_mode |=0222 ; +NInoSetFileNameDirty (ni); +mark_inode_dirty (inode); + } + err =0 ; + goto out; + } + +mutex_lock (&ni->mrec_lock); + err =ntfs_set_ea (inode, name,strlen (name), value, size, flags,NULL ); +mutex_unlock (&ni->mrec_lock); + +out: +inode_set_ctime_current (inode); +mark_inode_dirty (inode); +return err; +} + +static bool ntfs_xattr_user_list (struct dentry *dentry) +{ +return true; +} + +// clang-format off +static const struct xattr_handler ntfs_other_xattr_handler = { + .prefix ="" , + .get = ntfs_getxattr, + .set = ntfs_setxattr, + .list = ntfs_xattr_user_list, +}; + +const struct xattr_handler *const ntfsp_xattr_handlers[] = { + &ntfs_other_xattr_handler, +NULL , +}; +// clang-format on + +#ifdef CONFIG_NTFS_FS_POSIX_ACL +struct posix_acl *ntfsp_get_acl (struct mnt_idmap *idmap,struct dentry *dentry, +int type) +{ +struct inode *inode =d_inode (dentry); +struct ntfs_inode *ni =NTFS_I (inode); +const char *name; +size_t name_len; +struct posix_acl *acl; +int err; +void *buf; + +/* Allocate PATH_MAX bytes. */ + buf =__getname (); +if (!buf) +return ERR_PTR (-ENOMEM ); + +/* Possible values of 'type' was already checked above. */ +if (type ==ACL_TYPE_ACCESS ) { + name =XATTR_NAME_POSIX_ACL_ACCESS ; + name_len =sizeof (XATTR_NAME_POSIX_ACL_ACCESS ) -1 ; + }else { + name =XATTR_NAME_POSIX_ACL_DEFAULT ; + name_len =sizeof (XATTR_NAME_POSIX_ACL_DEFAULT ) -1 ; + } + +mutex_lock (&ni->mrec_lock); + err =ntfs_get_ea (inode, name, name_len, buf,PATH_MAX ); +mutex_unlock (&ni->mrec_lock); + +/* Translate extended attribute to acl. */ +if (err >=0 ) + acl =posix_acl_from_xattr (&init_user_ns, buf, err); +else if (err == -ENODATA ) + acl =NULL ; +else + acl =ERR_PTR (err); + +if (!IS_ERR (acl)) +set_cached_acl (inode, type, acl); + +__putname (buf); + +return acl; +} + +static noinline int ntfs_set_acl_ex(struct mnt_idmap *idmap, +struct inode *inode,struct posix_acl *acl, +int type,bool init_acl) +{ +const char *name; +size_t size, name_len; +void *value; +int err; +int flags; +umode_t mode; + +if (S_ISLNK (inode->i_mode)) +return -EOPNOTSUPP ; + + mode = inode->i_mode; +switch (type) { +case ACL_TYPE_ACCESS : +/* Do not change i_mode if we are in init_acl */ +if (acl && !init_acl) { + err =posix_acl_update_mode (idmap, inode, &mode, &acl); +if (err) +return err; + } + name =XATTR_NAME_POSIX_ACL_ACCESS ; + name_len =sizeof (XATTR_NAME_POSIX_ACL_ACCESS ) -1 ; +break ; + +case ACL_TYPE_DEFAULT : +if (!S_ISDIR (inode->i_mode)) +return acl ? -EACCES :0 ; + name =XATTR_NAME_POSIX_ACL_DEFAULT ; + name_len =sizeof (XATTR_NAME_POSIX_ACL_DEFAULT ) -1 ; +break ; + +default : +return -EINVAL ; + } + +if (!acl) { +/* Remove xattr if it can be presented via mode. */ + size =0 ; + value =NULL ; + flags =XATTR_REPLACE ; + }else { + size =posix_acl_xattr_size (acl->a_count); + value =kmalloc (size,GFP_NOFS ); +if (!value) +return -ENOMEM ; + err =posix_acl_to_xattr (&init_user_ns, acl, value, size); +if (err <0 ) + goto out; + flags =0 ; + } + +mutex_lock (&NTFS_I (inode)->mrec_lock); + err =ntfs_set_ea (inode, name, name_len, value, size, flags,NULL ); +mutex_unlock (&NTFS_I (inode)->mrec_lock); +if (err == -ENODATA && !size) + err =0 ;/* Removing non existed xattr. */ +if (!err) { +set_cached_acl (inode, type, acl); + inode->i_mode = mode; +inode_set_ctime_current (inode); +mark_inode_dirty (inode); + } + +out: +kfree (value); + +return err; +} + +int ntfsp_set_acl (struct mnt_idmap *idmap,struct dentry *dentry, +struct posix_acl *acl,int type) +{ +return ntfs_set_acl_ex (idmap,d_inode (dentry), acl, type, false); +} + +int ntfsp_init_acl (struct mnt_idmap *idmap,struct inode *inode, +struct inode *dir) +{ +struct posix_acl *default_acl, *acl; +int err; + + err =posix_acl_create (dir, &inode->i_mode, &default_acl, &acl); +if (err) +return err; + +if (default_acl) { + err =ntfs_set_acl_ex (idmap, inode, default_acl, +ACL_TYPE_DEFAULT , true); +posix_acl_release (default_acl); + }else { + inode->i_default_acl =NULL ; + } + +if (acl) { +if (!err) + err =ntfs_set_acl_ex (idmap, inode, acl, +ACL_TYPE_ACCESS , true); +posix_acl_release (acl); + }else { + inode->i_acl =NULL ; + } + +return err; +} +#endif
fs/ntfs/reparse.c new file +550 -0
550 lines not on this page · raw message
Signature · 1 line
2.25.1
Namjae Jeon
maintainerPATCH v3 11/14 ntfs: update misc operations
In reply to Namjae JeonThis updates the implementation of misc operations.
--- fs/ntfs/collate.c | 106 +++++++++--- fs/ntfs/debug.c | 44 +++-- fs/ntfs/logfile.c | 402 +++++++++++++++++++--------------------------- fs/ntfs/quota.c | 36 ++--- fs/ntfs/sysctl.c | 12 +- fs/ntfs/unistr.c | 243 +++++++++++++++++++--------- fs/ntfs/upcase.c | 12 +- 7 files changed, 471 insertions(+), 384 deletions(-)
fs/ntfs/collate.c +87 -19
@@ -1,15 +1,20 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* collate.c - NTFS kernel collation handling. Part of the Linux-NTFS project. +* NTFS kernel collation handling. Part of the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov +* +* Part of this file is based on code from the NTFS-3G project. +* and is copyrighted by the respective authors below: +* Copyright (c) 2004 Anton Altaparmakov +* Copyright (c) 2005 Yura Pakhuchiy */ #include "collate.h" #include "debug.h" #include "ntfs.h" -static int ntfs_collate_binary (ntfs_volume *vol, +static int ntfs_collate_binary (struct ntfs_volume *vol,const void *data1,const int data1_len,const void *data2,const int data2_len) {
@@ -27,7 +32,7 @@ static int ntfs_collate_binary(ntfs_volume *vol,return rc; } -static int ntfs_collate_ntofs_ulong (ntfs_volume *vol, +static int ntfs_collate_ntofs_ulong (struct ntfs_volume *vol,const void *data1,const int data1_len,const void *data2,const int data2_len) {
@@ -35,9 +40,10 @@ static int ntfs_collate_ntofs_ulong(ntfs_volume *vol,u32 d1, d2;ntfs_debug ("Entering." ); -// FIXME: We don't really want to bug here. -BUG_ON (data1_len != data2_len); -BUG_ON (data1_len !=4 ); + +if (data1_len != data2_len || data1_len !=4 ) +return -EINVAL ; + d1 =le32_to_cpup (data1); d2 =le32_to_cpup (data2);if (d1 < d2)
@@ -52,12 +58,72 @@ static int ntfs_collate_ntofs_ulong(ntfs_volume *vol,return rc; } -typedef int (*ntfs_collate_func_t )(ntfs_volume *,const void *,const int , +/** +* ntfs_collate_ntofs_ulongs - Which of two le32 arrays should be listed first +* +* Returns: -1, 0 or 1 depending of how the arrays compare +*/ +static int ntfs_collate_ntofs_ulongs (struct ntfs_volume *vol, +const void *data1,const int data1_len, +const void *data2,const int data2_len) +{ +int rc; +int len; +const __le32 *p1, *p2; +u32 d1, d2; + +ntfs_debug ("Entering." ); +if ((data1_len != data2_len) || (data1_len <=0 ) || (data1_len &3 )) { +ntfs_error (vol->sb,"data1_len or data2_len not valid\n" ); +return -1 ; + } + + p1 = (const __le32 *)data1; + p2 = (const __le32 *)data2; + len = data1_len; +do { + d1 =le32_to_cpup (p1); + p1++; + d2 =le32_to_cpup (p2); + p2++; + }while ((d1 == d2) && ((len -=4 ) >0 )); +if (d1 < d2) + rc =-1 ; +else { +if (d1 == d2) + rc =0 ; +else + rc =1 ; + } +ntfs_debug ("Done, returning %i." , rc); +return rc; +} + +/** +* ntfs_collate_file_name - Which of two filenames should be listed first +*/ +static int ntfs_collate_file_name (struct ntfs_volume *vol, +const void *data1,const int __always_unused data1_len, +const void *data2,const int __always_unused data2_len) +{ +int rc; + +ntfs_debug ("Entering.\n" ); + rc =ntfs_file_compare_values (data1, data2,-2 , +IGNORE_CASE , vol->upcase, vol->upcase_len); +if (!rc) + rc =ntfs_file_compare_values (data1, data2, +-2 ,CASE_SENSITIVE , vol->upcase, vol->upcase_len); +ntfs_debug ("Done, returning %i.\n" , rc); +return rc; +} + +typedef int (*ntfs_collate_func_t )(struct ntfs_volume *,const void *,const int ,const void *,const int );static ntfs_collate_func_t ntfs_do_collate0x0[3 ] = { ntfs_collate_binary, -NULL /*ntfs_collate_file_name*/ , + ntfs_collate_file_name,NULL /*ntfs_collate_unicode_string*/ , };
@@ -65,7 +131,7 @@ static ntfs_collate_func_t ntfs_do_collate0x1[4] = { ntfs_collate_ntofs_ulong,NULL /*ntfs_collate_ntofs_sid*/ ,NULL /*ntfs_collate_ntofs_security_hash*/ , - NULL/*ntfs_collate_ntofs_ulongs*/, + ntfs_collate_ntofs_ulongs, };/**
@@ -84,27 +150,29 @@ static ntfs_collate_func_t ntfs_do_collate0x1[4] = {* For speed we use the collation rule @cr as an index into two tables of * function pointers to call the appropriate collation function. */ -int ntfs_collate (ntfs_volume *vol,COLLATION_RULE cr, +int ntfs_collate (struct ntfs_volume *vol,__le32 cr,const void *data1,const int data1_len, -const void *data2,const int data2_len) { +const void *data2,const int data2_len) +{int i;ntfs_debug ("Entering." ); -/* -* FIXME: At the moment we only support COLLATION_BINARY and -* COLLATION_NTOFS_ULONG, so we BUG() for everything else for now. -*/ -BUG_ON (cr !=COLLATION_BINARY && cr !=COLLATION_NTOFS_ULONG ); + +if (cr !=COLLATION_BINARY && cr !=COLLATION_NTOFS_ULONG && + cr !=COLLATION_FILE_NAME && cr !=COLLATION_NTOFS_ULONGS ) +return -EINVAL ; + i =le32_to_cpu (cr); -BUG_ON (i <0 ); +if (i <0 ) +return -1 ;if (i <=0x02 )return ntfs_do_collate0x0[i](vol, data1, data1_len, data2, data2_len); -BUG_ON (i <0x10 ); +if (i <0x10 ) +return -1 ; i -=0x10 ;if (likely (i <=3 ))return ntfs_do_collate0x1[i](vol, data1, data1_len, data2, data2_len); -BUG ();return 0 ; }
fs/ntfs/debug.c +28 -16
108 lines not on this page · raw message
fs/ntfs/logfile.c +164 -238
793 lines not on this page · raw message
fs/ntfs/quota.c +15 -21
@@ -1,13 +1,11 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* quota.c - NTFS kernel quota ($Quota) handling. Part of the Linux-NTFS -* project. +* NTFS kernel quota ($Quota) handling. +* Part of the Linux-NTFS project. * * Copyright (c) 2004 Anton Altaparmakov */ -#ifdef NTFS_RW -#include "index.h" #include "quota.h" #include "debug.h"
@@ -20,11 +18,11 @@* Mark the quotas out of date on the ntfs volume @vol and return 'true' on * success and 'false' on error. */ -bool ntfs_mark_quotas_out_of_date (ntfs_volume *vol) +bool ntfs_mark_quotas_out_of_date (struct ntfs_volume *vol) { -ntfs_index_context *ictx; -QUOTA_CONTROL_ENTRY *qce; -const le32 qid =QUOTA_DEFAULTS_ID ; +struct ntfs_index_context *ictx; +struct quota_control_entry *qce; +const __le32 qid =QUOTA_DEFAULTS_ID ;int err;ntfs_debug ("Entering." );
@@ -35,7 +33,7 @@ bool ntfs_mark_quotas_out_of_date(ntfs_volume *vol)return false; }inode_lock (vol->quota_q_ino); - ictx =ntfs_index_ctx_get (NTFS_I (vol->quota_q_ino)); + ictx =ntfs_index_ctx_get (NTFS_I (vol->quota_q_ino),I30 ,4 );if (!ictx) {ntfs_error (vol->sb,"Failed to get index context." ); goto err_out;
@@ -43,22 +41,20 @@ bool ntfs_mark_quotas_out_of_date(ntfs_volume *vol) err =ntfs_index_lookup (&qid,sizeof (qid), ictx);if (err) {if (err == -ENOENT ) -ntfs_error (vol->sb,"Quota defaults entry is not " -"present." ); +ntfs_error (vol->sb,"Quota defaults entry is not present." );else -ntfs_error (vol->sb,"Lookup of quota defaults entry " -"failed." ); +ntfs_error (vol->sb,"Lookup of quota defaults entry failed." ); goto err_out; } -if (ictx->data_len < offsetof(QUOTA_CONTROL_ENTRY , sid)) { -ntfs_error (vol->sb,"Quota defaults entry size is invalid. " -"Run chkdsk." ); +if (ictx->data_len < offsetof(struct quota_control_entry , sid)) { +ntfs_error (vol->sb,"Quota defaults entry size is invalid. Run chkdsk." ); goto err_out; } - qce = (QUOTA_CONTROL_ENTRY *)ictx->data; + qce = (struct quota_control_entry *)ictx->data;if (le32_to_cpu (qce->version) !=QUOTA_VERSION ) { -ntfs_error (vol->sb,"Quota defaults entry version 0x%x is not " -"supported." ,le32_to_cpu (qce->version)); +ntfs_error (vol->sb, +"Quota defaults entry version 0x%x is not supported." , +le32_to_cpu (qce->version)); goto err_out; }ntfs_debug ("Quota defaults flags = 0x%x." ,le32_to_cpu (qce->flags));
@@ -99,5 +95,3 @@ bool ntfs_mark_quotas_out_of_date(ntfs_volume *vol)inode_unlock (vol->quota_q_ino);return false; } - -#endif /* NTFS_RW */
fs/ntfs/sysctl.c +5 -7
@@ -1,9 +1,9 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* sysctl.c - Code for sysctl handling in NTFS Linux kernel driver. Part of -* the Linux-NTFS project. Adapted from the old NTFS driver, -* Copyright (C) 1997 Martin von Löwis, Régis Duchesne +* Code for sysctl handling in NTFS Linux kernel driver. Part of +* the Linux-NTFS project. Adapted from the old NTFS driver, * +* Copyright (C) 1997 Martin von Löwis, Régis Duchesne * Copyright (c) 2002-2005 Anton Altaparmakov */
@@ -20,7 +20,7 @@#include "debug.h" /* Definition of the ntfs sysctl. */ -static struct ctl_table ntfs_sysctls[] = { +static const struct ctl_table ntfs_sysctls[] = { { .procname ="ntfs-debug" , .data = &debug_msgs,/* Data pointer and size. */
@@ -28,6 +28,7 @@ static struct ctl_table ntfs_sysctls[] = { .mode = 0644, /* Mode, proc handler. */ .proc_handler = proc_dointvec }, + {} };/* Storage for the sysctls header. */
@@ -42,17 +43,14 @@ static struct ctl_table_header *sysctls_root_table;int ntfs_sysctl (int add) {if (add) { -BUG_ON (sysctls_root_table); sysctls_root_table =register_sysctl ("fs" , ntfs_sysctls);if (!sysctls_root_table)return -ENOMEM ; }else { -BUG_ON (!sysctls_root_table);unregister_sysctl_table (sysctls_root_table); sysctls_root_table =NULL ; }return 0 ; } -#endif /* CONFIG_SYSCTL */ #endif /* DEBUG */
fs/ntfs/unistr.c +166 -77
358 lines not on this page · raw message
fs/ntfs/upcase.c +6 -6
@@ -1,7 +1,7 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* upcase.c - Generate the full NTFS Unicode upcase table in little endian. -* Part of the Linux-NTFS project. +* Generate the full NTFS Unicode upcase table in little endian. +* Part of the Linux-NTFS project. * * Copyright (c) 2001 Richard Russon <[email protected]> * Copyright (c) 2001-2006 Anton Altaparmakov
@@ -10,7 +10,7 @@#include "malloc.h" #include "ntfs.h" -ntfschar *generate_default_upcase (void ) +__le16 *generate_default_upcase (void ) {static const int uc_run_table[][3 ] = {/* Start, End, Add */ {0x0061 ,0x007B ,-32 }, {0x0451 ,0x045D ,-80 }, {0x1F70 ,0x1F72 ,74 },
@@ -52,12 +52,12 @@ ntfschar *generate_default_upcase(void) };int i, r; -ntfschar *uc; +__le16 *uc; - uc =ntfs_malloc_nofs (default_upcase_len *sizeof (ntfschar)); + uc =ntfs_malloc_nofs (default_upcase_len *sizeof (__le16));if (!uc)return uc; -memset (uc,0 , default_upcase_len *sizeof (ntfschar)); +memset (uc,0 , default_upcase_len *sizeof (__le16));/* Generate the little endian Unicode upcase table used by ntfs. */ for (i =0 ; i < default_upcase_len; i++) uc[i] =cpu_to_le16 (i);
Signature · 1 line
2.25.1
Namjae Jeon
maintainerPATCH v3 12/14 Revert: ntfs3: serve as alias for the legacy ntfs driver
In reply to Namjae Jeonntfs filesystem has been remade and is returning as a new implementation. ntfs3 no longer needs to be an alias for ntfs.
--- fs/ntfs3/Kconfig | 9 -------- fs/ntfs3/dir.c | 9 -------- fs/ntfs3/file.c | 10 --------- fs/ntfs3/inode.c | 16 ++++---------- fs/ntfs3/ntfs_fs.h | 11 ---------- fs/ntfs3/super.c | 52 ---------------------------------------------- 6 files changed, 4 insertions(+), 103 deletions(-)
fs/ntfs3/Kconfig +0 -9
@@ -46,12 +46,3 @@ config NTFS3_FS_POSIX_ACL NOTE: this is linux only feature. Windows will ignore these ACLs. If you don't know what Access Control Lists are, say N. - -config NTFS_FS - tristate "NTFS file system support" - select NTFS3_FS - select BUFFER_HEAD - select NLS - help - This config option is here only for backward compatibility. NTFS - filesystem is now handled by the NTFS3 driver.
fs/ntfs3/dir.c +0 -9
@@ -631,13 +631,4 @@ const struct file_operations ntfs_dir_operations = { .compat_ioctl = ntfs_compat_ioctl,#endif }; - -#if IS_ENABLED (CONFIG_NTFS_FS ) -const struct file_operations ntfs_legacy_dir_operations = { - .llseek = generic_file_llseek, - .read = generic_read_dir, - .iterate_shared = ntfs_readdir, - .open = ntfs_file_open, -}; -#endif // clang-format on
fs/ntfs3/file.c +0 -10
@@ -1478,14 +1478,4 @@ const struct file_operations ntfs_file_operations = { .fallocate = ntfs_fallocate, .release = ntfs_file_release, }; - -#if IS_ENABLED (CONFIG_NTFS_FS ) -const struct file_operations ntfs_legacy_file_operations = { - .llseek = generic_file_llseek, - .read_iter = ntfs_file_read_iter, - .splice_read = ntfs_file_splice_read, - .open = ntfs_file_open, - .release = ntfs_file_release, -}; -#endif // clang-format on
fs/ntfs3/inode.c +4 -12
@@ -444,9 +444,7 @@ static struct inode *ntfs_read_mft(struct inode *inode,* Usually a hard links to directories are disabled. */ inode->i_op = &ntfs_dir_inode_operations; - inode->i_fop =unlikely (is_legacy_ntfs (sb)) ? - &ntfs_legacy_dir_operations : - &ntfs_dir_operations; + inode->i_fop = &ntfs_dir_operations; ni->i_valid =0 ; }else if (S_ISLNK (mode)) { ni->std_fa &= ~FILE_ATTRIBUTE_DIRECTORY ;
@@ -456,9 +454,7 @@ static struct inode *ntfs_read_mft(struct inode *inode, }else if (S_ISREG (mode)) { ni->std_fa &= ~FILE_ATTRIBUTE_DIRECTORY ; inode->i_op = &ntfs_file_inode_operations; - inode->i_fop =unlikely (is_legacy_ntfs (sb)) ? - &ntfs_legacy_file_operations : - &ntfs_file_operations; + inode->i_fop = &ntfs_file_operations; inode->i_mapping->a_ops =is_compressed (ni) ? &ntfs_aops_cmpr : &ntfs_aops;if (ino !=MFT_REC_MFT )
@@ -1590,9 +1586,7 @@ int ntfs_create_inode(struct mnt_idmap *idmap, struct inode *dir,if (S_ISDIR (mode)) { inode->i_op = &ntfs_dir_inode_operations; - inode->i_fop =unlikely (is_legacy_ntfs (sb)) ? - &ntfs_legacy_dir_operations : - &ntfs_dir_operations; + inode->i_fop = &ntfs_dir_operations; }else if (S_ISLNK (mode)) { inode->i_op = &ntfs_link_inode_operations; inode->i_fop =NULL ;
@@ -1601,9 +1595,7 @@ int ntfs_create_inode(struct mnt_idmap *idmap, struct inode *dir,inode_nohighmem (inode); }else if (S_ISREG (mode)) { inode->i_op = &ntfs_file_inode_operations; - inode->i_fop =unlikely (is_legacy_ntfs (sb)) ? - &ntfs_legacy_file_operations : - &ntfs_file_operations; + inode->i_fop = &ntfs_file_operations; inode->i_mapping->a_ops =is_compressed (ni) ? &ntfs_aops_cmpr : &ntfs_aops;init_rwsem (&ni->file.run_lock);
fs/ntfs3/ntfs_fs.h +0 -11
@@ -501,7 +501,6 @@ struct inode *dir_search_u(struct inode *dir, const struct cpu_str *uni, struct ntfs_fnd *fnd);bool dir_is_empty (struct inode *dir);extern const struct file_operations ntfs_dir_operations; -extern const struct file_operations ntfs_legacy_dir_operations;/* Globals from file.c */ int ntfs_getattr(struct mnt_idmap *idmap, const struct path *path,
@@ -516,7 +515,6 @@ long ntfs_compat_ioctl(struct file *filp, u32 cmd, unsigned long arg);extern const struct inode_operations ntfs_special_inode_operations;extern const struct inode_operations ntfs_file_inode_operations;extern const struct file_operations ntfs_file_operations; -extern const struct file_operations ntfs_legacy_file_operations;/* Globals from frecord.c */ void ni_remove_mi (struct ntfs_inode *ni,struct mft_inode *mi);
@@ -1160,13 +1158,4 @@ static inline void le64_sub_cpu(__le64 *var, u64 val) *var = cpu_to_le64(le64_to_cpu(*var) - val); } -#if IS_ENABLED (CONFIG_NTFS_FS ) -bool is_legacy_ntfs (struct super_block *sb); -#else -static inline bool is_legacy_ntfs (struct super_block *sb) -{ -return false; -} -#endif -#endif /* _LINUX_NTFS3_NTFS_FS_H */
fs/ntfs3/super.c +0 -52
88 lines not on this page · raw message
Signature · 1 line
2.25.1