ntfs filesystem remake
Subsystems (4)
Namjae Jeon
maintainerv9 cover ntfs filesystem remake
v9:
- Rebased onto 7.0-rc1 to follow changes during the merge window:
- kernel.h no longer includes hex.h.
- Use posix_acl_to_xattr() that allocates the buffer internally.
- Add generic_setlease to retain the ability to set leases.
- Stop using __getname().
- Fix failure to load attribute list on mount.
- Fix stale attribute pointer in MFT extension (Reported by Mobin Aydinfar).
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 326 tests, significantly higher than ntfs3's 256. ntfs passed tests are a complete superset of the tests passed by ntfs3. 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 326 256 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
v8:
- Acked-by from Christoph Hellwig for the whole series.
- Remove unneeded check for unsigned lowest_vcn found by smatch.
- Use LCN_HOLE instead of hardcoded -1 in runlist validation.
v7:
- Fix mount options indentation in Documentation.
- Add FMODE_CAN_ODIRECT in file open.
- Use -EOPNOTSUPP for unsupported EFS-encrypted I/O and add the comments.
- Remove lcn_seek_trunc field and O_TRUNC workaround codes.
- Move preallocated size trim to helper in file release.
- Use lowercase for reparse data structures.
- Split complex reparse validation into readable checks.
- Use early return in reparse tag validation.
- Consolidate memalloc_nofs_restore to single exit point.
- Remove useless headers from aops.c.
- Fix comment in ntfs_readahead.
- Rename mark_ntfs_record_dirty to ntfs_mft_mark_dirty.
- Move ntfs_mft_mark_dirty to mft.c.
- Remove empty aops.h.
- Simplify __ntfs_iomap_read_begin.
- Split ntfs_zero_range.
- Refactor __ntfs_write_iomap_begin, ntfs_write_iomap_end and ntfs_iomap_put_folio.
v6:
- Update ntfs.rst documentation.(Removed historical comparisons and temporal terms as per review feedback)
- Remove outdated Linux-NTFS project references.
- Add missing return comments for functions.
- Move comments above in structure.
- Replace wait_for_stable_page with filemap_write_and_wait_range.
- Dereference the ntfs_inode field instead of the casts.
- Remove malloc.h file and use kvmalloc and friends.
- Update help text for NTFS_FS_POSIX_ACL in Kconfig.
- Remove __always_unused directives.
- Change #ifndef to #ifdef in debug.
- Refactor ntfs_collate_ntofs_ulongs.
- Change type of key length for index.
- Remove verbose debug logs from ntfs_collate.
- Fix sparse warnings.
- Move initialization into declaration line.
- Don't type cast from pointer to void.
- Refactor ntfs_collate.
- Re-implement llseek using iomap.
- Don't allow acl mount option when config is disabled.
- Fix kerneldoc warnings.
- Update comments for magic constants.
- Use sizeof(unsigned char) instead of UCHAR_T_SIZE_BITS.
- Replace macros with inline helpers.
- Add/use generic FS_IOC_SHUTDOWN definitions.
- Remove flush_dcache_folio.
- Introduce address space operations for $MFT.
- Add comment for ntfs_bio_end_io.
- Add ntfs_get_locked_folio helper.
- Remove outdated ntfs_setattr comment.
- Remove unnecessary kernel-doc comments.
- Fix missing error handling for compressed/encrypted files in setattr.
- Refactor ATTR_SIZE handling into ntfs_setattr_size().
- Rely on iomap for direct I/O alignment state.
- Report advanced file attributes and DIO alignment in getattr.
- Move ntfs_attr_expand and ntfs_extend_initialized_size to ntfs iomap.
- Factor out ntfs_dio_write_iter from ntfs_write_iter().
- Remove unneeded IS_IMMUTABLE in ntfs_filemap_page_mkwrite.
- Remove regular file check in ntfs_fallocate.
- Change COMPRESS_CONTEXT to lowercase.
- Add the comment for hash multiplier.
- Fix potential deadlock when inode is freed.
- Fix generic/321 failure when acl is enabled.
- use bdev_rw_virt in ntfs_bdev_read.
- Remove mft_writepage from ntfs_writepages.
- let ntfs_mft_writepages call ntfs_write_mft_block instead of ntfs_mft_writepage.
- Move ntfs_write_mft_block into mft.c.
- Move ntfs_bdev_read/write into bdev-io.c
- Move ntfs_mft_writepages to mft.c.
v5:
- Update outdated comments to match implementation.
- Remove unused types.h and endians.h.
- Replace submit_bio_wait() with submit_bio().
- Fix lockdep warnings caused by the latest xfstets and scratch_mkfs_sized support.
- Rename ntfs_convert_folio_index_into_lcn() to lcn_from_index().
- Fix warnings reported by Smatch static checker.
- Fix typos patch description of MAINTAINERS.
v4:
- remove choice variable in fs/Kconfig and make ntfs and ntfs3 mutually exclusive in simpler way.
- Original revert commit includes MAINTAINERS and CREDITS and update ntfs entry in MAITAINERS and Anton's info in CREDITS.
- Original revert commit include documentation and update it instead of adding a new one.
- Fix generic/401 test failure and indicate that ntfs passed tests are a complete superset of those for ntfs3.
- Remove unnecessary comments and warning options from Makefile.
- Add patch description to original revert patch and the patch that remove legacy ntfs driver related codes in ntfs.
- Support timestamps prior to epoch (fix generic/258).
- Fix xfstests generic/683, 684, 686, 687, 688.
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.
Appendix: xfstests Results on ntfs
Summary
- Total tests run: 787
- Passed: 326
- Failed: 38
- Not run / skipped: 423
Failed test cases and reasons
- Requires metadata journaling (34 tests)
043, 056, 051, 057, 065, 066, 073, 104, 225, 335, 336, 341, 342, 343,
348, 376, 388, 417, 475, 498, 502, 510, 526, 527, 530, 552,
640, 690, 764, 771, 779, 782, 784, 785 - Others (4 tests)
094: Not supported by NTFS on-disk format (no unwritten extent concept). 563: cgroup v2 aware writeback accounting not supported. 631: RENAME_WHITEOUT support is required on ntfs.
787: NFS delegation test.
Namjae Jeon (17):
Revert "fs: Remove NTFS classic"
fs: add generic FS_IOC_SHUTDOWN definitions
ntfs: update in-memory, on-disk structures and headers
ntfs: update super block operations
ntfs: update inode operations
ntfs: update mft 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
ntfs3: remove legacy ntfs driver support
ntfs: add Kconfig and Makefile
Documentation: filesystems: update NTFS driver documentation
MAINTAINERS: update ntfs filesystem entry
CREDITS | 9 +- Documentation/filesystems/index.rst | 1 + Documentation/filesystems/ntfs.rst | 159 + MAINTAINERS | 9 + fs/Kconfig | 1 + fs/Makefile | 1 + fs/ntfs/Kconfig | 47 + fs/ntfs/Makefile | 10 + fs/ntfs/aops.c | 263 ++ fs/ntfs/attrib.c | 5425 +++++++++++++++++++++++++++ fs/ntfs/attrib.h | 164 + fs/ntfs/attrlist.c | 289 ++ fs/ntfs/attrlist.h | 20 + fs/ntfs/bdev-io.c | 117 + fs/ntfs/bitmap.c | 287 ++ fs/ntfs/bitmap.h | 100 + fs/ntfs/collate.c | 146 + fs/ntfs/collate.h | 36 + fs/ntfs/compress.c | 1577 ++++++++ fs/ntfs/debug.c | 171 + fs/ntfs/debug.h | 63 + fs/ntfs/dir.c | 1236 ++++++ fs/ntfs/dir.h | 32 + fs/ntfs/ea.c | 942 +++++ fs/ntfs/ea.h | 30 + fs/ntfs/file.c | 1161 ++++++ fs/ntfs/index.c | 2117 +++++++++++ fs/ntfs/index.h | 111 + fs/ntfs/inode.c | 3820 +++++++++++++++++++ fs/ntfs/inode.h | 359 ++ fs/ntfs/iomap.c | 870 +++++ fs/ntfs/iomap.h | 23 + fs/ntfs/layout.h | 2346 ++++++++++++ fs/ntfs/lcnalloc.c | 1047 ++++++ fs/ntfs/lcnalloc.h | 134 + fs/ntfs/logfile.c | 778 ++++ fs/ntfs/logfile.h | 245 ++ fs/ntfs/malloc.h | 77 + fs/ntfs/mft.c | 2922 +++++++++++++++ fs/ntfs/mft.h | 94 + fs/ntfs/mst.c | 194 + fs/ntfs/namei.c | 1695 +++++++++ fs/ntfs/ntfs.h | 294 ++ fs/ntfs/object_id.c | 158 + fs/ntfs/object_id.h | 14 + fs/ntfs/quota.c | 95 + fs/ntfs/quota.h | 15 + fs/ntfs/reparse.c | 573 +++ fs/ntfs/reparse.h | 20 + fs/ntfs/runlist.c | 2066 ++++++++++ fs/ntfs/runlist.h | 97 + fs/ntfs/super.c | 2770 ++++++++++++++ fs/ntfs/sysctl.c | 55 + fs/ntfs/sysctl.h | 26 + fs/ntfs/time.h | 87 + fs/ntfs/unistr.c | 477 +++ fs/ntfs/upcase.c | 70 + fs/ntfs/volume.h | 296 ++ fs/ntfs3/Kconfig | 10 +- fs/ntfs3/dir.c | 10 - fs/ntfs3/file.c | 11 - fs/ntfs3/inode.c | 16 +- fs/ntfs3/ntfs_fs.h | 11 - fs/ntfs3/super.c | 59 +- include/uapi/linux/fs.h | 12 + 65 files changed, 36252 insertions(+), 118 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/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/bdev-io.c 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/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/object_id.c create mode 100644 fs/ntfs/object_id.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/unistr.c create mode 100644 fs/ntfs/upcase.c create mode 100644 fs/ntfs/volume.h
Signature · 1 line
2.25.1
Namjae Jeon
maintainerPATCH v9 1/17 Revert "fs: Remove NTFS classic"
This reverts commit 7ffa8f3d30236e0ab897c30bdb01224ff1fe1c89.
Reverts the removal of the classic read-only ntfs driver to serve as the base for a new read-write ntfs implementation. If we stack changes on top of the revert patch, It will significantly reduce the diff size, making the review easier.
This revert intentionally excludes the restoration of Kconfig and Makefile. The Kconfig and Makefile will be added back in the final patch of this series, enabling the driver only after all features and improvements have been applied.
--- CREDITS | 5 - Documentation/filesystems/ntfs.rst | 466 ++++ MAINTAINERS | 10 + 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/usnjrnl.c | 70 + fs/ntfs/usnjrnl.h | 191 ++ fs/ntfs/volume.h | 164 ++ 47 files changed, 29204 insertions(+), 5 deletions(-) create mode 100644 Documentation/filesystems/ntfs.rst 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/usnjrnl.c create mode 100644 fs/ntfs/usnjrnl.h create mode 100644 fs/ntfs/volume.h
CREDITS +0 -5
@@ -71,11 +71,6 @@ D: dosfs, LILO, some fd features, ATM, various other hacks here and there S: Buenos Aires S: Argentina -NTFS FILESYSTEM -N: Anton Altaparmakov -E: [email protected] -D: NTFS filesystem - N: Tim Alpaerts E: [email protected] D: 802.2 class II logical link control layer,
Documentation/filesystems/ntfs.rst new file +466 -0
466 lines not on this page · raw message
MAINTAINERS +10 -0
@@ -18810,6 +18810,16 @@ W: https://github.com/davejiang/linux/wiki T: git https://github.com/davejiang/linux.git F: drivers/ntb/hw/intel/ +NTFS FILESYSTEM +M: Anton Altaparmakov <[email protected]> +R: Namjae Jeon <[email protected]> +L: [email protected] +S: Supported +W: http://www.tuxera.com/ +T: git git://git.kernel.org/pub/scm/linux/kernel/git/aia21/ntfs.git +F: Documentation/filesystems/ntfs.rst +F: fs/ntfs/ + NTFS3 FILESYSTEM M: Konstantin Komarov <[email protected]> L: [email protected]
fs/ntfs/aops.c new file +1744 -0
1,744 lines not on this page · raw message
fs/ntfs/aops.h new file +88 -0
88 lines not on this page · raw message
fs/ntfs/attrib.c new file +2624 -0
675 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/usnjrnl.c new file +70 -0
70 lines not on this page · raw message
fs/ntfs/usnjrnl.h new file +191 -0
191 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 v9 2/17 fs: add generic FS_IOC_SHUTDOWN definitions
In reply to Namjae JeonCurrently, several filesystems (e.g., xfs, ext4, btrfs) implement a "shutdown" or "going down" ioctl to simulate filesystem force a shutdown. While they often use the same underlying numeric value, the definition is duplicated across filesystem headers or private definitions.
Add generic definitions for FS_IOC_SHUTDOWN in uapi/linux/fs.h. This allows new filesystems (like ntfs) to implement this feature using a standard VFS definition and paves the way for existing filesystems to unify their definitions later.
The flag names are standardized as FS_SHUTDOWN_* to be consistent with the ioctl name, replacing the historical GOING_DOWN naming convention.
--- include/uapi/linux/fs.h | 12 ++++++++++++ 1 file changed, 12 insertions(+)
include/uapi/linux/fs.h +12 -0
@@ -656,4 +656,16 @@ struct procmap_query { __u64 build_id_addr; /* in */ }; +/* +* Shutdown the filesystem. +*/ +#define FS_IOC_SHUTDOWN _IOR('X', 125, __u32) + +/* +* Flags for FS_IOC_SHUTDOWN +*/ +#define FS_SHUTDOWN_FLAGS_DEFAULT 0x0 +#define FS_SHUTDOWN_FLAGS_LOGFLUSH 0x1/* flush log but not data*/ +#define FS_SHUTDOWN_FLAGS_NOLOGFLUSH 0x2/* don't flush log nor data */ +#endif /* _UAPI_LINUX_FS_H */
Signature · 1 line
2.25.1
Re: [PATCH v9 02/17] fs: add generic FS_IOC_SHUTDOWN definitions
include/uapi/linux/fs.h struct procmap_query { · line 662
Quoted 4 lines
include/uapi/linux/fs.h +4
-0+/* +* Shutdown the filesystem. +*/ +#define FS_IOC_SHUTDOWN _IOR('X', 125, __u32)
Should've been _IOW, not _IOR. This is rather unfortunate.
Documentation/userspace-api/ioctl/ioctl-number.rst:
Quoted 9 lines
====== ===========================
macro parameters
====== ===========================
_IO none
_IOW write (read from userspace)
_IOR read (write to userspace)
_IOWR write and read
====== ===========================
Quoted 5 lines
'Write' and 'read' are from the user's point of view, just like the system calls 'write' and 'read'. For example, a
SET_FOOioctl would be_IOW, although the kernel would actually read data from user space; aGET_FOOioctl would be_IOR, although the kernel would actually write data to user space.
All the *_ioctl_shutdown() do get_user(..., arg).
Re: [PATCH v9 02/17] fs: add generic FS_IOC_SHUTDOWN definitions
Quoted 5 lines · David Timber
include/uapi/linux/fs.h struct procmap_query { · line 662
Quoted 4 lines
include/uapi/linux/fs.h +4
-0+/* +* Shutdown the filesystem. +*/ +#define FS_IOC_SHUTDOWN _IOR('X', 125, __u32)Should've been
_IOW, not_IOR. This is rather unfortunate.
Yep, it's too bad that this has been encoded in XFS like this for decades. :/
You /could/ send patches to add an _IOW definition and make fstests/xfsprogs prefer the new ioctl number over the old one.
--D
Quoted 17 lines
Documentation/userspace-api/ioctl/ioctl-number.rst:Quoted 9 lines
====== ===========================
macro parameters
====== ===========================
_IO none
_IOW write (read from userspace)
_IOR read (write to userspace)
_IOWR write and read
====== ===========================Quoted 5 lines
'Write' and 'read' are from the user's point of view, just like the system calls 'write' and 'read'. For example, a
SET_FOOioctl would be_IOW, although the kernel would actually read data from user space; aGET_FOOioctl would be_IOR, although the kernel would actually write data to user space.All the
*_ioctl_shutdown()doget_user(..., arg).
Namjae Jeon
maintainerPATCH v9 3/17 ntfs: update in-memory, on-disk structures and headers
In reply to Namjae JeonUpdate the NTFS filesystem driver's in-memory and on-disk structures:
- Introduce the infrastructure and initial support for reparse points and EA attribute.
- Refactor the core ntfs_inode and ntfs_volume structures to support new features such as iomap.
- Remove the unnecessary types.h and endian.h headers.
- Reorganize the comments in headers for better readability, including fixing warnings from checkpatch.pl.
--- fs/ntfs/aops.h | 88 -- fs/ntfs/attrib.h | 194 ++- fs/ntfs/attrlist.h | 20 + fs/ntfs/bitmap.h | 22 +- fs/ntfs/collate.h | 26 +- fs/ntfs/debug.h | 16 +- fs/ntfs/dir.h | 22 +- fs/ntfs/ea.h | 30 + fs/ntfs/endian.h | 79 -- fs/ntfs/index.h | 135 +- fs/ntfs/inode.h | 455 ++++--- fs/ntfs/iomap.h | 23 + fs/ntfs/layout.h | 2991 +++++++++++++++++++++---------------------- fs/ntfs/lcnalloc.h | 67 +- fs/ntfs/logfile.h | 402 +++--- fs/ntfs/mft.h | 80 +- fs/ntfs/ntfs.h | 238 +++- fs/ntfs/object_id.h | 14 + fs/ntfs/quota.h | 10 +- fs/ntfs/reparse.h | 20 + fs/ntfs/runlist.h | 115 +- fs/ntfs/sysctl.h | 7 +- fs/ntfs/time.h | 32 +- fs/ntfs/types.h | 55 - fs/ntfs/volume.h | 380 ++++-- 25 files changed, 2816 insertions(+), 2705 deletions(-) delete mode 100644 fs/ntfs/aops.h create mode 100644 fs/ntfs/attrlist.h create mode 100644 fs/ntfs/ea.h delete mode 100644 fs/ntfs/endian.h create mode 100644 fs/ntfs/iomap.h create mode 100644 fs/ntfs/object_id.h create mode 100644 fs/ntfs/reparse.h delete mode 100644 fs/ntfs/types.h
fs/ntfs/aops.h deleted +0 -88
@@ -1,88 +0,0 @@ -/* SPDX-License-Identifier: GPL-2.0-or-later */ -/* -* aops.h - Defines for NTFS kernel address space operations and page cache -* handling. Part of the Linux-NTFS project. -* -* Copyright (c) 2001-2004 Anton Altaparmakov -* Copyright (c) 2002 Richard Russon -*/ - -#ifndef _LINUX_NTFS_AOPS_H -#define _LINUX_NTFS_AOPS_H - -#include <linux/mm.h> -#include <linux/highmem.h> -#include <linux/pagemap.h> -#include <linux/fs.h> - -#include "inode.h" - -/** -* ntfs_unmap_page - release a page that was mapped using ntfs_map_page() -* @page: the page to release -* -* Unpin, unmap and release a page that was obtained from ntfs_map_page(). -*/ -static inline void ntfs_unmap_page (struct page *page) -{ -kunmap (page); -put_page (page); -} - -/** -* ntfs_map_page - map a page into accessible memory, reading it if necessary -* @mapping: address space for which to obtain the page -* @index: index into the page cache for @mapping of the page to map -* -* Read a page from the page cache of the address space @mapping at position -* @index, where @index is in units of PAGE_SIZE, and not in bytes. -* -* If the page is not in memory it is loaded from disk first using the -* read_folio method defined in the address space operations of @mapping -* and the page is added to the page cache of @mapping in the process. -* -* If the page belongs to an mst protected attribute and it is marked as such -* in its ntfs inode (NInoMstProtected()) the mst fixups are applied but no -* error checking is performed. This means the caller has to verify whether -* the ntfs record(s) contained in the page are valid or not using one of the -* ntfs_is_XXXX_record{,p}() macros, where XXXX is the record type you are -* expecting to see. (For details of the macros, see fs/ntfs/layout.h.) -* -* If the page is in high memory it is mapped into memory directly addressible -* by the kernel. -* -* Finally the page count is incremented, thus pinning the page into place. -* -* The above means that page_address(page) can be used on all pages obtained -* with ntfs_map_page() to get the kernel virtual address of the page. -* -* When finished with the page, the caller has to call ntfs_unmap_page() to -* unpin, unmap and release the page. -* -* Note this does not grant exclusive access. If such is desired, the caller -* must provide it independently of the ntfs_{un}map_page() calls by using -* a {rw_}semaphore or other means of serialization. A spin lock cannot be -* used as ntfs_map_page() can block. -* -* The unlocked and uptodate page is returned on success or an encoded error -* on failure. Caller has to test for error using the IS_ERR() macro on the -* return value. If that evaluates to 'true', the negative error code can be -* obtained using PTR_ERR() on the return value of ntfs_map_page(). -*/ -static inline struct page *ntfs_map_page (struct address_space *mapping, -unsigned long index) -{ -struct page *page =read_mapping_page (mapping, index,NULL ); - -if (!IS_ERR (page)) -kmap (page); -return page; -} - -#ifdef NTFS_RW - -extern void mark_ntfs_record_dirty (struct page *page,const unsigned int ofs); - -#endif /* NTFS_RW */ - -#endif /* _LINUX_NTFS_AOPS_H */
fs/ntfs/attrib.h +128 -66
223 lines not on this page · raw message
fs/ntfs/attrlist.h new file +20 -0
@@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ +/* +* Exports for attribute list attribute handling. +* +* 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 +9 -13
@@ -1,7 +1,6 @@/* 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. * * Copyright (c) 2004 Anton Altaparmakov */
@@ -9,16 +8,15 @@#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 ntfs_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); -/** +/* * ntfs_bitmap_set_bits_in_run - set a run of bits in a bitmap to a value * @vi: vfs inode describing the bitmap * @start_bit: first bit to set
@@ -37,7 +35,7 @@ static inline int ntfs_bitmap_set_bits_in_run(struct inode *vi, false); } -/** +/* * ntfs_bitmap_set_run - set a run of bits in a bitmap * @vi: vfs inode describing the bitmap * @start_bit: first bit to set
@@ -54,7 +52,7 @@ static inline int ntfs_bitmap_set_run(struct inode *vi, const s64 start_bit,return ntfs_bitmap_set_bits_in_run (vi, start_bit, count,1 ); } -/** +/* * ntfs_bitmap_clear_run - clear a run of bits in a bitmap * @vi: vfs inode describing the bitmap * @start_bit: first bit to clear
@@ -71,7 +69,7 @@ static inline int ntfs_bitmap_clear_run(struct inode *vi, const s64 start_bit,return ntfs_bitmap_set_bits_in_run (vi, start_bit, count,0 ); } -/** +/* * ntfs_bitmap_set_bit - set a bit in a bitmap * @vi: vfs inode describing the bitmap * @bit: bit to set
@@ -85,7 +83,7 @@ static inline int ntfs_bitmap_set_bit(struct inode *vi, const s64 bit)return ntfs_bitmap_set_run (vi, bit,1 ); } -/** +/* * ntfs_bitmap_clear_bit - clear a bit in a bitmap * @vi: vfs inode describing the bitmap * @bit: bit to clear
@@ -99,6 +97,4 @@ 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 +13 -13
@@ -1,26 +1,26 @@/* 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. * * Copyright (c) 2004 Anton Altaparmakov +* +* Part of this file is based on code from the NTFS-3G. +* 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,8 +29,8 @@ static inline bool ntfs_is_collation_rule_supported(COLLATION_RULE cr) { return false; } -extern int ntfs_collate (ntfs_volume *vol,COLLATION_RULE cr, -const void *data1,const int data1_len, -const void *data2,const int data2_len); +int ntfs_collate (struct ntfs_volume *vol,__le32 cr, +const void *data1,const u32 data1_len, +const void *data2,const u32 data2_len);#endif /* _LINUX_NTFS_COLLATE_H */
fs/ntfs/debug.h +11 -5
@@ -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. * * Copyright (c) 2001-2004 Anton Altaparmakov */
@@ -19,7 +19,7 @@ extern int debug_msgs; extern __printf(4, 5) void __ntfs_debug(const char *file, int line, const char *function, const char *format, ...); -/** +/* * ntfs_debug - write a debug level message to syslog * @f: a printf format string containing the message * @...: the variables to substitute into @f
@@ -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 +10 -12
@@ -1,7 +1,6 @@/* 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. * * Copyright (c) 2002-2004 Anton Altaparmakov */
@@ -9,26 +8,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 +30 -0
@@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: GPL-2.0-or-later */ + +#ifndef _LINUX_NTFS_EA_H +#define _LINUX_NTFS_EA_H + +#define NTFS_EA_UID BIT(1) +#define NTFS_EA_GID BIT(2) +#define NTFS_EA_MODE BIT(3) + +extern const struct xattr_handler *const ntfs_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 ntfs_listxattr (struct dentry *dentry,char *buffer,size_t size); + +#ifdef CONFIG_NTFS_FS_POSIX_ACL +struct posix_acl *ntfs_get_acl (struct mnt_idmap *idmap,struct dentry *dentry, +int type); +int ntfs_set_acl (struct mnt_idmap *idmap,struct dentry *dentry, +struct posix_acl *acl,int type); +int ntfs_init_acl (struct mnt_idmap *idmap,struct inode *inode, +struct inode *dir); +#else +#define ntfs_get_acl NULL +#define ntfs_set_acl NULL +#endif + +#endif /* _LINUX_NTFS_EA_H */
fs/ntfs/endian.h deleted +0 -79
79 lines not on this page · raw message
fs/ntfs/index.h +56 -79
169 lines not on this page · raw message
fs/ntfs/inode.h +252 -203
553 lines not on this page · raw message
fs/ntfs/iomap.h new file +23 -0
@@ -0,0 +1,23 @@ +/* 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_seek_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_dio_zero_range (struct inode *inode,loff_t offset,loff_t length); +#endif /* _LINUX_NTFS_IOMAP_H */
fs/ntfs/layout.h +1458 -1533
1,613 lines not on this page · raw message
fs/ntfs/lcnalloc.h +35 -32
67 lines not on this page · raw message
fs/ntfs/logfile.h +176 -226
402 lines not on this page · raw message
fs/ntfs/mft.h +32 -48
80 lines not on this page · raw message
fs/ntfs/ntfs.h +191 -47
238 lines not on this page · raw message
fs/ntfs/runlist.h +62 -53
115 lines not on this page · raw message
fs/ntfs/types.h deleted +0 -55
55 lines not on this page · raw message
fs/ntfs/volume.h +256 -124
380 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 v9 4/17 ntfs: update super block operations
In reply to Namjae JeonUpdate the super block operations to support the new fs_context-based mount API, full read-write support including ->sync_fs, and file system shutdown support.
Update ntfs_statfs() to provide statistics using atomic counters for free clusters and MFT records.
Add a dedicated workqueue to compute the total number of free clusters by scanning asynchronously. Synchronous bitmap scanning during mount can take a very long time on large volumes, severely delaying mount completion. Moving this to the background allows mount to finish almost immediately.
Implement ntfs_write_volume_label() to allow changing the volume label.
--- fs/ntfs/super.c | 2562 ++++++++++++++++++++--------------------------- 1 file changed, 1065 insertions(+), 1497 deletions(-)
fs/ntfs/super.c +1065 -1497
@@ -1,357 +1,328 @@// 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. * * 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 "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" /* 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: +#ifdef CONFIG_NTFS_FS_POSIX_ACL +if (result.boolean) + fc->sb_flags |=SB_POSIXACL ; +else + fc->sb_flags &= ~SB_POSIXACL ; +break ; +#else +return -EINVAL ; +#endif +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 * @vol: ntfs volume on which to modify the flags * @flags: new flags value for the volume information flags
@@ -366,53 +337,48 @@ 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; } -/** +/* * ntfs_set_volume_flags - set bits in the volume information flags * @vol: ntfs volume on which to modify the flags * @flags: flags to set on the volume
@@ -421,13 +387,13 @@ 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); } -/** +/* * ntfs_clear_volume_flags - clear bits in the volume information flags * @vol: ntfs volume on which to modify the flags * @flags: flags to clear on the volume
@@ -436,133 +402,65 @@ 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; } -/** +/* * is_boot_sector_ntfs - check whether a boot sector is a valid NTFS boot sector * @sb: Super block of the device to which @b belongs. * @b: Boot sector of device @sb to check.
@@ -575,7 +473,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 +482,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 +496,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 ) +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 : - 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) ||
@@ -648,108 +543,41 @@ static bool is_boot_sector_ntfs(const struct super_block *sb,return false; } -/** +/* * read_ntfs_boot_sector - read the NTFS boot sector of a device * @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 =kzalloc (PAGE_SIZE ,GFP_NOFS ); +if (!boot_sector) +return NULL ; + +if (ntfs_bdev_read (sb->s_bdev, 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; } -/** +/* * parse_ntfs_boot_sector - parse the boot sector and store the data in @vol * @vol: volume structure to initialise with data from boot sector * @b: boot sector to parse
@@ -757,9 +585,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 +599,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 +623,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 +654,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 +689,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 +699,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,28 +736,42 @@ 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; } -/** +/* * ntfs_setup_allocators - initialize the cluster and mft allocators * @vol: volume structure for which to setup the allocators * * 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 +792,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 +802,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 +819,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 +873,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);
@@ -1068,7 +889,7 @@ static bool load_and_init_mft_mirror(ntfs_volume *vol)return true; } -/** +/* * check_mft_mirror - compare contents of the mft mirror with the mft * @vol: ntfs super block describing device whose mft mirror to check *
@@ -1078,23 +899,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 +919,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 +1008,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; }
@@ -1201,39 +1018,38 @@ static bool check_mft_mirror(ntfs_volume *vol)return true; } -/** +/* * load_and_check_logfile - load and check the logfile inode for a volume -* @vol: ntfs super block describing device whose logfile to load +* @vol: ntfs volume to load the logfile for +* @rp: on success, set to the restart page header * -* 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 -/** +/* * check_windows_hibernation_status - check if Windows is suspended on a volume * @vol: ntfs super block of device to check *
@@ -1257,21 +1073,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,89 +1098,80 @@ 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; } -/** +/* * load_and_init_quota - load and setup the quota file for a volume if present * @vol: ntfs super block describing device whose quota file to load * * 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 +1182,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 +1201,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 +1221,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 +1250,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 =kvzalloc (i_size,GFP_NOFS );if (!vol->attrdef) goto iput_failed; index =0 ;
@@ -1614,12 +1259,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 ;
@@ -1631,7 +1278,7 @@ static bool load_and_init_attrdef(ntfs_volume *vol)iput (ino);return true; free_iput_failed: -ntfs_free (vol->attrdef); +kvfree (vol->attrdef); vol->attrdef =NULL ; iput_failed:iput (ino);
@@ -1640,20 +1287,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 +1307,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 =kvzalloc (i_size,GFP_NOFS );if (!vol->upcase) goto iput_upcase_failed; index =0 ;
@@ -1683,26 +1329,27 @@ 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) goto read_partial_upcase_page; } - vol->upcase_len = i_size >>UCHAR_T_SIZE_BITS ; + vol->upcase_len = i_size >>sizeof (unsigned char );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; }
@@ -1713,22 +1360,20 @@ static bool load_and_init_upcase(ntfs_volume *vol)if (vol->upcase[i] != default_upcase[i])break ;if (i == max) { -ntfs_free (vol->upcase); +kvfree (vol->upcase); vol->upcase = default_upcase; 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); -ntfs_free (vol->upcase); +kvfree (vol->upcase); vol->upcase =NULL ; upcase_failed:mutex_lock (&ntfs_lock);
@@ -1737,8 +1382,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);
@@ -1754,7 +1398,7 @@ static struct lock_class_key lcnbmp_runlist_lock_key, lcnbmp_mrec_lock_key, mftbmp_runlist_lock_key, mftbmp_mrec_lock_key; -/** +/* * load_system_files - open the system files using normal functions * @vol: ntfs super block describing device whose system files to load *
@@ -1763,47 +1407,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 +1444,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 +1478,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 +1491,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 +1518,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 +1551,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 +1569,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 */ + +kvfree (rp);/* 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,235 +1597,84 @@ 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); iput_attrdef_err_out: vol->attrdef_size =0 ;if (vol->attrdef) { - ntfs_free(vol->attrdef); +kvfree (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) {
@@ -2233,34 +1683,68 @@ static bool load_system_files(ntfs_volume *vol) }mutex_unlock (&ntfs_lock);if (vol->upcase) { -ntfs_free (vol->upcase); +kvfree (vol->upcase); vol->upcase =NULL ; } 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) { +kvfree (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) { +kvfree (default_upcase); + default_upcase =NULL ; + } + +free_compression_buffers (); + +mutex_unlock (&ntfs_lock); +if (vol->upcase) { +kvfree (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 +1753,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 +1765,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 +1787,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 +1813,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 +1826,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,46 +1850,70 @@ 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 ; +blkdev_issue_flush (sb->s_bdev); -/* 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 FS_SHUTDOWN_FLAGS_DEFAULT : +case FS_SHUTDOWN_FLAGS_LOGFLUSH : + ret =bdev_freeze (sb->s_bdev); +if (ret) +return ret; +bdev_thaw (sb->s_bdev); +NVolSetShutdown (vol); +break ; +case FS_SHUTDOWN_FLAGS_NOLOGFLUSH : +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,FS_SHUTDOWN_FLAGS_NOLOGFLUSH ); + +} + +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; } -/** +/* * get_nr_free_clusters - return the number of free clusters on a volume * @vol: ntfs volume for which to obtain free cluster count *
@@ -2451,16 +1932,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 +1967,20 @@ 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 =ntfs_get_locked_folio (mapping, index, max_index, ra); +/* 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 +1988,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,15 +2002,46 @@ 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 * @nr_free: number of mft records in filesystem
@@ -2531,33 +2058,43 @@ 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)
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 v9 5/17 ntfs: update inode operations
In reply to Namjae JeonAdd extent inode loading via ntfs_extent_inode_open() and ntfs_inode_attach_all_extents().
Allow dynamic creation of with ntfs_inode_add_attrlist() when the base MFT record overflows.
Introduce ntfs_inode_free_space() to move attributes out of the base record on demand.
Implement direct attribute I/O through ntfs_inode_attr_pread() and ntfs_inode_attr_pwrite().
Implement .create, .unlink, .mkdir, .rmdir, .rename, .symlink, .mknod, .link callbacks.
Introduce ntfs_non_resident_dealloc_clusters() to free clusters of non-resident attributes during inode eviction.
Add ntfs_drop_big_inode() logic to safely truncate and deallocate clusters.
--- fs/ntfs/inode.c | 3658 ++++++++++++++++++++++++++++------------------- fs/ntfs/namei.c | 1597 +++++++++++++++++++-- 2 files changed, 3638 insertions(+), 1617 deletions(-)
fs/ntfs/inode.c +2188 -1470
@@ -1,33 +1,26 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* inode.c - NTFS kernel inode handling. +* NTFS kernel inode handling. * * Copyright (c) 2001-2014 Anton Altaparmakov and Tuxera Inc. +* Copyright (c) 2025 LG Electronics Co., Ltd. */ -#include <linux/buffer_head.h> -#include <linux/fs.h> -#include <linux/mm.h> -#include <linux/mount.h> -#include <linux/mutex.h> -#include <linux/pagemap.h> -#include <linux/quotaops.h> -#include <linux/slab.h> -#include <linux/log2.h> - -#include "aops.h" -#include "attrib.h" -#include "bitmap.h" -#include "dir.h" -#include "debug.h" -#include "inode.h" +#include <linux/writeback.h> +#include <linux/seq_file.h> +#include "lcnalloc.h" -#include "malloc.h" -#include "mft.h" #include "time.h" #include "ntfs.h" +#include "index.h" +#include "attrlist.h" +#include "reparse.h" +#include "ea.h" +#include "attrib.h" +#include "iomap.h" +#include "object_id.h" -/** +/* * ntfs_test_inode - compare two (possibly fake) inodes for equality * @vi: vfs inode which to test * @data: data which is being tested with
@@ -45,12 +38,12 @@*/ int ntfs_test_inode (struct inode *vi,void *data) { -ntfs_attr *na = (ntfs_attr *)data; -ntfs_inode *ni; +struct ntfs_attr *na = data; +struct ntfs_inode *ni =NTFS_I (vi);if (vi->i_ino != na->mft_no)return 0 ; - ni =NTFS_I (vi); +/* If !NInoAttr(ni), @vi is a normal file or directory inode. */ if (likely (!NInoAttr (ni))) {/* If not looking for a normal inode this is a mismatch. */
@@ -63,14 +56,17 @@ int ntfs_test_inode(struct inode *vi, void *data)if (ni->name_len != na->name_len)return 0 ;if (na->name_len &&memcmp (ni->name, na->name, - na->name_len *sizeof (ntfschar))) + na->name_len *sizeof (__le16))) +return 0 ; +if (!ni->ext.base_ntfs_ino)return 0 ; } +/* Match! */ return 1 ; } -/** +/* * ntfs_init_locked_inode - initialize an inode * @vi: vfs inode to initialize * @data: data which to initialize @vi to
@@ -83,31 +79,31 @@ int ntfs_test_inode(struct inode *vi, void *data)* respectively. Although that is not strictly necessary as * ntfs_read_locked_inode() will fill them in later. * -* Return 0 on success and -errno on error. +* Return 0 on success and error. * * NOTE: This function runs with the inode->i_lock spin lock held so it is not * allowed to sleep. (Hence the GFP_ATOMIC allocation.) */ static int ntfs_init_locked_inode (struct inode *vi,void *data) { -ntfs_attr *na = (ntfs_attr *)data; -ntfs_inode *ni =NTFS_I (vi); +struct ntfs_attr *na = data; +struct ntfs_inode *ni =NTFS_I (vi); vi->i_ino = na->mft_no; - ni->type = na->type;if (na->type ==AT_INDEX_ALLOCATION )NInoSetMstProtected (ni); +else + ni->type = na->type; ni->name = na->name; ni->name_len = na->name_len; + ni->folio =NULL ; +atomic_set (&ni->count,1 );/* If initializing a normal inode, we are done. */ -if (likely (na->type ==AT_UNUSED )) { -BUG_ON (na->name); -BUG_ON (na->name_len); +if (likely (na->type ==AT_UNUSED ))return 0 ; - }/* It is a fake inode. */ NInoSetAttr (ni);
@@ -122,9 +118,8 @@ static int ntfs_init_locked_inode(struct inode *vi, void *data)if (na->name_len && na->name !=I30 ) {unsigned int i; -BUG_ON (!na->name); - i = na->name_len *sizeof (ntfschar); - ni->name =kmalloc (i +sizeof (ntfschar),GFP_ATOMIC ); + i = na->name_len *sizeof (__le16); + ni->name =kmalloc (i +sizeof (__le16),GFP_ATOMIC );if (!ni->name)return -ENOMEM ;memcpy (ni->name, na->name, i);
@@ -138,7 +133,7 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi);static int ntfs_read_locked_index_inode (struct inode *base_vi,struct inode *vi); -/** +/* * ntfs_iget - obtain a struct inode corresponding to a specific normal inode * @sb: super block of mounted volume * @mft_no: mft record number / inode number to obtain
@@ -158,7 +153,7 @@ struct inode *ntfs_iget(struct super_block *sb, unsigned long mft_no) {struct inode *vi;int err; -ntfs_attr na; +struct ntfs_attr na; na.mft_no = mft_no; na.type =AT_UNUSED ;
@@ -173,7 +168,7 @@ struct inode *ntfs_iget(struct super_block *sb, unsigned long mft_no) err =0 ;/* If this is a freshly allocated inode, need to read it now. */ -if (vi->i_state &I_NEW ) { +if (inode_state_read_once (vi) &I_NEW ) { err =ntfs_read_locked_inode (vi);unlock_new_inode (vi); }
@@ -188,7 +183,7 @@ struct inode *ntfs_iget(struct super_block *sb, unsigned long mft_no)return vi; } -/** +/* * ntfs_attr_iget - obtain a struct inode corresponding to an attribute * @base_vi: vfs base inode containing the attribute * @type: attribute type
@@ -211,15 +206,15 @@ struct inode *ntfs_iget(struct super_block *sb, unsigned long mft_no)* value with IS_ERR() and if true, the function failed and the error code is * obtained from PTR_ERR(). */ -struct inode *ntfs_attr_iget (struct inode *base_vi,ATTR_TYPE type, -ntfschar *name,u32 name_len) +struct inode *ntfs_attr_iget (struct inode *base_vi,__le32 type, +__le16 *name,u32 name_len) {struct inode *vi;int err; -ntfs_attr na; +struct ntfs_attr na;/* Make sure no one calls ntfs_attr_iget() for indices. */ -BUG_ON (type ==AT_INDEX_ALLOCATION ); +WARN_ON (type ==AT_INDEX_ALLOCATION ); na.mft_no = base_vi->i_ino; na.type = type;
@@ -230,11 +225,10 @@ struct inode *ntfs_attr_iget(struct inode *base_vi, ATTR_TYPE type, ntfs_init_locked_inode, &na);if (unlikely (!vi))return ERR_PTR (-ENOMEM ); - err =0 ;/* If this is a freshly allocated inode, need to read it now. */ -if (vi->i_state &I_NEW ) { +if (inode_state_read_once (vi) &I_NEW ) { err =ntfs_read_locked_attr_inode (base_vi, vi);unlock_new_inode (vi); }
@@ -250,7 +244,7 @@ struct inode *ntfs_attr_iget(struct inode *base_vi, ATTR_TYPE type,return vi; } -/** +/* * ntfs_index_iget - obtain a struct inode corresponding to an index * @base_vi: vfs base inode containing the index related attributes * @name: Unicode name of the index
@@ -269,12 +263,12 @@ struct inode *ntfs_attr_iget(struct inode *base_vi, ATTR_TYPE type,* value with IS_ERR() and if true, the function failed and the error code is * obtained from PTR_ERR(). */ -struct inode *ntfs_index_iget (struct inode *base_vi,ntfschar *name, +struct inode *ntfs_index_iget (struct inode *base_vi,__le16 *name,u32 name_len) {struct inode *vi;int err; -ntfs_attr na; +struct ntfs_attr na; na.mft_no = base_vi->i_ino; na.type =AT_INDEX_ALLOCATION ;
@@ -289,7 +283,7 @@ struct inode *ntfs_index_iget(struct inode *base_vi, ntfschar *name, err =0 ;/* If this is a freshly allocated inode, need to read it now. */ -if (vi->i_state &I_NEW ) { +if (inode_state_read_once (vi) &I_NEW ) { err =ntfs_read_locked_index_inode (base_vi, vi);unlock_new_inode (vi); }
@@ -307,12 +301,14 @@ struct inode *ntfs_index_iget(struct inode *base_vi, ntfschar *name,struct inode *ntfs_alloc_big_inode (struct super_block *sb) { -ntfs_inode *ni; +struct ntfs_inode *ni;ntfs_debug ("Entering." ); ni =alloc_inode_sb (sb, ntfs_big_inode_cache,GFP_NOFS );if (likely (ni !=NULL )) { ni->state =0 ; + ni->type =0 ; + ni->mft_no =0 ;return VFS_I (ni); }ntfs_error (sb,"Allocation of NTFS big inode structure failed." );
@@ -324,9 +320,96 @@ void ntfs_free_big_inode(struct inode *inode)kmem_cache_free (ntfs_big_inode_cache,NTFS_I (inode)); } -static inline ntfs_inode *ntfs_alloc_extent_inode (void ) +static int ntfs_non_resident_dealloc_clusters (struct ntfs_inode *ni) +{ +struct super_block *sb = ni->vol->sb; +struct ntfs_attr_search_ctx *actx; +int err =0 ; + + actx =ntfs_attr_get_search_ctx (ni,NULL ); +if (!actx) +return -ENOMEM ; +WARN_ON (actx->mrec->link_count !=0 ); + +/** +* ntfs_truncate_vfs cannot be called in evict() context due +* to some limitations, which are the @ni vfs inode is marked +* with I_FREEING, and etc. +*/ +if (NInoRunlistDirty (ni)) { + err =ntfs_cluster_free_from_rl (ni->vol, ni->runlist.rl); +if (err) +ntfs_error (sb, +"Failed to free clusters. Leaving inconsistent metadata.\n" ); + } + +while ((err =ntfs_attrs_walk (actx)) ==0 ) { +if (actx->attr->non_resident && + (!NInoRunlistDirty (ni) || actx->attr->type !=AT_DATA )) { +struct runlist_element *rl; +size_t new_rl_count; + + rl =ntfs_mapping_pairs_decompress (ni->vol, actx->attr,NULL , + &new_rl_count); +if (IS_ERR (rl)) { + err =PTR_ERR (rl); +ntfs_error (sb, +"Failed to decompress runlist. Leaving inconsistent metadata.\n" ); +continue ; + } + + err =ntfs_cluster_free_from_rl (ni->vol, rl); +if (err) +ntfs_error (sb, +"Failed to free attribute clusters. Leaving inconsistent metadata.\n" ); +kvfree (rl); + } + } + +ntfs_release_dirty_clusters (ni->vol, ni->i_dealloc_clusters); +ntfs_attr_put_search_ctx (actx); +return err; +} + +int ntfs_drop_big_inode (struct inode *inode) +{ +struct ntfs_inode *ni =NTFS_I (inode); + +if (!inode_unhashed (inode) &&inode_state_read_once (inode) &I_SYNC ) { +if (ni->type ==AT_DATA || ni->type ==AT_INDEX_ALLOCATION ) { +if (!inode->i_nlink) { +struct ntfs_inode *ni =NTFS_I (inode); + +if (ni->data_size ==0 ) +return 0 ; + +/* To avoid evict_inode call simultaneously */ +atomic_inc (&inode->i_count); +spin_unlock (&inode->i_lock); + +truncate_setsize (VFS_I (ni),0 ); +ntfs_truncate_vfs (VFS_I (ni),0 ,1 ); + +sb_start_intwrite (inode->i_sb); +i_size_write (inode,0 ); + ni->allocated_size = ni->initialized_size = ni->data_size =0 ; + +truncate_inode_pages_final (inode->i_mapping); +sb_end_intwrite (inode->i_sb); + +spin_lock (&inode->i_lock); +atomic_dec (&inode->i_count); + } + } +return 0 ; + } + +return inode_generic_drop (inode); +} + +static inline struct ntfs_inode *ntfs_alloc_extent_inode (void ) { -ntfs_inode *ni; +struct ntfs_inode *ni;ntfs_debug ("Entering." ); ni =kmem_cache_alloc (ntfs_inode_cache,GFP_NOFS );
@@ -338,22 +421,28 @@ static inline ntfs_inode *ntfs_alloc_extent_inode(void)return NULL ; } -static void ntfs_destroy_extent_inode (ntfs_inode *ni) +static void ntfs_destroy_extent_inode (struct ntfs_inode *ni) {ntfs_debug ("Entering." ); -BUG_ON (ni->page); +if (!atomic_dec_and_test (&ni->count)) -BUG (); +WARN_ON (1 ); +if (ni->folio) +folio_put (ni->folio); +kfree (ni->mrec);kmem_cache_free (ntfs_inode_cache, ni); } +static struct lock_class_key attr_inode_mrec_lock_class; +static struct lock_class_key attr_list_inode_mrec_lock_class; +/* * The attribute runlist lock has separate locking rules from the * normal runlist lock, so split the two lock-classes: */ static struct lock_class_key attr_list_rl_lock_class; -/** +/* * __ntfs_init_inode - initialize ntfs specific part of an inode * @sb: super block of mounted volume * @ni: freshly allocated ntfs inode which to initialize
@@ -362,10 +451,8 @@ static struct lock_class_key attr_list_rl_lock_class;* * NOTE: ni->mft_no, ni->state, ni->type, ni->name, and ni->name_len are left * untouched. Make sure to initialize them elsewhere. -* -* Return zero on success and -ENOMEM on error. */ -void __ntfs_init_inode (struct super_block *sb,ntfs_inode *ni) +void __ntfs_init_inode (struct super_block *sb,struct ntfs_inode *ni) {ntfs_debug ("Entering." );rwlock_init (&ni->size_lock);
@@ -375,13 +462,21 @@ void __ntfs_init_inode(struct super_block *sb, ntfs_inode *ni) ni->vol =NTFS_SB (sb);ntfs_init_runlist (&ni->runlist);mutex_init (&ni->mrec_lock); - ni->page =NULL ; - ni->page_ofs =0 ; +if (ni->type ==AT_ATTRIBUTE_LIST ) { +lockdep_set_class (&ni->mrec_lock, + &attr_list_inode_mrec_lock_class); +lockdep_set_class (&ni->runlist.lock, + &attr_list_rl_lock_class); + }else if (NInoAttr (ni)) { +lockdep_set_class (&ni->mrec_lock, + &attr_inode_mrec_lock_class); + } + + ni->folio =NULL ; + ni->folio_ofs =0 ; + ni->mrec =NULL ; ni->attr_list_size =0 ; ni->attr_list =NULL ; -ntfs_init_runlist (&ni->attr_list_rl); -lockdep_set_class (&ni->attr_list_rl.lock, - &attr_list_rl_lock_class); ni->itype.index.block_size =0 ; ni->itype.index.vcn_size =0 ; ni->itype.index.collation_rule =0 ;
@@ -390,6 +485,11 @@ void __ntfs_init_inode(struct super_block *sb, ntfs_inode *ni)mutex_init (&ni->extent_lock); ni->nr_extents =0 ; ni->ext.base_ntfs_ino =NULL ; + ni->flags =0 ; + ni->mft_lcn[0 ] =LCN_RL_NOT_MAPPED ; + ni->mft_lcn_count =0 ; + ni->target =NULL ; + ni->i_dealloc_clusters =0 ; }/*
@@ -399,10 +499,10 @@ void __ntfs_init_inode(struct super_block *sb, ntfs_inode *ni)*/ static struct lock_class_key extent_inode_mrec_lock_key; -inline ntfs_inode *ntfs_new_extent_inode (struct super_block *sb, +inline struct ntfs_inode *ntfs_new_extent_inode (struct super_block *sb,unsigned long mft_no) { -ntfs_inode *ni =ntfs_alloc_extent_inode (); +struct ntfs_inode *ni =ntfs_alloc_extent_inode ();ntfs_debug ("Entering." );if (likely (ni !=NULL )) {
@@ -416,7 +516,7 @@ inline ntfs_inode *ntfs_new_extent_inode(struct super_block *sb,return ni; } -/** +/* * ntfs_is_extended_system_file - check if a file is in the $Extend directory * @ctx: initialized attribute search context *
@@ -425,11 +525,13 @@ inline ntfs_inode *ntfs_new_extent_inode(struct super_block *sb,* directory. * * Return values: +* 3: file is $ObjId in $Extend directory +* 2: file is $Reparse in $Extend directory * 1: file is in $Extend directory * 0: file is not in $Extend directory * -errno: failed to determine if the file is in the $Extend directory */ -static int ntfs_is_extended_system_file (ntfs_attr_search_ctx *ctx) +static int ntfs_is_extended_system_file (struct ntfs_attr_search_ctx *ctx) {int nr_links, err;
@@ -442,8 +544,8 @@ static int ntfs_is_extended_system_file(ntfs_attr_search_ctx *ctx)/* Loop through all hard links. */ while (!(err =ntfs_attr_lookup (AT_FILE_NAME ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx))) { -FILE_NAME_ATTR *file_name_attr; -ATTR_RECORD *attr = ctx->attr; +struct file_name_attr *file_name_attr; +struct attr_record *attr = ctx->attr;u8 *p, *p2; nr_links--;
@@ -451,51 +553,96 @@ static int ntfs_is_extended_system_file(ntfs_attr_search_ctx *ctx)* Maximum sanity checking as we are called on an inode that * we suspect might be corrupt. */ - p = (u8 *)attr +le32_to_cpu (attr->length); -if (p < (u8 *)ctx->mrec || (u8 *)p > (u8 *)ctx->mrec + + p = (u8 *)attr +le32_to_cpu (attr->length); +if (p < (u8 *)ctx->mrec || (u8 *)p > (u8 *)ctx->mrec +le32_to_cpu (ctx->mrec->bytes_in_use)) { err_corrupt_attr: -ntfs_error (ctx->ntfs_ino->vol->sb,"Corrupt file name " -"attribute. You should run chkdsk." ); +ntfs_error (ctx->ntfs_ino->vol->sb, +"Corrupt file name attribute. You should run chkdsk." );return -EIO ; }if (attr->non_resident) { -ntfs_error (ctx->ntfs_ino->vol->sb,"Non-resident file " -"name. You should run chkdsk." ); +ntfs_error (ctx->ntfs_ino->vol->sb, +"Non-resident file name. You should run chkdsk." );return -EIO ; }if (attr->flags) { -ntfs_error (ctx->ntfs_ino->vol->sb,"File name with " -"invalid flags. You should run " -"chkdsk." ); +ntfs_error (ctx->ntfs_ino->vol->sb, +"File name with invalid flags. You should run chkdsk." );return -EIO ; }if (!(attr->data.resident.flags &RESIDENT_ATTR_IS_INDEXED )) { -ntfs_error (ctx->ntfs_ino->vol->sb,"Unindexed file " -"name. You should run chkdsk." ); +ntfs_error (ctx->ntfs_ino->vol->sb, +"Unindexed file name. You should run chkdsk." );return -EIO ; } - file_name_attr = (FILE_NAME_ATTR *)((u8 *)attr + + file_name_attr = (struct file_name_attr *)((u8 *)attr +le16_to_cpu (attr->data.resident.value_offset)); p2 = (u8 *)file_name_attr +le32_to_cpu (attr->data.resident.value_length); -if (p2 < (u8 *)attr || p2 > p) +if (p2 < (u8 *)attr || p2 > p) goto err_corrupt_attr;/* This attribute is ok, but is it in the $Extend directory? */ -if (MREF_LE (file_name_attr->parent_directory) == FILE_Extend) +if (MREF_LE (file_name_attr->parent_directory) == FILE_Extend) { +unsigned char *s; + + s =ntfs_attr_name_get (ctx->ntfs_ino->vol, + file_name_attr->file_name, + file_name_attr->file_name_length); +if (!s) +return 1 ; +if (!strcmp ("$Reparse" , s)) { +ntfs_attr_name_free (&s); +return 2 ;/* it's reparse point file */ + } +if (!strcmp ("$ObjId" , s)) { +ntfs_attr_name_free (&s); +return 3 ;/* it's object id file */ + } +ntfs_attr_name_free (&s);return 1 ;/* YES, it's an extended system file. */ + } }if (unlikely (err != -ENOENT ))return err;if (unlikely (nr_links)) { -ntfs_error (ctx->ntfs_ino->vol->sb,"Inode hard link count " -"doesn't match number of name attributes. You " -"should run chkdsk." ); +ntfs_error (ctx->ntfs_ino->vol->sb, +"Inode hard link count doesn't match number of name attributes. You should run chkdsk." );return -EIO ; }return 0 ;/* NO, it is not an extended system file. */ } -/** +static struct lock_class_key ntfs_dir_inval_lock_key; + +void ntfs_set_vfs_operations (struct inode *inode,mode_t mode,dev_t dev) +{ +if (S_ISDIR (mode)) { +if (!NInoAttr (NTFS_I (inode))) { + inode->i_op = &ntfs_dir_inode_ops; + inode->i_fop = &ntfs_dir_ops; + } + inode->i_mapping->a_ops = &ntfs_aops; +lockdep_set_class (&inode->i_mapping->invalidate_lock, + &ntfs_dir_inval_lock_key); + }else if (S_ISLNK (mode)) { + inode->i_op = &ntfs_symlink_inode_operations; + inode->i_mapping->a_ops = &ntfs_aops; + }else if (S_ISCHR (mode) ||S_ISBLK (mode) ||S_ISFIFO (mode) ||S_ISSOCK (mode)) { + inode->i_op = &ntfs_special_inode_operations; +init_special_inode (inode, inode->i_mode, dev); + }else { +if (!NInoAttr (NTFS_I (inode))) { + inode->i_op = &ntfs_file_inode_ops; + inode->i_fop = &ntfs_file_ops; + } +if (inode->i_ino ==FILE_MFT ) + inode->i_mapping->a_ops = &ntfs_mft_aops; +else + inode->i_mapping->a_ops = &ntfs_aops; + } +} + +/* * ntfs_read_locked_inode - read an inode from its device * @vi: inode to read *
@@ -518,26 +665,38 @@ static int ntfs_is_extended_system_file(ntfs_attr_search_ctx *ctx)* we need to do that using the IS_* macros defined in include/linux/fs.h. * In any case ntfs_read_locked_inode() has nothing to do with i_flags. * -* Return 0 on success and -errno on error. In the error case, the inode will -* have had make_bad_inode() executed on it. +* Return 0 on success and -errno on error. */ static int ntfs_read_locked_inode (struct inode *vi) { -ntfs_volume *vol =NTFS_SB (vi->i_sb); -ntfs_inode *ni; -struct inode *bvi; -MFT_RECORD *m; -ATTR_RECORD *a; -STANDARD_INFORMATION *si; -ntfs_attr_search_ctx *ctx; +struct ntfs_volume *vol =NTFS_SB (vi->i_sb); +struct ntfs_inode *ni; +struct mft_record *m; +struct attr_record *a; +struct standard_information *si; +struct ntfs_attr_search_ctx *ctx;int err =0 ; +__le16 *name =I30 ; +unsigned int name_len =4 , flags =0 ; +int extend_sys =0 ; +dev_t dev =0 ; +bool vol_err = true;ntfs_debug ("Entering for i_ino 0x%lx." , vi->i_ino); -/* Setup the generic vfs inode parts now. */ - vi->i_uid = vol->uid; - vi->i_gid = vol->gid; - vi->i_mode =0 ; +if (uid_valid (vol->uid)) { + vi->i_uid = vol->uid; + flags |=NTFS_VOL_UID ; + }else + vi->i_uid =GLOBAL_ROOT_UID ; + +if (gid_valid (vol->gid)) { + vi->i_gid = vol->gid; + flags |=NTFS_VOL_GID ; + }else + vi->i_gid =GLOBAL_ROOT_GID ; + + vi->i_mode =0777 ;/* * Initialize the ntfs specific part of @vi special casing
@@ -552,6 +711,7 @@ static int ntfs_read_locked_inode(struct inode *vi) err =PTR_ERR (m); goto err_out; } + ctx =ntfs_attr_get_search_ctx (ni, m);if (!ctx) { err = -ENOMEM ;
@@ -559,9 +719,11 @@ static int ntfs_read_locked_inode(struct inode *vi) }if (!(m->flags &MFT_RECORD_IN_USE )) { -ntfs_error (vi->i_sb,"Inode is not in use!" ); + err = -ENOENT ; + vol_err = false; goto unm_err_out; } +if (m->base_mft_record) {ntfs_error (vi->i_sb,"Inode is an extent inode!" ); goto unm_err_out;
@@ -570,61 +732,28 @@ static int ntfs_read_locked_inode(struct inode *vi)/* Transfer information from mft record into vfs and ntfs inodes. */ vi->i_generation = ni->seq_no =le16_to_cpu (m->sequence_number); -/* -* FIXME: Keep in mind that link_count is two for files which have both -* a long file name and a short file name as separate entries, so if -* we are hiding short file names this will be too high. Either we need -* to account for the short file names by subtracting them or we need -* to make sure we delete files even though i_nlink is not zero which -* might be tricky due to vfs interactions. Need to think about this -* some more when implementing the unlink command. -*/ +if (le16_to_cpu (m->link_count) <1 ) { +ntfs_error (vi->i_sb,"Inode link count is 0!" ); + goto unm_err_out; + }set_nlink (vi,le16_to_cpu (m->link_count)); -/* -* FIXME: Reparse points can have the directory bit set even though -* they would be S_IFLNK. Need to deal with this further below when we -* implement reparse points / symbolic links but it will do for now. -* Also if not a directory, it could be something else, rather than -* a regular file. But again, will do for now. -*/ -/* Everyone gets all permissions. */ - vi->i_mode |=S_IRWXUGO ; +/* If read-only, no one gets write permissions. */ if (IS_RDONLY (vi)) - vi->i_mode &= ~S_IWUGO ; -if (m->flags &MFT_RECORD_IS_DIRECTORY ) { - vi->i_mode |=S_IFDIR ; -/* -* Apply the directory permissions mask set in the mount -* options. -*/ - vi->i_mode &= ~vol->dmask; -/* Things break without this kludge! */ -if (vi->i_nlink >1 ) -set_nlink (vi,1 ); - }else { - vi->i_mode |=S_IFREG ; -/* Apply the file permissions mask set in the mount options. */ - vi->i_mode &= ~vol->fmask; - } + vi->i_mode &= ~0222 ; +/* * Find the standard information attribute in the mft record. At this * stage we haven't setup the attribute list stuff yet, so this could * in fact fail if the standard information is in an extent record, but * I don't think this actually ever happens. */ +ntfs_attr_reinit_search_ctx (ctx); err =ntfs_attr_lookup (AT_STANDARD_INFORMATION ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx);if (unlikely (err)) { -if (err == -ENOENT ) { -/* -* TODO: We should be performing a hot fix here (if the -* recover mount option is set) by creating a new -* attribute. -*/ -ntfs_error (vi->i_sb,"$STANDARD_INFORMATION attribute " -"is missing." ); - } +if (err == -ENOENT ) +ntfs_error (vi->i_sb,"$STANDARD_INFORMATION attribute is missing." ); goto unm_err_out; } a = ctx->attr;
@@ -635,7 +764,7 @@ static int ntfs_read_locked_inode(struct inode *vi)ntfs_error (vi->i_sb,"Corrupt standard information attribute in inode." ); goto unm_err_out; } - si = (STANDARD_INFORMATION *)((u8 *)a + + si = (struct standard_information *)((u8 *)a +le16_to_cpu (a->data.resident.value_offset));/* Transfer information from the standard information into vi. */
@@ -648,6 +777,8 @@ static int ntfs_read_locked_inode(struct inode *vi)* mtime is the last change of the data within the file. Not changed * when only metadata is changed, e.g. a rename doesn't affect mtime. */ + ni->i_crtime =ntfs2utc (si->creation_time); +inode_set_mtime_to_ts (vi,ntfs2utc (si->last_data_change_time));/* * ctime is the last change of the metadata of the file. This obviously
@@ -660,135 +791,143 @@ static int ntfs_read_locked_inode(struct inode *vi)* for example but changed whenever the file is written to. */ inode_set_atime_to_ts (vi,ntfs2utc (si->last_access_time)); + ni->flags = si->file_attributes;/* Find the attribute list attribute if present. */ ntfs_attr_reinit_search_ctx (ctx); err =ntfs_attr_lookup (AT_ATTRIBUTE_LIST ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx);if (err) {if (unlikely (err != -ENOENT )) { -ntfs_error (vi->i_sb,"Failed to lookup attribute list " -"attribute." ); +ntfs_error (vi->i_sb,"Failed to lookup attribute list attribute." ); goto unm_err_out; } - }else /* if (!err) */ { + }else {if (vi->i_ino ==FILE_MFT ) goto skip_attr_list_load;ntfs_debug ("Attribute list found in inode 0x%lx." , vi->i_ino);NInoSetAttrList (ni); a = ctx->attr;if (a->flags &ATTR_COMPRESSION_MASK ) { -ntfs_error (vi->i_sb,"Attribute list attribute is " -"compressed." ); +ntfs_error (vi->i_sb, +"Attribute list attribute is compressed." ); goto unm_err_out; }if (a->flags &ATTR_IS_ENCRYPTED || a->flags &ATTR_IS_SPARSE ) {if (a->non_resident) { -ntfs_error (vi->i_sb,"Non-resident attribute " -"list attribute is encrypted/" -"sparse." ); +ntfs_error (vi->i_sb, +"Non-resident attribute list attribute is encrypted/sparse." ); goto unm_err_out; } -ntfs_warning (vi->i_sb,"Resident attribute list " -"attribute in inode 0x%lx is marked " -"encrypted/sparse which is not true. " -"However, Windows allows this and " -"chkdsk does not detect or correct it " -"so we will just ignore the invalid " -"flags and pretend they are not set." , - vi->i_ino); +ntfs_warning (vi->i_sb, +"Resident attribute list attribute in inode 0x%lx is marked encrypted/sparse which is not true. However, Windows allows this and chkdsk does not detect or correct it so we will just ignore the invalid flags and pretend they are not set." , + vi->i_ino); }/* Now allocate memory for the attribute list. */ ni->attr_list_size = (u32 )ntfs_attr_size (a); - ni->attr_list =ntfs_malloc_nofs (ni->attr_list_size); +if (!ni->attr_list_size) { +ntfs_error (vi->i_sb,"Attr_list_size is zero" ); + goto unm_err_out; + } + ni->attr_list =kvzalloc (ni->attr_list_size,GFP_NOFS );if (!ni->attr_list) { -ntfs_error (vi->i_sb,"Not enough memory to allocate " -"buffer for attribute list." ); +ntfs_error (vi->i_sb, +"Not enough memory to allocate buffer for attribute list." ); err = -ENOMEM ; goto unm_err_out; }if (a->non_resident) {NInoSetAttrListNonResident (ni);if (a->data.non_resident.lowest_vcn) { -ntfs_error (vi->i_sb,"Attribute list has non " -"zero lowest_vcn." ); - goto unm_err_out; - } -/* -* Setup the runlist. No need for locking as we have -* exclusive access to the inode at this time. -*/ - ni->attr_list_rl.rl =ntfs_mapping_pairs_decompress (vol, - a,NULL ); -if (IS_ERR (ni->attr_list_rl.rl)) { - err =PTR_ERR (ni->attr_list_rl.rl); - ni->attr_list_rl.rl =NULL ; -ntfs_error (vi->i_sb,"Mapping pairs " -"decompression failed." ); +ntfs_error (vi->i_sb,"Attribute list has non zero lowest_vcn." ); goto unm_err_out; } +/* Now load the attribute list. */ -if ((err =load_attribute_list (vol, &ni->attr_list_rl, - ni->attr_list, ni->attr_list_size, -sle64_to_cpu (a->data.non_resident. - initialized_size)))) { -ntfs_error (vi->i_sb,"Failed to load " -"attribute list attribute." ); + err =load_attribute_list (ni, ni->attr_list, ni->attr_list_size); +if (err) { +ntfs_error (vi->i_sb,"Failed to load attribute list attribute." ); goto unm_err_out; } }else /* if (!a->non_resident) */ { -if ((u8 *)a +le16_to_cpu (a->data.resident.value_offset) +if ((u8 *)a +le16_to_cpu (a->data.resident.value_offset) +le32_to_cpu ( a->data.resident.value_length) > - (u8 *)ctx->mrec + vol->mft_record_size) { -ntfs_error (vi->i_sb,"Corrupt attribute list " -"in inode." ); + (u8 *)ctx->mrec + vol->mft_record_size) { +ntfs_error (vi->i_sb,"Corrupt attribute list in inode." ); goto unm_err_out; }/* Now copy the attribute list. */ -memcpy (ni->attr_list, (u8 *)a +le16_to_cpu ( +memcpy (ni->attr_list, (u8 *)a +le16_to_cpu ( a->data.resident.value_offset),le32_to_cpu ( a->data.resident.value_length)); } } skip_attr_list_load: + err =ntfs_attr_lookup (AT_EA_INFORMATION ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx); +if (!err) +NInoSetHasEA (ni); + +ntfs_ea_get_wsl_inode (vi, &dev, flags); + +if (m->flags &MFT_RECORD_IS_DIRECTORY ) { + vi->i_mode |=S_IFDIR ; +/* +* Apply the directory permissions mask set in the mount +* options. +*/ + vi->i_mode &= ~vol->dmask; +/* Things break without this kludge! */ +if (vi->i_nlink >1 ) +set_nlink (vi,1 ); + }else { +if (ni->flags &FILE_ATTR_REPARSE_POINT ) { +unsigned int mode; + + mode =ntfs_make_symlink (ni); +if (mode) + vi->i_mode |= mode; +else { + vi->i_mode &= ~S_IFLNK ; + vi->i_mode |=S_IFREG ; + } + }else + vi->i_mode |=S_IFREG ; +/* Apply the file permissions mask set in the mount options. */ + vi->i_mode &= ~vol->fmask; + } +/* * If an attribute list is present we now have the attribute list value * in ntfs_ino->attr_list and it is ntfs_ino->attr_list_size bytes. */ if (S_ISDIR (vi->i_mode)) { -loff_t bvi_size; -ntfs_inode *bni; -INDEX_ROOT *ir; +struct index_root *ir;u8 *ir_end, *index_end; +view_index_meta:/* It is a directory, find index root attribute. */ ntfs_attr_reinit_search_ctx (ctx); - err =ntfs_attr_lookup (AT_INDEX_ROOT ,I30 ,4 ,CASE_SENSITIVE , + err =ntfs_attr_lookup (AT_INDEX_ROOT , name, name_len,CASE_SENSITIVE ,0 ,NULL ,0 , ctx);if (unlikely (err)) { -if (err == -ENOENT ) { -// FIXME: File is corrupt! Hot-fix with empty -// index root attribute if recovery option is -// set. -ntfs_error (vi->i_sb,"$INDEX_ROOT attribute " -"is missing." ); - } +if (err == -ENOENT ) +ntfs_error (vi->i_sb,"$INDEX_ROOT attribute is missing." ); goto unm_err_out; } a = ctx->attr;/* Set up the state. */ if (unlikely (a->non_resident)) { -ntfs_error (vol->sb,"$INDEX_ROOT attribute is not " -"resident." ); +ntfs_error (vol->sb, +"$INDEX_ROOT attribute is not resident." ); goto unm_err_out; }/* Ensure the attribute name is placed before the value. */ if (unlikely (a->name_length && (le16_to_cpu (a->name_offset) >=le16_to_cpu (a->data.resident.value_offset)))) { -ntfs_error (vol->sb,"$INDEX_ROOT attribute name is " -"placed after the attribute value." ); +ntfs_error (vol->sb, +"$INDEX_ROOT attribute name is placed after the attribute value." ); goto unm_err_out; }/*
@@ -797,66 +936,75 @@ static int ntfs_read_locked_inode(struct inode *vi)* encrypted. However index root cannot be both compressed and * encrypted. */ -if (a->flags &ATTR_COMPRESSION_MASK ) +if (a->flags &ATTR_COMPRESSION_MASK ) {NInoSetCompressed (ni); + ni->flags |=FILE_ATTR_COMPRESSED ; + }if (a->flags &ATTR_IS_ENCRYPTED ) {if (a->flags &ATTR_COMPRESSION_MASK ) { -ntfs_error (vi->i_sb,"Found encrypted and " -"compressed attribute." ); +ntfs_error (vi->i_sb,"Found encrypted and compressed attribute." ); goto unm_err_out; }NInoSetEncrypted (ni); + ni->flags |=FILE_ATTR_ENCRYPTED ; } -if (a->flags &ATTR_IS_SPARSE ) +if (a->flags &ATTR_IS_SPARSE ) {NInoSetSparse (ni); - ir = (INDEX_ROOT *)((u8 *)a + + ni->flags |=FILE_ATTR_SPARSE_FILE ; + } + ir = (struct index_root *)((u8 *)a +le16_to_cpu (a->data.resident.value_offset)); - ir_end = (u8 *)ir +le32_to_cpu (a->data.resident.value_length); -if (ir_end > (u8 *)ctx->mrec + vol->mft_record_size) { -ntfs_error (vi->i_sb,"$INDEX_ROOT attribute is " -"corrupt." ); + ir_end = (u8 *)ir +le32_to_cpu (a->data.resident.value_length); +if (ir_end > (u8 *)ctx->mrec + vol->mft_record_size) { +ntfs_error (vi->i_sb,"$INDEX_ROOT attribute is corrupt." ); goto unm_err_out; } - index_end = (u8 *)&ir->index + + index_end = (u8 *)&ir->index +le32_to_cpu (ir->index.index_length);if (index_end > ir_end) {ntfs_error (vi->i_sb,"Directory index is corrupt." ); goto unm_err_out; } -if (ir->type !=AT_FILE_NAME ) { -ntfs_error (vi->i_sb,"Indexed attribute is not " -"$FILE_NAME." ); - goto unm_err_out; - } -if (ir->collation_rule !=COLLATION_FILE_NAME ) { -ntfs_error (vi->i_sb,"Index collation rule is not " -"COLLATION_FILE_NAME." ); - goto unm_err_out; + +if (extend_sys) { +if (ir->type) { +ntfs_error (vi->i_sb,"Indexed attribute is not zero." ); + goto unm_err_out; + } + }else { +if (ir->type !=AT_FILE_NAME ) { +ntfs_error (vi->i_sb,"Indexed attribute is not $FILE_NAME." ); + goto unm_err_out; + } + +if (ir->collation_rule !=COLLATION_FILE_NAME ) { +ntfs_error (vi->i_sb, +"Index collation rule is not COLLATION_FILE_NAME." ); + goto unm_err_out; + } } + ni->itype.index.collation_rule = ir->collation_rule; ni->itype.index.block_size =le32_to_cpu (ir->index_block_size);if (ni->itype.index.block_size & (ni->itype.index.block_size -1 )) { -ntfs_error (vi->i_sb,"Index block size (%u) is not a " -"power of two." , +ntfs_error (vi->i_sb,"Index block size (%u) is not a power of two." , ni->itype.index.block_size); goto unm_err_out; }if (ni->itype.index.block_size >PAGE_SIZE ) { -ntfs_error (vi->i_sb,"Index block size (%u) > " -"PAGE_SIZE (%ld) is not " -"supported. Sorry." , - ni->itype.index.block_size, -PAGE_SIZE ); +ntfs_error (vi->i_sb, +"Index block size (%u) > PAGE_SIZE (%ld) is not supported." , + ni->itype.index.block_size, +PAGE_SIZE ); err = -EOPNOTSUPP ; goto unm_err_out; }if (ni->itype.index.block_size <NTFS_BLOCK_SIZE ) { -ntfs_error (vi->i_sb,"Index block size (%u) < " -"NTFS_BLOCK_SIZE (%i) is not " -"supported. Sorry." , - ni->itype.index.block_size, -NTFS_BLOCK_SIZE ); +ntfs_error (vi->i_sb, +"Index block size (%u) < NTFS_BLOCK_SIZE (%i) is not supported." , + ni->itype.index.block_size, +NTFS_BLOCK_SIZE ); err = -EOPNOTSUPP ; goto unm_err_out; }
@@ -872,127 +1020,28 @@ static int ntfs_read_locked_inode(struct inode *vi) }/* Setup the index allocation attribute, even if not present. */ -NInoSetMstProtected (ni); - ni->type =AT_INDEX_ALLOCATION ; - ni->name =I30 ; - ni->name_len =4 ; - -if (!(ir->index.flags &LARGE_INDEX )) { -/* No index allocation. */ - vi->i_size = ni->initialized_size = - ni->allocated_size =0 ; -/* We are done with the mft record, so we release it. */ -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (ni); - m =NULL ; - ctx =NULL ; - goto skip_large_dir_stuff; - }/* LARGE_INDEX: Index allocation present. Setup state. */ -NInoSetIndexAllocPresent (ni); -/* Find index allocation attribute. */ -ntfs_attr_reinit_search_ctx (ctx); - err =ntfs_attr_lookup (AT_INDEX_ALLOCATION ,I30 ,4 , -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION " -"attribute is not present but " -"$INDEX_ROOT indicated it is." ); -else -ntfs_error (vi->i_sb,"Failed to lookup " -"$INDEX_ALLOCATION " -"attribute." ); - goto unm_err_out; - } - a = ctx->attr; -if (!a->non_resident) { -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute " -"is resident." ); - goto unm_err_out; - } -/* -* Ensure the attribute name is placed before the mapping pairs -* array. -*/ -if (unlikely (a->name_length && (le16_to_cpu (a->name_offset) >= -le16_to_cpu ( - a->data.non_resident.mapping_pairs_offset)))) { -ntfs_error (vol->sb,"$INDEX_ALLOCATION attribute name " -"is placed after the mapping pairs " -"array." ); - goto unm_err_out; - } -if (a->flags &ATTR_IS_ENCRYPTED ) { -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute " -"is encrypted." ); - goto unm_err_out; - } -if (a->flags &ATTR_IS_SPARSE ) { -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute " -"is sparse." ); - goto unm_err_out; - } -if (a->flags &ATTR_COMPRESSION_MASK ) { -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute " -"is compressed." ); - goto unm_err_out; - } -if (a->data.non_resident.lowest_vcn) { -ntfs_error (vi->i_sb,"First extent of " -"$INDEX_ALLOCATION attribute has non " -"zero lowest_vcn." ); - goto unm_err_out; - } - vi->i_size =sle64_to_cpu (a->data.non_resident.data_size); - ni->initialized_size =sle64_to_cpu ( - a->data.non_resident.initialized_size); - ni->allocated_size =sle64_to_cpu ( - a->data.non_resident.allocated_size); -/* -* We are done with the mft record, so we release it. Otherwise -* we would deadlock in ntfs_attr_iget(). -*/ + ni->type =AT_INDEX_ROOT ; + ni->name = name; + ni->name_len = name_len; + vi->i_size = ni->initialized_size = ni->data_size = +le32_to_cpu (a->data.resident.value_length); + ni->allocated_size = (ni->data_size +7 ) & ~7 ; +/* We are done with the mft record, so we release it. */ ntfs_attr_put_search_ctx (ctx);unmap_mft_record (ni); m =NULL ; ctx =NULL ; -/* Get the index bitmap attribute inode. */ - bvi =ntfs_attr_iget (vi,AT_BITMAP ,I30 ,4 ); -if (IS_ERR (bvi)) { -ntfs_error (vi->i_sb,"Failed to get bitmap attribute." ); - err =PTR_ERR (bvi); - goto unm_err_out; - } - bni =NTFS_I (bvi); -if (NInoCompressed (bni) ||NInoEncrypted (bni) || -NInoSparse (bni)) { -ntfs_error (vi->i_sb,"$BITMAP attribute is compressed " -"and/or encrypted and/or sparse." ); - goto iput_unm_err_out; - } -/* Consistency check bitmap size vs. index allocation size. */ - bvi_size =i_size_read (bvi); -if ((bvi_size <<3 ) < (vi->i_size >> - ni->itype.index.block_size_bits)) { -ntfs_error (vi->i_sb,"Index bitmap too small (0x%llx) " -"for index allocation (0x%llx)." , - bvi_size <<3 , vi->i_size); - goto iput_unm_err_out; - } -/* No longer need the bitmap attribute inode. */ -iput (bvi); -skip_large_dir_stuff:/* Setup the operations for this inode. */ - vi->i_op = &ntfs_dir_inode_ops; - vi->i_fop = &ntfs_dir_ops; - vi->i_mapping->a_ops = &ntfs_mst_aops; +ntfs_set_vfs_operations (vi,S_IFDIR ,0 ); +if (ir->index.flags &LARGE_INDEX ) +NInoSetIndexAllocPresent (ni); }else {/* It is a file. */ ntfs_attr_reinit_search_ctx (ctx);/* Setup the data attribute, even if not present. */ ni->type =AT_DATA ; - ni->name =NULL ; + ni->name =AT_UNNAMED ; ni->name_len =0 ;/* Find first extent of the unnamed data attribute. */
@@ -1001,8 +1050,7 @@ static int ntfs_read_locked_inode(struct inode *vi) vi->i_size = ni->initialized_size = ni->allocated_size =0 ;if (err != -ENOENT ) { -ntfs_error (vi->i_sb,"Failed to lookup $DATA " -"attribute." ); +ntfs_error (vi->i_sb,"Failed to lookup $DATA attribute." ); goto unm_err_out; }/*
@@ -1020,11 +1068,24 @@ static int ntfs_read_locked_inode(struct inode *vi)* name of this inode from the mft record as the name * contains the back reference to the parent directory. */ -if (ntfs_is_extended_system_file (ctx) >0 ) + extend_sys =ntfs_is_extended_system_file (ctx); +if (extend_sys >0 ) { +if (m->flags &MFT_RECORD_IS_VIEW_INDEX ) { +if (extend_sys ==2 ) { + name = reparse_index_name; + name_len =2 ; + goto view_index_meta; + }else if (extend_sys ==3 ) { + name = objid_index_name; + name_len =2 ; + goto view_index_meta; + } + } goto no_data_attr_special_case; -// FIXME: File is corrupt! Hot-fix with empty data -// attribute if recovery option is set. -ntfs_error (vi->i_sb,"$DATA attribute is missing." ); + } + + err = extend_sys; +ntfs_error (vi->i_sb,"$DATA attribute is missing, err : %d" , err); goto unm_err_out; } a = ctx->attr;
@@ -1032,63 +1093,66 @@ static int ntfs_read_locked_inode(struct inode *vi)if (a->flags & (ATTR_COMPRESSION_MASK |ATTR_IS_SPARSE )) {if (a->flags &ATTR_COMPRESSION_MASK ) {NInoSetCompressed (ni); + ni->flags |=FILE_ATTR_COMPRESSED ;if (vol->cluster_size >4096 ) { -ntfs_error (vi->i_sb,"Found " -"compressed data but " -"compression is " -"disabled due to " -"cluster size (%i) > " -"4kiB." , - vol->cluster_size); +ntfs_error (vi->i_sb, +"Found compressed data but compression is disabled due to cluster size (%i) > 4kiB." , + vol->cluster_size); goto unm_err_out; }if ((a->flags &ATTR_COMPRESSION_MASK ) !=ATTR_IS_COMPRESSED ) { -ntfs_error (vi->i_sb,"Found unknown " -"compression method " -"or corrupt file." ); +ntfs_error (vi->i_sb, +"Found unknown compression method or corrupt file." ); goto unm_err_out; } } -if (a->flags &ATTR_IS_SPARSE ) +if (a->flags &ATTR_IS_SPARSE ) {NInoSetSparse (ni); + ni->flags |=FILE_ATTR_SPARSE_FILE ; + } }if (a->flags &ATTR_IS_ENCRYPTED ) {if (NInoCompressed (ni)) { -ntfs_error (vi->i_sb,"Found encrypted and " -"compressed data." ); +ntfs_error (vi->i_sb,"Found encrypted and compressed data." ); goto unm_err_out; }NInoSetEncrypted (ni); + ni->flags |=FILE_ATTR_ENCRYPTED ; }if (a->non_resident) {NInoSetNonResident (ni);if (NInoCompressed (ni) ||NInoSparse (ni)) { -if (NInoCompressed (ni) && a->data.non_resident. - compression_unit !=4 ) { -ntfs_error (vi->i_sb,"Found " -"non-standard " -"compression unit (%u " -"instead of 4). " -"Cannot handle this." , - a->data.non_resident. - compression_unit); +if (NInoCompressed (ni) && + a->data.non_resident.compression_unit !=4 ) { +ntfs_error (vi->i_sb, +"Found non-standard compression unit (%u instead of 4). Cannot handle this." , + a->data.non_resident.compression_unit); + err = -EOPNOTSUPP ; + goto unm_err_out; + } + +if (NInoSparse (ni) && + a->data.non_resident.compression_unit && + a->data.non_resident.compression_unit != + vol->sparse_compression_unit) { +ntfs_error (vi->i_sb, +"Found non-standard compression unit (%u instead of 0 or %d). Cannot handle this." , + a->data.non_resident.compression_unit, + vol->sparse_compression_unit); err = -EOPNOTSUPP ; goto unm_err_out; } + +if (a->data.non_resident.compression_unit) { ni->itype.compressed.block_size =1U << - (a->data.non_resident. - compression_unit + + (a->data.non_resident.compression_unit + vol->cluster_size_bits); ni->itype.compressed.block_size_bits = -ffs (ni->itype. - compressed. - block_size) -1 ; +ffs (ni->itype.compressed.block_size) -1 ; ni->itype.compressed.block_clusters = -1U << a->data. - non_resident. - compression_unit; +1U << a->data.non_resident.compression_unit; }else { ni->itype.compressed.block_size =0 ; ni->itype.compressed.block_size_bits =
@@ -1096,32 +1160,26 @@ static int ntfs_read_locked_inode(struct inode *vi) ni->itype.compressed.block_clusters =0 ; } - ni->itype.compressed.size =sle64_to_cpu ( - a->data.non_resident. - compressed_size); + ni->itype.compressed.size =le64_to_cpu ( + a->data.non_resident.compressed_size); }if (a->data.non_resident.lowest_vcn) { -ntfs_error (vi->i_sb,"First extent of $DATA " -"attribute has non zero " -"lowest_vcn." ); +ntfs_error (vi->i_sb, +"First extent of $DATA attribute has non zero lowest_vcn." ); goto unm_err_out; } - vi->i_size =sle64_to_cpu ( - a->data.non_resident.data_size); - ni->initialized_size =sle64_to_cpu ( - a->data.non_resident.initialized_size); - ni->allocated_size =sle64_to_cpu ( - a->data.non_resident.allocated_size); + vi->i_size = ni->data_size =le64_to_cpu (a->data.non_resident.data_size); + ni->initialized_size =le64_to_cpu (a->data.non_resident.initialized_size); + ni->allocated_size =le64_to_cpu (a->data.non_resident.allocated_size); }else {/* Resident attribute. */ - vi->i_size = ni->initialized_size =le32_to_cpu ( + vi->i_size = ni->data_size = ni->initialized_size =le32_to_cpu ( a->data.resident.value_length); ni->allocated_size =le32_to_cpu (a->length) -le16_to_cpu ( a->data.resident.value_offset);if (vi->i_size > ni->allocated_size) { -ntfs_error (vi->i_sb,"Resident data attribute " -"is corrupt (size exceeds " -"allocation)." ); +ntfs_error (vi->i_sb, +"Resident data attribute is corrupt (size exceeds allocation)." ); goto unm_err_out; } }
@@ -1132,14 +1190,13 @@ static int ntfs_read_locked_inode(struct inode *vi) m =NULL ; ctx =NULL ;/* Setup the operations for this inode. */ - vi->i_op = &ntfs_file_inode_ops; - vi->i_fop = &ntfs_file_ops; - vi->i_mapping->a_ops = &ntfs_normal_aops; -if (NInoMstProtected (ni)) - vi->i_mapping->a_ops = &ntfs_mst_aops; -else if (NInoCompressed (ni)) - vi->i_mapping->a_ops = &ntfs_compressed_aops; +ntfs_set_vfs_operations (vi, vi->i_mode, dev); } + +if (NVolSysImmutable (vol) && (ni->flags &FILE_ATTR_SYSTEM ) && + !S_ISFIFO (vi->i_mode) && !S_ISSOCK (vi->i_mode) && !S_ISLNK (vi->i_mode)) + vi->i_flags |=S_IMMUTABLE ; +/* * The number of 512-byte blocks used on disk (for stat). This is in so * far inaccurate as it doesn't account for any named streams or other
@@ -1155,10 +1212,9 @@ static int ntfs_read_locked_inode(struct inode *vi) vi->i_blocks = ni->itype.compressed.size >>9 ; else vi->i_blocks = ni->allocated_size >> 9; +ntfs_debug ("Done." );return 0 ; -iput_unm_err_out: -iput (bvi); unm_err_out:if (!err) err = -EIO ;
@@ -1167,15 +1223,16 @@ static int ntfs_read_locked_inode(struct inode *vi)if (m)unmap_mft_record (ni); err_out: -ntfs_error (vol->sb,"Failed with error code %i. Marking corrupt " -"inode 0x%lx as bad. Run chkdsk." , err, vi->i_ino); -make_bad_inode (vi); -if (err != -EOPNOTSUPP && err != -ENOMEM ) +if (err != -EOPNOTSUPP && err != -ENOMEM && vol_err == true) { +ntfs_error (vol->sb, +"Failed with error code %i. Marking corrupt inode 0x%lx as bad. Run chkdsk." , + err, vi->i_ino);NVolSetErrors (vol); + }return err; } -/** +/* * ntfs_read_locked_attr_inode - read an attribute inode from its base inode * @base_vi: base inode * @vi: attribute inode to read
@@ -1192,27 +1249,23 @@ static int ntfs_read_locked_inode(struct inode *vi)* A: i_state has I_NEW set, hence the inode is locked, also * i_count is set to 1, so it is not going to go away * -* Return 0 on success and -errno on error. In the error case, the inode will -* have had make_bad_inode() executed on it. +* Return 0 on success and -errno on error. * * Note this cannot be called for AT_INDEX_ALLOCATION. */ static int ntfs_read_locked_attr_inode (struct inode *base_vi,struct inode *vi) { -ntfs_volume *vol =NTFS_SB (vi->i_sb); -ntfs_inode *ni, *base_ni; -MFT_RECORD *m; -ATTR_RECORD *a; -ntfs_attr_search_ctx *ctx; +struct ntfs_volume *vol =NTFS_SB (vi->i_sb); +struct ntfs_inode *ni =NTFS_I (vi), *base_ni =NTFS_I (base_vi); +struct mft_record *m; +struct attr_record *a; +struct ntfs_attr_search_ctx *ctx;int err =0 ;ntfs_debug ("Entering for i_ino 0x%lx." , vi->i_ino);ntfs_init_big_inode (vi); - ni =NTFS_I (vi); - base_ni =NTFS_I (base_vi); -/* Just mirror the values from the base inode. */ vi->i_uid = base_vi->i_uid; vi->i_gid = base_vi->i_gid;
@@ -1244,28 +1297,22 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)if (a->flags & (ATTR_COMPRESSION_MASK |ATTR_IS_SPARSE )) {if (a->flags &ATTR_COMPRESSION_MASK ) {NInoSetCompressed (ni); + ni->flags |=FILE_ATTR_COMPRESSED ;if ((ni->type !=AT_DATA ) || (ni->type ==AT_DATA && ni->name_len)) { -ntfs_error (vi->i_sb,"Found compressed " -"non-data or named data " -"attribute. Please report " -"you saw this message to " -"linux-ntfs-dev@lists." -"sourceforge.net" ); +ntfs_error (vi->i_sb, +"Found compressed non-data or named data attribute." ); goto unm_err_out; }if (vol->cluster_size >4096 ) { -ntfs_error (vi->i_sb,"Found compressed " -"attribute but compression is " -"disabled due to cluster size " -"(%i) > 4kiB." , - vol->cluster_size); +ntfs_error (vi->i_sb, +"Found compressed attribute but compression is disabled due to cluster size (%i) > 4kiB." , + vol->cluster_size); goto unm_err_out; }if ((a->flags &ATTR_COMPRESSION_MASK ) !=ATTR_IS_COMPRESSED ) { -ntfs_error (vi->i_sb,"Found unknown " -"compression method." ); +ntfs_error (vi->i_sb,"Found unknown compression method." ); goto unm_err_out; } }
@@ -1274,21 +1321,19 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)* to compress all files. */ if (NInoMstProtected (ni) && ni->type !=AT_INDEX_ROOT ) { -ntfs_error (vi->i_sb,"Found mst protected attribute " -"but the attribute is %s. Please " -"report you saw this message to " -"[email protected]" , -NInoCompressed (ni) ?"compressed" : -"sparse" ); +ntfs_error (vi->i_sb, +"Found mst protected attribute but the attribute is %s." , +NInoCompressed (ni) ?"compressed" :"sparse" ); goto unm_err_out; } -if (a->flags &ATTR_IS_SPARSE ) +if (a->flags &ATTR_IS_SPARSE ) {NInoSetSparse (ni); + ni->flags |=FILE_ATTR_SPARSE_FILE ; + } }if (a->flags &ATTR_IS_ENCRYPTED ) {if (NInoCompressed (ni)) { -ntfs_error (vi->i_sb,"Found encrypted and compressed " -"data." ); +ntfs_error (vi->i_sb,"Found encrypted and compressed data." ); goto unm_err_out; }/*
@@ -1296,42 +1341,38 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)* encrypt all files. */ if (NInoMstProtected (ni) && ni->type !=AT_INDEX_ROOT ) { -ntfs_error (vi->i_sb,"Found mst protected attribute " -"but the attribute is encrypted. " -"Please report you saw this message " -"to [email protected]." -"net" ); +ntfs_error (vi->i_sb, +"Found mst protected attribute but the attribute is encrypted." ); goto unm_err_out; }if (ni->type !=AT_DATA ) { -ntfs_error (vi->i_sb,"Found encrypted non-data " -"attribute." ); +ntfs_error (vi->i_sb, +"Found encrypted non-data attribute." ); goto unm_err_out; }NInoSetEncrypted (ni); + ni->flags |=FILE_ATTR_ENCRYPTED ; }if (!a->non_resident) {/* Ensure the attribute name is placed before the value. */ if (unlikely (a->name_length && (le16_to_cpu (a->name_offset) >=le16_to_cpu (a->data.resident.value_offset)))) { -ntfs_error (vol->sb,"Attribute name is placed after " -"the attribute value." ); +ntfs_error (vol->sb, +"Attribute name is placed after the attribute value." ); goto unm_err_out; }if (NInoMstProtected (ni)) { -ntfs_error (vi->i_sb,"Found mst protected attribute " -"but the attribute is resident. " -"Please report you saw this message to " -"[email protected]" ); +ntfs_error (vi->i_sb, +"Found mst protected attribute but the attribute is resident." ); goto unm_err_out; } - vi->i_size = ni->initialized_size =le32_to_cpu ( + vi->i_size = ni->initialized_size = ni->data_size =le32_to_cpu ( a->data.resident.value_length); ni->allocated_size =le32_to_cpu (a->length) -le16_to_cpu (a->data.resident.value_offset);if (vi->i_size > ni->allocated_size) { -ntfs_error (vi->i_sb,"Resident attribute is corrupt " -"(size exceeds allocation)." ); +ntfs_error (vi->i_sb, +"Resident attribute is corrupt (size exceeds allocation)." ); goto unm_err_out; } }else {
@@ -1343,56 +1384,43 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)if (unlikely (a->name_length && (le16_to_cpu (a->name_offset) >=le16_to_cpu ( a->data.non_resident.mapping_pairs_offset)))) { -ntfs_error (vol->sb,"Attribute name is placed after " -"the mapping pairs array." ); +ntfs_error (vol->sb, +"Attribute name is placed after the mapping pairs array." ); goto unm_err_out; }if (NInoCompressed (ni) ||NInoSparse (ni)) { -if (NInoCompressed (ni) && a->data.non_resident. - compression_unit !=4 ) { -ntfs_error (vi->i_sb,"Found non-standard " -"compression unit (%u instead " -"of 4). Cannot handle this." , - a->data.non_resident. - compression_unit); +if (NInoCompressed (ni) && a->data.non_resident.compression_unit !=4 ) { +ntfs_error (vi->i_sb, +"Found non-standard compression unit (%u instead of 4). Cannot handle this." , + a->data.non_resident.compression_unit); err = -EOPNOTSUPP ; goto unm_err_out; }if (a->data.non_resident.compression_unit) { ni->itype.compressed.block_size =1U << - (a->data.non_resident. - compression_unit + + (a->data.non_resident.compression_unit + vol->cluster_size_bits); ni->itype.compressed.block_size_bits = -ffs (ni->itype.compressed. - block_size) -1 ; +ffs (ni->itype.compressed.block_size) -1 ; ni->itype.compressed.block_clusters =1U << - a->data.non_resident. - compression_unit; + 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 ; } - ni->itype.compressed.size =sle64_to_cpu ( + ni->itype.compressed.size =le64_to_cpu ( a->data.non_resident.compressed_size); }if (a->data.non_resident.lowest_vcn) { -ntfs_error (vi->i_sb,"First extent of attribute has " -"non-zero lowest_vcn." ); +ntfs_error (vi->i_sb,"First extent of attribute has non-zero lowest_vcn." ); goto unm_err_out; } - vi->i_size =sle64_to_cpu (a->data.non_resident.data_size); - ni->initialized_size =sle64_to_cpu ( - a->data.non_resident.initialized_size); - ni->allocated_size =sle64_to_cpu ( - a->data.non_resident.allocated_size); - } - vi->i_mapping->a_ops = &ntfs_normal_aops; -if (NInoMstProtected (ni)) - vi->i_mapping->a_ops = &ntfs_mst_aops; -else if (NInoCompressed (ni)) - vi->i_mapping->a_ops = &ntfs_compressed_aops; + vi->i_size = ni->data_size =le64_to_cpu (a->data.non_resident.data_size); + ni->initialized_size =le64_to_cpu (a->data.non_resident.initialized_size); + ni->allocated_size =le64_to_cpu (a->data.non_resident.allocated_size); + } + vi->i_mapping->a_ops = &ntfs_aops;if ((NInoCompressed (ni) ||NInoSparse (ni)) && ni->type !=AT_INDEX_ROOT ) vi->i_blocks = ni->itype.compressed.size >>9 ;else
@@ -1401,7 +1429,10 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)* Make sure the base inode does not go away and attach it to the * attribute inode. */ -igrab (base_vi); +if (!igrab (base_vi)) { + err = -ENOENT ; + goto unm_err_out; + } ni->ext.base_ntfs_ino = base_ni; ni->nr_extents =-1 ;
@@ -1418,18 +1449,17 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)ntfs_attr_put_search_ctx (ctx);unmap_mft_record (base_ni); err_out: -ntfs_error (vol->sb,"Failed with error code %i while reading attribute " -"inode (mft_no 0x%lx, type 0x%x, name_len %i). " -"Marking corrupt inode and base inode 0x%lx as bad. " -"Run chkdsk." , err, vi->i_ino, ni->type, ni->name_len, +if (err != -ENOENT ) +ntfs_error (vol->sb, +"Failed with error code %i while reading attribute inode (mft_no 0x%lx, type 0x%x, name_len %i). Marking corrupt inode and base inode 0x%lx as bad. Run chkdsk." , + err, vi->i_ino, ni->type, ni->name_len, base_vi->i_ino); -make_bad_inode (vi); -if (err != -ENOMEM ) +if (err != -ENOENT && err != -ENOMEM )NVolSetErrors (vol);return err; } -/** +/* * ntfs_read_locked_index_inode - read an index inode from its base inode * @base_vi: base inode * @vi: index inode to read
@@ -1459,26 +1489,25 @@ static int ntfs_read_locked_attr_inode(struct inode *base_vi, struct inode *vi)* A: i_state has I_NEW set, hence the inode is locked, also * i_count is set to 1, so it is not going to go away * -* Return 0 on success and -errno on error. In the error case, the inode will -* have had make_bad_inode() executed on it. +* Return 0 on success and -errno on error. */ static int ntfs_read_locked_index_inode (struct inode *base_vi,struct inode *vi) {loff_t bvi_size; -ntfs_volume *vol =NTFS_SB (vi->i_sb); -ntfs_inode *ni, *base_ni, *bni; +struct ntfs_volume *vol =NTFS_SB (vi->i_sb); +struct ntfs_inode *ni =NTFS_I (vi), *base_ni =NTFS_I (base_vi), *bni;struct inode *bvi; -MFT_RECORD *m; -ATTR_RECORD *a; -ntfs_attr_search_ctx *ctx; -INDEX_ROOT *ir; +struct mft_record *m; +struct attr_record *a; +struct ntfs_attr_search_ctx *ctx; +struct index_root *ir;u8 *ir_end, *index_end;int err =0 ;ntfs_debug ("Entering for i_ino 0x%lx." , vi->i_ino); +lockdep_assert_held (&base_ni->mrec_lock); +ntfs_init_big_inode (vi); - ni =NTFS_I (vi); - base_ni =NTFS_I (base_vi);/* Just mirror the values from the base inode. */ vi->i_uid = base_vi->i_uid; vi->i_gid = base_vi->i_gid;
@@ -1505,8 +1534,7 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi) CASE_SENSITIVE, 0, NULL, 0, ctx);if (unlikely (err)) {if (err == -ENOENT ) -ntfs_error (vi->i_sb,"$INDEX_ROOT attribute is " -"missing." ); +ntfs_error (vi->i_sb,"$INDEX_ROOT attribute is missing." ); goto unm_err_out; } a = ctx->attr;
@@ -1518,55 +1546,41 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi)/* Ensure the attribute name is placed before the value. */ if (unlikely (a->name_length && (le16_to_cpu (a->name_offset) >=le16_to_cpu (a->data.resident.value_offset)))) { -ntfs_error (vol->sb,"$INDEX_ROOT attribute name is placed " -"after the attribute value." ); - goto unm_err_out; - } -/* -* Compressed/encrypted/sparse index root is not allowed, except for -* directories of course but those are not dealt with here. -*/ -if (a->flags & (ATTR_COMPRESSION_MASK |ATTR_IS_ENCRYPTED | -ATTR_IS_SPARSE )) { -ntfs_error (vi->i_sb,"Found compressed/encrypted/sparse index " -"root attribute." ); +ntfs_error (vol->sb, +"$INDEX_ROOT attribute name is placed after the attribute value." ); goto unm_err_out; } - ir = (INDEX_ROOT *)((u8 *)a +le16_to_cpu (a->data.resident.value_offset)); - ir_end = (u8 *)ir +le32_to_cpu (a->data.resident.value_length); -if (ir_end > (u8 *)ctx->mrec + vol->mft_record_size) { + + ir = (struct index_root *)((u8 *)a +le16_to_cpu (a->data.resident.value_offset)); + ir_end = (u8 *)ir +le32_to_cpu (a->data.resident.value_length); +if (ir_end > (u8 *)ctx->mrec + vol->mft_record_size) {ntfs_error (vi->i_sb,"$INDEX_ROOT attribute is corrupt." ); goto unm_err_out; } - index_end = (u8 *)&ir->index +le32_to_cpu (ir->index.index_length); + index_end = (u8 *)&ir->index +le32_to_cpu (ir->index.index_length);if (index_end > ir_end) {ntfs_error (vi->i_sb,"Index is corrupt." ); goto unm_err_out; } -if (ir->type) { -ntfs_error (vi->i_sb,"Index type is not 0 (type is 0x%x)." , -le32_to_cpu (ir->type)); - goto unm_err_out; - } + ni->itype.index.collation_rule = ir->collation_rule;ntfs_debug ("Index collation rule is 0x%x." ,le32_to_cpu (ir->collation_rule)); ni->itype.index.block_size =le32_to_cpu (ir->index_block_size);if (!is_power_of_2 (ni->itype.index.block_size)) { -ntfs_error (vi->i_sb,"Index block size (%u) is not a power of " -"two." , ni->itype.index.block_size); +ntfs_error (vi->i_sb,"Index block size (%u) is not a power of two." , + ni->itype.index.block_size); goto unm_err_out; }if (ni->itype.index.block_size >PAGE_SIZE ) { -ntfs_error (vi->i_sb,"Index block size (%u) > PAGE_SIZE " -"(%ld) is not supported. Sorry." , +ntfs_error (vi->i_sb,"Index block size (%u) > PAGE_SIZE (%ld) is not supported." , ni->itype.index.block_size,PAGE_SIZE ); err = -EOPNOTSUPP ; goto unm_err_out; }if (ni->itype.index.block_size <NTFS_BLOCK_SIZE ) { -ntfs_error (vi->i_sb,"Index block size (%u) < NTFS_BLOCK_SIZE " -"(%i) is not supported. Sorry." , +ntfs_error (vi->i_sb, +"Index block size (%u) < NTFS_BLOCK_SIZE (%i) is not supported." , ni->itype.index.block_size,NTFS_BLOCK_SIZE ); err = -EOPNOTSUPP ; goto unm_err_out;
@@ -1580,51 +1594,45 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi) ni->itype.index.vcn_size = vol->sector_size; ni->itype.index.vcn_size_bits = vol->sector_size_bits; } -/* Check for presence of index allocation attribute. */ -if (!(ir->index.flags &LARGE_INDEX )) { -/* No index allocation. */ - vi->i_size = ni->initialized_size = ni->allocated_size =0 ; -/* We are done with the mft record, so we release it. */ -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); - m =NULL ; - ctx =NULL ; - goto skip_large_index_stuff; - }/* LARGE_INDEX: Index allocation present. Setup state. */ -NInoSetIndexAllocPresent (ni); +/* Find index allocation attribute. */ ntfs_attr_reinit_search_ctx (ctx); err =ntfs_attr_lookup (AT_INDEX_ALLOCATION , ni->name, ni->name_len,CASE_SENSITIVE ,0 ,NULL ,0 , ctx);if (unlikely (err)) { -if (err == -ENOENT ) -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute is " -"not present but $INDEX_ROOT " -"indicated it is." ); -else -ntfs_error (vi->i_sb,"Failed to lookup " -"$INDEX_ALLOCATION attribute." ); +if (err == -ENOENT ) { +/* No index allocation. */ + vi->i_size = ni->initialized_size = ni->allocated_size =0 ; +/* We are done with the mft record, so we release it. */ +ntfs_attr_put_search_ctx (ctx); +unmap_mft_record (base_ni); + m =NULL ; + ctx =NULL ; + goto skip_large_index_stuff; + }else +ntfs_error (vi->i_sb,"Failed to lookup $INDEX_ALLOCATION attribute." ); goto unm_err_out; } +NInoSetIndexAllocPresent (ni); +NInoSetNonResident (ni); + ni->type =AT_INDEX_ALLOCATION ; + a = ctx->attr;if (!a->non_resident) { -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute is " -"resident." ); +ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute is resident." ); goto unm_err_out; }/* * Ensure the attribute name is placed before the mapping pairs array. */ if (unlikely (a->name_length && (le16_to_cpu (a->name_offset) >= -le16_to_cpu ( - a->data.non_resident.mapping_pairs_offset)))) { -ntfs_error (vol->sb,"$INDEX_ALLOCATION attribute name is " -"placed after the mapping pairs array." ); +le16_to_cpu (a->data.non_resident.mapping_pairs_offset)))) { +ntfs_error (vol->sb, +"$INDEX_ALLOCATION attribute name is placed after the mapping pairs array." ); goto unm_err_out; }if (a->flags &ATTR_IS_ENCRYPTED ) { -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute is " -"encrypted." ); +ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute is encrypted." ); goto unm_err_out; }if (a->flags &ATTR_IS_SPARSE ) {
@@ -1632,19 +1640,18 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi) goto unm_err_out; }if (a->flags &ATTR_COMPRESSION_MASK ) { -ntfs_error (vi->i_sb,"$INDEX_ALLOCATION attribute is " -"compressed." ); +ntfs_error (vi->i_sb, +"$INDEX_ALLOCATION attribute is compressed." ); goto unm_err_out; }if (a->data.non_resident.lowest_vcn) { -ntfs_error (vi->i_sb,"First extent of $INDEX_ALLOCATION " -"attribute has non zero lowest_vcn." ); +ntfs_error (vi->i_sb, +"First extent of $INDEX_ALLOCATION attribute has non zero lowest_vcn." ); goto unm_err_out; } - vi->i_size =sle64_to_cpu (a->data.non_resident.data_size); - ni->initialized_size =sle64_to_cpu ( - a->data.non_resident.initialized_size); - ni->allocated_size =sle64_to_cpu (a->data.non_resident.allocated_size); + vi->i_size = ni->data_size =le64_to_cpu (a->data.non_resident.data_size); + ni->initialized_size =le64_to_cpu (a->data.non_resident.initialized_size); + ni->allocated_size =le64_to_cpu (a->data.non_resident.allocated_size);/* * We are done with the mft record, so we release it. Otherwise * we would deadlock in ntfs_attr_iget().
@@ -1663,28 +1670,29 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi) bni =NTFS_I (bvi);if (NInoCompressed (bni) ||NInoEncrypted (bni) ||NInoSparse (bni)) { -ntfs_error (vi->i_sb,"$BITMAP attribute is compressed and/or " -"encrypted and/or sparse." ); +ntfs_error (vi->i_sb, +"$BITMAP attribute is compressed and/or encrypted and/or sparse." ); goto iput_unm_err_out; }/* Consistency check bitmap size vs. index allocation size. */ bvi_size =i_size_read (bvi);if ((bvi_size <<3 ) < (vi->i_size >> ni->itype.index.block_size_bits)) { -ntfs_error (vi->i_sb,"Index bitmap too small (0x%llx) for " -"index allocation (0x%llx)." , bvi_size <<3 , - vi->i_size); +ntfs_error (vi->i_sb, +"Index bitmap too small (0x%llx) for index allocation (0x%llx)." , + bvi_size <<3 , vi->i_size); goto iput_unm_err_out; }iput (bvi); skip_large_index_stuff:/* Setup the operations for this index inode. */ - vi->i_mapping->a_ops = &ntfs_mst_aops; +ntfs_set_vfs_operations (vi,S_IFDIR ,0 ); vi->i_blocks = ni->allocated_size >>9 ;/* * Make sure the base inode doesn't go away and attach it to the * index inode. */ -igrab (base_vi); +if (!igrab (base_vi)) + goto unm_err_out; ni->ext.base_ntfs_ino = base_ni; ni->nr_extents =-1 ;
@@ -1700,17 +1708,100 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi)if (m)unmap_mft_record (base_ni); err_out: -ntfs_error (vi->i_sb,"Failed with error code %i while reading index " -"inode (mft_no 0x%lx, name_len %i." , err, vi->i_ino, - ni->name_len); -make_bad_inode (vi); +ntfs_error (vi->i_sb, +"Failed with error code %i while reading index inode (mft_no 0x%lx, name_len %i." , + err, vi->i_ino, ni->name_len);if (err != -EOPNOTSUPP && err != -ENOMEM )NVolSetErrors (vol);return err; }/* -* The MFT inode has special locking, so teach the lock validator +* load_attribute_list_mount - load an attribute list into memory +* @vol: ntfs volume from which to read +* @rl: 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 @rl 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. +*/ +static int load_attribute_list_mount (struct ntfs_volume *vol, +struct runlist_element *rl,u8 *al_start,const s64 size, +const s64 initialized_size) +{ +s64 lcn; +u8 *al = al_start; +u8 *al_end = al + initialized_size; +struct super_block *sb; +int err =0 ; +loff_t rl_byte_off, rl_byte_len; + +ntfs_debug ("Entering." ); +if (!vol || !rl || !al || size <=0 || initialized_size <0 || + initialized_size > size) +return -EINVAL ; +if (!initialized_size) { +memset (al,0 , size); +return 0 ; + } + sb = vol->sb; + +/* 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; + } + + rl_byte_off =ntfs_cluster_to_bytes (vol, lcn); + rl_byte_len =ntfs_cluster_to_bytes (vol, rl->length); + +if (al + rl_byte_len > al_end) + rl_byte_len = al_end - al; + + err =ntfs_bdev_read (sb->s_bdev, al, rl_byte_off, +round_up (rl_byte_len,SECTOR_SIZE )); +if (err) { +ntfs_error (sb,"Cannot read attribute list." ); + goto err_out; + } + +if (al + rl_byte_len >= al_end) { +if (initialized_size < size) + goto initialize; + goto done; + } + + al += rl_byte_len; + rl++; + } +if (initialized_size < size) { +initialize: +memset (al_start + initialized_size,0 , size - initialized_size); + } +done: +return err; +/* Real overflow! */ +ntfs_error (sb,"Attribute list buffer overflow. Read attribute list is truncated." ); +err_out: + err = -EIO ; + goto done; +} + +/* +* The MFT inode has special locking, so teach the lock validator * about this by splitting off the locking rules of the MFT from * the locking rules of other inodes. The MFT inode can never be * accessed from the VFS side (or even internally), only by the
@@ -1718,7 +1809,7 @@ static int ntfs_read_locked_index_inode(struct inode *base_vi, struct inode *vi)*/ static struct lock_class_key mft_ni_runlist_lock_key, mft_ni_mrec_lock_key; -/** +/* * ntfs_read_inode_mount - special read_inode for mount time use only * @vi: inode to read *
@@ -1746,31 +1837,29 @@ static struct lock_class_key mft_ni_runlist_lock_key, mft_ni_mrec_lock_key;*/ int ntfs_read_inode_mount (struct inode *vi) { -VCN next_vcn, last_vcn, highest_vcn; -s64 block; +s64 next_vcn, last_vcn, highest_vcn;struct super_block *sb = vi->i_sb; -ntfs_volume *vol =NTFS_SB (sb); -struct buffer_head *bh; -ntfs_inode *ni; -MFT_RECORD *m =NULL ; -ATTR_RECORD *a; -ntfs_attr_search_ctx *ctx; +struct ntfs_volume *vol =NTFS_SB (sb); +struct ntfs_inode *ni =NTFS_I (vi); +struct mft_record *m =NULL ; +struct attr_record *a; +struct ntfs_attr_search_ctx *ctx;unsigned int i, nr_blocks;int err; +size_t new_rl_count;ntfs_debug ("Entering." );/* Initialize the ntfs specific part of @vi. */ ntfs_init_big_inode (vi); - ni =NTFS_I (vi);/* Setup the data attribute. It is special as it is mst protected. */ NInoSetNonResident (ni);NInoSetMstProtected (ni);NInoSetSparseDisabled (ni); ni->type =AT_DATA ; - ni->name =NULL ; + ni->name =AT_UNNAMED ; ni->name_len =0 ;/* * This sets up our little cheat allowing us to reuse the async read io
@@ -1788,32 +1877,28 @@ int ntfs_read_inode_mount(struct inode *vi) vol->mft_record_size); goto err_out; } + i = vol->mft_record_size;if (i < sb->s_blocksize) i = sb->s_blocksize; - m = (MFT_RECORD *)ntfs_malloc_nofs (i); + + m =kzalloc (i,GFP_NOFS );if (!m) {ntfs_error (sb,"Failed to allocate buffer for $MFT record 0." ); goto err_out; }/* Determine the first block of the $MFT/$DATA attribute. */ - block = vol->mft_lcn << vol->cluster_size_bits >> - sb->s_blocksize_bits; - nr_blocks = vol->mft_record_size >> sb->s_blocksize_bits; + nr_blocks =ntfs_bytes_to_sector (vol, vol->mft_record_size);if (!nr_blocks) nr_blocks =1 ;/* Load $MFT/$DATA's first mft record. */ -for (i =0 ; i < nr_blocks; i++) { - bh =sb_bread (sb, block++); -if (!bh) { -ntfs_error (sb,"Device read failed." ); - goto err_out; - } -memcpy ((char *)m + (i << sb->s_blocksize_bits), bh->b_data, - sb->s_blocksize); -brelse (bh); + err =ntfs_bdev_read (sb->s_bdev, (char *)m, +ntfs_cluster_to_bytes (vol, vol->mft_lcn), i); +if (err) { +ntfs_error (sb,"Device read failed." ); + goto err_out; }if (le32_to_cpu (m->bytes_allocated) != vol->mft_record_size) {
@@ -1823,16 +1908,13 @@ int ntfs_read_inode_mount(struct inode *vi) }/* Apply the mst fixups. */ -if (post_read_mst_fixup ((NTFS_RECORD *)m, vol->mft_record_size)) { -/* FIXME: Try to use the $MFTMirr now. */ +if (post_read_mst_fixup ((struct ntfs_record *)m, vol->mft_record_size)) {ntfs_error (sb,"MST fixup failed. $MFT is corrupt." ); goto err_out; } -/* Sanity check offset to the first attribute */ -if (le16_to_cpu (m->attrs_offset) >=le32_to_cpu (m->bytes_allocated)) { -ntfs_error (sb,"Incorrect mft offset to the first attribute %u in superblock." , -le16_to_cpu (m->attrs_offset)); +if (ntfs_mft_record_check (vol, m,FILE_MFT )) { +ntfs_error (sb,"ntfs_mft_record_check failed. $MFT is corrupt." ); goto err_out; }
@@ -1840,7 +1922,7 @@ int ntfs_read_inode_mount(struct inode *vi) vi->i_generation = ni->seq_no =le16_to_cpu (m->sequence_number);/* Provides read_folio() for map_mft_record(). */ - vi->i_mapping->a_ops = &ntfs_mst_aops; + vi->i_mapping->a_ops = &ntfs_mft_aops; ctx =ntfs_attr_get_search_ctx (ni, m);if (!ctx) {
@@ -1852,39 +1934,34 @@ int ntfs_read_inode_mount(struct inode *vi) err =ntfs_attr_lookup (AT_ATTRIBUTE_LIST ,NULL ,0 ,0 ,0 ,NULL ,0 , ctx);if (err) {if (unlikely (err != -ENOENT )) { -ntfs_error (sb,"Failed to lookup attribute list " -"attribute. You should run chkdsk." ); +ntfs_error (sb, +"Failed to lookup attribute list attribute. You should run chkdsk." ); goto put_err_out; } }else /* if (!err) */ { -ATTR_LIST_ENTRY *al_entry, *next_al_entry; +struct attr_list_entry *al_entry, *next_al_entry;u8 *al_end; -static const char *es =" Not allowed. $MFT is corrupt. " -"You should run chkdsk." ; +static const char *es =" Not allowed. $MFT is corrupt. You should run chkdsk." ;ntfs_debug ("Attribute list attribute found in $MFT." );NInoSetAttrList (ni); a = ctx->attr;if (a->flags &ATTR_COMPRESSION_MASK ) { -ntfs_error (sb,"Attribute list attribute is " -"compressed.%s" , es); +ntfs_error (sb, +"Attribute list attribute is compressed.%s" , + es); goto put_err_out; }if (a->flags &ATTR_IS_ENCRYPTED || a->flags &ATTR_IS_SPARSE ) {if (a->non_resident) { -ntfs_error (sb,"Non-resident attribute list " -"attribute is encrypted/" -"sparse.%s" , es); +ntfs_error (sb, +"Non-resident attribute list attribute is encrypted/sparse.%s" , + es); goto put_err_out; } -ntfs_warning (sb,"Resident attribute list attribute " -"in $MFT system file is marked " -"encrypted/sparse which is not true. " -"However, Windows allows this and " -"chkdsk does not detect or correct it " -"so we will just ignore the invalid " -"flags and pretend they are not set." ); +ntfs_warning (sb, +"Resident attribute list attribute in $MFT system file is marked encrypted/sparse which is not true. However, Windows allows this and chkdsk does not detect or correct it so we will just ignore the invalid flags and pretend they are not set." ); }/* Now allocate memory for the attribute list. */ ni->attr_list_size = (u32 )ntfs_attr_size (a);
@@ -1892,89 +1969,75 @@ int ntfs_read_inode_mount(struct inode *vi)ntfs_error (sb,"Attr_list_size is zero" ); goto put_err_out; } - ni->attr_list =ntfs_malloc_nofs (ni->attr_list_size); + ni->attr_list =kvzalloc (round_up (ni->attr_list_size,SECTOR_SIZE ), +GFP_NOFS );if (!ni->attr_list) { -ntfs_error (sb,"Not enough memory to allocate buffer " -"for attribute list." ); +ntfs_error (sb,"Not enough memory to allocate buffer for attribute list." ); goto put_err_out; }if (a->non_resident) { +struct runlist_element *rl; +size_t new_rl_count; +NInoSetAttrListNonResident (ni);if (a->data.non_resident.lowest_vcn) { -ntfs_error (sb,"Attribute list has non zero " -"lowest_vcn. $MFT is corrupt. " -"You should run chkdsk." ); +ntfs_error (sb, +"Attribute list has non zero lowest_vcn. $MFT is corrupt. You should run chkdsk." ); goto put_err_out; } -/* Setup the runlist. */ - ni->attr_list_rl.rl =ntfs_mapping_pairs_decompress (vol, - a,NULL ); -if (IS_ERR (ni->attr_list_rl.rl)) { - err =PTR_ERR (ni->attr_list_rl.rl); - ni->attr_list_rl.rl =NULL ; -ntfs_error (sb,"Mapping pairs decompression " -"failed with error code %i." , - -err); + + rl =ntfs_mapping_pairs_decompress (vol, a,NULL , &new_rl_count); +if (IS_ERR (rl)) { + err =PTR_ERR (rl); +ntfs_error (sb, +"Mapping pairs decompression failed with error code %i." , + -err); goto put_err_out; } -/* Now load the attribute list. */ -if ((err =load_attribute_list (vol, &ni->attr_list_rl, - ni->attr_list, ni->attr_list_size, -sle64_to_cpu (a->data. - non_resident.initialized_size)))) { -ntfs_error (sb,"Failed to load attribute list " -"attribute with error code %i." , - -err); + + err =load_attribute_list_mount (vol, rl, ni->attr_list, ni->attr_list_size, +le64_to_cpu (a->data.non_resident.initialized_size)); +kvfree (rl); +if (err) { +ntfs_error (sb, +"Failed to load attribute list with error code %i." , + -err); goto put_err_out; } }else /* if (!ctx.attr->non_resident) */ { -if ((u8 *)a +le16_to_cpu ( +if ((u8 *)a +le16_to_cpu ( a->data.resident.value_offset) + -le32_to_cpu ( - a->data.resident.value_length) > - (u8 *)ctx->mrec + vol->mft_record_size) { -ntfs_error (sb,"Corrupt attribute list " -"attribute." ); +le32_to_cpu (a->data.resident.value_length) > + (u8 *)ctx->mrec + vol->mft_record_size) { +ntfs_error (sb,"Corrupt attribute list attribute." ); goto put_err_out; }/* Now copy the attribute list. */ -memcpy (ni->attr_list, (u8 *)a +le16_to_cpu ( +memcpy (ni->attr_list, (u8 *)a +le16_to_cpu ( a->data.resident.value_offset), -le32_to_cpu ( - a->data.resident.value_length)); +le32_to_cpu (a->data.resident.value_length)); }/* The attribute list is now setup in memory. */ -/* -* FIXME: I don't know if this case is actually possible. -* According to logic it is not possible but I have seen too -* many weird things in MS software to rely on logic... Thus we -* perform a manual search and make sure the first $MFT/$DATA -* extent is in the base inode. If it is not we abort with an -* error and if we ever see a report of this error we will need -* to do some magic in order to have the necessary mft record -* loaded and in the right place in the page cache. But -* hopefully logic will prevail and this never happens... -*/ - al_entry = (ATTR_LIST_ENTRY *)ni->attr_list; - al_end = (u8 *)al_entry + ni->attr_list_size; + al_entry = (struct attr_list_entry *)ni->attr_list; + al_end = (u8 *)al_entry + ni->attr_list_size;for (;; al_entry = next_al_entry) {/* Out of bounds check. */ -if ((u8 *)al_entry < ni->attr_list || - (u8 *)al_entry > al_end) +if ((u8 *)al_entry < ni->attr_list || + (u8 *)al_entry > al_end) goto em_put_err_out;/* Catch the end of the attribute list. */ -if ((u8 *)al_entry == al_end) +if ((u8 *)al_entry == al_end) goto em_put_err_out;if (!al_entry->length) goto em_put_err_out; -if ((u8 *)al_entry +6 > al_end || (u8 *)al_entry + -le16_to_cpu (al_entry->length) > al_end) +if ((u8 *)al_entry +6 > al_end || + (u8 *)al_entry +le16_to_cpu (al_entry->length) > al_end) goto em_put_err_out; - next_al_entry = (ATTR_LIST_ENTRY *)((u8 *)al_entry + + 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 (AT_DATA )) goto em_put_err_out; -if (AT_DATA != al_entry->type) +if (al_entry->type !=AT_DATA )continue ;/* We want an unnamed attribute. */ if (al_entry->name_length)
@@ -1985,12 +2048,8 @@ int ntfs_read_inode_mount(struct inode *vi)/* First entry has to be in the base mft record. */ if (MREF_LE (al_entry->mft_reference) != vi->i_ino) {/* MFT references do not match, logic fails. */ -ntfs_error (sb,"BUG: The first $DATA extent " -"of $MFT is not in the base " -"mft record. Please report " -"you saw this message to " -"linux-ntfs-dev@lists." -"sourceforge.net" ); +ntfs_error (sb, +"BUG: The first $DATA extent of $MFT is not in the base mft record." ); goto put_err_out; }else {/* Sequence numbers must match. */
@@ -2010,26 +2069,22 @@ int ntfs_read_inode_mount(struct inode *vi) next_vcn = last_vcn = highest_vcn =0 ;while (!(err =ntfs_attr_lookup (AT_DATA ,NULL ,0 ,0 , next_vcn,NULL ,0 , ctx))) { -runlist_element *nrl; +struct runlist_element *nrl;/* Cache the current attribute. */ a = ctx->attr;/* $MFT must be non-resident. */ if (!a->non_resident) { -ntfs_error (sb,"$MFT must be non-resident but a " -"resident extent was found. $MFT is " -"corrupt. Run chkdsk." ); +ntfs_error (sb, +"$MFT must be non-resident but a resident extent was found. $MFT is corrupt. Run chkdsk." ); goto put_err_out; }/* $MFT must be uncompressed and unencrypted. */ if (a->flags &ATTR_COMPRESSION_MASK || a->flags &ATTR_IS_ENCRYPTED || a->flags &ATTR_IS_SPARSE ) { -ntfs_error (sb,"$MFT must be uncompressed, " -"non-sparse, and unencrypted but a " -"compressed/sparse/encrypted extent " -"was found. $MFT is corrupt. Run " -"chkdsk." ); +ntfs_error (sb, +"$MFT must be uncompressed, non-sparse, and unencrypted but a compressed/sparse/encrypted extent was found. $MFT is corrupt. Run chkdsk." ); goto put_err_out; }/*
@@ -2038,35 +2093,31 @@ int ntfs_read_inode_mount(struct inode *vi)* as we have exclusive access to the inode at this time and we * are a mount in progress task, too. */ - nrl =ntfs_mapping_pairs_decompress (vol, a, ni->runlist.rl); + nrl =ntfs_mapping_pairs_decompress (vol, a, &ni->runlist, + &new_rl_count);if (IS_ERR (nrl)) { -ntfs_error (sb,"ntfs_mapping_pairs_decompress() " -"failed with error code %ld. $MFT is " -"corrupt." ,PTR_ERR (nrl)); +ntfs_error (sb, +"ntfs_mapping_pairs_decompress() failed with error code %ld." , +PTR_ERR (nrl)); goto put_err_out; } ni->runlist.rl = nrl; + ni->runlist.count = new_rl_count;/* Are we in the first extent? */ if (!next_vcn) {if (a->data.non_resident.lowest_vcn) { -ntfs_error (sb,"First extent of $DATA " -"attribute has non zero " -"lowest_vcn. $MFT is corrupt. " -"You should run chkdsk." ); +ntfs_error (sb, +"First extent of $DATA attribute has non zero lowest_vcn. $MFT is corrupt. You should run chkdsk." ); goto put_err_out; }/* Get the last vcn in the $DATA attribute. */ - last_vcn =sle64_to_cpu ( - a->data.non_resident.allocated_size) - >> vol->cluster_size_bits; + last_vcn =ntfs_bytes_to_cluster (vol, +le64_to_cpu (a->data.non_resident.allocated_size));/* Fill in the inode size. */ - vi->i_size =sle64_to_cpu ( - a->data.non_resident.data_size); - ni->initialized_size =sle64_to_cpu ( - a->data.non_resident.initialized_size); - ni->allocated_size =sle64_to_cpu ( - a->data.non_resident.allocated_size); + vi->i_size =le64_to_cpu (a->data.non_resident.data_size); + ni->initialized_size =le64_to_cpu (a->data.non_resident.initialized_size); + ni->allocated_size =le64_to_cpu (a->data.non_resident.allocated_size);/* * Verify the number of mft records does not exceed * 2^32 - 1.
@@ -2095,18 +2146,12 @@ int ntfs_read_inode_mount(struct inode *vi)* ntfs_read_inode() on extents of $MFT/$DATA. But lets * hope this never happens... */ -ntfs_read_locked_inode (vi); -if (is_bad_inode (vi)) { -ntfs_error (sb,"ntfs_read_inode() of $MFT " -"failed. BUG or corrupt $MFT. " -"Run chkdsk and if no errors " -"are found, please report you " -"saw this message to " -"linux-ntfs-dev@lists." -"sourceforge.net" ); + err =ntfs_read_locked_inode (vi); +if (err) { +ntfs_error (sb,"ntfs_read_inode() of $MFT failed.\n" );ntfs_attr_put_search_ctx (ctx);/* Revert to the safe super operations. */ -ntfs_free (m); +kfree (m);return -1 ; }/*
@@ -2124,7 +2169,7 @@ int ntfs_read_inode_mount(struct inode *vi) }/* Get the lowest vcn for the next extent. */ - highest_vcn =sle64_to_cpu (a->data.non_resident.highest_vcn); + highest_vcn =le64_to_cpu (a->data.non_resident.highest_vcn); next_vcn = highest_vcn +1 ;/* Only one extent or error, which we catch below. */
@@ -2132,27 +2177,21 @@ int ntfs_read_inode_mount(struct inode *vi)break ;/* Avoid endless loops due to corruption. */ -if (next_vcn <sle64_to_cpu ( - a->data.non_resident.lowest_vcn)) { -ntfs_error (sb,"$MFT has corrupt attribute list " -"attribute. Run chkdsk." ); +if (next_vcn <le64_to_cpu (a->data.non_resident.lowest_vcn)) { +ntfs_error (sb,"$MFT has corrupt attribute list attribute. Run chkdsk." ); goto put_err_out; } }if (err != -ENOENT ) { -ntfs_error (sb,"Failed to lookup $MFT/$DATA attribute extent. " -"$MFT is corrupt. Run chkdsk." ); +ntfs_error (sb,"Failed to lookup $MFT/$DATA attribute extent. Run chkdsk.\n" ); goto put_err_out; }if (!a) { -ntfs_error (sb,"$MFT/$DATA attribute not found. $MFT is " -"corrupt. Run chkdsk." ); +ntfs_error (sb,"$MFT/$DATA attribute not found. $MFT is corrupt. Run chkdsk." ); goto put_err_out; }if (highest_vcn && highest_vcn != last_vcn -1 ) { -ntfs_error (sb,"Failed to load the complete runlist for " -"$MFT/$DATA. Driver bug or corrupt $MFT. " -"Run chkdsk." ); +ntfs_error (sb,"Failed to load the complete runlist for $MFT/$DATA. Run chkdsk." );ntfs_debug ("highest_vcn = 0x%llx, last_vcn - 1 = 0x%llx" , (unsigned long long )highest_vcn, (unsigned long long )last_vcn -1 );
@@ -2160,7 +2199,7 @@ int ntfs_read_inode_mount(struct inode *vi) }ntfs_attr_put_search_ctx (ctx);ntfs_debug ("Done." ); -ntfs_free (m); +kfree (m);/* * Split the locking rules of the MFT inode from the
@@ -2172,69 +2211,78 @@ int ntfs_read_inode_mount(struct inode *vi)return 0 ; em_put_err_out: -ntfs_error (sb,"Couldn't find first extent of $DATA attribute in " -"attribute list. $MFT is corrupt. Run chkdsk." ); +ntfs_error (sb, +"Couldn't find first extent of $DATA attribute in attribute list. $MFT is corrupt. Run chkdsk." ); put_err_out:ntfs_attr_put_search_ctx (ctx); err_out:ntfs_error (sb,"Failed. Marking inode as bad." ); -make_bad_inode (vi); -ntfs_free (m); +kfree (m);return -1 ; } -static void __ntfs_clear_inode (ntfs_inode *ni) +static void __ntfs_clear_inode (struct ntfs_inode *ni) {/* Free all alocated memory. */ -down_write (&ni->runlist.lock); -if (ni->runlist.rl) { -ntfs_free (ni->runlist.rl); +if (NInoNonResident (ni) && ni->runlist.rl) { +kvfree (ni->runlist.rl); ni->runlist.rl =NULL ; } -up_write (&ni->runlist.lock);if (ni->attr_list) { -ntfs_free (ni->attr_list); +kvfree (ni->attr_list); ni->attr_list =NULL ; } -down_write (&ni->attr_list_rl.lock); -if (ni->attr_list_rl.rl) { -ntfs_free (ni->attr_list_rl.rl); - ni->attr_list_rl.rl =NULL ; - } -up_write (&ni->attr_list_rl.lock); - -if (ni->name_len && ni->name !=I30 ) { -/* Catch bugs... */ -BUG_ON (!ni->name); +if (ni->name_len && ni->name !=I30 && + ni->name != reparse_index_name && + ni->name != objid_index_name) { +WARN_ON (!ni->name);kfree (ni->name); } } -void ntfs_clear_extent_inode (ntfs_inode *ni) +void ntfs_clear_extent_inode (struct ntfs_inode *ni) {ntfs_debug ("Entering for inode 0x%lx." , ni->mft_no); -BUG_ON (NInoAttr (ni)); -BUG_ON (ni->nr_extents !=-1 ); - -#ifdef NTFS_RW -if (NInoDirty (ni)) { -if (!is_bad_inode (VFS_I (ni->ext.base_ntfs_ino))) -ntfs_error (ni->vol->sb,"Clearing dirty extent inode! " -"Losing data! This is a BUG!!!" ); -// FIXME: Do something!!! - } -#endif /* NTFS_RW */ +WARN_ON (NInoAttr (ni)); +WARN_ON (ni->nr_extents !=-1 );__ntfs_clear_inode (ni); - -/* Bye, bye... */ ntfs_destroy_extent_inode (ni); } -/** +static int ntfs_delete_base_inode (struct ntfs_inode *ni) +{ +struct super_block *sb = ni->vol->sb; +int err; + +if (NInoAttr (ni) || ni->nr_extents ==-1 ) +return 0 ; + + err =ntfs_non_resident_dealloc_clusters (ni); + +/* +* Deallocate extent mft records and free extent inodes. +* No need to lock as no one else has a reference. +*/ +while (ni->nr_extents) { + err =ntfs_mft_record_free (ni->vol, *(ni->ext.extent_ntfs_inos)); +if (err) +ntfs_error (sb, +"Failed to free extent MFT record. Leaving inconsistent metadata.\n" ); +ntfs_inode_close (*(ni->ext.extent_ntfs_inos)); + } + +/* Deallocate base mft record */ + err =ntfs_mft_record_free (ni->vol, ni); +if (err) +ntfs_error (sb,"Failed to free base MFT record. Leaving inconsistent metadata.\n" ); +return err; +} + +/* * ntfs_evict_big_inode - clean up the ntfs specific part of an inode * @vi: vfs inode pending annihilation *
@@ -2246,35 +2294,45 @@ void ntfs_clear_extent_inode(ntfs_inode *ni)*/ void ntfs_evict_big_inode (struct inode *vi) { -ntfs_inode *ni =NTFS_I (vi); +struct ntfs_inode *ni =NTFS_I (vi);truncate_inode_pages_final (&vi->i_data); -clear_inode (vi); -#ifdef NTFS_RW -if (NInoDirty (ni)) { -bool was_bad = (is_bad_inode (vi)); +if (!vi->i_nlink) { +if (!NInoAttr (ni)) { +/* Never called with extent inodes */ +WARN_ON (ni->nr_extents ==-1 ); +ntfs_delete_base_inode (ni); + } + goto release; + } +if (NInoDirty (ni)) {/* Committing the inode also commits all extent inodes. */ ntfs_commit_inode (vi); -if (!was_bad && (is_bad_inode (vi) ||NInoDirty (ni))) { -ntfs_error (vi->i_sb,"Failed to commit dirty inode " -"0x%lx. Losing data!" , vi->i_ino); -// FIXME: Do something!!! +if (NInoDirty (ni)) { +ntfs_debug ("Failed to commit dirty inode 0x%lx. Losing data!" , + vi->i_ino); +NInoClearAttrListDirty (ni); +NInoClearDirty (ni); } } -#endif /* NTFS_RW */ /* No need to lock at this stage as no one else has a reference. */ if (ni->nr_extents >0 ) {int i; -for (i =0 ; i < ni->nr_extents; i++) -ntfs_clear_extent_inode (ni->ext.extent_ntfs_inos[i]); -kfree (ni->ext.extent_ntfs_inos); +for (i =0 ; i < ni->nr_extents; i++) { +if (ni->ext.extent_ntfs_inos[i]) +ntfs_clear_extent_inode (ni->ext.extent_ntfs_inos[i]); + } + ni->nr_extents =0 ; +kvfree (ni->ext.extent_ntfs_inos); } +release: +clear_inode (vi);__ntfs_clear_inode (ni);if (NInoAttr (ni)) {
@@ -2285,13 +2343,16 @@ void ntfs_evict_big_inode(struct inode *vi) ni->ext.base_ntfs_ino =NULL ; } } -BUG_ON (ni->page); +if (!atomic_dec_and_test (&ni->count)) -BUG (); -return ; +WARN_ON (1 ); +if (ni->folio) +folio_put (ni->folio); +kfree (ni->mrec); +kvfree (ni->target); } -/** +/* * ntfs_show_options - show mount options in /proc/mounts * @sf: seq_file in which to write our mount options * @root: root of the mounted tree whose mount options to display
@@ -2303,640 +2364,363 @@ void ntfs_evict_big_inode(struct inode *vi)*/ int ntfs_show_options (struct seq_file *sf,struct dentry *root) { -ntfs_volume *vol =NTFS_SB (root->d_sb); +struct ntfs_volume *vol =NTFS_SB (root->d_sb);int i; -seq_printf (sf,",uid=%i" ,from_kuid_munged (&init_user_ns, vol->uid)); -seq_printf (sf,",gid=%i" ,from_kgid_munged (&init_user_ns, vol->gid)); +if (uid_valid (vol->uid)) +seq_printf (sf,",uid=%i" ,from_kuid_munged (&init_user_ns, vol->uid)); +if (gid_valid (vol->gid)) +seq_printf (sf,",gid=%i" ,from_kgid_munged (&init_user_ns, vol->gid));if (vol->fmask == vol->dmask)seq_printf (sf,",umask=0%o" , vol->fmask);else {seq_printf (sf,",fmask=0%o" , vol->fmask);seq_printf (sf,",dmask=0%o" , vol->dmask); } -seq_printf (sf,",nls=%s" , vol->nls_map->charset); +seq_printf (sf,",iocharset=%s" , vol->nls_map->charset);if (NVolCaseSensitive (vol)) -seq_printf (sf,",case_sensitive" ); +seq_puts (sf,",case_sensitive" ); +else +seq_puts (sf,",nocase" );if (NVolShowSystemFiles (vol)) -seq_printf (sf,",show_sys_files" ); -if (!NVolSparseEnabled (vol)) -seq_printf (sf,",disable_sparse" ); +seq_puts (sf,",show_sys_files,showmeta" );for (i =0 ; on_errors_arr[i].val; i++) { -if (on_errors_arr[i].val & vol->on_errors) +if (on_errors_arr[i].val == vol->on_errors)seq_printf (sf,",errors=%s" , on_errors_arr[i].str); }seq_printf (sf,",mft_zone_multiplier=%i" , vol->mft_zone_multiplier); +if (NVolSysImmutable (vol)) +seq_puts (sf,",sys_immutable" ); +if (!NVolShowHiddenFiles (vol)) +seq_puts (sf,",nohidden" ); +if (NVolHideDotFiles (vol)) +seq_puts (sf,",hide_dot_files" ); +if (NVolCheckWindowsNames (vol)) +seq_puts (sf,",windows_names" ); +if (NVolDiscard (vol)) +seq_puts (sf,",discard" ); +if (NVolDisableSparse (vol)) +seq_puts (sf,",disable_sparse" ); +if (vol->sb->s_flags &SB_POSIXACL ) +seq_puts (sf,",acl" );return 0 ; } -#ifdef NTFS_RW - -static const char *es =" Leaving inconsistent metadata. Unmount and run " -"chkdsk." ; - -/** -* ntfs_truncate - called when the i_size of an ntfs inode is changed -* @vi: inode for which the i_size was changed -* -* We only support i_size changes for normal files at present, i.e. not -* compressed and not encrypted. This is enforced in ntfs_setattr(), see -* below. -* -* The kernel guarantees that @vi is a regular file (S_ISREG() is true) and -* that the change is allowed. -* -* This implies for us that @vi is a file inode rather than a directory, index, -* or attribute inode as well as that @vi is a base inode. -* -* Returns 0 on success or -errno on error. -* -* Called with ->i_mutex held. -*/ -int ntfs_truncate (struct inode *vi) +int ntfs_extend_initialized_size (struct inode *vi,const loff_t offset, +const loff_t new_size,bool bsync) { -s64 new_size, old_size, nr_freed, new_alloc_size, old_alloc_size; -VCN highest_vcn; +struct ntfs_inode *ni =NTFS_I (vi); +loff_t old_init_size;unsigned long flags; -ntfs_inode *base_ni, *ni =NTFS_I (vi); -ntfs_volume *vol = ni->vol; -ntfs_attr_search_ctx *ctx; -MFT_RECORD *m; -ATTR_RECORD *a; -const char *te =" Leaving file length out of sync with i_size." ; -int err, mp_size, size_change, alloc_change; - -ntfs_debug ("Entering for inode 0x%lx." , vi->i_ino); -BUG_ON (NInoAttr (ni)); -BUG_ON (S_ISDIR (vi->i_mode)); -BUG_ON (NInoMstProtected (ni)); -BUG_ON (ni->nr_extents <0 ); -retry_truncate: -/* -* Lock the runlist for writing and map the mft record to ensure it is -* safe to mess with the attribute runlist and sizes. -*/ -down_write (&ni->runlist.lock); -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); -ntfs_error (vi->i_sb,"Failed to map mft record for inode 0x%lx " -"(error code %d).%s" , vi->i_ino, err, te); - ctx =NULL ; - m =NULL ; - goto old_bad_out; - } - ctx =ntfs_attr_get_search_ctx (base_ni, m); -if (unlikely (!ctx)) { -ntfs_error (vi->i_sb,"Failed to allocate a search context for " -"inode 0x%lx (not enough memory).%s" , - vi->i_ino, te); - err = -ENOMEM ; - goto old_bad_out; - } - err =ntfs_attr_lookup (ni->type, ni->name, ni->name_len, -CASE_SENSITIVE ,0 ,NULL ,0 , ctx); -if (unlikely (err)) { -if (err == -ENOENT ) { -ntfs_error (vi->i_sb,"Open attribute is missing from " -"mft record. Inode 0x%lx is corrupt. " -"Run chkdsk.%s" , vi->i_ino, te); - err = -EIO ; - }else -ntfs_error (vi->i_sb,"Failed to lookup attribute in " -"inode 0x%lx (error code %d).%s" , - vi->i_ino, err, te); - goto old_bad_out; - } - m = ctx->mrec; - a = ctx->attr; -/* -* The i_size of the vfs inode is the new size for the attribute value. -*/ - new_size =i_size_read (vi); -/* The current size of the attribute value is the old size. */ - old_size =ntfs_attr_size (a); -/* Calculate the new allocated size. */ -if (NInoNonResident (ni)) - new_alloc_size = (new_size + vol->cluster_size -1 ) & - ~(s64 )vol->cluster_size_mask; -else - new_alloc_size = (new_size +7 ) & ~7 ; -/* The current allocated size is the old allocated size. */ +int err; +read_lock_irqsave (&ni->size_lock, flags); - old_alloc_size = ni->allocated_size; + old_init_size = ni->initialized_size;read_unlock_irqrestore (&ni->size_lock, flags); -/* -* The change in the file size. This will be 0 if no change, >0 if the -* size is growing, and <0 if the size is shrinking. -*/ - size_change =-1 ; -if (new_size - old_size >=0 ) { - size_change =1 ; -if (new_size == old_size) - size_change =0 ; - } -/* As above for the allocated size. */ - alloc_change =-1 ; -if (new_alloc_size - old_alloc_size >=0 ) { - alloc_change =1 ; -if (new_alloc_size == old_alloc_size) - alloc_change =0 ; - } -/* -* If neither the size nor the allocation are being changed there is -* nothing to do. -*/ -if (!size_change && !alloc_change) - goto unm_done; -/* If the size is changing, check if new size is allowed in $AttrDef. */ -if (size_change) { - err =ntfs_attr_size_bounds_check (vol, ni->type, new_size); -if (unlikely (err)) { -if (err == -ERANGE ) { -ntfs_error (vol->sb,"Truncate would cause the " -"inode 0x%lx to %simum size " -"for its attribute type " -"(0x%x). Aborting truncate." , - vi->i_ino, - new_size > old_size ?"exceed " -"the max" :"go under the min" , -le32_to_cpu (ni->type)); - err = -EFBIG ; - }else { -ntfs_error (vol->sb,"Inode 0x%lx has unknown " -"attribute type 0x%x. " -"Aborting truncate." , - vi->i_ino, -le32_to_cpu (ni->type)); - err = -EIO ; - } -/* Reset the vfs inode size to the old size. */ -i_size_write (vi, old_size); - goto err_out; - } - } -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 ; - goto bad_out; - } -if (a->non_resident) - goto do_non_resident_truncate; -BUG_ON (NInoNonResident (ni)); -/* Resize the attribute record to best fit the new attribute size. */ -if (new_size < vol->mft_record_size && - !ntfs_resident_attr_value_resize (m, a, new_size)) { -/* The resize succeeded! */ -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); -write_lock_irqsave (&ni->size_lock, flags); -/* Update the sizes in the ntfs inode and all is done. */ - ni->allocated_size =le32_to_cpu (a->length) - -le16_to_cpu (a->data.resident.value_offset); -/* -* Note ntfs_resident_attr_value_resize() has already done any -* necessary data clearing in the attribute record. When the -* file is being shrunk vmtruncate() will already have cleared -* the top part of the last partial page, i.e. since this is -* the resident case this is the page with index 0. However, -* when the file is being expanded, the page cache page data -* between the old data_size, i.e. old_size, and the new_size -* has not been zeroed. Fortunately, we do not need to zero it -* either since on one hand it will either already be zero due -* to both read_folio and writepage clearing partial page data -* beyond i_size in which case there is nothing to do or in the -* case of the file being mmap()ped at the same time, POSIX -* specifies that the behaviour is unspecified thus we do not -* have to do anything. This means that in our implementation -* in the rare case that the file is mmap()ped and a write -* occurred into the mmap()ped region just beyond the file size -* and writepage has not yet been called to write out the page -* (which would clear the area beyond the file size) and we now -* extend the file size to incorporate this dirty region -* outside the file size, a write of the page would result in -* this data being written to disk instead of being cleared. -* Given both POSIX and the Linux mmap(2) man page specify that -* this corner case is undefined, we choose to leave it like -* that as this is much simpler for us as we cannot lock the -* relevant page now since we are holding too many ntfs locks -* which would result in a lock reversal deadlock. -*/ - ni->initialized_size = new_size; -write_unlock_irqrestore (&ni->size_lock, flags); - goto unm_done; - } -/* If the above resize failed, this must be an attribute extension. */ -BUG_ON (size_change <0 ); -/* -* 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 as it only ever can happen -* once for any given file. -*/ -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 truncation process. -*/ - err =ntfs_attr_make_non_resident (ni, old_size); -if (likely (!err)) - goto retry_truncate; -/* -* 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 )) { -ntfs_error (vol->sb,"Cannot truncate 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. */ -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; - } -// 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_truncate:
Lines of this file are not shown. View the raw message.
fs/ntfs/namei.c +1450 -147
1,597 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 v9 6/17 ntfs: update mft operations
In reply to Namjae JeonRefactors MFT record handling to use folio APIs with consistency validation, and improving allocation extension and writeback paths for and .
--- fs/ntfs/mft.c | 2499 +++++++++++++++++++++++++------------------------ fs/ntfs/mst.c | 65 +- 2 files changed, 1292 insertions(+), 1272 deletions(-)
fs/ntfs/mft.c +1257 -1242
@@ -1,57 +1,119 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* mft.c - NTFS kernel mft record operations. Part of the Linux-NTFS project. +* NTFS kernel mft record operations. +* Part of this file is based on code from the NTFS-3G. * * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc. * Copyright (c) 2002 Richard Russon +* Copyright (c) 2025 LG Electronics Co., Ltd. */ -#include <linux/buffer_head.h> -#include <linux/slab.h> -#include <linux/swap.h> +#include <linux/writeback.h> #include <linux/bio.h> +#include <linux/iomap.h> -#include "attrib.h" -#include "aops.h" #include "bitmap.h" -#include "debug.h" -#include "dir.h" #include "lcnalloc.h" -#include "malloc.h" #include "mft.h" #include "ntfs.h" -#define MAX_BHS (PAGE_SIZE / NTFS_BLOCK_SIZE) +/* +* ntfs_mft_record_check - Check the consistency of an MFT record +* +* Make sure its general fields are safe, then examine all its +* attributes and apply generic checks to them. +* +* Returns 0 if the checks are successful. If not, return -EIO. +*/ +int ntfs_mft_record_check (const struct ntfs_volume *vol,struct mft_record *m, +unsigned long mft_no) +{ +struct attr_record *a; +struct super_block *sb = vol->sb; + +if (!ntfs_is_file_record (m->magic)) { +ntfs_error (sb,"Record %llu has no FILE magic (0x%x)\n" , + (unsigned long long )mft_no,le32_to_cpu (*(__le32 *)m)); + goto err_out; + } + +if (le16_to_cpu (m->usa_ofs) &0x1 || + (vol->mft_record_size >>NTFS_BLOCK_SIZE_BITS ) +1 !=le16_to_cpu (m->usa_count) || +le16_to_cpu (m->usa_ofs) +le16_to_cpu (m->usa_count) *2 > vol->mft_record_size) { +ntfs_error (sb,"Record %llu has corrupt fix-up values fields\n" , + (unsigned long long )mft_no); + goto err_out; + } + +if (le32_to_cpu (m->bytes_allocated) != vol->mft_record_size) { +ntfs_error (sb,"Record %llu has corrupt allocation size (%u <> %u)\n" , + (unsigned long long )mft_no, + vol->mft_record_size, +le32_to_cpu (m->bytes_allocated)); + goto err_out; + } + +if (le32_to_cpu (m->bytes_in_use) > vol->mft_record_size) { +ntfs_error (sb,"Record %llu has corrupt in-use size (%u > %u)\n" , + (unsigned long long )mft_no, +le32_to_cpu (m->bytes_in_use), + vol->mft_record_size); + goto err_out; + } + +if (le16_to_cpu (m->attrs_offset) &7 ) { +ntfs_error (sb,"Attributes badly aligned in record %llu\n" , + (unsigned long long )mft_no); + goto err_out; + } + + a = (struct attr_record *)((char *)m +le16_to_cpu (m->attrs_offset)); +if ((char *)a < (char *)m || (char *)a > (char *)m + vol->mft_record_size) { +ntfs_error (sb,"Record %llu is corrupt\n" , + (unsigned long long )mft_no); + goto err_out; + } + +return 0 ; + +err_out: +return -EIO ; +} -/** -* map_mft_record_page - map the page in which a specific mft record resides +/* +* map_mft_record_folio - map the folio in which a specific mft record resides * @ni: ntfs inode whose mft record page to map * -* This maps the page in which the mft record of the ntfs inode @ni is situated -* and returns a pointer to the mft record within the mapped page. +* This maps the folio in which the mft record of the ntfs inode @ni is +* situated. +* +* This allocates a new buffer (@ni->mrec), copies the MFT record data from +* the mapped folio into this buffer, and applies the MST (Multi Sector +* Transfer) fixups on the copy. * -* Return value needs to be checked with IS_ERR() and if that is true PTR_ERR() -* contains the negative error code returned. +* The folio is pinned (referenced) in @ni->folio to ensure the data remains +* valid in the page cache, but the returned pointer is the allocated copy. +* +* Return: A pointer to the allocated and fixed-up mft record (@ni->mrec). +* The return value needs to be checked with IS_ERR(). If it is true, +* PTR_ERR() contains the negative error code. */ -static inline MFT_RECORD *map_mft_record_page (ntfs_inode *ni) +static inline struct mft_record *map_mft_record_folio (struct ntfs_inode *ni) {loff_t i_size; -ntfs_volume *vol = ni->vol; +struct ntfs_volume *vol = ni->vol;struct inode *mft_vi = vol->mft_ino; -struct page *page; +struct folio *folio;unsigned long index, end_index; -unsigned ofs; +unsigned int ofs; -BUG_ON (ni->page); +WARN_ON (ni->folio);/* * The index into the page cache and the offset within the page cache -* page of the wanted mft record. FIXME: We need to check for -* overflowing the unsigned long, but I don't think we would ever get -* here if the volume was that big... +* page of the wanted mft record. */ - index = (u64 )ni->mft_no << vol->mft_record_size_bits >> -PAGE_SHIFT ; - ofs = (ni->mft_no << vol->mft_record_size_bits) & ~PAGE_MASK ; + index =NTFS_MFT_NR_TO_PIDX (vol, ni->mft_no); + ofs =NTFS_MFT_NR_TO_POFS (vol, ni->mft_no); i_size =i_size_read (mft_vi);/* The maximum valid index into the page cache for $MFT's data. */
@@ -61,169 +123,126 @@ static inline MFT_RECORD *map_mft_record_page(ntfs_inode *ni)if (unlikely (index >= end_index)) {if (index > end_index || (i_size & ~PAGE_MASK ) < ofs + vol->mft_record_size) { - page =ERR_PTR (-ENOENT ); -ntfs_error (vol->sb,"Attempt to read mft record 0x%lx, " -"which is beyond the end of the mft. " -"This is probably a bug in the ntfs " -"driver." , ni->mft_no); + folio =ERR_PTR (-ENOENT ); +ntfs_error (vol->sb, +"Attempt to read mft record 0x%lx, which is beyond the end of the mft. This is probably a bug in the ntfs driver." , + ni->mft_no); goto err_out; } } -/* Read, map, and pin the page. */ - page =ntfs_map_page (mft_vi->i_mapping, index); -if (!IS_ERR (page)) { + +/* Read, map, and pin the folio. */ + folio =read_mapping_folio (mft_vi->i_mapping, index,NULL ); +if (!IS_ERR (folio)) { +u8 *addr; + + ni->mrec =kmalloc (vol->mft_record_size,GFP_NOFS ); +if (!ni->mrec) { +folio_put (folio); + folio =ERR_PTR (-ENOMEM ); + goto err_out; + } + + addr =kmap_local_folio (folio,0 ); +memcpy (ni->mrec, addr + ofs, vol->mft_record_size); +post_read_mst_fixup ((struct ntfs_record *)ni->mrec, vol->mft_record_size); +/* Catch multi sector transfer fixup errors. */ -if (likely (ntfs_is_mft_recordp ((le32 *)(page_address (page) + - ofs)))) { - ni->page = page; - ni->page_ofs = ofs; -return page_address (page) + ofs; +if (!ntfs_mft_record_check (vol, (struct mft_record *)ni->mrec, ni->mft_no)) { +kunmap_local (addr); + ni->folio = folio; + ni->folio_ofs = ofs; +return ni->mrec; } -ntfs_error (vol->sb,"Mft record 0x%lx is corrupt. " -"Run chkdsk." , ni->mft_no); -ntfs_unmap_page (page); - page =ERR_PTR (-EIO ); +kunmap_local (addr); +folio_put (folio); +kfree (ni->mrec); + ni->mrec =NULL ; + folio =ERR_PTR (-EIO );NVolSetErrors (vol); } err_out: - ni->page =NULL ; - ni->page_ofs =0 ; -return (void *)page; + ni->folio =NULL ; + ni->folio_ofs =0 ; +return (struct mft_record *)folio; } -/** -* map_mft_record - map, pin and lock an mft record +/* +* map_mft_record - map and pin an mft record * @ni: ntfs inode whose MFT record to map * -* First, take the mrec_lock mutex. We might now be sleeping, while waiting -* for the mutex if it was already locked by someone else. -* -* The page of the record is mapped using map_mft_record_page() before being -* returned to the caller. -* -* This in turn uses ntfs_map_page() to get the page containing the wanted mft -* record (it in turn calls read_cache_page() which reads it in from disk if -* necessary, increments the use count on the page so that it cannot disappear -* under us and returns a reference to the page cache page). -* -* If read_cache_page() invokes ntfs_readpage() to load the page from disk, it -* sets PG_locked and clears PG_uptodate on the page. Once I/O has completed -* and the post-read mst fixups on each mft record in the page have been -* performed, the page gets PG_uptodate set and PG_locked cleared (this is done -* in our asynchronous I/O completion handler end_buffer_read_mft_async()). -* ntfs_map_page() waits for PG_locked to become clear and checks if -* PG_uptodate is set and returns an error code if not. This provides -* sufficient protection against races when reading/using the page. -* -* However there is the write mapping to think about. Doing the above described -* checking here will be fine, because when initiating the write we will set -* PG_locked and clear PG_uptodate making sure nobody is touching the page -* contents. Doing the locking this way means that the commit to disk code in -* the page cache code paths is automatically sufficiently locked with us as -* we will not touch a page that has been locked or is not uptodate. The only -* locking problem then is them locking the page while we are accessing it. -* -* So that code will end up having to own the mrec_lock of all mft -* records/inodes present in the page before I/O can proceed. In that case we -* wouldn't need to bother with PG_locked and PG_uptodate as nobody will be -* accessing anything without owning the mrec_lock mutex. But we do need to -* use them because of the read_cache_page() invocation and the code becomes so -* much simpler this way that it is well worth it. -* -* The mft record is now ours and we return a pointer to it. You need to check -* the returned pointer with IS_ERR() and if that is true, PTR_ERR() will return -* the error code. -* -* NOTE: Caller is responsible for setting the mft record dirty before calling -* unmap_mft_record(). This is obviously only necessary if the caller really -* modified the mft record... -* Q: Do we want to recycle one of the VFS inode state bits instead? -* A: No, the inode ones mean we want to change the mft record, not we want to -* write it out. +* This function ensures the MFT record for the given inode is mapped and +* accessible. +* +* It increments the reference count of the ntfs inode. If the record is +* already mapped (@ni->folio is set), it returns the cached record +* immediately. +* +* Otherwise, it calls map_mft_record_folio() to read the folio from disk +* (if necessary via read_mapping_folio), allocate a buffer, and copy the +* record data. +* +* Return: A pointer to the mft record. You need to check the returned +* pointer with IS_ERR(). */ -MFT_RECORD *map_mft_record (ntfs_inode *ni) +struct mft_record *map_mft_record (struct ntfs_inode *ni) { -MFT_RECORD *m; +struct mft_record *m; + +if (!ni) +return ERR_PTR (-EINVAL );ntfs_debug ("Entering for mft_no 0x%lx." , ni->mft_no);/* Make sure the ntfs inode doesn't go away. */ atomic_inc (&ni->count); -/* Serialize access to this mft record. */ -mutex_lock (&ni->mrec_lock); +if (ni->folio) +return (struct mft_record *)ni->mrec; - m =map_mft_record_page (ni); + m =map_mft_record_folio (ni);if (!IS_ERR (m))return m; -mutex_unlock (&ni->mrec_lock);atomic_dec (&ni->count);ntfs_error (ni->vol->sb,"Failed with error code %lu." , -PTR_ERR (m));return m; } -/** -* unmap_mft_record_page - unmap the page in which a specific mft record resides -* @ni: ntfs inode whose mft record page to unmap -* -* This unmaps the page in which the mft record of the ntfs inode @ni is -* situated and returns. This is a NOOP if highmem is not configured. -* -* The unmap happens via ntfs_unmap_page() which in turn decrements the use -* count on the page thus releasing it from the pinned state. -* -* We do not actually unmap the page from memory of course, as that will be -* done by the page cache code itself when memory pressure increases or -* whatever. -*/ -static inline void unmap_mft_record_page (ntfs_inode *ni) -{ -BUG_ON (!ni->page); - -// TODO: If dirty, blah... -ntfs_unmap_page (ni->page); - ni->page =NULL ; - ni->page_ofs =0 ; -return ; -} - -/** -* unmap_mft_record - release a mapped mft record +/* +* unmap_mft_record - release a reference to a mapped mft record * @ni: ntfs inode whose MFT record to unmap * -* We release the page mapping and the mrec_lock mutex which unmaps the mft -* record and releases it for others to get hold of. We also release the ntfs -* inode by decrementing the ntfs inode reference count. +* This decrements the reference count of the ntfs inode. +* +* It releases the caller's hold on the inode. If the reference count indicates +* that there are still other users (count > 1), the function returns +* immediately, keeping the resources (folio and mrec buffer) pinned for +* those users. * * NOTE: If caller has modified the mft record, it is imperative to set the mft * record dirty BEFORE calling unmap_mft_record(). */ -void unmap_mft_record (ntfs_inode *ni) +void unmap_mft_record (struct ntfs_inode *ni) { -struct page *page = ni->page; +struct folio *folio; -BUG_ON (!page); +if (!ni) +return ;ntfs_debug ("Entering for mft_no 0x%lx." , ni->mft_no); -unmap_mft_record_page (ni); -mutex_unlock (&ni->mrec_lock); -atomic_dec (&ni->count); -/* -* If pure ntfs_inode, i.e. no vfs inode attached, we leave it to -* ntfs_clear_extent_inode() in the extent inode case, and to the -* caller in the non-extent, yet pure ntfs inode case, to do the actual -* tear down of all structures and freeing of all allocated memory. -*/ -return ; + folio = ni->folio; +if (atomic_dec_return (&ni->count) >1 ) +return ; +WARN_ON (!folio); } -/** +/* * map_extent_mft_record - load an extent inode and attach it to its base * @base_ni: base ntfs inode * @mref: mft reference of the extent inode to load -* @ntfs_ino: on successful return, pointer to the ntfs_inode structure +* @ntfs_ino: on successful return, pointer to the struct ntfs_inode structure * * Load the extent mft record @mref and attach it to its base inode @base_ni. * Return the mapped extent mft record if IS_ERR(result) is false. Otherwise
@@ -232,12 +251,12 @@ void unmap_mft_record(ntfs_inode *ni)* On successful return, @ntfs_ino contains a pointer to the ntfs_inode * structure of the mapped extent inode. */ -MFT_RECORD *map_extent_mft_record (ntfs_inode *base_ni,MFT_REF mref, -ntfs_inode **ntfs_ino) +struct mft_record *map_extent_mft_record (struct ntfs_inode *base_ni,u64 mref, +struct ntfs_inode **ntfs_ino) { -MFT_RECORD *m; -ntfs_inode *ni =NULL ; -ntfs_inode **extent_nis =NULL ; +struct mft_record *m; +struct ntfs_inode *ni =NULL ; +struct ntfs_inode **extent_nis =NULL ;int i;unsigned long mft_no =MREF (mref);u16 seq_no =MSEQNO (mref);
@@ -252,6 +271,7 @@ MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,* in which case just return it. If not found, add it to the base * inode before returning it. */ +retry:mutex_lock (&base_ni->extent_lock);if (base_ni->nr_extents >0 ) { extent_nis = base_ni->ext.extent_ntfs_inos;
@@ -279,20 +299,21 @@ MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,return m; }unmap_mft_record (ni); -ntfs_error (base_ni->vol->sb,"Found stale extent mft " -"reference! Corrupt filesystem. " -"Run chkdsk." ); +ntfs_error (base_ni->vol->sb, +"Found stale extent mft reference! Corrupt filesystem. Run chkdsk." );return ERR_PTR (-EIO ); } map_err_out: -ntfs_error (base_ni->vol->sb,"Failed to map extent " -"mft record, error code %ld." , -PTR_ERR (m)); +ntfs_error (base_ni->vol->sb, +"Failed to map extent mft record, error code %ld." , + -PTR_ERR (m));return m; } +mutex_unlock (&base_ni->extent_lock); +/* Record wasn't there. Get a new ntfs inode and initialize it. */ ni =ntfs_new_extent_inode (base_ni->vol->sb, mft_no);if (unlikely (!ni)) { -mutex_unlock (&base_ni->extent_lock);atomic_dec (&base_ni->count);return ERR_PTR (-ENOMEM ); }
@@ -303,37 +324,44 @@ MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,/* Now map the record. */ m =map_mft_record (ni);if (IS_ERR (m)) { -mutex_unlock (&base_ni->extent_lock);atomic_dec (&base_ni->count);ntfs_clear_extent_inode (ni); goto map_err_out; }/* Verify the sequence number if it is present. */ if (seq_no && (le16_to_cpu (m->sequence_number) != seq_no)) { -ntfs_error (base_ni->vol->sb,"Found stale extent mft " -"reference! Corrupt filesystem. Run chkdsk." ); +ntfs_error (base_ni->vol->sb, +"Found stale extent mft reference! Corrupt filesystem. Run chkdsk." ); destroy_ni = true; m =ERR_PTR (-EIO ); - goto unm_err_out; + goto unm_nolock_err_out; + } + +mutex_lock (&base_ni->extent_lock); +for (i =0 ; i < base_ni->nr_extents; i++) { +if (mft_no == extent_nis[i]->mft_no) { +mutex_unlock (&base_ni->extent_lock); +ntfs_clear_extent_inode (ni); + goto retry; + } }/* Attach extent inode to base inode, reallocating memory if needed. */ if (!(base_ni->nr_extents &3 )) { -ntfs_inode **tmp; -int new_size = (base_ni->nr_extents +4 ) *sizeof (ntfs_inode *); +struct ntfs_inode **tmp; +int new_size = (base_ni->nr_extents +4 ) *sizeof (struct ntfs_inode *); - tmp =kmalloc (new_size,GFP_NOFS ); + tmp =kvzalloc (new_size,GFP_NOFS );if (unlikely (!tmp)) { -ntfs_error (base_ni->vol->sb,"Failed to allocate " -"internal buffer." ); +ntfs_error (base_ni->vol->sb,"Failed to allocate internal buffer." ); destroy_ni = true; m =ERR_PTR (-ENOMEM ); goto unm_err_out; }if (base_ni->nr_extents) { -BUG_ON (!base_ni->ext.extent_ntfs_inos); +WARN_ON (!base_ni->ext.extent_ntfs_inos);memcpy (tmp, base_ni->ext.extent_ntfs_inos, new_size - -4 *sizeof (ntfs_inode *)); -kfree (base_ni->ext.extent_ntfs_inos); +4 *sizeof (struct ntfs_inode *)); +kvfree (base_ni->ext.extent_ntfs_inos); } base_ni->ext.extent_ntfs_inos = tmp; }
@@ -344,8 +372,9 @@ MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref, *ntfs_ino = ni;return m; unm_err_out: -unmap_mft_record (ni);mutex_unlock (&base_ni->extent_lock); +unm_nolock_err_out: +unmap_mft_record (ni);atomic_dec (&base_ni->count);/* * If the extent inode was not attached to the base inode we need to
@@ -356,18 +385,14 @@ MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,return m; } -#ifdef NTFS_RW - -/** -* __mark_mft_record_dirty - set the mft record and the page containing it dirty +/* +* __mark_mft_record_dirty - mark the base vfs inode dirty * @ni: ntfs inode describing the mapped mft record * * Internal function. Users should call mark_mft_record_dirty() instead. * -* Set the mapped (extent) mft record of the (base or extent) ntfs inode @ni, -* as well as the page containing the mft record, dirty. Also, mark the base -* vfs inode dirty. This ensures that any changes to the mft record are -* written out to disk. +* This function determines the base ntfs inode (in case @ni is an extent +* inode) and marks the corresponding VFS inode dirty. * * NOTE: We only set I_DIRTY_DATASYNC (and not I_DIRTY_PAGES) * on the base vfs inode, because even though file data may have been modified,
@@ -381,64 +406,40 @@ MFT_RECORD *map_extent_mft_record(ntfs_inode *base_ni, MFT_REF mref,* I_DIRTY_SYNC, since the file data has not actually hit the block device yet, * which is not what I_DIRTY_SYNC on its own would suggest. */ -void __mark_mft_record_dirty (ntfs_inode *ni) +void __mark_mft_record_dirty (struct ntfs_inode *ni) { -ntfs_inode *base_ni; +struct ntfs_inode *base_ni;ntfs_debug ("Entering for inode 0x%lx." , ni->mft_no); -BUG_ON (NInoAttr (ni)); -mark_ntfs_record_dirty (ni->page, ni->page_ofs); +WARN_ON (NInoAttr (ni));/* Determine the base vfs inode and mark it dirty, too. */ -mutex_lock (&ni->extent_lock);if (likely (ni->nr_extents >=0 )) base_ni = ni;else base_ni = ni->ext.base_ntfs_ino; -mutex_unlock (&ni->extent_lock);__mark_inode_dirty (VFS_I (base_ni),I_DIRTY_DATASYNC ); } -static const char *ntfs_please_email ="Please email " -"[email protected] and say that you saw " -"this message. Thank you." ; - -/** -* ntfs_sync_mft_mirror_umount - synchronise an mft record to the mft mirror -* @vol: ntfs volume on which the mft record to synchronize resides -* @mft_no: mft record number of mft record to synchronize -* @m: mapped, mst protected (extent) mft record to synchronize -* -* Write the mapped, mst protected (extent) mft record @m with mft record -* number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol, -* bypassing the page cache and the $MFTMirr inode itself. -* -* This function is only for use at umount time when the mft mirror inode has -* already been disposed off. We BUG() if we are called while the mft mirror -* inode is still attached to the volume. -* -* On success return 0. On error return -errno. +/* +* ntfs_bio_end_io - bio completion callback for MFT record writes * -* NOTE: This function is not implemented yet as I am not convinced it can -* actually be triggered considering the sequence of commits we do in super.c:: -* ntfs_put_super(). But just in case we provide this place holder as the -* alternative would be either to BUG() or to get a NULL pointer dereference -* and Oops. +* Decrements the folio reference count that was incremented before +* submit_bio(). This prevents a race condition where umount could +* evict the inode and release the folio while I/O is still in flight, +* potentially causing data corruption or use-after-free. */ -static int ntfs_sync_mft_mirror_umount (ntfs_volume *vol, -const unsigned long mft_no,MFT_RECORD *m) +static void ntfs_bio_end_io (struct bio *bio) { -BUG_ON (vol->mftmirr_ino); -ntfs_error (vol->sb,"Umount time mft mirror syncing is not " -"implemented yet. %s" , ntfs_please_email); -return -EOPNOTSUPP ; +if (bio->bi_private) +folio_put ((struct folio *)bio->bi_private); +bio_put (bio); } -/** +/* * ntfs_sync_mft_mirror - synchronize an mft record to the mft mirror * @vol: ntfs volume on which the mft record to synchronize resides * @mft_no: mft record number of mft record to synchronize * @m: mapped, mst protected (extent) mft record to synchronize -* @sync: if true, wait for i/o completion * * Write the mapped, mst protected (extent) mft record @m with mft record * number @mft_no to the mft mirror ($MFTMirr) of the ntfs volume @vol.
@@ -446,187 +447,81 @@ static int ntfs_sync_mft_mirror_umount(ntfs_volume *vol,* On success return 0. On error return -errno and set the volume errors flag * in the ntfs volume @vol. * -* NOTE: We always perform synchronous i/o and ignore the @sync parameter. -* -* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just -* schedule i/o via ->writepage or do it via kntfsd or whatever. +* NOTE: We always perform synchronous i/o. */ -int ntfs_sync_mft_mirror (ntfs_volume *vol,const unsigned long mft_no, -MFT_RECORD *m,int sync) +int ntfs_sync_mft_mirror (struct ntfs_volume *vol,const unsigned long mft_no, +struct mft_record *m) { -struct page *page; -unsigned int blocksize = vol->sb->s_blocksize; -int max_bhs = vol->mft_record_size / blocksize; -struct buffer_head *bhs[MAX_BHS ]; -struct buffer_head *bh, *head; -u8 *kmirr; -runlist_element *rl; -unsigned int block_start, block_end, m_start, m_end, page_ofs; -int i_bhs, nr_bhs, err =0 ; -unsigned char blocksize_bits = vol->sb->s_blocksize_bits; +u8 *kmirr =NULL ; +struct folio *folio; +unsigned int folio_ofs, lcn_folio_off =0 ; +int err =0 ; +struct bio *bio;ntfs_debug ("Entering for inode 0x%lx." , mft_no); -BUG_ON (!max_bhs); -if (WARN_ON (max_bhs >MAX_BHS )) -return -EINVAL ; +if (unlikely (!vol->mftmirr_ino)) {/* This could happen during umount... */ - err =ntfs_sync_mft_mirror_umount (vol, mft_no, m); -if (likely (!err)) -return err; + err = -EIO ; goto err_out; }/* Get the page containing the mirror copy of the mft record @m. */ - page =ntfs_map_page (vol->mftmirr_ino->i_mapping, mft_no >> - (PAGE_SHIFT - vol->mft_record_size_bits)); -if (IS_ERR (page)) { + folio =read_mapping_folio (vol->mftmirr_ino->i_mapping, +NTFS_MFT_NR_TO_PIDX (vol, mft_no),NULL ); +if (IS_ERR (folio)) {ntfs_error (vol->sb,"Failed to map mft mirror page." ); - err =PTR_ERR (page); + err =PTR_ERR (folio); goto err_out; } -lock_page (page); -BUG_ON (!PageUptodate (page)); -ClearPageUptodate (page); + +folio_lock (folio); +folio_clear_uptodate (folio);/* Offset of the mft mirror record inside the page. */ - page_ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_MASK ; + folio_ofs =NTFS_MFT_NR_TO_POFS (vol, mft_no);/* The address in the page of the mirror copy of the mft record @m. */ - kmirr =page_address (page) + page_ofs; + kmirr =kmap_local_folio (folio,0 ) + folio_ofs;/* Copy the mst protected mft record to the mirror. */ memcpy (kmirr, m, vol->mft_record_size); -/* Create uptodate buffers if not present. */ -if (unlikely (!page_has_buffers (page))) { -struct buffer_head *tail; - - bh = head =alloc_page_buffers (page, blocksize, true); -do { -set_buffer_uptodate (bh); - tail = bh; - bh = bh->b_this_page; - }while (bh); - tail->b_this_page = head; -attach_page_private (page, head); - } - bh = head =page_buffers (page); -BUG_ON (!bh); - rl =NULL ; - nr_bhs =0 ; - block_start =0 ; - m_start = kmirr - (u8 *)page_address (page); - m_end = m_start + vol->mft_record_size; -do { - block_end = block_start + blocksize; -/* If the buffer is outside the mft record, skip it. */ -if (block_end <= m_start) -continue ; -if (unlikely (block_start >= m_end)) -break ; -/* 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 )mft_no << vol->mft_record_size_bits) + - (block_start - m_start); - vcn_ofs = vcn & vol->cluster_size_mask; - vcn >>= vol->cluster_size_bits; -if (!rl) { -down_read (&NTFS_I (vol->mftmirr_ino)-> - runlist.lock); - rl =NTFS_I (vol->mftmirr_ino)->runlist.rl; -/* -* $MFTMirr always has the whole of its runlist -* in memory. -*/ -BUG_ON (!rl); - } -/* Seek to element containing target vcn. */ -while (rl->length && rl[1 ].vcn <= vcn) - rl++; - lcn =ntfs_rl_vcn_to_lcn (rl, vcn); -/* For $MFTMirr, only lcn >= 0 is a successful remap. */ -if (likely (lcn >=0 )) { -/* Setup buffer head to correct block. */ - bh->b_blocknr = ((lcn << - vol->cluster_size_bits) + - vcn_ofs) >> blocksize_bits; -set_buffer_mapped (bh); - }else { - bh->b_blocknr =-1 ; -ntfs_error (vol->sb,"Cannot write mft mirror " -"record 0x%lx because its " -"location on disk could not " -"be determined (error code " -"%lli)." , mft_no, - (long long )lcn); - err = -EIO ; - } - } -BUG_ON (!buffer_uptodate (bh)); -BUG_ON (!nr_bhs && (m_start != block_start)); -BUG_ON (nr_bhs >= max_bhs); - bhs[nr_bhs++] = bh; -BUG_ON ((nr_bhs >= max_bhs) && (m_end != block_end)); - }while (block_start = block_end, (bh = bh->b_this_page) != head); -if (unlikely (rl)) -up_read (&NTFS_I (vol->mftmirr_ino)->runlist.lock); -if (likely (!err)) { -/* Lock buffers and start synchronous write i/o on them. */ -for (i_bhs =0 ; i_bhs < nr_bhs; i_bhs++) { -struct buffer_head *tbh = bhs[i_bhs]; - -if (!trylock_buffer (tbh)) -BUG (); -BUG_ON (!buffer_uptodate (tbh)); -clear_buffer_dirty (tbh); -get_bh (tbh); - tbh->b_end_io = end_buffer_write_sync; -submit_bh (REQ_OP_WRITE , tbh); - } -/* Wait on i/o completion of buffers. */ -for (i_bhs =0 ; i_bhs < nr_bhs; i_bhs++) { -struct buffer_head *tbh = bhs[i_bhs]; -wait_on_buffer (tbh); -if (unlikely (!buffer_uptodate (tbh))) { - err = -EIO ; -/* -* Set the buffer uptodate so the page and -* buffer states do not become out of sync. -*/ -set_buffer_uptodate (tbh); - } - } - }else /* if (unlikely(err)) */ { -/* Clean the buffers. */ -for (i_bhs =0 ; i_bhs < nr_bhs; i_bhs++) -clear_buffer_dirty (bhs[i_bhs]); +if (vol->cluster_size_bits >PAGE_SHIFT ) { + lcn_folio_off = folio->index <<PAGE_SHIFT ; + lcn_folio_off &= vol->cluster_size_mask; } + + bio =bio_alloc (vol->sb->s_bdev,1 ,REQ_OP_WRITE ,GFP_NOIO ); + bio->bi_iter.bi_sector = +NTFS_B_TO_SECTOR (vol,NTFS_CLU_TO_B (vol, vol->mftmirr_lcn) + + lcn_folio_off + folio_ofs); + +if (!bio_add_folio (bio, folio, vol->mft_record_size, folio_ofs)) { + err = -EIO ; +bio_put (bio); + goto unlock_folio; + } + + bio->bi_end_io = ntfs_bio_end_io; +submit_bio (bio);/* Current state: all buffers are clean, unlocked, and uptodate. */ -/* Remove the mst protection fixups again. */ -post_write_mst_fixup ((NTFS_RECORD *)kmirr); -flush_dcache_page (page); -SetPageUptodate (page); -unlock_page (page); -ntfs_unmap_page (page); +folio_mark_uptodate (folio); + +unlock_folio: +folio_unlock (folio); +kunmap_local (kmirr); +folio_put (folio);if (likely (!err)) {ntfs_debug ("Done." ); }else { -ntfs_error (vol->sb,"I/O error while writing mft mirror " -"record 0x%lx!" , mft_no); +ntfs_error (vol->sb,"I/O error while writing mft mirror record 0x%lx!" , mft_no); err_out: -ntfs_error (vol->sb,"Failed to synchronize $MFTMirr (error " -"code %i). Volume will be left marked dirty " -"on umount. Run ntfsfix on the partition " -"after umounting to correct this." , -err); +ntfs_error (vol->sb, +"Failed to synchronize $MFTMirr (error code %i). Volume will be left marked dirty on umount. Run chkdsk on the partition after umounting to correct this." , + err);NVolSetErrors (vol); }return err; } -/** +/* * write_mft_record_nolock - write out a mapped (extent) mft record * @ni: ntfs inode describing the mapped (extent) mft record * @m: mapped (extent) mft record to write
@@ -636,201 +531,103 @@ int ntfs_sync_mft_mirror(ntfs_volume *vol, const unsigned long mft_no,* ntfs inode @ni to backing store. If the mft record @m has a counterpart in * the mft mirror, that is also updated. * -* We only write the mft record if the ntfs inode @ni is dirty and the first -* buffer belonging to its mft record is dirty, too. We ignore the dirty state -* of subsequent buffers because we could have raced with -* fs/ntfs/aops.c::mark_ntfs_record_dirty(). -* -* On success, clean the mft record and return 0. On error, leave the mft -* record dirty and return -errno. -* -* NOTE: We always perform synchronous i/o and ignore the @sync parameter. -* However, if the mft record has a counterpart in the mft mirror and @sync is -* true, we write the mft record, wait for i/o completion, and only then write -* the mft mirror copy. This ensures that if the system crashes either the mft -* or the mft mirror will contain a self-consistent mft record @m. If @sync is -* false on the other hand, we start i/o on both and then wait for completion -* on them. This provides a speedup but no longer guarantees that you will end -* up with a self-consistent mft record in the case of a crash but if you asked -* for asynchronous writing you probably do not care about that anyway. -* -* TODO: If @sync is false, want to do truly asynchronous i/o, i.e. just -* schedule i/o via ->writepage or do it via kntfsd or whatever. +* We only write the mft record if the ntfs inode @ni is dirty. +* +* On success, clean the mft record and return 0. +* On error (specifically ENOMEM), we redirty the record so it can be retried. +* For other errors, we mark the volume with errors. */ -int write_mft_record_nolock (ntfs_inode *ni,MFT_RECORD *m,int sync) +int write_mft_record_nolock (struct ntfs_inode *ni,struct mft_record *m,int sync) { -ntfs_volume *vol = ni->vol; -struct page *page = ni->page; -unsigned int blocksize = vol->sb->s_blocksize; -unsigned char blocksize_bits = vol->sb->s_blocksize_bits; -int max_bhs = vol->mft_record_size / blocksize; -struct buffer_head *bhs[MAX_BHS ]; -struct buffer_head *bh, *head; -runlist_element *rl; -unsigned int block_start, block_end, m_start, m_end; -int i_bhs, nr_bhs, err =0 ; +struct ntfs_volume *vol = ni->vol; +struct folio *folio = ni->folio; +int err =0 , i =0 ; +u8 *kaddr; +struct mft_record *fixup_m; +struct bio *bio; +unsigned int offset =0 , folio_size;ntfs_debug ("Entering for inode 0x%lx." , ni->mft_no); -BUG_ON (NInoAttr (ni)); -BUG_ON (!max_bhs); -BUG_ON (!PageLocked (page)); -if (WARN_ON (max_bhs >MAX_BHS )) { - err = -EINVAL ; - goto err_out; - } + +WARN_ON (NInoAttr (ni)); +WARN_ON (!folio_test_locked (folio)); +/* -* If the ntfs_inode is clean no need to do anything. If it is dirty, +* If the struct ntfs_inode is clean no need to do anything. If it is dirty, * mark it as clean now so that it can be redirtied later on if needed. * There is no danger of races since the caller is holding the locks * for the mft record @m and the page it is in. */ if (!NInoTestClearDirty (ni)) goto done; - bh = head =page_buffers (page); -BUG_ON (!bh); - rl =NULL ; - nr_bhs =0 ; - block_start =0 ; - m_start = ni->page_ofs; - m_end = m_start + vol->mft_record_size; -do { - block_end = block_start + blocksize; -/* If the buffer is outside the mft record, skip it. */ -if (block_end <= m_start) -continue ; -if (unlikely (block_start >= m_end)) -break ; -/* -* If 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 (block_start == m_start) { -/* This block is the first one in the record. */ -if (!buffer_dirty (bh)) { -BUG_ON (nr_bhs); -/* Clean records are not written out. */ -break ; - } - } -/* 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 )ni->mft_no << vol->mft_record_size_bits) + - (block_start - m_start); - vcn_ofs = vcn & vol->cluster_size_mask; - vcn >>= vol->cluster_size_bits; -if (!rl) { -down_read (&NTFS_I (vol->mft_ino)->runlist.lock); - rl =NTFS_I (vol->mft_ino)->runlist.rl; -BUG_ON (!rl); - } -/* Seek to element containing target vcn. */ -while (rl->length && rl[1 ].vcn <= vcn) - rl++; - lcn =ntfs_rl_vcn_to_lcn (rl, vcn); -/* For $MFT, only lcn >= 0 is a successful remap. */ -if (likely (lcn >=0 )) { -/* Setup buffer head to correct block. */ - bh->b_blocknr = ((lcn << - vol->cluster_size_bits) + - vcn_ofs) >> blocksize_bits; -set_buffer_mapped (bh); - }else { - bh->b_blocknr =-1 ; -ntfs_error (vol->sb,"Cannot write mft record " -"0x%lx because its location " -"on disk could not be " -"determined (error code %lli)." , - ni->mft_no, (long long )lcn); - err = -EIO ; - } - } -BUG_ON (!buffer_uptodate (bh)); -BUG_ON (!nr_bhs && (m_start != block_start)); -BUG_ON (nr_bhs >= max_bhs); - bhs[nr_bhs++] = bh; -BUG_ON ((nr_bhs >= max_bhs) && (m_end != block_end)); - }while (block_start = block_end, (bh = bh->b_this_page) != head); -if (unlikely (rl)) -up_read (&NTFS_I (vol->mft_ino)->runlist.lock); -if (!nr_bhs) - goto done; -if (unlikely (err)) - goto cleanup_out; + + kaddr =kmap_local_folio (folio,0 ); + fixup_m = (struct mft_record *)(kaddr + ni->folio_ofs); +memcpy (fixup_m, m, vol->mft_record_size); +/* Apply the mst protection fixups. */ - err =pre_write_mst_fixup ((NTFS_RECORD *)m, vol->mft_record_size); + err =pre_write_mst_fixup ((struct ntfs_record *)fixup_m, vol->mft_record_size);if (err) {ntfs_error (vol->sb,"Failed to apply mst fixups!" ); - goto cleanup_out; - } -flush_dcache_mft_record_page (ni); -/* Lock buffers and start synchronous write i/o on them. */ -for (i_bhs =0 ; i_bhs < nr_bhs; i_bhs++) { -struct buffer_head *tbh = bhs[i_bhs]; - -if (!trylock_buffer (tbh)) -BUG (); -BUG_ON (!buffer_uptodate (tbh)); -clear_buffer_dirty (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 (!sync && ni->mft_no < vol->mftmirr_size) -ntfs_sync_mft_mirror (vol, ni->mft_no, m, sync); -/* Wait on i/o completion of buffers. */ -for (i_bhs =0 ; i_bhs < nr_bhs; i_bhs++) { -struct buffer_head *tbh = bhs[i_bhs]; - -wait_on_buffer (tbh); -if (unlikely (!buffer_uptodate (tbh))) { + goto err_out; + } + + folio_size = vol->mft_record_size / ni->mft_lcn_count; +while (i < ni->mft_lcn_count) { +unsigned int clu_off; + + clu_off = (unsigned int )((s64 )ni->mft_no * vol->mft_record_size + offset) & + vol->cluster_size_mask; + + bio =bio_alloc (vol->sb->s_bdev,1 ,REQ_OP_WRITE ,GFP_NOIO ); + bio->bi_iter.bi_sector = +NTFS_B_TO_SECTOR (vol,NTFS_CLU_TO_B (vol, ni->mft_lcn[i]) + + clu_off); + +if (!bio_add_folio (bio, folio, folio_size, + ni->folio_ofs + offset)) { err = -EIO ; -/* -* Set the buffer uptodate so the page and buffer -* states do not become out of sync. -*/ -if (PageUptodate (page)) -set_buffer_uptodate (tbh); + goto put_bio_out; } + +/* Synchronize the mft mirror now if not @sync. */ +if (!sync && ni->mft_no < vol->mftmirr_size) +ntfs_sync_mft_mirror (vol, ni->mft_no, fixup_m); + +folio_get (folio); + bio->bi_private = folio; + bio->bi_end_io = ntfs_bio_end_io; +submit_bio (bio); + offset += vol->cluster_size; + i++; } +/* If @sync, now synchronize the mft mirror. */ if (sync && ni->mft_no < vol->mftmirr_size) -ntfs_sync_mft_mirror (vol, ni->mft_no, m, sync); -/* Remove the mst protection fixups again. */ -post_write_mst_fixup ((NTFS_RECORD *)m); -flush_dcache_mft_record_page (ni); +ntfs_sync_mft_mirror (vol, ni->mft_no, fixup_m); +kunmap_local (kaddr);if (unlikely (err)) {/* I/O error during writing. This is really bad! */ -ntfs_error (vol->sb,"I/O error while writing mft record " -"0x%lx! Marking base inode as bad. You " -"should unmount the volume and run chkdsk." , - ni->mft_no); +ntfs_error (vol->sb, +"I/O error while writing mft record 0x%lx! Marking base inode as bad. You should unmount the volume and run chkdsk." , + ni->mft_no); goto err_out; } done:ntfs_debug ("Done." );return 0 ; -cleanup_out: -/* Clean the buffers. */ -for (i_bhs =0 ; i_bhs < nr_bhs; i_bhs++) -clear_buffer_dirty (bhs[i_bhs]); +put_bio_out: +bio_put (bio); err_out:/* * Current state: all buffers are clean, unlocked, and uptodate. * The caller should mark the base inode as bad so that no more i/o -* happens. ->clear_inode() will still be invoked so all extent inodes +* happens. ->drop_inode() will still be invoked so all extent inodes * and other allocated memory will be freed. */ if (err == -ENOMEM ) { -ntfs_error (vol->sb,"Not enough memory to write mft record. " -"Redirtying so the write is retried later." ); +ntfs_error (vol->sb, +"Not enough memory to write mft record. Redirtying so the write is retried later." );mark_mft_record_dirty (ni); err =0 ; }else
@@ -838,12 +635,46 @@ int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)return err; } -/** +static int ntfs_test_inode_wb (struct inode *vi,unsigned long ino,void *data) +{ +struct ntfs_attr *na = data; + +if (!ntfs_test_inode (vi, na)) +return 0 ; + +/* +* Without this, ntfs_write_mst_block() could call iput_final() +* , and ntfs_evict_big_inode() could try to unlink this inode +* and the contex could be blocked infinitly in map_mft_record(). +*/ +if (NInoBeingDeleted (NTFS_I (vi))) { + na->state = NI_BeingDeleted; +return -1 ; + } + +/* +* This condition can prevent ntfs_write_mst_block() +* from applying/undo fixups while ntfs_create() being +* called +*/ +spin_lock (&vi->i_lock); +if (inode_state_read_once (vi) &I_CREATING ) { +spin_unlock (&vi->i_lock); + na->state = NI_BeingCreated; +return -1 ; + } +spin_unlock (&vi->i_lock); + +return igrab (vi) ?1 :-1 ; +} + +/* * ntfs_may_write_mft_record - check if an mft record may be written out * @vol: [IN] ntfs volume on which the mft record to check resides * @mft_no: [IN] mft record number of the mft record to check * @m: [IN] mapped mft record to check * @locked_ni: [OUT] caller has to unlock this ntfs inode if one is returned +* @ref_vi: [OUT] caller has to drop this vfs inode if one is returned * * Check if the mapped (base or extent) mft record @m with mft record number * @mft_no belonging to the ntfs volume @vol may be written out. If necessary
@@ -852,23 +683,23 @@ int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)* caller is responsible for unlocking the ntfs inode and unpinning the base * vfs inode. * +* To avoid deadlock when the caller holds a folio lock, if the function +* returns @ref_vi it defers dropping the vfs inode reference by returning +* it in @ref_vi instead of calling iput() directly. The caller must call +* iput() on @ref_vi after releasing the folio lock. +* * Return 'true' if the mft record may be written out and 'false' if not. * * The caller has locked the page and cleared the uptodate flag on it which * means that we can safely write out any dirty mft records that do not have -* their inodes in icache as determined by ilookup5() as anyone -* opening/creating such an inode would block when attempting to map the mft -* record in read_cache_page() until we are finished with the write out. +* their inodes in icache as determined by find_inode_nowait(). * * Here is a description of the tests we perform: * * If the inode is found in icache we know the mft record must be a base mft * record. If it is dirty, we do not write it and return 'false' as the vfs * inode write paths will result in the access times being updated which would -* cause the base mft record to be redirtied and written out again. (We know -* the access time update will modify the base mft record because Windows -* chkdsk complains if the standard information attribute is not in the base -* mft record.) +* cause the base mft record to be redirtied and written out again. * * If the inode is in icache and not dirty, we attempt to lock the mft record * and if we find the lock was already taken, it is not safe to write the mft
@@ -879,9 +710,7 @@ int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)* @locked_ni to the locked ntfs inode and return 'true'. * * Note we cannot just lock the mft record and sleep while waiting for the lock -* because this would deadlock due to lock reversal (normally the mft record is -* locked before the page is locked but we already have the page locked here -* when we try to lock the mft record). +* because this would deadlock due to lock reversal. * * If the inode is not in icache we need to perform further checks. *
@@ -889,58 +718,46 @@ int write_mft_record_nolock(ntfs_inode *ni, MFT_RECORD *m, int sync)* safely write it and return 'true'. * * We now know the mft record is an extent mft record. We check if the inode -* corresponding to its base mft record is in icache and obtain a reference to -* it if it is. If it is not, we can safely write it and return 'true'. +* corresponding to its base mft record is in icache. If it is not, we cannot +* safely determine the state of the extent inode, so we return 'false'. * * We now have the base inode for the extent mft record. We check if it has an -* ntfs inode for the extent mft record attached and if not it is safe to write +* ntfs inode for the extent mft record attached. If not, it is safe to write * the extent mft record and we return 'true'. * -* The ntfs inode for the extent mft record is attached to the base inode so we -* attempt to lock the extent mft record and if we find the lock was already -* taken, it is not safe to write the extent mft record and we return 'false'. +* If the extent inode is attached, we check if it is dirty. If so, we return +* 'false' (letting the standard write_inode path handle it). +* +* If it is not dirty, we attempt to lock the extent mft record. If the lock +* was already taken, it is not safe to write and we return 'false'. * * If we manage to obtain the lock we have exclusive access to the extent mft -* record, which also allows us safe writeout of the extent mft record. We -* set the ntfs inode of the extent mft record clean and then set @locked_ni to -* the now locked ntfs inode and return 'true'. -* -* Note, the reason for actually writing dirty mft records here and not just -* relying on the vfs inode dirty code paths is that we can have mft records -* modified without them ever having actual inodes in memory. Also we can have -* dirty mft records with clean ntfs inodes in memory. None of the described -* cases would result in the dirty mft records being written out if we only -* relied on the vfs inode dirty code paths. And these cases can really occur -* during allocation of new mft records and in particular when the -* initialized_size of the $MFT/$DATA attribute is extended and the new space -* is initialized using ntfs_mft_record_format(). The clean inode can then -* appear if the mft record is reused for a new inode before it got written -* out. +* record. We set @locked_ni to the now locked ntfs inode and return 'true'. */ -bool ntfs_may_write_mft_record (ntfs_volume *vol,const unsigned long mft_no, -const MFT_RECORD *m,ntfs_inode **locked_ni) +bool ntfs_may_write_mft_record (struct ntfs_volume *vol,const unsigned long mft_no, +const struct mft_record *m,struct ntfs_inode **locked_ni, +struct inode **ref_vi) {struct super_block *sb = vol->sb;struct inode *mft_vi = vol->mft_ino;struct inode *vi; -ntfs_inode *ni, *eni, **extent_nis; +struct ntfs_inode *ni, *eni, **extent_nis;int i; -ntfs_attr na; +struct ntfs_attr na = {0 };ntfs_debug ("Entering for inode 0x%lx." , mft_no);/* * Normally we do not return a locked inode so set @locked_ni to NULL. */ -BUG_ON (!locked_ni); *locked_ni =NULL ; + *ref_vi =NULL ; +/* * Check if the inode corresponding to this mft record is in the VFS * inode cache and obtain a reference to it if it is. */ ntfs_debug ("Looking for inode 0x%lx in icache." , mft_no); na.mft_no = mft_no; - na.name =NULL ; - na.name_len =0 ; na.type =AT_UNUSED ;/* * Optimize inode 0, i.e. $MFT itself, since we have it in memory and
@@ -949,16 +766,16 @@ bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,if (!mft_no) {/* Balance the below iput(). */ vi =igrab (mft_vi); -BUG_ON (vi != mft_vi); +WARN_ON (vi != mft_vi); }else {/* -* Have to use ilookup5_nowait() since ilookup5() waits for the -* inode lock which causes ntfs to deadlock when a concurrent -* inode write via the inode dirty code paths and the page -* dirty code path of the inode dirty code path when writing -* $MFT occurs. +* Have to use find_inode_nowait() since ilookup5_nowait() +* waits for inode with I_FREEING, which causes ntfs to deadlock +* when inodes are unlinked concurrently */ - vi =ilookup5_nowait (sb, mft_no, ntfs_test_inode, &na); + vi =find_inode_nowait (sb, mft_no, ntfs_test_inode_wb, &na); +if (na.state == NI_BeingDeleted || na.state == NI_BeingCreated) +return false; }if (vi) {ntfs_debug ("Base inode 0x%lx is in icache." , mft_no);
@@ -971,16 +788,15 @@ bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,ntfs_debug ("Inode 0x%lx is dirty, do not write it." , mft_no);atomic_dec (&ni->count); -iput (vi); + *ref_vi = vi;return false; }ntfs_debug ("Inode 0x%lx is not dirty." , mft_no);/* The inode is not dirty, try to take the mft record lock. */ if (unlikely (!mutex_trylock (&ni->mrec_lock))) { -ntfs_debug ("Mft record 0x%lx is already locked, do " -"not write it." , mft_no); +ntfs_debug ("Mft record 0x%lx is already locked, do not write it." , mft_no);atomic_dec (&ni->count); -iput (vi); + *ref_vi = vi;return false; } ntfs_debug("Managed to lock mft record 0x%lx, write it.",
@@ -1012,24 +828,21 @@ bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,* is. */ na.mft_no =MREF_LE (m->base_mft_record); -ntfs_debug ("Mft record 0x%lx is an extent record. Looking for base " -"inode 0x%lx in icache." , mft_no, na.mft_no); + na.state =0 ; +ntfs_debug ("Mft record 0x%lx is an extent record. Looking for base inode 0x%lx in icache." , + mft_no, na.mft_no);if (!na.mft_no) {/* Balance the below iput(). */ vi =igrab (mft_vi); -BUG_ON (vi != mft_vi); - }else - vi =ilookup5_nowait (sb, na.mft_no, ntfs_test_inode, - &na); -if (!vi) { -/* -* The base inode is not in icache, write this extent mft -* record. -*/ -ntfs_debug ("Base inode 0x%lx is not in icache, write the " -"extent record." , na.mft_no); -return true; +WARN_ON (vi != mft_vi); + }else { + vi =find_inode_nowait (sb, mft_no, ntfs_test_inode_wb, &na); +if (na.state == NI_BeingDeleted || na.state == NI_BeingCreated) +return false; } + +if (!vi) +return false;ntfs_debug ("Base inode 0x%lx is in icache." , na.mft_no);/* * The base inode is in icache. Check if it has the extent inode
@@ -1043,9 +856,9 @@ bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,* extent mft record. */ mutex_unlock (&ni->extent_lock); -iput (vi); -ntfs_debug ("Base inode 0x%lx has no attached extent inodes, " -"write the extent record." , na.mft_no); + *ref_vi = vi; +ntfs_debug ("Base inode 0x%lx has no attached extent inodes, write the extent record." , + na.mft_no);return true; }/* Iterate over the attached extent inodes. */
@@ -1066,9 +879,8 @@ bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,*/ if (!eni) {mutex_unlock (&ni->extent_lock); -iput (vi); -ntfs_debug ("Extent inode 0x%lx is not attached to its base " -"inode 0x%lx, write the extent record." , + *ref_vi = vi; +ntfs_debug ("Extent inode 0x%lx is not attached to its base inode 0x%lx, write the extent record." , mft_no, na.mft_no);return true; }
@@ -1077,22 +889,27 @@ bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,/* Take a reference to the extent ntfs inode. */ atomic_inc (&eni->count);mutex_unlock (&ni->extent_lock); + +/* if extent inode is dirty, write_inode will write it */ +if (NInoDirty (eni)) { +atomic_dec (&eni->count); + *ref_vi = vi; +return false; + } +/* * Found the extent inode coresponding to this extent mft record. * Try to take the mft record lock. */ if (unlikely (!mutex_trylock (&eni->mrec_lock))) {atomic_dec (&eni->count); -iput (vi); -ntfs_debug ("Extent mft record 0x%lx is already locked, do " -"not write it." , mft_no); + *ref_vi = vi; +ntfs_debug ("Extent mft record 0x%lx is already locked, do not write it." , + mft_no);return false; }ntfs_debug ("Managed to lock extent mft record 0x%lx, write it." , mft_no); -if (NInoTestClearDirty (eni)) -ntfs_debug ("Extent inode 0x%lx is dirty, marking it clean." , - mft_no);/* * The write has to occur while we hold the mft record lock so return * the locked extent ntfs inode.
@@ -1101,10 +918,11 @@ bool ntfs_may_write_mft_record(ntfs_volume *vol, const unsigned long mft_no,return true; } -static const char *es =" Leaving inconsistent metadata. Unmount and run " -"chkdsk." ; +static const char *es =" Leaving inconsistent metadata. Unmount and run chkdsk." ; + +#define RESERVED_MFT_RECORDS 64 -/** +/* * ntfs_mft_bitmap_find_and_alloc_free_rec_nolock - see name * @vol: volume on which to search for a free mft record * @base_ni: open base inode if allocating an extent mft record or NULL
@@ -1123,19 +941,18 @@ static const char *es = " Leaving inconsistent metadata. Unmount and run "* * Locking: Caller must hold vol->mftbmp_lock for writing. */ -static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock (ntfs_volume *vol, -ntfs_inode *base_ni) +static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock (struct ntfs_volume *vol, +struct ntfs_inode *base_ni) {s64 pass_end, ll, data_pos, pass_start, ofs, bit;unsigned long flags;struct address_space *mftbmp_mapping; -u8 *buf, *byte; -struct page *page; -unsigned int page_ofs, size; +u8 *buf =NULL , *byte; +struct folio *folio; +unsigned int folio_ofs, size;u8 pass, b; -ntfs_debug ("Searching for free mft record in the currently " -"initialized mft bitmap." ); +ntfs_debug ("Searching for free mft record in the currently initialized mft bitmap." ); mftbmp_mapping = vol->mftbmp_ino->i_mapping;/* * Set the end of the pass making sure we do not overflow the mft
@@ -1155,26 +972,30 @@ static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol, data_pos = vol->mft_data_pos; else data_pos = base_ni->mft_no +1 ; -if (data_pos <24 ) - data_pos =24 ; +if (data_pos <RESERVED_MFT_RECORDS ) + data_pos =RESERVED_MFT_RECORDS ;if (data_pos >= pass_end) { - data_pos =24 ; + data_pos =RESERVED_MFT_RECORDS ; pass =2 ;/* This happens on a freshly formatted volume. */ if (data_pos >= pass_end)return -ENOSPC ; } + +if (base_ni && base_ni->mft_no ==FILE_MFT ) { + data_pos =0 ; + pass =2 ; + } + pass_start = data_pos; -ntfs_debug ("Starting bitmap search: pass %u, pass_start 0x%llx, " -"pass_end 0x%llx, data_pos 0x%llx." , pass, - (long long )pass_start, (long long )pass_end, - (long long )data_pos); +ntfs_debug ("Starting bitmap search: pass %u, pass_start 0x%llx, pass_end 0x%llx, data_pos 0x%llx." , + pass, pass_start, pass_end, data_pos);/* Loop until a free mft record is found. */ for (; pass <=2 ;) {/* Cap size to pass_end. */ ofs = data_pos >>3 ; - page_ofs = ofs & ~PAGE_MASK ; - size =PAGE_SIZE - page_ofs; + folio_ofs = ofs & ~PAGE_MASK ; + size =PAGE_SIZE - folio_ofs; ll = ((pass_end +7 ) >>3 ) - ofs;if (size > ll) size = ll;
@@ -1184,21 +1005,32 @@ static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,* for a zero bit. */ if (size) { - page =ntfs_map_page (mftbmp_mapping, - ofs >>PAGE_SHIFT ); -if (IS_ERR (page)) { -ntfs_error (vol->sb,"Failed to read mft " -"bitmap, aborting." ); -return PTR_ERR (page); + folio =read_mapping_folio (mftbmp_mapping, + ofs >>PAGE_SHIFT ,NULL ); +if (IS_ERR (folio)) { +ntfs_error (vol->sb,"Failed to read mft bitmap, aborting." ); +return PTR_ERR (folio); } - buf = (u8 *)page_address (page) + page_ofs; +folio_lock (folio); + buf = (u8 *)kmap_local_folio (folio,0 ) + folio_ofs; bit = data_pos &7 ; data_pos &= ~7ull ; -ntfs_debug ("Before inner for loop: size 0x%x, " -"data_pos 0x%llx, bit 0x%llx" , size, - (long long )data_pos, (long long )bit); +ntfs_debug ("Before inner for loop: size 0x%x, data_pos 0x%llx, bit 0x%llx" , + size, data_pos, bit);for (; bit < size && data_pos + bit < pass_end; bit &= ~7ull , bit +=8 ) { +/* +* If we're extending $MFT and running out of the first +* mft record (base record) then give up searching since +* no guarantee that the found record will be accessible. +*/ +if (base_ni && base_ni->mft_no ==FILE_MFT && bit >400 ) { +folio_unlock (folio); +kunmap_local (buf); +folio_put (folio); +return -ENOSPC ; + } + byte = buf + (bit >>3 );if (*byte ==0xff )continue ;
@@ -1206,25 +1038,27 @@ static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,if (b <8 && b >= (bit &7 )) { ll = data_pos + (bit & ~7ull ) + b;if (unlikely (ll > (1ll <<32 ))) { -ntfs_unmap_page (page); +folio_unlock (folio); +kunmap_local (buf); +folio_put (folio);return -ENOSPC ; } *byte |=1 << b; -flush_dcache_page (page); -set_page_dirty (page); -ntfs_unmap_page (page); -ntfs_debug ("Done. (Found and " -"allocated mft record " -"0x%llx.)" , - (long long )ll); +folio_mark_dirty (folio); +folio_unlock (folio); +kunmap_local (buf); +folio_put (folio); +ntfs_debug ("Done. (Found and allocated mft record 0x%llx.)" , + ll);return ll; } } -ntfs_debug ("After inner for loop: size 0x%x, " -"data_pos 0x%llx, bit 0x%llx" , size, - (long long )data_pos, (long long )bit); +ntfs_debug ("After inner for loop: size 0x%x, data_pos 0x%llx, bit 0x%llx" , + size, data_pos, bit); data_pos += size; -ntfs_unmap_page (page); +folio_unlock (folio); +kunmap_local (buf); +folio_put (folio);/* * If the end of the pass has not been reached yet, * continue searching the mft bitmap for a zero bit.
@@ -1239,21 +1073,48 @@ static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,* part of the zone which we omitted earlier. */ pass_end = pass_start; - data_pos = pass_start =24 ; -ntfs_debug ("pass %i, pass_start 0x%llx, pass_end " -"0x%llx." , pass, (long long )pass_start, - (long long )pass_end); + data_pos = pass_start =RESERVED_MFT_RECORDS ; +ntfs_debug ("pass %i, pass_start 0x%llx, pass_end 0x%llx." , + pass, pass_start, pass_end);if (data_pos >= pass_end)break ; } }/* No free mft records in currently initialized mft bitmap. */ -ntfs_debug ("Done. (No free mft records left in currently initialized " -"mft bitmap.)" ); +ntfs_debug ("Done. (No free mft records left in currently initialized mft bitmap.)" );return -ENOSPC ; } -/** +static int ntfs_mft_attr_extend (struct ntfs_inode *ni) +{ +int ret =0 ; +struct ntfs_inode *base_ni; + +if (NInoAttr (ni)) + base_ni = ni->ext.base_ntfs_ino; +else + base_ni = ni; + +if (!NInoAttrList (base_ni)) { + ret =ntfs_inode_add_attrlist (base_ni); +if (ret) { +pr_err ("Can not add attrlist\n" ); + goto out; + }else { + ret = -EAGAIN ; + goto out; + } + } + + ret =ntfs_attr_update_mapping_pairs (ni,0 ); +if (ret) +pr_err ("MP update failed\n" ); + +out: +return ret; +} + +/* * ntfs_mft_bitmap_extend_allocation_nolock - extend mft bitmap by a cluster * @vol: volume on which to extend the mft bitmap attribute *
@@ -1270,17 +1131,17 @@ static int ntfs_mft_bitmap_find_and_alloc_free_rec_nolock(ntfs_volume *vol,* - This function takes vol->lcnbmp_lock for writing and releases it * before returning. */ -static int ntfs_mft_bitmap_extend_allocation_nolock (ntfs_volume *vol) +static int ntfs_mft_bitmap_extend_allocation_nolock (struct ntfs_volume *vol) { -LCN lcn; +s64 lcn;s64 ll;unsigned long flags; -struct page *page; -ntfs_inode *mft_ni, *mftbmp_ni; -runlist_element *rl, *rl2 =NULL ; -ntfs_attr_search_ctx *ctx =NULL ; -MFT_RECORD *mrec; -ATTR_RECORD *a =NULL ; +struct folio *folio; +struct ntfs_inode *mft_ni, *mftbmp_ni; +struct runlist_element *rl, *rl2 =NULL ; +struct ntfs_attr_search_ctx *ctx =NULL ; +struct mft_record *mrec; +struct attr_record *a =NULL ;int ret, mp_size;u32 old_alen =0 ;u8 *b, tb;
@@ -1288,7 +1149,9 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol) u8 added_cluster:1; u8 added_run:1; u8 mp_rebuilt:1; - } status = { 0, 0, 0 }; + u8 mp_extended:1; + } status = { 0, 0, 0, 0 }; +size_t new_rl_count;ntfs_debug ("Extending mft bitmap allocation." ); mft_ni =NTFS_I (vol->mft_ino);
@@ -1302,11 +1165,11 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol) ll = mftbmp_ni->allocated_size;read_unlock_irqrestore (&mftbmp_ni->size_lock, flags); rl =ntfs_attr_find_vcn_nolock (mftbmp_ni, - (ll -1 ) >> vol->cluster_size_bits,NULL ); +NTFS_B_TO_CLU (vol, ll -1 ),NULL );if (IS_ERR (rl) ||unlikely (!rl->length || rl->lcn <0 )) {up_write (&mftbmp_ni->runlist.lock); -ntfs_error (vol->sb,"Failed to determine last allocated " -"cluster of mft bitmap attribute." ); +ntfs_error (vol->sb, +"Failed to determine last allocated cluster of mft bitmap attribute." );if (!IS_ERR (rl)) ret = -EIO ;else
@@ -1322,54 +1185,59 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)* to us. */ ll = lcn >>3 ; - page =ntfs_map_page (vol->lcnbmp_ino->i_mapping, - ll >>PAGE_SHIFT ); -if (IS_ERR (page)) { + folio =read_mapping_folio (vol->lcnbmp_ino->i_mapping, + ll >>PAGE_SHIFT ,NULL ); +if (IS_ERR (folio)) {up_write (&mftbmp_ni->runlist.lock);ntfs_error (vol->sb,"Failed to read from lcn bitmap." ); -return PTR_ERR (page); +return PTR_ERR (folio); } - b = (u8 *)page_address (page) + (ll & ~PAGE_MASK ); - tb =1 << (lcn &7ull ); +down_write (&vol->lcnbmp_lock); +folio_lock (folio); + b = (u8 *)kmap_local_folio (folio,0 ) + (ll & ~PAGE_MASK ); + tb =1 << (lcn &7ull );if (*b !=0xff && !(*b & tb)) {/* Next cluster is free, allocate it. */ *b |= tb; -flush_dcache_page (page); -set_page_dirty (page); +folio_mark_dirty (folio); +folio_unlock (folio); +kunmap_local (b); +folio_put (folio);up_write (&vol->lcnbmp_lock); -ntfs_unmap_page (page);/* Update the mft bitmap runlist. */ rl->length++; rl[1 ].vcn++; status.added_cluster =1 ;ntfs_debug ("Appending one cluster to mft bitmap." ); }else { +folio_unlock (folio); +kunmap_local (b); +folio_put (folio);up_write (&vol->lcnbmp_lock); -ntfs_unmap_page (page);/* Allocate a cluster from the DATA_ZONE. */ rl2 =ntfs_cluster_alloc (vol, rl[1 ].vcn,1 , lcn,DATA_ZONE , - true); + true, false, false);if (IS_ERR (rl2)) {up_write (&mftbmp_ni->runlist.lock); -ntfs_error (vol->sb,"Failed to allocate a cluster for " -"the mft bitmap." ); +ntfs_error (vol->sb, +"Failed to allocate a cluster for the mft bitmap." );return PTR_ERR (rl2); } - rl =ntfs_runlists_merge (mftbmp_ni->runlist.rl, rl2); + rl =ntfs_runlists_merge (&mftbmp_ni->runlist, rl2,0 , &new_rl_count);if (IS_ERR (rl)) {up_write (&mftbmp_ni->runlist.lock); -ntfs_error (vol->sb,"Failed to merge runlists for mft " -"bitmap." ); +ntfs_error (vol->sb,"Failed to merge runlists for mft bitmap." );if (ntfs_cluster_free_from_rl (vol, rl2)) { -ntfs_error (vol->sb,"Failed to deallocate " -"allocated cluster.%s" , es); +ntfs_error (vol->sb,"Failed to deallocate allocated cluster.%s" , + es);NVolSetErrors (vol); } -ntfs_free (rl2); +kvfree (rl2);return PTR_ERR (rl); } mftbmp_ni->runlist.rl = rl; + mftbmp_ni->runlist.count = new_rl_count; status.added_run =1 ;ntfs_debug ("Adding one run to mft bitmap." );/* Find the last run in the new runlist. */
@@ -1396,26 +1264,26 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol) mftbmp_ni->name_len,CASE_SENSITIVE , rl[1 ].vcn,NULL , 0, ctx);if (unlikely (ret)) { -ntfs_error (vol->sb,"Failed to find last attribute extent of " -"mft bitmap attribute." ); +ntfs_error (vol->sb, +"Failed to find last attribute extent of mft bitmap attribute." );if (ret == -ENOENT ) ret = -EIO ; goto undo_alloc; } a = ctx->attr; - ll =sle64_to_cpu (a->data.non_resident.lowest_vcn); + ll =le64_to_cpu (a->data.non_resident.lowest_vcn);/* Search back for the previous last allocated cluster of mft bitmap. */ for (rl2 = rl; rl2 > mftbmp_ni->runlist.rl; rl2--) {if (ll >= rl2->vcn)break ; } -BUG_ON (ll < rl2->vcn); -BUG_ON (ll >= rl2->vcn + rl2->length); +WARN_ON (ll < rl2->vcn); +WARN_ON (ll >= rl2->vcn + rl2->length);/* Get the size for the new mapping pairs array for this extent. */ - mp_size =ntfs_get_size_for_mapping_pairs (vol, rl2, ll,-1 ); + mp_size =ntfs_get_size_for_mapping_pairs (vol, rl2, ll,-1 ,-1 );if (unlikely (mp_size <=0 )) { -ntfs_error (vol->sb,"Get size for mapping pairs failed for " -"mft bitmap attribute extent." ); +ntfs_error (vol->sb, +"Get size for mapping pairs failed for mft bitmap attribute extent." ); ret = mp_size;if (!ret) ret = -EIO ;
@@ -1426,76 +1294,68 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol) ret =ntfs_attr_record_resize (ctx->mrec, a, mp_size +le16_to_cpu (a->data.non_resident.mapping_pairs_offset));if (unlikely (ret)) { -if (ret != -ENOSPC ) { -ntfs_error (vol->sb,"Failed to resize attribute " -"record for mft bitmap attribute." ); - goto undo_alloc; - } -// TODO: Deal with this by moving this extent to a new mft -// record or by starting a new extent in a new mft record or by -// moving other attributes out of this mft record. -// Note: It will need to be a special mft record and if none of -// those are available it gets rather complicated... -ntfs_error (vol->sb,"Not enough space in this mft record to " -"accommodate extended mft bitmap attribute " -"extent. Cannot handle this yet." ); - ret = -EOPNOTSUPP ; + ret =ntfs_mft_attr_extend (mftbmp_ni); +if (!ret) + goto extended_ok; +if (ret != -EAGAIN ) + status.mp_extended =1 ; goto undo_alloc; } status.mp_rebuilt =1 ;/* Generate the mapping pairs array directly into the attr record. */ - ret =ntfs_mapping_pairs_build (vol, (u8 *)a + + ret =ntfs_mapping_pairs_build (vol, (u8 *)a +le16_to_cpu (a->data.non_resident.mapping_pairs_offset), - mp_size, rl2, ll,-1 ,NULL ); + mp_size, rl2, ll,-1 ,NULL ,NULL ,NULL );if (unlikely (ret)) { -ntfs_error (vol->sb,"Failed to build mapping pairs array for " -"mft bitmap attribute." ); +ntfs_error (vol->sb, +"Failed to build mapping pairs array for mft bitmap attribute." ); goto undo_alloc; }/* Update the highest_vcn. */ - a->data.non_resident.highest_vcn =cpu_to_sle64 (rl[1 ].vcn -1 ); + a->data.non_resident.highest_vcn =cpu_to_le64 (rl[1 ].vcn -1 );/* * We now have extended the mft bitmap allocated_size by one cluster. -* Reflect this in the ntfs_inode structure and the attribute record. +* Reflect this in the struct ntfs_inode structure and the attribute record. */ 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); +extended_ok:ntfs_attr_reinit_search_ctx (ctx); ret =ntfs_attr_lookup (mftbmp_ni->type, mftbmp_ni->name, mftbmp_ni->name_len,CASE_SENSITIVE ,0 ,NULL ,0 , ctx);if (unlikely (ret)) { -ntfs_error (vol->sb,"Failed to find first attribute " -"extent of mft bitmap attribute." ); +ntfs_error (vol->sb, +"Failed to find first attribute extent of mft bitmap attribute." ); goto restore_undo_alloc; } a = ctx->attr; } +write_lock_irqsave (&mftbmp_ni->size_lock, flags); mftbmp_ni->allocated_size += vol->cluster_size; a->data.non_resident.allocated_size = -cpu_to_sle64 (mftbmp_ni->allocated_size); +cpu_to_le64 (mftbmp_ni->allocated_size);write_unlock_irqrestore (&mftbmp_ni->size_lock, flags);/* 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 (mft_ni);up_write (&mftbmp_ni->runlist.lock);ntfs_debug ("Done." );return 0 ; + restore_undo_alloc:ntfs_attr_reinit_search_ctx (ctx);if (ntfs_attr_lookup (mftbmp_ni->type, mftbmp_ni->name, mftbmp_ni->name_len,CASE_SENSITIVE , rl[1 ].vcn,NULL ,0 , ctx)) { -ntfs_error (vol->sb,"Failed to find last attribute extent of " -"mft bitmap attribute.%s" , es); +ntfs_error (vol->sb, +"Failed to find last attribute extent of mft bitmap attribute.%s" , es);write_lock_irqsave (&mftbmp_ni->size_lock, flags); mftbmp_ni->allocated_size += vol->cluster_size;write_unlock_irqrestore (&mftbmp_ni->size_lock, flags);
@@ -1510,7 +1370,7 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)return ret; } a = ctx->attr; - a->data.non_resident.highest_vcn =cpu_to_sle64 (rl[1 ].vcn -2 ); + a->data.non_resident.highest_vcn =cpu_to_le64 (rl[1 ].vcn -2 ); undo_alloc:if (status.added_cluster) {/* Truncate the last run in the runlist by one cluster. */
@@ -1521,31 +1381,33 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)/* Remove the last run from the runlist. */ rl->lcn = rl[1 ].lcn; rl->length =0 ; + mftbmp_ni->runlist.count--; }/* Deallocate the cluster. */ down_write (&vol->lcnbmp_lock);if (ntfs_bitmap_clear_bit (vol->lcnbmp_ino, lcn)) {ntfs_error (vol->sb,"Failed to free allocated cluster.%s" , es);NVolSetErrors (vol); - } + }else +ntfs_inc_free_clusters (vol,1 );up_write (&vol->lcnbmp_lock);if (status.mp_rebuilt) { -if (ntfs_mapping_pairs_build (vol, (u8 *)a +le16_to_cpu ( +if (ntfs_mapping_pairs_build (vol, (u8 *)a +le16_to_cpu ( a->data.non_resident.mapping_pairs_offset), old_alen -le16_to_cpu ( a->data.non_resident.mapping_pairs_offset), - rl2, ll,-1 ,NULL )) { -ntfs_error (vol->sb,"Failed to restore mapping pairs " -"array.%s" , es); + rl2, ll,-1 ,NULL ,NULL ,NULL )) { +ntfs_error (vol->sb,"Failed to restore mapping pairs array.%s" , es);NVolSetErrors (vol); }if (ntfs_attr_record_resize (ctx->mrec, a, old_alen)) { -ntfs_error (vol->sb,"Failed to restore attribute " -"record.%s" , es); +ntfs_error (vol->sb,"Failed to restore attribute record.%s" , es);NVolSetErrors (vol); } -flush_dcache_mft_record_page (ctx->ntfs_ino);mark_mft_record_dirty (ctx->ntfs_ino); + }else if (status.mp_extended &&ntfs_attr_update_mapping_pairs (mftbmp_ni,0 )) { +ntfs_error (vol->sb,"Failed to restore mapping pairs.%s" , es); +NVolSetErrors (vol); }if (ctx)ntfs_attr_put_search_ctx (ctx);
@@ -1555,7 +1417,7 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)return ret; } -/** +/* * ntfs_mft_bitmap_extend_initialized_nolock - extend mftbmp initialized data * @vol: volume on which to extend the mft bitmap attribute *
@@ -1569,15 +1431,15 @@ static int ntfs_mft_bitmap_extend_allocation_nolock(ntfs_volume *vol)* * Locking: Caller must hold vol->mftbmp_lock for writing. */ -static int ntfs_mft_bitmap_extend_initialized_nolock (ntfs_volume *vol) +static int ntfs_mft_bitmap_extend_initialized_nolock (struct ntfs_volume *vol) {s64 old_data_size, old_initialized_size;unsigned long flags;struct inode *mftbmp_vi; -ntfs_inode *mft_ni, *mftbmp_ni; -ntfs_attr_search_ctx *ctx; -MFT_RECORD *mrec; -ATTR_RECORD *a; +struct ntfs_inode *mft_ni, *mftbmp_ni; +struct ntfs_attr_search_ctx *ctx; +struct mft_record *mrec; +struct attr_record *a;int ret;ntfs_debug ("Extending mft bitmap initiailized (and data) size." );
@@ -1599,8 +1461,8 @@ static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol) ret =ntfs_attr_lookup (mftbmp_ni->type, mftbmp_ni->name, mftbmp_ni->name_len,CASE_SENSITIVE ,0 ,NULL ,0 , ctx);if (unlikely (ret)) { -ntfs_error (vol->sb,"Failed to find first attribute extent of " -"mft bitmap attribute." ); +ntfs_error (vol->sb, +"Failed to find first attribute extent of mft bitmap attribute." );if (ret == -ENOENT ) ret = -EIO ; goto put_err_out;
@@ -1616,23 +1478,22 @@ static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)*/ mftbmp_ni->initialized_size +=8 ; a->data.non_resident.initialized_size = -cpu_to_sle64 (mftbmp_ni->initialized_size); +cpu_to_le64 (mftbmp_ni->initialized_size);if (mftbmp_ni->initialized_size > old_data_size) {i_size_write (mftbmp_vi, mftbmp_ni->initialized_size); a->data.non_resident.data_size = -cpu_to_sle64 (mftbmp_ni->initialized_size); +cpu_to_le64 (mftbmp_ni->initialized_size); }write_unlock_irqrestore (&mftbmp_ni->size_lock, flags);/* 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 (mft_ni);/* Initialize the mft bitmap attribute value with zeroes. */ ret =ntfs_attr_set (mftbmp_ni, old_initialized_size,8 ,0 );if (likely (!ret)) { -ntfs_debug ("Done. (Wrote eight initialized bytes to mft " -"bitmap." ); +ntfs_debug ("Done. (Wrote eight initialized bytes to mft bitmap." ); +ntfs_inc_free_mft_records (vol,8 *8 );return 0 ; }ntfs_error (vol->sb,"Failed to write to mft bitmap." );
@@ -1651,8 +1512,8 @@ static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol) }if (ntfs_attr_lookup (mftbmp_ni->type, mftbmp_ni->name, mftbmp_ni->name_len,CASE_SENSITIVE ,0 ,NULL ,0 , ctx)) { -ntfs_error (vol->sb,"Failed to find first attribute extent of " -"mft bitmap attribute.%s" , es); +ntfs_error (vol->sb, +"Failed to find first attribute extent of mft bitmap attribute.%s" , es);NVolSetErrors (vol); put_err_out:ntfs_attr_put_search_ctx (ctx);
@@ -1664,30 +1525,27 @@ static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)write_lock_irqsave (&mftbmp_ni->size_lock, flags); mftbmp_ni->initialized_size = old_initialized_size; a->data.non_resident.initialized_size = -cpu_to_sle64 (old_initialized_size); +cpu_to_le64 (old_initialized_size);if (i_size_read (mftbmp_vi) != old_data_size) {i_size_write (mftbmp_vi, old_data_size); - a->data.non_resident.data_size =cpu_to_sle64 (old_data_size); + a->data.non_resident.data_size =cpu_to_le64 (old_data_size); }write_unlock_irqrestore (&mftbmp_ni->size_lock, 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 (mft_ni);#ifdef DEBUG read_lock_irqsave (&mftbmp_ni->size_lock, flags); -ntfs_debug ("Restored status of mftbmp: allocated_size 0x%llx, " -"data_size 0x%llx, initialized_size 0x%llx." , - (long long )mftbmp_ni->allocated_size, - (long long )i_size_read (mftbmp_vi), - (long long )mftbmp_ni->initialized_size); +ntfs_debug ("Restored status of mftbmp: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx." , + mftbmp_ni->allocated_size,i_size_read (mftbmp_vi), + mftbmp_ni->initialized_size);read_unlock_irqrestore (&mftbmp_ni->size_lock, flags);#endif /* DEBUG */ err_out:return ret; } -/** +/* * ntfs_mft_data_extend_allocation_nolock - extend mft data attribute * @vol: volume on which to extend the mft data attribute *
@@ -1706,20 +1564,21 @@ static int ntfs_mft_bitmap_extend_initialized_nolock(ntfs_volume *vol)* - This function calls functions which take vol->lcnbmp_lock for * writing and release it before returning. */ -static int ntfs_mft_data_extend_allocation_nolock (ntfs_volume *vol) +static int ntfs_mft_data_extend_allocation_nolock (struct ntfs_volume *vol) { -LCN lcn; -VCN old_last_vcn; +s64 lcn; +s64 old_last_vcn;s64 min_nr, nr, ll;unsigned long flags; -ntfs_inode *mft_ni; -runlist_element *rl, *rl2; -ntfs_attr_search_ctx *ctx =NULL ; -MFT_RECORD *mrec; -ATTR_RECORD *a =NULL ; +struct ntfs_inode *mft_ni; +struct runlist_element *rl, *rl2; +struct ntfs_attr_search_ctx *ctx =NULL ; +struct mft_record *mrec; +struct attr_record *a =NULL ;int ret, mp_size;u32 old_alen =0 ; -bool mp_rebuilt = false; +bool mp_rebuilt = false, mp_extended = false; +size_t new_rl_count;ntfs_debug ("Extending mft data allocation." ); mft_ni =NTFS_I (vol->mft_ino);
@@ -1733,11 +1592,11 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol) ll = mft_ni->allocated_size;read_unlock_irqrestore (&mft_ni->size_lock, flags); rl =ntfs_attr_find_vcn_nolock (mft_ni, - (ll -1 ) >> vol->cluster_size_bits,NULL ); +NTFS_B_TO_CLU (vol, ll -1 ),NULL );if (IS_ERR (rl) ||unlikely (!rl->length || rl->lcn <0 )) {up_write (&mft_ni->runlist.lock); -ntfs_error (vol->sb,"Failed to determine last allocated " -"cluster of mft data attribute." ); +ntfs_error (vol->sb, +"Failed to determine last allocated cluster of mft data attribute." );if (!IS_ERR (rl)) ret = -EIO ;else
@@ -1745,9 +1604,9 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)return ret; } lcn = rl->lcn + rl->length; -ntfs_debug ("Last lcn of mft data attribute is 0x%llx." , (long long )lcn); +ntfs_debug ("Last lcn of mft data attribute is 0x%llx." , lcn);/* Minimum allocation is one mft record worth of clusters. */ - min_nr = vol->mft_record_size >> vol->cluster_size_bits; + min_nr =NTFS_B_TO_CLU (vol, vol->mft_record_size);if (!min_nr) min_nr =1 ;/* Want to allocate 16 mft records worth of clusters. */
@@ -1758,14 +1617,13 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)read_lock_irqsave (&mft_ni->size_lock, flags); ll = mft_ni->allocated_size;read_unlock_irqrestore (&mft_ni->size_lock, flags); -if (unlikely ((ll + (nr << vol->cluster_size_bits)) >> +if (unlikely ((ll +NTFS_CLU_TO_B (vol, nr)) >> vol->mft_record_size_bits >= (1ll <<32 ))) { nr = min_nr; -if (unlikely ((ll + (nr << vol->cluster_size_bits)) >> +if (unlikely ((ll +NTFS_CLU_TO_B (vol, nr)) >> vol->mft_record_size_bits >= (1ll <<32 ))) { -ntfs_warning (vol->sb,"Cannot allocate mft record " -"because the maximum number of inodes " -"(2^32) has already been reached." ); +ntfs_warning (vol->sb, +"Cannot allocate mft record because the maximum number of inodes (2^32) has already been reached." );up_write (&mft_ni->runlist.lock);return -ENOSPC ; }
@@ -1773,16 +1631,24 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)ntfs_debug ("Trying mft data allocation with %s cluster count %lli." , nr > min_nr ?"default" :"minimal" , (long long )nr); old_last_vcn = rl[1 ].vcn; +/* +* We can release the mft_ni runlist lock, Because this function is +* the only one that expends $MFT data attribute and is called with +* mft_ni->mrec_lock. +* This is required for the lock order, vol->lcnbmp_lock => +* mft_ni->runlist.lock. +*/ +up_write (&mft_ni->runlist.lock); + do { rl2 = ntfs_cluster_alloc(vol, old_last_vcn, nr, lcn, MFT_ZONE, - true); + true, false, false); if (!IS_ERR(rl2)) break; if (PTR_ERR(rl2) != -ENOSPC || nr == min_nr) { - ntfs_error(vol->sb, "Failed to allocate the minimal " - "number of clusters (%lli) for the " - "mft data attribute.", (long long)nr); - up_write(&mft_ni->runlist.lock); + ntfs_error(vol->sb, + "Failed to allocate the minimal number of clusters (%lli) for the mft data attribute.", + nr); return PTR_ERR(rl2); } /*
@@ -1791,32 +1657,36 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)* before failing. */ nr = min_nr; -ntfs_debug ("Retrying mft data allocation with minimal cluster " -"count %lli." , (long long )nr); +ntfs_debug ("Retrying mft data allocation with minimal cluster count %lli." , nr); }while (1 ); - rl =ntfs_runlists_merge (mft_ni->runlist.rl, rl2); + +down_write (&mft_ni->runlist.lock); + rl =ntfs_runlists_merge (&mft_ni->runlist, rl2,0 , &new_rl_count);if (IS_ERR (rl)) {up_write (&mft_ni->runlist.lock); -ntfs_error (vol->sb,"Failed to merge runlists for mft data " -"attribute." ); +ntfs_error (vol->sb,"Failed to merge runlists for mft data attribute." );if (ntfs_cluster_free_from_rl (vol, rl2)) { -ntfs_error (vol->sb,"Failed to deallocate clusters " -"from the mft data attribute.%s" , es); +ntfs_error (vol->sb, +"Failed to deallocate clusters from the mft data attribute.%s" , es);NVolSetErrors (vol); } -ntfs_free (rl2); +kvfree (rl2);return PTR_ERR (rl); } mft_ni->runlist.rl = rl; + mft_ni->runlist.count = new_rl_count;ntfs_debug ("Allocated %lli clusters." , (long long )nr);/* Find the last run in the new runlist. */ for (; rl[1 ].length; rl++) ; +up_write (&mft_ni->runlist.lock); +/* Update the attribute record as well. */ mrec =map_mft_record (mft_ni);if (IS_ERR (mrec)) {ntfs_error (vol->sb,"Failed to map mft record." ); ret =PTR_ERR (mrec); +down_write (&mft_ni->runlist.lock); goto undo_alloc; } ctx =ntfs_attr_get_search_ctx (mft_ni, mrec);
@@ -1828,72 +1698,61 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol) ret =ntfs_attr_lookup (mft_ni->type, mft_ni->name, mft_ni->name_len,CASE_SENSITIVE , rl[1 ].vcn,NULL ,0 , ctx);if (unlikely (ret)) { -ntfs_error (vol->sb,"Failed to find last attribute extent of " -"mft data attribute." ); +ntfs_error (vol->sb,"Failed to find last attribute extent of mft data attribute." );if (ret == -ENOENT ) ret = -EIO ; goto undo_alloc; } a = ctx->attr; - ll =sle64_to_cpu (a->data.non_resident.lowest_vcn); + ll =le64_to_cpu (a->data.non_resident.lowest_vcn); + +down_write (&mft_ni->runlist.lock);/* Search back for the previous last allocated cluster of mft bitmap. */ for (rl2 = rl; rl2 > mft_ni->runlist.rl; rl2--) {if (ll >= rl2->vcn)break ; } -BUG_ON (ll < rl2->vcn); -BUG_ON (ll >= rl2->vcn + rl2->length); +WARN_ON (ll < rl2->vcn); +WARN_ON (ll >= rl2->vcn + rl2->length);/* Get the size for the new mapping pairs array for this extent. */ - mp_size =ntfs_get_size_for_mapping_pairs (vol, rl2, ll,-1 ); + mp_size =ntfs_get_size_for_mapping_pairs (vol, rl2, ll,-1 ,-1 );if (unlikely (mp_size <=0 )) { -ntfs_error (vol->sb,"Get size for mapping pairs failed for " -"mft data attribute extent." ); +ntfs_error (vol->sb, +"Get size for mapping pairs failed for mft data attribute extent." ); ret = mp_size;if (!ret) ret = -EIO ; +up_write (&mft_ni->runlist.lock); goto undo_alloc; } +up_write (&mft_ni->runlist.lock); +/* Expand the attribute record if necessary. */ old_alen =le32_to_cpu (a->length); ret =ntfs_attr_record_resize (ctx->mrec, a, mp_size +le16_to_cpu (a->data.non_resident.mapping_pairs_offset));if (unlikely (ret)) { -if (ret != -ENOSPC ) { -ntfs_error (vol->sb,"Failed to resize attribute " -"record for mft data attribute." ); - goto undo_alloc; - } -// TODO: Deal with this by moving this extent to a new mft -// record or by starting a new extent in a new mft record or by -// moving other attributes out of this mft record. -// Note: Use the special reserved mft records and ensure that -// this extent is not required to find the mft record in -// question. If no free special records left we would need to -// move an existing record away, insert ours in its place, and -// then place the moved record into the newly allocated space -// and we would then need to update all references to this mft -// record appropriately. This is rather complicated... -ntfs_error (vol->sb,"Not enough space in this mft record to " -"accommodate extended mft data attribute " -"extent. Cannot handle this yet." ); - ret = -EOPNOTSUPP ; + ret =ntfs_mft_attr_extend (mft_ni); +if (!ret) + goto extended_ok; +if (ret != -EAGAIN ) + mp_extended = true; goto undo_alloc; } mp_rebuilt = true;/* Generate the mapping pairs array directly into the attr record. */ - ret =ntfs_mapping_pairs_build (vol, (u8 *)a + + ret =ntfs_mapping_pairs_build (vol, (u8 *)a +le16_to_cpu (a->data.non_resident.mapping_pairs_offset), - mp_size, rl2, ll,-1 ,NULL ); + mp_size, rl2, ll,-1 ,NULL ,NULL ,NULL );if (unlikely (ret)) { -ntfs_error (vol->sb,"Failed to build mapping pairs array of " -"mft data attribute." ); +ntfs_error (vol->sb,"Failed to build mapping pairs array of mft data attribute." ); goto undo_alloc; }/* Update the highest_vcn. */ - a->data.non_resident.highest_vcn =cpu_to_sle64 (rl[1 ].vcn -1 ); + a->data.non_resident.highest_vcn =cpu_to_le64 (rl[1 ].vcn -1 );/* * We now have extended the mft data allocated_size by nr clusters. -* Reflect this in the ntfs_inode structure and the attribute record. +* Reflect this in the struct ntfs_inode structure and the attribute record. * @rl is the last (non-terminator) runlist element of mft data * attribute. */
@@ -1902,40 +1761,39 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)* 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); +extended_ok:ntfs_attr_reinit_search_ctx (ctx); ret =ntfs_attr_lookup (mft_ni->type, mft_ni->name, mft_ni->name_len,CASE_SENSITIVE ,0 ,NULL ,0 , ctx);if (unlikely (ret)) { -ntfs_error (vol->sb,"Failed to find first attribute " -"extent of mft data attribute." ); +ntfs_error (vol->sb, +"Failed to find first attribute extent of mft data attribute." ); goto restore_undo_alloc; } a = ctx->attr; } +write_lock_irqsave (&mft_ni->size_lock, flags); - mft_ni->allocated_size += nr << vol->cluster_size_bits; + mft_ni->allocated_size +=NTFS_CLU_TO_B (vol, nr); a->data.non_resident.allocated_size = -cpu_to_sle64 (mft_ni->allocated_size); +cpu_to_le64 (mft_ni->allocated_size);write_unlock_irqrestore (&mft_ni->size_lock, flags);/* 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 (mft_ni); -up_write (&mft_ni->runlist.lock);ntfs_debug ("Done." );return 0 ; restore_undo_alloc:ntfs_attr_reinit_search_ctx (ctx);if (ntfs_attr_lookup (mft_ni->type, mft_ni->name, mft_ni->name_len,CASE_SENSITIVE , rl[1 ].vcn,NULL ,0 , ctx)) { -ntfs_error (vol->sb,"Failed to find last attribute extent of " -"mft data attribute.%s" , es); +ntfs_error (vol->sb, +"Failed to find last attribute extent of mft data attribute.%s" , es);write_lock_irqsave (&mft_ni->size_lock, flags); - mft_ni->allocated_size += nr << vol->cluster_size_bits; + mft_ni->allocated_size +=NTFS_CLU_TO_B (vol, nr);write_unlock_irqrestore (&mft_ni->size_lock, flags);ntfs_attr_put_search_ctx (ctx);unmap_mft_record (mft_ni);
@@ -1948,17 +1806,20 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)return ret; } ctx->attr->data.non_resident.highest_vcn = -cpu_to_sle64 (old_last_vcn -1 ); +cpu_to_le64 (old_last_vcn -1 ); undo_alloc:if (ntfs_cluster_free (mft_ni, old_last_vcn,-1 , ctx) <0 ) { -ntfs_error (vol->sb,"Failed to free clusters from mft data " -"attribute.%s" , es); +ntfs_error (vol->sb,"Failed to free clusters from mft data attribute.%s" , es);NVolSetErrors (vol); }if (ntfs_rl_truncate_nolock (vol, &mft_ni->runlist, old_last_vcn)) { -ntfs_error (vol->sb,"Failed to truncate mft data attribute " -"runlist.%s" , es); +ntfs_error (vol->sb,"Failed to truncate mft data attribute runlist.%s" , es); +NVolSetErrors (vol); + } +if (mp_extended &&ntfs_attr_update_mapping_pairs (mft_ni,0 )) { +ntfs_error (vol->sb,"Failed to restore mapping pairs.%s" , + es);NVolSetErrors (vol); }if (ctx) {
@@ -1968,32 +1829,27 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol) a->data.non_resident.mapping_pairs_offset), old_alen - le16_to_cpu( a->data.non_resident.mapping_pairs_offset), - rl2, ll, -1, NULL)) { -ntfs_error (vol->sb,"Failed to restore mapping pairs " -"array.%s" , es); + rl2, ll, -1, NULL, NULL, NULL)) { +ntfs_error (vol->sb,"Failed to restore mapping pairs array.%s" , es);NVolSetErrors (vol); }if (ntfs_attr_record_resize (ctx->mrec, a, old_alen)) { -ntfs_error (vol->sb,"Failed to restore attribute " -"record.%s" , es); +ntfs_error (vol->sb,"Failed to restore attribute record.%s" , es);NVolSetErrors (vol); } -flush_dcache_mft_record_page (ctx->ntfs_ino);mark_mft_record_dirty (ctx->ntfs_ino); }else if (IS_ERR (ctx->mrec)) { -ntfs_error (vol->sb,"Failed to restore attribute search " -"context.%s" , es); +ntfs_error (vol->sb,"Failed to restore attribute search context.%s" , es);NVolSetErrors (vol); }ntfs_attr_put_search_ctx (ctx); }if (!IS_ERR (mrec))unmap_mft_record (mft_ni); -up_write (&mft_ni->runlist.lock);return ret; } -/** +/* * ntfs_mft_record_layout - layout an mft record into a memory buffer * @vol: volume to which the mft record will belong * @mft_no: mft reference specifying the mft record number
@@ -2006,24 +1862,24 @@ static int ntfs_mft_data_extend_allocation_nolock(ntfs_volume *vol)* * Return 0 on success and -errno on error. */ -static int ntfs_mft_record_layout (const ntfs_volume *vol,const s64 mft_no, -MFT_RECORD *m) +static int ntfs_mft_record_layout (const struct ntfs_volume *vol,const s64 mft_no, +struct mft_record *m) { -ATTR_RECORD *a; +struct attr_record *a;ntfs_debug ("Entering for mft record 0x%llx." , (long long )mft_no);if (mft_no >= (1ll <<32 )) { -ntfs_error (vol->sb,"Mft record number 0x%llx exceeds " -"maximum of 2^32." , (long long )mft_no); +ntfs_error (vol->sb,"Mft record number 0x%llx exceeds maximum of 2^32." , + (long long )mft_no);return -ERANGE ; }/* Start by clearing the whole mft record to gives us a clean slate. */ memset (m,0 , vol->mft_record_size);/* Aligned to 2-byte boundary. */ if (vol->major_ver <3 || (vol->major_ver ==3 && !vol->minor_ver)) - m->usa_ofs =cpu_to_le16 ((sizeof (MFT_RECORD_OLD ) +1 ) & ~1 ); + m->usa_ofs =cpu_to_le16 ((sizeof (struct mft_record_old ) +1 ) & ~1 );else { - m->usa_ofs =cpu_to_le16 ((sizeof (MFT_RECORD ) +1 ) & ~1 ); + m->usa_ofs =cpu_to_le16 ((sizeof (struct mft_record ) +1 ) & ~1 );/* * Set the NTFS 3.1+ specific fields while we know that the * volume version is 3.1+.
@@ -2037,16 +1893,11 @@ static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no, NTFS_BLOCK_SIZE + 1); else { m->usa_count =cpu_to_le16 (1 ); -ntfs_warning (vol->sb,"Sector size is bigger than mft record " -"size. Setting usa_count to 1. If chkdsk " -"reports this as corruption, please email " -"[email protected] stating " -"that you saw this message and that the " -"modified filesystem created was corrupt. " -"Thank you." ); +ntfs_warning (vol->sb, +"Sector size is bigger than mft record size. Setting usa_count to 1. If chkdsk reports this as corruption" ); }/* Set the update sequence number to 1. */ - *(le16 *)((u8 *)m +le16_to_cpu (m->usa_ofs)) =cpu_to_le16 (1 ); + *(__le16 *)((u8 *)m +le16_to_cpu (m->usa_ofs)) =cpu_to_le16 (1 ); m->lsn =0 ; m->sequence_number =cpu_to_le16 (1 ); m->link_count =0 ;
@@ -2067,14 +1918,14 @@ static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no, m->base_mft_record =0 ; m->next_attr_instance =0 ;/* Add the termination attribute. */ - a = (ATTR_RECORD *)((u8 *)m +le16_to_cpu (m->attrs_offset)); + a = (struct attr_record *)((u8 *)m +le16_to_cpu (m->attrs_offset)); a->type =AT_END ; a->length =0 ;ntfs_debug ("Done." );return 0 ; } -/** +/* * ntfs_mft_record_format - format an mft record on an ntfs volume * @vol: volume on which to format the mft record * @mft_no: mft record number to format
@@ -2085,12 +1936,12 @@ static int ntfs_mft_record_layout(const ntfs_volume *vol, const s64 mft_no,* * Return 0 on success and -errno on error. */ -static int ntfs_mft_record_format (const ntfs_volume *vol,const s64 mft_no) +static int ntfs_mft_record_format (const struct ntfs_volume *vol,const s64 mft_no) {loff_t i_size;struct inode *mft_vi = vol->mft_ino; -struct page *page; -MFT_RECORD *m; +struct folio *folio; +struct mft_record *m;pgoff_t index, end_index;unsigned int ofs;int err;
@@ -2100,59 +1951,62 @@ static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)* The index into the page cache and the offset within the page cache * page of the wanted mft record. */ - index = mft_no << vol->mft_record_size_bits >>PAGE_SHIFT ; - ofs = (mft_no << vol->mft_record_size_bits) & ~PAGE_MASK ; + index =NTFS_MFT_NR_TO_PIDX (vol, mft_no); + ofs =NTFS_MFT_NR_TO_POFS (vol, mft_no);/* The maximum valid index into the page cache for $MFT's data. */ i_size =i_size_read (mft_vi); end_index = i_size >>PAGE_SHIFT ;if (unlikely (index >= end_index)) { -if (unlikely (index > end_index || ofs + vol->mft_record_size >= - (i_size & ~PAGE_MASK ))) { -ntfs_error (vol->sb,"Tried to format non-existing mft " -"record 0x%llx." , (long long )mft_no); +if (unlikely (index > end_index || + ofs + vol->mft_record_size > (i_size & ~PAGE_MASK ))) { +ntfs_error (vol->sb,"Tried to format non-existing mft record 0x%llx." , + (long long )mft_no);return -ENOENT ; } } -/* Read, map, and pin the page containing the mft record. */ - page =ntfs_map_page (mft_vi->i_mapping, index); -if (IS_ERR (page)) { -ntfs_error (vol->sb,"Failed to map page containing mft record " -"to format 0x%llx." , (long long )mft_no); -return PTR_ERR (page); - } -lock_page (page); -BUG_ON (!PageUptodate (page)); -ClearPageUptodate (page); - m = (MFT_RECORD *)((u8 *)page_address (page) + ofs); + +/* Read, map, and pin the folio containing the mft record. */ + folio =read_mapping_folio (mft_vi->i_mapping, index,NULL ); +if (IS_ERR (folio)) { +ntfs_error (vol->sb,"Failed to map page containing mft record to format 0x%llx." , + (long long )mft_no); +return PTR_ERR (folio); + } +folio_lock (folio); +folio_clear_uptodate (folio); + m = (struct mft_record *)((u8 *)kmap_local_folio (folio,0 ) + ofs); err =ntfs_mft_record_layout (vol, mft_no, m);if (unlikely (err)) {ntfs_error (vol->sb,"Failed to layout mft record 0x%llx." , (long long )mft_no); -SetPageUptodate (page); -unlock_page (page); -ntfs_unmap_page (page); +folio_mark_uptodate (folio); +folio_unlock (folio); +kunmap_local (m); +folio_put (folio);return err; } -flush_dcache_page (page); -SetPageUptodate (page); -unlock_page (page); +pre_write_mst_fixup ((struct ntfs_record *)m, vol->mft_record_size); +folio_mark_uptodate (folio);/* * Make sure the mft record is written out to disk. We could use * ilookup5() to check if an inode is in icache and so on but this is * unnecessary as ntfs_writepage() will write the dirty record anyway. */ -mark_ntfs_record_dirty (page, ofs); -ntfs_unmap_page (page); +ntfs_mft_mark_dirty (folio); +folio_unlock (folio); +kunmap_local (m); +folio_put (folio);ntfs_debug ("Done." );return 0 ; } -/** +/* * ntfs_mft_record_alloc - allocate an mft record on an ntfs volume * @vol: [IN] volume on which to allocate the mft record * @mode: [IN] mode if want a file or directory, i.e. base inode or 0 +* @ni: [OUT] on success, set to the allocated ntfs inode * @base_ni: [IN] open base inode if allocating an extent mft record or NULL -* @mrec: [OUT] on successful return this is the mapped mft record +* @ni_mrec: [OUT] on successful return this is the mapped mft record * * Allocate an mft record in $MFT/$DATA of an open ntfs volume @vol. *
@@ -2180,8 +2034,8 @@ static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)* optimize this we start scanning at the place specified by @base_ni or if * @base_ni is NULL we start where we last stopped and we perform wrap around * when we reach the end. Note, we do not try to allocate mft records below -* number 24 because numbers 0 to 15 are the defined system files anyway and 16 -* to 24 are special in that they are used for storing extension mft records +* number 64 because numbers 0 to 15 are the defined system files anyway and 16 +* to 64 are special in that they are used for storing extension mft records * for the $DATA attribute of $MFT. This is required to avoid the possibility * of creating a runlist with a circular dependency which once written to disk * can never be read in again. Windows will only use records 16 to 24 for
@@ -2191,7 +2045,7 @@ static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)* doing this at some later time, it does not matter much for now. * * When scanning the mft bitmap, we only search up to the last allocated mft -* record. If there are no free records left in the range 24 to number of +* record. If there are no free records left in the range 64 to number of * allocated mft records, then we extend the $MFT/$DATA attribute in order to * create free mft records. We extend the allocated size of $MFT/$DATA by 16 * records at a time or one cluster, if cluster size is above 16kiB. If there
@@ -2200,24 +2054,24 @@ static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)* * No matter how many mft records we allocate, we initialize only the first * allocated mft record, incrementing mft data size and initialized size -* accordingly, open an ntfs_inode for it and return it to the caller, unless -* there are less than 24 mft records, in which case we allocate and initialize -* mft records until we reach record 24 which we consider as the first free mft +* accordingly, open an struct ntfs_inode for it and return it to the caller, unless +* there are less than 64 mft records, in which case we allocate and initialize +* mft records until we reach record 64 which we consider as the first free mft * record for use by normal files. * * If during any stage we overflow the initialized data in the mft bitmap, we * extend the initialized size (and data size) by 8 bytes, allocating another * cluster if required. The bitmap data size has to be at least equal to the * number of mft records in the mft, but it can be bigger, in which case the -* superflous bits are padded with zeroes. +* superfluous bits are padded with zeroes. * * Thus, when we return successfully (IS_ERR() is false), we will have: * - initialized / extended the mft bitmap if necessary, * - initialized / extended the mft data if necessary, * - set the bit corresponding to the mft record being allocated in the * mft bitmap, -* - opened an ntfs_inode for the allocated mft record, and we will have -* - returned the ntfs_inode as well as the allocated mapped, pinned, and +* - opened an struct ntfs_inode for the allocated mft record, and we will have +* - returned the struct ntfs_inode as well as the allocated mapped, pinned, and * locked mft record. * * On error, the volume will be left in a consistent state and no record will
@@ -2237,42 +2091,46 @@ static int ntfs_mft_record_format(const ntfs_volume *vol, const s64 mft_no)* easier because otherwise there might be circular invocations of functions * when reading the bitmap. */ -ntfs_inode *ntfs_mft_record_alloc (ntfs_volume *vol,const int mode, -ntfs_inode *base_ni,MFT_RECORD **mrec) +int ntfs_mft_record_alloc (struct ntfs_volume *vol,const int mode, +struct ntfs_inode **ni,struct ntfs_inode *base_ni, +struct mft_record **ni_mrec) {s64 ll, bit, old_data_initialized, old_data_size;unsigned long flags; -struct inode *vi; -struct page *page; -ntfs_inode *mft_ni, *mftbmp_ni, *ni; -ntfs_attr_search_ctx *ctx; -MFT_RECORD *m; -ATTR_RECORD *a; +struct folio *folio; +struct ntfs_inode *mft_ni, *mftbmp_ni; +struct ntfs_attr_search_ctx *ctx; +struct mft_record *m =NULL ; +struct attr_record *a;pgoff_t index;unsigned int ofs;int err; -le16 seq_no, usn; +__le16 seq_no, usn;bool record_formatted = false; +unsigned int memalloc_flags; -if (base_ni) { -ntfs_debug ("Entering (allocating an extent mft record for " -"base mft record 0x%llx)." , +if (base_ni && *ni) +return -EINVAL ; + +/* @mode and @base_ni are mutually exclusive. */ +if (mode && base_ni) +return -EINVAL ; + +if (base_ni) +ntfs_debug ("Entering (allocating an extent mft record for base mft record 0x%llx)." , (long long )base_ni->mft_no); -/* @mode and @base_ni are mutually exclusive. */ -BUG_ON (mode); - }else +else ntfs_debug ("Entering (allocating a base mft record)." ); -if (mode) { -/* @mode and @base_ni are mutually exclusive. */ -BUG_ON (base_ni); -/* We only support creation of normal files and directories. */ -if (!S_ISREG (mode) && !S_ISDIR (mode)) -return ERR_PTR (-EOPNOTSUPP ); - } -BUG_ON (!mrec); + + memalloc_flags =memalloc_nofs_save (); + mft_ni =NTFS_I (vol->mft_ino); +if (!base_ni || base_ni->mft_no !=FILE_MFT ) +mutex_lock (&mft_ni->mrec_lock); mftbmp_ni =NTFS_I (vol->mftbmp_ino); -down_write (&vol->mftbmp_lock); +search_free_rec: +if (!base_ni || base_ni->mft_no !=FILE_MFT ) +down_write (&vol->mftbmp_lock); bit =ntfs_mft_bitmap_find_and_alloc_free_rec_nolock (vol, base_ni);if (bit >=0 ) { ntfs_debug("Found and allocated free record (#1), bit 0x%llx.",
@@ -2280,9 +2138,19 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode, goto have_alloc_rec; }if (bit != -ENOSPC ) { -up_write (&vol->mftbmp_lock); -return ERR_PTR (bit); +if (!base_ni || base_ni->mft_no !=FILE_MFT ) { +up_write (&vol->mftbmp_lock); +mutex_unlock (&mft_ni->mrec_lock); + } +memalloc_nofs_restore (memalloc_flags); +return bit; + } + +if (base_ni && base_ni->mft_no ==FILE_MFT ) { +memalloc_nofs_restore (memalloc_flags); +return bit; } +/* * No free mft records left. If the mft bitmap already covers more * than the currently used mft records, the next records are all free,
@@ -2297,10 +2165,11 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,read_lock_irqsave (&mftbmp_ni->size_lock, flags); old_data_initialized = mftbmp_ni->initialized_size;read_unlock_irqrestore (&mftbmp_ni->size_lock, flags); -if (old_data_initialized <<3 > ll && old_data_initialized >3 ) { +if (old_data_initialized <<3 > ll && + old_data_initialized >RESERVED_MFT_RECORDS /8 ) { bit = ll; -if (bit <24 ) - bit =24 ; +if (bit <RESERVED_MFT_RECORDS ) + bit =RESERVED_MFT_RECORDS ;if (unlikely (bit >= (1ll <<32 ))) goto max_err_out; ntfs_debug("Found free record (#2), bit 0x%llx.",
@@ -2317,28 +2186,28 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode, goto max_err_out;read_lock_irqsave (&mftbmp_ni->size_lock, flags); old_data_size = mftbmp_ni->allocated_size; -ntfs_debug ("Status of mftbmp before extension: allocated_size 0x%llx, " -"data_size 0x%llx, initialized_size 0x%llx." , - (long long )old_data_size, - (long long )i_size_read (vol->mftbmp_ino), - (long long )old_data_initialized); +ntfs_debug ("Status of mftbmp before extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx." , + old_data_size,i_size_read (vol->mftbmp_ino), + old_data_initialized);read_unlock_irqrestore (&mftbmp_ni->size_lock, flags);if (old_data_initialized +8 > old_data_size) {/* Need to extend bitmap by one more cluster. */ ntfs_debug ("mftbmp: initialized_size + 8 > allocated_size." ); err =ntfs_mft_bitmap_extend_allocation_nolock (vol); +if (err == -EAGAIN ) + err =ntfs_mft_bitmap_extend_allocation_nolock (vol); +if (unlikely (err)) { -up_write (&vol->mftbmp_lock); +if (!base_ni || base_ni->mft_no !=FILE_MFT ) +up_write (&vol->mftbmp_lock); goto err_out; }#ifdef DEBUG read_lock_irqsave (&mftbmp_ni->size_lock, flags); -ntfs_debug ("Status of mftbmp after allocation extension: " -"allocated_size 0x%llx, data_size 0x%llx, " -"initialized_size 0x%llx." , - (long long )mftbmp_ni->allocated_size, - (long long )i_size_read (vol->mftbmp_ino), - (long long )mftbmp_ni->initialized_size); +ntfs_debug ("Status of mftbmp after allocation extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx." , + mftbmp_ni->allocated_size, +i_size_read (vol->mftbmp_ino), + mftbmp_ni->initialized_size);read_unlock_irqrestore (&mftbmp_ni->size_lock, flags);#endif /* DEBUG */ }
@@ -2349,17 +2218,16 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,*/ err =ntfs_mft_bitmap_extend_initialized_nolock (vol);if (unlikely (err)) { -up_write (&vol->mftbmp_lock); +if (!base_ni || base_ni->mft_no !=FILE_MFT ) +up_write (&vol->mftbmp_lock); goto err_out; }#ifdef DEBUG read_lock_irqsave (&mftbmp_ni->size_lock, flags); -ntfs_debug ("Status of mftbmp after initialized extension: " -"allocated_size 0x%llx, data_size 0x%llx, " -"initialized_size 0x%llx." , - (long long )mftbmp_ni->allocated_size, - (long long )i_size_read (vol->mftbmp_ino), - (long long )mftbmp_ni->initialized_size); +ntfs_debug ("Status of mftbmp after initialized extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx." , + mftbmp_ni->allocated_size, +i_size_read (vol->mftbmp_ino), + mftbmp_ni->initialized_size);read_unlock_irqrestore (&mftbmp_ni->size_lock, flags);#endif /* DEBUG */ ntfs_debug ("Found free record (#3), bit 0x%llx." , (long long )bit);
@@ -2369,7 +2237,8 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode, err =ntfs_bitmap_set_bit (vol->mftbmp_ino, bit);if (unlikely (err)) {ntfs_error (vol->sb,"Failed to allocate bit in mft bitmap." ); -up_write (&vol->mftbmp_lock); +if (!base_ni || base_ni->mft_no !=FILE_MFT ) +up_write (&vol->mftbmp_lock); goto err_out; }ntfs_debug ("Set bit 0x%llx in mft bitmap." , (long long )bit);
@@ -2397,34 +2266,35 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,* actually traversed more than once when a freshly formatted volume is * first written to so it optimizes away nicely in the common case. */ -read_lock_irqsave (&mft_ni->size_lock, flags); -ntfs_debug ("Status of mft data before extension: " -"allocated_size 0x%llx, data_size 0x%llx, " -"initialized_size 0x%llx." , - (long long )mft_ni->allocated_size, - (long long )i_size_read (vol->mft_ino), - (long long )mft_ni->initialized_size); -while (ll > mft_ni->allocated_size) { -read_unlock_irqrestore (&mft_ni->size_lock, flags); - err =ntfs_mft_data_extend_allocation_nolock (vol); -if (unlikely (err)) { -ntfs_error (vol->sb,"Failed to extend mft data " -"allocation." ); - goto undo_mftbmp_alloc_nolock; - } +if (!base_ni || base_ni->mft_no !=FILE_MFT ) {read_lock_irqsave (&mft_ni->size_lock, flags); -ntfs_debug ("Status of mft data after allocation extension: " -"allocated_size 0x%llx, data_size 0x%llx, " -"initialized_size 0x%llx." , - (long long )mft_ni->allocated_size, - (long long )i_size_read (vol->mft_ino), - (long long )mft_ni->initialized_size); +ntfs_debug ("Status of mft data before extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx." , + mft_ni->allocated_size,i_size_read (vol->mft_ino), + mft_ni->initialized_size); +while (ll > mft_ni->allocated_size) { +read_unlock_irqrestore (&mft_ni->size_lock, flags); + err =ntfs_mft_data_extend_allocation_nolock (vol); +if (err == -EAGAIN ) + err =ntfs_mft_data_extend_allocation_nolock (vol); + +if (unlikely (err)) { +ntfs_error (vol->sb,"Failed to extend mft data allocation." ); + goto undo_mftbmp_alloc_nolock; + } +read_lock_irqsave (&mft_ni->size_lock, flags); +ntfs_debug ("Status of mft data after allocation extension: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx." , + mft_ni->allocated_size,i_size_read (vol->mft_ino), + mft_ni->initialized_size); + } +read_unlock_irqrestore (&mft_ni->size_lock, flags); + }else if (ll > mft_ni->allocated_size) { + err = -ENOSPC ; + goto undo_mftbmp_alloc_nolock; } -read_unlock_irqrestore (&mft_ni->size_lock, flags);/* * Extend mft data initialized size (and data size of course) to reach * the allocated mft record, formatting the mft records allong the way. -* Note: We only modify the ntfs_inode structure as that is all that is +* Note: We only modify the struct ntfs_inode structure as that is all that is * needed by ntfs_mft_record_format(). We will update the attribute * record itself in one fell swoop later on. */
@@ -2433,7 +2303,7 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode, old_data_size = vol->mft_ino->i_size;while (ll > mft_ni->initialized_size) {s64 new_initialized_size, mft_no; - + new_initialized_size = mft_ni->initialized_size + vol->mft_record_size; mft_no = mft_ni->initialized_size >> vol->mft_record_size_bits;
@@ -2469,8 +2339,7 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode, err =ntfs_attr_lookup (mft_ni->type, mft_ni->name, mft_ni->name_len,CASE_SENSITIVE ,0 ,NULL ,0 , ctx);if (unlikely (err)) { -ntfs_error (vol->sb,"Failed to find first attribute extent of " -"mft data attribute." ); +ntfs_error (vol->sb,"Failed to find first attribute extent of mft data attribute." );ntfs_attr_put_search_ctx (ctx);unmap_mft_record (mft_ni); goto undo_data_init;
@@ -2478,24 +2347,20 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode, a = ctx->attr;read_lock_irqsave (&mft_ni->size_lock, flags); a->data.non_resident.initialized_size = -cpu_to_sle64 (mft_ni->initialized_size); +cpu_to_le64 (mft_ni->initialized_size); a->data.non_resident.data_size = -cpu_to_sle64 (i_size_read (vol->mft_ino)); +cpu_to_le64 (i_size_read (vol->mft_ino));read_unlock_irqrestore (&mft_ni->size_lock, flags);/* 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 (mft_ni);read_lock_irqsave (&mft_ni->size_lock, flags); -ntfs_debug ("Status of mft data after mft record initialization: " -"allocated_size 0x%llx, data_size 0x%llx, " -"initialized_size 0x%llx." , - (long long )mft_ni->allocated_size, - (long long )i_size_read (vol->mft_ino), - (long long )mft_ni->initialized_size); -BUG_ON (i_size_read (vol->mft_ino) > mft_ni->allocated_size); -BUG_ON (mft_ni->initialized_size >i_size_read (vol->mft_ino)); +ntfs_debug ("Status of mft data after mft record initialization: allocated_size 0x%llx, data_size 0x%llx, initialized_size 0x%llx." , + mft_ni->allocated_size,i_size_read (vol->mft_ino), + mft_ni->initialized_size); +WARN_ON (i_size_read (vol->mft_ino) > mft_ni->allocated_size); +WARN_ON (mft_ni->initialized_size >i_size_read (vol->mft_ino));read_unlock_irqrestore (&mft_ni->size_lock, flags); mft_rec_already_initialized:/*
@@ -2507,41 +2372,39 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,* that it is allocated in the mft bitmap means that no-one will try to * allocate it either. */ -up_write (&vol->mftbmp_lock); +if (!base_ni || base_ni->mft_no !=FILE_MFT ) +up_write (&vol->mftbmp_lock);/* * We now have allocated and initialized the mft record. Calculate the * index of and the offset within the page cache page the record is in. */ - index = bit << vol->mft_record_size_bits >>PAGE_SHIFT ; - ofs = (bit << vol->mft_record_size_bits) & ~PAGE_MASK ; -/* Read, map, and pin the page containing the mft record. */ - page =ntfs_map_page (vol->mft_ino->i_mapping, index); -if (IS_ERR (page)) { -ntfs_error (vol->sb,"Failed to map page containing allocated " -"mft record 0x%llx." , (long long )bit); - err =PTR_ERR (page); + index =NTFS_MFT_NR_TO_PIDX (vol, bit); + ofs =NTFS_MFT_NR_TO_POFS (vol, bit); +/* Read, map, and pin the folio containing the mft record. */ + folio =read_mapping_folio (vol->mft_ino->i_mapping, index,NULL ); +if (IS_ERR (folio)) { +ntfs_error (vol->sb,"Failed to map page containing allocated mft record 0x%llx." , + bit); + err =PTR_ERR (folio); goto undo_mftbmp_alloc; } -lock_page (page); -BUG_ON (!PageUptodate (page)); -ClearPageUptodate (page); - m = (MFT_RECORD *)((u8 *)page_address (page) + ofs); +folio_lock (folio); +folio_clear_uptodate (folio); + m = (struct mft_record *)((u8 *)kmap_local_folio (folio,0 ) + ofs);/* If we just formatted the mft record no need to do it again. */ if (!record_formatted) {/* Sanity check that the mft record is really not in use. */ if (ntfs_is_file_record (m->magic) && (m->flags &MFT_RECORD_IN_USE )) { -ntfs_error (vol->sb,"Mft record 0x%llx was marked " -"free in mft bitmap but is marked " -"used itself. Corrupt filesystem. " -"Unmount and run chkdsk." , - (long long )bit); - err = -EIO ; -SetPageUptodate (page); -unlock_page (page); -ntfs_unmap_page (page); +ntfs_warning (vol->sb, +"Mft record 0x%llx was marked free in mft bitmap but is marked used itself. Unmount and run chkdsk." , + bit); +folio_mark_uptodate (folio); +folio_unlock (folio); +kunmap_local (m); +folio_put (folio);NVolSetErrors (vol); - goto undo_mftbmp_alloc; + goto search_free_rec; }/* * We need to (re-)format the mft record, preserving the
@@ -2551,29 +2414,30 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,* wrong with the previous mft record. */ seq_no = m->sequence_number; - usn = *(le16 *)((u8 *)m +le16_to_cpu (m->usa_ofs)); + usn = *(__le16 *)((u8 *)m +le16_to_cpu (m->usa_ofs)); err =ntfs_mft_record_layout (vol, bit, m);if (unlikely (err)) { -ntfs_error (vol->sb,"Failed to layout allocated mft " -"record 0x%llx." , (long long )bit); -SetPageUptodate (page); -unlock_page (page); -ntfs_unmap_page (page); +ntfs_error (vol->sb,"Failed to layout allocated mft record 0x%llx." , + bit); +folio_mark_uptodate (folio); +folio_unlock (folio); +kunmap_local (m); +folio_put (folio); goto undo_mftbmp_alloc; }if (seq_no) m->sequence_number = seq_no;if (usn &&le16_to_cpu (usn) !=0xffff ) - *(le16 *)((u8 *)m +le16_to_cpu (m->usa_ofs)) = usn; + *(__le16 *)((u8 *)m +le16_to_cpu (m->usa_ofs)) = usn; +pre_write_mst_fixup ((struct ntfs_record *)m, vol->mft_record_size); }/* Set the mft record itself in use. */ m->flags |=MFT_RECORD_IN_USE ;if (S_ISDIR (mode)) m->flags |=MFT_RECORD_IS_DIRECTORY ; -flush_dcache_page (page); -SetPageUptodate (page); +folio_mark_uptodate (folio);if (base_ni) { -MFT_RECORD *m_tmp; +struct mft_record *m_tmp;/* * Setup the base mft record in the extent mft record. This
@@ -2587,22 +2451,24 @@ ntfs_inode *ntfs_mft_record_alloc(ntfs_volume *vol, const int mode,* attach it to the base inode @base_ni and map, pin, and lock * its, i.e. the allocated, mft record. */ - m_tmp =map_extent_mft_record (base_ni, bit, &ni); + m_tmp =map_extent_mft_record (base_ni, +MK_MREF (bit,le16_to_cpu (m->sequence_number)), + ni);if (IS_ERR (m_tmp)) { -ntfs_error (vol->sb,"Failed to map allocated extent " -"mft record 0x%llx." , (long long )bit); +ntfs_error (vol->sb,"Failed to map allocated extent mft record 0x%llx." , + bit); err =PTR_ERR (m_tmp);/* Set the mft record itself not in use. */ m->flags &=cpu_to_le16 ( ~le16_to_cpu (MFT_RECORD_IN_USE ));
Lines of this file are not shown. View the raw message.
fs/ntfs/mst.c +35 -30
65 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 v9 7/17 ntfs: update directory operations
In reply to Namjae JeonUpdate the directory and index operations to support full read-write functionality and use the folio API, including directory modification.
--- fs/ntfs/dir.c | 1650 +++++++++++++------------------- fs/ntfs/index.c | 2403 ++++++++++++++++++++++++++++++++++++++++------- 2 files changed, 2713 insertions(+), 1340 deletions(-)
fs/ntfs/dir.c +673 -977
@@ -1,29 +1,29 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* dir.c - NTFS kernel directory operations. Part of the Linux-NTFS project. +* NTFS kernel directory operations. * * 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" + +#include <linux/filelock.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 }; -/** +/* * 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
@@ -61,30 +61,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 +101,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 +132,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 +147,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 +163,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 +194,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 +224,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 +234,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 +253,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 +283,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 +403,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 +418,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 +434,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 +451,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 +465,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 +496,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 +506,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 +525,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 +545,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_cluster_to_pidx (vol, old_vcn) == +ntfs_cluster_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 +576,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,859 +591,497 @@ 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; - } -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; + 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 ; } - 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 +=le16_to_cpu (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_no_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 +=le16_to_cpu (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 (le32_to_cpu (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 * @filp: file structure describing the inode
@@ -1457,13 +1106,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 +1136,58 @@ 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_CHILD ); +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)); + +if (MREF_LE (fn->parent_directory) == ni->mft_no) +continue ; + + 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_NORMAL ); + 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 +1195,42 @@ 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 = ntfs_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = ntfs_compat_ioctl, +#endif + .setlease = generic_setlease, };
fs/ntfs/index.c +2040 -363
1,000 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 v9 8/17 ntfs: update file operations
In reply to Namjae JeonRewrite the file operations to utilize the iomap infrastructure, replacing the legacy buffer-head based implementation.
Implement ntfs_setattr() with size change handling, uid/gid/mode.
Add support for Direct I/O.
Add support for fallocate with the FALLOC_FL_KEEP_SIZE, FALLOC_FL_PUNCH_HOLE, FALLOC_FL_COLLAPSE_RANGE, FALLOC_FL_INSERT_RANGE and FALLOC_FL_ALLOCATE_RANGE modes.
Implement .llseek with SEEK_DATA / SEEK_HOLE support.
Implement ntfs_fiemap() using iomap_fiemap().
Add FS_IOC_SHUTDOWN, FS_IOC_[GS]ETFSLABEL, FITRIM ioctl support.
--- fs/ntfs/file.c | 2880 +++++++++++++++++------------------------------- 1 file changed, 1022 insertions(+), 1858 deletions(-)
fs/ntfs/file.c +1022 -1858
@@ -1,34 +1,31 @@// SPDX-License-Identifier: GPL-2.0-or-later /* -* file.c - NTFS kernel file operations. Part of the Linux-NTFS project. +* NTFS kernel file operations. * * 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 <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 "reparse.h" +#include "ea.h" +#include "iomap.h" +#include "bitmap.h" + +#include <linux/filelock.h> -/** +/* * ntfs_file_open - called when an inode is about to be opened * @vi: inode to be opened * @filp: file structure describing the inode
@@ -48,1948 +45,1115 @@*/ 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 ; } + + filp->f_mode |=FMODE_NOWAIT |FMODE_CAN_ODIRECT ; +return generic_file_open (vi, filp); } -#ifdef NTFS_RW - -/** -* 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). -* -* 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. +/* +* Trim preallocated space on file release. * -* 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. +* When the preallo_size mount option is set (default 64KB), writes extend +* allocated_size and runlist in units of preallocated size to reduce +* runlist merge overhead for small writes. This can leave +* allocated_size > data_size if not all preallocated space is used. * -* 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. +* We perform the trim here because ->release() is called only when +* the file is no longer open. At this point, no further writes can occur, +* so it is safe to reclaim the unused preallocated space. * -* Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be -* held by the caller. +* Returns 0 on success, or negative error on failure. */ -static int ntfs_attr_extend_initialized (ntfs_inode *ni,const s64 new_init_size) +static int ntfs_trim_prealloc (struct inode *vi) { -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 ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; +struct runlist_element *rl; +s64 aligned_data_size; +s64 vcn_ds, vcn_tr; +ssize_t rc; +int err =0 ; -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; -} +inode_lock (vi); +mutex_lock (&ni->mrec_lock); +down_write (&ni->runlist.lock); -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; + aligned_data_size =round_up (ni->data_size, vol->cluster_size); +if (aligned_data_size >= ni->allocated_size) + goto out_unlock; + + vcn_ds =ntfs_bytes_to_cluster (vol, aligned_data_size); + vcn_tr =-1 ; + rc = ni->runlist.count -2 ; + rl = ni->runlist.rl; + +while (rc >=0 && rl[rc].lcn ==LCN_HOLE && vcn_ds <= rl[rc].vcn) { + vcn_tr = rl[rc].vcn; + rc--; } - 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); - } + +if (vcn_tr >=0 ) { + err =ntfs_rl_truncate_nolock (vol, &ni->runlist, vcn_tr); +if (err) { +kvfree (ni->runlist.rl); + ni->runlist.rl =NULL ; +ntfs_error (vol->sb,"Preallocated block rollback failed" ); }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; - } + ni->allocated_size =ntfs_cluster_to_bytes (vol, vcn_tr); + err =ntfs_attr_update_mapping_pairs (ni,0 ); +if (err) +ntfs_error (vol->sb, +"Failed to rollback mapping pairs for prealloc" ); } } -/* -* 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. -*/ -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; -} -/** -* __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 -* -* Obtain @nr_pages locked page cache pages from the mapping @mapping and -* starting at index @index. -* -* If a page is newly created, add it to lru list -* -* Note, the page locks are obtained in ascending page index order. -*/ -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 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; - } - } - 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; - } - pages[nr] = *cached_page; - *cached_page =NULL ; - } - index++; - nr++; - }while (nr < nr_pages); -out: +out_unlock: +up_write (&ni->runlist.lock); +mutex_unlock (&ni->mrec_lock); +inode_unlock (vi); +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) +static int ntfs_file_release (struct inode *vi,struct file *filp) { -lock_buffer (bh); -get_bh (bh); - bh->b_end_io = end_buffer_read_sync; -submit_bh (REQ_OP_READ , bh); +if (!NInoCompressed (NTFS_I (vi))) +return ntfs_trim_prealloc (vi); + +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 +/* +* 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 * -* 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. +* 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 @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. +* 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. * -* i_size is not to be modified yet. +* 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). * -* Return 0 on success or -errno on error. +* 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_prepare_pages_for_non_resident_write (struct page **pages, -unsigned nr_pages,s64 pos,size_t bytes) +static int ntfs_file_fsync (struct file *filp,loff_t start,loff_t end, +int datasync) { -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); +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; + +ntfs_debug ("Entering for inode 0x%lx." , vi->i_ino); + +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_CHILD ); +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 ; - } -/* -* 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); - } +mutex_lock_nested (&NTFS_I (parent_vi)->mrec_lock,NTFS_INODE_MUTEX_NORMAL ); + 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 ; } -/* 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); - } - } +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 ; - } -/* 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); + + attr_vi =ntfs_attr_iget (vi, ctx->attr->type, + name, ctx->attr->name_length); +if (IS_ERR (attr_vi))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. -*/ -read_lock_irqsave (&ni->size_lock, flags); - initialized_size = ni->allocated_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 (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. -*/ -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; - } +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 - 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); - } -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 ; - } -/* @m is not used any more so do not set it. */ - a = ctx->attr; - } -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); - } -/* 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; - } -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 ; - } - } -/* -* 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); +spin_unlock (&attr_vi->i_lock); +iput (attr_vi); } } -/* -* 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); - } -flush_dcache_mft_record_page (ctx->ntfs_ino); -mark_mft_record_dirty (ctx->ntfs_ino); - } - } -/* Release the mft record and the attribute. */ -if (status.mft_attr_mapped) { -ntfs_attr_put_search_ctx (ctx); -unmap_mft_record (base_ni); - } -/* 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; -} +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 ); -static inline void ntfs_flush_dcache_pages (struct page **pages, -unsigned nr_pages) -{ -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. +* 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). */ -do { - --nr_pages; -flush_dcache_page (pages[nr_pages]); - }while (nr_pages >0 ); + 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_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 int ntfs_setattr_size (struct inode *vi,struct iattr *attr) { -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; +struct ntfs_inode *ni =NTFS_I (vi);int err; +loff_t old_size = vi->i_size; - 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 ; +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" ); +return -EOPNOTSUPP ; } -/* -* 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 =inode_newsize_ok (vi, attr->ia_size); +if (err) +return err; + +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) +return err; } - 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; + +truncate_setsize (vi, attr->ia_size); + err =ntfs_truncate_vfs (vi, attr->ia_size, old_size); +if (err) { +i_size_write (vi, old_size); +return err; } - 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 (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_seek_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); } -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." ); -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. +/* +* ntfs_setattr * -* 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. +* Called from notify_change() when an attribute is being changed. * -* Return 0 on success or -errno on error. +* NOTE: Changes in inode size are not supported yet for compressed or +* encrypted files. */ -static int ntfs_commit_pages_after_write (struct page **pages, -const unsigned nr_pages,s64 pos,size_t bytes) +int ntfs_setattr (struct mnt_idmap *idmap,struct dentry *dentry, +struct iattr *attr) { -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; +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; -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); +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 ) { + err =ntfs_setattr_size (vi, attr); +if (err) + goto out; + + ia_valid |=ATTR_MTIME |ATTR_CTIME ; } -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); + +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; } -/* 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." ); -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); + +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); } -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) -{ -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); +mark_inode_dirty (vi); 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 err; } -/** -* 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) +int ntfs_getattr (struct mnt_idmap *idmap,const struct path *path, +struct kstat *stat,unsigned int request_mask, +unsigned int query_flags) { -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)); +struct inode *inode =d_backing_inode (path->dentry); +struct ntfs_inode *ni =NTFS_I (inode); + +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; + +if (NInoCompressed (ni)) + stat->attributes |=STATX_ATTR_COMPRESSED ; + +if (NInoEncrypted (ni)) + stat->attributes |=STATX_ATTR_ENCRYPTED ; + +if (inode->i_flags &S_IMMUTABLE ) + stat->attributes |=STATX_ATTR_IMMUTABLE ; + +if (inode->i_flags &S_APPEND ) + stat->attributes |=STATX_ATTR_APPEND ; + + stat->attributes_mask |=STATX_ATTR_COMPRESSED |STATX_ATTR_ENCRYPTED | +STATX_ATTR_IMMUTABLE |STATX_ATTR_APPEND ; +/* -* If a previous ntfs_truncate() failed, repeat it and abort if it -* fails again. +* If it's a compressed or encrypted file, NTFS currently +* does not support DIO. For normal files, we report the bdev +* logical block size. */ -if (unlikely (NInoTruncateFailed (ni))) { -int err; +if (request_mask &STATX_DIOALIGN &&S_ISREG (inode->i_mode)) { +unsigned int align = +bdev_logical_block_size (inode->i_sb->s_bdev); -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); -return err; + stat->result_mask |=STATX_DIOALIGN ; +if (!NInoCompressed (ni) && !NInoEncrypted (ni)) { + stat->dio_mem_align = align; + stat->dio_offset_align = align; } } -/* -* 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 (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 ; - } -/* 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 ; - } - } - 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); + +return 0 ; +} + +static loff_t ntfs_file_llseek (struct file *file,loff_t offset,int whence) +{ +struct inode *inode = file->f_mapping->host; + +switch (whence) { +case SEEK_HOLE : +inode_lock_shared (inode); + offset =iomap_seek_hole (inode, offset, &ntfs_seek_iomap_ops); +inode_unlock_shared (inode); +break ; +case SEEK_DATA : +inode_lock_shared (inode); + offset =iomap_seek_data (inode, offset, &ntfs_seek_iomap_ops); +inode_unlock_shared (inode); +break ; +default : +return generic_file_llseek_size (file, offset, whence, + inode->i_sb->s_maxbytes, +i_size_read (inode)); + } +if (offset <0 ) +return offset; +return vfs_setpos (file, offset, inode->i_sb->s_maxbytes); +} + +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; } -do { -unlock_page (pages[--do_pages]); -put_page (pages[do_pages]); - }while (do_pages); -if (unlikely (status <0 )) { -iov_iter_revert (i, copied); -break ; + +file_accessed (iocb->ki_filp); + ret =iomap_dio_rw (iocb, to, &ntfs_read_iomap_ops,NULL ,0 , +NULL ,0 ); + }else { + ret =generic_file_read_iter (iocb, to); + } + +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); } -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; + } + +return 0 ; +} + +static const struct iomap_dio_ops ntfs_write_dio_ops = { + .end_io = ntfs_file_write_dio_end_io, +}; + +static ssize_t ntfs_dio_write_iter (struct kiocb *iocb,struct iov_iter *from) +{ +ssize_t ret; + + 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 ) { + ret = written; + goto out; } - pos += copied; - written += copied; -balance_dirty_pages_ratelimited (mapping); -if (fatal_signal_pending (current)) { - status = -EINTR ; -break ; + + ret += written; + end = iocb->ki_pos + written -1 ; + ret2 =filemap_write_and_wait_range (iocb->ki_filp->f_mapping, + offset, end); +if (ret2) { + ret = -EIO ; + goto out; } - }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; +if (!ret2) +invalidate_mapping_pages (iocb->ki_filp->f_mapping, + offset >>PAGE_SHIFT , + end >>PAGE_SHIFT ); + } + +out: +return ret; } -/** -* 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; +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; -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); +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; + + 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 (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 =ntfs_dio_write_iter (iocb, from); +else + ret =iomap_file_buffered_write (iocb, from, &ntfs_write_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); +out: +if (ret <0 && ret != -EIOCBQUEUED ) { +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); + } + } +out_lock:inode_unlock (vi); - iocb->ki_pos += written; -if (likely (written >0 )) - written =generic_write_sync (iocb, written); -return written ? written : err; +if (ret >0 ) + ret =generic_write_sync (iocb, ret); +return ret; } -/** -* 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) +static vm_fault_t ntfs_filemap_page_mkwrite (struct vm_fault *vmf) { -struct inode *vi = filp->f_mapping->host; -int err, ret =0 ; +struct inode *inode =file_inode (vmf->vma->vm_file); +vm_fault_t ret; -ntfs_debug ("Entering for inode 0x%lx." , vi->i_ino); +sb_start_pagefault (inode->i_sb); +file_update_time (vmf->vma->vm_file); - err =file_write_and_wait_range (filp, start, end); -if (err) + ret =iomap_page_mkwrite (vmf, &ntfs_page_mkwrite_iomap_ops,NULL ); +sb_end_pagefault (inode->i_sb); +return ret; +} + +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) +{ +struct file *file = desc->file; +struct inode *inode =file_inode (file); + +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, false); +if (err) +return err; + } + } + + +file_accessed (file); + desc->vm_ops = &ntfs_file_vm_ops; +return 0 ; +} + +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) +{ +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; + +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 =ntfs_trim_fs (vol, &range); +if (err <0 )return err; -inode_lock (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." ); +if (copy_to_user (user_range, &range,sizeof (range))) +return -EFAULT ; + +return 0 ; +} + +long ntfs_ioctl (struct file *filp,unsigned int cmd,unsigned long arg) +{ +switch (cmd) { +case FS_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 ; + } +} + +#ifdef CONFIG_COMPAT +long ntfs_compat_ioctl (struct file *filp,unsigned int cmd, +unsigned long arg) +{ +return ntfs_ioctl (filp, cmd, (unsigned long )compat_ptr (arg)); +} +#endif + +static int ntfs_allocate_range (struct ntfs_inode *ni,int mode,loff_t offset, +loff_t len) +{ +struct inode *vi =VFS_I (ni); +struct ntfs_volume *vol = ni->vol; +s64 need_space; +loff_t old_size, new_size; +s64 start_vcn, end_vcn; +int err; + + old_size =i_size_read (vi); + new_size =max_t (loff_t, old_size, offset + len); + start_vcn =ntfs_bytes_to_cluster (vol, offset); + end_vcn =ntfs_bytes_to_cluster (vol, offset + len -1 ) +1 ; + + err =inode_newsize_ok (vi, new_size); +if (err) + goto out; + + need_space =ntfs_bytes_to_cluster (vol, ni->allocated_size); +if (need_space > start_vcn) + need_space = end_vcn - need_space;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; + 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 (!(mode &FALLOC_FL_KEEP_SIZE ) && new_size != old_size) +i_size_write (vi, ni->data_size); +out: +return err; +} + +static int ntfs_punch_hole (struct ntfs_inode *ni,int mode,loff_t offset, +loff_t len) +{ +struct ntfs_volume *vol = ni->vol; +struct inode *vi =VFS_I (ni); +loff_t end_offset; +s64 start_vcn, end_vcn; +int err =0 ; + + loff_t offset_down = round_down(offset, max_t(unsigned int, + vol->cluster_size,PAGE_SIZE )); + +if (NVolDisableSparse (vol)) { + err = -EOPNOTSUPP ; + goto out; + } + +if (offset >= ni->data_size) + goto out; + +if (offset + len > ni->data_size) + end_offset = ni->data_size; +else + end_offset = offset + len; + + err =filemap_write_and_wait_range (vi->i_mapping, offset_down,LLONG_MAX ); +if (err) + goto out; +truncate_pagecache (vi, offset_down); + + start_vcn =ntfs_bytes_to_cluster (vol, offset); + end_vcn =ntfs_bytes_to_cluster (vol, end_offset -1 ) +1 ; + +if (offset & vol->cluster_size_mask) { +loff_t to; + + to =min_t (loff_t,ntfs_cluster_to_bytes (vol, start_vcn +1 ), + end_offset); + err =iomap_zero_range (vi, offset, to - offset,NULL , + &ntfs_seek_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; + + from =ntfs_cluster_to_bytes (vol, end_vcn -1 ); + err =iomap_zero_range (vi, from, end_offset - from,NULL , + &ntfs_seek_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); +if (err <0 || (end_vcn - start_vcn) ==1 ) + goto out; + end_vcn--; + } + +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); +out: +return err; } -#endif /* NTFS_RW */ +static int ntfs_collapse_range (struct ntfs_inode *ni,loff_t offset,loff_t len) +{ +struct ntfs_volume *vol = ni->vol; +struct inode *vi =VFS_I (ni); +loff_t old_size, new_size; +s64 start_vcn, end_vcn; +int err; + +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; + } + + old_size =i_size_read (vi); + start_vcn =ntfs_bytes_to_cluster (vol, offset); + end_vcn =ntfs_bytes_to_cluster (vol, offset + len -1 ) +1 ; + +if (ntfs_cluster_to_bytes (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_cluster_to_bytes (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 (new_size != old_size) +i_size_write (vi, ni->data_size); +out: +return err; +} + +static int ntfs_insert_range (struct ntfs_inode *ni,loff_t offset,loff_t len) +{ +struct ntfs_volume *vol = ni->vol; +struct inode *vi =VFS_I (ni); +loff_t offset_down =round_down (offset, + max_t(unsigned long, vol->cluster_size, PAGE_SIZE)); +loff_t alloc_size, end_offset = offset + len; +loff_t old_size, new_size; +s64 start_vcn, end_vcn; +int err; + +if (NVolDisableSparse (vol)) { + err = -EOPNOTSUPP ; + goto out; + } + +if ((offset & vol->cluster_size_mask) || + (len & vol->cluster_size_mask) || + offset >= ni->allocated_size) { + err = -EINVAL ; + goto out; + } + + old_size =i_size_read (vi); + start_vcn =ntfs_bytes_to_cluster (vol, offset); + end_vcn =ntfs_bytes_to_cluster (vol, end_offset -1 ) +1 ; + + new_size = old_size +ntfs_cluster_to_bytes (vol, end_vcn - start_vcn); + alloc_size = ni->allocated_size + +ntfs_cluster_to_bytes (vol, end_vcn - start_vcn); +if (alloc_size <0 ) { + err = -EFBIG ; + goto out; + } + 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 (new_size != old_size) +i_size_write (vi, ni->data_size); +out: +return err; +} + +#define NTFS_FALLOC_FL_SUPPORTED \ + (FALLOC_FL_ALLOCATE_RANGE | FALLOC_FL_KEEP_SIZE | \ + FALLOC_FL_INSERT_RANGE | FALLOC_FL_PUNCH_HOLE | \ + FALLOC_FL_COLLAPSE_RANGE) + +static long ntfs_fallocate (struct file *file,int mode,loff_t offset,loff_t len) +{ +struct inode *vi =file_inode (file); +struct ntfs_inode *ni =NTFS_I (vi); +struct ntfs_volume *vol = ni->vol; +int err =0 ; +loff_t old_size; +bool map_locked = false; + +if (mode & ~(NTFS_FALLOC_FL_SUPPORTED )) +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 ; + +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; + } + +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); + +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; + } + +switch (mode &FALLOC_FL_MODE_MASK ) { +case FALLOC_FL_ALLOCATE_RANGE : +case FALLOC_FL_KEEP_SIZE : + err =ntfs_allocate_range (ni, mode, offset, len); +break ; +case FALLOC_FL_PUNCH_HOLE : + err =ntfs_punch_hole (ni, mode, offset, len); +break ; +case FALLOC_FL_COLLAPSE_RANGE : + err =ntfs_collapse_range (ni, offset, len); +break ; +case FALLOC_FL_INSERT_RANGE : + err =ntfs_insert_range (ni, offset, len); +break ; +default : + err = -EOPNOTSUPP ; + } + +if (err) + goto out; + + err =file_modified (file); +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_seek_iomap_ops, + &ntfs_iomap_folio_ops,NULL ); + } +NInoSetFileNameDirty (ni); +inode_set_mtime_to_ts (vi,inode_set_ctime_current (vi)); +mark_inode_dirty (vi); + } + +inode_unlock (vi); +return err; +}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 = ntfs_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = ntfs_compat_ioctl, +#endif + .fallocate = ntfs_fallocate, + .setlease = generic_setlease, };const struct inode_operations ntfs_file_inode_ops = { -#ifdef NTFS_RW .setattr = ntfs_setattr, -#endif /* NTFS_RW */ + .getattr = ntfs_getattr, + .listxattr = ntfs_listxattr, + .get_acl = ntfs_get_acl, + .set_acl = ntfs_set_acl, + .fiemap = ntfs_fiemap, +}; + +const struct inode_operations ntfs_symlink_inode_operations = { + .get_link = ntfs_get_link, + .setattr = ntfs_setattr, + .listxattr = ntfs_listxattr, +}; + +const struct inode_operations ntfs_special_inode_operations = { + .setattr = ntfs_setattr, + .getattr = ntfs_getattr, + .listxattr = ntfs_listxattr, + .get_acl = ntfs_get_acl,
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.