* [PATCH 06/11] ntfsplus: add iomap and address space operations
@ 2025-10-20 2:12 Namjae Jeon
2025-10-20 2:12 ` [PATCH 07/11] ntfsplus: add attrib operatrions Namjae Jeon
` (4 more replies)
0 siblings, 5 replies; 6+ messages in thread
From: Namjae Jeon @ 2025-10-20 2:12 UTC (permalink / raw)
To: viro, brauner, hch, hch, tytso, willy, jack, djwong, josef,
sandeen, rgoldwyn, xiang, dsterba, pali, ebiggers, neil,
amir73il
Cc: linux-fsdevel, linux-kernel, iamjoonsoo.kim, cheol.lee, jay.sim,
gunho.lee, Namjae Jeon
This adds the implementation of iomap and address space operations
for ntfsplus.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
---
fs/ntfsplus/aops.c | 631 +++++++++++++++++++++++++++++++++++
fs/ntfsplus/ntfs_iomap.c | 704 +++++++++++++++++++++++++++++++++++++++
2 files changed, 1335 insertions(+)
create mode 100644 fs/ntfsplus/aops.c
create mode 100644 fs/ntfsplus/ntfs_iomap.c
diff --git a/fs/ntfsplus/aops.c b/fs/ntfsplus/aops.c
new file mode 100644
index 000000000000..50c804be3bd4
--- /dev/null
+++ b/fs/ntfsplus/aops.c
@@ -0,0 +1,631 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/**
+ * NTFS kernel address space operations and page cache handling.
+ *
+ * Copyright (c) 2001-2014 Anton Altaparmakov and Tuxera Inc.
+ * Copyright (c) 2002 Richard Russon
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ */
+
+#include <linux/writeback.h>
+#include <linux/mpage.h>
+#include <linux/uio.h>
+
+#include "aops.h"
+#include "attrib.h"
+#include "mft.h"
+#include "ntfs.h"
+#include "misc.h"
+#include "ntfs_iomap.h"
+
+static s64 ntfs_convert_page_index_into_lcn(struct ntfs_volume *vol, struct ntfs_inode *ni,
+ unsigned long page_index)
+{
+ sector_t iblock;
+ s64 vcn;
+ s64 lcn;
+ unsigned char blocksize_bits = vol->sb->s_blocksize_bits;
+
+ iblock = (s64)page_index << (PAGE_SHIFT - blocksize_bits);
+ vcn = (s64)iblock << blocksize_bits >> vol->cluster_size_bits;
+
+ down_read(&ni->runlist.lock);
+ lcn = ntfs_attr_vcn_to_lcn_nolock(ni, vcn, false);
+ up_read(&ni->runlist.lock);
+
+ return lcn;
+}
+
+struct bio *ntfs_setup_bio(struct ntfs_volume *vol, unsigned int opf, s64 lcn,
+ unsigned int pg_ofs)
+{
+ struct bio *bio;
+
+ bio = bio_alloc(vol->sb->s_bdev, 1, opf, GFP_NOIO);
+ if (!bio)
+ return NULL;
+ bio->bi_iter.bi_sector = ((lcn << vol->cluster_size_bits) + pg_ofs) >>
+ vol->sb->s_blocksize_bits;
+
+ return bio;
+}
+
+/**
+ * ntfs_read_folio - fill a @folio of a @file with data from the device
+ * @file: open file to which the folio @folio belongs or NULL
+ * @folio: page cache folio to fill with data
+ *
+ * For non-resident attributes, ntfs_read_folio() fills the @folio of the open
+ * file @file by calling the ntfs version of the generic block_read_full_folio()
+ * function, which in turn creates and reads in the buffers associated with
+ * the folio asynchronously.
+ *
+ * For resident attributes, OTOH, ntfs_read_folio() fills @folio by copying the
+ * data from the mft record (which at this stage is most likely in memory) and
+ * fills the remainder with zeroes. Thus, in this case, I/O is synchronous, as
+ * even if the mft record is not cached at this point in time, we need to wait
+ * for it to be read in before we can do the copy.
+ *
+ * Return 0 on success and -errno on error.
+ */
+static int ntfs_read_folio(struct file *file, struct folio *folio)
+{
+ loff_t i_size;
+ struct inode *vi;
+ struct ntfs_inode *ni;
+
+ vi = folio->mapping->host;
+ i_size = i_size_read(vi);
+ /* Is the page fully outside i_size? (truncate in progress) */
+ if (unlikely(folio->index >= (i_size + PAGE_SIZE - 1) >>
+ PAGE_SHIFT)) {
+ folio_zero_segment(folio, 0, PAGE_SIZE);
+ ntfs_debug("Read outside i_size - truncated?");
+ folio_mark_uptodate(folio);
+ folio_unlock(folio);
+ return 0;
+ }
+ /*
+ * This can potentially happen because we clear PageUptodate() during
+ * ntfs_writepage() of MstProtected() attributes.
+ */
+ if (folio_test_uptodate(folio)) {
+ folio_unlock(folio);
+ return 0;
+ }
+ ni = NTFS_I(vi);
+
+ /*
+ * Only $DATA attributes can be encrypted and only unnamed $DATA
+ * attributes can be compressed. Index root can have the flags set but
+ * this means to create compressed/encrypted files, not that the
+ * attribute is compressed/encrypted. Note we need to check for
+ * AT_INDEX_ALLOCATION since this is the type of both directory and
+ * index inodes.
+ */
+ if (ni->type != AT_INDEX_ALLOCATION) {
+ /* If attribute is encrypted, deny access, just like NT4. */
+ if (NInoEncrypted(ni)) {
+ BUG_ON(ni->type != AT_DATA);
+ folio_unlock(folio);
+ return -EACCES;
+ }
+ /* Compressed data streams are handled in compress.c. */
+ if (NInoNonResident(ni) && NInoCompressed(ni)) {
+ BUG_ON(ni->type != AT_DATA);
+ BUG_ON(ni->name_len);
+ return ntfs_read_compressed_block(folio);
+ }
+ }
+
+ return iomap_read_folio(folio, &ntfs_read_iomap_ops);
+}
+
+static int ntfs_write_mft_block(struct ntfs_inode *ni, struct folio *folio,
+ struct writeback_control *wbc)
+{
+ struct inode *vi = VFS_I(ni);
+ struct ntfs_volume *vol = ni->vol;
+ u8 *kaddr;
+ struct ntfs_inode *locked_nis[PAGE_SIZE / NTFS_BLOCK_SIZE];
+ int nr_locked_nis = 0, err = 0, mft_ofs, prev_mft_ofs;
+ struct bio *bio = NULL;
+ unsigned long mft_no;
+ struct ntfs_inode *tni;
+ s64 lcn;
+ unsigned int lcn_folio_off = 0;
+ s64 vcn = (s64)folio->index << PAGE_SHIFT >> vol->cluster_size_bits;
+ s64 end_vcn = ni->allocated_size >> vol->cluster_size_bits;
+ unsigned int folio_sz;
+ struct runlist_element *rl;
+
+ ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, folio index 0x%lx.",
+ vi->i_ino, ni->type, folio->index);
+ BUG_ON(!NInoNonResident(ni));
+ BUG_ON(!NInoMstProtected(ni));
+
+ /*
+ * NOTE: ntfs_write_mft_block() would be called for $MFTMirr if a page
+ * in its page cache were to be marked dirty. However this should
+ * never happen with the current driver and considering we do not
+ * handle this case here we do want to BUG(), at least for now.
+ */
+
+ BUG_ON(!((S_ISREG(vi->i_mode) && !vi->i_ino) || S_ISDIR(vi->i_mode) ||
+ (NInoAttr(ni) && ni->type == AT_INDEX_ALLOCATION)));
+
+ lcn = ntfs_convert_page_index_into_lcn(vol, ni, folio->index);
+ if (lcn <= LCN_HOLE) {
+ folio_start_writeback(folio);
+ folio_unlock(folio);
+ folio_end_writeback(folio);
+ return -EIO;
+ }
+
+ if (vol->cluster_size_bits > PAGE_SHIFT) {
+ lcn_folio_off = folio->index << PAGE_SHIFT;
+ lcn_folio_off &= vol->cluster_size_mask;
+ }
+
+ /* Map folio so we can access its contents. */
+ kaddr = kmap_local_folio(folio, 0);
+ /* Clear the page uptodate flag whilst the mst fixups are applied. */
+ folio_clear_uptodate(folio);
+
+ for (mft_ofs = 0; mft_ofs < PAGE_SIZE && vcn < end_vcn;
+ mft_ofs += vol->mft_record_size) {
+ /* Get the mft record number. */
+ mft_no = (((s64)folio->index << PAGE_SHIFT) + mft_ofs) >>
+ vol->mft_record_size_bits;
+ /* Check whether to write this mft record. */
+ tni = NULL;
+ if (ntfs_may_write_mft_record(vol, mft_no,
+ (struct mft_record *)(kaddr + mft_ofs), &tni)) {
+ unsigned int mft_record_off = 0;
+ s64 vcn_off = vcn;
+
+ /*
+ * The record should be written. If a locked ntfs
+ * inode was returned, add it to the array of locked
+ * ntfs inodes.
+ */
+ if (tni)
+ locked_nis[nr_locked_nis++] = tni;
+
+ if (bio && (mft_ofs != prev_mft_ofs + vol->mft_record_size)) {
+flush_bio:
+ flush_dcache_folio(folio);
+ submit_bio_wait(bio);
+ bio_put(bio);
+ bio = NULL;
+ }
+
+ if (vol->cluster_size == NTFS_BLOCK_SIZE) {
+ down_write(&ni->runlist.lock);
+ rl = ntfs_attr_vcn_to_rl(ni, vcn_off, &lcn);
+ up_write(&ni->runlist.lock);
+ if (IS_ERR(rl) || lcn < 0) {
+ err = -EIO;
+ goto unm_done;
+ }
+ }
+
+ if (!bio) {
+ unsigned int off = lcn_folio_off;
+
+ if (vol->cluster_size != NTFS_BLOCK_SIZE)
+ off += mft_ofs;
+
+ bio = ntfs_setup_bio(vol, REQ_OP_WRITE, lcn, off);
+ if (!bio) {
+ err = -ENOMEM;
+ goto unm_done;
+ }
+ }
+
+ if (vol->cluster_size == NTFS_BLOCK_SIZE && rl->length == 1)
+ folio_sz = NTFS_BLOCK_SIZE;
+ else
+ folio_sz = vol->mft_record_size;
+ if (!bio_add_folio(bio, folio, folio_sz,
+ mft_ofs + mft_record_off)) {
+ err = -EIO;
+ bio_put(bio);
+ goto unm_done;
+ }
+ prev_mft_ofs = mft_ofs;
+ mft_record_off += folio_sz;
+
+ if (mft_record_off != vol->mft_record_size) {
+ vcn_off++;
+ goto flush_bio;
+ }
+
+ if (mft_no < vol->mftmirr_size)
+ ntfs_sync_mft_mirror(vol, mft_no,
+ (struct mft_record *)(kaddr + mft_ofs));
+ }
+
+ vcn += vol->mft_record_size >> vol->cluster_size_bits;
+ }
+
+ if (bio) {
+ flush_dcache_folio(folio);
+ submit_bio_wait(bio);
+ bio_put(bio);
+ }
+ flush_dcache_folio(folio);
+unm_done:
+ folio_mark_uptodate(folio);
+ kunmap_local(kaddr);
+
+ folio_start_writeback(folio);
+ folio_unlock(folio);
+ folio_end_writeback(folio);
+
+ /* Unlock any locked inodes. */
+ while (nr_locked_nis-- > 0) {
+ struct ntfs_inode *base_tni;
+
+ tni = locked_nis[nr_locked_nis];
+ mutex_unlock(&tni->mrec_lock);
+
+ /* Get the base inode. */
+ mutex_lock(&tni->extent_lock);
+ if (tni->nr_extents >= 0)
+ base_tni = tni;
+ else {
+ base_tni = tni->ext.base_ntfs_ino;
+ BUG_ON(!base_tni);
+ }
+ mutex_unlock(&tni->extent_lock);
+ ntfs_debug("Unlocking %s inode 0x%lx.",
+ tni == base_tni ? "base" : "extent",
+ tni->mft_no);
+ atomic_dec(&tni->count);
+ iput(VFS_I(base_tni));
+ }
+
+ if (unlikely(err && err != -ENOMEM))
+ NVolSetErrors(vol);
+ if (likely(!err))
+ ntfs_debug("Done.");
+ return err;
+}
+
+/**
+ * ntfs_bmap - map logical file block to physical device block
+ * @mapping: address space mapping to which the block to be mapped belongs
+ * @block: logical block to map to its physical device block
+ *
+ * For regular, non-resident files (i.e. not compressed and not encrypted), map
+ * the logical @block belonging to the file described by the address space
+ * mapping @mapping to its physical device block.
+ *
+ * The size of the block is equal to the @s_blocksize field of the super block
+ * of the mounted file system which is guaranteed to be smaller than or equal
+ * to the cluster size thus the block is guaranteed to fit entirely inside the
+ * cluster which means we do not need to care how many contiguous bytes are
+ * available after the beginning of the block.
+ *
+ * Return the physical device block if the mapping succeeded or 0 if the block
+ * is sparse or there was an error.
+ *
+ * Note: This is a problem if someone tries to run bmap() on $Boot system file
+ * as that really is in block zero but there is nothing we can do. bmap() is
+ * just broken in that respect (just like it cannot distinguish sparse from
+ * not available or error).
+ */
+static sector_t ntfs_bmap(struct address_space *mapping, sector_t block)
+{
+ s64 ofs, size;
+ loff_t i_size;
+ s64 lcn;
+ unsigned long blocksize, flags;
+ struct ntfs_inode *ni = NTFS_I(mapping->host);
+ struct ntfs_volume *vol = ni->vol;
+ unsigned int delta;
+ unsigned char blocksize_bits, cluster_size_shift;
+
+ ntfs_debug("Entering for mft_no 0x%lx, logical block 0x%llx.",
+ ni->mft_no, (unsigned long long)block);
+ if (ni->type != AT_DATA || !NInoNonResident(ni) || NInoEncrypted(ni)) {
+ ntfs_error(vol->sb, "BMAP does not make sense for %s attributes, returning 0.",
+ (ni->type != AT_DATA) ? "non-data" :
+ (!NInoNonResident(ni) ? "resident" :
+ "encrypted"));
+ return 0;
+ }
+ /* None of these can happen. */
+ BUG_ON(NInoCompressed(ni));
+ BUG_ON(NInoMstProtected(ni));
+ blocksize = vol->sb->s_blocksize;
+ blocksize_bits = vol->sb->s_blocksize_bits;
+ ofs = (s64)block << blocksize_bits;
+ read_lock_irqsave(&ni->size_lock, flags);
+ size = ni->initialized_size;
+ i_size = i_size_read(VFS_I(ni));
+ read_unlock_irqrestore(&ni->size_lock, flags);
+ /*
+ * If the offset is outside the initialized size or the block straddles
+ * the initialized size then pretend it is a hole unless the
+ * initialized size equals the file size.
+ */
+ if (unlikely(ofs >= size || (ofs + blocksize > size && size < i_size)))
+ goto hole;
+ cluster_size_shift = vol->cluster_size_bits;
+ down_read(&ni->runlist.lock);
+ lcn = ntfs_attr_vcn_to_lcn_nolock(ni, ofs >> cluster_size_shift, false);
+ up_read(&ni->runlist.lock);
+ if (unlikely(lcn < LCN_HOLE)) {
+ /*
+ * Step down to an integer to avoid gcc doing a long long
+ * comparision in the switch when we know @lcn is between
+ * LCN_HOLE and LCN_EIO (i.e. -1 to -5).
+ *
+ * Otherwise older gcc (at least on some architectures) will
+ * try to use __cmpdi2() which is of course not available in
+ * the kernel.
+ */
+ switch ((int)lcn) {
+ case LCN_ENOENT:
+ /*
+ * If the offset is out of bounds then pretend it is a
+ * hole.
+ */
+ goto hole;
+ case LCN_ENOMEM:
+ ntfs_error(vol->sb,
+ "Not enough memory to complete mapping for inode 0x%lx. Returning 0.",
+ ni->mft_no);
+ break;
+ default:
+ ntfs_error(vol->sb,
+ "Failed to complete mapping for inode 0x%lx. Run chkdsk. Returning 0.",
+ ni->mft_no);
+ break;
+ }
+ return 0;
+ }
+ if (lcn < 0) {
+ /* It is a hole. */
+hole:
+ ntfs_debug("Done (returning hole).");
+ return 0;
+ }
+ /*
+ * The block is really allocated and fullfils all our criteria.
+ * Convert the cluster to units of block size and return the result.
+ */
+ delta = ofs & vol->cluster_size_mask;
+ if (unlikely(sizeof(block) < sizeof(lcn))) {
+ block = lcn = ((lcn << cluster_size_shift) + delta) >>
+ blocksize_bits;
+ /* If the block number was truncated return 0. */
+ if (unlikely(block != lcn)) {
+ ntfs_error(vol->sb,
+ "Physical block 0x%llx is too large to be returned, returning 0.",
+ (long long)lcn);
+ return 0;
+ }
+ } else
+ block = ((lcn << cluster_size_shift) + delta) >>
+ blocksize_bits;
+ ntfs_debug("Done (returning block 0x%llx).", (unsigned long long)lcn);
+ return block;
+}
+
+static void ntfs_readahead(struct readahead_control *rac)
+{
+ struct address_space *mapping = rac->mapping;
+ struct inode *inode = mapping->host;
+ struct ntfs_inode *ni = NTFS_I(inode);
+
+ if (!NInoNonResident(ni) || NInoCompressed(ni)) {
+ /* No readahead for resident and compressed. */
+ return;
+ }
+
+ if (NInoMstProtected(ni) &&
+ (ni->mft_no == FILE_MFT || ni->mft_no == FILE_MFTMirr))
+ return;
+
+ iomap_readahead(rac, &ntfs_read_iomap_ops);
+}
+
+static int ntfs_mft_writepage(struct folio *folio, struct writeback_control *wbc)
+{
+ struct address_space *mapping = folio->mapping;
+ struct inode *vi = mapping->host;
+ struct ntfs_inode *ni = NTFS_I(vi);
+ loff_t i_size;
+ int ret;
+
+ i_size = i_size_read(vi);
+
+ /* We have to zero every time due to mmap-at-end-of-file. */
+ if (folio->index >= (i_size >> PAGE_SHIFT)) {
+ /* The page straddles i_size. */
+ unsigned int ofs = i_size & ~PAGE_MASK;
+
+ folio_zero_segment(folio, ofs, PAGE_SIZE);
+ }
+
+ ret = ntfs_write_mft_block(ni, folio, wbc);
+ mapping_set_error(mapping, ret);
+ return ret;
+}
+
+static int ntfs_writepages(struct address_space *mapping,
+ struct writeback_control *wbc)
+{
+ struct inode *inode = mapping->host;
+ struct ntfs_inode *ni = NTFS_I(inode);
+ struct iomap_writepage_ctx wpc = {
+ .inode = mapping->host,
+ .wbc = wbc,
+ .ops = &ntfs_writeback_ops,
+ };
+
+ if (NVolShutdown(ni->vol))
+ return -EIO;
+
+ if (!NInoNonResident(ni))
+ return 0;
+
+ if (NInoMstProtected(ni) && ni->mft_no == FILE_MFT) {
+ struct folio *folio = NULL;
+ int error;
+
+ while ((folio = writeback_iter(mapping, wbc, folio, &error)))
+ error = ntfs_mft_writepage(folio, wbc);
+ return error;
+ }
+
+ /* If file is encrypted, deny access, just like NT4. */
+ if (NInoEncrypted(ni)) {
+ ntfs_debug("Denying write access to encrypted file.");
+ return -EACCES;
+ }
+
+ return iomap_writepages(&wpc);
+}
+
+static int ntfs_swap_activate(struct swap_info_struct *sis,
+ struct file *swap_file, sector_t *span)
+{
+ return iomap_swapfile_activate(sis, swap_file, span,
+ &ntfs_read_iomap_ops);
+}
+
+/**
+ * ntfs_normal_aops - address space operations for normal inodes and attributes
+ *
+ * Note these are not used for compressed or mst protected inodes and
+ * attributes.
+ */
+const struct address_space_operations ntfs_normal_aops = {
+ .read_folio = ntfs_read_folio,
+ .readahead = ntfs_readahead,
+ .writepages = ntfs_writepages,
+ .direct_IO = noop_direct_IO,
+ .dirty_folio = iomap_dirty_folio,
+ .bmap = ntfs_bmap,
+ .migrate_folio = filemap_migrate_folio,
+ .is_partially_uptodate = iomap_is_partially_uptodate,
+ .error_remove_folio = generic_error_remove_folio,
+ .release_folio = iomap_release_folio,
+ .invalidate_folio = iomap_invalidate_folio,
+ .swap_activate = ntfs_swap_activate,
+};
+
+/**
+ * ntfs_compressed_aops - address space operations for compressed inodes
+ */
+const struct address_space_operations ntfs_compressed_aops = {
+ .read_folio = ntfs_read_folio,
+ .direct_IO = noop_direct_IO,
+ .writepages = ntfs_writepages,
+ .dirty_folio = iomap_dirty_folio,
+ .migrate_folio = filemap_migrate_folio,
+ .is_partially_uptodate = iomap_is_partially_uptodate,
+ .error_remove_folio = generic_error_remove_folio,
+ .release_folio = iomap_release_folio,
+ .invalidate_folio = iomap_invalidate_folio,
+};
+
+/**
+ * ntfs_mst_aops - general address space operations for mst protecteed inodes
+ * and attributes
+ */
+const struct address_space_operations ntfs_mst_aops = {
+ .read_folio = ntfs_read_folio, /* Fill page with data. */
+ .readahead = ntfs_readahead,
+ .writepages = ntfs_writepages, /* Write dirty page to disk. */
+ .dirty_folio = iomap_dirty_folio,
+ .migrate_folio = filemap_migrate_folio,
+ .is_partially_uptodate = iomap_is_partially_uptodate,
+ .error_remove_folio = generic_error_remove_folio,
+ .release_folio = iomap_release_folio,
+ .invalidate_folio = iomap_invalidate_folio,
+};
+
+void mark_ntfs_record_dirty(struct folio *folio)
+{
+ iomap_dirty_folio(folio->mapping, folio);
+}
+
+int ntfs_dev_read(struct super_block *sb, void *buf, loff_t start, loff_t size)
+{
+ pgoff_t idx, idx_end;
+ loff_t offset, end = start + size;
+ u32 from, to, buf_off = 0;
+ struct folio *folio;
+ char *kaddr;
+
+ idx = start >> PAGE_SHIFT;
+ idx_end = end >> PAGE_SHIFT;
+ from = start & ~PAGE_MASK;
+
+ if (idx == idx_end)
+ idx_end++;
+
+ for (; idx < idx_end; idx++, from = 0) {
+ folio = ntfs_read_mapping_folio(sb->s_bdev->bd_mapping, idx);
+ if (IS_ERR(folio)) {
+ ntfs_error(sb, "Unable to read %ld page", idx);
+ return PTR_ERR(folio);
+ }
+
+ kaddr = kmap_local_folio(folio, 0);
+ offset = (loff_t)idx << PAGE_SHIFT;
+ to = min_t(u32, end - offset, PAGE_SIZE);
+
+ memcpy(buf + buf_off, kaddr + from, to);
+ buf_off += to;
+ kunmap_local(kaddr);
+ folio_put(folio);
+ }
+
+ return 0;
+}
+
+int ntfs_dev_write(struct super_block *sb, void *buf, loff_t start,
+ loff_t size, bool wait)
+{
+ pgoff_t idx, idx_end;
+ loff_t offset, end = start + size;
+ u32 from, to, buf_off = 0;
+ struct folio *folio;
+ char *kaddr;
+
+ idx = start >> PAGE_SHIFT;
+ idx_end = end >> PAGE_SHIFT;
+ from = start & ~PAGE_MASK;
+
+ if (idx == idx_end)
+ idx_end++;
+
+ for (; idx < idx_end; idx++, from = 0) {
+ folio = ntfs_read_mapping_folio(sb->s_bdev->bd_mapping, idx);
+ if (IS_ERR(folio)) {
+ ntfs_error(sb, "Unable to read %ld page", idx);
+ return PTR_ERR(folio);
+ }
+
+ kaddr = kmap_local_folio(folio, 0);
+ offset = (loff_t)idx << PAGE_SHIFT;
+ to = min_t(u32, end - offset, PAGE_SIZE);
+
+ memcpy(kaddr + from, buf + buf_off, to);
+ buf_off += to;
+ kunmap_local(kaddr);
+ folio_mark_uptodate(folio);
+ folio_mark_dirty(folio);
+ if (wait)
+ folio_wait_stable(folio);
+ folio_put(folio);
+ }
+
+ return 0;
+}
diff --git a/fs/ntfsplus/ntfs_iomap.c b/fs/ntfsplus/ntfs_iomap.c
new file mode 100644
index 000000000000..a6d2c9e01ca6
--- /dev/null
+++ b/fs/ntfsplus/ntfs_iomap.c
@@ -0,0 +1,704 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/**
+ * iomap callack functions
+ *
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ */
+
+#include <linux/writeback.h>
+#include <linux/mpage.h>
+#include <linux/uio.h>
+
+#include "aops.h"
+#include "attrib.h"
+#include "mft.h"
+#include "ntfs.h"
+#include "misc.h"
+#include "ntfs_iomap.h"
+
+static void ntfs_iomap_put_folio(struct inode *inode, loff_t pos,
+ unsigned int len, struct folio *folio)
+{
+ struct ntfs_inode *ni = NTFS_I(inode);
+ unsigned long sector_size = 1UL << inode->i_blkbits;
+ loff_t start_down, end_up, init;
+
+ if (!NInoNonResident(ni))
+ goto out;
+
+ start_down = round_down(pos, sector_size);
+ end_up = (pos + len - 1) | (sector_size - 1);
+ init = ni->initialized_size;
+
+ if (init >= start_down && init <= end_up) {
+ if (init < pos) {
+ loff_t offset = offset_in_folio(folio, pos + len);
+
+ if (offset == 0)
+ offset = folio_size(folio);
+ folio_zero_segments(folio,
+ offset_in_folio(folio, init),
+ offset_in_folio(folio, pos),
+ offset,
+ folio_size(folio));
+
+ } else {
+ loff_t offset = max_t(loff_t, pos + len, init);
+
+ offset = offset_in_folio(folio, offset);
+ if (offset == 0)
+ offset = folio_size(folio);
+ folio_zero_segment(folio,
+ offset,
+ folio_size(folio));
+ }
+ } else if (init <= pos) {
+ loff_t offset = 0, offset2 = offset_in_folio(folio, pos + len);
+
+ if ((init >> folio_shift(folio)) == (pos >> folio_shift(folio)))
+ offset = offset_in_folio(folio, init);
+ if (offset2 == 0)
+ offset2 = folio_size(folio);
+ folio_zero_segments(folio,
+ offset,
+ offset_in_folio(folio, pos),
+ offset2,
+ folio_size(folio));
+ }
+
+out:
+ folio_unlock(folio);
+ folio_put(folio);
+}
+
+const struct iomap_write_ops ntfs_iomap_folio_ops = {
+ .put_folio = ntfs_iomap_put_folio,
+};
+
+static int ntfs_read_iomap_begin(struct inode *inode, loff_t offset, loff_t length,
+ unsigned int flags, struct iomap *iomap, struct iomap *srcmap)
+{
+ struct ntfs_inode *base_ni, *ni = NTFS_I(inode);
+ struct ntfs_attr_search_ctx *ctx;
+ loff_t i_size;
+ u32 attr_len;
+ int err = 0;
+ char *kattr;
+ struct page *ipage;
+
+ if (NInoNonResident(ni)) {
+ s64 vcn;
+ s64 lcn;
+ struct runlist_element *rl;
+ struct ntfs_volume *vol = ni->vol;
+ loff_t vcn_ofs;
+ loff_t rl_length;
+
+ vcn = offset >> vol->cluster_size_bits;
+ vcn_ofs = offset & vol->cluster_size_mask;
+
+ down_write(&ni->runlist.lock);
+ rl = ntfs_attr_vcn_to_rl(ni, vcn, &lcn);
+ if (IS_ERR(rl)) {
+ up_write(&ni->runlist.lock);
+ return PTR_ERR(rl);
+ }
+
+ if (flags & IOMAP_REPORT) {
+ if (lcn < LCN_HOLE) {
+ up_write(&ni->runlist.lock);
+ return -ENOENT;
+ }
+ } else if (lcn < LCN_ENOENT) {
+ up_write(&ni->runlist.lock);
+ return -EINVAL;
+ }
+
+ iomap->bdev = inode->i_sb->s_bdev;
+ iomap->offset = offset;
+
+ if (lcn <= LCN_DELALLOC) {
+ if (lcn == LCN_DELALLOC)
+ iomap->type = IOMAP_DELALLOC;
+ else
+ iomap->type = IOMAP_HOLE;
+ iomap->addr = IOMAP_NULL_ADDR;
+ } else {
+ if (!(flags & IOMAP_ZERO) && offset >= ni->initialized_size)
+ iomap->type = IOMAP_UNWRITTEN;
+ else
+ iomap->type = IOMAP_MAPPED;
+ iomap->addr = (lcn << vol->cluster_size_bits) + vcn_ofs;
+ }
+
+ rl_length = (rl->length - (vcn - rl->vcn)) << ni->vol->cluster_size_bits;
+
+ if (rl_length == 0 && rl->lcn > LCN_DELALLOC) {
+ ntfs_error(inode->i_sb,
+ "runlist(vcn : %lld, length : %lld, lcn : %lld) is corrupted\n",
+ rl->vcn, rl->length, rl->lcn);
+ up_write(&ni->runlist.lock);
+ return -EIO;
+ }
+
+ if (rl_length && length > rl_length - vcn_ofs)
+ iomap->length = rl_length - vcn_ofs;
+ else
+ iomap->length = length;
+ up_write(&ni->runlist.lock);
+
+ if (!(flags & IOMAP_ZERO) &&
+ iomap->type == IOMAP_MAPPED &&
+ iomap->offset < ni->initialized_size &&
+ iomap->offset + iomap->length > ni->initialized_size) {
+ iomap->length = round_up(ni->initialized_size, 1 << inode->i_blkbits) -
+ iomap->offset;
+ }
+ iomap->flags |= IOMAP_F_MERGED;
+ return 0;
+ }
+
+ if (NInoAttr(ni))
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+ BUG_ON(NInoNonResident(ni));
+
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ err = -ENOMEM;
+ goto out;
+ }
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx);
+ if (unlikely(err))
+ goto out;
+
+ attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
+ if (unlikely(attr_len > ni->initialized_size))
+ attr_len = ni->initialized_size;
+ i_size = i_size_read(inode);
+
+ if (unlikely(attr_len > i_size)) {
+ /* Race with shrinking truncate. */
+ attr_len = i_size;
+ }
+
+ if (offset >= attr_len) {
+ if (flags & IOMAP_REPORT)
+ err = -ENOENT;
+ else
+ err = -EFAULT;
+ goto out;
+ }
+
+ kattr = (u8 *)ctx->attr + le16_to_cpu(ctx->attr->data.resident.value_offset);
+
+ ipage = alloc_page(__GFP_NOWARN | __GFP_IO | __GFP_ZERO);
+ if (!ipage) {
+ err = -ENOMEM;
+ goto out;
+ }
+
+ memcpy(page_address(ipage), kattr, attr_len);
+ iomap->type = IOMAP_INLINE;
+ iomap->inline_data = page_address(ipage);
+ iomap->offset = 0;
+ iomap->length = min_t(loff_t, attr_len, PAGE_SIZE);
+ iomap->private = ipage;
+
+out:
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+static int ntfs_read_iomap_end(struct inode *inode, loff_t pos, loff_t length,
+ ssize_t written, unsigned int flags, struct iomap *iomap)
+{
+ if (iomap->type == IOMAP_INLINE) {
+ struct page *ipage = iomap->private;
+
+ put_page(ipage);
+ }
+ return written;
+}
+
+const struct iomap_ops ntfs_read_iomap_ops = {
+ .iomap_begin = ntfs_read_iomap_begin,
+ .iomap_end = ntfs_read_iomap_end,
+};
+
+static int ntfs_buffered_zeroed_clusters(struct inode *vi, s64 vcn)
+{
+ struct ntfs_inode *ni = NTFS_I(vi);
+ struct ntfs_volume *vol = ni->vol;
+ struct address_space *mapping = vi->i_mapping;
+ struct folio *folio;
+ pgoff_t idx, idx_end;
+ u32 from, to;
+
+ idx = (vcn << vol->cluster_size_bits) >> PAGE_SHIFT;
+ idx_end = ((vcn + 1) << vol->cluster_size_bits) >> PAGE_SHIFT;
+ from = (vcn << vol->cluster_size_bits) & ~PAGE_MASK;
+ if (idx == idx_end)
+ idx_end++;
+
+ to = min_t(u32, vol->cluster_size, PAGE_SIZE);
+ for (; idx < idx_end; idx++, from = 0) {
+ if (to != PAGE_SIZE) {
+ folio = ntfs_read_mapping_folio(mapping, idx);
+ if (IS_ERR(folio))
+ return PTR_ERR(folio);
+ folio_lock(folio);
+ } else {
+ folio = __filemap_get_folio(mapping, idx,
+ FGP_WRITEBEGIN | FGP_NOFS, mapping_gfp_mask(mapping));
+ if (IS_ERR(folio))
+ return PTR_ERR(folio);
+ }
+
+ if (folio_test_uptodate(folio) ||
+ iomap_is_partially_uptodate(folio, from, to))
+ goto next_folio;
+
+ folio_zero_segment(folio, from, from + to);
+ folio_mark_uptodate(folio);
+
+next_folio:
+ iomap_dirty_folio(mapping, folio);
+ folio_unlock(folio);
+ folio_put(folio);
+ balance_dirty_pages_ratelimited(mapping);
+ cond_resched();
+ }
+
+ return 0;
+}
+
+int ntfs_zeroed_clusters(struct inode *vi, s64 lcn, s64 num)
+{
+ struct ntfs_inode *ni = NTFS_I(vi);
+ struct ntfs_volume *vol = ni->vol;
+ u32 to;
+ struct bio *bio = NULL;
+ s64 err = 0, zero_len = num << vol->cluster_size_bits;
+ s64 loc = lcn << vol->cluster_size_bits, curr = 0;
+
+ while (zero_len > 0) {
+setup_bio:
+ if (!bio) {
+ bio = bio_alloc(vol->sb->s_bdev,
+ bio_max_segs(DIV_ROUND_UP(zero_len, PAGE_SIZE)),
+ REQ_OP_WRITE | REQ_SYNC | REQ_IDLE, GFP_NOIO);
+ if (!bio)
+ return -ENOMEM;
+ bio->bi_iter.bi_sector = (loc + curr) >> vol->sb->s_blocksize_bits;
+ }
+
+ to = min_t(u32, zero_len, PAGE_SIZE);
+ if (!bio_add_page(bio, ZERO_PAGE(0), to, 0)) {
+ err = submit_bio_wait(bio);
+ bio_put(bio);
+ bio = NULL;
+ if (err)
+ break;
+ goto setup_bio;
+ }
+ zero_len -= to;
+ curr += to;
+ }
+
+ if (bio) {
+ err = submit_bio_wait(bio);
+ bio_put(bio);
+ }
+
+ return err;
+}
+
+static int __ntfs_write_iomap_begin(struct inode *inode, loff_t offset,
+ loff_t length, unsigned int flags,
+ struct iomap *iomap, bool da, bool mapped)
+{
+ struct ntfs_inode *ni = NTFS_I(inode);
+ struct ntfs_volume *vol = ni->vol;
+ struct attr_record *a;
+ struct ntfs_attr_search_ctx *ctx;
+ u32 attr_len;
+ int err = 0;
+ char *kattr;
+ struct page *ipage;
+
+ if (NVolShutdown(vol))
+ return -EIO;
+
+ mutex_lock(&ni->mrec_lock);
+ if (NInoNonResident(ni)) {
+ s64 vcn;
+ loff_t vcn_ofs;
+ loff_t rl_length;
+ s64 max_clu_count =
+ round_up(length, vol->cluster_size) >> vol->cluster_size_bits;
+
+ vcn = offset >> vol->cluster_size_bits;
+ vcn_ofs = offset & vol->cluster_size_mask;
+
+ if (da) {
+ bool balloc = false;
+ s64 start_lcn, lcn_count;
+ bool update_mp;
+
+ update_mp = (flags & IOMAP_DIRECT) || mapped ||
+ NInoAttr(ni) || ni->mft_no < FILE_first_user;
+ down_write(&ni->runlist.lock);
+ err = ntfs_attr_map_cluster(ni, vcn, &start_lcn, &lcn_count,
+ max_clu_count, &balloc, update_mp,
+ !(flags & IOMAP_DIRECT) && !mapped);
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ if (err) {
+ ni->i_dealloc_clusters = 0;
+ return err;
+ }
+
+ iomap->bdev = inode->i_sb->s_bdev;
+ iomap->offset = offset;
+
+ rl_length = lcn_count << ni->vol->cluster_size_bits;
+ if (length > rl_length - vcn_ofs)
+ iomap->length = rl_length - vcn_ofs;
+ else
+ iomap->length = length;
+
+ if (start_lcn == LCN_HOLE)
+ iomap->type = IOMAP_HOLE;
+ else
+ iomap->type = IOMAP_MAPPED;
+ if (balloc == true)
+ iomap->flags = IOMAP_F_NEW;
+
+ iomap->addr = (start_lcn << vol->cluster_size_bits) + vcn_ofs;
+
+ if (balloc == true) {
+ if (flags & IOMAP_DIRECT || mapped == true) {
+ loff_t end = offset + length;
+
+ if (vcn_ofs || ((vol->cluster_size > iomap->length) &&
+ end < ni->initialized_size))
+ err = ntfs_zeroed_clusters(inode,
+ start_lcn, 1);
+ if (!err && lcn_count > 1 &&
+ (iomap->length & vol->cluster_size_mask &&
+ end < ni->initialized_size))
+ err = ntfs_zeroed_clusters(inode,
+ start_lcn + (lcn_count - 1), 1);
+ } else {
+ if (lcn_count > ni->i_dealloc_clusters)
+ ni->i_dealloc_clusters = 0;
+ else
+ ni->i_dealloc_clusters -= lcn_count;
+ }
+ if (err < 0)
+ return err;
+ }
+
+ if (mapped && iomap->offset + iomap->length >
+ ni->initialized_size) {
+ err = ntfs_attr_set_initialized_size(ni, iomap->offset +
+ iomap->length);
+ if (err)
+ return err;
+ }
+ } else {
+ struct runlist_element *rl, *rlc;
+ s64 lcn;
+ bool is_retry = false;
+
+ down_read(&ni->runlist.lock);
+ rl = ni->runlist.rl;
+ if (!rl) {
+ up_read(&ni->runlist.lock);
+ err = ntfs_map_runlist(ni, vcn);
+ if (err) {
+ mutex_unlock(&ni->mrec_lock);
+ return -ENOENT;
+ }
+ down_read(&ni->runlist.lock);
+ rl = ni->runlist.rl;
+ }
+ up_read(&ni->runlist.lock);
+
+ down_write(&ni->runlist.lock);
+remap_rl:
+ /* Seek to element containing target vcn. */
+ while (rl->length && rl[1].vcn <= vcn)
+ rl++;
+ lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
+
+ if (lcn <= LCN_RL_NOT_MAPPED && is_retry == false) {
+ is_retry = true;
+ if (!ntfs_map_runlist_nolock(ni, vcn, NULL)) {
+ rl = ni->runlist.rl;
+ goto remap_rl;
+ }
+ }
+
+ max_clu_count = min(max_clu_count, rl->length - (vcn - rl->vcn));
+ if (max_clu_count == 0) {
+ ntfs_error(inode->i_sb,
+ "runlist(vcn : %lld, length : %lld) is corrupted\n",
+ rl->vcn, rl->length);
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ return -EIO;
+ }
+
+ iomap->bdev = inode->i_sb->s_bdev;
+ iomap->offset = offset;
+
+ if (lcn <= LCN_DELALLOC) {
+ if (lcn < LCN_DELALLOC) {
+ max_clu_count =
+ ntfs_available_clusters_count(vol, max_clu_count);
+ if (max_clu_count < 0) {
+ err = max_clu_count;
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ return err;
+ }
+ }
+
+ iomap->type = IOMAP_DELALLOC;
+ iomap->addr = IOMAP_NULL_ADDR;
+
+ if (lcn <= LCN_HOLE) {
+ size_t new_rl_count;
+
+ rlc = ntfs_malloc_nofs(sizeof(struct runlist_element) * 2);
+ if (!rlc) {
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ return -ENOMEM;
+ }
+
+ rlc->vcn = vcn;
+ rlc->lcn = LCN_DELALLOC;
+ rlc->length = max_clu_count;
+
+ rlc[1].vcn = vcn + max_clu_count;
+ rlc[1].lcn = LCN_RL_NOT_MAPPED;
+ rlc[1].length = 0;
+
+ rl = ntfs_runlists_merge(&ni->runlist, rlc, 0,
+ &new_rl_count);
+ if (IS_ERR(rl)) {
+ ntfs_error(vol->sb, "Failed to merge runlists");
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ ntfs_free(rlc);
+ return PTR_ERR(rl);
+ }
+
+ ni->runlist.rl = rl;
+ ni->runlist.count = new_rl_count;
+ ni->i_dealloc_clusters += max_clu_count;
+ }
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+
+ if (lcn < LCN_DELALLOC)
+ ntfs_hold_dirty_clusters(vol, max_clu_count);
+
+ rl_length = max_clu_count << ni->vol->cluster_size_bits;
+ if (length > rl_length - vcn_ofs)
+ iomap->length = rl_length - vcn_ofs;
+ else
+ iomap->length = length;
+
+ iomap->flags = IOMAP_F_NEW;
+ if (lcn <= LCN_HOLE) {
+ loff_t end = offset + length;
+
+ if (vcn_ofs || ((vol->cluster_size > iomap->length) &&
+ end < ni->initialized_size))
+ err = ntfs_buffered_zeroed_clusters(inode, vcn);
+ if (!err && max_clu_count > 1 &&
+ (iomap->length & vol->cluster_size_mask &&
+ end < ni->initialized_size))
+ err = ntfs_buffered_zeroed_clusters(inode,
+ vcn + (max_clu_count - 1));
+ if (err) {
+ ntfs_release_dirty_clusters(vol, max_clu_count);
+ return err;
+ }
+ }
+ } else {
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+
+ iomap->type = IOMAP_MAPPED;
+ iomap->addr = (lcn << vol->cluster_size_bits) + vcn_ofs;
+
+ rl_length = max_clu_count << ni->vol->cluster_size_bits;
+ if (length > rl_length - vcn_ofs)
+ iomap->length = rl_length - vcn_ofs;
+ else
+ iomap->length = length;
+ }
+ }
+
+ return 0;
+ }
+
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ err = -ENOMEM;
+ goto out;
+ }
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx);
+ if (err) {
+ if (err == -ENOENT)
+ err = -EIO;
+ goto 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);
+
+ BUG_ON(offset > attr_len);
+ kattr = (u8 *)a + le16_to_cpu(a->data.resident.value_offset);
+
+ ipage = alloc_page(__GFP_NOWARN | __GFP_IO | __GFP_ZERO);
+ if (!ipage) {
+ err = -ENOMEM;
+ goto out;
+ }
+ memcpy(page_address(ipage), kattr, attr_len);
+
+ iomap->type = IOMAP_INLINE;
+ iomap->inline_data = page_address(ipage);
+ iomap->offset = 0;
+ /* iomap requires there is only one INLINE_DATA extent */
+ iomap->length = attr_len;
+ iomap->private = ipage;
+
+out:
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+ mutex_unlock(&ni->mrec_lock);
+
+ return err;
+}
+
+static int ntfs_write_iomap_begin(struct inode *inode, loff_t offset,
+ loff_t length, unsigned int flags,
+ struct iomap *iomap, struct iomap *srcmap)
+{
+ return __ntfs_write_iomap_begin(inode, offset, length, flags, iomap,
+ false, false);
+}
+
+static int ntfs_write_iomap_end(struct inode *inode, loff_t pos, loff_t length,
+ ssize_t written, unsigned int flags, struct iomap *iomap)
+{
+ if (iomap->type == IOMAP_INLINE) {
+ struct page *ipage = iomap->private;
+ struct ntfs_inode *ni = NTFS_I(inode);
+ struct ntfs_attr_search_ctx *ctx;
+ u32 attr_len;
+ int err;
+ char *kattr;
+
+ mutex_lock(&ni->mrec_lock);
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ written = -ENOMEM;
+ mutex_unlock(&ni->mrec_lock);
+ goto out;
+ }
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx);
+ if (err) {
+ if (err == -ENOENT)
+ err = -EIO;
+ written = err;
+ goto err_out;
+ }
+
+ /* The total length of the attribute value. */
+ attr_len = le32_to_cpu(ctx->attr->data.resident.value_length);
+ if (pos >= attr_len || pos + written > attr_len)
+ goto err_out;
+
+ kattr = (u8 *)ctx->attr + le16_to_cpu(ctx->attr->data.resident.value_offset);
+ memcpy(kattr + pos, iomap_inline_data(iomap, pos), written);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+err_out:
+ ntfs_attr_put_search_ctx(ctx);
+ put_page(ipage);
+ mutex_unlock(&ni->mrec_lock);
+ }
+
+out:
+ return written;
+}
+
+const struct iomap_ops ntfs_write_iomap_ops = {
+ .iomap_begin = ntfs_write_iomap_begin,
+ .iomap_end = ntfs_write_iomap_end,
+};
+
+static int ntfs_page_mkwrite_iomap_begin(struct inode *inode, loff_t offset,
+ loff_t length, unsigned int flags,
+ struct iomap *iomap, struct iomap *srcmap)
+{
+ return __ntfs_write_iomap_begin(inode, offset, length, flags, iomap,
+ true, true);
+}
+
+const struct iomap_ops ntfs_page_mkwrite_iomap_ops = {
+ .iomap_begin = ntfs_page_mkwrite_iomap_begin,
+ .iomap_end = ntfs_write_iomap_end,
+};
+
+static int ntfs_dio_iomap_begin(struct inode *inode, loff_t offset,
+ loff_t length, unsigned int flags,
+ struct iomap *iomap, struct iomap *srcmap)
+{
+ return __ntfs_write_iomap_begin(inode, offset, length, flags, iomap,
+ true, false);
+}
+
+const struct iomap_ops ntfs_dio_iomap_ops = {
+ .iomap_begin = ntfs_dio_iomap_begin,
+ .iomap_end = ntfs_write_iomap_end,
+};
+
+static ssize_t ntfs_writeback_range(struct iomap_writepage_ctx *wpc,
+ struct folio *folio, u64 offset, unsigned int len, u64 end_pos)
+{
+ if (offset < wpc->iomap.offset ||
+ offset >= wpc->iomap.offset + wpc->iomap.length) {
+ int error;
+
+ error = __ntfs_write_iomap_begin(wpc->inode, offset,
+ NTFS_I(wpc->inode)->allocated_size - offset,
+ IOMAP_WRITE, &wpc->iomap, true, false);
+ if (error)
+ return error;
+ }
+
+ return iomap_add_to_ioend(wpc, folio, offset, end_pos, len);
+}
+
+const struct iomap_writeback_ops ntfs_writeback_ops = {
+ .writeback_range = ntfs_writeback_range,
+ .writeback_submit = iomap_ioend_writeback_submit,
+};
--
2.34.1
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH 07/11] ntfsplus: add attrib operatrions
2025-10-20 2:12 [PATCH 06/11] ntfsplus: add iomap and address space operations Namjae Jeon
@ 2025-10-20 2:12 ` Namjae Jeon
2025-10-20 2:12 ` [PATCH 08/11] ntfsplus: add runlist handling and cluster allocator Namjae Jeon
` (3 subsequent siblings)
4 siblings, 0 replies; 6+ messages in thread
From: Namjae Jeon @ 2025-10-20 2:12 UTC (permalink / raw)
To: viro, brauner, hch, hch, tytso, willy, jack, djwong, josef,
sandeen, rgoldwyn, xiang, dsterba, pali, ebiggers, neil,
amir73il
Cc: linux-fsdevel, linux-kernel, iamjoonsoo.kim, cheol.lee, jay.sim,
gunho.lee, Namjae Jeon
This adds the implementation of attrib operatrions for ntfsplus.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
---
fs/ntfsplus/attrib.c | 5373 ++++++++++++++++++++++++++++++++++++++++
fs/ntfsplus/attrlist.c | 276 +++
fs/ntfsplus/compress.c | 1565 ++++++++++++
3 files changed, 7214 insertions(+)
create mode 100644 fs/ntfsplus/attrib.c
create mode 100644 fs/ntfsplus/attrlist.c
create mode 100644 fs/ntfsplus/compress.c
diff --git a/fs/ntfsplus/attrib.c b/fs/ntfsplus/attrib.c
new file mode 100644
index 000000000000..ba309d1acdcb
--- /dev/null
+++ b/fs/ntfsplus/attrib.c
@@ -0,0 +1,5373 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/**
+ * NTFS attribute operations. Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2001-2012 Anton Altaparmakov and Tuxera Inc.
+ * Copyright (c) 2002 Richard Russon
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ *
+ * Part of this file is based on code from the NTFS-3G project.
+ * and is copyrighted by the respective authors below:
+ * Copyright (c) 2000-2010 Anton Altaparmakov
+ * Copyright (c) 2002-2005 Richard Russon
+ * Copyright (c) 2002-2008 Szabolcs Szakacsits
+ * Copyright (c) 2004-2007 Yura Pakhuchiy
+ * Copyright (c) 2007-2021 Jean-Pierre Andre
+ * Copyright (c) 2010 Erik Larsson
+ */
+
+#include <linux/writeback.h>
+#include <linux/iomap.h>
+
+#include "attrib.h"
+#include "attrlist.h"
+#include "lcnalloc.h"
+#include "misc.h"
+#include "mft.h"
+#include "ntfs.h"
+#include "aops.h"
+#include "ntfs_iomap.h"
+
+__le16 AT_UNNAMED[] = { cpu_to_le16('\0') };
+
+/**
+ * ntfs_map_runlist_nolock - map (a part of) a runlist of an ntfs inode
+ * @ni: ntfs inode for which to map (part of) a runlist
+ * @vcn: map runlist part containing this vcn
+ * @ctx: active attribute search context if present or NULL if not
+ *
+ * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
+ *
+ * If @ctx is specified, it is an active search context of @ni and its base mft
+ * record. This is needed when ntfs_map_runlist_nolock() encounters unmapped
+ * runlist fragments and allows their mapping. If you do not have the mft
+ * record mapped, you can specify @ctx as NULL and ntfs_map_runlist_nolock()
+ * will perform the necessary mapping and unmapping.
+ *
+ * Note, ntfs_map_runlist_nolock() saves the state of @ctx on entry and
+ * restores it before returning. Thus, @ctx will be left pointing to the same
+ * attribute on return as on entry. However, the actual pointers in @ctx may
+ * point to different memory locations on return, so you must remember to reset
+ * any cached pointers from the @ctx, i.e. after the call to
+ * ntfs_map_runlist_nolock(), you will probably want to do:
+ * m = ctx->mrec;
+ * a = ctx->attr;
+ * Assuming you cache ctx->attr in a variable @a of type attr_record * and that
+ * you cache ctx->mrec in a variable @m of type struct mft_record *.
+ */
+int ntfs_map_runlist_nolock(struct ntfs_inode *ni, s64 vcn, struct ntfs_attr_search_ctx *ctx)
+{
+ s64 end_vcn;
+ unsigned long flags;
+ struct ntfs_inode *base_ni;
+ struct mft_record *m;
+ struct attr_record *a;
+ struct runlist_element *rl;
+ struct folio *put_this_folio = NULL;
+ int err = 0;
+ bool ctx_is_temporary, ctx_needs_reset;
+ struct ntfs_attr_search_ctx old_ctx = { NULL, };
+ size_t new_rl_count;
+
+ ntfs_debug("Mapping runlist part containing vcn 0x%llx.",
+ (unsigned long long)vcn);
+ if (!NInoAttr(ni))
+ base_ni = ni;
+ else
+ base_ni = ni->ext.base_ntfs_ino;
+ if (!ctx) {
+ ctx_is_temporary = ctx_needs_reset = true;
+ m = map_mft_record(base_ni);
+ if (IS_ERR(m))
+ return PTR_ERR(m);
+ ctx = ntfs_attr_get_search_ctx(base_ni, m);
+ if (unlikely(!ctx)) {
+ err = -ENOMEM;
+ goto err_out;
+ }
+ } else {
+ s64 allocated_size_vcn;
+
+ BUG_ON(IS_ERR(ctx->mrec));
+ a = ctx->attr;
+ if (!a->non_resident) {
+ err = -EIO;
+ goto err_out;
+ }
+ ctx_is_temporary = false;
+ end_vcn = le64_to_cpu(a->data.non_resident.highest_vcn);
+ read_lock_irqsave(&ni->size_lock, flags);
+ allocated_size_vcn = ni->allocated_size >>
+ ni->vol->cluster_size_bits;
+ read_unlock_irqrestore(&ni->size_lock, flags);
+ if (!a->data.non_resident.lowest_vcn && end_vcn <= 0)
+ end_vcn = allocated_size_vcn - 1;
+ /*
+ * If we already have the attribute extent containing @vcn in
+ * @ctx, no need to look it up again. We slightly cheat in
+ * that if vcn exceeds the allocated size, we will refuse to
+ * map the runlist below, so there is definitely no need to get
+ * the right attribute extent.
+ */
+ if (vcn >= allocated_size_vcn || (a->type == ni->type &&
+ a->name_length == ni->name_len &&
+ !memcmp((u8 *)a + le16_to_cpu(a->name_offset),
+ ni->name, ni->name_len) &&
+ le64_to_cpu(a->data.non_resident.lowest_vcn)
+ <= vcn && end_vcn >= vcn))
+ ctx_needs_reset = false;
+ else {
+ /* Save the old search context. */
+ old_ctx = *ctx;
+ /*
+ * If the currently mapped (extent) inode is not the
+ * base inode we will unmap it when we reinitialize the
+ * search context which means we need to get a
+ * reference to the page containing the mapped mft
+ * record so we do not accidentally drop changes to the
+ * mft record when it has not been marked dirty yet.
+ */
+ if (old_ctx.base_ntfs_ino && old_ctx.ntfs_ino !=
+ old_ctx.base_ntfs_ino) {
+ put_this_folio = old_ctx.ntfs_ino->folio;
+ folio_get(put_this_folio);
+ }
+ /*
+ * Reinitialize the search context so we can lookup the
+ * needed attribute extent.
+ */
+ ntfs_attr_reinit_search_ctx(ctx);
+ ctx_needs_reset = true;
+ }
+ }
+ if (ctx_needs_reset) {
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, vcn, NULL, 0, ctx);
+ if (unlikely(err)) {
+ if (err == -ENOENT)
+ err = -EIO;
+ goto err_out;
+ }
+ BUG_ON(!ctx->attr->non_resident);
+ }
+ a = ctx->attr;
+ /*
+ * Only decompress the mapping pairs if @vcn is inside it. Otherwise
+ * we get into problems when we try to map an out of bounds vcn because
+ * we then try to map the already mapped runlist fragment and
+ * ntfs_mapping_pairs_decompress() fails.
+ */
+ end_vcn = le64_to_cpu(a->data.non_resident.highest_vcn) + 1;
+ if (unlikely(vcn && vcn >= end_vcn)) {
+ err = -ENOENT;
+ goto err_out;
+ }
+ rl = ntfs_mapping_pairs_decompress(ni->vol, a, &ni->runlist, &new_rl_count);
+ if (IS_ERR(rl))
+ err = PTR_ERR(rl);
+ else {
+ ni->runlist.rl = rl;
+ ni->runlist.count = new_rl_count;
+ }
+err_out:
+ if (ctx_is_temporary) {
+ if (likely(ctx))
+ ntfs_attr_put_search_ctx(ctx);
+ unmap_mft_record(base_ni);
+ } else if (ctx_needs_reset) {
+ /*
+ * If there is no attribute list, restoring the search context
+ * is accomplished simply by copying the saved context back over
+ * the caller supplied context. If there is an attribute list,
+ * things are more complicated as we need to deal with mapping
+ * of mft records and resulting potential changes in pointers.
+ */
+ if (NInoAttrList(base_ni)) {
+ /*
+ * If the currently mapped (extent) inode is not the
+ * one we had before, we need to unmap it and map the
+ * old one.
+ */
+ if (ctx->ntfs_ino != old_ctx.ntfs_ino) {
+ /*
+ * If the currently mapped inode is not the
+ * base inode, unmap it.
+ */
+ if (ctx->base_ntfs_ino && ctx->ntfs_ino !=
+ ctx->base_ntfs_ino) {
+ unmap_extent_mft_record(ctx->ntfs_ino);
+ ctx->mrec = ctx->base_mrec;
+ BUG_ON(!ctx->mrec);
+ }
+ /*
+ * If the old mapped inode is not the base
+ * inode, map it.
+ */
+ if (old_ctx.base_ntfs_ino &&
+ old_ctx.ntfs_ino != old_ctx.base_ntfs_ino) {
+retry_map:
+ ctx->mrec = map_mft_record(old_ctx.ntfs_ino);
+ /*
+ * Something bad has happened. If out
+ * of memory retry till it succeeds.
+ * Any other errors are fatal and we
+ * return the error code in ctx->mrec.
+ * Let the caller deal with it... We
+ * just need to fudge things so the
+ * caller can reinit and/or put the
+ * search context safely.
+ */
+ if (IS_ERR(ctx->mrec)) {
+ if (PTR_ERR(ctx->mrec) == -ENOMEM) {
+ schedule();
+ goto retry_map;
+ } else
+ old_ctx.ntfs_ino =
+ old_ctx.base_ntfs_ino;
+ }
+ }
+ }
+ /* Update the changed pointers in the saved context. */
+ if (ctx->mrec != old_ctx.mrec) {
+ if (!IS_ERR(ctx->mrec))
+ old_ctx.attr = (struct attr_record *)(
+ (u8 *)ctx->mrec +
+ ((u8 *)old_ctx.attr -
+ (u8 *)old_ctx.mrec));
+ old_ctx.mrec = ctx->mrec;
+ }
+ }
+ /* Restore the search context to the saved one. */
+ *ctx = old_ctx;
+ /*
+ * We drop the reference on the page we took earlier. In the
+ * case that IS_ERR(ctx->mrec) is true this means we might lose
+ * some changes to the mft record that had been made between
+ * the last time it was marked dirty/written out and now. This
+ * at this stage is not a problem as the mapping error is fatal
+ * enough that the mft record cannot be written out anyway and
+ * the caller is very likely to shutdown the whole inode
+ * immediately and mark the volume dirty for chkdsk to pick up
+ * the pieces anyway.
+ */
+ if (put_this_folio)
+ folio_put(put_this_folio);
+ }
+ return err;
+}
+
+/**
+ * ntfs_map_runlist - map (a part of) a runlist of an ntfs inode
+ * @ni: ntfs inode for which to map (part of) a runlist
+ * @vcn: map runlist part containing this vcn
+ *
+ * Map the part of a runlist containing the @vcn of the ntfs inode @ni.
+ */
+int ntfs_map_runlist(struct ntfs_inode *ni, s64 vcn)
+{
+ int err = 0;
+
+ down_write(&ni->runlist.lock);
+ /* Make sure someone else didn't do the work while we were sleeping. */
+ if (likely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) <=
+ LCN_RL_NOT_MAPPED))
+ err = ntfs_map_runlist_nolock(ni, vcn, NULL);
+ up_write(&ni->runlist.lock);
+ return err;
+}
+
+struct runlist_element *ntfs_attr_vcn_to_rl(struct ntfs_inode *ni, s64 vcn, s64 *lcn)
+{
+ struct runlist_element *rl;
+ int err;
+ bool is_retry = false;
+
+ rl = ni->runlist.rl;
+ if (!rl) {
+ err = ntfs_attr_map_whole_runlist(ni);
+ if (err)
+ return ERR_PTR(-ENOENT);
+ rl = ni->runlist.rl;
+ }
+
+remap_rl:
+ /* Seek to element containing target vcn. */
+ while (rl->length && rl[1].vcn <= vcn)
+ rl++;
+ *lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
+
+ if (*lcn <= LCN_RL_NOT_MAPPED && is_retry == false) {
+ is_retry = true;
+ if (!ntfs_map_runlist_nolock(ni, vcn, NULL)) {
+ rl = ni->runlist.rl;
+ goto remap_rl;
+ }
+ }
+
+ return rl;
+}
+
+/**
+ * ntfs_attr_vcn_to_lcn_nolock - convert a vcn into a lcn given an ntfs inode
+ * @ni: ntfs inode of the attribute whose runlist to search
+ * @vcn: vcn to convert
+ * @write_locked: true if the runlist is locked for writing
+ *
+ * Find the virtual cluster number @vcn in the runlist of the ntfs attribute
+ * described by the ntfs inode @ni and return the corresponding logical cluster
+ * number (lcn).
+ *
+ * If the @vcn is not mapped yet, the attempt is made to map the attribute
+ * extent containing the @vcn and the vcn to lcn conversion is retried.
+ *
+ * If @write_locked is true the caller has locked the runlist for writing and
+ * if false for reading.
+ *
+ * Since lcns must be >= 0, we use negative return codes with special meaning:
+ *
+ * Return code Meaning / Description
+ * ==========================================
+ * LCN_HOLE Hole / not allocated on disk.
+ * LCN_ENOENT There is no such vcn in the runlist, i.e. @vcn is out of bounds.
+ * LCN_ENOMEM Not enough memory to map runlist.
+ * LCN_EIO Critical error (runlist/file is corrupt, i/o error, etc).
+ *
+ * Locking: - The runlist must be locked on entry and is left locked on return.
+ * - If @write_locked is 'false', i.e. the runlist is locked for reading,
+ * the lock may be dropped inside the function so you cannot rely on
+ * the runlist still being the same when this function returns.
+ */
+s64 ntfs_attr_vcn_to_lcn_nolock(struct ntfs_inode *ni, const s64 vcn,
+ const bool write_locked)
+{
+ s64 lcn;
+ unsigned long flags;
+ bool is_retry = false;
+
+ BUG_ON(!ni);
+ ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, %s_locked.",
+ ni->mft_no, (unsigned long long)vcn,
+ write_locked ? "write" : "read");
+ BUG_ON(!NInoNonResident(ni));
+ BUG_ON(vcn < 0);
+ if (!ni->runlist.rl) {
+ read_lock_irqsave(&ni->size_lock, flags);
+ if (!ni->allocated_size) {
+ read_unlock_irqrestore(&ni->size_lock, flags);
+ return LCN_ENOENT;
+ }
+ read_unlock_irqrestore(&ni->size_lock, flags);
+ }
+retry_remap:
+ /* Convert vcn to lcn. If that fails map the runlist and retry once. */
+ lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn);
+ if (likely(lcn >= LCN_HOLE)) {
+ ntfs_debug("Done, lcn 0x%llx.", (long long)lcn);
+ return lcn;
+ }
+ if (lcn != LCN_RL_NOT_MAPPED) {
+ if (lcn != LCN_ENOENT)
+ lcn = LCN_EIO;
+ } else if (!is_retry) {
+ int err;
+
+ if (!write_locked) {
+ up_read(&ni->runlist.lock);
+ down_write(&ni->runlist.lock);
+ if (unlikely(ntfs_rl_vcn_to_lcn(ni->runlist.rl, vcn) !=
+ LCN_RL_NOT_MAPPED)) {
+ up_write(&ni->runlist.lock);
+ down_read(&ni->runlist.lock);
+ goto retry_remap;
+ }
+ }
+ err = ntfs_map_runlist_nolock(ni, vcn, NULL);
+ if (!write_locked) {
+ up_write(&ni->runlist.lock);
+ down_read(&ni->runlist.lock);
+ }
+ if (likely(!err)) {
+ is_retry = true;
+ goto retry_remap;
+ }
+ if (err == -ENOENT)
+ lcn = LCN_ENOENT;
+ else if (err == -ENOMEM)
+ lcn = LCN_ENOMEM;
+ else
+ lcn = LCN_EIO;
+ }
+ if (lcn != LCN_ENOENT)
+ ntfs_error(ni->vol->sb, "Failed with error code %lli.",
+ (long long)lcn);
+ return lcn;
+}
+
+struct runlist_element *__ntfs_attr_find_vcn_nolock(struct runlist *runlist, const s64 vcn)
+{
+ size_t lower_idx, upper_idx, idx;
+ struct runlist_element *run;
+
+ if (runlist->count <= 1)
+ return ERR_PTR(-ENOENT);
+
+ run = &runlist->rl[0];
+ if (vcn < run->vcn)
+ return ERR_PTR(-ENOENT);
+ else if (vcn < run->vcn + run->length)
+ return run;
+
+ run = &runlist->rl[runlist->count - 2];
+ if (vcn >= run->vcn && vcn < run->vcn + run->length)
+ return run;
+ if (vcn >= run->vcn + run->length)
+ return ERR_PTR(-ENOENT);
+
+ lower_idx = 1;
+ upper_idx = runlist->count - 2;
+
+ while (lower_idx <= upper_idx) {
+ idx = (lower_idx + upper_idx) >> 1;
+ run = &runlist->rl[idx];
+
+ if (vcn < run->vcn)
+ upper_idx = idx - 1;
+ else if (vcn >= run->vcn + run->length)
+ lower_idx = idx + 1;
+ else
+ return run;
+ }
+
+ return ERR_PTR(-ENOENT);
+}
+
+/**
+ * ntfs_attr_find_vcn_nolock - find a vcn in the runlist of an ntfs inode
+ * @ni: ntfs inode describing the runlist to search
+ * @vcn: vcn to find
+ * @ctx: active attribute search context if present or NULL if not
+ *
+ * Find the virtual cluster number @vcn in the runlist described by the ntfs
+ * inode @ni and return the address of the runlist element containing the @vcn.
+ *
+ * If the @vcn is not mapped yet, the attempt is made to map the attribute
+ * extent containing the @vcn and the vcn to lcn conversion is retried.
+ *
+ * If @ctx is specified, it is an active search context of @ni and its base mft
+ * record. This is needed when ntfs_attr_find_vcn_nolock() encounters unmapped
+ * runlist fragments and allows their mapping. If you do not have the mft
+ * record mapped, you can specify @ctx as NULL and ntfs_attr_find_vcn_nolock()
+ * will perform the necessary mapping and unmapping.
+ *
+ * Note, ntfs_attr_find_vcn_nolock() saves the state of @ctx on entry and
+ * restores it before returning. Thus, @ctx will be left pointing to the same
+ * attribute on return as on entry. However, the actual pointers in @ctx may
+ * point to different memory locations on return, so you must remember to reset
+ * any cached pointers from the @ctx, i.e. after the call to
+ * ntfs_attr_find_vcn_nolock(), you will probably want to do:
+ * m = ctx->mrec;
+ * a = ctx->attr;
+ * Assuming you cache ctx->attr in a variable @a of type attr_record * and that
+ * you cache ctx->mrec in a variable @m of type struct mft_record *.
+ * Note you need to distinguish between the lcn of the returned runlist element
+ * being >= 0 and LCN_HOLE. In the later case you have to return zeroes on
+ * read and allocate clusters on write.
+ */
+struct runlist_element *ntfs_attr_find_vcn_nolock(struct ntfs_inode *ni, const s64 vcn,
+ struct ntfs_attr_search_ctx *ctx)
+{
+ unsigned long flags;
+ struct runlist_element *rl;
+ int err = 0;
+ bool is_retry = false;
+
+ BUG_ON(!ni);
+ ntfs_debug("Entering for i_ino 0x%lx, vcn 0x%llx, with%s ctx.",
+ ni->mft_no, (unsigned long long)vcn, ctx ? "" : "out");
+ BUG_ON(!NInoNonResident(ni));
+ BUG_ON(vcn < 0);
+ if (!ni->runlist.rl) {
+ read_lock_irqsave(&ni->size_lock, flags);
+ if (!ni->allocated_size) {
+ read_unlock_irqrestore(&ni->size_lock, flags);
+ return ERR_PTR(-ENOENT);
+ }
+ read_unlock_irqrestore(&ni->size_lock, flags);
+ }
+
+retry_remap:
+ rl = ni->runlist.rl;
+ if (likely(rl && vcn >= rl[0].vcn)) {
+ rl = __ntfs_attr_find_vcn_nolock(&ni->runlist, vcn);
+ if (IS_ERR(rl))
+ err = PTR_ERR(rl);
+ else if (rl->lcn >= LCN_HOLE)
+ return rl;
+ else if (rl->lcn <= LCN_ENOENT)
+ err = -EIO;
+ }
+ if (!err && !is_retry) {
+ /*
+ * If the search context is invalid we cannot map the unmapped
+ * region.
+ */
+ if (ctx && IS_ERR(ctx->mrec))
+ err = PTR_ERR(ctx->mrec);
+ else {
+ /*
+ * The @vcn is in an unmapped region, map the runlist
+ * and retry.
+ */
+ err = ntfs_map_runlist_nolock(ni, vcn, ctx);
+ if (likely(!err)) {
+ is_retry = true;
+ goto retry_remap;
+ }
+ }
+ if (err == -EINVAL)
+ err = -EIO;
+ } else if (!err)
+ err = -EIO;
+ if (err != -ENOENT)
+ ntfs_error(ni->vol->sb, "Failed with error code %i.", err);
+ return ERR_PTR(err);
+}
+
+/**
+ * ntfs_attr_find - find (next) attribute in mft record
+ * @type: attribute type to find
+ * @name: attribute name to find (optional, i.e. NULL means don't care)
+ * @name_len: attribute name length (only needed if @name present)
+ * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
+ * @val: attribute value to find (optional, resident attributes only)
+ * @val_len: attribute value length
+ * @ctx: search context with mft record and attribute to search from
+ *
+ * You should not need to call this function directly. Use ntfs_attr_lookup()
+ * instead.
+ *
+ * ntfs_attr_find() takes a search context @ctx as parameter and searches the
+ * mft record specified by @ctx->mrec, beginning at @ctx->attr, for an
+ * attribute of @type, optionally @name and @val.
+ *
+ * If the attribute is found, ntfs_attr_find() returns 0 and @ctx->attr will
+ * point to the found attribute.
+ *
+ * If the attribute is not found, ntfs_attr_find() returns -ENOENT and
+ * @ctx->attr will point to the attribute before which the attribute being
+ * searched for would need to be inserted if such an action were to be desired.
+ *
+ * On actual error, ntfs_attr_find() returns -EIO. In this case @ctx->attr is
+ * undefined and in particular do not rely on it not changing.
+ *
+ * If @ctx->is_first is 'true', the search begins with @ctx->attr itself. If it
+ * is 'false', the search begins after @ctx->attr.
+ *
+ * If @ic is IGNORE_CASE, the @name comparisson is not case sensitive and
+ * @ctx->ntfs_ino must be set to the ntfs inode to which the mft record
+ * @ctx->mrec belongs. This is so we can get at the ntfs volume and hence at
+ * the upcase table. If @ic is CASE_SENSITIVE, the comparison is case
+ * sensitive. When @name is present, @name_len is the @name length in Unicode
+ * characters.
+ *
+ * If @name is not present (NULL), we assume that the unnamed attribute is
+ * being searched for.
+ *
+ * Finally, the resident attribute value @val is looked for, if present. If
+ * @val is not present (NULL), @val_len is ignored.
+ *
+ * ntfs_attr_find() only searches the specified mft record and it ignores the
+ * presence of an attribute list attribute (unless it is the one being searched
+ * for, obviously). If you need to take attribute lists into consideration,
+ * use ntfs_attr_lookup() instead (see below). This also means that you cannot
+ * use ntfs_attr_find() to search for extent records of non-resident
+ * attributes, as extents with lowest_vcn != 0 are usually described by the
+ * attribute list attribute only. - Note that it is possible that the first
+ * extent is only in the attribute list while the last extent is in the base
+ * mft record, so do not rely on being able to find the first extent in the
+ * base mft record.
+ *
+ * Warning: Never use @val when looking for attribute types which can be
+ * non-resident as this most likely will result in a crash!
+ */
+static int ntfs_attr_find(const __le32 type, const __le16 *name,
+ const u32 name_len, const u32 ic,
+ const u8 *val, const u32 val_len, struct ntfs_attr_search_ctx *ctx)
+{
+ struct attr_record *a;
+ struct ntfs_volume *vol = ctx->ntfs_ino->vol;
+ __le16 *upcase = vol->upcase;
+ u32 upcase_len = vol->upcase_len;
+ unsigned int space;
+
+ /*
+ * Iterate over attributes in mft record starting at @ctx->attr, or the
+ * attribute following that, if @ctx->is_first is 'true'.
+ */
+ if (ctx->is_first) {
+ a = ctx->attr;
+ ctx->is_first = false;
+ } else
+ a = (struct attr_record *)((u8 *)ctx->attr +
+ le32_to_cpu(ctx->attr->length));
+ for (;; a = (struct attr_record *)((u8 *)a + le32_to_cpu(a->length))) {
+ if ((u8 *)a < (u8 *)ctx->mrec || (u8 *)a > (u8 *)ctx->mrec +
+ le32_to_cpu(ctx->mrec->bytes_allocated))
+ break;
+
+ space = le32_to_cpu(ctx->mrec->bytes_in_use) - ((u8 *)a - (u8 *)ctx->mrec);
+ if ((space < offsetof(struct attr_record, data.resident.reserved) + 1 ||
+ space < le32_to_cpu(a->length)) && (space < 4 || a->type != AT_END))
+ break;
+
+ ctx->attr = a;
+ if (((type != AT_UNUSED) && (le32_to_cpu(a->type) > le32_to_cpu(type))) ||
+ a->type == AT_END)
+ return -ENOENT;
+ if (unlikely(!a->length))
+ break;
+ if (type == AT_UNUSED)
+ return 0;
+ if (a->type != type)
+ continue;
+ /*
+ * If @name is present, compare the two names. If @name is
+ * missing, assume we want an unnamed attribute.
+ */
+ if (!name || name == AT_UNNAMED) {
+ /* The search failed if the found attribute is named. */
+ if (a->name_length)
+ return -ENOENT;
+ } else {
+ if (a->name_length && ((le16_to_cpu(a->name_offset) +
+ a->name_length * sizeof(__le16)) >
+ le32_to_cpu(a->length))) {
+ ntfs_error(vol->sb, "Corrupt attribute name in MFT record %lld\n",
+ (long long)ctx->ntfs_ino->mft_no);
+ break;
+ }
+
+ if (!ntfs_are_names_equal(name, name_len,
+ (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
+ a->name_length, ic, upcase, upcase_len)) {
+ register int rc;
+
+ rc = ntfs_collate_names(name, name_len,
+ (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
+ a->name_length, 1, IGNORE_CASE,
+ upcase, upcase_len);
+ /*
+ * If @name collates before a->name, there is no
+ * matching attribute.
+ */
+ if (rc == -1)
+ return -ENOENT;
+ /* If the strings are not equal, continue search. */
+ if (rc)
+ continue;
+ rc = ntfs_collate_names(name, name_len,
+ (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
+ a->name_length, 1, CASE_SENSITIVE,
+ upcase, upcase_len);
+ if (rc == -1)
+ return -ENOENT;
+ if (rc)
+ continue;
+ }
+ }
+ /*
+ * The names match or @name not present and attribute is
+ * unnamed. If no @val specified, we have found the attribute
+ * and are done.
+ */
+ if (!val)
+ return 0;
+ /* @val is present; compare values. */
+ else {
+ register int rc;
+
+ rc = memcmp(val, (u8 *)a + le16_to_cpu(
+ a->data.resident.value_offset),
+ min_t(u32, val_len, le32_to_cpu(
+ a->data.resident.value_length)));
+ /*
+ * If @val collates before the current attribute's
+ * value, there is no matching attribute.
+ */
+ if (!rc) {
+ register u32 avl;
+
+ avl = le32_to_cpu(a->data.resident.value_length);
+ if (val_len == avl)
+ return 0;
+ if (val_len < avl)
+ return -ENOENT;
+ } else if (rc < 0)
+ return -ENOENT;
+ }
+ }
+ ntfs_error(vol->sb, "Inode is corrupt. Run chkdsk.");
+ NVolSetErrors(vol);
+ return -EIO;
+}
+
+void ntfs_attr_name_free(unsigned char **name)
+{
+ if (*name) {
+ ntfs_free(*name);
+ *name = NULL;
+ }
+}
+
+char *ntfs_attr_name_get(const struct ntfs_volume *vol, const __le16 *uname,
+ const int uname_len)
+{
+ unsigned char *name = NULL;
+ int name_len;
+
+ name_len = ntfs_ucstonls(vol, uname, uname_len, &name, 0);
+ if (name_len < 0) {
+ ntfs_error(vol->sb, "ntfs_ucstonls error");
+ /* This function when returns -1, memory for name might
+ * be allocated. So lets free this memory.
+ */
+ ntfs_attr_name_free(&name);
+ return NULL;
+
+ } else if (name_len > 0)
+ return name;
+
+ ntfs_attr_name_free(&name);
+ return NULL;
+}
+
+int load_attribute_list(struct ntfs_inode *base_ni, u8 *al_start, const s64 size)
+{
+ struct inode *attr_vi = NULL;
+ u8 *al;
+ struct attr_list_entry *ale;
+
+ if (!al_start || size <= 0)
+ return -EINVAL;
+
+ attr_vi = ntfs_attr_iget(VFS_I(base_ni), AT_ATTRIBUTE_LIST, AT_UNNAMED, 0);
+ if (IS_ERR(attr_vi)) {
+ ntfs_error(base_ni->vol->sb,
+ "Failed to open an inode for Attribute list, mft = %ld",
+ base_ni->mft_no);
+ return PTR_ERR(attr_vi);
+ }
+
+ if (ntfs_inode_attr_pread(attr_vi, 0, size, al_start) != size) {
+ iput(attr_vi);
+ ntfs_error(base_ni->vol->sb,
+ "Failed to read attribute list, mft = %ld",
+ base_ni->mft_no);
+ return -EIO;
+ }
+ iput(attr_vi);
+
+ for (al = al_start; al < al_start + size; al += le16_to_cpu(ale->length)) {
+ ale = (struct attr_list_entry *)al;
+ if (ale->name_offset != sizeof(struct attr_list_entry))
+ break;
+ if (le16_to_cpu(ale->length) <= ale->name_offset + ale->name_length ||
+ al + le16_to_cpu(ale->length) > al_start + size)
+ break;
+ if (ale->type == AT_UNUSED)
+ break;
+ if (MSEQNO_LE(ale->mft_reference) == 0)
+ break;
+ }
+ if (al != al_start + size) {
+ ntfs_error(base_ni->vol->sb, "Corrupt attribute list, mft = %ld",
+ base_ni->mft_no);
+ return -EIO;
+ }
+ return 0;
+}
+
+/**
+ * ntfs_external_attr_find - find an attribute in the attribute list of an inode
+ * @type: attribute type to find
+ * @name: attribute name to find (optional, i.e. NULL means don't care)
+ * @name_len: attribute name length (only needed if @name present)
+ * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
+ * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
+ * @val: attribute value to find (optional, resident attributes only)
+ * @val_len: attribute value length
+ * @ctx: search context with mft record and attribute to search from
+ *
+ * You should not need to call this function directly. Use ntfs_attr_lookup()
+ * instead.
+ *
+ * Find an attribute by searching the attribute list for the corresponding
+ * attribute list entry. Having found the entry, map the mft record if the
+ * attribute is in a different mft record/inode, ntfs_attr_find() the attribute
+ * in there and return it.
+ *
+ * On first search @ctx->ntfs_ino must be the base mft record and @ctx must
+ * have been obtained from a call to ntfs_attr_get_search_ctx(). On subsequent
+ * calls @ctx->ntfs_ino can be any extent inode, too (@ctx->base_ntfs_ino is
+ * then the base inode).
+ *
+ * After finishing with the attribute/mft record you need to call
+ * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
+ * mapped inodes, etc).
+ *
+ * If the attribute is found, ntfs_external_attr_find() returns 0 and
+ * @ctx->attr will point to the found attribute. @ctx->mrec will point to the
+ * mft record in which @ctx->attr is located and @ctx->al_entry will point to
+ * the attribute list entry for the attribute.
+ *
+ * If the attribute is not found, ntfs_external_attr_find() returns -ENOENT and
+ * @ctx->attr will point to the attribute in the base mft record before which
+ * the attribute being searched for would need to be inserted if such an action
+ * were to be desired. @ctx->mrec will point to the mft record in which
+ * @ctx->attr is located and @ctx->al_entry will point to the attribute list
+ * entry of the attribute before which the attribute being searched for would
+ * need to be inserted if such an action were to be desired.
+ *
+ * Thus to insert the not found attribute, one wants to add the attribute to
+ * @ctx->mrec (the base mft record) and if there is not enough space, the
+ * attribute should be placed in a newly allocated extent mft record. The
+ * attribute list entry for the inserted attribute should be inserted in the
+ * attribute list attribute at @ctx->al_entry.
+ *
+ * On actual error, ntfs_external_attr_find() returns -EIO. In this case
+ * @ctx->attr is undefined and in particular do not rely on it not changing.
+ */
+static int ntfs_external_attr_find(const __le32 type,
+ const __le16 *name, const u32 name_len,
+ const u32 ic, const s64 lowest_vcn,
+ const u8 *val, const u32 val_len, struct ntfs_attr_search_ctx *ctx)
+{
+ struct ntfs_inode *base_ni, *ni;
+ struct ntfs_volume *vol;
+ struct attr_list_entry *al_entry, *next_al_entry;
+ u8 *al_start, *al_end;
+ struct attr_record *a;
+ __le16 *al_name;
+ u32 al_name_len;
+ bool is_first_search = false;
+ int err = 0;
+ static const char *es = " Unmount and run chkdsk.";
+
+ ni = ctx->ntfs_ino;
+ base_ni = ctx->base_ntfs_ino;
+ ntfs_debug("Entering for inode 0x%lx, type 0x%x.", ni->mft_no, type);
+ if (!base_ni) {
+ /* First call happens with the base mft record. */
+ base_ni = ctx->base_ntfs_ino = ctx->ntfs_ino;
+ ctx->base_mrec = ctx->mrec;
+ ctx->mapped_base_mrec = ctx->mapped_mrec;
+ }
+ if (ni == base_ni)
+ ctx->base_attr = ctx->attr;
+ if (type == AT_END)
+ goto not_found;
+ vol = base_ni->vol;
+ al_start = base_ni->attr_list;
+ al_end = al_start + base_ni->attr_list_size;
+ if (!ctx->al_entry) {
+ ctx->al_entry = (struct attr_list_entry *)al_start;
+ is_first_search = true;
+ }
+ /*
+ * Iterate over entries in attribute list starting at @ctx->al_entry,
+ * or the entry following that, if @ctx->is_first is 'true'.
+ */
+ if (ctx->is_first) {
+ al_entry = ctx->al_entry;
+ ctx->is_first = false;
+ /*
+ * If an enumeration and the first attribute is higher than
+ * the attribute list itself, need to return the attribute list
+ * attribute.
+ */
+ if ((type == AT_UNUSED) && is_first_search &&
+ le32_to_cpu(al_entry->type) >
+ le32_to_cpu(AT_ATTRIBUTE_LIST))
+ goto find_attr_list_attr;
+ } else {
+ /* Check for small entry */
+ if (((al_end - (u8 *)ctx->al_entry) <
+ (long)offsetof(struct attr_list_entry, name)) ||
+ (le16_to_cpu(ctx->al_entry->length) & 7) ||
+ (le16_to_cpu(ctx->al_entry->length) < offsetof(struct attr_list_entry, name)))
+ goto corrupt;
+
+ al_entry = (struct attr_list_entry *)((u8 *)ctx->al_entry +
+ le16_to_cpu(ctx->al_entry->length));
+
+ if ((u8 *)al_entry == al_end)
+ goto not_found;
+
+ /* Preliminary check for small entry */
+ if ((al_end - (u8 *)al_entry) <
+ (long)offsetof(struct attr_list_entry, name))
+ goto corrupt;
+
+ /*
+ * If this is an enumeration and the attribute list attribute
+ * is the next one in the enumeration sequence, just return the
+ * attribute list attribute from the base mft record as it is
+ * not listed in the attribute list itself.
+ */
+ if ((type == AT_UNUSED) && le32_to_cpu(ctx->al_entry->type) <
+ le32_to_cpu(AT_ATTRIBUTE_LIST) &&
+ le32_to_cpu(al_entry->type) >
+ le32_to_cpu(AT_ATTRIBUTE_LIST)) {
+find_attr_list_attr:
+
+ /* Check for bogus calls. */
+ if (name || name_len || val || val_len || lowest_vcn)
+ return -EINVAL;
+
+ /* We want the base record. */
+ if (ctx->ntfs_ino != base_ni)
+ unmap_mft_record(ctx->ntfs_ino);
+ ctx->ntfs_ino = base_ni;
+ ctx->mapped_mrec = ctx->mapped_base_mrec;
+ ctx->mrec = ctx->base_mrec;
+ ctx->is_first = true;
+
+ /* Sanity checks are performed elsewhere. */
+ ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
+ le16_to_cpu(ctx->mrec->attrs_offset));
+
+ /* Find the attribute list attribute. */
+ err = ntfs_attr_find(AT_ATTRIBUTE_LIST, NULL, 0,
+ IGNORE_CASE, NULL, 0, ctx);
+
+ /*
+ * Setup the search context so the correct
+ * attribute is returned next time round.
+ */
+ ctx->al_entry = al_entry;
+ ctx->is_first = true;
+
+ /* Got it. Done. */
+ if (!err)
+ return 0;
+
+ /* Error! If other than not found return it. */
+ if (err != -ENOENT)
+ return err;
+
+ /* Not found?!? Absurd! */
+ ntfs_error(ctx->ntfs_ino->vol->sb, "Attribute list wasn't found");
+ return -EIO;
+ }
+ }
+ for (;; al_entry = next_al_entry) {
+ /* Out of bounds check. */
+ if ((u8 *)al_entry < base_ni->attr_list ||
+ (u8 *)al_entry > al_end)
+ break; /* Inode is corrupt. */
+ ctx->al_entry = al_entry;
+ /* Catch the end of the attribute list. */
+ if ((u8 *)al_entry == al_end)
+ goto not_found;
+
+ if ((((u8 *)al_entry + offsetof(struct attr_list_entry, name)) > al_end) ||
+ ((u8 *)al_entry + le16_to_cpu(al_entry->length) > al_end) ||
+ (le16_to_cpu(al_entry->length) & 7) ||
+ (le16_to_cpu(al_entry->length) <
+ offsetof(struct attr_list_entry, name_length)) ||
+ (al_entry->name_length && ((u8 *)al_entry + al_entry->name_offset +
+ al_entry->name_length * sizeof(__le16)) > al_end))
+ break; /* corrupt */
+
+ next_al_entry = (struct attr_list_entry *)((u8 *)al_entry +
+ le16_to_cpu(al_entry->length));
+ if (type != AT_UNUSED) {
+ if (le32_to_cpu(al_entry->type) > le32_to_cpu(type))
+ goto not_found;
+ if (type != al_entry->type)
+ continue;
+ }
+ /*
+ * If @name is present, compare the two names. If @name is
+ * missing, assume we want an unnamed attribute.
+ */
+ al_name_len = al_entry->name_length;
+ al_name = (__le16 *)((u8 *)al_entry + al_entry->name_offset);
+
+ /*
+ * If !@type we want the attribute represented by this
+ * attribute list entry.
+ */
+ if (type == AT_UNUSED)
+ goto is_enumeration;
+
+ if (!name || name == AT_UNNAMED) {
+ if (al_name_len)
+ goto not_found;
+ } else if (!ntfs_are_names_equal(al_name, al_name_len, name,
+ name_len, ic, vol->upcase, vol->upcase_len)) {
+ register int rc;
+
+ rc = ntfs_collate_names(name, name_len, al_name,
+ al_name_len, 1, IGNORE_CASE,
+ vol->upcase, vol->upcase_len);
+ /*
+ * If @name collates before al_name, there is no
+ * matching attribute.
+ */
+ if (rc == -1)
+ goto not_found;
+ /* If the strings are not equal, continue search. */
+ if (rc)
+ continue;
+
+ rc = ntfs_collate_names(name, name_len, al_name,
+ al_name_len, 1, CASE_SENSITIVE,
+ vol->upcase, vol->upcase_len);
+ if (rc == -1)
+ goto not_found;
+ if (rc)
+ continue;
+ }
+ /*
+ * The names match or @name not present and attribute is
+ * unnamed. Now check @lowest_vcn. Continue search if the
+ * next attribute list entry still fits @lowest_vcn. Otherwise
+ * we have reached the right one or the search has failed.
+ */
+ if (lowest_vcn && (u8 *)next_al_entry >= al_start &&
+ (u8 *)next_al_entry + 6 < al_end &&
+ (u8 *)next_al_entry + le16_to_cpu(
+ next_al_entry->length) <= al_end &&
+ le64_to_cpu(next_al_entry->lowest_vcn) <=
+ lowest_vcn &&
+ next_al_entry->type == al_entry->type &&
+ next_al_entry->name_length == al_name_len &&
+ ntfs_are_names_equal((__le16 *)((u8 *)
+ next_al_entry +
+ next_al_entry->name_offset),
+ next_al_entry->name_length,
+ al_name, al_name_len, CASE_SENSITIVE,
+ vol->upcase, vol->upcase_len))
+ continue;
+
+is_enumeration:
+ if (MREF_LE(al_entry->mft_reference) == ni->mft_no) {
+ if (MSEQNO_LE(al_entry->mft_reference) != ni->seq_no) {
+ ntfs_error(vol->sb,
+ "Found stale mft reference in attribute list of base inode 0x%lx.%s",
+ base_ni->mft_no, es);
+ err = -EIO;
+ break;
+ }
+ } else { /* Mft references do not match. */
+ /* If there is a mapped record unmap it first. */
+ if (ni != base_ni)
+ unmap_extent_mft_record(ni);
+ /* Do we want the base record back? */
+ if (MREF_LE(al_entry->mft_reference) ==
+ base_ni->mft_no) {
+ ni = ctx->ntfs_ino = base_ni;
+ ctx->mrec = ctx->base_mrec;
+ ctx->mapped_mrec = ctx->mapped_base_mrec;
+ } else {
+ /* We want an extent record. */
+ ctx->mrec = map_extent_mft_record(base_ni,
+ le64_to_cpu(
+ al_entry->mft_reference), &ni);
+ if (IS_ERR(ctx->mrec)) {
+ ntfs_error(vol->sb,
+ "Failed to map extent mft record 0x%lx of base inode 0x%lx.%s",
+ MREF_LE(al_entry->mft_reference),
+ base_ni->mft_no, es);
+ err = PTR_ERR(ctx->mrec);
+ if (err == -ENOENT)
+ err = -EIO;
+ /* Cause @ctx to be sanitized below. */
+ ni = NULL;
+ break;
+ }
+ ctx->ntfs_ino = ni;
+ ctx->mapped_mrec = true;
+
+ }
+ }
+ a = ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
+ le16_to_cpu(ctx->mrec->attrs_offset));
+ /*
+ * ctx->vfs_ino, ctx->mrec, and ctx->attr now point to the
+ * mft record containing the attribute represented by the
+ * current al_entry.
+ */
+ /*
+ * We could call into ntfs_attr_find() to find the right
+ * attribute in this mft record but this would be less
+ * efficient and not quite accurate as ntfs_attr_find() ignores
+ * the attribute instance numbers for example which become
+ * important when one plays with attribute lists. Also,
+ * because a proper match has been found in the attribute list
+ * entry above, the comparison can now be optimized. So it is
+ * worth re-implementing a simplified ntfs_attr_find() here.
+ */
+ /*
+ * Use a manual loop so we can still use break and continue
+ * with the same meanings as above.
+ */
+do_next_attr_loop:
+ if ((u8 *)a < (u8 *)ctx->mrec || (u8 *)a > (u8 *)ctx->mrec +
+ le32_to_cpu(ctx->mrec->bytes_allocated))
+ break;
+ if (a->type == AT_END)
+ continue;
+ if (!a->length)
+ break;
+ if (al_entry->instance != a->instance)
+ goto do_next_attr;
+ /*
+ * If the type and/or the name are mismatched between the
+ * attribute list entry and the attribute record, there is
+ * corruption so we break and return error EIO.
+ */
+ if (al_entry->type != a->type)
+ break;
+ if (!ntfs_are_names_equal((__le16 *)((u8 *)a +
+ le16_to_cpu(a->name_offset)), a->name_length,
+ al_name, al_name_len, CASE_SENSITIVE,
+ vol->upcase, vol->upcase_len))
+ break;
+ ctx->attr = a;
+ /*
+ * If no @val specified or @val specified and it matches, we
+ * have found it!
+ */
+ if ((type == AT_UNUSED) || !val || (!a->non_resident && le32_to_cpu(
+ a->data.resident.value_length) == val_len &&
+ !memcmp((u8 *)a +
+ le16_to_cpu(a->data.resident.value_offset),
+ val, val_len))) {
+ ntfs_debug("Done, found.");
+ return 0;
+ }
+do_next_attr:
+ /* Proceed to the next attribute in the current mft record. */
+ a = (struct attr_record *)((u8 *)a + le32_to_cpu(a->length));
+ goto do_next_attr_loop;
+ }
+
+corrupt:
+ if (ni != base_ni) {
+ if (ni)
+ unmap_extent_mft_record(ni);
+ ctx->ntfs_ino = base_ni;
+ ctx->mrec = ctx->base_mrec;
+ ctx->attr = ctx->base_attr;
+ ctx->mapped_mrec = ctx->mapped_base_mrec;
+ }
+
+ if (!err) {
+ ntfs_error(vol->sb,
+ "Base inode 0x%lx contains corrupt attribute list attribute.%s",
+ base_ni->mft_no, es);
+ err = -EIO;
+ }
+
+ if (err != -ENOMEM)
+ NVolSetErrors(vol);
+ return err;
+not_found:
+ /*
+ * If we were looking for AT_END, we reset the search context @ctx and
+ * use ntfs_attr_find() to seek to the end of the base mft record.
+ */
+ if (type == AT_UNUSED || type == AT_END) {
+ ntfs_attr_reinit_search_ctx(ctx);
+ return ntfs_attr_find(AT_END, name, name_len, ic, val, val_len,
+ ctx);
+ }
+ /*
+ * The attribute was not found. Before we return, we want to ensure
+ * @ctx->mrec and @ctx->attr indicate the position at which the
+ * attribute should be inserted in the base mft record. Since we also
+ * want to preserve @ctx->al_entry we cannot reinitialize the search
+ * context using ntfs_attr_reinit_search_ctx() as this would set
+ * @ctx->al_entry to NULL. Thus we do the necessary bits manually (see
+ * ntfs_attr_init_search_ctx() below). Note, we _only_ preserve
+ * @ctx->al_entry as the remaining fields (base_*) are identical to
+ * their non base_ counterparts and we cannot set @ctx->base_attr
+ * correctly yet as we do not know what @ctx->attr will be set to by
+ * the call to ntfs_attr_find() below.
+ */
+ if (ni != base_ni)
+ unmap_extent_mft_record(ni);
+ ctx->mrec = ctx->base_mrec;
+ ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
+ le16_to_cpu(ctx->mrec->attrs_offset));
+ ctx->is_first = true;
+ ctx->ntfs_ino = base_ni;
+ ctx->base_ntfs_ino = NULL;
+ ctx->base_mrec = NULL;
+ ctx->base_attr = NULL;
+ ctx->mapped_mrec = ctx->mapped_base_mrec;
+ /*
+ * In case there are multiple matches in the base mft record, need to
+ * keep enumerating until we get an attribute not found response (or
+ * another error), otherwise we would keep returning the same attribute
+ * over and over again and all programs using us for enumeration would
+ * lock up in a tight loop.
+ */
+ do {
+ err = ntfs_attr_find(type, name, name_len, ic, val, val_len,
+ ctx);
+ } while (!err);
+ ntfs_debug("Done, not found.");
+ return err;
+}
+
+/**
+ * ntfs_attr_lookup - find an attribute in an ntfs inode
+ * @type: attribute type to find
+ * @name: attribute name to find (optional, i.e. NULL means don't care)
+ * @name_len: attribute name length (only needed if @name present)
+ * @ic: IGNORE_CASE or CASE_SENSITIVE (ignored if @name not present)
+ * @lowest_vcn: lowest vcn to find (optional, non-resident attributes only)
+ * @val: attribute value to find (optional, resident attributes only)
+ * @val_len: attribute value length
+ * @ctx: search context with mft record and attribute to search from
+ *
+ * Find an attribute in an ntfs inode. On first search @ctx->ntfs_ino must
+ * be the base mft record and @ctx must have been obtained from a call to
+ * ntfs_attr_get_search_ctx().
+ *
+ * This function transparently handles attribute lists and @ctx is used to
+ * continue searches where they were left off at.
+ *
+ * After finishing with the attribute/mft record you need to call
+ * ntfs_attr_put_search_ctx() to cleanup the search context (unmapping any
+ * mapped inodes, etc).
+ *
+ * Return 0 if the search was successful and -errno if not.
+ *
+ * When 0, @ctx->attr is the found attribute and it is in mft record
+ * @ctx->mrec. If an attribute list attribute is present, @ctx->al_entry is
+ * the attribute list entry of the found attribute.
+ *
+ * When -ENOENT, @ctx->attr is the attribute which collates just after the
+ * attribute being searched for, i.e. if one wants to add the attribute to the
+ * mft record this is the correct place to insert it into. If an attribute
+ * list attribute is present, @ctx->al_entry is the attribute list entry which
+ * collates just after the attribute list entry of the attribute being searched
+ * for, i.e. if one wants to add the attribute to the mft record this is the
+ * correct place to insert its attribute list entry into.
+ */
+int ntfs_attr_lookup(const __le32 type, const __le16 *name,
+ const u32 name_len, const u32 ic,
+ const s64 lowest_vcn, const u8 *val, const u32 val_len,
+ struct ntfs_attr_search_ctx *ctx)
+{
+ struct ntfs_inode *base_ni;
+
+ ntfs_debug("Entering.");
+ BUG_ON(IS_ERR(ctx->mrec));
+ if (ctx->base_ntfs_ino)
+ base_ni = ctx->base_ntfs_ino;
+ else
+ base_ni = ctx->ntfs_ino;
+ /* Sanity check, just for debugging really. */
+ if (!base_ni || !NInoAttrList(base_ni) || type == AT_ATTRIBUTE_LIST)
+ return ntfs_attr_find(type, name, name_len, ic, val, val_len,
+ ctx);
+ return ntfs_external_attr_find(type, name, name_len, ic, lowest_vcn,
+ val, val_len, ctx);
+}
+
+/**
+ * ntfs_attr_init_search_ctx - initialize an attribute search context
+ * @ctx: attribute search context to initialize
+ * @ni: ntfs inode with which to initialize the search context
+ * @mrec: mft record with which to initialize the search context
+ *
+ * Initialize the attribute search context @ctx with @ni and @mrec.
+ */
+static bool ntfs_attr_init_search_ctx(struct ntfs_attr_search_ctx *ctx,
+ struct ntfs_inode *ni, struct mft_record *mrec)
+{
+ if (!mrec) {
+ mrec = map_mft_record(ni);
+ if (IS_ERR(mrec))
+ return false;
+ ctx->mapped_mrec = true;
+ } else {
+ ctx->mapped_mrec = false;
+ }
+
+ ctx->mrec = mrec;
+ /* Sanity checks are performed elsewhere. */
+ ctx->attr = (struct attr_record *)((u8 *)mrec + le16_to_cpu(mrec->attrs_offset));
+ ctx->is_first = true;
+ ctx->ntfs_ino = ni;
+ ctx->al_entry = NULL;
+ ctx->base_ntfs_ino = NULL;
+ ctx->base_mrec = NULL;
+ ctx->base_attr = NULL;
+ ctx->mapped_base_mrec = false;
+ return true;
+}
+
+/**
+ * ntfs_attr_reinit_search_ctx - reinitialize an attribute search context
+ * @ctx: attribute search context to reinitialize
+ *
+ * Reinitialize the attribute search context @ctx, unmapping an associated
+ * extent mft record if present, and initialize the search context again.
+ *
+ * This is used when a search for a new attribute is being started to reset
+ * the search context to the beginning.
+ */
+void ntfs_attr_reinit_search_ctx(struct ntfs_attr_search_ctx *ctx)
+{
+ bool mapped_mrec;
+
+ if (likely(!ctx->base_ntfs_ino)) {
+ /* No attribute list. */
+ ctx->is_first = true;
+ /* Sanity checks are performed elsewhere. */
+ ctx->attr = (struct attr_record *)((u8 *)ctx->mrec +
+ le16_to_cpu(ctx->mrec->attrs_offset));
+ /*
+ * This needs resetting due to ntfs_external_attr_find() which
+ * can leave it set despite having zeroed ctx->base_ntfs_ino.
+ */
+ ctx->al_entry = NULL;
+ return;
+ } /* Attribute list. */
+ if (ctx->ntfs_ino != ctx->base_ntfs_ino && ctx->ntfs_ino)
+ unmap_extent_mft_record(ctx->ntfs_ino);
+
+ mapped_mrec = ctx->mapped_base_mrec;
+ ntfs_attr_init_search_ctx(ctx, ctx->base_ntfs_ino, ctx->base_mrec);
+ ctx->mapped_mrec = mapped_mrec;
+}
+
+/**
+ * ntfs_attr_get_search_ctx - allocate/initialize a new attribute search context
+ * @ni: ntfs inode with which to initialize the search context
+ * @mrec: mft record with which to initialize the search context
+ *
+ * Allocate a new attribute search context, initialize it with @ni and @mrec,
+ * and return it. Return NULL if allocation failed.
+ */
+struct ntfs_attr_search_ctx *ntfs_attr_get_search_ctx(struct ntfs_inode *ni,
+ struct mft_record *mrec)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ bool init;
+
+ ctx = kmem_cache_alloc(ntfs_attr_ctx_cache, GFP_NOFS);
+ if (ctx) {
+ init = ntfs_attr_init_search_ctx(ctx, ni, mrec);
+ if (init == false) {
+ kmem_cache_free(ntfs_attr_ctx_cache, ctx);
+ ctx = NULL;
+ }
+ }
+
+ return ctx;
+}
+
+/**
+ * ntfs_attr_put_search_ctx - release an attribute search context
+ * @ctx: attribute search context to free
+ *
+ * Release the attribute search context @ctx, unmapping an associated extent
+ * mft record if present.
+ */
+void ntfs_attr_put_search_ctx(struct ntfs_attr_search_ctx *ctx)
+{
+ if (ctx->mapped_mrec)
+ unmap_mft_record(ctx->ntfs_ino);
+
+ if (ctx->mapped_base_mrec && ctx->base_ntfs_ino &&
+ ctx->ntfs_ino != ctx->base_ntfs_ino)
+ unmap_extent_mft_record(ctx->base_ntfs_ino);
+ kmem_cache_free(ntfs_attr_ctx_cache, ctx);
+}
+
+/**
+ * ntfs_attr_find_in_attrdef - find an attribute in the $AttrDef system file
+ * @vol: ntfs volume to which the attribute belongs
+ * @type: attribute type which to find
+ *
+ * Search for the attribute definition record corresponding to the attribute
+ * @type in the $AttrDef system file.
+ *
+ * Return the attribute type definition record if found and NULL if not found.
+ */
+static struct attr_def *ntfs_attr_find_in_attrdef(const struct ntfs_volume *vol,
+ const __le32 type)
+{
+ struct attr_def *ad;
+
+ BUG_ON(!vol->attrdef);
+ BUG_ON(!type);
+ for (ad = vol->attrdef; (u8 *)ad - (u8 *)vol->attrdef <
+ vol->attrdef_size && ad->type; ++ad) {
+ /* We have not found it yet, carry on searching. */
+ if (likely(le32_to_cpu(ad->type) < le32_to_cpu(type)))
+ continue;
+ /* We found the attribute; return it. */
+ if (likely(ad->type == type))
+ return ad;
+ /* We have gone too far already. No point in continuing. */
+ break;
+ }
+ /* Attribute not found. */
+ ntfs_debug("Attribute type 0x%x not found in $AttrDef.",
+ le32_to_cpu(type));
+ return NULL;
+}
+
+/**
+ * ntfs_attr_size_bounds_check - check a size of an attribute type for validity
+ * @vol: ntfs volume to which the attribute belongs
+ * @type: attribute type which to check
+ * @size: size which to check
+ *
+ * Check whether the @size in bytes is valid for an attribute of @type on the
+ * ntfs volume @vol. This information is obtained from $AttrDef system file.
+ */
+int ntfs_attr_size_bounds_check(const struct ntfs_volume *vol, const __le32 type,
+ const s64 size)
+{
+ struct attr_def *ad;
+
+ BUG_ON(size < 0);
+ /*
+ * $ATTRIBUTE_LIST has a maximum size of 256kiB, but this is not
+ * listed in $AttrDef.
+ */
+ if (unlikely(type == AT_ATTRIBUTE_LIST && size > 256 * 1024))
+ return -ERANGE;
+ /* Get the $AttrDef entry for the attribute @type. */
+ ad = ntfs_attr_find_in_attrdef(vol, type);
+ if (unlikely(!ad))
+ return -ENOENT;
+ /* Do the bounds check. */
+ if (((le64_to_cpu(ad->min_size) > 0) &&
+ size < le64_to_cpu(ad->min_size)) ||
+ ((le64_to_cpu(ad->max_size) > 0) && size >
+ le64_to_cpu(ad->max_size)))
+ return -ERANGE;
+ return 0;
+}
+
+/**
+ * ntfs_attr_can_be_non_resident - check if an attribute can be non-resident
+ * @vol: ntfs volume to which the attribute belongs
+ * @type: attribute type which to check
+ *
+ * Check whether the attribute of @type on the ntfs volume @vol is allowed to
+ * be non-resident. This information is obtained from $AttrDef system file.
+ */
+static int ntfs_attr_can_be_non_resident(const struct ntfs_volume *vol,
+ const __le32 type)
+{
+ struct attr_def *ad;
+
+ /* Find the attribute definition record in $AttrDef. */
+ ad = ntfs_attr_find_in_attrdef(vol, type);
+ if (unlikely(!ad))
+ return -ENOENT;
+ /* Check the flags and return the result. */
+ if (ad->flags & ATTR_DEF_RESIDENT)
+ return -EPERM;
+ return 0;
+}
+
+/**
+ * ntfs_attr_can_be_resident - check if an attribute can be resident
+ * @vol: ntfs volume to which the attribute belongs
+ * @type: attribute type which to check
+ *
+ * Check whether the attribute of @type on the ntfs volume @vol is allowed to
+ * be resident. This information is derived from our ntfs knowledge and may
+ * not be completely accurate, especially when user defined attributes are
+ * present. Basically we allow everything to be resident except for index
+ * allocation and $EA attributes.
+ *
+ * Return 0 if the attribute is allowed to be non-resident and -EPERM if not.
+ *
+ * Warning: In the system file $MFT the attribute $Bitmap must be non-resident
+ * otherwise windows will not boot (blue screen of death)! We cannot
+ * check for this here as we do not know which inode's $Bitmap is
+ * being asked about so the caller needs to special case this.
+ */
+int ntfs_attr_can_be_resident(const struct ntfs_volume *vol, const __le32 type)
+{
+ if (type == AT_INDEX_ALLOCATION)
+ return -EPERM;
+ return 0;
+}
+
+/**
+ * ntfs_attr_record_resize - resize an attribute record
+ * @m: mft record containing attribute record
+ * @a: attribute record to resize
+ * @new_size: new size in bytes to which to resize the attribute record @a
+ *
+ * Resize the attribute record @a, i.e. the resident part of the attribute, in
+ * the mft record @m to @new_size bytes.
+ */
+int ntfs_attr_record_resize(struct mft_record *m, struct attr_record *a, u32 new_size)
+{
+ u32 old_size, alloc_size, attr_size;
+
+ old_size = le32_to_cpu(m->bytes_in_use);
+ alloc_size = le32_to_cpu(m->bytes_allocated);
+ attr_size = le32_to_cpu(a->length);
+
+ ntfs_debug("Sizes: old=%u alloc=%u attr=%u new=%u\n",
+ (unsigned int)old_size, (unsigned int)alloc_size,
+ (unsigned int)attr_size, (unsigned int)new_size);
+
+ /* Align to 8 bytes if it is not already done. */
+ if (new_size & 7)
+ new_size = (new_size + 7) & ~7;
+ /* If the actual attribute length has changed, move things around. */
+ if (new_size != attr_size) {
+ u32 new_muse = le32_to_cpu(m->bytes_in_use) -
+ attr_size + new_size;
+ /* Not enough space in this mft record. */
+ if (new_muse > le32_to_cpu(m->bytes_allocated))
+ return -ENOSPC;
+
+ if (a->type == AT_INDEX_ROOT && new_size > attr_size &&
+ new_muse + 120 > alloc_size && old_size + 120 <= alloc_size) {
+ ntfs_debug("Too big struct index_root (%u > %u)\n",
+ new_muse, alloc_size);
+ return -ENOSPC;
+ }
+
+ /* Move attributes following @a to their new location. */
+ memmove((u8 *)a + new_size, (u8 *)a + le32_to_cpu(a->length),
+ le32_to_cpu(m->bytes_in_use) - ((u8 *)a -
+ (u8 *)m) - attr_size);
+ /* Adjust @m to reflect the change in used space. */
+ m->bytes_in_use = cpu_to_le32(new_muse);
+ /* Adjust @a to reflect the new size. */
+ if (new_size >= offsetof(struct attr_record, length) + sizeof(a->length))
+ a->length = cpu_to_le32(new_size);
+ }
+ return 0;
+}
+
+/**
+ * ntfs_resident_attr_value_resize - resize the value of a resident attribute
+ * @m: mft record containing attribute record
+ * @a: attribute record whose value to resize
+ * @new_size: new size in bytes to which to resize the attribute value of @a
+ *
+ * Resize the value of the attribute @a in the mft record @m to @new_size bytes.
+ * If the value is made bigger, the newly allocated space is cleared.
+ */
+int ntfs_resident_attr_value_resize(struct mft_record *m, struct attr_record *a,
+ const u32 new_size)
+{
+ u32 old_size;
+
+ /* Resize the resident part of the attribute record. */
+ if (ntfs_attr_record_resize(m, a,
+ le16_to_cpu(a->data.resident.value_offset) + new_size))
+ return -ENOSPC;
+ /*
+ * The resize succeeded! If we made the attribute value bigger, clear
+ * the area between the old size and @new_size.
+ */
+ old_size = le32_to_cpu(a->data.resident.value_length);
+ if (new_size > old_size)
+ memset((u8 *)a + le16_to_cpu(a->data.resident.value_offset) +
+ old_size, 0, new_size - old_size);
+ /* Finally update the length of the attribute value. */
+ a->data.resident.value_length = cpu_to_le32(new_size);
+ return 0;
+}
+
+/**
+ * ntfs_attr_make_non_resident - convert a resident to a non-resident attribute
+ * @ni: ntfs inode describing the attribute to convert
+ * @data_size: size of the resident data to copy to the non-resident attribute
+ *
+ * Convert the resident ntfs attribute described by the ntfs inode @ni to a
+ * non-resident one.
+ *
+ * @data_size must be equal to the attribute value size. This is needed since
+ * we need to know the size before we can map the mft record and our callers
+ * always know it. The reason we cannot simply read the size from the vfs
+ * inode i_size is that this is not necessarily uptodate. This happens when
+ * ntfs_attr_make_non_resident() is called in the ->truncate call path(s).
+ */
+int ntfs_attr_make_non_resident(struct ntfs_inode *ni, const u32 data_size)
+{
+ s64 new_size;
+ struct inode *vi = VFS_I(ni);
+ struct ntfs_volume *vol = ni->vol;
+ struct ntfs_inode *base_ni;
+ struct mft_record *m;
+ struct attr_record *a;
+ struct ntfs_attr_search_ctx *ctx;
+ struct folio *folio;
+ struct runlist_element *rl;
+ u8 *kaddr;
+ unsigned long flags;
+ int mp_size, mp_ofs, name_ofs, arec_size, err, err2;
+ u32 attr_size;
+ u8 old_res_attr_flags;
+
+ if (NInoNonResident(ni)) {
+ ntfs_warning(vol->sb,
+ "Trying to make non-resident attribute non-resident. Aborting...\n");
+ return -EINVAL;
+ }
+
+ /* Check that the attribute is allowed to be non-resident. */
+ err = ntfs_attr_can_be_non_resident(vol, ni->type);
+ if (unlikely(err)) {
+ if (err == -EPERM)
+ ntfs_debug("Attribute is not allowed to be non-resident.");
+ else
+ ntfs_debug("Attribute not defined on the NTFS volume!");
+ return err;
+ }
+
+ BUG_ON(NInoEncrypted(ni));
+
+ 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);
+ 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;
+ }
+ m = ctx->mrec;
+ a = ctx->attr;
+
+ /*
+ * The size needs to be aligned to a cluster boundary for allocation
+ * purposes.
+ */
+ new_size = (data_size + vol->cluster_size - 1) &
+ ~(vol->cluster_size - 1);
+ if (new_size > 0) {
+ if ((a->flags & ATTR_COMPRESSION_MASK) == ATTR_IS_COMPRESSED) {
+ /* must allocate full compression blocks */
+ new_size =
+ ((new_size - 1) |
+ ((1L << (STANDARD_COMPRESSION_UNIT +
+ vol->cluster_size_bits)) - 1)) + 1;
+ }
+
+ /*
+ * Will need folio later and since folio lock nests
+ * outside all ntfs locks, we need to get the folio now.
+ */
+ folio = __filemap_get_folio(vi->i_mapping, 0,
+ FGP_CREAT | FGP_LOCK,
+ mapping_gfp_mask(vi->i_mapping));
+ if (IS_ERR(folio)) {
+ err = -ENOMEM;
+ goto err_out;
+ }
+
+ /* Start by allocating clusters to hold the attribute value. */
+ rl = ntfs_cluster_alloc(vol, 0, new_size >>
+ vol->cluster_size_bits, -1, DATA_ZONE, true,
+ false, false);
+ if (IS_ERR(rl)) {
+ err = PTR_ERR(rl);
+ ntfs_debug("Failed to allocate cluster%s, error code %i.",
+ (new_size >> vol->cluster_size_bits) > 1 ? "s" : "",
+ err);
+ goto folio_err_out;
+ }
+ } else {
+ rl = NULL;
+ folio = NULL;
+ }
+
+ down_write(&ni->runlist.lock);
+ /* Determine the size of the mapping pairs array. */
+ mp_size = ntfs_get_size_for_mapping_pairs(vol, rl, 0, -1, -1);
+ if (unlikely(mp_size < 0)) {
+ err = mp_size;
+ ntfs_debug("Failed to get size for mapping pairs array, error code %i.\n", err);
+ goto rl_err_out;
+ }
+
+ if (NInoNonResident(ni) || a->non_resident) {
+ err = -EIO;
+ goto rl_err_out;
+ }
+
+ /*
+ * Calculate new offsets for the name and the mapping pairs array.
+ */
+ if (NInoSparse(ni) || NInoCompressed(ni))
+ name_ofs = (offsetof(struct attr_record,
+ data.non_resident.compressed_size) +
+ sizeof(a->data.non_resident.compressed_size) +
+ 7) & ~7;
+ else
+ name_ofs = (offsetof(struct attr_record,
+ data.non_resident.compressed_size) + 7) & ~7;
+ mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
+ /*
+ * Determine the size of the resident part of the now non-resident
+ * attribute record.
+ */
+ arec_size = (mp_ofs + mp_size + 7) & ~7;
+ /*
+ * If the folio is not uptodate bring it uptodate by copying from the
+ * attribute value.
+ */
+ attr_size = le32_to_cpu(a->data.resident.value_length);
+ BUG_ON(attr_size != data_size);
+ if (folio && !folio_test_uptodate(folio)) {
+ kaddr = kmap_local_folio(folio, 0);
+ memcpy(kaddr, (u8 *)a +
+ le16_to_cpu(a->data.resident.value_offset),
+ attr_size);
+ memset(kaddr + attr_size, 0, PAGE_SIZE - attr_size);
+ kunmap_local(kaddr);
+ flush_dcache_folio(folio);
+ folio_mark_uptodate(folio);
+ }
+
+ /* Backup the attribute flag. */
+ old_res_attr_flags = a->data.resident.flags;
+ /* Resize the resident part of the attribute record. */
+ err = ntfs_attr_record_resize(m, a, arec_size);
+ if (unlikely(err))
+ goto rl_err_out;
+
+ /*
+ * Convert the resident part of the attribute record to describe a
+ * non-resident attribute.
+ */
+ a->non_resident = 1;
+ /* Move the attribute name if it exists and update the offset. */
+ if (a->name_length)
+ memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
+ a->name_length * sizeof(__le16));
+ a->name_offset = cpu_to_le16(name_ofs);
+ /* Setup the fields specific to non-resident attributes. */
+ a->data.non_resident.lowest_vcn = 0;
+ a->data.non_resident.highest_vcn = cpu_to_le64((new_size - 1) >>
+ vol->cluster_size_bits);
+ a->data.non_resident.mapping_pairs_offset = cpu_to_le16(mp_ofs);
+ memset(&a->data.non_resident.reserved, 0,
+ sizeof(a->data.non_resident.reserved));
+ a->data.non_resident.allocated_size = cpu_to_le64(new_size);
+ a->data.non_resident.data_size =
+ a->data.non_resident.initialized_size =
+ cpu_to_le64(attr_size);
+ if (NInoSparse(ni) || NInoCompressed(ni)) {
+ a->data.non_resident.compression_unit = 0;
+ if (NInoCompressed(ni) || vol->major_ver < 3)
+ a->data.non_resident.compression_unit = 4;
+ a->data.non_resident.compressed_size =
+ a->data.non_resident.allocated_size;
+ } else
+ a->data.non_resident.compression_unit = 0;
+ /* Generate the mapping pairs array into the attribute record. */
+ err = ntfs_mapping_pairs_build(vol, (u8 *)a + mp_ofs,
+ arec_size - mp_ofs, rl, 0, -1, NULL, NULL, NULL);
+ if (unlikely(err)) {
+ ntfs_error(vol->sb, "Failed to build mapping pairs, error code %i.",
+ err);
+ goto undo_err_out;
+ }
+
+ /* Setup the in-memory attribute structure to be non-resident. */
+ ni->runlist.rl = rl;
+ if (rl) {
+ for (ni->runlist.count = 1; rl->length != 0; rl++)
+ ni->runlist.count++;
+ } else
+ ni->runlist.count = 0;
+ write_lock_irqsave(&ni->size_lock, flags);
+ ni->allocated_size = new_size;
+ if (NInoSparse(ni) || NInoCompressed(ni)) {
+ ni->itype.compressed.size = ni->allocated_size;
+ if (a->data.non_resident.compression_unit) {
+ ni->itype.compressed.block_size = 1U <<
+ (a->data.non_resident.compression_unit +
+ vol->cluster_size_bits);
+ ni->itype.compressed.block_size_bits =
+ ffs(ni->itype.compressed.block_size) -
+ 1;
+ ni->itype.compressed.block_clusters = 1U <<
+ a->data.non_resident.compression_unit;
+ } else {
+ ni->itype.compressed.block_size = 0;
+ ni->itype.compressed.block_size_bits = 0;
+ ni->itype.compressed.block_clusters = 0;
+ }
+ vi->i_blocks = ni->itype.compressed.size >> 9;
+ } else
+ vi->i_blocks = ni->allocated_size >> 9;
+ write_unlock_irqrestore(&ni->size_lock, flags);
+ /*
+ * This needs to be last since the address space operations ->read_folio
+ * and ->writepage can run concurrently with us as they are not
+ * serialized on i_mutex. Note, we are not allowed to fail once we flip
+ * this switch, which is another reason to do this last.
+ */
+ NInoSetNonResident(ni);
+ NInoSetFullyMapped(ni);
+ /* Mark the mft record dirty, so it gets written back. */
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ ntfs_attr_put_search_ctx(ctx);
+ unmap_mft_record(base_ni);
+ up_write(&ni->runlist.lock);
+ if (folio) {
+ iomap_dirty_folio(vi->i_mapping, folio);
+ folio_unlock(folio);
+ folio_put(folio);
+ }
+ ntfs_debug("Done.");
+ return 0;
+undo_err_out:
+ /* Convert the attribute back into a resident attribute. */
+ a->non_resident = 0;
+ /* Move the attribute name if it exists and update the offset. */
+ name_ofs = (offsetof(struct attr_record, data.resident.reserved) +
+ sizeof(a->data.resident.reserved) + 7) & ~7;
+ if (a->name_length)
+ memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
+ a->name_length * sizeof(__le16));
+ mp_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
+ a->name_offset = cpu_to_le16(name_ofs);
+ arec_size = (mp_ofs + attr_size + 7) & ~7;
+ /* Resize the resident part of the attribute record. */
+ err2 = ntfs_attr_record_resize(m, a, arec_size);
+ if (unlikely(err2)) {
+ /*
+ * This cannot happen (well if memory corruption is at work it
+ * could happen in theory), but deal with it as well as we can.
+ * If the old size is too small, truncate the attribute,
+ * otherwise simply give it a larger allocated size.
+ */
+ arec_size = le32_to_cpu(a->length);
+ if ((mp_ofs + attr_size) > arec_size) {
+ err2 = attr_size;
+ attr_size = arec_size - mp_ofs;
+ ntfs_error(vol->sb,
+ "Failed to undo partial resident to non-resident attribute conversion. Truncating inode 0x%lx, attribute type 0x%x from %i bytes to %i bytes to maintain metadata consistency. THIS MEANS YOU ARE LOSING %i BYTES DATA FROM THIS %s.",
+ vi->i_ino,
+ (unsigned int)le32_to_cpu(ni->type),
+ err2, attr_size, err2 - attr_size,
+ ((ni->type == AT_DATA) &&
+ !ni->name_len) ? "FILE" : "ATTRIBUTE");
+ write_lock_irqsave(&ni->size_lock, flags);
+ ni->initialized_size = attr_size;
+ i_size_write(vi, attr_size);
+ write_unlock_irqrestore(&ni->size_lock, flags);
+ }
+ }
+ /* Setup the fields specific to resident attributes. */
+ a->data.resident.value_length = cpu_to_le32(attr_size);
+ a->data.resident.value_offset = cpu_to_le16(mp_ofs);
+ a->data.resident.flags = old_res_attr_flags;
+ memset(&a->data.resident.reserved, 0,
+ sizeof(a->data.resident.reserved));
+ /* Copy the data from folio back to the attribute value. */
+ if (folio)
+ memcpy_from_folio((u8 *)a + mp_ofs, folio, 0, attr_size);
+ /* Setup the allocated size in the ntfs inode in case it changed. */
+ write_lock_irqsave(&ni->size_lock, flags);
+ ni->allocated_size = arec_size - mp_ofs;
+ write_unlock_irqrestore(&ni->size_lock, flags);
+ /* Mark the mft record dirty, so it gets written back. */
+ mark_mft_record_dirty(ctx->ntfs_ino);
+rl_err_out:
+ up_write(&ni->runlist.lock);
+ if (rl) {
+ if (ntfs_cluster_free_from_rl(vol, rl) < 0) {
+ ntfs_error(vol->sb,
+ "Failed to release allocated cluster(s) in error code path. Run chkdsk to recover the lost cluster(s).");
+ NVolSetErrors(vol);
+ }
+ ntfs_free(rl);
+folio_err_out:
+ folio_unlock(folio);
+ folio_put(folio);
+ }
+err_out:
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+ if (m)
+ unmap_mft_record(base_ni);
+ ni->runlist.rl = NULL;
+
+ if (err == -EINVAL)
+ err = -EIO;
+ return err;
+}
+
+/**
+ * ntfs_attr_set - fill (a part of) an attribute with a byte
+ * @ni: ntfs inode describing the attribute to fill
+ * @ofs: offset inside the attribute at which to start to fill
+ * @cnt: number of bytes to fill
+ * @val: the unsigned 8-bit value with which to fill the attribute
+ *
+ * Fill @cnt bytes of the attribute described by the ntfs inode @ni starting at
+ * byte offset @ofs inside the attribute with the constant byte @val.
+ *
+ * This function is effectively like memset() applied to an ntfs attribute.
+ * Note thie function actually only operates on the page cache pages belonging
+ * to the ntfs attribute and it marks them dirty after doing the memset().
+ * Thus it relies on the vm dirty page write code paths to cause the modified
+ * pages to be written to the mft record/disk.
+ */
+int ntfs_attr_set(struct ntfs_inode *ni, s64 ofs, s64 cnt, const u8 val)
+{
+ struct address_space *mapping = VFS_I(ni)->i_mapping;
+ struct folio *folio;
+ pgoff_t index;
+ u8 *addr;
+ unsigned long offset;
+ size_t attr_len;
+ int ret = 0;
+
+ index = ofs >> PAGE_SHIFT;
+ while (cnt) {
+ folio = ntfs_read_mapping_folio(mapping, index);
+ if (IS_ERR(folio)) {
+ ret = PTR_ERR(folio);
+ ntfs_error(VFS_I(ni)->i_sb, "Failed to read a page %lu for attr %#x: %ld",
+ index, ni->type, PTR_ERR(folio));
+ break;
+ }
+
+ offset = offset_in_folio(folio, ofs);
+ attr_len = min_t(size_t, (size_t)cnt, folio_size(folio) - offset);
+
+ folio_lock(folio);
+ addr = kmap_local_folio(folio, offset);
+ memset(addr, val, attr_len);
+ kunmap_local(addr);
+
+ flush_dcache_folio(folio);
+ folio_mark_dirty(folio);
+ folio_unlock(folio);
+ folio_put(folio);
+
+ ofs += attr_len;
+ cnt -= attr_len;
+ index++;
+ cond_resched();
+ }
+
+ return ret;
+}
+
+int ntfs_attr_set_initialized_size(struct ntfs_inode *ni, loff_t new_size)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ int err = 0;
+
+ if (!NInoNonResident(ni))
+ return -EINVAL;
+
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx)
+ return -ENOMEM;
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx);
+ if (err)
+ goto out_ctx;
+
+ ctx->attr->data.non_resident.initialized_size = cpu_to_le64(new_size);
+ ni->initialized_size = new_size;
+ mark_mft_record_dirty(ctx->ntfs_ino);
+out_ctx:
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+/**
+ * ntfs_make_room_for_attr - make room for an attribute inside an mft record
+ * @m: mft record
+ * @pos: position at which to make space
+ * @size: byte size to make available at this position
+ *
+ * @pos points to the attribute in front of which we want to make space.
+ */
+static int ntfs_make_room_for_attr(struct mft_record *m, u8 *pos, u32 size)
+{
+ u32 biu;
+
+ ntfs_debug("Entering for pos 0x%x, size %u.\n",
+ (int)(pos - (u8 *)m), (unsigned int) size);
+
+ /* Make size 8-byte alignment. */
+ size = (size + 7) & ~7;
+
+ /* Rigorous consistency checks. */
+ if (!m || !pos || pos < (u8 *)m) {
+ pr_err("%s: pos=%p m=%p", __func__, pos, m);
+ return -EINVAL;
+ }
+
+ /* The -8 is for the attribute terminator. */
+ if (pos - (u8 *)m > (int)le32_to_cpu(m->bytes_in_use) - 8)
+ return -EINVAL;
+ /* Nothing to do. */
+ if (!size)
+ return 0;
+
+ biu = le32_to_cpu(m->bytes_in_use);
+ /* Do we have enough space? */
+ if (biu + size > le32_to_cpu(m->bytes_allocated) ||
+ pos + size > (u8 *)m + le32_to_cpu(m->bytes_allocated)) {
+ ntfs_debug("No enough space in the MFT record\n");
+ return -ENOSPC;
+ }
+ /* Move everything after pos to pos + size. */
+ memmove(pos + size, pos, biu - (pos - (u8 *)m));
+ /* Update mft record. */
+ m->bytes_in_use = cpu_to_le32(biu + size);
+ return 0;
+}
+
+/**
+ * ntfs_resident_attr_record_add - add resident attribute to inode
+ * @ni: opened ntfs inode to which MFT record add attribute
+ * @type: type of the new attribute
+ * @name: name of the new attribute
+ * @name_len: name length of the new attribute
+ * @val: value of the new attribute
+ * @size: size of new attribute (length of @val, if @val != NULL)
+ * @flags: flags of the new attribute
+ */
+int ntfs_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
+ __le16 *name, u8 name_len, u8 *val, u32 size,
+ __le16 flags)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ u32 length;
+ struct attr_record *a;
+ struct mft_record *m;
+ int err, offset;
+ struct ntfs_inode *base_ni;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x, flags 0x%x.\n",
+ (long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
+ (unsigned int) le16_to_cpu(flags));
+
+ if (!ni || (!name && name_len))
+ return -EINVAL;
+
+ err = ntfs_attr_can_be_resident(ni->vol, type);
+ if (err) {
+ if (err == -EPERM)
+ ntfs_debug("Attribute can't be resident.\n");
+ else
+ ntfs_debug("ntfs_attr_can_be_resident failed.\n");
+ return err;
+ }
+
+ /* Locate place where record should be. */
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ ntfs_error(ni->vol->sb, "%s: Failed to get search context",
+ __func__);
+ return -ENOMEM;
+ }
+ /*
+ * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
+ * attribute in @ni->mrec, not any extent inode in case if @ni is base
+ * file record.
+ */
+ err = ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, val, size, ctx);
+ if (!err) {
+ err = -EEXIST;
+ ntfs_debug("Attribute already present.\n");
+ goto put_err_out;
+ }
+ if (err != -ENOENT) {
+ err = -EIO;
+ goto put_err_out;
+ }
+ a = ctx->attr;
+ m = ctx->mrec;
+
+ /* Make room for attribute. */
+ length = offsetof(struct attr_record, data.resident.reserved) +
+ sizeof(a->data.resident.reserved) +
+ ((name_len * sizeof(__le16) + 7) & ~7) +
+ ((size + 7) & ~7);
+ err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
+ if (err) {
+ ntfs_debug("Failed to make room for attribute.\n");
+ goto put_err_out;
+ }
+
+ /* Setup record fields. */
+ offset = ((u8 *)a - (u8 *)m);
+ a->type = type;
+ a->length = cpu_to_le32(length);
+ a->non_resident = 0;
+ a->name_length = name_len;
+ a->name_offset =
+ name_len ? cpu_to_le16((offsetof(struct attr_record, data.resident.reserved) +
+ sizeof(a->data.resident.reserved))) : cpu_to_le16(0);
+
+ a->flags = flags;
+ a->instance = m->next_attr_instance;
+ a->data.resident.value_length = cpu_to_le32(size);
+ a->data.resident.value_offset = cpu_to_le16(length - ((size + 7) & ~7));
+ if (val)
+ memcpy((u8 *)a + le16_to_cpu(a->data.resident.value_offset), val, size);
+ else
+ memset((u8 *)a + le16_to_cpu(a->data.resident.value_offset), 0, size);
+ if (type == AT_FILE_NAME)
+ a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
+ else
+ a->data.resident.flags = 0;
+ if (name_len)
+ memcpy((u8 *)a + le16_to_cpu(a->name_offset),
+ name, sizeof(__le16) * name_len);
+ m->next_attr_instance =
+ cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
+ if (ni->nr_extents == -1)
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+ if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
+ err = ntfs_attrlist_entry_add(ni, a);
+ if (err) {
+ ntfs_attr_record_resize(m, a, 0);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ ntfs_debug("Failed add attribute entry to ATTRIBUTE_LIST.\n");
+ goto put_err_out;
+ }
+ }
+ mark_mft_record_dirty(ni);
+ ntfs_attr_put_search_ctx(ctx);
+ return offset;
+put_err_out:
+ ntfs_attr_put_search_ctx(ctx);
+ return -EIO;
+}
+
+/**
+ * ntfs_non_resident_attr_record_add - add extent of non-resident attribute
+ * @ni: opened ntfs inode to which MFT record add attribute
+ * @type: type of the new attribute extent
+ * @name: name of the new attribute extent
+ * @name_len: name length of the new attribute extent
+ * @lowest_vcn: lowest vcn of the new attribute extent
+ * @dataruns_size: dataruns size of the new attribute extent
+ * @flags: flags of the new attribute extent
+ */
+static int ntfs_non_resident_attr_record_add(struct ntfs_inode *ni, __le32 type,
+ __le16 *name, u8 name_len, s64 lowest_vcn, int dataruns_size,
+ __le16 flags)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ u32 length;
+ struct attr_record *a;
+ struct mft_record *m;
+ struct ntfs_inode *base_ni;
+ int err, offset;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld, dataruns_size %d, flags 0x%x.\n",
+ (long long) ni->mft_no, (unsigned int) le32_to_cpu(type),
+ (long long) lowest_vcn, dataruns_size,
+ (unsigned int) le16_to_cpu(flags));
+
+ if (!ni || dataruns_size <= 0 || (!name && name_len))
+ return -EINVAL;
+
+ err = ntfs_attr_can_be_non_resident(ni->vol, type);
+ if (err) {
+ if (err == -EPERM)
+ pr_err("Attribute can't be non resident");
+ else
+ pr_err("ntfs_attr_can_be_non_resident failed");
+ return err;
+ }
+
+ /* Locate place where record should be. */
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ pr_err("%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+ /*
+ * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
+ * attribute in @ni->mrec, not any extent inode in case if @ni is base
+ * file record.
+ */
+ err = ntfs_attr_find(type, name, name_len, CASE_SENSITIVE, NULL, 0, ctx);
+ if (!err) {
+ err = -EEXIST;
+ pr_err("Attribute 0x%x already present", type);
+ goto put_err_out;
+ }
+ if (err != -ENOENT) {
+ pr_err("ntfs_attr_find failed");
+ err = -EIO;
+ goto put_err_out;
+ }
+ a = ctx->attr;
+ m = ctx->mrec;
+
+ /* Make room for attribute. */
+ dataruns_size = (dataruns_size + 7) & ~7;
+ length = offsetof(struct attr_record, data.non_resident.compressed_size) +
+ ((sizeof(__le16) * name_len + 7) & ~7) + dataruns_size +
+ ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
+ sizeof(a->data.non_resident.compressed_size) : 0);
+ err = ntfs_make_room_for_attr(ctx->mrec, (u8 *) ctx->attr, length);
+ if (err) {
+ pr_err("Failed to make room for attribute");
+ goto put_err_out;
+ }
+
+ /* Setup record fields. */
+ a->type = type;
+ a->length = cpu_to_le32(length);
+ a->non_resident = 1;
+ a->name_length = name_len;
+ a->name_offset = cpu_to_le16(offsetof(struct attr_record,
+ data.non_resident.compressed_size) +
+ ((flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE)) ?
+ sizeof(a->data.non_resident.compressed_size) : 0));
+ a->flags = flags;
+ a->instance = m->next_attr_instance;
+ a->data.non_resident.lowest_vcn = cpu_to_le64(lowest_vcn);
+ a->data.non_resident.mapping_pairs_offset = cpu_to_le16(length - dataruns_size);
+ a->data.non_resident.compression_unit =
+ (flags & ATTR_IS_COMPRESSED) ? STANDARD_COMPRESSION_UNIT : 0;
+ /* If @lowest_vcn == 0, than setup empty attribute. */
+ if (!lowest_vcn) {
+ a->data.non_resident.highest_vcn = cpu_to_le64(-1);
+ a->data.non_resident.allocated_size = 0;
+ a->data.non_resident.data_size = 0;
+ a->data.non_resident.initialized_size = 0;
+ /* Set empty mapping pairs. */
+ *((u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset)) = 0;
+ }
+ if (name_len)
+ memcpy((u8 *)a + le16_to_cpu(a->name_offset),
+ name, sizeof(__le16) * name_len);
+ m->next_attr_instance =
+ cpu_to_le16((le16_to_cpu(m->next_attr_instance) + 1) & 0xffff);
+ if (ni->nr_extents == -1)
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+ if (type != AT_ATTRIBUTE_LIST && NInoAttrList(base_ni)) {
+ err = ntfs_attrlist_entry_add(ni, a);
+ if (err) {
+ pr_err("Failed add attr entry to attrlist");
+ ntfs_attr_record_resize(m, a, 0);
+ goto put_err_out;
+ }
+ }
+ mark_mft_record_dirty(ni);
+ /*
+ * Locate offset from start of the MFT record where new attribute is
+ * placed. We need relookup it, because record maybe moved during
+ * update of attribute list.
+ */
+ ntfs_attr_reinit_search_ctx(ctx);
+ err = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE,
+ lowest_vcn, NULL, 0, ctx);
+ if (err) {
+ pr_err("%s: attribute lookup failed", __func__);
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+
+ }
+ offset = (u8 *)ctx->attr - (u8 *)ctx->mrec;
+ ntfs_attr_put_search_ctx(ctx);
+ return offset;
+put_err_out:
+ ntfs_attr_put_search_ctx(ctx);
+ return -1;
+}
+
+/**
+ * ntfs_attr_record_rm - remove attribute extent
+ * @ctx: search context describing the attribute which should be removed
+ *
+ * If this function succeed, user should reinit search context if he/she wants
+ * use it anymore.
+ */
+int ntfs_attr_record_rm(struct ntfs_attr_search_ctx *ctx)
+{
+ struct ntfs_inode *base_ni, *ni;
+ __le32 type;
+ int err;
+
+ if (!ctx || !ctx->ntfs_ino || !ctx->mrec || !ctx->attr)
+ return -EINVAL;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
+ (long long) ctx->ntfs_ino->mft_no,
+ (unsigned int) le32_to_cpu(ctx->attr->type));
+ type = ctx->attr->type;
+ ni = ctx->ntfs_ino;
+ if (ctx->base_ntfs_ino)
+ base_ni = ctx->base_ntfs_ino;
+ else
+ base_ni = ctx->ntfs_ino;
+
+ /* Remove attribute itself. */
+ if (ntfs_attr_record_resize(ctx->mrec, ctx->attr, 0)) {
+ ntfs_debug("Couldn't remove attribute record. Bug or damaged MFT record.\n");
+ return -EIO;
+ }
+ mark_mft_record_dirty(ni);
+
+ /*
+ * Remove record from $ATTRIBUTE_LIST if present and we don't want
+ * delete $ATTRIBUTE_LIST itself.
+ */
+ if (NInoAttrList(base_ni) && type != AT_ATTRIBUTE_LIST) {
+ err = ntfs_attrlist_entry_rm(ctx);
+ if (err) {
+ ntfs_debug("Couldn't delete record from $ATTRIBUTE_LIST.\n");
+ return err;
+ }
+ }
+
+ /* Post $ATTRIBUTE_LIST delete setup. */
+ if (type == AT_ATTRIBUTE_LIST) {
+ if (NInoAttrList(base_ni) && base_ni->attr_list)
+ ntfs_free(base_ni->attr_list);
+ base_ni->attr_list = NULL;
+ NInoClearAttrList(base_ni);
+ }
+
+ /* Free MFT record, if it doesn't contain attributes. */
+ if (le32_to_cpu(ctx->mrec->bytes_in_use) -
+ le16_to_cpu(ctx->mrec->attrs_offset) == 8) {
+ if (ntfs_mft_record_free(ni->vol, ni)) {
+ ntfs_debug("Couldn't free MFT record.\n");
+ return -EIO;
+ }
+ /* Remove done if we freed base inode. */
+ if (ni == base_ni)
+ return 0;
+ ntfs_inode_close(ni);
+ ctx->ntfs_ino = ni = NULL;
+ }
+
+ if (type == AT_ATTRIBUTE_LIST || !NInoAttrList(base_ni))
+ return 0;
+
+ /* Remove attribute list if we don't need it any more. */
+ if (!ntfs_attrlist_need(base_ni)) {
+ struct ntfs_attr na;
+ struct inode *attr_vi;
+
+ ntfs_attr_reinit_search_ctx(ctx);
+ if (ntfs_attr_lookup(AT_ATTRIBUTE_LIST, NULL, 0, CASE_SENSITIVE,
+ 0, NULL, 0, ctx)) {
+ ntfs_debug("Couldn't find attribute list. Succeed anyway.\n");
+ return 0;
+ }
+ /* Deallocate clusters. */
+ if (ctx->attr->non_resident) {
+ struct runlist_element *al_rl;
+ size_t new_rl_count;
+
+ al_rl = ntfs_mapping_pairs_decompress(base_ni->vol,
+ ctx->attr, NULL, &new_rl_count);
+ if (IS_ERR(al_rl)) {
+ ntfs_debug("Couldn't decompress attribute list runlist. Succeed anyway.\n");
+ return 0;
+ }
+ if (ntfs_cluster_free_from_rl(base_ni->vol, al_rl))
+ ntfs_debug("Leaking clusters! Run chkdsk. Couldn't free clusters from attribute list runlist.\n");
+ ntfs_free(al_rl);
+ }
+ /* Remove attribute record itself. */
+ if (ntfs_attr_record_rm(ctx)) {
+ ntfs_debug("Couldn't remove attribute list. Succeed anyway.\n");
+ return 0;
+ }
+
+ na.mft_no = VFS_I(base_ni)->i_ino;
+ na.type = AT_ATTRIBUTE_LIST;
+ na.name = NULL;
+ na.name_len = 0;
+
+ attr_vi = ilookup5(VFS_I(base_ni)->i_sb, VFS_I(base_ni)->i_ino,
+ ntfs_test_inode, &na);
+ if (attr_vi) {
+ clear_nlink(attr_vi);
+ iput(attr_vi);
+ }
+
+ }
+ return 0;
+}
+
+/**
+ * ntfs_attr_add - add attribute to inode
+ * @ni: opened ntfs inode to which add attribute
+ * @type: type of the new attribute
+ * @name: name in unicode of the new attribute
+ * @name_len: name length in unicode characters of the new attribute
+ * @val: value of new attribute
+ * @size: size of the new attribute / length of @val (if specified)
+ *
+ * @val should always be specified for always resident attributes (eg. FILE_NAME
+ * attribute), for attributes that can become non-resident @val can be NULL
+ * (eg. DATA attribute). @size can be specified even if @val is NULL, in this
+ * case data size will be equal to @size and initialized size will be equal
+ * to 0.
+ *
+ * If inode haven't got enough space to add attribute, add attribute to one of
+ * it extents, if no extents present or no one of them have enough space, than
+ * allocate new extent and add attribute to it.
+ *
+ * If on one of this steps attribute list is needed but not present, than it is
+ * added transparently to caller. So, this function should not be called with
+ * @type == AT_ATTRIBUTE_LIST, if you really need to add attribute list call
+ * ntfs_inode_add_attrlist instead.
+ *
+ * On success return 0. On error return -1 with errno set to the error code.
+ */
+int ntfs_attr_add(struct ntfs_inode *ni, __le32 type,
+ __le16 *name, u8 name_len, u8 *val, s64 size)
+{
+ struct super_block *sb;
+ u32 attr_rec_size;
+ int err, i, offset;
+ bool is_resident;
+ bool can_be_non_resident = false;
+ struct ntfs_inode *attr_ni;
+ struct inode *attr_vi;
+ struct mft_record *ni_mrec;
+
+ if (!ni || size < 0 || type == AT_ATTRIBUTE_LIST)
+ return -EINVAL;
+
+ ntfs_debug("Entering for inode 0x%llx, attr %x, size %lld.\n",
+ (long long) ni->mft_no, type, size);
+
+ if (ni->nr_extents == -1)
+ ni = ni->ext.base_ntfs_ino;
+
+ /* Check the attribute type and the size. */
+ err = ntfs_attr_size_bounds_check(ni->vol, type, size);
+ if (err) {
+ if (err == -ENOENT)
+ err = -EIO;
+ return err;
+ }
+
+ sb = ni->vol->sb;
+ /* Sanity checks for always resident attributes. */
+ err = ntfs_attr_can_be_non_resident(ni->vol, type);
+ if (err) {
+ if (err != -EPERM) {
+ ntfs_error(sb, "ntfs_attr_can_be_non_resident failed");
+ goto err_out;
+ }
+ /* @val is mandatory. */
+ if (!val) {
+ ntfs_error(sb,
+ "val is mandatory for always resident attributes");
+ return -EINVAL;
+ }
+ if (size > ni->vol->mft_record_size) {
+ ntfs_error(sb, "Attribute is too big");
+ return -ERANGE;
+ }
+ } else
+ can_be_non_resident = true;
+
+ /*
+ * Determine resident or not will be new attribute. We add 8 to size in
+ * non resident case for mapping pairs.
+ */
+ err = ntfs_attr_can_be_resident(ni->vol, type);
+ if (!err) {
+ is_resident = true;
+ } else {
+ if (err != -EPERM) {
+ ntfs_error(sb, "ntfs_attr_can_be_resident failed");
+ goto err_out;
+ }
+ is_resident = false;
+ }
+
+ /* Calculate attribute record size. */
+ if (is_resident)
+ attr_rec_size = offsetof(struct attr_record, data.resident.reserved) +
+ 1 +
+ ((name_len * sizeof(__le16) + 7) & ~7) +
+ ((size + 7) & ~7);
+ else
+ attr_rec_size = offsetof(struct attr_record, data.non_resident.compressed_size) +
+ ((name_len * sizeof(__le16) + 7) & ~7) + 8;
+
+ /*
+ * If we have enough free space for the new attribute in the base MFT
+ * record, then add attribute to it.
+ */
+retry:
+ ni_mrec = map_mft_record(ni);
+ if (IS_ERR(ni_mrec)) {
+ err = -EIO;
+ goto err_out;
+ }
+
+ if (le32_to_cpu(ni_mrec->bytes_allocated) -
+ le32_to_cpu(ni_mrec->bytes_in_use) >= attr_rec_size) {
+ attr_ni = ni;
+ unmap_mft_record(ni);
+ goto add_attr_record;
+ }
+ unmap_mft_record(ni);
+
+ /* Try to add to extent inodes. */
+ err = ntfs_inode_attach_all_extents(ni);
+ if (err) {
+ ntfs_error(sb, "Failed to attach all extents to inode");
+ goto err_out;
+ }
+
+ for (i = 0; i < ni->nr_extents; i++) {
+ attr_ni = ni->ext.extent_ntfs_inos[i];
+ ni_mrec = map_mft_record(attr_ni);
+ if (IS_ERR(ni_mrec)) {
+ err = -EIO;
+ goto err_out;
+ }
+
+ if (le32_to_cpu(ni_mrec->bytes_allocated) -
+ le32_to_cpu(ni_mrec->bytes_in_use) >=
+ attr_rec_size) {
+ unmap_mft_record(attr_ni);
+ goto add_attr_record;
+ }
+ unmap_mft_record(attr_ni);
+ }
+
+ /* There is no extent that contain enough space for new attribute. */
+ if (!NInoAttrList(ni)) {
+ /* Add attribute list not present, add it and retry. */
+ err = ntfs_inode_add_attrlist(ni);
+ if (err) {
+ ntfs_error(sb, "Failed to add attribute list");
+ goto err_out;
+ }
+ goto retry;
+ }
+
+ attr_ni = NULL;
+ /* Allocate new extent. */
+ err = ntfs_mft_record_alloc(ni->vol, 0, &attr_ni, ni, NULL);
+ if (err) {
+ ntfs_error(sb, "Failed to allocate extent record");
+ goto err_out;
+ }
+ unmap_mft_record(attr_ni);
+
+add_attr_record:
+ if (is_resident) {
+ /* Add resident attribute. */
+ offset = ntfs_resident_attr_record_add(attr_ni, type, name,
+ name_len, val, size, 0);
+ if (offset < 0) {
+ if (offset == -ENOSPC && can_be_non_resident)
+ goto add_non_resident;
+ err = offset;
+ ntfs_error(sb, "Failed to add resident attribute");
+ goto free_err_out;
+ }
+ return 0;
+ }
+
+add_non_resident:
+ /* Add non resident attribute. */
+ offset = ntfs_non_resident_attr_record_add(attr_ni, type, name,
+ name_len, 0, 8, 0);
+ if (offset < 0) {
+ err = offset;
+ ntfs_error(sb, "Failed to add non resident attribute");
+ goto free_err_out;
+ }
+
+ /* If @size == 0, we are done. */
+ if (!size)
+ return 0;
+
+ /* Open new attribute and resize it. */
+ attr_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
+ if (IS_ERR(attr_vi)) {
+ ntfs_error(sb, "Failed to open just added attribute");
+ goto rm_attr_err_out;
+ }
+ attr_ni = NTFS_I(attr_vi);
+
+ /* Resize and set attribute value. */
+ if (ntfs_attr_truncate(attr_ni, size) ||
+ (val && (ntfs_inode_attr_pwrite(attr_vi, 0, size, val, false) != size))) {
+ err = -EIO;
+ ntfs_error(sb, "Failed to initialize just added attribute");
+ if (ntfs_attr_rm(attr_ni))
+ ntfs_error(sb, "Failed to remove just added attribute");
+ iput(attr_vi);
+ goto err_out;
+ }
+ iput(attr_vi);
+ return 0;
+
+rm_attr_err_out:
+ /* Remove just added attribute. */
+ ni_mrec = map_mft_record(attr_ni);
+ if (!IS_ERR(ni_mrec)) {
+ if (ntfs_attr_record_resize(ni_mrec,
+ (struct attr_record *)((u8 *)ni_mrec + offset), 0))
+ ntfs_error(sb, "Failed to remove just added attribute #2");
+ unmap_mft_record(attr_ni);
+ } else
+ pr_err("EIO when try to remove new added attr\n");
+
+free_err_out:
+ /* Free MFT record, if it doesn't contain attributes. */
+ ni_mrec = map_mft_record(attr_ni);
+ if (!IS_ERR(ni_mrec)) {
+ int attr_size;
+
+ attr_size = le32_to_cpu(ni_mrec->bytes_in_use) -
+ le16_to_cpu(ni_mrec->attrs_offset);
+ unmap_mft_record(attr_ni);
+ if (attr_size == 8) {
+ if (ntfs_mft_record_free(attr_ni->vol, attr_ni))
+ ntfs_error(sb, "Failed to free MFT record");
+ if (attr_ni->nr_extents < 0)
+ ntfs_inode_close(attr_ni);
+ }
+ } else
+ pr_err("EIO when testing mft record is free-able\n");
+
+err_out:
+ return err;
+}
+
+/**
+ * __ntfs_attr_init - primary initialization of an ntfs attribute structure
+ * @ni: ntfs attribute inode to initialize
+ * @ni: ntfs inode with which to initialize the ntfs attribute
+ * @type: attribute type
+ * @name: attribute name in little endian Unicode or NULL
+ * @name_len: length of attribute @name in Unicode characters (if @name given)
+ *
+ * Initialize the ntfs attribute @na with @ni, @type, @name, and @name_len.
+ */
+static void __ntfs_attr_init(struct ntfs_inode *ni,
+ const __le32 type, __le16 *name, const u32 name_len)
+{
+ ni->runlist.rl = NULL;
+ ni->type = type;
+ ni->name = name;
+ if (name)
+ ni->name_len = name_len;
+ else
+ ni->name_len = 0;
+}
+
+/**
+ * ntfs_attr_init - initialize an ntfs_attr with data sizes and status
+ * Final initialization for an ntfs attribute.
+ */
+static void ntfs_attr_init(struct ntfs_inode *ni, const bool non_resident,
+ const bool compressed, const bool encrypted, const bool sparse,
+ const s64 allocated_size, const s64 data_size,
+ const s64 initialized_size, const s64 compressed_size,
+ const u8 compression_unit)
+{
+ if (non_resident)
+ NInoSetNonResident(ni);
+ if (compressed) {
+ NInoSetCompressed(ni);
+ ni->flags |= FILE_ATTR_COMPRESSED;
+ }
+ if (encrypted) {
+ NInoSetEncrypted(ni);
+ ni->flags |= FILE_ATTR_ENCRYPTED;
+ }
+ if (sparse) {
+ NInoSetSparse(ni);
+ ni->flags |= FILE_ATTR_SPARSE_FILE;
+ }
+ ni->allocated_size = allocated_size;
+ ni->data_size = data_size;
+ ni->initialized_size = initialized_size;
+ if (compressed || sparse) {
+ struct ntfs_volume *vol = ni->vol;
+
+ ni->itype.compressed.size = compressed_size;
+ ni->itype.compressed.block_clusters = 1 << compression_unit;
+ ni->itype.compressed.block_size = 1 << (compression_unit +
+ vol->cluster_size_bits);
+ ni->itype.compressed.block_size_bits = ffs(
+ ni->itype.compressed.block_size) - 1;
+ }
+}
+
+/**
+ * ntfs_attr_open - open an ntfs attribute for access
+ * @ni: open ntfs inode in which the ntfs attribute resides
+ * @type: attribute type
+ * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL
+ * @name_len: length of attribute @name in Unicode characters (if @name given)
+ */
+int ntfs_attr_open(struct ntfs_inode *ni, const __le32 type,
+ __le16 *name, u32 name_len)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ __le16 *newname = NULL;
+ struct attr_record *a;
+ bool cs;
+ struct ntfs_inode *base_ni;
+ int err;
+
+ ntfs_debug("Entering for inode %lld, attr 0x%x.\n",
+ (unsigned long long)ni->mft_no, type);
+
+ if (!ni || !ni->vol)
+ return -EINVAL;
+
+ if (NInoAttr(ni))
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+
+ if (name && name != AT_UNNAMED && name != I30) {
+ name = ntfs_ucsndup(name, name_len);
+ if (!name) {
+ err = -ENOMEM;
+ goto err_out;
+ }
+ newname = name;
+ }
+
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ err = -ENOMEM;
+ pr_err("%s: Failed to get search context", __func__);
+ goto err_out;
+ }
+
+ err = ntfs_attr_lookup(type, name, name_len, 0, 0, NULL, 0, ctx);
+ if (err)
+ goto put_err_out;
+
+ a = ctx->attr;
+
+ if (!name) {
+ if (a->name_length) {
+ name = ntfs_ucsndup((__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
+ a->name_length);
+ if (!name)
+ goto put_err_out;
+ newname = name;
+ name_len = a->name_length;
+ } else {
+ name = AT_UNNAMED;
+ name_len = 0;
+ }
+ }
+
+ __ntfs_attr_init(ni, type, name, name_len);
+
+ /*
+ * Wipe the flags in case they are not zero for an attribute list
+ * attribute. Windows does not complain about invalid flags and chkdsk
+ * does not detect or fix them so we need to cope with it, too.
+ */
+ if (type == AT_ATTRIBUTE_LIST)
+ a->flags = 0;
+
+ if ((type == AT_DATA) &&
+ (a->non_resident ? !a->data.non_resident.initialized_size :
+ !a->data.resident.value_length)) {
+ /*
+ * Define/redefine the compression state if stream is
+ * empty, based on the compression mark on parent
+ * directory (for unnamed data streams) or on current
+ * inode (for named data streams). The compression mark
+ * may change any time, the compression state can only
+ * change when stream is wiped out.
+ *
+ * Also prevent compression on NTFS version < 3.0
+ * or cluster size > 4K or compression is disabled
+ */
+ a->flags &= ~ATTR_COMPRESSION_MASK;
+ if (NInoCompressed(ni)
+ && (ni->vol->major_ver >= 3)
+ && NVolCompression(ni->vol)
+ && (ni->vol->cluster_size <= MAX_COMPRESSION_CLUSTER_SIZE))
+ a->flags |= ATTR_IS_COMPRESSED;
+ }
+
+ cs = a->flags & (ATTR_IS_COMPRESSED | ATTR_IS_SPARSE);
+
+ if (ni->type == AT_DATA && ni->name == AT_UNNAMED &&
+ ((!(a->flags & ATTR_IS_COMPRESSED) != !NInoCompressed(ni)) ||
+ (!(a->flags & ATTR_IS_SPARSE) != !NInoSparse(ni)) ||
+ (!(a->flags & ATTR_IS_ENCRYPTED) != !NInoEncrypted(ni)))) {
+ err = -EIO;
+ pr_err("Inode %lld has corrupt attribute flags (0x%x <> 0x%x)\n",
+ (unsigned long long)ni->mft_no,
+ a->flags, ni->flags);
+ goto put_err_out;
+ }
+
+ if (a->non_resident) {
+ if (((a->flags & ATTR_COMPRESSION_MASK) || a->data.non_resident.compression_unit) &&
+ (ni->vol->major_ver < 3)) {
+ err = -EIO;
+ pr_err("Compressed inode %lld not allowed on NTFS %d.%d\n",
+ (unsigned long long)ni->mft_no,
+ ni->vol->major_ver,
+ ni->vol->major_ver);
+ goto put_err_out;
+ }
+
+ if ((a->flags & ATTR_IS_COMPRESSED) && !a->data.non_resident.compression_unit) {
+ err = -EIO;
+ pr_err("Compressed inode %lld attr 0x%x has no compression unit\n",
+ (unsigned long long)ni->mft_no, type);
+ goto put_err_out;
+ }
+ if ((a->flags & ATTR_COMPRESSION_MASK) &&
+ (a->data.non_resident.compression_unit != STANDARD_COMPRESSION_UNIT)) {
+ err = -EIO;
+ pr_err("Compressed inode %lld attr 0x%lx has an unsupported compression unit %d\n",
+ (unsigned long long)ni->mft_no,
+ (long)le32_to_cpu(type),
+ (int)a->data.non_resident.compression_unit);
+ goto put_err_out;
+ }
+ ntfs_attr_init(ni, true, a->flags & ATTR_IS_COMPRESSED,
+ a->flags & ATTR_IS_ENCRYPTED,
+ a->flags & ATTR_IS_SPARSE,
+ le64_to_cpu(a->data.non_resident.allocated_size),
+ le64_to_cpu(a->data.non_resident.data_size),
+ le64_to_cpu(a->data.non_resident.initialized_size),
+ cs ? le64_to_cpu(a->data.non_resident.compressed_size) : 0,
+ cs ? a->data.non_resident.compression_unit : 0);
+ } else {
+ s64 l = le32_to_cpu(a->data.resident.value_length);
+
+ ntfs_attr_init(ni, false, a->flags & ATTR_IS_COMPRESSED,
+ a->flags & ATTR_IS_ENCRYPTED,
+ a->flags & ATTR_IS_SPARSE, (l + 7) & ~7, l, l,
+ cs ? (l + 7) & ~7 : 0, 0);
+ }
+ ntfs_attr_put_search_ctx(ctx);
+out:
+ ntfs_debug("\n");
+ return err;
+
+put_err_out:
+ ntfs_attr_put_search_ctx(ctx);
+err_out:
+ ntfs_free(newname);
+ goto out;
+}
+
+/**
+ * ntfs_attr_close - free an ntfs attribute structure
+ * @ni: ntfs inode to free
+ *
+ * Release all memory associated with the ntfs attribute @na and then release
+ * @na itself.
+ */
+void ntfs_attr_close(struct ntfs_inode *ni)
+{
+ if (NInoNonResident(ni) && ni->runlist.rl)
+ ntfs_free(ni->runlist.rl);
+ /* Don't release if using an internal constant. */
+ if (ni->name != AT_UNNAMED && ni->name != I30)
+ ntfs_free(ni->name);
+}
+
+/**
+ * ntfs_attr_map_whole_runlist - map the whole runlist of an ntfs attribute
+ * @ni: ntfs inode for which to map the runlist
+ *
+ * Map the whole runlist of the ntfs attribute @na. For an attribute made up
+ * of only one attribute extent this is the same as calling
+ * ntfs_map_runlist(ni, 0) but for an attribute with multiple extents this
+ * will map the runlist fragments from each of the extents thus giving access
+ * to the entirety of the disk allocation of an attribute.
+ */
+int ntfs_attr_map_whole_runlist(struct ntfs_inode *ni)
+{
+ s64 next_vcn, last_vcn, highest_vcn;
+ struct ntfs_attr_search_ctx *ctx;
+ struct ntfs_volume *vol = ni->vol;
+ struct super_block *sb = vol->sb;
+ struct attr_record *a;
+ int err;
+ struct ntfs_inode *base_ni;
+ int not_mapped;
+ size_t new_rl_count;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
+ (unsigned long long)ni->mft_no, ni->type);
+
+ if (NInoFullyMapped(ni) && ni->runlist.rl)
+ return 0;
+
+ if (NInoAttr(ni))
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ ntfs_error(sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+
+ /* Map all attribute extents one by one. */
+ next_vcn = last_vcn = highest_vcn = 0;
+ a = NULL;
+ while (1) {
+ struct runlist_element *rl;
+
+ not_mapped = 0;
+ if (ntfs_rl_vcn_to_lcn(ni->runlist.rl, next_vcn) == LCN_RL_NOT_MAPPED)
+ not_mapped = 1;
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, next_vcn, NULL, 0, ctx);
+ if (err)
+ break;
+
+ a = ctx->attr;
+
+ if (not_mapped) {
+ /* Decode the runlist. */
+ rl = ntfs_mapping_pairs_decompress(ni->vol, a, &ni->runlist,
+ &new_rl_count);
+ if (IS_ERR(rl)) {
+ err = PTR_ERR(rl);
+ goto err_out;
+ }
+ ni->runlist.rl = rl;
+ ni->runlist.count = new_rl_count;
+ }
+
+ /* Are we in the first extent? */
+ if (!next_vcn) {
+ if (a->data.non_resident.lowest_vcn) {
+ err = -EIO;
+ ntfs_error(sb,
+ "First extent of inode %llu attribute has non-zero lowest_vcn",
+ (unsigned long long)ni->mft_no);
+ goto err_out;
+ }
+ /* Get the last vcn in the attribute. */
+ last_vcn = le64_to_cpu(a->data.non_resident.allocated_size) >>
+ vol->cluster_size_bits;
+ }
+
+ /* Get the lowest vcn for the next extent. */
+ 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. */
+ if (next_vcn <= 0) {
+ err = -ENOENT;
+ break;
+ }
+
+ /* Avoid endless loops due to corruption. */
+ if (next_vcn < le64_to_cpu(a->data.non_resident.lowest_vcn)) {
+ err = -EIO;
+ ntfs_error(sb, "Inode %llu has corrupt attribute list",
+ (unsigned long long)ni->mft_no);
+ goto err_out;
+ }
+ }
+ if (!a) {
+ ntfs_error(sb, "Couldn't find attribute for runlist mapping");
+ goto err_out;
+ }
+ if (not_mapped && highest_vcn && highest_vcn != last_vcn - 1) {
+ err = -EIO;
+ ntfs_error(sb,
+ "Failed to load full runlist: inode: %llu highest_vcn: 0x%llx last_vcn: 0x%llx",
+ (unsigned long long)ni->mft_no,
+ (long long)highest_vcn, (long long)last_vcn);
+ goto err_out;
+ }
+ ntfs_attr_put_search_ctx(ctx);
+ if (err == -ENOENT) {
+ NInoSetFullyMapped(ni);
+ return 0;
+ }
+
+ return err;
+
+err_out:
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+/**
+ * ntfs_attr_record_move_to - move attribute record to target inode
+ * @ctx: attribute search context describing the attribute record
+ * @ni: opened ntfs inode to which move attribute record
+ */
+int ntfs_attr_record_move_to(struct ntfs_attr_search_ctx *ctx, struct ntfs_inode *ni)
+{
+ struct ntfs_attr_search_ctx *nctx;
+ struct attr_record *a;
+ int err;
+ struct mft_record *ni_mrec;
+ struct super_block *sb;
+
+ if (!ctx || !ctx->attr || !ctx->ntfs_ino || !ni) {
+ ntfs_debug("Invalid arguments passed.\n");
+ return -EINVAL;
+ }
+
+ sb = ni->vol->sb;
+ ntfs_debug("Entering for ctx->attr->type 0x%x, ctx->ntfs_ino->mft_no 0x%llx, ni->mft_no 0x%llx.\n",
+ (unsigned int) le32_to_cpu(ctx->attr->type),
+ (long long) ctx->ntfs_ino->mft_no,
+ (long long) ni->mft_no);
+
+ if (ctx->ntfs_ino == ni)
+ return 0;
+
+ if (!ctx->al_entry) {
+ ntfs_debug("Inode should contain attribute list to use this function.\n");
+ return -EINVAL;
+ }
+
+ /* Find place in MFT record where attribute will be moved. */
+ a = ctx->attr;
+ nctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!nctx) {
+ ntfs_error(sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+
+ /*
+ * Use ntfs_attr_find instead of ntfs_attr_lookup to find place for
+ * attribute in @ni->mrec, not any extent inode in case if @ni is base
+ * file record.
+ */
+ err = ntfs_attr_find(a->type, (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
+ a->name_length, CASE_SENSITIVE, NULL,
+ 0, nctx);
+ if (!err) {
+ ntfs_debug("Attribute of such type, with same name already present in this MFT record.\n");
+ err = -EEXIST;
+ goto put_err_out;
+ }
+ if (err != -ENOENT) {
+ ntfs_debug("Attribute lookup failed.\n");
+ goto put_err_out;
+ }
+
+ /* Make space and move attribute. */
+ ni_mrec = map_mft_record(ni);
+ if (IS_ERR(ni_mrec)) {
+ err = -EIO;
+ goto put_err_out;
+ }
+
+ err = ntfs_make_room_for_attr(ni_mrec, (u8 *) nctx->attr,
+ le32_to_cpu(a->length));
+ if (err) {
+ ntfs_debug("Couldn't make space for attribute.\n");
+ unmap_mft_record(ni);
+ goto put_err_out;
+ }
+ memcpy(nctx->attr, a, le32_to_cpu(a->length));
+ nctx->attr->instance = nctx->mrec->next_attr_instance;
+ nctx->mrec->next_attr_instance =
+ cpu_to_le16((le16_to_cpu(nctx->mrec->next_attr_instance) + 1) & 0xffff);
+ ntfs_attr_record_resize(ctx->mrec, a, 0);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ mark_mft_record_dirty(ni);
+
+ /* Update attribute list. */
+ ctx->al_entry->mft_reference =
+ MK_LE_MREF(ni->mft_no, le16_to_cpu(ni_mrec->sequence_number));
+ ctx->al_entry->instance = nctx->attr->instance;
+ unmap_mft_record(ni);
+put_err_out:
+ ntfs_attr_put_search_ctx(nctx);
+ return err;
+}
+
+/**
+ * ntfs_attr_record_move_away - move away attribute record from it's mft record
+ * @ctx: attribute search context describing the attribute record
+ * @extra: minimum amount of free space in the new holder of record
+ */
+int ntfs_attr_record_move_away(struct ntfs_attr_search_ctx *ctx, int extra)
+{
+ struct ntfs_inode *base_ni, *ni = NULL;
+ struct mft_record *m;
+ int i, err;
+ struct super_block *sb;
+
+ if (!ctx || !ctx->attr || !ctx->ntfs_ino || extra < 0)
+ return -EINVAL;
+
+ ntfs_debug("Entering for attr 0x%x, inode %llu\n",
+ (unsigned int) le32_to_cpu(ctx->attr->type),
+ (unsigned long long)ctx->ntfs_ino->mft_no);
+
+ if (ctx->ntfs_ino->nr_extents == -1)
+ base_ni = ctx->base_ntfs_ino;
+ else
+ base_ni = ctx->ntfs_ino;
+
+ sb = ctx->ntfs_ino->vol->sb;
+ if (!NInoAttrList(base_ni)) {
+ ntfs_error(sb, "Inode %llu has no attrlist",
+ (unsigned long long)base_ni->mft_no);
+ return -EINVAL;
+ }
+
+ err = ntfs_inode_attach_all_extents(ctx->ntfs_ino);
+ if (err) {
+ ntfs_error(sb, "Couldn't attach extents, inode=%llu",
+ (unsigned long long)base_ni->mft_no);
+ return err;
+ }
+
+ mutex_lock(&base_ni->extent_lock);
+ /* Walk through all extents and try to move attribute to them. */
+ for (i = 0; i < base_ni->nr_extents; i++) {
+ ni = base_ni->ext.extent_ntfs_inos[i];
+
+ if (ctx->ntfs_ino->mft_no == ni->mft_no)
+ continue;
+ m = map_mft_record(ni);
+ if (IS_ERR(m)) {
+ ntfs_error(sb, "Can not map mft record for mft_no %lld",
+ (unsigned long long)ni->mft_no);
+ mutex_unlock(&base_ni->extent_lock);
+ return -EIO;
+ }
+ if (le32_to_cpu(m->bytes_allocated) -
+ le32_to_cpu(m->bytes_in_use) < le32_to_cpu(ctx->attr->length) + extra) {
+ unmap_mft_record(ni);
+ continue;
+ }
+ unmap_mft_record(ni);
+
+ /*
+ * ntfs_attr_record_move_to can fail if extent with other lowest
+ * s64 already present in inode we trying move record to. So,
+ * do not return error.
+ */
+ if (!ntfs_attr_record_move_to(ctx, ni)) {
+ mutex_unlock(&base_ni->extent_lock);
+ return 0;
+ }
+ }
+ mutex_unlock(&base_ni->extent_lock);
+
+ /*
+ * Failed to move attribute to one of the current extents, so allocate
+ * new extent and move attribute to it.
+ */
+ ni = NULL;
+ err = ntfs_mft_record_alloc(base_ni->vol, 0, &ni, base_ni, NULL);
+ if (err) {
+ ntfs_error(sb, "Couldn't allocate MFT record, err : %d", err);
+ return err;
+ }
+ unmap_mft_record(ni);
+
+ err = ntfs_attr_record_move_to(ctx, ni);
+ if (err)
+ ntfs_error(sb, "Couldn't move attribute to MFT record");
+
+ return err;
+}
+
+/*
+ * If we are in the first extent, then set/clean sparse bit,
+ * update allocated and compressed size.
+ */
+static int ntfs_attr_update_meta(struct attr_record *a, struct ntfs_inode *ni,
+ struct mft_record *m, struct ntfs_attr_search_ctx *ctx)
+{
+ int sparse, err = 0;
+ struct ntfs_inode *base_ni;
+ struct super_block *sb = ni->vol->sb;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x\n",
+ (unsigned long long)ni->mft_no, ni->type);
+
+ if (NInoAttr(ni))
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+
+ if (a->data.non_resident.lowest_vcn)
+ goto out;
+
+ a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
+
+ sparse = ntfs_rl_sparse(ni->runlist.rl);
+ if (sparse < 0) {
+ err = -EIO;
+ goto out;
+ }
+
+ /* Attribute become sparse. */
+ if (sparse && !(a->flags & (ATTR_IS_SPARSE | ATTR_IS_COMPRESSED))) {
+ /*
+ * Move attribute to another mft record, if attribute is too
+ * small to add compressed_size field to it and we have no
+ * free space in the current mft record.
+ */
+ if ((le32_to_cpu(a->length) -
+ le16_to_cpu(a->data.non_resident.mapping_pairs_offset) == 8) &&
+ !(le32_to_cpu(m->bytes_allocated) - le32_to_cpu(m->bytes_in_use))) {
+
+ if (!NInoAttrList(base_ni)) {
+ err = ntfs_inode_add_attrlist(base_ni);
+ if (err)
+ goto out;
+ err = -EAGAIN;
+ goto out;
+ }
+ err = ntfs_attr_record_move_away(ctx, 8);
+ if (err) {
+ ntfs_error(sb, "Failed to move attribute");
+ goto out;
+ }
+
+ err = ntfs_attrlist_update(base_ni);
+ if (err)
+ goto out;
+ err = -EAGAIN;
+ goto out;
+ }
+ if (!(le32_to_cpu(a->length) -
+ le16_to_cpu(a->data.non_resident.mapping_pairs_offset))) {
+ err = -EIO;
+ ntfs_error(sb, "Mapping pairs space is 0");
+ goto out;
+ }
+
+ NInoSetSparse(ni);
+ ni->flags |= FILE_ATTR_SPARSE_FILE;
+ a->flags |= ATTR_IS_SPARSE;
+ a->data.non_resident.compression_unit = 0;
+
+ memmove((u8 *)a + le16_to_cpu(a->name_offset) + 8,
+ (u8 *)a + le16_to_cpu(a->name_offset),
+ a->name_length * sizeof(__le16));
+
+ a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) + 8);
+
+ a->data.non_resident.mapping_pairs_offset =
+ cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) + 8);
+ }
+
+ /* Attribute no longer sparse. */
+ if (!sparse && (a->flags & ATTR_IS_SPARSE) &&
+ !(a->flags & ATTR_IS_COMPRESSED)) {
+ NInoClearSparse(ni);
+ ni->flags &= ~FILE_ATTR_SPARSE_FILE;
+ a->flags &= ~ATTR_IS_SPARSE;
+ a->data.non_resident.compression_unit = 0;
+
+ memmove((u8 *)a + le16_to_cpu(a->name_offset) - 8,
+ (u8 *)a + le16_to_cpu(a->name_offset),
+ a->name_length * sizeof(__le16));
+
+ if (le16_to_cpu(a->name_offset) >= 8)
+ a->name_offset = cpu_to_le16(le16_to_cpu(a->name_offset) - 8);
+
+ a->data.non_resident.mapping_pairs_offset =
+ cpu_to_le16(le16_to_cpu(a->data.non_resident.mapping_pairs_offset) - 8);
+ }
+
+ /* Update compressed size if required. */
+ if (NInoFullyMapped(ni) && (sparse || NInoCompressed(ni))) {
+ s64 new_compr_size;
+
+ new_compr_size = ntfs_rl_get_compressed_size(ni->vol, ni->runlist.rl);
+ if (new_compr_size < 0) {
+ err = new_compr_size;
+ goto out;
+ }
+
+ ni->itype.compressed.size = new_compr_size;
+ a->data.non_resident.compressed_size = cpu_to_le64(new_compr_size);
+ }
+
+ if (NInoSparse(ni) || NInoCompressed(ni))
+ VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
+ else
+ VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
+ /*
+ * Set FILE_NAME dirty flag, to update sparse bit and
+ * allocated size in the index.
+ */
+ if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
+ NInoSetFileNameDirty(ni);
+out:
+ return err;
+}
+
+#define NTFS_VCN_DELETE_MARK -2
+/**
+ * ntfs_attr_update_mapping_pairs - update mapping pairs for ntfs attribute
+ * @ni: non-resident ntfs inode for which we need update
+ * @from_vcn: update runlist starting this VCN
+ *
+ * Build mapping pairs from @na->rl and write them to the disk. Also, this
+ * function updates sparse bit, allocated and compressed size (allocates/frees
+ * space for this field if required).
+ *
+ * @na->allocated_size should be set to correct value for the new runlist before
+ * call to this function. Vice-versa @na->compressed_size will be calculated and
+ * set to correct value during this function.
+ */
+int ntfs_attr_update_mapping_pairs(struct ntfs_inode *ni, s64 from_vcn)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ struct ntfs_inode *base_ni;
+ struct mft_record *m;
+ struct attr_record *a;
+ s64 stop_vcn;
+ int err = 0, mp_size, cur_max_mp_size, exp_max_mp_size;
+ bool finished_build;
+ bool first_updated = false;
+ struct super_block *sb;
+ struct runlist_element *start_rl;
+ unsigned int de_cluster_count = 0;
+
+retry:
+ if (!ni || !ni->runlist.rl)
+ return -EINVAL;
+
+ ntfs_debug("Entering for inode %llu, attr 0x%x\n",
+ (unsigned long long)ni->mft_no, ni->type);
+
+ sb = ni->vol->sb;
+ if (!NInoNonResident(ni)) {
+ ntfs_error(sb, "%s: resident attribute", __func__);
+ return -EINVAL;
+ }
+
+ if (ni->nr_extents == -1)
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ ntfs_error(sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+
+ /* Fill attribute records with new mapping pairs. */
+ stop_vcn = 0;
+ finished_build = false;
+ start_rl = ni->runlist.rl;
+ while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, from_vcn, NULL, 0, ctx))) {
+ unsigned int de_cnt = 0;
+
+ a = ctx->attr;
+ m = ctx->mrec;
+ if (!a->data.non_resident.lowest_vcn)
+ first_updated = true;
+
+ /*
+ * If runlist is updating not from the beginning, then set
+ * @stop_vcn properly, i.e. to the lowest vcn of record that
+ * contain @from_vcn. Also we do not need @from_vcn anymore,
+ * set it to 0 to make ntfs_attr_lookup enumerate attributes.
+ */
+ if (from_vcn) {
+ s64 first_lcn;
+
+ stop_vcn = le64_to_cpu(a->data.non_resident.lowest_vcn);
+ from_vcn = 0;
+ /*
+ * Check whether the first run we need to update is
+ * the last run in runlist, if so, then deallocate
+ * all attrubute extents starting this one.
+ */
+ first_lcn = ntfs_rl_vcn_to_lcn(ni->runlist.rl, stop_vcn);
+ if (first_lcn == LCN_EINVAL) {
+ err = -EIO;
+ ntfs_error(sb, "Bad runlist");
+ goto put_err_out;
+ }
+ if (first_lcn == LCN_ENOENT ||
+ first_lcn == LCN_RL_NOT_MAPPED)
+ finished_build = true;
+ }
+
+ /*
+ * Check whether we finished mapping pairs build, if so mark
+ * extent as need to delete (by setting highest vcn to
+ * NTFS_VCN_DELETE_MARK (-2), we shall check it later and
+ * delete extent) and continue search.
+ */
+ if (finished_build) {
+ ntfs_debug("Mark attr 0x%x for delete in inode 0x%lx.\n",
+ (unsigned int)le32_to_cpu(a->type), ctx->ntfs_ino->mft_no);
+ a->data.non_resident.highest_vcn = cpu_to_le64(NTFS_VCN_DELETE_MARK);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ continue;
+ }
+
+ err = ntfs_attr_update_meta(a, ni, m, ctx);
+ if (err < 0) {
+ if (err == -EAGAIN) {
+ ntfs_attr_put_search_ctx(ctx);
+ goto retry;
+ }
+ goto put_err_out;
+ }
+
+ /*
+ * Determine maximum possible length of mapping pairs,
+ * if we shall *not* expand space for mapping pairs.
+ */
+ cur_max_mp_size = le32_to_cpu(a->length) -
+ le16_to_cpu(a->data.non_resident.mapping_pairs_offset);
+ /*
+ * Determine maximum possible length of mapping pairs in the
+ * current mft record, if we shall expand space for mapping
+ * pairs.
+ */
+ exp_max_mp_size = le32_to_cpu(m->bytes_allocated) -
+ le32_to_cpu(m->bytes_in_use) + cur_max_mp_size;
+
+ /* Get the size for the rest of mapping pairs array. */
+ mp_size = ntfs_get_size_for_mapping_pairs(ni->vol, start_rl,
+ stop_vcn, -1, exp_max_mp_size);
+ if (mp_size <= 0) {
+ err = mp_size;
+ ntfs_error(sb, "%s: get MP size failed", __func__);
+ goto put_err_out;
+ }
+ /* Test mapping pairs for fitting in the current mft record. */
+ if (mp_size > exp_max_mp_size) {
+ /*
+ * Mapping pairs of $ATTRIBUTE_LIST attribute must fit
+ * in the base mft record. Try to move out other
+ * attributes and try again.
+ */
+ if (ni->type == AT_ATTRIBUTE_LIST) {
+ ntfs_attr_put_search_ctx(ctx);
+ if (ntfs_inode_free_space(base_ni, mp_size -
+ cur_max_mp_size)) {
+ ntfs_error(sb,
+ "Attribute list is too big. Defragment the volume\n");
+ return -EIO;
+ }
+ if (ntfs_attrlist_update(base_ni))
+ return -EIO;
+ goto retry;
+ }
+
+ /* Add attribute list if it isn't present, and retry. */
+ if (!NInoAttrList(base_ni)) {
+ ntfs_attr_put_search_ctx(ctx);
+ if (ntfs_inode_add_attrlist(base_ni)) {
+ ntfs_error(sb, "Can not add attrlist");
+ return -EIO;
+ }
+ goto retry;
+ }
+
+ /*
+ * Set mapping pairs size to maximum possible for this
+ * mft record. We shall write the rest of mapping pairs
+ * to another MFT records.
+ */
+ mp_size = exp_max_mp_size;
+ }
+
+ /* Change space for mapping pairs if we need it. */
+ if (((mp_size + 7) & ~7) != cur_max_mp_size) {
+ if (ntfs_attr_record_resize(m, a,
+ le16_to_cpu(a->data.non_resident.mapping_pairs_offset) +
+ mp_size)) {
+ err = -EIO;
+ ntfs_error(sb, "Failed to resize attribute");
+ goto put_err_out;
+ }
+ }
+
+ /* Update lowest vcn. */
+ a->data.non_resident.lowest_vcn = cpu_to_le64(stop_vcn);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ if ((ctx->ntfs_ino->nr_extents == -1 || NInoAttrList(ctx->ntfs_ino)) &&
+ ctx->attr->type != AT_ATTRIBUTE_LIST) {
+ ctx->al_entry->lowest_vcn = cpu_to_le64(stop_vcn);
+ err = ntfs_attrlist_update(base_ni);
+ if (err)
+ goto put_err_out;
+ }
+
+ /*
+ * Generate the new mapping pairs array directly into the
+ * correct destination, i.e. the attribute record itself.
+ */
+ err = ntfs_mapping_pairs_build(ni->vol,
+ (u8 *)a + le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
+ mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl, &de_cnt);
+ if (!err)
+ finished_build = true;
+ if (!finished_build && err != -ENOSPC) {
+ ntfs_error(sb, "Failed to build mapping pairs");
+ goto put_err_out;
+ }
+ a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ de_cluster_count += de_cnt;
+ }
+
+ /* Check whether error occurred. */
+ if (err && err != -ENOENT) {
+ ntfs_error(sb, "%s: Attribute lookup failed", __func__);
+ goto put_err_out;
+ }
+
+ /*
+ * If the base extent was skipped in the above process,
+ * we still may have to update the sizes.
+ */
+ if (!first_updated) {
+ ntfs_attr_reinit_search_ctx(ctx);
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx);
+ if (!err) {
+ a = ctx->attr;
+ a->data.non_resident.allocated_size = cpu_to_le64(ni->allocated_size);
+ if (NInoCompressed(ni) || NInoSparse(ni))
+ a->data.non_resident.compressed_size =
+ cpu_to_le64(ni->itype.compressed.size);
+ /* Updating sizes taints the extent holding the attr */
+ if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
+ NInoSetFileNameDirty(ni);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ } else {
+ ntfs_error(sb, "Failed to update sizes in base extent\n");
+ goto put_err_out;
+ }
+ }
+
+ /* Deallocate not used attribute extents and return with success. */
+ if (finished_build) {
+ ntfs_attr_reinit_search_ctx(ctx);
+ ntfs_debug("Deallocate marked extents.\n");
+ while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx))) {
+ if (le64_to_cpu(ctx->attr->data.non_resident.highest_vcn) !=
+ NTFS_VCN_DELETE_MARK)
+ continue;
+ /* Remove unused attribute record. */
+ err = ntfs_attr_record_rm(ctx);
+ if (err) {
+ ntfs_error(sb, "Could not remove unused attr");
+ goto put_err_out;
+ }
+ ntfs_attr_reinit_search_ctx(ctx);
+ }
+ if (err && err != -ENOENT) {
+ ntfs_error(sb, "%s: Attr lookup failed", __func__);
+ goto put_err_out;
+ }
+ ntfs_debug("Deallocate done.\n");
+ ntfs_attr_put_search_ctx(ctx);
+ goto out;
+ }
+ ntfs_attr_put_search_ctx(ctx);
+ ctx = NULL;
+
+ /* Allocate new MFT records for the rest of mapping pairs. */
+ while (1) {
+ struct ntfs_inode *ext_ni = NULL;
+ unsigned int de_cnt = 0;
+
+ /* Allocate new mft record. */
+ err = ntfs_mft_record_alloc(ni->vol, 0, &ext_ni, base_ni, NULL);
+ if (err) {
+ ntfs_error(sb, "Failed to allocate extent record");
+ goto put_err_out;
+ }
+ unmap_mft_record(ext_ni);
+
+ m = map_mft_record(ext_ni);
+ if (IS_ERR(m)) {
+ ntfs_error(sb, "Could not map new MFT record");
+ if (ntfs_mft_record_free(ni->vol, ext_ni))
+ ntfs_error(sb, "Could not free MFT record");
+ ntfs_inode_close(ext_ni);
+ err = -ENOMEM;
+ ext_ni = NULL;
+ goto put_err_out;
+ }
+ /*
+ * If mapping size exceed available space, set them to
+ * possible maximum.
+ */
+ cur_max_mp_size = le32_to_cpu(m->bytes_allocated) -
+ le32_to_cpu(m->bytes_in_use) -
+ (sizeof(struct attr_record) +
+ ((NInoCompressed(ni) || NInoSparse(ni)) ?
+ sizeof(a->data.non_resident.compressed_size) : 0)) -
+ ((sizeof(__le16) * ni->name_len + 7) & ~7);
+
+ /* Calculate size of rest mapping pairs. */
+ mp_size = ntfs_get_size_for_mapping_pairs(ni->vol,
+ start_rl, stop_vcn, -1, cur_max_mp_size);
+ if (mp_size <= 0) {
+ unmap_mft_record(ext_ni);
+ ntfs_inode_close(ext_ni);
+ err = mp_size;
+ ntfs_error(sb, "%s: get mp size failed", __func__);
+ goto put_err_out;
+ }
+
+ if (mp_size > cur_max_mp_size)
+ mp_size = cur_max_mp_size;
+ /* Add attribute extent to new record. */
+ err = ntfs_non_resident_attr_record_add(ext_ni, ni->type,
+ ni->name, ni->name_len, stop_vcn, mp_size, 0);
+ if (err < 0) {
+ ntfs_error(sb, "Could not add attribute extent");
+ unmap_mft_record(ext_ni);
+ if (ntfs_mft_record_free(ni->vol, ext_ni))
+ ntfs_error(sb, "Could not free MFT record");
+ ntfs_inode_close(ext_ni);
+ goto put_err_out;
+ }
+ a = (struct attr_record *)((u8 *)m + err);
+
+ err = ntfs_mapping_pairs_build(ni->vol, (u8 *)a +
+ le16_to_cpu(a->data.non_resident.mapping_pairs_offset),
+ mp_size, start_rl, stop_vcn, -1, &stop_vcn, &start_rl,
+ &de_cnt);
+ if (err < 0 && err != -ENOSPC) {
+ ntfs_error(sb, "Failed to build MP");
+ unmap_mft_record(ext_ni);
+ if (ntfs_mft_record_free(ni->vol, ext_ni))
+ ntfs_error(sb, "Couldn't free MFT record");
+ goto put_err_out;
+ }
+ a->data.non_resident.highest_vcn = cpu_to_le64(stop_vcn - 1);
+ mark_mft_record_dirty(ext_ni);
+ unmap_mft_record(ext_ni);
+
+ de_cluster_count += de_cnt;
+ /* All mapping pairs has been written. */
+ if (!err)
+ break;
+ }
+out:
+ if (from_vcn == 0)
+ ni->i_dealloc_clusters = de_cluster_count;
+ return 0;
+
+put_err_out:
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+/**
+ * ntfs_attr_make_resident - convert a non-resident to a resident attribute
+ * @ni: open ntfs attribute to make resident
+ * @ctx: ntfs search context describing the attribute
+ *
+ * Convert a non-resident ntfs attribute to a resident one.
+ */
+static int ntfs_attr_make_resident(struct ntfs_inode *ni, struct ntfs_attr_search_ctx *ctx)
+{
+ struct ntfs_volume *vol = ni->vol;
+ struct super_block *sb = vol->sb;
+ struct attr_record *a = ctx->attr;
+ int name_ofs, val_ofs, err;
+ s64 arec_size;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
+ (unsigned long long)ni->mft_no, ni->type);
+
+ /* Should be called for the first extent of the attribute. */
+ if (le64_to_cpu(a->data.non_resident.lowest_vcn)) {
+ ntfs_debug("Eeek! Should be called for the first extent of the attribute. Aborting...\n");
+ return -EINVAL;
+ }
+
+ /* Some preliminary sanity checking. */
+ if (!NInoNonResident(ni)) {
+ ntfs_debug("Eeek! Trying to make resident attribute resident. Aborting...\n");
+ return -EINVAL;
+ }
+
+ /* Make sure this is not $MFT/$BITMAP or Windows will not boot! */
+ if (ni->type == AT_BITMAP && ni->mft_no == FILE_MFT)
+ return -EPERM;
+
+ /* Check that the attribute is allowed to be resident. */
+ err = ntfs_attr_can_be_resident(vol, ni->type);
+ if (err)
+ return err;
+
+ if (NInoCompressed(ni) || NInoEncrypted(ni)) {
+ ntfs_debug("Making compressed or encrypted files resident is not implemented yet.\n");
+ return -EOPNOTSUPP;
+ }
+
+ /* Work out offsets into and size of the resident attribute. */
+ name_ofs = 24; /* = sizeof(resident_struct attr_record); */
+ val_ofs = (name_ofs + a->name_length * sizeof(__le16) + 7) & ~7;
+ arec_size = (val_ofs + ni->data_size + 7) & ~7;
+
+ /* Sanity check the size before we start modifying the attribute. */
+ if (le32_to_cpu(ctx->mrec->bytes_in_use) - le32_to_cpu(a->length) +
+ arec_size > le32_to_cpu(ctx->mrec->bytes_allocated)) {
+ ntfs_debug("Not enough space to make attribute resident\n");
+ return -ENOSPC;
+ }
+
+ /* Read and cache the whole runlist if not already done. */
+ err = ntfs_attr_map_whole_runlist(ni);
+ if (err)
+ return err;
+
+ /* Move the attribute name if it exists and update the offset. */
+ if (a->name_length) {
+ memmove((u8 *)a + name_ofs, (u8 *)a + le16_to_cpu(a->name_offset),
+ a->name_length * sizeof(__le16));
+ }
+ a->name_offset = cpu_to_le16(name_ofs);
+
+ /* Resize the resident part of the attribute record. */
+ if (ntfs_attr_record_resize(ctx->mrec, a, arec_size) < 0) {
+ /*
+ * Bug, because ntfs_attr_record_resize should not fail (we
+ * already checked that attribute fits MFT record).
+ */
+ ntfs_error(ctx->ntfs_ino->vol->sb, "BUG! Failed to resize attribute record. ");
+ return -EIO;
+ }
+
+ /* Convert the attribute record to describe a resident attribute. */
+ a->non_resident = 0;
+ a->flags = 0;
+ a->data.resident.value_length = cpu_to_le32(ni->data_size);
+ a->data.resident.value_offset = cpu_to_le16(val_ofs);
+ /*
+ * File names cannot be non-resident so we would never see this here
+ * but at least it serves as a reminder that there may be attributes
+ * for which we do need to set this flag. (AIA)
+ */
+ if (a->type == AT_FILE_NAME)
+ a->data.resident.flags = RESIDENT_ATTR_IS_INDEXED;
+ else
+ a->data.resident.flags = 0;
+ a->data.resident.reserved = 0;
+
+ /*
+ * Deallocate clusters from the runlist.
+ *
+ * NOTE: We can use ntfs_cluster_free() because we have already mapped
+ * the whole run list and thus it doesn't matter that the attribute
+ * record is in a transiently corrupted state at this moment in time.
+ */
+ err = ntfs_cluster_free(ni, 0, -1, ctx);
+ if (err) {
+ ntfs_error(sb, "Eeek! Failed to release allocated clusters");
+ ntfs_debug("Ignoring error and leaving behind wasted clusters.\n");
+ }
+
+ /* Throw away the now unused runlist. */
+ ntfs_free(ni->runlist.rl);
+ ni->runlist.rl = NULL;
+ ni->runlist.count = 0;
+ /* Update in-memory struct ntfs_attr. */
+ NInoClearNonResident(ni);
+ NInoClearCompressed(ni);
+ ni->flags &= ~FILE_ATTR_COMPRESSED;
+ NInoClearSparse(ni);
+ ni->flags &= ~FILE_ATTR_SPARSE_FILE;
+ NInoClearEncrypted(ni);
+ ni->flags &= ~FILE_ATTR_ENCRYPTED;
+ ni->initialized_size = ni->data_size;
+ ni->allocated_size = ni->itype.compressed.size = (ni->data_size + 7) & ~7;
+ ni->itype.compressed.block_size = 0;
+ ni->itype.compressed.block_size_bits = ni->itype.compressed.block_clusters = 0;
+ return 0;
+}
+
+/**
+ * ntfs_non_resident_attr_shrink - shrink a non-resident, open ntfs attribute
+ * @ni: non-resident ntfs attribute to shrink
+ * @newsize: new size (in bytes) to which to shrink the attribute
+ *
+ * Reduce the size of a non-resident, open ntfs attribute @na to @newsize bytes.
+ */
+static int ntfs_non_resident_attr_shrink(struct ntfs_inode *ni, const s64 newsize)
+{
+ struct ntfs_volume *vol;
+ struct ntfs_attr_search_ctx *ctx;
+ s64 first_free_vcn;
+ s64 nr_freed_clusters;
+ int err;
+ struct ntfs_inode *base_ni;
+
+ ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
+ (unsigned long long)ni->mft_no, ni->type, (long long)newsize);
+
+ vol = ni->vol;
+
+ if (NInoAttr(ni))
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+
+ /*
+ * Check the attribute type and the corresponding minimum size
+ * against @newsize and fail if @newsize is too small.
+ */
+ err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
+ if (err) {
+ if (err == -ERANGE)
+ ntfs_debug("Eeek! Size bounds check failed. Aborting...\n");
+ else if (err == -ENOENT)
+ err = -EIO;
+ return err;
+ }
+
+ /* The first cluster outside the new allocation. */
+ if (NInoCompressed(ni))
+ /*
+ * For compressed files we must keep full compressions blocks,
+ * but currently we do not decompress/recompress the last
+ * block to truncate the data, so we may leave more allocated
+ * clusters than really needed.
+ */
+ first_free_vcn = (((newsize - 1) | (ni->itype.compressed.block_size - 1)) + 1) >>
+ vol->cluster_size_bits;
+ else
+ first_free_vcn = (newsize + vol->cluster_size - 1) >>
+ vol->cluster_size_bits;
+
+ if (first_free_vcn < 0)
+ return -EINVAL;
+ /*
+ * Compare the new allocation with the old one and only deallocate
+ * clusters if there is a change.
+ */
+ if ((ni->allocated_size >> vol->cluster_size_bits) != first_free_vcn) {
+ struct ntfs_attr_search_ctx *ctx;
+
+ err = ntfs_attr_map_whole_runlist(ni);
+ if (err) {
+ ntfs_debug("Eeek! ntfs_attr_map_whole_runlist failed.\n");
+ return err;
+ }
+
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+
+ /* Deallocate all clusters starting with the first free one. */
+ nr_freed_clusters = ntfs_cluster_free(ni, first_free_vcn, -1, ctx);
+ if (nr_freed_clusters < 0) {
+ ntfs_debug("Eeek! Freeing of clusters failed. Aborting...\n");
+ ntfs_attr_put_search_ctx(ctx);
+ return (int)nr_freed_clusters;
+ }
+ ntfs_attr_put_search_ctx(ctx);
+
+ /* Truncate the runlist itself. */
+ if (ntfs_rl_truncate_nolock(vol, &ni->runlist, first_free_vcn)) {
+ /*
+ * Failed to truncate the runlist, so just throw it
+ * away, it will be mapped afresh on next use.
+ */
+ ntfs_free(ni->runlist.rl);
+ ni->runlist.rl = NULL;
+ ntfs_error(vol->sb, "Eeek! Run list truncation failed.\n");
+ return -EIO;
+ }
+
+ /* Prepare to mapping pairs update. */
+ ni->allocated_size = first_free_vcn << vol->cluster_size_bits;
+
+ if (NInoSparse(ni) || NInoCompressed(ni)) {
+ if (nr_freed_clusters) {
+ ni->itype.compressed.size -= nr_freed_clusters <<
+ vol->cluster_size_bits;
+ VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
+ }
+ } else
+ VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
+
+ /* Write mapping pairs for new runlist. */
+ err = ntfs_attr_update_mapping_pairs(ni, 0 /*first_free_vcn*/);
+ if (err) {
+ ntfs_debug("Eeek! Mapping pairs update failed. Leaving inconstant metadata. Run chkdsk.\n");
+ return err;
+ }
+ }
+
+ /* Get the first attribute record. */
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
+ 0, NULL, 0, ctx);
+ if (err) {
+ if (err == -ENOENT)
+ err = -EIO;
+ ntfs_debug("Eeek! Lookup of first attribute extent failed. Leaving inconstant metadata.\n");
+ goto put_err_out;
+ }
+
+ /* Update data and initialized size. */
+ ni->data_size = newsize;
+ ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
+ if (newsize < ni->initialized_size) {
+ ni->initialized_size = newsize;
+ ctx->attr->data.non_resident.initialized_size = cpu_to_le64(newsize);
+ }
+ /* Update data size in the index. */
+ if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
+ NInoSetFileNameDirty(ni);
+
+ /* If the attribute now has zero size, make it resident. */
+ if (!newsize && !NInoEncrypted(ni) && !NInoCompressed(ni)) {
+ err = ntfs_attr_make_resident(ni, ctx);
+ if (err) {
+ /* If couldn't make resident, just continue. */
+ if (err != -EPERM)
+ ntfs_error(ni->vol->sb,
+ "Failed to make attribute resident. Leaving as is...\n");
+ }
+ }
+
+ /* Set the inode dirty so it is written out later. */
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ /* Done! */
+ ntfs_attr_put_search_ctx(ctx);
+ return 0;
+put_err_out:
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+/**
+ * ntfs_non_resident_attr_expand - expand a non-resident, open ntfs attribute
+ * @ni: non-resident ntfs attribute to expand
+ * @prealloc_size: preallocation size (in bytes) to which to expand the attribute
+ * @newsize: new size (in bytes) to which to expand the attribute
+ *
+ * Expand the size of a non-resident, open ntfs attribute @na to @newsize bytes,
+ * by allocating new clusters.
+ */
+static int ntfs_non_resident_attr_expand(struct ntfs_inode *ni, const s64 newsize,
+ const s64 prealloc_size, unsigned int holes)
+{
+ s64 lcn_seek_from;
+ s64 first_free_vcn;
+ struct ntfs_volume *vol;
+ struct ntfs_attr_search_ctx *ctx = NULL;
+ struct runlist_element *rl, *rln;
+ s64 org_alloc_size, org_compressed_size;
+ int err, err2;
+ struct ntfs_inode *base_ni;
+ struct super_block *sb = ni->vol->sb;
+ size_t new_rl_count;
+
+ ntfs_debug("Inode 0x%llx, attr 0x%x, new size %lld old size %lld\n",
+ (unsigned long long)ni->mft_no, ni->type,
+ (long long)newsize, (long long)ni->data_size);
+
+ vol = ni->vol;
+
+ if (NInoAttr(ni))
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+
+ /*
+ * Check the attribute type and the corresponding maximum size
+ * against @newsize and fail if @newsize is too big.
+ */
+ err = ntfs_attr_size_bounds_check(vol, ni->type, newsize);
+ if (err < 0) {
+ ntfs_error(sb, "%s: bounds check failed", __func__);
+ return err;
+ }
+
+ /* Save for future use. */
+ org_alloc_size = ni->allocated_size;
+ org_compressed_size = ni->itype.compressed.size;
+
+ /* The first cluster outside the new allocation. */
+ if (prealloc_size)
+ first_free_vcn = (prealloc_size + vol->cluster_size - 1) >>
+ vol->cluster_size_bits;
+ else
+ first_free_vcn = (newsize + vol->cluster_size - 1) >>
+ vol->cluster_size_bits;
+ if (first_free_vcn < 0)
+ return -EFBIG;
+
+ /*
+ * Compare the new allocation with the old one and only allocate
+ * clusters if there is a change.
+ */
+ if ((ni->allocated_size >> vol->cluster_size_bits) < first_free_vcn) {
+ err = ntfs_attr_map_whole_runlist(ni);
+ if (err) {
+ ntfs_error(sb, "ntfs_attr_map_whole_runlist failed");
+ return err;
+ }
+
+ /*
+ * If we extend $DATA attribute on NTFS 3+ volume, we can add
+ * sparse runs instead of real allocation of clusters.
+ */
+ if ((ni->type == AT_DATA && (vol->major_ver >= 3 || !NInoSparseDisabled(ni))) &&
+ (holes != HOLES_NO)) {
+ if (NInoCompressed(ni)) {
+ int last = 0, i = 0;
+ s64 alloc_size;
+ int more_entries =
+ round_up(first_free_vcn -
+ (ni->allocated_size >>
+ vol->cluster_size_bits),
+ ni->itype.compressed.block_clusters) /
+ ni->itype.compressed.block_clusters;
+
+ while (ni->runlist.rl[last].length)
+ last++;
+
+ rl = ntfs_rl_realloc(ni->runlist.rl, last + 1,
+ last + more_entries + 1);
+ if (IS_ERR(rl)) {
+ err = -ENOMEM;
+ goto put_err_out;
+ }
+
+ alloc_size = ni->allocated_size;
+ while (i++ < more_entries) {
+ rl[last].vcn = round_up(alloc_size, vol->cluster_size) >>
+ vol->cluster_size_bits;
+ rl[last].length = ni->itype.compressed.block_clusters -
+ (rl[last].vcn &
+ (ni->itype.compressed.block_clusters - 1));
+ rl[last].lcn = LCN_HOLE;
+ last++;
+ alloc_size += ni->itype.compressed.block_size;
+ }
+
+ rl[last].vcn = first_free_vcn;
+ rl[last].lcn = LCN_ENOENT;
+ rl[last].length = 0;
+
+ ni->runlist.rl = rl;
+ ni->runlist.count += more_entries;
+ } else {
+ rl = ntfs_malloc_nofs(sizeof(struct runlist_element) * 2);
+ if (!rl) {
+ err = -ENOMEM;
+ goto put_err_out;
+ }
+
+ rl[0].vcn = (ni->allocated_size >>
+ vol->cluster_size_bits);
+ rl[0].lcn = LCN_HOLE;
+ rl[0].length = first_free_vcn -
+ (ni->allocated_size >> vol->cluster_size_bits);
+ rl[1].vcn = first_free_vcn;
+ rl[1].lcn = LCN_ENOENT;
+ rl[1].length = 0;
+ }
+ } else {
+ /*
+ * Determine first after last LCN of attribute.
+ * We will start seek clusters from this LCN to avoid
+ * fragmentation. If there are no valid LCNs in the
+ * attribute let the cluster allocator choose the
+ * starting LCN.
+ */
+ lcn_seek_from = -1;
+ if (ni->runlist.rl->length) {
+ /* Seek to the last run list element. */
+ for (rl = ni->runlist.rl; (rl + 1)->length; rl++)
+ ;
+ /*
+ * If the last LCN is a hole or similar seek
+ * back to last valid LCN.
+ */
+ while (rl->lcn < 0 && rl != ni->runlist.rl)
+ rl--;
+ /*
+ * Only set lcn_seek_from it the LCN is valid.
+ */
+ if (rl->lcn >= 0)
+ lcn_seek_from = rl->lcn + rl->length;
+ }
+
+ rl = ntfs_cluster_alloc(vol, ni->allocated_size >>
+ vol->cluster_size_bits, first_free_vcn -
+ (ni->allocated_size >>
+ vol->cluster_size_bits), lcn_seek_from,
+ DATA_ZONE, false, false, false);
+ if (IS_ERR(rl)) {
+ ntfs_debug("Cluster allocation failed (%lld)",
+ (long long)first_free_vcn -
+ ((long long)ni->allocated_size >>
+ vol->cluster_size_bits));
+ return PTR_ERR(rl);
+ }
+ }
+
+ if (!NInoCompressed(ni)) {
+ /* Append new clusters to attribute runlist. */
+ rln = ntfs_runlists_merge(&ni->runlist, rl, 0, &new_rl_count);
+ if (IS_ERR(rln)) {
+ /* Failed, free just allocated clusters. */
+ ntfs_error(sb, "Run list merge failed");
+ ntfs_cluster_free_from_rl(vol, rl);
+ ntfs_free(rl);
+ return -EIO;
+ }
+ ni->runlist.rl = rln;
+ ni->runlist.count = new_rl_count;
+ }
+
+ /* Prepare to mapping pairs update. */
+ ni->allocated_size = first_free_vcn << vol->cluster_size_bits;
+ err = ntfs_attr_update_mapping_pairs(ni, 0);
+ if (err) {
+ ntfs_error(sb, "Mapping pairs update failed");
+ goto rollback;
+ }
+ }
+
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ err = -ENOMEM;
+ if (ni->allocated_size == org_alloc_size)
+ return err;
+ goto rollback;
+ }
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
+ 0, NULL, 0, ctx);
+ if (err) {
+ if (err == -ENOENT)
+ err = -EIO;
+ if (ni->allocated_size != org_alloc_size)
+ goto rollback;
+ goto put_err_out;
+ }
+
+ /* Update data size. */
+ ni->data_size = newsize;
+ ctx->attr->data.non_resident.data_size = cpu_to_le64(newsize);
+ /* Update data size in the index. */
+ if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
+ NInoSetFileNameDirty(ni);
+ /* Set the inode dirty so it is written out later. */
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ /* Done! */
+ ntfs_attr_put_search_ctx(ctx);
+ return 0;
+rollback:
+ /* Free allocated clusters. */
+ err2 = ntfs_cluster_free(ni, org_alloc_size >>
+ vol->cluster_size_bits, -1, ctx);
+ if (err2)
+ ntfs_error(sb, "Leaking clusters");
+
+ /* Now, truncate the runlist itself. */
+ down_write(&ni->runlist.lock);
+ err2 = ntfs_rl_truncate_nolock(vol, &ni->runlist, org_alloc_size >>
+ vol->cluster_size_bits);
+ up_write(&ni->runlist.lock);
+ if (err2) {
+ /*
+ * Failed to truncate the runlist, so just throw it away, it
+ * will be mapped afresh on next use.
+ */
+ ntfs_free(ni->runlist.rl);
+ ni->runlist.rl = NULL;
+ ntfs_error(sb, "Couldn't truncate runlist. Rollback failed");
+ } else {
+ /* Prepare to mapping pairs update. */
+ ni->allocated_size = org_alloc_size;
+ /* Restore mapping pairs. */
+ down_read(&ni->runlist.lock);
+ if (ntfs_attr_update_mapping_pairs(ni, 0))
+ ntfs_error(sb, "Failed to restore old mapping pairs");
+ up_read(&ni->runlist.lock);
+
+ if (NInoSparse(ni) || NInoCompressed(ni)) {
+ ni->itype.compressed.size = org_compressed_size;
+ VFS_I(base_ni)->i_blocks = ni->itype.compressed.size >> 9;
+ } else
+ VFS_I(base_ni)->i_blocks = ni->allocated_size >> 9;
+ }
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+put_err_out:
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+/**
+ * ntfs_resident_attr_resize - resize a resident, open ntfs attribute
+ * @attr_ni: resident ntfs inode to resize
+ * @prealloc_size: preallocation size (in bytes) to which to resize the attribute
+ * @newsize: new size (in bytes) to which to resize the attribute
+ *
+ * Change the size of a resident, open ntfs attribute @na to @newsize bytes.
+ */
+static int ntfs_resident_attr_resize(struct ntfs_inode *attr_ni, const s64 newsize,
+ const s64 prealloc_size, unsigned int holes)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ struct ntfs_volume *vol = attr_ni->vol;
+ struct super_block *sb = vol->sb;
+ int err = -EIO;
+ struct ntfs_inode *base_ni, *ext_ni = NULL;
+
+attr_resize_again:
+ ntfs_debug("Inode 0x%llx attr 0x%x new size %lld\n",
+ (unsigned long long)attr_ni->mft_no, attr_ni->type,
+ (long long)newsize);
+
+ if (NInoAttr(attr_ni))
+ base_ni = attr_ni->ext.base_ntfs_ino;
+ else
+ base_ni = attr_ni;
+
+ /* Get the attribute record that needs modification. */
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ ntfs_error(sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+ err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
+ 0, 0, NULL, 0, ctx);
+ if (err) {
+ ntfs_error(sb, "ntfs_attr_lookup failed");
+ goto put_err_out;
+ }
+
+ /*
+ * Check the attribute type and the corresponding minimum and maximum
+ * sizes against @newsize and fail if @newsize is out of bounds.
+ */
+ err = ntfs_attr_size_bounds_check(vol, attr_ni->type, newsize);
+ if (err) {
+ if (err == -ENOENT)
+ err = -EIO;
+ ntfs_debug("%s: bounds check failed", __func__);
+ goto put_err_out;
+ }
+ /*
+ * If @newsize is bigger than the mft record we need to make the
+ * attribute non-resident if the attribute type supports it. If it is
+ * smaller we can go ahead and attempt the resize.
+ */
+ if (newsize < vol->mft_record_size) {
+ /* Perform the resize of the attribute record. */
+ err = ntfs_resident_attr_value_resize(ctx->mrec, ctx->attr,
+ newsize);
+ if (!err) {
+ /* Update attribute size everywhere. */
+ attr_ni->data_size = attr_ni->initialized_size = newsize;
+ attr_ni->allocated_size = (newsize + 7) & ~7;
+ if (NInoCompressed(attr_ni) || NInoSparse(attr_ni))
+ attr_ni->itype.compressed.size = attr_ni->allocated_size;
+ if (attr_ni->type == AT_DATA && attr_ni->name == AT_UNNAMED)
+ NInoSetFileNameDirty(attr_ni);
+ goto resize_done;
+ }
+
+ /* Prefer AT_INDEX_ALLOCATION instead of AT_ATTRIBUTE_LIST */
+ if (err == -ENOSPC && ctx->attr->type == AT_INDEX_ROOT)
+ goto put_err_out;
+
+ }
+ /* There is not enough space in the mft record to perform the resize. */
+
+ /* Make the attribute non-resident if possible. */
+ err = ntfs_attr_make_non_resident(attr_ni,
+ le32_to_cpu(ctx->attr->data.resident.value_length));
+ if (!err) {
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ ntfs_attr_put_search_ctx(ctx);
+ /* Resize non-resident attribute */
+ return ntfs_non_resident_attr_expand(attr_ni, newsize, prealloc_size, holes);
+ } else if (err != -ENOSPC && err != -EPERM) {
+ ntfs_error(sb, "Failed to make attribute non-resident");
+ goto put_err_out;
+ }
+
+ /* Try to make other attributes non-resident and retry each time. */
+ ntfs_attr_reinit_search_ctx(ctx);
+ while (!(err = ntfs_attr_lookup(AT_UNUSED, NULL, 0, 0, 0, NULL, 0, ctx))) {
+ struct inode *tvi;
+ struct attr_record *a;
+
+ a = ctx->attr;
+ if (a->non_resident || a->type == AT_ATTRIBUTE_LIST)
+ continue;
+
+ if (ntfs_attr_can_be_non_resident(vol, a->type))
+ continue;
+
+ /*
+ * Check out whether convert is reasonable. Assume that mapping
+ * pairs will take 8 bytes.
+ */
+ if (le32_to_cpu(a->length) <= (sizeof(struct attr_record) - sizeof(s64)) +
+ ((a->name_length * sizeof(__le16) + 7) & ~7) + 8)
+ continue;
+
+ if (a->type == AT_DATA)
+ tvi = ntfs_iget(sb, base_ni->mft_no);
+ else
+ tvi = ntfs_attr_iget(VFS_I(base_ni), a->type,
+ (__le16 *)((u8 *)a + le16_to_cpu(a->name_offset)),
+ a->name_length);
+ if (IS_ERR(tvi)) {
+ ntfs_error(sb, "Couldn't open attribute");
+ continue;
+ }
+
+ if (ntfs_attr_make_non_resident(NTFS_I(tvi),
+ le32_to_cpu(ctx->attr->data.resident.value_length))) {
+ iput(tvi);
+ continue;
+ }
+
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ iput(tvi);
+ ntfs_attr_put_search_ctx(ctx);
+ goto attr_resize_again;
+ }
+
+ /* Check whether error occurred. */
+ if (err != -ENOENT) {
+ ntfs_error(sb, "%s: Attribute lookup failed 1", __func__);
+ goto put_err_out;
+ }
+
+ /*
+ * The standard information and attribute list attributes can't be
+ * moved out from the base MFT record, so try to move out others.
+ */
+ if (attr_ni->type == AT_STANDARD_INFORMATION ||
+ attr_ni->type == AT_ATTRIBUTE_LIST) {
+ ntfs_attr_put_search_ctx(ctx);
+
+ if (!NInoAttrList(base_ni)) {
+ err = ntfs_inode_add_attrlist(base_ni);
+ if (err)
+ return err;
+ }
+
+ err = ntfs_inode_free_space(base_ni, sizeof(struct attr_record));
+ if (err) {
+ err = -ENOSPC;
+ ntfs_error(sb,
+ "Couldn't free space in the MFT record to make attribute list non resident");
+ return err;
+ }
+ err = ntfs_attrlist_update(base_ni);
+ if (err)
+ return err;
+ goto attr_resize_again;
+ }
+
+ /*
+ * Move the attribute to a new mft record, creating an attribute list
+ * attribute or modifying it if it is already present.
+ */
+
+ /* Point search context back to attribute which we need resize. */
+ ntfs_attr_reinit_search_ctx(ctx);
+ err = ntfs_attr_lookup(attr_ni->type, attr_ni->name, attr_ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx);
+ if (err) {
+ ntfs_error(sb, "%s: Attribute lookup failed 2", __func__);
+ goto put_err_out;
+ }
+
+ /*
+ * Check whether attribute is already single in this MFT record.
+ * 8 added for the attribute terminator.
+ */
+ if (le32_to_cpu(ctx->mrec->bytes_in_use) ==
+ le16_to_cpu(ctx->mrec->attrs_offset) + le32_to_cpu(ctx->attr->length) + 8) {
+ err = -ENOSPC;
+ ntfs_debug("MFT record is filled with one attribute\n");
+ goto put_err_out;
+ }
+
+ /* Add attribute list if not present. */
+ if (!NInoAttrList(base_ni)) {
+ ntfs_attr_put_search_ctx(ctx);
+ err = ntfs_inode_add_attrlist(base_ni);
+ if (err)
+ return err;
+ goto attr_resize_again;
+ }
+
+ /* Allocate new mft record. */
+ err = ntfs_mft_record_alloc(base_ni->vol, 0, &ext_ni, base_ni, NULL);
+ if (err) {
+ ntfs_error(sb, "Couldn't allocate MFT record");
+ goto put_err_out;
+ }
+ unmap_mft_record(ext_ni);
+
+ /* Move attribute to it. */
+ err = ntfs_attr_record_move_to(ctx, ext_ni);
+ if (err) {
+ ntfs_error(sb, "Couldn't move attribute to new MFT record");
+ err = -ENOMEM;
+ goto put_err_out;
+ }
+
+ err = ntfs_attrlist_update(base_ni);
+ if (err < 0)
+ goto put_err_out;
+
+ ntfs_attr_put_search_ctx(ctx);
+ /* Try to perform resize once again. */
+ goto attr_resize_again;
+
+resize_done:
+ /*
+ * Set the inode (and its base inode if it exists) dirty so it is
+ * written out later.
+ */
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ ntfs_attr_put_search_ctx(ctx);
+ return 0;
+
+put_err_out:
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+int __ntfs_attr_truncate_vfs(struct ntfs_inode *ni, const s64 newsize,
+ const s64 i_size)
+{
+ int err = 0;
+
+ if (newsize < 0 ||
+ (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
+ ntfs_debug("Invalid arguments passed.\n");
+ return -EINVAL;
+ }
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
+ (unsigned long long)ni->mft_no, ni->type, newsize);
+
+ if (NInoNonResident(ni)) {
+ if (newsize > i_size) {
+ down_write(&ni->runlist.lock);
+ err = ntfs_non_resident_attr_expand(ni, newsize, 0, HOLES_OK);
+ up_write(&ni->runlist.lock);
+ } else
+ err = ntfs_non_resident_attr_shrink(ni, newsize);
+ } else
+ err = ntfs_resident_attr_resize(ni, newsize, 0, HOLES_OK);
+ ntfs_debug("Return status %d\n", err);
+ return err;
+}
+
+int ntfs_attr_expand(struct ntfs_inode *ni, const s64 newsize, const s64 prealloc_size)
+{
+ int err = 0;
+
+ if (newsize < 0 ||
+ (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
+ ntfs_debug("Invalid arguments passed.\n");
+ return -EINVAL;
+ }
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
+ (unsigned long long)ni->mft_no, ni->type, newsize);
+
+ if (ni->data_size == newsize) {
+ ntfs_debug("Size is already ok\n");
+ return 0;
+ }
+
+ /*
+ * Encrypted attributes are not supported. We return access denied,
+ * which is what Windows NT4 does, too.
+ */
+ if (NInoEncrypted(ni)) {
+ pr_err("Failed to truncate encrypted attribute");
+ return -EACCES;
+ }
+
+ if (NInoNonResident(ni)) {
+ if (newsize > ni->data_size)
+ err = ntfs_non_resident_attr_expand(ni, newsize, prealloc_size, HOLES_OK);
+ } else
+ err = ntfs_resident_attr_resize(ni, newsize, prealloc_size, HOLES_OK);
+ if (!err)
+ i_size_write(VFS_I(ni), newsize);
+ ntfs_debug("Return status %d\n", err);
+ return err;
+}
+
+/**
+ * ntfs_attr_truncate_i - resize an ntfs attribute
+ * @ni: open ntfs inode to resize
+ * @newsize: new size (in bytes) to which to resize the attribute
+ *
+ * Change the size of an open ntfs attribute @na to @newsize bytes. If the
+ * attribute is made bigger and the attribute is resident the newly
+ * "allocated" space is cleared and if the attribute is non-resident the
+ * newly allocated space is marked as not initialised and no real allocation
+ * on disk is performed.
+ */
+int ntfs_attr_truncate_i(struct ntfs_inode *ni, const s64 newsize, unsigned int holes)
+{
+ int err;
+
+ if (newsize < 0 ||
+ (ni->mft_no == FILE_MFT && ni->type == AT_DATA)) {
+ ntfs_debug("Invalid arguments passed.\n");
+ return -EINVAL;
+ }
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x, size %lld\n",
+ (unsigned long long)ni->mft_no, ni->type, newsize);
+
+ if (ni->data_size == newsize) {
+ ntfs_debug("Size is already ok\n");
+ return 0;
+ }
+
+ /*
+ * Encrypted attributes are not supported. We return access denied,
+ * which is what Windows NT4 does, too.
+ */
+ if (NInoEncrypted(ni)) {
+ pr_err("Failed to truncate encrypted attribute");
+ return -EACCES;
+ }
+
+ if (NInoCompressed(ni)) {
+ pr_err("Failed to truncate compressed attribute");
+ return -EOPNOTSUPP;
+ }
+
+ if (NInoNonResident(ni)) {
+ if (newsize > ni->data_size)
+ err = ntfs_non_resident_attr_expand(ni, newsize, 0, holes);
+ else
+ err = ntfs_non_resident_attr_shrink(ni, newsize);
+ } else
+ err = ntfs_resident_attr_resize(ni, newsize, 0, holes);
+ ntfs_debug("Return status %d\n", err);
+ return err;
+}
+
+/*
+ * Resize an attribute, creating a hole if relevant
+ */
+int ntfs_attr_truncate(struct ntfs_inode *ni, const s64 newsize)
+{
+ return ntfs_attr_truncate_i(ni, newsize, HOLES_OK);
+}
+
+int ntfs_attr_map_cluster(struct ntfs_inode *ni, s64 vcn_start, s64 *lcn_start,
+ s64 *lcn_count, s64 max_clu_count, bool *balloc, bool update_mp,
+ bool skip_holes)
+{
+ struct ntfs_volume *vol = ni->vol;
+ struct ntfs_attr_search_ctx *ctx;
+ struct runlist_element *rl, *rlc;
+ s64 vcn = vcn_start, lcn, clu_count;
+ s64 lcn_seek_from = -1;
+ int err = 0;
+ size_t new_rl_count;
+
+ BUG_ON(!NInoNonResident(ni));
+
+ err = ntfs_attr_map_whole_runlist(ni);
+ if (err)
+ return err;
+
+ if (NInoAttr(ni))
+ ctx = ntfs_attr_get_search_ctx(ni->ext.base_ntfs_ino, NULL);
+ else
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ ntfs_error(vol->sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+
+ err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, vcn, NULL, 0, ctx);
+ if (err) {
+ ntfs_error(vol->sb,
+ "ntfs_attr_lookup failed, ntfs inode(mft_no : %ld) type : 0x%x, err : %d",
+ ni->mft_no, ni->type, err);
+ goto out;
+ }
+
+ rl = ntfs_attr_find_vcn_nolock(ni, vcn, ctx);
+ if (IS_ERR(rl)) {
+ ntfs_error(vol->sb, "Failed to find run after mapping runlist.");
+ err = PTR_ERR(rl);
+ goto out;
+ }
+
+ lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
+ clu_count = min(max_clu_count, rl->length - (vcn - rl->vcn));
+ if (lcn >= LCN_HOLE) {
+ if (lcn > LCN_DELALLOC ||
+ (lcn == LCN_HOLE && skip_holes)) {
+ *lcn_start = lcn;
+ *lcn_count = clu_count;
+ *balloc = false;
+ goto out;
+ }
+ } else {
+ BUG_ON(lcn == LCN_RL_NOT_MAPPED);
+ if (lcn == LCN_ENOENT)
+ err = -ENOENT;
+ else
+ err = -EIO;
+ goto out;
+ }
+
+ /* Search backwards to find the best lcn to start seek from. */
+ rlc = rl;
+ while (rlc->vcn) {
+ rlc--;
+ if (rlc->lcn >= 0) {
+ /*
+ * avoid fragmenting a compressed file
+ * Windows does not do that, and that may
+ * not be desirable for files which can
+ * be updated
+ */
+ if (NInoCompressed(ni))
+ lcn_seek_from = rlc->lcn + rlc->length;
+ else
+ lcn_seek_from = rlc->lcn + (vcn - rlc->vcn);
+ break;
+ }
+ }
+
+ if (lcn_seek_from == -1) {
+ /* Backwards search failed, search forwards. */
+ rlc = rl;
+ while (rlc->length) {
+ rlc++;
+ if (rlc->lcn >= 0) {
+ lcn_seek_from = rlc->lcn - (rlc->vcn - vcn);
+ if (lcn_seek_from < -1)
+ lcn_seek_from = -1;
+ break;
+ }
+ }
+ }
+
+ if (lcn_seek_from == -1 && ni->lcn_seek_trunc != LCN_RL_NOT_MAPPED) {
+ lcn_seek_from = ni->lcn_seek_trunc;
+ ni->lcn_seek_trunc = LCN_RL_NOT_MAPPED;
+ }
+
+ rlc = ntfs_cluster_alloc(vol, vcn, clu_count, lcn_seek_from, DATA_ZONE,
+ false, true, true);
+ if (IS_ERR(rlc)) {
+ err = PTR_ERR(rlc);
+ goto out;
+ }
+
+ BUG_ON(rlc->vcn != vcn);
+ lcn = rlc->lcn;
+ clu_count = rlc->length;
+
+ rl = ntfs_runlists_merge(&ni->runlist, rlc, 0, &new_rl_count);
+ if (IS_ERR(rl)) {
+ ntfs_error(vol->sb, "Failed to merge runlists");
+ err = PTR_ERR(rl);
+ if (ntfs_cluster_free_from_rl(vol, rlc))
+ ntfs_error(vol->sb, "Failed to free hot clusters.");
+ ntfs_free(rlc);
+ goto out;
+ }
+ ni->runlist.rl = rl;
+ ni->runlist.count = new_rl_count;
+
+ if (!update_mp) {
+ if (((long long)atomic64_read(&vol->free_clusters) * 100) /
+ (long)vol->nr_clusters <= 5)
+ update_mp = true;
+ }
+
+ if (update_mp) {
+ ntfs_attr_reinit_search_ctx(ctx);
+ err = ntfs_attr_update_mapping_pairs(ni, 0);
+ if (err) {
+ int err2;
+
+ err2 = ntfs_cluster_free(ni, vcn, clu_count, ctx);
+ if (err2 < 0)
+ ntfs_error(vol->sb,
+ "Failed to free cluster allocation. Leaving inconstant metadata.\n");
+ goto out;
+ }
+ } else {
+ VFS_I(ni)->i_blocks += clu_count << (vol->cluster_size_bits - 9);
+ NInoSetRunlistDirty(ni);
+ mark_mft_record_dirty(ni);
+ }
+
+ *lcn_start = lcn;
+ *lcn_count = clu_count;
+ *balloc = true;
+out:
+ ntfs_attr_put_search_ctx(ctx);
+ return err;
+}
+
+/**
+ * ntfs_attr_rm - remove attribute from ntfs inode
+ * @ni: opened ntfs attribute to delete
+ *
+ * Remove attribute and all it's extents from ntfs inode. If attribute was non
+ * resident also free all clusters allocated by attribute.
+ */
+int ntfs_attr_rm(struct ntfs_inode *ni)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ int err = 0, ret = 0;
+ struct ntfs_inode *base_ni;
+ struct super_block *sb = ni->vol->sb;
+
+ if (NInoAttr(ni))
+ base_ni = ni->ext.base_ntfs_ino;
+ else
+ base_ni = ni;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
+ (long long) ni->mft_no, ni->type);
+
+ /* Free cluster allocation. */
+ if (NInoNonResident(ni)) {
+ struct ntfs_attr_search_ctx *ctx;
+
+ err = ntfs_attr_map_whole_runlist(ni);
+ if (err)
+ return err;
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ ntfs_error(sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+
+ ret = ntfs_cluster_free(ni, 0, -1, ctx);
+ if (ret < 0)
+ ntfs_error(sb,
+ "Failed to free cluster allocation. Leaving inconstant metadata.\n");
+ ntfs_attr_put_search_ctx(ctx);
+ }
+
+ /* Search for attribute extents and remove them all. */
+ ctx = ntfs_attr_get_search_ctx(base_ni, NULL);
+ if (!ctx) {
+ ntfs_error(sb, "%s: Failed to get search context", __func__);
+ return -ENOMEM;
+ }
+ while (!(err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
+ CASE_SENSITIVE, 0, NULL, 0, ctx))) {
+ err = ntfs_attr_record_rm(ctx);
+ if (err) {
+ ntfs_error(sb,
+ "Failed to remove attribute extent. Leaving inconstant metadata.\n");
+ ret = err;
+ }
+ ntfs_attr_reinit_search_ctx(ctx);
+ }
+ ntfs_attr_put_search_ctx(ctx);
+ if (err != -ENOENT) {
+ ntfs_error(sb, "Attribute lookup failed. Probably leaving inconstant metadata.\n");
+ ret = err;
+ }
+
+ return ret;
+}
+
+int ntfs_attr_exist(struct ntfs_inode *ni, const __le32 type, __le16 *name,
+ u32 name_len)
+{
+ struct ntfs_attr_search_ctx *ctx;
+ int ret;
+
+ ntfs_debug("Entering\n");
+
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ ntfs_error(ni->vol->sb, "%s: Failed to get search context",
+ __func__);
+ return 0;
+ }
+
+ ret = ntfs_attr_lookup(type, name, name_len, CASE_SENSITIVE,
+ 0, NULL, 0, ctx);
+ ntfs_attr_put_search_ctx(ctx);
+
+ return !ret;
+}
+
+int ntfs_attr_remove(struct ntfs_inode *ni, const __le32 type, __le16 *name,
+ u32 name_len)
+{
+ struct super_block *sb;
+ int err;
+ struct inode *attr_vi;
+ struct ntfs_inode *attr_ni;
+
+ ntfs_debug("Entering\n");
+
+ sb = ni->vol->sb;
+ if (!ni) {
+ ntfs_error(sb, "NULL inode pointer\n");
+ return -EINVAL;
+ }
+
+ attr_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
+ if (IS_ERR(attr_vi)) {
+ err = PTR_ERR(attr_vi);
+ ntfs_error(sb, "Failed to open attribute 0x%02x of inode 0x%llx",
+ type, (unsigned long long)ni->mft_no);
+ return err;
+ }
+ attr_ni = NTFS_I(attr_vi);
+
+ err = ntfs_attr_rm(attr_ni);
+ if (err)
+ ntfs_error(sb, "Failed to remove attribute 0x%02x of inode 0x%llx",
+ type, (unsigned long long)ni->mft_no);
+ iput(attr_vi);
+ return err;
+}
+
+/**
+ * ntfs_attr_readall - read the entire data from an ntfs attribute
+ * @ni: open ntfs inode in which the ntfs attribute resides
+ * @type: attribute type
+ * @name: attribute name in little endian Unicode or AT_UNNAMED or NULL
+ * @name_len: length of attribute @name in Unicode characters (if @name given)
+ * @data_size: if non-NULL then store here the data size
+ *
+ * This function will read the entire content of an ntfs attribute.
+ * If @name is AT_UNNAMED then look specifically for an unnamed attribute.
+ * If @name is NULL then the attribute could be either named or not.
+ * In both those cases @name_len is not used at all.
+ *
+ * On success a buffer is allocated with the content of the attribute
+ * and which needs to be freed when it's not needed anymore. If the
+ * @data_size parameter is non-NULL then the data size is set there.
+ */
+void *ntfs_attr_readall(struct ntfs_inode *ni, const __le32 type,
+ __le16 *name, u32 name_len, s64 *data_size)
+{
+ struct ntfs_inode *bmp_ni;
+ struct inode *bmp_vi;
+ void *data, *ret = NULL;
+ s64 size;
+ struct super_block *sb = ni->vol->sb;
+
+ ntfs_debug("Entering\n");
+
+ bmp_vi = ntfs_attr_iget(VFS_I(ni), type, name, name_len);
+ if (IS_ERR(bmp_vi)) {
+ ntfs_debug("ntfs_attr_iget failed");
+ goto err_exit;
+ }
+ bmp_ni = NTFS_I(bmp_vi);
+
+ data = ntfs_malloc_nofs(bmp_ni->data_size);
+ if (!data) {
+ ntfs_error(sb, "ntfs_malloc_nofs failed");
+ goto out;
+ }
+
+ size = ntfs_inode_attr_pread(VFS_I(bmp_ni), 0, bmp_ni->data_size,
+ (u8 *)data);
+ if (size != bmp_ni->data_size) {
+ ntfs_error(sb, "ntfs_attr_pread failed");
+ ntfs_free(data);
+ goto out;
+ }
+ ret = data;
+ if (data_size)
+ *data_size = size;
+out:
+ iput(bmp_vi);
+err_exit:
+ ntfs_debug("\n");
+ return ret;
+}
+
+int ntfs_non_resident_attr_insert_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
+{
+ struct ntfs_volume *vol = ni->vol;
+ struct runlist_element *hole_rl, *rl;
+ struct ntfs_attr_search_ctx *ctx;
+ int ret;
+ size_t new_rl_count;
+
+ if (NInoAttr(ni) || ni->type != AT_DATA)
+ return -EOPNOTSUPP;
+ if (start_vcn > (ni->allocated_size >> vol->cluster_size_bits))
+ return -EINVAL;
+
+ hole_rl = ntfs_malloc_nofs(sizeof(*hole_rl) * 2);
+ if (!hole_rl)
+ return -ENOMEM;
+ hole_rl[0].vcn = start_vcn;
+ hole_rl[0].lcn = LCN_HOLE;
+ hole_rl[0].length = len;
+ hole_rl[1].vcn = start_vcn + len;
+ hole_rl[1].lcn = LCN_ENOENT;
+ hole_rl[1].length = 0;
+
+ down_write(&ni->runlist.lock);
+ ret = ntfs_attr_map_whole_runlist(ni);
+ if (ret) {
+ up_write(&ni->runlist.lock);
+ return ret;
+ }
+
+ rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
+ if (!rl) {
+ up_write(&ni->runlist.lock);
+ ntfs_free(hole_rl);
+ return -EIO;
+ }
+
+ rl = ntfs_rl_insert_range(ni->runlist.rl, (int)ni->runlist.count,
+ hole_rl, 1, &new_rl_count);
+ if (IS_ERR(rl)) {
+ up_write(&ni->runlist.lock);
+ ntfs_free(hole_rl);
+ return PTR_ERR(rl);
+ }
+ ni->runlist.rl = rl;
+ ni->runlist.count = new_rl_count;
+
+ ni->allocated_size += len << vol->cluster_size_bits;
+ ni->data_size += len << vol->cluster_size_bits;
+ if ((start_vcn << vol->cluster_size_bits) < ni->initialized_size)
+ ni->initialized_size += len << vol->cluster_size_bits;
+ ret = ntfs_attr_update_mapping_pairs(ni, 0);
+ up_write(&ni->runlist.lock);
+ if (ret)
+ return ret;
+
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ ret = -ENOMEM;
+ return ret;
+ }
+
+ ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
+ 0, NULL, 0, ctx);
+ if (ret) {
+ ntfs_attr_put_search_ctx(ctx);
+ return ret;
+ }
+
+ ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
+ ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
+ if (ni->type == AT_DATA && ni->name == AT_UNNAMED)
+ NInoSetFileNameDirty(ni);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+ ntfs_attr_put_search_ctx(ctx);
+ return ret;
+}
+
+int ntfs_non_resident_attr_collapse_range(struct ntfs_inode *ni, s64 start_vcn, s64 len)
+{
+ struct ntfs_volume *vol = ni->vol;
+ struct runlist_element *punch_rl, *rl;
+ struct ntfs_attr_search_ctx *ctx = NULL;
+ s64 end_vcn;
+ int dst_cnt;
+ int ret;
+ size_t new_rl_cnt;
+
+ if (NInoAttr(ni) || ni->type != AT_DATA)
+ return -EOPNOTSUPP;
+
+ end_vcn = ni->allocated_size >> vol->cluster_size_bits;
+ if (start_vcn >= end_vcn)
+ return -EINVAL;
+
+ down_write(&ni->runlist.lock);
+ ret = ntfs_attr_map_whole_runlist(ni);
+ if (ret)
+ return ret;
+
+ len = min(len, end_vcn - start_vcn);
+ for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
+ dst_cnt++;
+ rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
+ if (!rl) {
+ up_write(&ni->runlist.lock);
+ return -EIO;
+ }
+
+ rl = ntfs_rl_collapse_range(ni->runlist.rl, dst_cnt + 1,
+ start_vcn, len, &punch_rl, &new_rl_cnt);
+ if (IS_ERR(rl)) {
+ up_write(&ni->runlist.lock);
+ return PTR_ERR(rl);
+ }
+ ni->runlist.rl = rl;
+ ni->runlist.count = new_rl_cnt;
+
+ ni->allocated_size -= len << vol->cluster_size_bits;
+ if (ni->data_size > (start_vcn << vol->cluster_size_bits)) {
+ if (ni->data_size > (start_vcn + len) << vol->cluster_size_bits)
+ ni->data_size -= len << vol->cluster_size_bits;
+ else
+ ni->data_size = start_vcn << vol->cluster_size_bits;
+ }
+ if (ni->initialized_size > (start_vcn << vol->cluster_size_bits)) {
+ if (ni->initialized_size >
+ (start_vcn + len) << vol->cluster_size_bits)
+ ni->initialized_size -= len << vol->cluster_size_bits;
+ else
+ ni->initialized_size = start_vcn << vol->cluster_size_bits;
+ }
+
+ if (ni->allocated_size > 0) {
+ ret = ntfs_attr_update_mapping_pairs(ni, 0);
+ if (ret) {
+ up_write(&ni->runlist.lock);
+ goto out_rl;
+ }
+ }
+ up_write(&ni->runlist.lock);
+
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ ret = -ENOMEM;
+ goto out_rl;
+ }
+
+ ret = ntfs_attr_lookup(ni->type, ni->name, ni->name_len, CASE_SENSITIVE,
+ 0, NULL, 0, ctx);
+ if (ret)
+ goto out_ctx;
+
+ ctx->attr->data.non_resident.data_size = cpu_to_le64(ni->data_size);
+ ctx->attr->data.non_resident.initialized_size = cpu_to_le64(ni->initialized_size);
+ if (ni->allocated_size == 0)
+ ntfs_attr_make_resident(ni, ctx);
+ mark_mft_record_dirty(ctx->ntfs_ino);
+
+ ret = ntfs_cluster_free_from_rl(vol, punch_rl);
+ if (ret)
+ ntfs_error(vol->sb, "Freeing of clusters failed");
+out_ctx:
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+out_rl:
+ ntfs_free(punch_rl);
+ mark_mft_record_dirty(ni);
+ return ret;
+}
+
+int ntfs_non_resident_attr_punch_hole(struct ntfs_inode *ni, s64 start_vcn, s64 len)
+{
+ struct ntfs_volume *vol = ni->vol;
+ struct runlist_element *punch_rl, *rl;
+ s64 end_vcn;
+ int dst_cnt;
+ int ret;
+ size_t new_rl_count;
+
+ if (NInoAttr(ni) || ni->type != AT_DATA)
+ return -EOPNOTSUPP;
+
+ end_vcn = ni->allocated_size >> vol->cluster_size_bits;
+ if (start_vcn >= end_vcn)
+ return -EINVAL;
+
+ down_write(&ni->runlist.lock);
+ ret = ntfs_attr_map_whole_runlist(ni);
+ if (ret) {
+ up_write(&ni->runlist.lock);
+ return ret;
+ }
+
+ len = min(len, end_vcn - start_vcn + 1);
+ for (rl = ni->runlist.rl, dst_cnt = 0; rl && rl->length; rl++)
+ dst_cnt++;
+ rl = ntfs_rl_find_vcn_nolock(ni->runlist.rl, start_vcn);
+ if (!rl) {
+ up_write(&ni->runlist.lock);
+ return -EIO;
+ }
+
+ rl = ntfs_rl_punch_hole(ni->runlist.rl, dst_cnt + 1,
+ start_vcn, len, &punch_rl, &new_rl_count);
+ if (IS_ERR(rl)) {
+ up_write(&ni->runlist.lock);
+ return PTR_ERR(rl);
+ }
+ ni->runlist.rl = rl;
+ ni->runlist.count = new_rl_count;
+
+ ret = ntfs_attr_update_mapping_pairs(ni, 0);
+ up_write(&ni->runlist.lock);
+ if (ret) {
+ ntfs_free(punch_rl);
+ return ret;
+ }
+
+ ret = ntfs_cluster_free_from_rl(vol, punch_rl);
+ if (ret)
+ ntfs_error(vol->sb, "Freeing of clusters failed");
+
+ ntfs_free(punch_rl);
+ mark_mft_record_dirty(ni);
+ return ret;
+}
+
+int ntfs_attr_fallocate(struct ntfs_inode *ni, loff_t start, loff_t byte_len, bool keep_size)
+{
+ struct ntfs_volume *vol = ni->vol;
+ struct mft_record *mrec;
+ struct ntfs_attr_search_ctx *ctx;
+ s64 old_data_size;
+ s64 vcn_start, vcn_end, vcn_uninit, vcn, try_alloc_cnt;
+ s64 lcn, alloc_cnt;
+ int err = 0;
+ struct runlist_element *rl;
+ bool balloc;
+
+ if (NInoAttr(ni) || ni->type != AT_DATA)
+ return -EINVAL;
+
+ 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;
+ }
+
+ mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
+ mrec = map_mft_record(ni);
+ if (IS_ERR(mrec)) {
+ mutex_unlock(&ni->mrec_lock);
+ return PTR_ERR(mrec);
+ }
+
+ ctx = ntfs_attr_get_search_ctx(ni, mrec);
+ if (!ctx) {
+ err = -ENOMEM;
+ goto out_unmap;
+ }
+
+ err = ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx);
+ if (err) {
+ err = -EIO;
+ goto out_unmap;
+ }
+
+ old_data_size = ni->data_size;
+ if (start + byte_len > ni->data_size) {
+ err = ntfs_attr_truncate(ni, start + byte_len);
+ if (err)
+ goto out_unmap;
+ if (keep_size) {
+ ntfs_attr_reinit_search_ctx(ctx);
+ err = ntfs_attr_lookup(AT_DATA, AT_UNNAMED, 0, 0, 0, NULL, 0, ctx);
+ if (err) {
+ err = -EIO;
+ goto out_unmap;
+ }
+ ni->data_size = old_data_size;
+ if (NInoNonResident(ni))
+ ctx->attr->data.non_resident.data_size =
+ cpu_to_le64(old_data_size);
+ else
+ ctx->attr->data.resident.value_length =
+ cpu_to_le64(old_data_size);
+ mark_mft_record_dirty(ni);
+ }
+ }
+
+ ntfs_attr_put_search_ctx(ctx);
+ unmap_mft_record(ni);
+ mutex_unlock(&ni->mrec_lock);
+
+ if (!NInoNonResident(ni))
+ goto out;
+
+ vcn_start = (s64)(start >> vol->cluster_size_bits);
+ vcn_end = (s64)(round_up(start + byte_len, vol->cluster_size) >>
+ vol->cluster_size_bits);
+ vcn_uninit = (s64)(round_up(ni->initialized_size, vol->cluster_size) /
+ vol->cluster_size);
+ vcn_uninit = min_t(s64, vcn_uninit, vcn_end);
+
+ /*
+ * we have to allocate clusters for holes and delayed within initialized_size,
+ * and zero out the clusters only for the holes.
+ */
+ vcn = vcn_start;
+ while (vcn < vcn_uninit) {
+ down_read(&ni->runlist.lock);
+ rl = ntfs_attr_find_vcn_nolock(ni, vcn, NULL);
+ up_read(&ni->runlist.lock);
+ if (IS_ERR(rl)) {
+ err = PTR_ERR(rl);
+ goto out;
+ }
+
+ if (rl->lcn > 0) {
+ vcn += rl->length - (vcn - rl->vcn);
+ } else if (rl->lcn == LCN_DELALLOC || rl->lcn == LCN_HOLE) {
+ try_alloc_cnt = min(rl->length - (vcn - rl->vcn),
+ vcn_uninit - vcn);
+
+ if (rl->lcn == LCN_DELALLOC) {
+ vcn += try_alloc_cnt;
+ continue;
+ }
+
+ while (try_alloc_cnt > 0) {
+ mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
+ down_write(&ni->runlist.lock);
+ err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
+ try_alloc_cnt, &balloc, false, false);
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ if (err)
+ goto out;
+
+ err = ntfs_zeroed_clusters(VFS_I(ni), lcn, alloc_cnt);
+ if (err > 0)
+ goto out;
+
+ if (signal_pending(current))
+ goto out;
+
+ vcn += alloc_cnt;
+ try_alloc_cnt -= alloc_cnt;
+ }
+ } else {
+ err = -EIO;
+ goto out;
+ }
+ }
+
+ /* allocate clusters outside of initialized_size */
+ try_alloc_cnt = vcn_end - vcn;
+ while (try_alloc_cnt > 0) {
+ mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
+ down_write(&ni->runlist.lock);
+ err = ntfs_attr_map_cluster(ni, vcn, &lcn, &alloc_cnt,
+ try_alloc_cnt, &balloc, false, false);
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ if (err || signal_pending(current))
+ goto out;
+
+ vcn += alloc_cnt;
+ try_alloc_cnt -= alloc_cnt;
+ cond_resched();
+ }
+
+ if (NInoRunlistDirty(ni)) {
+ mutex_lock_nested(&ni->mrec_lock, NTFS_INODE_MUTEX_NORMAL);
+ down_write(&ni->runlist.lock);
+ err = ntfs_attr_update_mapping_pairs(ni, 0);
+ if (err)
+ ntfs_error(ni->vol->sb, "Updating mapping pairs failed");
+ else
+ NInoClearRunlistDirty(ni);
+ up_write(&ni->runlist.lock);
+ mutex_unlock(&ni->mrec_lock);
+ }
+ return err;
+out_unmap:
+ if (ctx)
+ ntfs_attr_put_search_ctx(ctx);
+ unmap_mft_record(ni);
+ mutex_unlock(&ni->mrec_lock);
+out:
+ return err >= 0 ? 0 : err;
+}
diff --git a/fs/ntfsplus/attrlist.c b/fs/ntfsplus/attrlist.c
new file mode 100644
index 000000000000..d83be752a846
--- /dev/null
+++ b/fs/ntfsplus/attrlist.c
@@ -0,0 +1,276 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Attribute list attribute handling code. Originated from the Linux-NTFS
+ * project.
+ * Part of this file is based on code from the NTFS-3G project.
+ *
+ * Copyright (c) 2004-2005 Anton Altaparmakov
+ * Copyright (c) 2004-2005 Yura Pakhuchiy
+ * Copyright (c) 2006 Szabolcs Szakacsits
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ */
+
+#include "mft.h"
+#include "attrib.h"
+#include "misc.h"
+#include "attrlist.h"
+
+/**
+ * ntfs_attrlist_need - check whether inode need attribute list
+ * @ni: opened ntfs inode for which perform check
+ *
+ * Check whether all are attributes belong to one MFT record, in that case
+ * attribute list is not needed.
+ */
+int ntfs_attrlist_need(struct ntfs_inode *ni)
+{
+ struct attr_list_entry *ale;
+
+ if (!ni) {
+ ntfs_debug("Invalid arguments.\n");
+ return -EINVAL;
+ }
+ ntfs_debug("Entering for inode 0x%llx.\n", (long long) ni->mft_no);
+
+ if (!NInoAttrList(ni)) {
+ ntfs_debug("Inode haven't got attribute list.\n");
+ return -EINVAL;
+ }
+
+ if (!ni->attr_list) {
+ ntfs_debug("Corrupt in-memory struct.\n");
+ return -EINVAL;
+ }
+
+ ale = (struct attr_list_entry *)ni->attr_list;
+ while ((u8 *)ale < ni->attr_list + ni->attr_list_size) {
+ if (MREF_LE(ale->mft_reference) != ni->mft_no)
+ return 1;
+ ale = (struct attr_list_entry *)((u8 *)ale + le16_to_cpu(ale->length));
+ }
+ return 0;
+}
+
+int ntfs_attrlist_update(struct ntfs_inode *base_ni)
+{
+ struct inode *attr_vi;
+ struct ntfs_inode *attr_ni;
+ int err;
+
+ BUG_ON(!NInoAttrList(base_ni));
+
+ attr_vi = ntfs_attr_iget(VFS_I(base_ni), AT_ATTRIBUTE_LIST, AT_UNNAMED, 0);
+ if (IS_ERR(attr_vi)) {
+ err = PTR_ERR(attr_vi);
+ return err;
+ }
+ attr_ni = NTFS_I(attr_vi);
+
+ if (ntfs_attr_truncate_i(attr_ni, base_ni->attr_list_size, HOLES_NO) != 0) {
+ iput(attr_vi);
+ ntfs_error(base_ni->vol->sb,
+ "Failed to truncate attribute list of inode %#llx",
+ (long long)base_ni->mft_no);
+ return -EIO;
+ }
+ i_size_write(attr_vi, base_ni->attr_list_size);
+
+ if (NInoNonResident(attr_ni) && !NInoAttrListNonResident(base_ni))
+ NInoSetAttrListNonResident(base_ni);
+
+ if (ntfs_inode_attr_pwrite(attr_vi, 0, base_ni->attr_list_size,
+ base_ni->attr_list, false) !=
+ base_ni->attr_list_size) {
+ iput(attr_vi);
+ ntfs_error(base_ni->vol->sb,
+ "Failed to write attribute list of inode %#llx",
+ (long long)base_ni->mft_no);
+ return -EIO;
+ }
+
+ NInoSetAttrListDirty(base_ni);
+ iput(attr_vi);
+ return 0;
+}
+
+/**
+ * ntfs_attrlist_entry_add - add an attribute list attribute entry
+ * @ni: opened ntfs inode, which contains that attribute
+ * @attr: attribute record to add to attribute list
+ */
+int ntfs_attrlist_entry_add(struct ntfs_inode *ni, struct attr_record *attr)
+{
+ struct attr_list_entry *ale;
+ __le64 mref;
+ struct ntfs_attr_search_ctx *ctx;
+ u8 *new_al;
+ int entry_len, entry_offset, err;
+ struct mft_record *ni_mrec;
+ u8 *old_al;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x.\n",
+ (long long) ni->mft_no,
+ (unsigned int) le32_to_cpu(attr->type));
+
+ if (!ni || !attr) {
+ ntfs_debug("Invalid arguments.\n");
+ return -EINVAL;
+ }
+
+ ni_mrec = map_mft_record(ni);
+ if (IS_ERR(ni_mrec)) {
+ ntfs_debug("Invalid arguments.\n");
+ return -EIO;
+ }
+
+ mref = MK_LE_MREF(ni->mft_no, le16_to_cpu(ni_mrec->sequence_number));
+ unmap_mft_record(ni);
+
+ if (ni->nr_extents == -1)
+ ni = ni->ext.base_ntfs_ino;
+
+ if (!NInoAttrList(ni)) {
+ ntfs_debug("Attribute list isn't present.\n");
+ return -ENOENT;
+ }
+
+ /* Determine size and allocate memory for new attribute list. */
+ entry_len = (sizeof(struct attr_list_entry) + sizeof(__le16) *
+ attr->name_length + 7) & ~7;
+ new_al = ntfs_malloc_nofs(ni->attr_list_size + entry_len);
+ if (!new_al)
+ return -ENOMEM;
+
+ /* Find place for the new entry. */
+ ctx = ntfs_attr_get_search_ctx(ni, NULL);
+ if (!ctx) {
+ err = -ENOMEM;
+ ntfs_error(ni->vol->sb, "Failed to get search context");
+ goto err_out;
+ }
+
+ err = ntfs_attr_lookup(attr->type, (attr->name_length) ? (__le16 *)
+ ((u8 *)attr + le16_to_cpu(attr->name_offset)) :
+ AT_UNNAMED, attr->name_length, CASE_SENSITIVE,
+ (attr->non_resident) ? le64_to_cpu(attr->data.non_resident.lowest_vcn) :
+ 0, (attr->non_resident) ? NULL : ((u8 *)attr +
+ le16_to_cpu(attr->data.resident.value_offset)), (attr->non_resident) ?
+ 0 : le32_to_cpu(attr->data.resident.value_length), ctx);
+ if (!err) {
+ /* Found some extent, check it to be before new extent. */
+ if (ctx->al_entry->lowest_vcn == attr->data.non_resident.lowest_vcn) {
+ err = -EEXIST;
+ ntfs_debug("Such attribute already present in the attribute list.\n");
+ ntfs_attr_put_search_ctx(ctx);
+ goto err_out;
+ }
+ /* Add new entry after this extent. */
+ ale = (struct attr_list_entry *)((u8 *)ctx->al_entry +
+ le16_to_cpu(ctx->al_entry->length));
+ } else {
+ /* Check for real errors. */
+ if (err != -ENOENT) {
+ ntfs_debug("Attribute lookup failed.\n");
+ ntfs_attr_put_search_ctx(ctx);
+ goto err_out;
+ }
+ /* No previous extents found. */
+ ale = ctx->al_entry;
+ }
+ /* Don't need it anymore, @ctx->al_entry points to @ni->attr_list. */
+ ntfs_attr_put_search_ctx(ctx);
+
+ /* Determine new entry offset. */
+ entry_offset = ((u8 *)ale - ni->attr_list);
+ /* Set pointer to new entry. */
+ ale = (struct attr_list_entry *)(new_al + entry_offset);
+ memset(ale, 0, entry_len);
+ /* Form new entry. */
+ ale->type = attr->type;
+ ale->length = cpu_to_le16(entry_len);
+ ale->name_length = attr->name_length;
+ ale->name_offset = offsetof(struct attr_list_entry, name);
+ if (attr->non_resident)
+ ale->lowest_vcn = attr->data.non_resident.lowest_vcn;
+ else
+ ale->lowest_vcn = 0;
+ ale->mft_reference = mref;
+ ale->instance = attr->instance;
+ memcpy(ale->name, (u8 *)attr + le16_to_cpu(attr->name_offset),
+ attr->name_length * sizeof(__le16));
+
+ /* Copy entries from old attribute list to new. */
+ memcpy(new_al, ni->attr_list, entry_offset);
+ memcpy(new_al + entry_offset + entry_len, ni->attr_list +
+ entry_offset, ni->attr_list_size - entry_offset);
+
+ /* Set new runlist. */
+ old_al = ni->attr_list;
+ ni->attr_list = new_al;
+ ni->attr_list_size = ni->attr_list_size + entry_len;
+
+ err = ntfs_attrlist_update(ni);
+ if (err) {
+ ni->attr_list = old_al;
+ ni->attr_list_size -= entry_len;
+ goto err_out;
+ }
+ ntfs_free(old_al);
+ return 0;
+err_out:
+ ntfs_free(new_al);
+ return err;
+}
+
+/**
+ * ntfs_attrlist_entry_rm - remove an attribute list attribute entry
+ * @ctx: attribute search context describing the attribute list entry
+ *
+ * Remove the attribute list entry @ctx->al_entry from the attribute list.
+ */
+int ntfs_attrlist_entry_rm(struct ntfs_attr_search_ctx *ctx)
+{
+ u8 *new_al;
+ int new_al_len;
+ struct ntfs_inode *base_ni;
+ struct attr_list_entry *ale;
+
+ if (!ctx || !ctx->ntfs_ino || !ctx->al_entry) {
+ ntfs_debug("Invalid arguments.\n");
+ return -EINVAL;
+ }
+
+ if (ctx->base_ntfs_ino)
+ base_ni = ctx->base_ntfs_ino;
+ else
+ base_ni = ctx->ntfs_ino;
+ ale = ctx->al_entry;
+
+ ntfs_debug("Entering for inode 0x%llx, attr 0x%x, lowest_vcn %lld.\n",
+ (long long)ctx->ntfs_ino->mft_no,
+ (unsigned int)le32_to_cpu(ctx->al_entry->type),
+ (long long)le64_to_cpu(ctx->al_entry->lowest_vcn));
+
+ if (!NInoAttrList(base_ni)) {
+ ntfs_debug("Attribute list isn't present.\n");
+ return -ENOENT;
+ }
+
+ /* Allocate memory for new attribute list. */
+ new_al_len = base_ni->attr_list_size - le16_to_cpu(ale->length);
+ new_al = ntfs_malloc_nofs(new_al_len);
+ if (!new_al)
+ return -ENOMEM;
+
+ /* Copy entries from old attribute list to new. */
+ memcpy(new_al, base_ni->attr_list, (u8 *)ale - base_ni->attr_list);
+ memcpy(new_al + ((u8 *)ale - base_ni->attr_list), (u8 *)ale + le16_to_cpu(
+ ale->length), new_al_len - ((u8 *)ale - base_ni->attr_list));
+
+ /* Set new runlist. */
+ ntfs_free(base_ni->attr_list);
+ base_ni->attr_list = new_al;
+ base_ni->attr_list_size = new_al_len;
+
+ return ntfs_attrlist_update(base_ni);
+}
diff --git a/fs/ntfsplus/compress.c b/fs/ntfsplus/compress.c
new file mode 100644
index 000000000000..5de465a00788
--- /dev/null
+++ b/fs/ntfsplus/compress.c
@@ -0,0 +1,1565 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/**
+ * NTFS kernel compressed attributes handling.
+ * Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2001-2004 Anton Altaparmakov
+ * Copyright (c) 2002 Richard Russon
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ *
+ * Part of this file is based on code from the NTFS-3G project.
+ * and is copyrighted by the respective authors below:
+ * Copyright (c) 2004-2005 Anton Altaparmakov
+ * Copyright (c) 2004-2006 Szabolcs Szakacsits
+ * Copyright (c) 2005 Yura Pakhuchiy
+ * Copyright (c) 2009-2014 Jean-Pierre Andre
+ * Copyright (c) 2014 Eric Biggers
+ */
+
+#include <linux/fs.h>
+#include <linux/blkdev.h>
+#include <linux/vmalloc.h>
+#include <linux/slab.h>
+
+#include "attrib.h"
+#include "inode.h"
+#include "misc.h"
+#include "ntfs.h"
+#include "misc.h"
+#include "aops.h"
+#include "lcnalloc.h"
+#include "mft.h"
+
+/**
+ * enum of constants used in the compression code
+ */
+enum {
+ /* Token types and access mask. */
+ NTFS_SYMBOL_TOKEN = 0,
+ NTFS_PHRASE_TOKEN = 1,
+ NTFS_TOKEN_MASK = 1,
+
+ /* Compression sub-block constants. */
+ NTFS_SB_SIZE_MASK = 0x0fff,
+ NTFS_SB_SIZE = 0x1000,
+ NTFS_SB_IS_COMPRESSED = 0x8000,
+
+ /*
+ * The maximum compression block size is by definition 16 * the cluster
+ * size, with the maximum supported cluster size being 4kiB. Thus the
+ * maximum compression buffer size is 64kiB, so we use this when
+ * initializing the compression buffer.
+ */
+ NTFS_MAX_CB_SIZE = 64 * 1024,
+};
+
+/**
+ * ntfs_compression_buffer - one buffer for the decompression engine
+ */
+static u8 *ntfs_compression_buffer;
+
+/**
+ * ntfs_cb_lock - mutex lock which protects ntfs_compression_buffer
+ */
+static DEFINE_MUTEX(ntfs_cb_lock);
+
+/**
+ * allocate_compression_buffers - allocate the decompression buffers
+ *
+ * Caller has to hold the ntfs_lock mutex.
+ *
+ * Return 0 on success or -ENOMEM if the allocations failed.
+ */
+int allocate_compression_buffers(void)
+{
+ if (ntfs_compression_buffer)
+ return 0;
+
+ ntfs_compression_buffer = vmalloc(NTFS_MAX_CB_SIZE);
+ if (!ntfs_compression_buffer)
+ return -ENOMEM;
+ return 0;
+}
+
+/**
+ * free_compression_buffers - free the decompression buffers
+ *
+ * Caller has to hold the ntfs_lock mutex.
+ */
+void free_compression_buffers(void)
+{
+ mutex_lock(&ntfs_cb_lock);
+ if (!ntfs_compression_buffer) {
+ mutex_unlock(&ntfs_cb_lock);
+ return;
+ }
+
+ vfree(ntfs_compression_buffer);
+ ntfs_compression_buffer = NULL;
+ mutex_unlock(&ntfs_cb_lock);
+}
+
+/**
+ * zero_partial_compressed_page - zero out of bounds compressed page region
+ */
+static void zero_partial_compressed_page(struct page *page,
+ const s64 initialized_size)
+{
+ u8 *kp = page_address(page);
+ unsigned int kp_ofs;
+
+ ntfs_debug("Zeroing page region outside initialized size.");
+ if (((s64)page->__folio_index << PAGE_SHIFT) >= initialized_size) {
+ clear_page(kp);
+ return;
+ }
+ kp_ofs = initialized_size & ~PAGE_MASK;
+ memset(kp + kp_ofs, 0, PAGE_SIZE - kp_ofs);
+}
+
+/**
+ * handle_bounds_compressed_page - test for&handle out of bounds compressed page
+ */
+static inline void handle_bounds_compressed_page(struct page *page,
+ const loff_t i_size, const s64 initialized_size)
+{
+ if ((page->__folio_index >= (initialized_size >> PAGE_SHIFT)) &&
+ (initialized_size < i_size))
+ zero_partial_compressed_page(page, initialized_size);
+}
+
+/**
+ * ntfs_decompress - decompress a compression block into an array of pages
+ * @dest_pages: destination array of pages
+ * @completed_pages: scratch space to track completed pages
+ * @dest_index: current index into @dest_pages (IN/OUT)
+ * @dest_ofs: current offset within @dest_pages[@dest_index] (IN/OUT)
+ * @dest_max_index: maximum index into @dest_pages (IN)
+ * @dest_max_ofs: maximum offset within @dest_pages[@dest_max_index] (IN)
+ * @xpage: the target page (-1 if none) (IN)
+ * @xpage_done: set to 1 if xpage was completed successfully (IN/OUT)
+ * @cb_start: compression block to decompress (IN)
+ * @cb_size: size of compression block @cb_start in bytes (IN)
+ * @i_size: file size when we started the read (IN)
+ * @initialized_size: initialized file size when we started the read (IN)
+ *
+ * The caller must have disabled preemption. ntfs_decompress() reenables it when
+ * the critical section is finished.
+ *
+ * This decompresses the compression block @cb_start into the array of
+ * destination pages @dest_pages starting at index @dest_index into @dest_pages
+ * and at offset @dest_pos into the page @dest_pages[@dest_index].
+ *
+ * When the page @dest_pages[@xpage] is completed, @xpage_done is set to 1.
+ * If xpage is -1 or @xpage has not been completed, @xpage_done is not modified.
+ *
+ * @cb_start is a pointer to the compression block which needs decompressing
+ * and @cb_size is the size of @cb_start in bytes (8-64kiB).
+ *
+ * Return 0 if success or -EOVERFLOW on error in the compressed stream.
+ * @xpage_done indicates whether the target page (@dest_pages[@xpage]) was
+ * completed during the decompression of the compression block (@cb_start).
+ *
+ * Warning: This function *REQUIRES* PAGE_SIZE >= 4096 or it will blow up
+ * unpredicatbly! You have been warned!
+ *
+ * Note to hackers: This function may not sleep until it has finished accessing
+ * the compression block @cb_start as it is a per-CPU buffer.
+ */
+static int ntfs_decompress(struct page *dest_pages[], int completed_pages[],
+ int *dest_index, int *dest_ofs, const int dest_max_index,
+ const int dest_max_ofs, const int xpage, char *xpage_done,
+ u8 *const cb_start, const u32 cb_size, const loff_t i_size,
+ const s64 initialized_size)
+{
+ /*
+ * Pointers into the compressed data, i.e. the compression block (cb),
+ * and the therein contained sub-blocks (sb).
+ */
+ u8 *cb_end = cb_start + cb_size; /* End of cb. */
+ u8 *cb = cb_start; /* Current position in cb. */
+ u8 *cb_sb_start = cb; /* Beginning of the current sb in the cb. */
+ u8 *cb_sb_end; /* End of current sb / beginning of next sb. */
+
+ /* Variables for uncompressed data / destination. */
+ struct page *dp; /* Current destination page being worked on. */
+ u8 *dp_addr; /* Current pointer into dp. */
+ u8 *dp_sb_start; /* Start of current sub-block in dp. */
+ u8 *dp_sb_end; /* End of current sb in dp (dp_sb_start + NTFS_SB_SIZE). */
+ u16 do_sb_start; /* @dest_ofs when starting this sub-block. */
+ u16 do_sb_end; /* @dest_ofs of end of this sb (do_sb_start + NTFS_SB_SIZE). */
+
+ /* Variables for tag and token parsing. */
+ u8 tag; /* Current tag. */
+ int token; /* Loop counter for the eight tokens in tag. */
+ int nr_completed_pages = 0;
+
+ /* Default error code. */
+ int err = -EOVERFLOW;
+
+ ntfs_debug("Entering, cb_size = 0x%x.", cb_size);
+do_next_sb:
+ ntfs_debug("Beginning sub-block at offset = 0x%zx in the cb.",
+ cb - cb_start);
+ /*
+ * Have we reached the end of the compression block or the end of the
+ * decompressed data? The latter can happen for example if the current
+ * position in the compression block is one byte before its end so the
+ * first two checks do not detect it.
+ */
+ if (cb == cb_end || !le16_to_cpup((__le16 *)cb) ||
+ (*dest_index == dest_max_index &&
+ *dest_ofs == dest_max_ofs)) {
+ int i;
+
+ ntfs_debug("Completed. Returning success (0).");
+ err = 0;
+return_error:
+ /* We can sleep from now on, so we drop lock. */
+ mutex_unlock(&ntfs_cb_lock);
+ /* Second stage: finalize completed pages. */
+ if (nr_completed_pages > 0) {
+ for (i = 0; i < nr_completed_pages; i++) {
+ int di = completed_pages[i];
+
+ dp = dest_pages[di];
+ /*
+ * If we are outside the initialized size, zero
+ * the out of bounds page range.
+ */
+ handle_bounds_compressed_page(dp, i_size,
+ initialized_size);
+ flush_dcache_page(dp);
+ kunmap_local(page_address(dp));
+ SetPageUptodate(dp);
+ unlock_page(dp);
+ if (di == xpage)
+ *xpage_done = 1;
+ else
+ put_page(dp);
+ dest_pages[di] = NULL;
+ }
+ }
+ return err;
+ }
+
+ /* Setup offsets for the current sub-block destination. */
+ do_sb_start = *dest_ofs;
+ do_sb_end = do_sb_start + NTFS_SB_SIZE;
+
+ /* Check that we are still within allowed boundaries. */
+ if (*dest_index == dest_max_index && do_sb_end > dest_max_ofs)
+ goto return_overflow;
+
+ /* Does the minimum size of a compressed sb overflow valid range? */
+ if (cb + 6 > cb_end)
+ goto return_overflow;
+
+ /* Setup the current sub-block source pointers and validate range. */
+ cb_sb_start = cb;
+ cb_sb_end = cb_sb_start + (le16_to_cpup((__le16 *)cb) & NTFS_SB_SIZE_MASK)
+ + 3;
+ if (cb_sb_end > cb_end)
+ goto return_overflow;
+
+ /* Get the current destination page. */
+ dp = dest_pages[*dest_index];
+ if (!dp) {
+ /* No page present. Skip decompression of this sub-block. */
+ cb = cb_sb_end;
+
+ /* Advance destination position to next sub-block. */
+ *dest_ofs = (*dest_ofs + NTFS_SB_SIZE) & ~PAGE_MASK;
+ if (!*dest_ofs && (++*dest_index > dest_max_index))
+ goto return_overflow;
+ goto do_next_sb;
+ }
+
+ /* We have a valid destination page. Setup the destination pointers. */
+ dp_addr = (u8 *)page_address(dp) + do_sb_start;
+
+ /* Now, we are ready to process the current sub-block (sb). */
+ if (!(le16_to_cpup((__le16 *)cb) & NTFS_SB_IS_COMPRESSED)) {
+ ntfs_debug("Found uncompressed sub-block.");
+ /* This sb is not compressed, just copy it into destination. */
+
+ /* Advance source position to first data byte. */
+ cb += 2;
+
+ /* An uncompressed sb must be full size. */
+ if (cb_sb_end - cb != NTFS_SB_SIZE)
+ goto return_overflow;
+
+ /* Copy the block and advance the source position. */
+ memcpy(dp_addr, cb, NTFS_SB_SIZE);
+ cb += NTFS_SB_SIZE;
+
+ /* Advance destination position to next sub-block. */
+ *dest_ofs += NTFS_SB_SIZE;
+ *dest_ofs &= ~PAGE_MASK;
+ if (!(*dest_ofs)) {
+finalize_page:
+ /*
+ * First stage: add current page index to array of
+ * completed pages.
+ */
+ completed_pages[nr_completed_pages++] = *dest_index;
+ if (++*dest_index > dest_max_index)
+ goto return_overflow;
+ }
+ goto do_next_sb;
+ }
+ ntfs_debug("Found compressed sub-block.");
+ /* This sb is compressed, decompress it into destination. */
+
+ /* Setup destination pointers. */
+ dp_sb_start = dp_addr;
+ dp_sb_end = dp_sb_start + NTFS_SB_SIZE;
+
+ /* Forward to the first tag in the sub-block. */
+ cb += 2;
+do_next_tag:
+ if (cb == cb_sb_end) {
+ /* Check if the decompressed sub-block was not full-length. */
+ if (dp_addr < dp_sb_end) {
+ int nr_bytes = do_sb_end - *dest_ofs;
+
+ ntfs_debug("Filling incomplete sub-block with zeroes.");
+ /* Zero remainder and update destination position. */
+ memset(dp_addr, 0, nr_bytes);
+ *dest_ofs += nr_bytes;
+ }
+ /* We have finished the current sub-block. */
+ *dest_ofs &= ~PAGE_MASK;
+ if (!(*dest_ofs))
+ goto finalize_page;
+ goto do_next_sb;
+ }
+
+ /* Check we are still in range. */
+ if (cb > cb_sb_end || dp_addr > dp_sb_end)
+ goto return_overflow;
+
+ /* Get the next tag and advance to first token. */
+ tag = *cb++;
+
+ /* Parse the eight tokens described by the tag. */
+ for (token = 0; token < 8; token++, tag >>= 1) {
+ register u16 i;
+ u16 lg, pt, length, max_non_overlap;
+ u8 *dp_back_addr;
+
+ /* Check if we are done / still in range. */
+ if (cb >= cb_sb_end || dp_addr > dp_sb_end)
+ break;
+
+ /* Determine token type and parse appropriately.*/
+ if ((tag & NTFS_TOKEN_MASK) == NTFS_SYMBOL_TOKEN) {
+ /*
+ * We have a symbol token, copy the symbol across, and
+ * advance the source and destination positions.
+ */
+ *dp_addr++ = *cb++;
+ ++*dest_ofs;
+
+ /* Continue with the next token. */
+ continue;
+ }
+
+ /*
+ * We have a phrase token. Make sure it is not the first tag in
+ * the sb as this is illegal and would confuse the code below.
+ */
+ if (dp_addr == dp_sb_start)
+ goto return_overflow;
+
+ /*
+ * Determine the number of bytes to go back (p) and the number
+ * of bytes to copy (l). We use an optimized algorithm in which
+ * we first calculate log2(current destination position in sb),
+ * which allows determination of l and p in O(1) rather than
+ * O(n). We just need an arch-optimized log2() function now.
+ */
+ lg = 0;
+ for (i = *dest_ofs - do_sb_start - 1; i >= 0x10; i >>= 1)
+ lg++;
+
+ /* Get the phrase token into i. */
+ pt = le16_to_cpup((__le16 *)cb);
+
+ /*
+ * Calculate starting position of the byte sequence in
+ * the destination using the fact that p = (pt >> (12 - lg)) + 1
+ * and make sure we don't go too far back.
+ */
+ dp_back_addr = dp_addr - (pt >> (12 - lg)) - 1;
+ if (dp_back_addr < dp_sb_start)
+ goto return_overflow;
+
+ /* Now calculate the length of the byte sequence. */
+ length = (pt & (0xfff >> lg)) + 3;
+
+ /* Advance destination position and verify it is in range. */
+ *dest_ofs += length;
+ if (*dest_ofs > do_sb_end)
+ goto return_overflow;
+
+ /* The number of non-overlapping bytes. */
+ max_non_overlap = dp_addr - dp_back_addr;
+
+ if (length <= max_non_overlap) {
+ /* The byte sequence doesn't overlap, just copy it. */
+ memcpy(dp_addr, dp_back_addr, length);
+
+ /* Advance destination pointer. */
+ dp_addr += length;
+ } else {
+ /*
+ * The byte sequence does overlap, copy non-overlapping
+ * part and then do a slow byte by byte copy for the
+ * overlapping part. Also, advance the destination
+ * pointer.
+ */
+ memcpy(dp_addr, dp_back_addr, max_non_overlap);
+ dp_addr += max_non_overlap;
+ dp_back_addr += max_non_overlap;
+ length -= max_non_overlap;
+ while (length--)
+ *dp_addr++ = *dp_back_addr++;
+ }
+
+ /* Advance source position and continue with the next token. */
+ cb += 2;
+ }
+
+ /* No tokens left in the current tag. Continue with the next tag. */
+ goto do_next_tag;
+
+return_overflow:
+ ntfs_error(NULL, "Failed. Returning -EOVERFLOW.");
+ goto return_error;
+}
+
+/**
+ * ntfs_read_compressed_block - read a compressed block into the page cache
+ * @folio: locked folio in the compression block(s) we need to read
+ *
+ * When we are called the page has already been verified to be locked and the
+ * attribute is known to be non-resident, not encrypted, but compressed.
+ *
+ * 1. Determine which compression block(s) @page is in.
+ * 2. Get hold of all pages corresponding to this/these compression block(s).
+ * 3. Read the (first) compression block.
+ * 4. Decompress it into the corresponding pages.
+ * 5. Throw the compressed data away and proceed to 3. for the next compression
+ * block or return success if no more compression blocks left.
+ *
+ * Warning: We have to be careful what we do about existing pages. They might
+ * have been written to so that we would lose data if we were to just overwrite
+ * them with the out-of-date uncompressed data.
+ */
+int ntfs_read_compressed_block(struct folio *folio)
+{
+ struct page *page = &folio->page;
+ loff_t i_size;
+ s64 initialized_size;
+ struct address_space *mapping = page->mapping;
+ struct ntfs_inode *ni = NTFS_I(mapping->host);
+ struct ntfs_volume *vol = ni->vol;
+ struct super_block *sb = vol->sb;
+ struct runlist_element *rl;
+ unsigned long flags;
+ u8 *cb, *cb_pos, *cb_end;
+ unsigned long offset, index = page->__folio_index;
+ u32 cb_size = ni->itype.compressed.block_size;
+ u64 cb_size_mask = cb_size - 1UL;
+ s64 vcn;
+ s64 lcn;
+ /* The first wanted vcn (minimum alignment is PAGE_SIZE). */
+ s64 start_vcn = (((s64)index << PAGE_SHIFT) & ~cb_size_mask) >>
+ vol->cluster_size_bits;
+ /*
+ * The first vcn after the last wanted vcn (minimum alignment is again
+ * PAGE_SIZE.
+ */
+ s64 end_vcn = ((((s64)(index + 1UL) << PAGE_SHIFT) + cb_size - 1)
+ & ~cb_size_mask) >> vol->cluster_size_bits;
+ /* Number of compression blocks (cbs) in the wanted vcn range. */
+ unsigned int nr_cbs = (end_vcn - start_vcn) << vol->cluster_size_bits
+ >> ni->itype.compressed.block_size_bits;
+ /*
+ * Number of pages required to store the uncompressed data from all
+ * compression blocks (cbs) overlapping @page. Due to alignment
+ * guarantees of start_vcn and end_vcn, no need to round up here.
+ */
+ unsigned int nr_pages = (end_vcn - start_vcn) <<
+ vol->cluster_size_bits >> PAGE_SHIFT;
+ unsigned int xpage, max_page, cur_page, cur_ofs, i, page_ofs, page_index;
+ unsigned int cb_clusters, cb_max_ofs;
+ int cb_max_page, err = 0;
+ struct page **pages;
+ int *completed_pages;
+ unsigned char xpage_done = 0;
+ struct page *lpage;
+
+ ntfs_debug("Entering, page->index = 0x%lx, cb_size = 0x%x, nr_pages = %i.",
+ index, cb_size, nr_pages);
+ /*
+ * Bad things happen if we get here for anything that is not an
+ * unnamed $DATA attribute.
+ */
+ BUG_ON(ni->type != AT_DATA);
+ BUG_ON(ni->name_len);
+
+ pages = kmalloc_array(nr_pages, sizeof(struct page *), GFP_NOFS);
+ completed_pages = kmalloc_array(nr_pages + 1, sizeof(int), GFP_NOFS);
+
+ if (unlikely(!pages || !completed_pages)) {
+ kfree(pages);
+ kfree(completed_pages);
+ unlock_page(page);
+ ntfs_error(vol->sb, "Failed to allocate internal buffers.");
+ return -ENOMEM;
+ }
+
+ /*
+ * We have already been given one page, this is the one we must do.
+ * Once again, the alignment guarantees keep it simple.
+ */
+ offset = start_vcn << vol->cluster_size_bits >> PAGE_SHIFT;
+ xpage = index - offset;
+ pages[xpage] = page;
+ /*
+ * The remaining pages need to be allocated and inserted into the page
+ * cache, alignment guarantees keep all the below much simpler. (-8
+ */
+ read_lock_irqsave(&ni->size_lock, flags);
+ i_size = i_size_read(VFS_I(ni));
+ initialized_size = ni->initialized_size;
+ read_unlock_irqrestore(&ni->size_lock, flags);
+ max_page = ((i_size + PAGE_SIZE - 1) >> PAGE_SHIFT) -
+ offset;
+ /* Is the page fully outside i_size? (truncate in progress) */
+ if (xpage >= max_page) {
+ kfree(pages);
+ kfree(completed_pages);
+ zero_user_segments(page, 0, PAGE_SIZE, 0, 0);
+ ntfs_debug("Compressed read outside i_size - truncated?");
+ SetPageUptodate(page);
+ unlock_page(page);
+ return 0;
+ }
+ if (nr_pages < max_page)
+ max_page = nr_pages;
+
+ for (i = 0; i < max_page; i++, offset++) {
+ if (i != xpage)
+ pages[i] = grab_cache_page_nowait(mapping, offset);
+ page = pages[i];
+ if (page) {
+ /*
+ * We only (re)read the page if it isn't already read
+ * in and/or dirty or we would be losing data or at
+ * least wasting our time.
+ */
+ if (!PageDirty(page) && (!PageUptodate(page))) {
+ kmap_local_page(page);
+ continue;
+ }
+ unlock_page(page);
+ put_page(page);
+ pages[i] = NULL;
+ }
+ }
+
+ /*
+ * We have the runlist, and all the destination pages we need to fill.
+ * Now read the first compression block.
+ */
+ cur_page = 0;
+ cur_ofs = 0;
+ cb_clusters = ni->itype.compressed.block_clusters;
+do_next_cb:
+ nr_cbs--;
+
+ mutex_lock(&ntfs_cb_lock);
+ if (!ntfs_compression_buffer)
+ if (allocate_compression_buffers()) {
+ mutex_unlock(&ntfs_cb_lock);
+ goto err_out;
+ }
+
+
+ cb = ntfs_compression_buffer;
+
+ BUG_ON(!cb);
+
+ cb_pos = cb;
+ cb_end = cb + cb_size;
+
+ rl = NULL;
+ for (vcn = start_vcn, start_vcn += cb_clusters; vcn < start_vcn;
+ vcn++) {
+ bool is_retry = false;
+
+ if (!rl) {
+lock_retry_remap:
+ down_read(&ni->runlist.lock);
+ rl = ni->runlist.rl;
+ }
+ if (likely(rl != NULL)) {
+ /* Seek to element containing target vcn. */
+ while (rl->length && rl[1].vcn <= vcn)
+ rl++;
+ lcn = ntfs_rl_vcn_to_lcn(rl, vcn);
+ } else
+ lcn = LCN_RL_NOT_MAPPED;
+ ntfs_debug("Reading vcn = 0x%llx, lcn = 0x%llx.",
+ (unsigned long long)vcn,
+ (unsigned long long)lcn);
+ if (lcn < 0) {
+ /*
+ * When we reach the first sparse cluster we have
+ * finished with the cb.
+ */
+ if (lcn == LCN_HOLE)
+ break;
+ if (is_retry || lcn != LCN_RL_NOT_MAPPED) {
+ mutex_unlock(&ntfs_cb_lock);
+ goto rl_err;
+ }
+ is_retry = true;
+ /*
+ * Attempt to map runlist, dropping lock for the
+ * duration.
+ */
+ up_read(&ni->runlist.lock);
+ if (!ntfs_map_runlist(ni, vcn))
+ goto lock_retry_remap;
+ mutex_unlock(&ntfs_cb_lock);
+ goto map_rl_err;
+ }
+
+ page_ofs = (lcn << vol->cluster_size_bits) & ~PAGE_MASK;
+ page_index = (lcn << vol->cluster_size_bits) >> PAGE_SHIFT;
+
+retry:
+ lpage = read_mapping_page(sb->s_bdev->bd_mapping,
+ page_index, NULL);
+ if (PTR_ERR(page) == -EINTR)
+ goto retry;
+ else if (IS_ERR(lpage)) {
+ err = PTR_ERR(lpage);
+ mutex_unlock(&ntfs_cb_lock);
+ goto read_err;
+ }
+
+ lock_page(lpage);
+ memcpy(cb_pos, page_address(lpage) + page_ofs,
+ vol->cluster_size);
+ unlock_page(lpage);
+ put_page(lpage);
+ cb_pos += vol->cluster_size;
+ }
+
+ /* Release the lock if we took it. */
+ if (rl)
+ up_read(&ni->runlist.lock);
+
+ /* Just a precaution. */
+ if (cb_pos + 2 <= cb + cb_size)
+ *(u16 *)cb_pos = 0;
+
+ /* Reset cb_pos back to the beginning. */
+ cb_pos = cb;
+
+ /* We now have both source (if present) and destination. */
+ ntfs_debug("Successfully read the compression block.");
+
+ /* The last page and maximum offset within it for the current cb. */
+ cb_max_page = (cur_page << PAGE_SHIFT) + cur_ofs + cb_size;
+ cb_max_ofs = cb_max_page & ~PAGE_MASK;
+ cb_max_page >>= PAGE_SHIFT;
+
+ /* Catch end of file inside a compression block. */
+ if (cb_max_page > max_page)
+ cb_max_page = max_page;
+
+ if (vcn == start_vcn - cb_clusters) {
+ /* Sparse cb, zero out page range overlapping the cb. */
+ ntfs_debug("Found sparse compression block.");
+ /* We can sleep from now on, so we drop lock. */
+ mutex_unlock(&ntfs_cb_lock);
+ if (cb_max_ofs)
+ cb_max_page--;
+ for (; cur_page < cb_max_page; cur_page++) {
+ page = pages[cur_page];
+ if (page) {
+ if (likely(!cur_ofs))
+ clear_page(page_address(page));
+ else
+ memset(page_address(page) + cur_ofs, 0,
+ PAGE_SIZE -
+ cur_ofs);
+ flush_dcache_page(page);
+ kunmap_local(page_address(page));
+ SetPageUptodate(page);
+ unlock_page(page);
+ if (cur_page == xpage)
+ xpage_done = 1;
+ else
+ put_page(page);
+ pages[cur_page] = NULL;
+ }
+ cb_pos += PAGE_SIZE - cur_ofs;
+ cur_ofs = 0;
+ if (cb_pos >= cb_end)
+ break;
+ }
+ /* If we have a partial final page, deal with it now. */
+ if (cb_max_ofs && cb_pos < cb_end) {
+ page = pages[cur_page];
+ if (page)
+ memset(page_address(page) + cur_ofs, 0,
+ cb_max_ofs - cur_ofs);
+ /*
+ * No need to update cb_pos at this stage:
+ * cb_pos += cb_max_ofs - cur_ofs;
+ */
+ cur_ofs = cb_max_ofs;
+ }
+ } else if (vcn == start_vcn) {
+ /* We can't sleep so we need two stages. */
+ unsigned int cur2_page = cur_page;
+ unsigned int cur_ofs2 = cur_ofs;
+ u8 *cb_pos2 = cb_pos;
+
+ ntfs_debug("Found uncompressed compression block.");
+ /* Uncompressed cb, copy it to the destination pages. */
+ if (cb_max_ofs)
+ cb_max_page--;
+ /* First stage: copy data into destination pages. */
+ for (; cur_page < cb_max_page; cur_page++) {
+ page = pages[cur_page];
+ if (page)
+ memcpy(page_address(page) + cur_ofs, cb_pos,
+ PAGE_SIZE - cur_ofs);
+ cb_pos += PAGE_SIZE - cur_ofs;
+ cur_ofs = 0;
+ if (cb_pos >= cb_end)
+ break;
+ }
+ /* If we have a partial final page, deal with it now. */
+ if (cb_max_ofs && cb_pos < cb_end) {
+ page = pages[cur_page];
+ if (page)
+ memcpy(page_address(page) + cur_ofs, cb_pos,
+ cb_max_ofs - cur_ofs);
+ cb_pos += cb_max_ofs - cur_ofs;
+ cur_ofs = cb_max_ofs;
+ }
+ /* We can sleep from now on, so drop lock. */
+ mutex_unlock(&ntfs_cb_lock);
+ /* Second stage: finalize pages. */
+ for (; cur2_page < cb_max_page; cur2_page++) {
+ page = pages[cur2_page];
+ if (page) {
+ /*
+ * If we are outside the initialized size, zero
+ * the out of bounds page range.
+ */
+ handle_bounds_compressed_page(page, i_size,
+ initialized_size);
+ flush_dcache_page(page);
+ kunmap_local(page_address(page));
+ SetPageUptodate(page);
+ unlock_page(page);
+ if (cur2_page == xpage)
+ xpage_done = 1;
+ else
+ put_page(page);
+ pages[cur2_page] = NULL;
+ }
+ cb_pos2 += PAGE_SIZE - cur_ofs2;
+ cur_ofs2 = 0;
+ if (cb_pos2 >= cb_end)
+ break;
+ }
+ } else {
+ /* Compressed cb, decompress it into the destination page(s). */
+ unsigned int prev_cur_page = cur_page;
+
+ ntfs_debug("Found compressed compression block.");
+ err = ntfs_decompress(pages, completed_pages, &cur_page,
+ &cur_ofs, cb_max_page, cb_max_ofs, xpage,
+ &xpage_done, cb_pos, cb_size - (cb_pos - cb),
+ i_size, initialized_size);
+ /*
+ * We can sleep from now on, lock already dropped by
+ * ntfs_decompress().
+ */
+ if (err) {
+ ntfs_error(vol->sb,
+ "ntfs_decompress() failed in inode 0x%lx with error code %i. Skipping this compression block.",
+ ni->mft_no, -err);
+ /* Release the unfinished pages. */
+ for (; prev_cur_page < cur_page; prev_cur_page++) {
+ page = pages[prev_cur_page];
+ if (page) {
+ flush_dcache_page(page);
+ kunmap_local(page_address(page));
+ unlock_page(page);
+ if (prev_cur_page != xpage)
+ put_page(page);
+ pages[prev_cur_page] = NULL;
+ }
+ }
+ }
+ }
+
+ /* Do we have more work to do? */
+ if (nr_cbs)
+ goto do_next_cb;
+
+ /* Clean up if we have any pages left. Should never happen. */
+ for (cur_page = 0; cur_page < max_page; cur_page++) {
+ page = pages[cur_page];
+ if (page) {
+ ntfs_error(vol->sb,
+ "Still have pages left! Terminating them with extreme prejudice. Inode 0x%lx, page index 0x%lx.",
+ ni->mft_no, page->__folio_index);
+ flush_dcache_page(page);
+ kunmap_local(page_address(page));
+ unlock_page(page);
+ if (cur_page != xpage)
+ put_page(page);
+ pages[cur_page] = NULL;
+ }
+ }
+
+ /* We no longer need the list of pages. */
+ kfree(pages);
+ kfree(completed_pages);
+
+ /* If we have completed the requested page, we return success. */
+ if (likely(xpage_done))
+ return 0;
+
+ ntfs_debug("Failed. Returning error code %s.", err == -EOVERFLOW ?
+ "EOVERFLOW" : (!err ? "EIO" : "unknown error"));
+ return err < 0 ? err : -EIO;
+
+map_rl_err:
+ ntfs_error(vol->sb, "ntfs_map_runlist() failed. Cannot read compression block.");
+ goto err_out;
+
+rl_err:
+ up_read(&ni->runlist.lock);
+ ntfs_error(vol->sb, "ntfs_rl_vcn_to_lcn() failed. Cannot read compression block.");
+ goto err_out;
+
+read_err:
+ up_read(&ni->runlist.lock);
+ ntfs_error(vol->sb, "IO error while reading compressed data.");
+
+err_out:
+ for (i = cur_page; i < max_page; i++) {
+ page = pages[i];
+ if (page) {
+ flush_dcache_page(page);
+ kunmap_local(page_address(page));
+ unlock_page(page);
+ if (i != xpage)
+ put_page(page);
+ }
+ }
+ kfree(pages);
+ kfree(completed_pages);
+ return -EIO;
+}
+
+/*
+ * Match length at or above which ntfs_best_match() will stop searching for
+ * longer matches.
+ */
+#define NICE_MATCH_LEN 18
+
+/*
+ * Maximum number of potential matches that ntfs_best_match() will consider at
+ * each position.
+ */
+#define MAX_SEARCH_DEPTH 24
+
+/* log base 2 of the number of entries in the hash table for match-finding. */
+#define HASH_SHIFT 14
+
+/* Constant for the multiplicative hash function. */
+#define HASH_MULTIPLIER 0x1E35A7BD
+
+struct COMPRESS_CONTEXT {
+ const unsigned char *inbuf;
+ int bufsize;
+ int size;
+ int rel;
+ int mxsz;
+ s16 head[1 << HASH_SHIFT];
+ s16 prev[NTFS_SB_SIZE];
+};
+
+/*
+ * Hash the next 3-byte sequence in the input buffer
+ */
+static inline unsigned int ntfs_hash(const u8 *p)
+{
+ u32 str;
+ u32 hash;
+
+ /*
+ * Unaligned access allowed, and little endian CPU.
+ * Callers ensure that at least 4 (not 3) bytes are remaining.
+ */
+ str = *(const u32 *)p & 0xFFFFFF;
+ hash = str * HASH_MULTIPLIER;
+
+ /* High bits are more random than the low bits. */
+ return hash >> (32 - HASH_SHIFT);
+}
+
+/*
+ * Search for the longest sequence matching current position
+ *
+ * A hash table, each entry of which points to a chain of sequence
+ * positions sharing the corresponding hash code, is maintained to speed up
+ * searching for matches. To maintain the hash table, either
+ * ntfs_best_match() or ntfs_skip_position() has to be called for each
+ * consecutive position.
+ *
+ * This function is heavily used; it has to be optimized carefully.
+ *
+ * This function sets pctx->size and pctx->rel to the length and offset,
+ * respectively, of the longest match found.
+ *
+ * The minimum match length is assumed to be 3, and the maximum match
+ * length is assumed to be pctx->mxsz. If this function produces
+ * pctx->size < 3, then no match was found.
+ *
+ * Note: for the following reasons, this function is not guaranteed to find
+ * *the* longest match up to pctx->mxsz:
+ *
+ * (1) If this function finds a match of NICE_MATCH_LEN bytes or greater,
+ * it ends early because a match this long is good enough and it's not
+ * worth spending more time searching.
+ *
+ * (2) If this function considers MAX_SEARCH_DEPTH matches with a single
+ * position, it ends early and returns the longest match found so far.
+ * This saves a lot of time on degenerate inputs.
+ */
+static void ntfs_best_match(struct COMPRESS_CONTEXT *pctx, const int i,
+ int best_len)
+{
+ const u8 * const inbuf = pctx->inbuf;
+ const u8 * const strptr = &inbuf[i]; /* String we're matching against */
+ s16 * const prev = pctx->prev;
+ const int max_len = min(pctx->bufsize - i, pctx->mxsz);
+ const int nice_len = min(NICE_MATCH_LEN, max_len);
+ int depth_remaining = MAX_SEARCH_DEPTH;
+ const u8 *best_matchptr = strptr;
+ unsigned int hash;
+ s16 cur_match;
+ const u8 *matchptr;
+ int len;
+
+ if (max_len < 4)
+ goto out;
+
+ /* Insert the current sequence into the appropriate hash chain. */
+ hash = ntfs_hash(strptr);
+ cur_match = pctx->head[hash];
+ prev[i] = cur_match;
+ pctx->head[hash] = i;
+
+ if (best_len >= max_len) {
+ /*
+ * Lazy match is being attempted, but there aren't enough length
+ * bits remaining to code a longer match.
+ */
+ goto out;
+ }
+
+ /* Search the appropriate hash chain for matches. */
+
+ for (; cur_match >= 0 && depth_remaining--; cur_match = prev[cur_match]) {
+ matchptr = &inbuf[cur_match];
+
+ /*
+ * Considering the potential match at 'matchptr': is it longer
+ * than 'best_len'?
+ *
+ * The bytes at index 'best_len' are the most likely to differ,
+ * so check them first.
+ *
+ * The bytes at indices 'best_len - 1' and '0' are less
+ * important to check separately. But doing so still gives a
+ * slight performance improvement, at least on x86_64, probably
+ * because they create separate branches for the CPU to predict
+ * independently of the branches in the main comparison loops.
+ */
+ if (matchptr[best_len] != strptr[best_len] ||
+ matchptr[best_len - 1] != strptr[best_len - 1] ||
+ matchptr[0] != strptr[0])
+ goto next_match;
+
+ for (len = 1; len < best_len - 1; len++)
+ if (matchptr[len] != strptr[len])
+ goto next_match;
+
+ /*
+ * The match is the longest found so far ---
+ * at least 'best_len' + 1 bytes. Continue extending it.
+ */
+
+ best_matchptr = matchptr;
+
+ do {
+ if (++best_len >= nice_len) {
+ /*
+ * 'nice_len' reached; don't waste time
+ * searching for longer matches. Extend the
+ * match as far as possible and terminate the
+ * search.
+ */
+ while (best_len < max_len &&
+ (best_matchptr[best_len] ==
+ strptr[best_len]))
+ best_len++;
+ goto out;
+ }
+ } while (best_matchptr[best_len] == strptr[best_len]);
+
+ /* Found a longer match, but 'nice_len' not yet reached. */
+
+next_match:
+ /* Continue to next match in the chain. */
+ ;
+ }
+
+ /*
+ * Reached end of chain, or ended early due to reaching the maximum
+ * search depth.
+ */
+
+out:
+ /* Return the longest match we were able to find. */
+ pctx->size = best_len;
+ pctx->rel = best_matchptr - strptr; /* given as a negative number! */
+}
+
+/*
+ * Advance the match-finder, but don't search for matches.
+ */
+static void ntfs_skip_position(struct COMPRESS_CONTEXT *pctx, const int i)
+{
+ unsigned int hash;
+
+ if (pctx->bufsize - i < 4)
+ return;
+
+ /* Insert the current sequence into the appropriate hash chain. */
+ hash = ntfs_hash(pctx->inbuf + i);
+ pctx->prev[i] = pctx->head[hash];
+ pctx->head[hash] = i;
+}
+
+/*
+ * Compress a 4096-byte block
+ *
+ * Returns a header of two bytes followed by the compressed data.
+ * If compression is not effective, the header and an uncompressed
+ * block is returned.
+ *
+ * Note : two bytes may be output before output buffer overflow
+ * is detected, so a 4100-bytes output buffer must be reserved.
+ *
+ * Returns the size of the compressed block, including the
+ * header (minimal size is 2, maximum size is 4098)
+ * 0 if an error has been met.
+ */
+static unsigned int ntfs_compress_block(const char *inbuf, const int bufsize,
+ char *outbuf)
+{
+ struct COMPRESS_CONTEXT *pctx;
+ int i; /* current position */
+ int j; /* end of best match from current position */
+ int k; /* end of best match from next position */
+ int offs; /* offset to best match */
+ int bp; /* bits to store offset */
+ int bp_cur; /* saved bits to store offset at current position */
+ int mxoff; /* max match offset : 1 << bp */
+ unsigned int xout;
+ unsigned int q; /* aggregated offset and size */
+ int have_match; /* do we have a match at the current position? */
+ char *ptag; /* location reserved for a tag */
+ int tag; /* current value of tag */
+ int ntag; /* count of bits still undefined in tag */
+
+ pctx = ntfs_malloc_nofs(sizeof(struct COMPRESS_CONTEXT));
+ if (!pctx)
+ return -ENOMEM;
+
+ /*
+ * All hash chains start as empty. The special value '-1' indicates the
+ * end of each hash chain.
+ */
+ memset(pctx->head, 0xFF, sizeof(pctx->head));
+
+ pctx->inbuf = (const unsigned char *)inbuf;
+ pctx->bufsize = bufsize;
+ xout = 2;
+ i = 0;
+ bp = 4;
+ mxoff = 1 << bp;
+ pctx->mxsz = (1 << (16 - bp)) + 2;
+ have_match = 0;
+ tag = 0;
+ ntag = 8;
+ ptag = &outbuf[xout++];
+
+ while ((i < bufsize) && (xout < (NTFS_SB_SIZE + 2))) {
+
+ /*
+ * This implementation uses "lazy" parsing: it always chooses
+ * the longest match, unless the match at the next position is
+ * longer. This is the same strategy used by the high
+ * compression modes of zlib.
+ */
+ if (!have_match) {
+ /*
+ * Find the longest match at the current position. But
+ * first adjust the maximum match length if needed.
+ * (This loop might need to run more than one time in
+ * the case that we just output a long match.)
+ */
+ while (mxoff < i) {
+ bp++;
+ mxoff <<= 1;
+ pctx->mxsz = (pctx->mxsz + 2) >> 1;
+ }
+ ntfs_best_match(pctx, i, 2);
+ }
+
+ if (pctx->size >= 3) {
+ /* Found a match at the current position. */
+ j = i + pctx->size;
+ bp_cur = bp;
+ offs = pctx->rel;
+
+ if (pctx->size >= NICE_MATCH_LEN) {
+ /* Choose long matches immediately. */
+ q = (~offs << (16 - bp_cur)) + (j - i - 3);
+ outbuf[xout++] = q & 255;
+ outbuf[xout++] = (q >> 8) & 255;
+ tag |= (1 << (8 - ntag));
+
+ if (j == bufsize) {
+ /*
+ * Shortcut if the match extends to the
+ * end of the buffer.
+ */
+ i = j;
+ --ntag;
+ break;
+ }
+ i += 1;
+ do {
+ ntfs_skip_position(pctx, i);
+ } while (++i != j);
+ have_match = 0;
+ } else {
+ /*
+ * Check for a longer match at the next
+ * position.
+ */
+
+ /*
+ * Doesn't need to be while() since we just
+ * adjusted the maximum match length at the
+ * previous position.
+ */
+ if (mxoff < i + 1) {
+ bp++;
+ mxoff <<= 1;
+ pctx->mxsz = (pctx->mxsz + 2) >> 1;
+ }
+ ntfs_best_match(pctx, i + 1, pctx->size);
+ k = i + 1 + pctx->size;
+
+ if (k > (j + 1)) {
+ /*
+ * Next match is longer.
+ * Output a literal.
+ */
+ outbuf[xout++] = inbuf[i++];
+ have_match = 1;
+ } else {
+ /*
+ * Next match isn't longer.
+ * Output the current match.
+ */
+ q = (~offs << (16 - bp_cur)) +
+ (j - i - 3);
+ outbuf[xout++] = q & 255;
+ outbuf[xout++] = (q >> 8) & 255;
+ tag |= (1 << (8 - ntag));
+
+ /*
+ * The minimum match length is 3, and
+ * we've run two bytes through the
+ * matchfinder already. So the minimum
+ * number of positions we need to skip
+ * is 1.
+ */
+ i += 2;
+ do {
+ ntfs_skip_position(pctx, i);
+ } while (++i != j);
+ have_match = 0;
+ }
+ }
+ } else {
+ /* No match at current position. Output a literal. */
+ outbuf[xout++] = inbuf[i++];
+ have_match = 0;
+ }
+
+ /* Store the tag if fully used. */
+ if (!--ntag) {
+ *ptag = tag;
+ ntag = 8;
+ ptag = &outbuf[xout++];
+ tag = 0;
+ }
+ }
+
+ /* Store the last tag if partially used. */
+ if (ntag == 8)
+ xout--;
+ else
+ *ptag = tag;
+
+ /* Determine whether to store the data compressed or uncompressed. */
+ if ((i >= bufsize) && (xout < (NTFS_SB_SIZE + 2))) {
+ /* Compressed. */
+ outbuf[0] = (xout - 3) & 255;
+ outbuf[1] = 0xb0 + (((xout - 3) >> 8) & 15);
+ } else {
+ /* Uncompressed. */
+ memcpy(&outbuf[2], inbuf, bufsize);
+ if (bufsize < NTFS_SB_SIZE)
+ memset(&outbuf[bufsize + 2], 0, NTFS_SB_SIZE - bufsize);
+ outbuf[0] = 0xff;
+ outbuf[1] = 0x3f;
+ xout = NTFS_SB_SIZE + 2;
+ }
+
+ /*
+ * Free the compression context and return the total number of bytes
+ * written to 'outbuf'.
+ */
+ ntfs_free(pctx);
+ return xout;
+}
+
+static int ntfs_write_cb(struct ntfs_inode *ni, loff_t pos, struct page **pages,
+ int pages_per_cb)
+{
+ struct ntfs_volume *vol = ni->vol;
+ char *outbuf = NULL, *pbuf, *inbuf;
+ u32 compsz, p, insz = pages_per_cb << PAGE_SHIFT;
+ s32 rounded, bio_size;
+ unsigned int sz, bsz;
+ bool fail = false, allzeroes;
+ /* a single compressed zero */
+ static char onezero[] = {0x01, 0xb0, 0x00, 0x00};
+ /* a couple of compressed zeroes */
+ static char twozeroes[] = {0x02, 0xb0, 0x00, 0x00, 0x00};
+ /* more compressed zeroes, to be followed by some count */
+ static char morezeroes[] = {0x03, 0xb0, 0x02, 0x00};
+ struct page **pages_disk = NULL, *pg;
+ s64 bio_lcn;
+ struct runlist_element *rlc, *rl;
+ int i, err;
+ int pages_count = (round_up(ni->itype.compressed.block_size + 2 *
+ (ni->itype.compressed.block_size / NTFS_SB_SIZE) + 2, PAGE_SIZE)) / PAGE_SIZE;
+ size_t new_rl_count;
+ struct bio *bio = NULL;
+ loff_t new_length;
+ s64 new_vcn;
+
+ inbuf = vmap(pages, pages_per_cb, VM_MAP, PAGE_KERNEL_RO);
+ if (!inbuf)
+ return -ENOMEM;
+
+ /* may need 2 extra bytes per block and 2 more bytes */
+ pages_disk = kcalloc(pages_count, sizeof(struct page *), GFP_NOFS);
+ if (!pages_disk) {
+ vunmap(inbuf);
+ return -ENOMEM;
+ }
+
+ for (i = 0; i < pages_count; i++) {
+ pg = alloc_page(GFP_KERNEL);
+ if (!pg) {
+ err = -ENOMEM;
+ goto out;
+ }
+ pages_disk[i] = pg;
+ lock_page(pg);
+ kmap_local_page(pg);
+ }
+
+ outbuf = vmap(pages_disk, pages_count, VM_MAP, PAGE_KERNEL);
+ if (!outbuf) {
+ err = -ENOMEM;
+ goto out;
+ }
+
+ compsz = 0;
+ allzeroes = true;
+ for (p = 0; (p < insz) && !fail; p += NTFS_SB_SIZE) {
+ if ((p + NTFS_SB_SIZE) < insz)
+ bsz = NTFS_SB_SIZE;
+ else
+ bsz = insz - p;
+ pbuf = &outbuf[compsz];
+ sz = ntfs_compress_block(&inbuf[p], bsz, pbuf);
+ /* fail if all the clusters (or more) are needed */
+ if (!sz || ((compsz + sz + vol->cluster_size + 2) >
+ ni->itype.compressed.block_size))
+ fail = true;
+ else {
+ if (allzeroes) {
+ /* check whether this is all zeroes */
+ switch (sz) {
+ case 4:
+ allzeroes = !memcmp(pbuf, onezero, 4);
+ break;
+ case 5:
+ allzeroes = !memcmp(pbuf, twozeroes, 5);
+ break;
+ case 6:
+ allzeroes = !memcmp(pbuf, morezeroes, 4);
+ break;
+ default:
+ allzeroes = false;
+ break;
+ }
+ }
+ compsz += sz;
+ }
+ }
+
+ if (!fail && !allzeroes) {
+ outbuf[compsz++] = 0;
+ outbuf[compsz++] = 0;
+ rounded = ((compsz - 1) | (vol->cluster_size - 1)) + 1;
+ memset(&outbuf[compsz], 0, rounded - compsz);
+ bio_size = rounded;
+ pages = pages_disk;
+ } else if (allzeroes) {
+ err = 0;
+ goto out;
+ } else {
+ bio_size = insz;
+ }
+
+ new_vcn = (pos & ~(ni->itype.compressed.block_size - 1)) >> vol->cluster_size_bits;
+ new_length = round_up(bio_size, vol->cluster_size) >> vol->cluster_size_bits;
+
+ err = ntfs_non_resident_attr_punch_hole(ni, new_vcn, ni->itype.compressed.block_clusters);
+ if (err < 0)
+ goto out;
+
+ rlc = ntfs_cluster_alloc(vol, new_vcn, new_length, -1, DATA_ZONE,
+ false, true, true);
+ if (IS_ERR(rlc)) {
+ err = PTR_ERR(rlc);
+ goto out;
+ }
+
+ bio_lcn = rlc->lcn;
+ down_write(&ni->runlist.lock);
+ rl = ntfs_runlists_merge(&ni->runlist, rlc, 0, &new_rl_count);
+ if (IS_ERR(rl)) {
+ up_write(&ni->runlist.lock);
+ ntfs_error(vol->sb, "Failed to merge runlists");
+ err = PTR_ERR(rl);
+ if (ntfs_cluster_free_from_rl(vol, rlc))
+ ntfs_error(vol->sb, "Failed to free hot clusters.");
+ ntfs_free(rlc);
+ goto out;
+ }
+
+ ni->runlist.count = new_rl_count;
+ ni->runlist.rl = rl;
+
+ err = ntfs_attr_update_mapping_pairs(ni, 0);
+ up_write(&ni->runlist.lock);
+ if (err) {
+ err = -EIO;
+ goto out;
+ }
+
+ i = 0;
+ while (bio_size > 0) {
+ int page_size;
+
+ if (bio_size >= PAGE_SIZE) {
+ page_size = PAGE_SIZE;
+ bio_size -= PAGE_SIZE;
+ } else {
+ page_size = bio_size;
+ bio_size = 0;
+ }
+
+setup_bio:
+ if (!bio) {
+ bio = ntfs_setup_bio(vol, REQ_OP_WRITE, bio_lcn + i, 0);
+ if (!bio) {
+ err = -ENOMEM;
+ goto out;
+ }
+ }
+
+ if (!bio_add_page(bio, pages[i], page_size, 0)) {
+ err = submit_bio_wait(bio);
+ bio_put(bio);
+ if (err)
+ goto out;
+ bio = NULL;
+ goto setup_bio;
+ }
+ i++;
+ }
+
+ err = submit_bio_wait(bio);
+ bio_put(bio);
+out:
+ vunmap(outbuf);
+ for (i = 0; i < pages_count; i++) {
+ pg = pages_disk[i];
+ if (pg) {
+ kunmap_local(page_address(pg));
+ unlock_page(pg);
+ put_page(pg);
+ }
+ }
+ kfree(pages_disk);
+ vunmap(inbuf);
+ NInoSetFileNameDirty(ni);
+ mark_mft_record_dirty(ni);
+
+ return err;
+}
+
+int ntfs_compress_write(struct ntfs_inode *ni, loff_t pos, size_t count,
+ struct iov_iter *from)
+{
+ struct folio *folio;
+ struct page **pages = NULL, *page;
+ int pages_per_cb = ni->itype.compressed.block_size >> PAGE_SHIFT;
+ int cb_size = ni->itype.compressed.block_size, cb_off, err = 0;
+ int i, ip;
+ size_t written = 0;
+ struct address_space *mapping = VFS_I(ni)->i_mapping;
+
+ pages = kmalloc_array(pages_per_cb, sizeof(struct page *), GFP_NOFS);
+ if (!pages)
+ return -ENOMEM;
+
+ while (count) {
+ pgoff_t index;
+ size_t copied, bytes;
+ int off;
+
+ off = pos & (cb_size - 1);
+ bytes = cb_size - off;
+ if (bytes > count)
+ bytes = count;
+
+ cb_off = pos & ~(cb_size - 1);
+ index = cb_off >> PAGE_SHIFT;
+
+ if (unlikely(fault_in_iov_iter_readable(from, bytes))) {
+ err = -EFAULT;
+ goto out;
+ }
+
+ for (i = 0; i < pages_per_cb; i++) {
+ folio = ntfs_read_mapping_folio(mapping, index + i);
+ if (IS_ERR(folio)) {
+ for (ip = 0; ip < i; ip++) {
+ folio_unlock(page_folio(pages[ip]));
+ folio_put(page_folio(pages[ip]));
+ }
+ err = PTR_ERR(folio);
+ goto out;
+ }
+
+ folio_lock(folio);
+ pages[i] = folio_page(folio, 0);
+ }
+
+ WARN_ON(!bytes);
+ copied = 0;
+ ip = off >> PAGE_SHIFT;
+ off = offset_in_page(pos);
+
+ for (;;) {
+ size_t cp, tail = PAGE_SIZE - off;
+
+ page = pages[ip];
+ cp = copy_folio_from_iter_atomic(page_folio(page), off,
+ min(tail, bytes), from);
+ flush_dcache_page(page);
+
+ copied += cp;
+ bytes -= cp;
+ if (!bytes || !cp)
+ break;
+
+ if (cp < tail) {
+ off += cp;
+ } else {
+ ip++;
+ off = 0;
+ }
+ }
+
+ err = ntfs_write_cb(ni, pos, pages, pages_per_cb);
+
+ for (i = 0; i < pages_per_cb; i++) {
+ folio = page_folio(pages[i]);
+ if (i < ip) {
+ folio_clear_dirty(folio);
+ folio_mark_uptodate(folio);
+ }
+ folio_unlock(folio);
+ folio_put(folio);
+ }
+
+ if (err)
+ goto out;
+
+ cond_resched();
+ pos += copied;
+ written += copied;
+ count = iov_iter_count(from);
+ }
+
+out:
+ kfree(pages);
+ if (err < 0)
+ written = err;
+
+ return written;
+}
--
2.34.1
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH 08/11] ntfsplus: add runlist handling and cluster allocator
2025-10-20 2:12 [PATCH 06/11] ntfsplus: add iomap and address space operations Namjae Jeon
2025-10-20 2:12 ` [PATCH 07/11] ntfsplus: add attrib operatrions Namjae Jeon
@ 2025-10-20 2:12 ` Namjae Jeon
2025-10-20 2:12 ` [PATCH 09/11] ntfsplus: add reparse and ea operations Namjae Jeon
` (2 subsequent siblings)
4 siblings, 0 replies; 6+ messages in thread
From: Namjae Jeon @ 2025-10-20 2:12 UTC (permalink / raw)
To: viro, brauner, hch, hch, tytso, willy, jack, djwong, josef,
sandeen, rgoldwyn, xiang, dsterba, pali, ebiggers, neil,
amir73il
Cc: linux-fsdevel, linux-kernel, iamjoonsoo.kim, cheol.lee, jay.sim,
gunho.lee, Namjae Jeon
This adds the implementation of runlist handling and cluster allocator
for ntfsplus.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
---
fs/ntfsplus/bitmap.c | 193 ++++
fs/ntfsplus/lcnalloc.c | 993 ++++++++++++++++++++
fs/ntfsplus/runlist.c | 1995 ++++++++++++++++++++++++++++++++++++++++
3 files changed, 3181 insertions(+)
create mode 100644 fs/ntfsplus/bitmap.c
create mode 100644 fs/ntfsplus/lcnalloc.c
create mode 100644 fs/ntfsplus/runlist.c
diff --git a/fs/ntfsplus/bitmap.c b/fs/ntfsplus/bitmap.c
new file mode 100644
index 000000000000..9454c9d64be2
--- /dev/null
+++ b/fs/ntfsplus/bitmap.c
@@ -0,0 +1,193 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * NTFS kernel bitmap handling. Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2004-2005 Anton Altaparmakov
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ */
+
+#include "bitmap.h"
+#include "aops.h"
+#include "ntfs.h"
+
+/**
+ * __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
+ * @count: number of bits to set
+ * @value: value to set the bits to (i.e. 0 or 1)
+ * @is_rollback: if 'true' this is a rollback operation
+ *
+ * Set @count bits starting at bit @start_bit in the bitmap described by the
+ * vfs inode @vi to @value, where @value is either 0 or 1.
+ *
+ * @is_rollback should always be 'false', it is for internal use to rollback
+ * errors. You probably want to use ntfs_bitmap_set_bits_in_run() instead.
+ */
+int __ntfs_bitmap_set_bits_in_run(struct inode *vi, const s64 start_bit,
+ const s64 count, const u8 value, const bool is_rollback)
+{
+ s64 cnt = count;
+ pgoff_t index, end_index;
+ struct address_space *mapping;
+ struct folio *folio;
+ u8 *kaddr;
+ int pos, len;
+ u8 bit;
+ struct ntfs_inode *ni = NTFS_I(vi);
+ struct ntfs_volume *vol = ni->vol;
+
+ BUG_ON(!vi);
+ ntfs_debug("Entering for i_ino 0x%lx, start_bit 0x%llx, count 0x%llx, value %u.%s",
+ vi->i_ino, (unsigned long long)start_bit,
+ (unsigned long long)cnt, (unsigned int)value,
+ is_rollback ? " (rollback)" : "");
+ BUG_ON(start_bit < 0);
+ BUG_ON(cnt < 0);
+ BUG_ON(value > 1);
+ /*
+ * Calculate the indices for the pages containing the first and last
+ * bits, i.e. @start_bit and @start_bit + @cnt - 1, respectively.
+ */
+ index = start_bit >> (3 + PAGE_SHIFT);
+ end_index = (start_bit + cnt - 1) >> (3 + PAGE_SHIFT);
+
+ /* Get the page containing the first bit (@start_bit). */
+ mapping = vi->i_mapping;
+ folio = ntfs_read_mapping_folio(mapping, index);
+ if (IS_ERR(folio)) {
+ if (!is_rollback)
+ ntfs_error(vi->i_sb,
+ "Failed to map first page (error %li), aborting.",
+ PTR_ERR(folio));
+ return PTR_ERR(folio);
+ }
+
+ folio_lock(folio);
+ kaddr = kmap_local_folio(folio, 0);
+
+ /* Set @pos to the position of the byte containing @start_bit. */
+ pos = (start_bit >> 3) & ~PAGE_MASK;
+
+ /* Calculate the position of @start_bit in the first byte. */
+ bit = start_bit & 7;
+
+ /* If the first byte is partial, modify the appropriate bits in it. */
+ if (bit) {
+ u8 *byte = kaddr + pos;
+
+ if (ni->mft_no == FILE_Bitmap)
+ ntfs_set_lcn_empty_bits(vol, index, value, min_t(s64, 8 - bit, cnt));
+ while ((bit & 7) && cnt) {
+ cnt--;
+ if (value)
+ *byte |= 1 << bit++;
+ else
+ *byte &= ~(1 << bit++);
+ }
+ /* If we are done, unmap the page and return success. */
+ if (!cnt)
+ goto done;
+
+ /* Update @pos to the new position. */
+ pos++;
+ }
+ /*
+ * Depending on @value, modify all remaining whole bytes in the page up
+ * to @cnt.
+ */
+ len = min_t(s64, cnt >> 3, PAGE_SIZE - pos);
+ memset(kaddr + pos, value ? 0xff : 0, len);
+ cnt -= len << 3;
+ if (ni->mft_no == FILE_Bitmap)
+ ntfs_set_lcn_empty_bits(vol, index, value, len << 3);
+
+ /* Update @len to point to the first not-done byte in the page. */
+ if (cnt < 8)
+ len += pos;
+
+ /* If we are not in the last page, deal with all subsequent pages. */
+ while (index < end_index) {
+ BUG_ON(cnt <= 0);
+
+ /* Update @index and get the next folio. */
+ flush_dcache_folio(folio);
+ folio_mark_dirty(folio);
+ folio_unlock(folio);
+ ntfs_unmap_folio(folio, kaddr);
+ folio = ntfs_read_mapping_folio(mapping, ++index);
+ if (IS_ERR(folio)) {
+ ntfs_error(vi->i_sb,
+ "Failed to map subsequent page (error %li), aborting.",
+ PTR_ERR(folio));
+ goto rollback;
+ }
+
+ folio_lock(folio);
+ kaddr = kmap_local_folio(folio, 0);
+ /*
+ * Depending on @value, modify all remaining whole bytes in the
+ * page up to @cnt.
+ */
+ len = min_t(s64, cnt >> 3, PAGE_SIZE);
+ memset(kaddr, value ? 0xff : 0, len);
+ cnt -= len << 3;
+ if (ni->mft_no == FILE_Bitmap)
+ ntfs_set_lcn_empty_bits(vol, index, value, len << 3);
+ }
+ /*
+ * The currently mapped page is the last one. If the last byte is
+ * partial, modify the appropriate bits in it. Note, @len is the
+ * position of the last byte inside the page.
+ */
+ if (cnt) {
+ u8 *byte;
+
+ BUG_ON(cnt > 7);
+
+ bit = cnt;
+ byte = kaddr + len;
+ if (ni->mft_no == FILE_Bitmap)
+ ntfs_set_lcn_empty_bits(vol, index, value, bit);
+ while (bit--) {
+ if (value)
+ *byte |= 1 << bit;
+ else
+ *byte &= ~(1 << bit);
+ }
+ }
+done:
+ /* We are done. Unmap the folio and return success. */
+ flush_dcache_folio(folio);
+ folio_mark_dirty(folio);
+ folio_unlock(folio);
+ ntfs_unmap_folio(folio, kaddr);
+ ntfs_debug("Done.");
+ return 0;
+rollback:
+ /*
+ * Current state:
+ * - no pages are mapped
+ * - @count - @cnt is the number of bits that have been modified
+ */
+ if (is_rollback)
+ return PTR_ERR(folio);
+ if (count != cnt)
+ pos = __ntfs_bitmap_set_bits_in_run(vi, start_bit, count - cnt,
+ value ? 0 : 1, true);
+ else
+ pos = 0;
+ if (!pos) {
+ /* Rollback was successful. */
+ ntfs_error(vi->i_sb,
+ "Failed to map subsequent page (error %li), aborting.",
+ PTR_ERR(folio));
+ } else {
+ /* Rollback failed. */
+ ntfs_error(vi->i_sb,
+ "Failed to map subsequent page (error %li) and rollback failed (error %i). Aborting and leaving inconsistent metadata. Unmount and run chkdsk.",
+ PTR_ERR(folio), pos);
+ NVolSetErrors(NTFS_SB(vi->i_sb));
+ }
+ return PTR_ERR(folio);
+}
diff --git a/fs/ntfsplus/lcnalloc.c b/fs/ntfsplus/lcnalloc.c
new file mode 100644
index 000000000000..bac93a896c03
--- /dev/null
+++ b/fs/ntfsplus/lcnalloc.c
@@ -0,0 +1,993 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Cluster (de)allocation code. Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2004-2005 Anton Altaparmakov
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ *
+ * Part of this file is based on code from the NTFS-3G project.
+ * and is copyrighted by the respective authors below:
+ * Copyright (c) 2002-2004 Anton Altaparmakov
+ * Copyright (c) 2004 Yura Pakhuchiy
+ * Copyright (c) 2004-2008 Szabolcs Szakacsits
+ * Copyright (c) 2008-2009 Jean-Pierre Andre
+ */
+
+#include "lcnalloc.h"
+#include "bitmap.h"
+#include "misc.h"
+#include "aops.h"
+#include "ntfs.h"
+
+/**
+ * ntfs_cluster_free_from_rl_nolock - free clusters from runlist
+ * @vol: mounted ntfs volume on which to free the clusters
+ * @rl: runlist describing the clusters to free
+ *
+ * Free all the clusters described by the runlist @rl on the volume @vol. In
+ * the case of an error being returned, at least some of the clusters were not
+ * freed.
+ *
+ * Return 0 on success and -errno on error.
+ *
+ * Locking: - The volume lcn bitmap must be locked for writing on entry and is
+ * left locked on return.
+ */
+int ntfs_cluster_free_from_rl_nolock(struct ntfs_volume *vol,
+ const struct runlist_element *rl)
+{
+ struct inode *lcnbmp_vi = vol->lcnbmp_ino;
+ int ret = 0;
+ s64 nr_freed = 0;
+
+ ntfs_debug("Entering.");
+ if (!rl)
+ return 0;
+
+ if (!NVolFreeClusterKnown(vol))
+ wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
+
+ for (; rl->length; rl++) {
+ int err;
+
+ if (rl->lcn < 0)
+ continue;
+ err = ntfs_bitmap_clear_run(lcnbmp_vi, rl->lcn, rl->length);
+ if (unlikely(err && (!ret || ret == -ENOMEM) && ret != err))
+ ret = err;
+ else
+ nr_freed += rl->length;
+ }
+ ntfs_inc_free_clusters(vol, nr_freed);
+ ntfs_debug("Done.");
+ return ret;
+}
+
+static s64 max_empty_bit_range(unsigned char *buf, int size)
+{
+ int i, j, run = 0;
+ int max_range = 0;
+ s64 start_pos = -1;
+
+ ntfs_debug("Entering\n");
+
+ i = 0;
+ while (i < size) {
+ switch (*buf) {
+ case 0:
+ do {
+ buf++;
+ run += 8;
+ i++;
+ } while ((i < size) && !*buf);
+ break;
+ case 255:
+ if (run > max_range) {
+ max_range = run;
+ start_pos = (s64)i * 8 - run;
+ }
+ run = 0;
+ do {
+ buf++;
+ i++;
+ } while ((i < size) && (*buf == 255));
+ break;
+ default:
+ for (j = 0; j < 8; j++) {
+ int bit = *buf & (1 << j);
+
+ if (bit) {
+ if (run > max_range) {
+ max_range = run;
+ start_pos = (s64)i * 8 + (j - run);
+ }
+ run = 0;
+ } else
+ run++;
+ }
+ i++;
+ buf++;
+ }
+ }
+
+ if (run > max_range)
+ start_pos = (s64)i * 8 - run;
+
+ return start_pos;
+}
+
+/**
+ * ntfs_cluster_alloc - allocate clusters on an ntfs volume
+ *
+ * Allocate @count clusters preferably starting at cluster @start_lcn or at the
+ * current allocator position if @start_lcn is -1, on the mounted ntfs volume
+ * @vol. @zone is either DATA_ZONE for allocation of normal clusters or
+ * MFT_ZONE for allocation of clusters for the master file table, i.e. the
+ * $MFT/$DATA attribute.
+ *
+ * @start_vcn specifies the vcn of the first allocated cluster. This makes
+ * merging the resulting runlist with the old runlist easier.
+ *
+ * If @is_extension is 'true', the caller is allocating clusters to extend an
+ * attribute and if it is 'false', the caller is allocating clusters to fill a
+ * hole in an attribute. Practically the difference is that if @is_extension
+ * is 'true' the returned runlist will be terminated with LCN_ENOENT and if
+ * @is_extension is 'false' the runlist will be terminated with
+ * LCN_RL_NOT_MAPPED.
+ *
+ * You need to check the return value with IS_ERR(). If this is false, the
+ * function was successful and the return value is a runlist describing the
+ * allocated cluster(s). If IS_ERR() is true, the function failed and
+ * PTR_ERR() gives you the error code.
+ *
+ * Notes on the allocation algorithm
+ * =================================
+ *
+ * There are two data zones. First is the area between the end of the mft zone
+ * and the end of the volume, and second is the area between the start of the
+ * volume and the start of the mft zone. On unmodified/standard NTFS 1.x
+ * volumes, the second data zone does not exist due to the mft zone being
+ * expanded to cover the start of the volume in order to reserve space for the
+ * mft bitmap attribute.
+ *
+ * This is not the prettiest function but the complexity stems from the need of
+ * implementing the mft vs data zoned approach and from the fact that we have
+ * access to the lcn bitmap in portions of up to 8192 bytes at a time, so we
+ * need to cope with crossing over boundaries of two buffers. Further, the
+ * fact that the allocator allows for caller supplied hints as to the location
+ * of where allocation should begin and the fact that the allocator keeps track
+ * of where in the data zones the next natural allocation should occur,
+ * contribute to the complexity of the function. But it should all be
+ * worthwhile, because this allocator should: 1) be a full implementation of
+ * the MFT zone approach used by Windows NT, 2) cause reduction in
+ * fragmentation, and 3) be speedy in allocations (the code is not optimized
+ * for speed, but the algorithm is, so further speed improvements are probably
+ * possible).
+ *
+ * Locking: - The volume lcn bitmap must be unlocked on entry and is unlocked
+ * on return.
+ * - This function takes the volume lcn bitmap lock for writing and
+ * modifies the bitmap contents.
+ */
+struct runlist_element *ntfs_cluster_alloc(struct ntfs_volume *vol, const s64 start_vcn,
+ const s64 count, const s64 start_lcn,
+ const int zone,
+ const bool is_extension,
+ const bool is_contig,
+ const bool is_dealloc)
+{
+ s64 zone_start, zone_end, bmp_pos, bmp_initial_pos, last_read_pos, lcn;
+ s64 prev_lcn = 0, prev_run_len = 0, mft_zone_size;
+ s64 clusters, free_clusters;
+ loff_t i_size;
+ struct inode *lcnbmp_vi;
+ struct runlist_element *rl = NULL;
+ struct address_space *mapping;
+ struct folio *folio = NULL;
+ u8 *buf = NULL, *byte;
+ int err = 0, rlpos, rlsize, buf_size, pg_off;
+ u8 pass, done_zones, search_zone, need_writeback = 0, bit;
+ unsigned int memalloc_flags;
+ u8 has_guess;
+ pgoff_t index;
+
+ ntfs_debug("Entering for start_vcn 0x%llx, count 0x%llx, start_lcn 0x%llx, zone %s_ZONE.",
+ start_vcn, count, start_lcn,
+ zone == MFT_ZONE ? "MFT" : "DATA");
+ BUG_ON(!vol);
+ lcnbmp_vi = vol->lcnbmp_ino;
+ BUG_ON(!lcnbmp_vi);
+ BUG_ON(start_vcn < 0);
+ BUG_ON(count < 0);
+ BUG_ON(start_lcn < LCN_HOLE);
+ BUG_ON(zone < FIRST_ZONE);
+ BUG_ON(zone > LAST_ZONE);
+
+ /* Return NULL if @count is zero. */
+ if (!count)
+ return ERR_PTR(-EINVAL);
+
+ memalloc_flags = memalloc_nofs_save();
+
+ if (!NVolFreeClusterKnown(vol))
+ wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
+ free_clusters = atomic64_read(&vol->free_clusters);
+
+ /* Take the lcnbmp lock for writing. */
+ down_write(&vol->lcnbmp_lock);
+ if (is_dealloc == false)
+ free_clusters -= atomic64_read(&vol->dirty_clusters);
+
+ if (free_clusters < count) {
+ up_write(&vol->lcnbmp_lock);
+ return ERR_PTR(-ENOSPC);
+ }
+
+ /*
+ * If no specific @start_lcn was requested, use the current data zone
+ * position, otherwise use the requested @start_lcn but make sure it
+ * lies outside the mft zone. Also set done_zones to 0 (no zones done)
+ * and pass depending on whether we are starting inside a zone (1) or
+ * at the beginning of a zone (2). If requesting from the MFT_ZONE,
+ * we either start at the current position within the mft zone or at
+ * the specified position. If the latter is out of bounds then we start
+ * at the beginning of the MFT_ZONE.
+ */
+ done_zones = 0;
+ pass = 1;
+ /*
+ * zone_start and zone_end are the current search range. search_zone
+ * is 1 for mft zone, 2 for data zone 1 (end of mft zone till end of
+ * volume) and 4 for data zone 2 (start of volume till start of mft
+ * zone).
+ */
+ has_guess = 1;
+ zone_start = start_lcn;
+
+ if (zone_start < 0) {
+ if (zone == DATA_ZONE)
+ zone_start = vol->data1_zone_pos;
+ else
+ zone_start = vol->mft_zone_pos;
+ if (!zone_start) {
+ /*
+ * Zone starts at beginning of volume which means a
+ * single pass is sufficient.
+ */
+ pass = 2;
+ }
+ has_guess = 0;
+ } else if (zone == DATA_ZONE && zone_start >= vol->mft_zone_start &&
+ zone_start < vol->mft_zone_end) {
+ zone_start = vol->mft_zone_end;
+ /*
+ * Starting at beginning of data1_zone which means a single
+ * pass in this zone is sufficient.
+ */
+ pass = 2;
+ } else if (zone == MFT_ZONE && (zone_start < vol->mft_zone_start ||
+ zone_start >= vol->mft_zone_end)) {
+ zone_start = vol->mft_lcn;
+ if (!vol->mft_zone_end)
+ zone_start = 0;
+ /*
+ * Starting at beginning of volume which means a single pass
+ * is sufficient.
+ */
+ pass = 2;
+ }
+
+ if (zone == MFT_ZONE) {
+ zone_end = vol->mft_zone_end;
+ search_zone = 1;
+ } else /* if (zone == DATA_ZONE) */ {
+ /* Skip searching the mft zone. */
+ done_zones |= 1;
+ if (zone_start >= vol->mft_zone_end) {
+ zone_end = vol->nr_clusters;
+ search_zone = 2;
+ } else {
+ zone_end = vol->mft_zone_start;
+ search_zone = 4;
+ }
+ }
+ /*
+ * bmp_pos is the current bit position inside the bitmap. We use
+ * bmp_initial_pos to determine whether or not to do a zone switch.
+ */
+ bmp_pos = bmp_initial_pos = zone_start;
+
+ /* Loop until all clusters are allocated, i.e. clusters == 0. */
+ clusters = count;
+ rlpos = rlsize = 0;
+ mapping = lcnbmp_vi->i_mapping;
+ i_size = i_size_read(lcnbmp_vi);
+ while (1) {
+ ntfs_debug("Start of outer while loop: done_zones 0x%x, search_zone %i, pass %i, zone_start 0x%llx, zone_end 0x%llx, bmp_initial_pos 0x%llx, bmp_pos 0x%llx, rlpos %i, rlsize %i.",
+ done_zones, search_zone, pass,
+ zone_start, zone_end, bmp_initial_pos,
+ bmp_pos, rlpos, rlsize);
+ /* Loop until we run out of free clusters. */
+ last_read_pos = bmp_pos >> 3;
+ ntfs_debug("last_read_pos 0x%llx.", last_read_pos);
+ if (last_read_pos >= i_size) {
+ ntfs_debug("End of attribute reached. Skipping to zone_pass_done.");
+ goto zone_pass_done;
+ }
+ if (likely(folio)) {
+ if (need_writeback) {
+ ntfs_debug("Marking page dirty.");
+ flush_dcache_folio(folio);
+ folio_mark_dirty(folio);
+ need_writeback = 0;
+ }
+ folio_unlock(folio);
+ ntfs_unmap_folio(folio, buf);
+ folio = NULL;
+ }
+
+ index = last_read_pos >> PAGE_SHIFT;
+ pg_off = last_read_pos & ~PAGE_MASK;
+ buf_size = PAGE_SIZE - pg_off;
+ if (unlikely(last_read_pos + buf_size > i_size))
+ buf_size = i_size - last_read_pos;
+ buf_size <<= 3;
+ lcn = bmp_pos & 7;
+ bmp_pos &= ~(s64)7;
+
+ if (vol->lcn_empty_bits_per_page[index] == 0)
+ goto next_bmp_pos;
+
+ folio = ntfs_read_mapping_folio(mapping, index);
+ if (IS_ERR(folio)) {
+ err = PTR_ERR(folio);
+ ntfs_error(vol->sb, "Failed to map page.");
+ goto out;
+ }
+
+ folio_lock(folio);
+ buf = kmap_local_folio(folio, 0) + pg_off;
+ ntfs_debug("Before inner while loop: buf_size %i, lcn 0x%llx, bmp_pos 0x%llx, need_writeback %i.",
+ buf_size, lcn, bmp_pos, need_writeback);
+ while (lcn < buf_size && lcn + bmp_pos < zone_end) {
+ byte = buf + (lcn >> 3);
+ ntfs_debug("In inner while loop: buf_size %i, lcn 0x%llx, bmp_pos 0x%llx, need_writeback %i, byte ofs 0x%x, *byte 0x%x.",
+ buf_size, lcn, bmp_pos, need_writeback,
+ (unsigned int)(lcn >> 3),
+ (unsigned int)*byte);
+ bit = 1 << (lcn & 7);
+ ntfs_debug("bit 0x%x.", bit);
+
+ if (has_guess) {
+ if (*byte & bit) {
+ if (is_contig == true && prev_run_len > 0)
+ goto done;
+
+ has_guess = 0;
+ break;
+ }
+ } else {
+ lcn = max_empty_bit_range(buf, buf_size >> 3);
+ if (lcn < 0)
+ break;
+ has_guess = 1;
+ continue;
+ }
+ /*
+ * Allocate more memory if needed, including space for
+ * the terminator element.
+ * ntfs_malloc_nofs() operates on whole pages only.
+ */
+ if ((rlpos + 2) * sizeof(*rl) > rlsize) {
+ struct runlist_element *rl2;
+
+ ntfs_debug("Reallocating memory.");
+ if (!rl)
+ ntfs_debug("First free bit is at s64 0x%llx.",
+ lcn + bmp_pos);
+ rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
+ if (unlikely(!rl2)) {
+ err = -ENOMEM;
+ ntfs_error(vol->sb, "Failed to allocate memory.");
+ goto out;
+ }
+ memcpy(rl2, rl, rlsize);
+ ntfs_free(rl);
+ rl = rl2;
+ rlsize += PAGE_SIZE;
+ ntfs_debug("Reallocated memory, rlsize 0x%x.",
+ rlsize);
+ }
+ /* Allocate the bitmap bit. */
+ *byte |= bit;
+ /* We need to write this bitmap page to disk. */
+ need_writeback = 1;
+ ntfs_debug("*byte 0x%x, need_writeback is set.",
+ (unsigned int)*byte);
+ ntfs_dec_free_clusters(vol, 1);
+ ntfs_set_lcn_empty_bits(vol, index, 1, 1);
+
+ /*
+ * Coalesce with previous run if adjacent LCNs.
+ * Otherwise, append a new run.
+ */
+ ntfs_debug("Adding run (lcn 0x%llx, len 0x%llx), prev_lcn 0x%llx, lcn 0x%llx, bmp_pos 0x%llx, prev_run_len 0x%llx, rlpos %i.",
+ lcn + bmp_pos, 1ULL, prev_lcn,
+ lcn, bmp_pos, prev_run_len, rlpos);
+ if (prev_lcn == lcn + bmp_pos - prev_run_len && rlpos) {
+ ntfs_debug("Coalescing to run (lcn 0x%llx, len 0x%llx).",
+ rl[rlpos - 1].lcn,
+ rl[rlpos - 1].length);
+ rl[rlpos - 1].length = ++prev_run_len;
+ ntfs_debug("Run now (lcn 0x%llx, len 0x%llx), prev_run_len 0x%llx.",
+ rl[rlpos - 1].lcn,
+ rl[rlpos - 1].length,
+ prev_run_len);
+ } else {
+ if (likely(rlpos)) {
+ ntfs_debug("Adding new run, (previous run lcn 0x%llx, len 0x%llx).",
+ rl[rlpos - 1].lcn, rl[rlpos - 1].length);
+ rl[rlpos].vcn = rl[rlpos - 1].vcn +
+ prev_run_len;
+ } else {
+ ntfs_debug("Adding new run, is first run.");
+ rl[rlpos].vcn = start_vcn;
+ }
+ rl[rlpos].lcn = prev_lcn = lcn + bmp_pos;
+ rl[rlpos].length = prev_run_len = 1;
+ rlpos++;
+ }
+ /* Done? */
+ if (!--clusters) {
+ s64 tc;
+done:
+ /*
+ * Update the current zone position. Positions
+ * of already scanned zones have been updated
+ * during the respective zone switches.
+ */
+ tc = lcn + bmp_pos + 1;
+ ntfs_debug("Done. Updating current zone position, tc 0x%llx, search_zone %i.",
+ tc, search_zone);
+ switch (search_zone) {
+ case 1:
+ ntfs_debug("Before checks, vol->mft_zone_pos 0x%llx.",
+ vol->mft_zone_pos);
+ if (tc >= vol->mft_zone_end) {
+ vol->mft_zone_pos =
+ vol->mft_lcn;
+ if (!vol->mft_zone_end)
+ vol->mft_zone_pos = 0;
+ } else if ((bmp_initial_pos >=
+ vol->mft_zone_pos ||
+ tc > vol->mft_zone_pos)
+ && tc >= vol->mft_lcn)
+ vol->mft_zone_pos = tc;
+ ntfs_debug("After checks, vol->mft_zone_pos 0x%llx.",
+ vol->mft_zone_pos);
+ break;
+ case 2:
+ ntfs_debug("Before checks, vol->data1_zone_pos 0x%llx.",
+ vol->data1_zone_pos);
+ if (tc >= vol->nr_clusters)
+ vol->data1_zone_pos =
+ vol->mft_zone_end;
+ else if ((bmp_initial_pos >=
+ vol->data1_zone_pos ||
+ tc > vol->data1_zone_pos)
+ && tc >= vol->mft_zone_end)
+ vol->data1_zone_pos = tc;
+ ntfs_debug("After checks, vol->data1_zone_pos 0x%llx.",
+ vol->data1_zone_pos);
+ break;
+ case 4:
+ ntfs_debug("Before checks, vol->data2_zone_pos 0x%llx.",
+ vol->data2_zone_pos);
+ if (tc >= vol->mft_zone_start)
+ vol->data2_zone_pos = 0;
+ else if (bmp_initial_pos >=
+ vol->data2_zone_pos ||
+ tc > vol->data2_zone_pos)
+ vol->data2_zone_pos = tc;
+ ntfs_debug("After checks, vol->data2_zone_pos 0x%llx.",
+ vol->data2_zone_pos);
+ break;
+ default:
+ BUG();
+ }
+ ntfs_debug("Finished. Going to out.");
+ goto out;
+ }
+ lcn++;
+ }
+next_bmp_pos:
+ bmp_pos += buf_size;
+ ntfs_debug("After inner while loop: buf_size 0x%x, lcn 0x%llx, bmp_pos 0x%llx, need_writeback %i.",
+ buf_size, lcn, bmp_pos, need_writeback);
+ if (bmp_pos < zone_end) {
+ ntfs_debug("Continuing outer while loop, bmp_pos 0x%llx, zone_end 0x%llx.",
+ bmp_pos, zone_end);
+ continue;
+ }
+zone_pass_done: /* Finished with the current zone pass. */
+ ntfs_debug("At zone_pass_done, pass %i.", pass);
+ if (pass == 1) {
+ /*
+ * Now do pass 2, scanning the first part of the zone
+ * we omitted in pass 1.
+ */
+ pass = 2;
+ zone_end = zone_start;
+ switch (search_zone) {
+ case 1: /* mft_zone */
+ zone_start = vol->mft_zone_start;
+ break;
+ case 2: /* data1_zone */
+ zone_start = vol->mft_zone_end;
+ break;
+ case 4: /* data2_zone */
+ zone_start = 0;
+ break;
+ default:
+ BUG();
+ }
+ /* Sanity check. */
+ if (zone_end < zone_start)
+ zone_end = zone_start;
+ bmp_pos = zone_start;
+ ntfs_debug("Continuing outer while loop, pass 2, zone_start 0x%llx, zone_end 0x%llx, bmp_pos 0x%llx.",
+ zone_start, zone_end, bmp_pos);
+ continue;
+ } /* pass == 2 */
+done_zones_check:
+ ntfs_debug("At done_zones_check, search_zone %i, done_zones before 0x%x, done_zones after 0x%x.",
+ search_zone, done_zones,
+ done_zones | search_zone);
+ done_zones |= search_zone;
+ if (done_zones < 7) {
+ ntfs_debug("Switching zone.");
+ /* Now switch to the next zone we haven't done yet. */
+ pass = 1;
+ switch (search_zone) {
+ case 1:
+ ntfs_debug("Switching from mft zone to data1 zone.");
+ /* Update mft zone position. */
+ if (rlpos) {
+ s64 tc;
+
+ ntfs_debug("Before checks, vol->mft_zone_pos 0x%llx.",
+ vol->mft_zone_pos);
+ tc = rl[rlpos - 1].lcn +
+ rl[rlpos - 1].length;
+ if (tc >= vol->mft_zone_end) {
+ vol->mft_zone_pos =
+ vol->mft_lcn;
+ if (!vol->mft_zone_end)
+ vol->mft_zone_pos = 0;
+ } else if ((bmp_initial_pos >=
+ vol->mft_zone_pos ||
+ tc > vol->mft_zone_pos)
+ && tc >= vol->mft_lcn)
+ vol->mft_zone_pos = tc;
+ ntfs_debug("After checks, vol->mft_zone_pos 0x%llx.",
+ vol->mft_zone_pos);
+ }
+ /* Switch from mft zone to data1 zone. */
+switch_to_data1_zone: search_zone = 2;
+ zone_start = bmp_initial_pos =
+ vol->data1_zone_pos;
+ zone_end = vol->nr_clusters;
+ if (zone_start == vol->mft_zone_end)
+ pass = 2;
+ if (zone_start >= zone_end) {
+ vol->data1_zone_pos = zone_start =
+ vol->mft_zone_end;
+ pass = 2;
+ }
+ break;
+ case 2:
+ ntfs_debug("Switching from data1 zone to data2 zone.");
+ /* Update data1 zone position. */
+ if (rlpos) {
+ s64 tc;
+
+ ntfs_debug("Before checks, vol->data1_zone_pos 0x%llx.",
+ vol->data1_zone_pos);
+ tc = rl[rlpos - 1].lcn +
+ rl[rlpos - 1].length;
+ if (tc >= vol->nr_clusters)
+ vol->data1_zone_pos =
+ vol->mft_zone_end;
+ else if ((bmp_initial_pos >=
+ vol->data1_zone_pos ||
+ tc > vol->data1_zone_pos)
+ && tc >= vol->mft_zone_end)
+ vol->data1_zone_pos = tc;
+ ntfs_debug("After checks, vol->data1_zone_pos 0x%llx.",
+ vol->data1_zone_pos);
+ }
+ /* Switch from data1 zone to data2 zone. */
+ search_zone = 4;
+ zone_start = bmp_initial_pos =
+ vol->data2_zone_pos;
+ zone_end = vol->mft_zone_start;
+ if (!zone_start)
+ pass = 2;
+ if (zone_start >= zone_end) {
+ vol->data2_zone_pos = zone_start =
+ bmp_initial_pos = 0;
+ pass = 2;
+ }
+ break;
+ case 4:
+ ntfs_debug("Switching from data2 zone to data1 zone.");
+ /* Update data2 zone position. */
+ if (rlpos) {
+ s64 tc;
+
+ ntfs_debug("Before checks, vol->data2_zone_pos 0x%llx.",
+ vol->data2_zone_pos);
+ tc = rl[rlpos - 1].lcn +
+ rl[rlpos - 1].length;
+ if (tc >= vol->mft_zone_start)
+ vol->data2_zone_pos = 0;
+ else if (bmp_initial_pos >=
+ vol->data2_zone_pos ||
+ tc > vol->data2_zone_pos)
+ vol->data2_zone_pos = tc;
+ ntfs_debug("After checks, vol->data2_zone_pos 0x%llx.",
+ vol->data2_zone_pos);
+ }
+ /* Switch from data2 zone to data1 zone. */
+ goto switch_to_data1_zone;
+ default:
+ BUG();
+ }
+ ntfs_debug("After zone switch, search_zone %i, pass %i, bmp_initial_pos 0x%llx, zone_start 0x%llx, zone_end 0x%llx.",
+ search_zone, pass,
+ bmp_initial_pos,
+ zone_start,
+ zone_end);
+ bmp_pos = zone_start;
+ if (zone_start == zone_end) {
+ ntfs_debug("Empty zone, going to done_zones_check.");
+ /* Empty zone. Don't bother searching it. */
+ goto done_zones_check;
+ }
+ ntfs_debug("Continuing outer while loop.");
+ continue;
+ } /* done_zones == 7 */
+ ntfs_debug("All zones are finished.");
+ /*
+ * All zones are finished! If DATA_ZONE, shrink mft zone. If
+ * MFT_ZONE, we have really run out of space.
+ */
+ mft_zone_size = vol->mft_zone_end - vol->mft_zone_start;
+ ntfs_debug("vol->mft_zone_start 0x%llx, vol->mft_zone_end 0x%llx, mft_zone_size 0x%llx.",
+ vol->mft_zone_start, vol->mft_zone_end,
+ mft_zone_size);
+ if (zone == MFT_ZONE || mft_zone_size <= 0) {
+ ntfs_debug("No free clusters left, going to out.");
+ /* Really no more space left on device. */
+ err = -ENOSPC;
+ goto out;
+ } /* zone == DATA_ZONE && mft_zone_size > 0 */
+ ntfs_debug("Shrinking mft zone.");
+ zone_end = vol->mft_zone_end;
+ mft_zone_size >>= 1;
+ if (mft_zone_size > 0)
+ vol->mft_zone_end = vol->mft_zone_start + mft_zone_size;
+ else /* mft zone and data2 zone no longer exist. */
+ vol->data2_zone_pos = vol->mft_zone_start =
+ vol->mft_zone_end = 0;
+ if (vol->mft_zone_pos >= vol->mft_zone_end) {
+ vol->mft_zone_pos = vol->mft_lcn;
+ if (!vol->mft_zone_end)
+ vol->mft_zone_pos = 0;
+ }
+ bmp_pos = zone_start = bmp_initial_pos =
+ vol->data1_zone_pos = vol->mft_zone_end;
+ search_zone = 2;
+ pass = 2;
+ done_zones &= ~2;
+ ntfs_debug("After shrinking mft zone, mft_zone_size 0x%llx, vol->mft_zone_start 0x%llx, vol->mft_zone_end 0x%llx, vol->mft_zone_pos 0x%llx, search_zone 2, pass 2, dones_zones 0x%x, zone_start 0x%llx, zone_end 0x%llx, vol->data1_zone_pos 0x%llx, continuing outer while loop.",
+ mft_zone_size, vol->mft_zone_start,
+ vol->mft_zone_end, vol->mft_zone_pos,
+ done_zones, zone_start, zone_end,
+ vol->data1_zone_pos);
+ }
+ ntfs_debug("After outer while loop.");
+out:
+ ntfs_debug("At out.");
+ /* Add runlist terminator element. */
+ if (likely(rl)) {
+ rl[rlpos].vcn = rl[rlpos - 1].vcn + rl[rlpos - 1].length;
+ rl[rlpos].lcn = is_extension ? LCN_ENOENT : LCN_RL_NOT_MAPPED;
+ rl[rlpos].length = 0;
+ }
+ if (likely(folio && !IS_ERR(folio))) {
+ if (need_writeback) {
+ ntfs_debug("Marking page dirty.");
+ flush_dcache_folio(folio);
+ folio_mark_dirty(folio);
+ need_writeback = 0;
+ }
+ folio_unlock(folio);
+ ntfs_unmap_folio(folio, buf);
+ }
+ if (likely(!err)) {
+ if (is_dealloc == true)
+ ntfs_release_dirty_clusters(vol, rl->length);
+ up_write(&vol->lcnbmp_lock);
+ memalloc_nofs_restore(memalloc_flags);
+ ntfs_debug("Done.");
+ return rl == NULL ? ERR_PTR(-EIO) : rl;
+ }
+ if (err != -ENOSPC)
+ ntfs_error(vol->sb,
+ "Failed to allocate clusters, aborting (error %i).",
+ err);
+ if (rl) {
+ int err2;
+
+ if (err == -ENOSPC)
+ ntfs_debug("Not enough space to complete allocation, err -ENOSPC, first free lcn 0x%llx, could allocate up to 0x%llx clusters.",
+ rl[0].lcn, count - clusters);
+ /* Deallocate all allocated clusters. */
+ ntfs_debug("Attempting rollback...");
+ err2 = ntfs_cluster_free_from_rl_nolock(vol, rl);
+ if (err2) {
+ ntfs_error(vol->sb,
+ "Failed to rollback (error %i). Leaving inconsistent metadata! Unmount and run chkdsk.",
+ err2);
+ NVolSetErrors(vol);
+ }
+ /* Free the runlist. */
+ ntfs_free(rl);
+ } else if (err == -ENOSPC)
+ ntfs_debug("No space left at all, err = -ENOSPC, first free lcn = 0x%llx.",
+ vol->data1_zone_pos);
+ atomic64_set(&vol->dirty_clusters, 0);
+ up_write(&vol->lcnbmp_lock);
+ memalloc_nofs_restore(memalloc_flags);
+ return ERR_PTR(err);
+}
+
+/**
+ * __ntfs_cluster_free - free clusters on an ntfs volume
+ * @ni: ntfs inode whose runlist describes the clusters to free
+ * @start_vcn: vcn in the runlist of @ni at which to start freeing clusters
+ * @count: number of clusters to free or -1 for all clusters
+ * @ctx: active attribute search context if present or NULL if not
+ * @is_rollback: true if this is a rollback operation
+ *
+ * Free @count clusters starting at the cluster @start_vcn in the runlist
+ * described by the vfs inode @ni.
+ *
+ * If @count is -1, all clusters from @start_vcn to the end of the runlist are
+ * deallocated. Thus, to completely free all clusters in a runlist, use
+ * @start_vcn = 0 and @count = -1.
+ *
+ * If @ctx is specified, it is an active search context of @ni and its base mft
+ * record. This is needed when __ntfs_cluster_free() encounters unmapped
+ * runlist fragments and allows their mapping. If you do not have the mft
+ * record mapped, you can specify @ctx as NULL and __ntfs_cluster_free() will
+ * perform the necessary mapping and unmapping.
+ *
+ * Note, __ntfs_cluster_free() saves the state of @ctx on entry and restores it
+ * before returning. Thus, @ctx will be left pointing to the same attribute on
+ * return as on entry. However, the actual pointers in @ctx may point to
+ * different memory locations on return, so you must remember to reset any
+ * cached pointers from the @ctx, i.e. after the call to __ntfs_cluster_free(),
+ * you will probably want to do:
+ * m = ctx->mrec;
+ * a = ctx->attr;
+ * Assuming you cache ctx->attr in a variable @a of type attr_record * and that
+ * you cache ctx->mrec in a variable @m of type struct mft_record *.
+ *
+ * @is_rollback should always be 'false', it is for internal use to rollback
+ * errors. You probably want to use ntfs_cluster_free() instead.
+ *
+ * Note, __ntfs_cluster_free() does not modify the runlist, so you have to
+ * remove from the runlist or mark sparse the freed runs later.
+ *
+ * Return the number of deallocated clusters (not counting sparse ones) on
+ * success and -errno on error.
+ *
+ * WARNING: If @ctx is supplied, regardless of whether success or failure is
+ * returned, you need to check IS_ERR(@ctx->mrec) and if 'true' the @ctx
+ * is no longer valid, i.e. you need to either call
+ * ntfs_attr_reinit_search_ctx() or ntfs_attr_put_search_ctx() on it.
+ * In that case PTR_ERR(@ctx->mrec) will give you the error code for
+ * why the mapping of the old inode failed.
+ *
+ * Locking: - The runlist described by @ni must be locked for writing on entry
+ * and is locked on return. Note the runlist may be modified when
+ * needed runlist fragments need to be mapped.
+ * - The volume lcn bitmap must be unlocked on entry and is unlocked
+ * on return.
+ * - This function takes the volume lcn bitmap lock for writing and
+ * modifies the bitmap contents.
+ * - If @ctx is NULL, the base mft record of @ni must not be mapped on
+ * entry and it will be left unmapped on return.
+ * - If @ctx is not NULL, the base mft record must be mapped on entry
+ * and it will be left mapped on return.
+ */
+s64 __ntfs_cluster_free(struct ntfs_inode *ni, const s64 start_vcn, s64 count,
+ struct ntfs_attr_search_ctx *ctx, const bool is_rollback)
+{
+ s64 delta, to_free, total_freed, real_freed;
+ struct ntfs_volume *vol;
+ struct inode *lcnbmp_vi;
+ struct runlist_element *rl;
+ int err;
+ unsigned int memalloc_flags;
+
+ BUG_ON(!ni);
+ ntfs_debug("Entering for i_ino 0x%lx, start_vcn 0x%llx, count 0x%llx.%s",
+ ni->mft_no, start_vcn, count,
+ is_rollback ? " (rollback)" : "");
+ vol = ni->vol;
+ lcnbmp_vi = vol->lcnbmp_ino;
+ BUG_ON(!lcnbmp_vi);
+ BUG_ON(start_vcn < 0);
+ BUG_ON(count < -1);
+
+ if (!NVolFreeClusterKnown(vol))
+ wait_event(vol->free_waitq, NVolFreeClusterKnown(vol));
+
+ /*
+ * Lock the lcn bitmap for writing but only if not rolling back. We
+ * must hold the lock all the way including through rollback otherwise
+ * rollback is not possible because once we have cleared a bit and
+ * dropped the lock, anyone could have set the bit again, thus
+ * allocating the cluster for another use.
+ */
+ if (likely(!is_rollback)) {
+ memalloc_flags = memalloc_nofs_save();
+ down_write(&vol->lcnbmp_lock);
+ }
+
+ total_freed = real_freed = 0;
+
+ rl = ntfs_attr_find_vcn_nolock(ni, start_vcn, ctx);
+ if (IS_ERR(rl)) {
+ err = PTR_ERR(rl);
+ if (err == -ENOENT) {
+ if (likely(!is_rollback)) {
+ up_write(&vol->lcnbmp_lock);
+ memalloc_nofs_restore(memalloc_flags);
+ }
+ return 0;
+ }
+
+ if (!is_rollback)
+ ntfs_error(vol->sb,
+ "Failed to find first runlist element (error %d), aborting.",
+ err);
+ goto err_out;
+ }
+ if (unlikely(rl->lcn < LCN_HOLE)) {
+ if (!is_rollback)
+ ntfs_error(vol->sb, "First runlist element has invalid lcn, aborting.");
+ err = -EIO;
+ goto err_out;
+ }
+ /* Find the starting cluster inside the run that needs freeing. */
+ delta = start_vcn - rl->vcn;
+
+ /* The number of clusters in this run that need freeing. */
+ to_free = rl->length - delta;
+ if (count >= 0 && to_free > count)
+ to_free = count;
+
+ if (likely(rl->lcn >= 0)) {
+ /* Do the actual freeing of the clusters in this run. */
+ err = ntfs_bitmap_set_bits_in_run(lcnbmp_vi, rl->lcn + delta,
+ to_free, likely(!is_rollback) ? 0 : 1);
+ if (unlikely(err)) {
+ if (!is_rollback)
+ ntfs_error(vol->sb,
+ "Failed to clear first run (error %i), aborting.",
+ err);
+ goto err_out;
+ }
+ /* We have freed @to_free real clusters. */
+ real_freed = to_free;
+ }
+ /* Go to the next run and adjust the number of clusters left to free. */
+ ++rl;
+ if (count >= 0)
+ count -= to_free;
+
+ /* Keep track of the total "freed" clusters, including sparse ones. */
+ total_freed = to_free;
+ /*
+ * Loop over the remaining runs, using @count as a capping value, and
+ * free them.
+ */
+ for (; rl->length && count != 0; ++rl) {
+ if (unlikely(rl->lcn < LCN_HOLE)) {
+ s64 vcn;
+
+ /* Attempt to map runlist. */
+ vcn = rl->vcn;
+ rl = ntfs_attr_find_vcn_nolock(ni, vcn, ctx);
+ if (IS_ERR(rl)) {
+ err = PTR_ERR(rl);
+ if (!is_rollback)
+ ntfs_error(vol->sb,
+ "Failed to map runlist fragment or failed to find subsequent runlist element.");
+ goto err_out;
+ }
+ if (unlikely(rl->lcn < LCN_HOLE)) {
+ if (!is_rollback)
+ ntfs_error(vol->sb,
+ "Runlist element has invalid lcn (0x%llx).",
+ rl->lcn);
+ err = -EIO;
+ goto err_out;
+ }
+ }
+ /* The number of clusters in this run that need freeing. */
+ to_free = rl->length;
+ if (count >= 0 && to_free > count)
+ to_free = count;
+
+ if (likely(rl->lcn >= 0)) {
+ /* Do the actual freeing of the clusters in the run. */
+ err = ntfs_bitmap_set_bits_in_run(lcnbmp_vi, rl->lcn,
+ to_free, likely(!is_rollback) ? 0 : 1);
+ if (unlikely(err)) {
+ if (!is_rollback)
+ ntfs_error(vol->sb, "Failed to clear subsequent run.");
+ goto err_out;
+ }
+ /* We have freed @to_free real clusters. */
+ real_freed += to_free;
+ }
+ /* Adjust the number of clusters left to free. */
+ if (count >= 0)
+ count -= to_free;
+
+ /* Update the total done clusters. */
+ total_freed += to_free;
+ }
+ ntfs_inc_free_clusters(vol, real_freed);
+ if (likely(!is_rollback)) {
+ up_write(&vol->lcnbmp_lock);
+ memalloc_nofs_restore(memalloc_flags);
+ }
+
+ BUG_ON(count > 0);
+
+ /* We are done. Return the number of actually freed clusters. */
+ ntfs_debug("Done.");
+ return real_freed;
+err_out:
+ if (is_rollback)
+ return err;
+ /* If no real clusters were freed, no need to rollback. */
+ if (!real_freed) {
+ up_write(&vol->lcnbmp_lock);
+ memalloc_nofs_restore(memalloc_flags);
+ return err;
+ }
+ /*
+ * Attempt to rollback and if that succeeds just return the error code.
+ * If rollback fails, set the volume errors flag, emit an error
+ * message, and return the error code.
+ */
+ delta = __ntfs_cluster_free(ni, start_vcn, total_freed, ctx, true);
+ if (delta < 0) {
+ ntfs_error(vol->sb,
+ "Failed to rollback (error %i). Leaving inconsistent metadata! Unmount and run chkdsk.",
+ (int)delta);
+ NVolSetErrors(vol);
+ }
+ ntfs_dec_free_clusters(vol, delta);
+ up_write(&vol->lcnbmp_lock);
+ memalloc_nofs_restore(memalloc_flags);
+ ntfs_error(vol->sb, "Aborting (error %i).", err);
+ return err;
+}
diff --git a/fs/ntfsplus/runlist.c b/fs/ntfsplus/runlist.c
new file mode 100644
index 000000000000..32ad32989be0
--- /dev/null
+++ b/fs/ntfsplus/runlist.c
@@ -0,0 +1,1995 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/**
+ * NTFS runlist handling code.
+ * Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2001-2007 Anton Altaparmakov
+ * Copyright (c) 2002-2005 Richard Russon
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ *
+ * Part of this file is based on code from the NTFS-3G project.
+ * and is copyrighted by the respective authors below:
+ * Copyright (c) 2002-2005 Anton Altaparmakov
+ * Copyright (c) 2002-2005 Richard Russon
+ * Copyright (c) 2002-2008 Szabolcs Szakacsits
+ * Copyright (c) 2004 Yura Pakhuchiy
+ * Copyright (c) 2007-2022 Jean-Pierre Andre
+ */
+
+#include "misc.h"
+#include "ntfs.h"
+#include "attrib.h"
+
+/**
+ * ntfs_rl_mm - runlist memmove
+ *
+ * It is up to the caller to serialize access to the runlist @base.
+ */
+static inline void ntfs_rl_mm(struct runlist_element *base, int dst, int src, int size)
+{
+ if (likely((dst != src) && (size > 0)))
+ memmove(base + dst, base + src, size * sizeof(*base));
+}
+
+/**
+ * ntfs_rl_mc - runlist memory copy
+ *
+ * It is up to the caller to serialize access to the runlists @dstbase and
+ * @srcbase.
+ */
+static inline void ntfs_rl_mc(struct runlist_element *dstbase, int dst,
+ struct runlist_element *srcbase, int src, int size)
+{
+ if (likely(size > 0))
+ memcpy(dstbase + dst, srcbase + src, size * sizeof(*dstbase));
+}
+
+/**
+ * ntfs_rl_realloc - Reallocate memory for runlists
+ * @rl: original runlist
+ * @old_size: number of runlist elements in the original runlist @rl
+ * @new_size: number of runlist elements we need space for
+ *
+ * As the runlists grow, more memory will be required. To prevent the
+ * kernel having to allocate and reallocate large numbers of small bits of
+ * memory, this function returns an entire page of memory.
+ *
+ * It is up to the caller to serialize access to the runlist @rl.
+ *
+ * N.B. If the new allocation doesn't require a different number of pages in
+ * memory, the function will return the original pointer.
+ */
+struct runlist_element *ntfs_rl_realloc(struct runlist_element *rl,
+ int old_size, int new_size)
+{
+ struct runlist_element *new_rl;
+
+ old_size = PAGE_ALIGN(old_size * sizeof(*rl));
+ new_size = PAGE_ALIGN(new_size * sizeof(*rl));
+ if (old_size == new_size)
+ return rl;
+
+ new_rl = ntfs_malloc_nofs(new_size);
+ if (unlikely(!new_rl))
+ return ERR_PTR(-ENOMEM);
+
+ if (likely(rl != NULL)) {
+ if (unlikely(old_size > new_size))
+ old_size = new_size;
+ memcpy(new_rl, rl, old_size);
+ ntfs_free(rl);
+ }
+ return new_rl;
+}
+
+/**
+ * ntfs_rl_realloc_nofail - Reallocate memory for runlists
+ * @rl: original runlist
+ * @old_size: number of runlist elements in the original runlist @rl
+ * @new_size: number of runlist elements we need space for
+ *
+ * As the runlists grow, more memory will be required. To prevent the
+ * kernel having to allocate and reallocate large numbers of small bits of
+ * memory, this function returns an entire page of memory.
+ *
+ * This function guarantees that the allocation will succeed. It will sleep
+ * for as long as it takes to complete the allocation.
+ *
+ * It is up to the caller to serialize access to the runlist @rl.
+ *
+ * N.B. If the new allocation doesn't require a different number of pages in
+ * memory, the function will return the original pointer.
+ */
+static inline struct runlist_element *ntfs_rl_realloc_nofail(struct runlist_element *rl,
+ int old_size, int new_size)
+{
+ struct runlist_element *new_rl;
+
+ old_size = PAGE_ALIGN(old_size * sizeof(*rl));
+ new_size = PAGE_ALIGN(new_size * sizeof(*rl));
+ if (old_size == new_size)
+ return rl;
+
+ new_rl = ntfs_malloc_nofs_nofail(new_size);
+ BUG_ON(!new_rl);
+
+ if (likely(rl != NULL)) {
+ if (unlikely(old_size > new_size))
+ old_size = new_size;
+ memcpy(new_rl, rl, old_size);
+ ntfs_free(rl);
+ }
+ return new_rl;
+}
+
+/**
+ * ntfs_are_rl_mergeable - test if two runlists can be joined together
+ * @dst: original runlist
+ * @src: new runlist to test for mergeability with @dst
+ *
+ * Test if two runlists can be joined together. For this, their VCNs and LCNs
+ * must be adjacent.
+ *
+ * It is up to the caller to serialize access to the runlists @dst and @src.
+ *
+ * Return: true Success, the runlists can be merged.
+ * false Failure, the runlists cannot be merged.
+ */
+static inline bool ntfs_are_rl_mergeable(struct runlist_element *dst,
+ struct runlist_element *src)
+{
+ BUG_ON(!dst);
+ BUG_ON(!src);
+
+ /* We can merge unmapped regions even if they are misaligned. */
+ if ((dst->lcn == LCN_RL_NOT_MAPPED) && (src->lcn == LCN_RL_NOT_MAPPED))
+ return true;
+ /* If the runs are misaligned, we cannot merge them. */
+ if ((dst->vcn + dst->length) != src->vcn)
+ return false;
+ /* If both runs are non-sparse and contiguous, we can merge them. */
+ if ((dst->lcn >= 0) && (src->lcn >= 0) &&
+ ((dst->lcn + dst->length) == src->lcn))
+ return true;
+ /* If we are merging two holes, we can merge them. */
+ if ((dst->lcn == LCN_HOLE) && (src->lcn == LCN_HOLE))
+ return true;
+ /* If we are merging two dealloc, we can merge them. */
+ if ((dst->lcn == LCN_DELALLOC) && (src->lcn == LCN_DELALLOC))
+ return true;
+ /* Cannot merge. */
+ return false;
+}
+
+/**
+ * __ntfs_rl_merge - merge two runlists without testing if they can be merged
+ * @dst: original, destination runlist
+ * @src: new runlist to merge with @dst
+ *
+ * Merge the two runlists, writing into the destination runlist @dst. The
+ * caller must make sure the runlists can be merged or this will corrupt the
+ * destination runlist.
+ *
+ * It is up to the caller to serialize access to the runlists @dst and @src.
+ */
+static inline void __ntfs_rl_merge(struct runlist_element *dst, struct runlist_element *src)
+{
+ dst->length += src->length;
+}
+
+/**
+ * ntfs_rl_append - append a runlist after a given element
+ *
+ * Append the runlist @src after element @loc in @dst. Merge the right end of
+ * the new runlist, if necessary. Adjust the size of the hole before the
+ * appended runlist.
+ *
+ * It is up to the caller to serialize access to the runlists @dst and @src.
+ *
+ * On success, return a pointer to the new, combined, runlist. Note, both
+ * runlists @dst and @src are deallocated before returning so you cannot use
+ * the pointers for anything any more. (Strictly speaking the returned runlist
+ * may be the same as @dst but this is irrelevant.)
+ */
+static inline struct runlist_element *ntfs_rl_append(struct runlist_element *dst,
+ int dsize, struct runlist_element *src, int ssize, int loc,
+ size_t *new_size)
+{
+ bool right = false; /* Right end of @src needs merging. */
+ int marker; /* End of the inserted runs. */
+
+ BUG_ON(!dst);
+ BUG_ON(!src);
+
+ /* First, check if the right hand end needs merging. */
+ if ((loc + 1) < dsize)
+ right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
+
+ /* Space required: @dst size + @src size, less one if we merged. */
+ dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - right);
+ if (IS_ERR(dst))
+ return dst;
+
+ *new_size = dsize + ssize - right;
+ /*
+ * We are guaranteed to succeed from here so can start modifying the
+ * original runlists.
+ */
+
+ /* First, merge the right hand end, if necessary. */
+ if (right)
+ __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
+
+ /* First run after the @src runs that have been inserted. */
+ marker = loc + ssize + 1;
+
+ /* Move the tail of @dst out of the way, then copy in @src. */
+ ntfs_rl_mm(dst, marker, loc + 1 + right, dsize - (loc + 1 + right));
+ ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
+
+ /* Adjust the size of the preceding hole. */
+ dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
+
+ /* We may have changed the length of the file, so fix the end marker */
+ if (dst[marker].lcn == LCN_ENOENT)
+ dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
+
+ return dst;
+}
+
+/**
+ * ntfs_rl_insert - insert a runlist into another
+ *
+ * Insert the runlist @src before element @loc in the runlist @dst. Merge the
+ * left end of the new runlist, if necessary. Adjust the size of the hole
+ * after the inserted runlist.
+ *
+ * It is up to the caller to serialize access to the runlists @dst and @src.
+ *
+ * On success, return a pointer to the new, combined, runlist. Note, both
+ * runlists @dst and @src are deallocated before returning so you cannot use
+ * the pointers for anything any more. (Strictly speaking the returned runlist
+ * may be the same as @dst but this is irrelevant.)
+ */
+static inline struct runlist_element *ntfs_rl_insert(struct runlist_element *dst,
+ int dsize, struct runlist_element *src, int ssize, int loc,
+ size_t *new_size)
+{
+ bool left = false; /* Left end of @src needs merging. */
+ bool disc = false; /* Discontinuity between @dst and @src. */
+ int marker; /* End of the inserted runs. */
+
+ BUG_ON(!dst);
+ BUG_ON(!src);
+
+ /*
+ * disc => Discontinuity between the end of @dst and the start of @src.
+ * This means we might need to insert a "not mapped" run.
+ */
+ if (loc == 0)
+ disc = (src[0].vcn > 0);
+ else {
+ s64 merged_length;
+
+ left = ntfs_are_rl_mergeable(dst + loc - 1, src);
+
+ merged_length = dst[loc - 1].length;
+ if (left)
+ merged_length += src->length;
+
+ disc = (src[0].vcn > dst[loc - 1].vcn + merged_length);
+ }
+ /*
+ * Space required: @dst size + @src size, less one if we merged, plus
+ * one if there was a discontinuity.
+ */
+ dst = ntfs_rl_realloc(dst, dsize, dsize + ssize - left + disc);
+ if (IS_ERR(dst))
+ return dst;
+
+ *new_size = dsize + ssize - left + disc;
+ /*
+ * We are guaranteed to succeed from here so can start modifying the
+ * original runlist.
+ */
+ if (left)
+ __ntfs_rl_merge(dst + loc - 1, src);
+ /*
+ * First run after the @src runs that have been inserted.
+ * Nominally, @marker equals @loc + @ssize, i.e. location + number of
+ * runs in @src. However, if @left, then the first run in @src has
+ * been merged with one in @dst. And if @disc, then @dst and @src do
+ * not meet and we need an extra run to fill the gap.
+ */
+ marker = loc + ssize - left + disc;
+
+ /* Move the tail of @dst out of the way, then copy in @src. */
+ ntfs_rl_mm(dst, marker, loc, dsize - loc);
+ ntfs_rl_mc(dst, loc + disc, src, left, ssize - left);
+
+ /* Adjust the VCN of the first run after the insertion... */
+ dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
+ /* ... and the length. */
+ if (dst[marker].lcn == LCN_HOLE || dst[marker].lcn == LCN_RL_NOT_MAPPED ||
+ dst[marker].lcn == LCN_DELALLOC)
+ dst[marker].length = dst[marker + 1].vcn - dst[marker].vcn;
+
+ /* Writing beyond the end of the file and there is a discontinuity. */
+ if (disc) {
+ if (loc > 0) {
+ dst[loc].vcn = dst[loc - 1].vcn + dst[loc - 1].length;
+ dst[loc].length = dst[loc + 1].vcn - dst[loc].vcn;
+ } else {
+ dst[loc].vcn = 0;
+ dst[loc].length = dst[loc + 1].vcn;
+ }
+ dst[loc].lcn = LCN_RL_NOT_MAPPED;
+ }
+ return dst;
+}
+
+/**
+ * ntfs_rl_replace - overwrite a runlist element with another runlist
+ *
+ * Replace the runlist element @dst at @loc with @src. Merge the left and
+ * right ends of the inserted runlist, if necessary.
+ *
+ * It is up to the caller to serialize access to the runlists @dst and @src.
+ *
+ * On success, return a pointer to the new, combined, runlist. Note, both
+ * runlists @dst and @src are deallocated before returning so you cannot use
+ * the pointers for anything any more. (Strictly speaking the returned runlist
+ * may be the same as @dst but this is irrelevant.)
+ */
+static inline struct runlist_element *ntfs_rl_replace(struct runlist_element *dst,
+ int dsize, struct runlist_element *src, int ssize, int loc,
+ size_t *new_size)
+{
+ int delta;
+ bool left = false; /* Left end of @src needs merging. */
+ bool right = false; /* Right end of @src needs merging. */
+ int tail; /* Start of tail of @dst. */
+ int marker; /* End of the inserted runs. */
+
+ BUG_ON(!dst);
+ BUG_ON(!src);
+
+ /* First, see if the left and right ends need merging. */
+ if ((loc + 1) < dsize)
+ right = ntfs_are_rl_mergeable(src + ssize - 1, dst + loc + 1);
+ if (loc > 0)
+ left = ntfs_are_rl_mergeable(dst + loc - 1, src);
+ /*
+ * Allocate some space. We will need less if the left, right, or both
+ * ends get merged. The -1 accounts for the run being replaced.
+ */
+ delta = ssize - 1 - left - right;
+ if (delta > 0) {
+ dst = ntfs_rl_realloc(dst, dsize, dsize + delta);
+ if (IS_ERR(dst))
+ return dst;
+ }
+
+ *new_size = dsize + delta;
+ /*
+ * We are guaranteed to succeed from here so can start modifying the
+ * original runlists.
+ */
+
+ /* First, merge the left and right ends, if necessary. */
+ if (right)
+ __ntfs_rl_merge(src + ssize - 1, dst + loc + 1);
+ if (left)
+ __ntfs_rl_merge(dst + loc - 1, src);
+ /*
+ * Offset of the tail of @dst. This needs to be moved out of the way
+ * to make space for the runs to be copied from @src, i.e. the first
+ * run of the tail of @dst.
+ * Nominally, @tail equals @loc + 1, i.e. location, skipping the
+ * replaced run. However, if @right, then one of @dst's runs is
+ * already merged into @src.
+ */
+ tail = loc + right + 1;
+ /*
+ * First run after the @src runs that have been inserted, i.e. where
+ * the tail of @dst needs to be moved to.
+ * Nominally, @marker equals @loc + @ssize, i.e. location + number of
+ * runs in @src. However, if @left, then the first run in @src has
+ * been merged with one in @dst.
+ */
+ marker = loc + ssize - left;
+
+ /* Move the tail of @dst out of the way, then copy in @src. */
+ ntfs_rl_mm(dst, marker, tail, dsize - tail);
+ ntfs_rl_mc(dst, loc, src, left, ssize - left);
+
+ /* We may have changed the length of the file, so fix the end marker. */
+ if (dsize - tail > 0 && dst[marker].lcn == LCN_ENOENT)
+ dst[marker].vcn = dst[marker - 1].vcn + dst[marker - 1].length;
+ return dst;
+}
+
+/**
+ * ntfs_rl_split - insert a runlist into the centre of a hole
+ *
+ * Split the runlist @dst at @loc into two and insert @new in between the two
+ * fragments. No merging of runlists is necessary. Adjust the size of the
+ * holes either side.
+ *
+ * It is up to the caller to serialize access to the runlists @dst and @src.
+ *
+ * On success, return a pointer to the new, combined, runlist. Note, both
+ * runlists @dst and @src are deallocated before returning so you cannot use
+ * the pointers for anything any more. (Strictly speaking the returned runlist
+ * may be the same as @dst but this is irrelevant.)
+ */
+static inline struct runlist_element *ntfs_rl_split(struct runlist_element *dst, int dsize,
+ struct runlist_element *src, int ssize, int loc,
+ size_t *new_size)
+{
+ BUG_ON(!dst);
+ BUG_ON(!src);
+
+ /* Space required: @dst size + @src size + one new hole. */
+ dst = ntfs_rl_realloc(dst, dsize, dsize + ssize + 1);
+ if (IS_ERR(dst))
+ return dst;
+
+ *new_size = dsize + ssize + 1;
+ /*
+ * We are guaranteed to succeed from here so can start modifying the
+ * original runlists.
+ */
+
+ /* Move the tail of @dst out of the way, then copy in @src. */
+ ntfs_rl_mm(dst, loc + 1 + ssize, loc, dsize - loc);
+ ntfs_rl_mc(dst, loc + 1, src, 0, ssize);
+
+ /* Adjust the size of the holes either size of @src. */
+ dst[loc].length = dst[loc+1].vcn - dst[loc].vcn;
+ dst[loc+ssize+1].vcn = dst[loc+ssize].vcn + dst[loc+ssize].length;
+ dst[loc+ssize+1].length = dst[loc+ssize+2].vcn - dst[loc+ssize+1].vcn;
+
+ return dst;
+}
+
+/**
+ * ntfs_runlists_merge - merge two runlists into one
+ *
+ * First we sanity check the two runlists @srl and @drl to make sure that they
+ * are sensible and can be merged. The runlist @srl must be either after the
+ * runlist @drl or completely within a hole (or unmapped region) in @drl.
+ *
+ * It is up to the caller to serialize access to the runlists @drl and @srl.
+ *
+ * Merging of runlists is necessary in two cases:
+ * 1. When attribute lists are used and a further extent is being mapped.
+ * 2. When new clusters are allocated to fill a hole or extend a file.
+ *
+ * There are four possible ways @srl can be merged. It can:
+ * - be inserted at the beginning of a hole,
+ * - split the hole in two and be inserted between the two fragments,
+ * - be appended at the end of a hole, or it can
+ * - replace the whole hole.
+ * It can also be appended to the end of the runlist, which is just a variant
+ * of the insert case.
+ *
+ * On success, return a pointer to the new, combined, runlist. Note, both
+ * runlists @drl and @srl are deallocated before returning so you cannot use
+ * the pointers for anything any more. (Strictly speaking the returned runlist
+ * may be the same as @dst but this is irrelevant.)
+ */
+struct runlist_element *ntfs_runlists_merge(struct runlist *d_runlist,
+ struct runlist_element *srl, size_t s_rl_count,
+ size_t *new_rl_count)
+{
+ int di, si; /* Current index into @[ds]rl. */
+ int sstart; /* First index with lcn > LCN_RL_NOT_MAPPED. */
+ int dins; /* Index into @drl at which to insert @srl. */
+ int dend, send; /* Last index into @[ds]rl. */
+ int dfinal, sfinal; /* The last index into @[ds]rl with lcn >= LCN_HOLE. */
+ int marker = 0;
+ s64 marker_vcn = 0;
+ struct runlist_element *drl = d_runlist->rl, *rl;
+
+#ifdef DEBUG
+ ntfs_debug("dst:");
+ ntfs_debug_dump_runlist(drl);
+ ntfs_debug("src:");
+ ntfs_debug_dump_runlist(srl);
+#endif
+
+ /* Check for silly calling... */
+ if (unlikely(!srl))
+ return drl;
+ if (IS_ERR(srl) || IS_ERR(drl))
+ return ERR_PTR(-EINVAL);
+
+ if (s_rl_count == 0) {
+ for (; srl[s_rl_count].length; s_rl_count++)
+ ;
+ s_rl_count++;
+ }
+
+ /* Check for the case where the first mapping is being done now. */
+ if (unlikely(!drl)) {
+ drl = srl;
+ /* Complete the source runlist if necessary. */
+ if (unlikely(drl[0].vcn)) {
+ /* Scan to the end of the source runlist. */
+ drl = ntfs_rl_realloc(drl, s_rl_count, s_rl_count + 1);
+ if (IS_ERR(drl))
+ return drl;
+ /* Insert start element at the front of the runlist. */
+ ntfs_rl_mm(drl, 1, 0, s_rl_count);
+ drl[0].vcn = 0;
+ drl[0].lcn = LCN_RL_NOT_MAPPED;
+ drl[0].length = drl[1].vcn;
+ s_rl_count++;
+ }
+
+ *new_rl_count = s_rl_count;
+ goto finished;
+ }
+
+ if (d_runlist->count < 1 || s_rl_count < 2)
+ return ERR_PTR(-EINVAL);
+
+ si = di = 0;
+
+ /* Skip any unmapped start element(s) in the source runlist. */
+ while (srl[si].length && srl[si].lcn < LCN_HOLE)
+ si++;
+
+ /* Can't have an entirely unmapped source runlist. */
+ BUG_ON(!srl[si].length);
+
+ /* Record the starting points. */
+ sstart = si;
+
+ /*
+ * Skip forward in @drl until we reach the position where @srl needs to
+ * be inserted. If we reach the end of @drl, @srl just needs to be
+ * appended to @drl.
+ */
+ rl = __ntfs_attr_find_vcn_nolock(d_runlist, srl[sstart].vcn);
+ if (IS_ERR(rl))
+ di = (int)d_runlist->count - 1;
+ else
+ di = (int)(rl - d_runlist->rl);
+ dins = di;
+
+ /* Sanity check for illegal overlaps. */
+ if ((drl[di].vcn == srl[si].vcn) && (drl[di].lcn >= 0) &&
+ (srl[si].lcn >= 0)) {
+ ntfs_error(NULL, "Run lists overlap. Cannot merge!");
+ return ERR_PTR(-ERANGE);
+ }
+
+ /* Scan to the end of both runlists in order to know their sizes. */
+ send = (int)s_rl_count - 1;
+ dend = (int)d_runlist->count - 1;
+
+ if (srl[send].lcn == LCN_ENOENT)
+ marker_vcn = srl[marker = send].vcn;
+
+ /* Scan to the last element with lcn >= LCN_HOLE. */
+ for (sfinal = send; sfinal >= 0 && srl[sfinal].lcn < LCN_HOLE; sfinal--)
+ ;
+ for (dfinal = dend; dfinal >= 0 && drl[dfinal].lcn < LCN_HOLE; dfinal--)
+ ;
+
+ {
+ bool start;
+ bool finish;
+ int ds = dend + 1; /* Number of elements in drl & srl */
+ int ss = sfinal - sstart + 1;
+
+ start = ((drl[dins].lcn < LCN_RL_NOT_MAPPED) || /* End of file */
+ (drl[dins].vcn == srl[sstart].vcn)); /* Start of hole */
+ finish = ((drl[dins].lcn >= LCN_RL_NOT_MAPPED) && /* End of file */
+ ((drl[dins].vcn + drl[dins].length) <= /* End of hole */
+ (srl[send - 1].vcn + srl[send - 1].length)));
+
+ /* Or we will lose an end marker. */
+ if (finish && !drl[dins].length)
+ ss++;
+ if (marker && (drl[dins].vcn + drl[dins].length > srl[send - 1].vcn))
+ finish = false;
+
+ if (start) {
+ if (finish)
+ drl = ntfs_rl_replace(drl, ds, srl + sstart, ss, dins, new_rl_count);
+ else
+ drl = ntfs_rl_insert(drl, ds, srl + sstart, ss, dins, new_rl_count);
+ } else {
+ if (finish)
+ drl = ntfs_rl_append(drl, ds, srl + sstart, ss, dins, new_rl_count);
+ else
+ drl = ntfs_rl_split(drl, ds, srl + sstart, ss, dins, new_rl_count);
+ }
+ if (IS_ERR(drl)) {
+ ntfs_error(NULL, "Merge failed.");
+ return drl;
+ }
+ ntfs_free(srl);
+ if (marker) {
+ ntfs_debug("Triggering marker code.");
+ for (ds = dend; drl[ds].length; ds++)
+ ;
+ /* We only need to care if @srl ended after @drl. */
+ if (drl[ds].vcn <= marker_vcn) {
+ int slots = 0;
+
+ if (drl[ds].vcn == marker_vcn) {
+ ntfs_debug("Old marker = 0x%llx, replacing with LCN_ENOENT.",
+ drl[ds].lcn);
+ drl[ds].lcn = LCN_ENOENT;
+ goto finished;
+ }
+ /*
+ * We need to create an unmapped runlist element in
+ * @drl or extend an existing one before adding the
+ * ENOENT terminator.
+ */
+ if (drl[ds].lcn == LCN_ENOENT) {
+ ds--;
+ slots = 1;
+ }
+ if (drl[ds].lcn != LCN_RL_NOT_MAPPED) {
+ /* Add an unmapped runlist element. */
+ if (!slots) {
+ drl = ntfs_rl_realloc_nofail(drl, ds,
+ ds + 2);
+ slots = 2;
+ *new_rl_count += 2;
+ }
+ ds++;
+ /* Need to set vcn if it isn't set already. */
+ if (slots != 1)
+ drl[ds].vcn = drl[ds - 1].vcn +
+ drl[ds - 1].length;
+ drl[ds].lcn = LCN_RL_NOT_MAPPED;
+ /* We now used up a slot. */
+ slots--;
+ }
+ drl[ds].length = marker_vcn - drl[ds].vcn;
+ /* Finally add the ENOENT terminator. */
+ ds++;
+ if (!slots) {
+ drl = ntfs_rl_realloc_nofail(drl, ds, ds + 1);
+ *new_rl_count += 1;
+ }
+ drl[ds].vcn = marker_vcn;
+ drl[ds].lcn = LCN_ENOENT;
+ drl[ds].length = (s64)0;
+ }
+ }
+ }
+
+finished:
+ /* The merge was completed successfully. */
+ ntfs_debug("Merged runlist:");
+ ntfs_debug_dump_runlist(drl);
+ return drl;
+}
+
+/**
+ * ntfs_mapping_pairs_decompress - convert mapping pairs array to runlist
+ *
+ * It is up to the caller to serialize access to the runlist @old_rl.
+ *
+ * Decompress the attribute @attr's mapping pairs array into a runlist. On
+ * success, return the decompressed runlist.
+ *
+ * If @old_rl is not NULL, decompressed runlist is inserted into the
+ * appropriate place in @old_rl and the resultant, combined runlist is
+ * returned. The original @old_rl is deallocated.
+ *
+ * On error, return -errno. @old_rl is left unmodified in that case.
+ */
+struct runlist_element *ntfs_mapping_pairs_decompress(const struct ntfs_volume *vol,
+ const struct attr_record *attr, struct runlist *old_runlist,
+ size_t *new_rl_count)
+{
+ s64 vcn; /* Current vcn. */
+ s64 lcn; /* Current lcn. */
+ s64 deltaxcn; /* Change in [vl]cn. */
+ struct runlist_element *rl, *new_rl; /* The output runlist. */
+ u8 *buf; /* Current position in mapping pairs array. */
+ u8 *attr_end; /* End of attribute. */
+ int rlsize; /* Size of runlist buffer. */
+ u16 rlpos; /* Current runlist position in units of struct runlist_elements. */
+ u8 b; /* Current byte offset in buf. */
+
+#ifdef DEBUG
+ /* Make sure attr exists and is non-resident. */
+ if (!attr || !attr->non_resident ||
+ le64_to_cpu(attr->data.non_resident.lowest_vcn) < 0) {
+ ntfs_error(vol->sb, "Invalid arguments.");
+ return ERR_PTR(-EINVAL);
+ }
+#endif
+ /* Start at vcn = lowest_vcn and lcn 0. */
+ vcn = le64_to_cpu(attr->data.non_resident.lowest_vcn);
+ lcn = 0;
+ /* Get start of the mapping pairs array. */
+ buf = (u8 *)attr +
+ le16_to_cpu(attr->data.non_resident.mapping_pairs_offset);
+ attr_end = (u8 *)attr + le32_to_cpu(attr->length);
+ if (unlikely(buf < (u8 *)attr || buf > attr_end)) {
+ ntfs_error(vol->sb, "Corrupt attribute.");
+ return ERR_PTR(-EIO);
+ }
+
+ /* Current position in runlist array. */
+ rlpos = 0;
+ /* Allocate first page and set current runlist size to one page. */
+ rl = ntfs_malloc_nofs(rlsize = PAGE_SIZE);
+ if (unlikely(!rl))
+ return ERR_PTR(-ENOMEM);
+ /* Insert unmapped starting element if necessary. */
+ if (vcn) {
+ rl->vcn = 0;
+ rl->lcn = LCN_RL_NOT_MAPPED;
+ rl->length = vcn;
+ rlpos++;
+ }
+ while (buf < attr_end && *buf) {
+ /*
+ * Allocate more memory if needed, including space for the
+ * not-mapped and terminator elements. ntfs_malloc_nofs()
+ * operates on whole pages only.
+ */
+ if (((rlpos + 3) * sizeof(*rl)) > rlsize) {
+ struct runlist_element *rl2;
+
+ rl2 = ntfs_malloc_nofs(rlsize + (int)PAGE_SIZE);
+ if (unlikely(!rl2)) {
+ ntfs_free(rl);
+ return ERR_PTR(-ENOMEM);
+ }
+ memcpy(rl2, rl, rlsize);
+ ntfs_free(rl);
+ rl = rl2;
+ rlsize += PAGE_SIZE;
+ }
+ /* Enter the current vcn into the current runlist element. */
+ rl[rlpos].vcn = vcn;
+ /*
+ * Get the change in vcn, i.e. the run length in clusters.
+ * Doing it this way ensures that we signextend negative values.
+ * A negative run length doesn't make any sense, but hey, I
+ * didn't make up the NTFS specs and Windows NT4 treats the run
+ * length as a signed value so that's how it is...
+ */
+ b = *buf & 0xf;
+ if (b) {
+ if (unlikely(buf + b > attr_end))
+ goto io_error;
+ for (deltaxcn = (s8)buf[b--]; b; b--)
+ deltaxcn = (deltaxcn << 8) + buf[b];
+ } else { /* The length entry is compulsory. */
+ ntfs_error(vol->sb, "Missing length entry in mapping pairs array.");
+ deltaxcn = (s64)-1;
+ }
+ /*
+ * Assume a negative length to indicate data corruption and
+ * hence clean-up and return NULL.
+ */
+ if (unlikely(deltaxcn < 0)) {
+ ntfs_error(vol->sb, "Invalid length in mapping pairs array.");
+ goto err_out;
+ }
+ /*
+ * Enter the current run length into the current runlist
+ * element.
+ */
+ rl[rlpos].length = deltaxcn;
+ /* Increment the current vcn by the current run length. */
+ vcn += deltaxcn;
+ /*
+ * There might be no lcn change at all, as is the case for
+ * sparse clusters on NTFS 3.0+, in which case we set the lcn
+ * to LCN_HOLE.
+ */
+ if (!(*buf & 0xf0))
+ rl[rlpos].lcn = LCN_HOLE;
+ else {
+ /* Get the lcn change which really can be negative. */
+ u8 b2 = *buf & 0xf;
+
+ b = b2 + ((*buf >> 4) & 0xf);
+ if (buf + b > attr_end)
+ goto io_error;
+ for (deltaxcn = (s8)buf[b--]; b > b2; b--)
+ deltaxcn = (deltaxcn << 8) + buf[b];
+ /* Change the current lcn to its new value. */
+ lcn += deltaxcn;
+#ifdef DEBUG
+ /*
+ * On NTFS 1.2-, apparently can have lcn == -1 to
+ * indicate a hole. But we haven't verified ourselves
+ * whether it is really the lcn or the deltaxcn that is
+ * -1. So if either is found give us a message so we
+ * can investigate it further!
+ */
+ if (vol->major_ver < 3) {
+ if (unlikely(deltaxcn == -1))
+ ntfs_error(vol->sb, "lcn delta == -1");
+ if (unlikely(lcn == -1))
+ ntfs_error(vol->sb, "lcn == -1");
+ }
+#endif
+ /* Check lcn is not below -1. */
+ if (unlikely(lcn < -1)) {
+ ntfs_error(vol->sb, "Invalid s64 < -1 in mapping pairs array.");
+ goto err_out;
+ }
+
+ /* chkdsk accepts zero-sized runs only for holes */
+ if ((lcn != -1) && !rl[rlpos].length) {
+ ntfs_error(vol->sb, "Invalid zero-sized data run.\n");
+ goto err_out;
+ }
+
+ /* Enter the current lcn into the runlist element. */
+ rl[rlpos].lcn = lcn;
+ }
+ /* Get to the next runlist element, skipping zero-sized holes */
+ if (rl[rlpos].length)
+ rlpos++;
+ /* Increment the buffer position to the next mapping pair. */
+ buf += (*buf & 0xf) + ((*buf >> 4) & 0xf) + 1;
+ }
+ if (unlikely(buf >= attr_end))
+ goto io_error;
+ /*
+ * If there is a highest_vcn specified, it must be equal to the final
+ * vcn in the runlist - 1, or something has gone badly wrong.
+ */
+ deltaxcn = le64_to_cpu(attr->data.non_resident.highest_vcn);
+ if (unlikely(deltaxcn && vcn - 1 != deltaxcn)) {
+mpa_err:
+ ntfs_error(vol->sb, "Corrupt mapping pairs array in non-resident attribute.");
+ goto err_out;
+ }
+ /* Setup not mapped runlist element if this is the base extent. */
+ if (!attr->data.non_resident.lowest_vcn) {
+ s64 max_cluster;
+
+ max_cluster = ((le64_to_cpu(attr->data.non_resident.allocated_size) +
+ vol->cluster_size - 1) >>
+ vol->cluster_size_bits) - 1;
+ /*
+ * A highest_vcn of zero means this is a single extent
+ * attribute so simply terminate the runlist with LCN_ENOENT).
+ */
+ if (deltaxcn) {
+ /*
+ * If there is a difference between the highest_vcn and
+ * the highest cluster, the runlist is either corrupt
+ * or, more likely, there are more extents following
+ * this one.
+ */
+ if (deltaxcn < max_cluster) {
+ ntfs_debug("More extents to follow; deltaxcn = 0x%llx, max_cluster = 0x%llx",
+ deltaxcn, max_cluster);
+ rl[rlpos].vcn = vcn;
+ vcn += rl[rlpos].length = max_cluster -
+ deltaxcn;
+ rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
+ rlpos++;
+ } else if (unlikely(deltaxcn > max_cluster)) {
+ ntfs_error(vol->sb,
+ "Corrupt attribute. deltaxcn = 0x%llx, max_cluster = 0x%llx",
+ deltaxcn, max_cluster);
+ goto mpa_err;
+ }
+ }
+ rl[rlpos].lcn = LCN_ENOENT;
+ } else /* Not the base extent. There may be more extents to follow. */
+ rl[rlpos].lcn = LCN_RL_NOT_MAPPED;
+
+ /* Setup terminating runlist element. */
+ rl[rlpos].vcn = vcn;
+ rl[rlpos].length = (s64)0;
+ /* If no existing runlist was specified, we are done. */
+ if (!old_runlist || !old_runlist->rl) {
+ *new_rl_count = rlpos + 1;
+ ntfs_debug("Mapping pairs array successfully decompressed:");
+ ntfs_debug_dump_runlist(rl);
+ return rl;
+ }
+ /* Now combine the new and old runlists checking for overlaps. */
+ new_rl = ntfs_runlists_merge(old_runlist, rl, rlpos + 1, new_rl_count);
+ if (!IS_ERR(new_rl))
+ return new_rl;
+ ntfs_free(rl);
+ ntfs_error(vol->sb, "Failed to merge runlists.");
+ return new_rl;
+io_error:
+ ntfs_error(vol->sb, "Corrupt attribute.");
+err_out:
+ ntfs_free(rl);
+ return ERR_PTR(-EIO);
+}
+
+/**
+ * ntfs_rl_vcn_to_lcn - convert a vcn into a lcn given a runlist
+ * @rl: runlist to use for conversion
+ * @vcn: vcn to convert
+ *
+ * Convert the virtual cluster number @vcn of an attribute into a logical
+ * cluster number (lcn) of a device using the runlist @rl to map vcns to their
+ * corresponding lcns.
+ *
+ * It is up to the caller to serialize access to the runlist @rl.
+ *
+ * Since lcns must be >= 0, we use negative return codes with special meaning:
+ *
+ * Return code Meaning / Description
+ * ==================================================
+ * LCN_HOLE Hole / not allocated on disk.
+ * LCN_RL_NOT_MAPPED This is part of the runlist which has not been
+ * inserted into the runlist yet.
+ * LCN_ENOENT There is no such vcn in the attribute.
+ *
+ * Locking: - The caller must have locked the runlist (for reading or writing).
+ * - This function does not touch the lock, nor does it modify the
+ * runlist.
+ */
+s64 ntfs_rl_vcn_to_lcn(const struct runlist_element *rl, const s64 vcn)
+{
+ int i;
+
+ BUG_ON(vcn < 0);
+ /*
+ * If rl is NULL, assume that we have found an unmapped runlist. The
+ * caller can then attempt to map it and fail appropriately if
+ * necessary.
+ */
+ if (unlikely(!rl))
+ return LCN_RL_NOT_MAPPED;
+
+ /* Catch out of lower bounds vcn. */
+ if (unlikely(vcn < rl[0].vcn))
+ return LCN_ENOENT;
+
+ for (i = 0; likely(rl[i].length); i++) {
+ if (vcn < rl[i+1].vcn) {
+ if (likely(rl[i].lcn >= 0))
+ return rl[i].lcn + (vcn - rl[i].vcn);
+ return rl[i].lcn;
+ }
+ }
+ /*
+ * The terminator element is setup to the correct value, i.e. one of
+ * LCN_HOLE, LCN_RL_NOT_MAPPED, or LCN_ENOENT.
+ */
+ if (likely(rl[i].lcn < 0))
+ return rl[i].lcn;
+ /* Just in case... We could replace this with BUG() some day. */
+ return LCN_ENOENT;
+}
+
+/**
+ * ntfs_rl_find_vcn_nolock - find a vcn in a runlist
+ * @rl: runlist to search
+ * @vcn: vcn to find
+ *
+ * Find the virtual cluster number @vcn in the runlist @rl and return the
+ * address of the runlist element containing the @vcn on success.
+ *
+ * Return NULL if @rl is NULL or @vcn is in an unmapped part/out of bounds of
+ * the runlist.
+ *
+ * Locking: The runlist must be locked on entry.
+ */
+struct runlist_element *ntfs_rl_find_vcn_nolock(struct runlist_element *rl, const s64 vcn)
+{
+ BUG_ON(vcn < 0);
+ if (unlikely(!rl || vcn < rl[0].vcn))
+ return NULL;
+ while (likely(rl->length)) {
+ if (unlikely(vcn < rl[1].vcn)) {
+ if (likely(rl->lcn >= LCN_HOLE))
+ return rl;
+ return NULL;
+ }
+ rl++;
+ }
+ if (likely(rl->lcn == LCN_ENOENT))
+ return rl;
+ return NULL;
+}
+
+/**
+ * ntfs_get_nr_significant_bytes - get number of bytes needed to store a number
+ * @n: number for which to get the number of bytes for
+ *
+ * Return the number of bytes required to store @n unambiguously as
+ * a signed number.
+ *
+ * This is used in the context of the mapping pairs array to determine how
+ * many bytes will be needed in the array to store a given logical cluster
+ * number (lcn) or a specific run length.
+ *
+ * Return the number of bytes written. This function cannot fail.
+ */
+static inline int ntfs_get_nr_significant_bytes(const s64 n)
+{
+ s64 l = n;
+ int i;
+ s8 j;
+
+ i = 0;
+ do {
+ l >>= 8;
+ i++;
+ } while (l != 0 && l != -1);
+ j = (n >> 8 * (i - 1)) & 0xff;
+ /* If the sign bit is wrong, we need an extra byte. */
+ if ((n < 0 && j >= 0) || (n > 0 && j < 0))
+ i++;
+ return i;
+}
+
+/**
+ * ntfs_get_size_for_mapping_pairs - get bytes needed for mapping pairs array
+ *
+ * Walk the locked runlist @rl and calculate the size in bytes of the mapping
+ * pairs array corresponding to the runlist @rl, starting at vcn @first_vcn and
+ * finishing with vcn @last_vcn.
+ *
+ * A @last_vcn of -1 means end of runlist and in that case the size of the
+ * mapping pairs array corresponding to the runlist starting at vcn @first_vcn
+ * and finishing at the end of the runlist is determined.
+ *
+ * This for example allows us to allocate a buffer of the right size when
+ * building the mapping pairs array.
+ *
+ * If @rl is NULL, just return 1 (for the single terminator byte).
+ *
+ * Return the calculated size in bytes on success. On error, return -errno.
+ */
+int ntfs_get_size_for_mapping_pairs(const struct ntfs_volume *vol,
+ const struct runlist_element *rl, const s64 first_vcn,
+ const s64 last_vcn, int max_mp_size)
+{
+ s64 prev_lcn;
+ int rls;
+ bool the_end = false;
+
+ BUG_ON(first_vcn < 0);
+ BUG_ON(last_vcn < -1);
+ BUG_ON(last_vcn >= 0 && first_vcn > last_vcn);
+ if (!rl) {
+ BUG_ON(first_vcn);
+ BUG_ON(last_vcn > 0);
+ return 1;
+ }
+ if (max_mp_size <= 0)
+ max_mp_size = INT_MAX;
+ /* Skip to runlist element containing @first_vcn. */
+ while (rl->length && first_vcn >= rl[1].vcn)
+ rl++;
+ if (unlikely((!rl->length && first_vcn > rl->vcn) ||
+ first_vcn < rl->vcn))
+ return -EINVAL;
+ prev_lcn = 0;
+ /* Always need the termining zero byte. */
+ rls = 1;
+ /* Do the first partial run if present. */
+ if (first_vcn > rl->vcn) {
+ s64 delta, length = rl->length;
+
+ /* We know rl->length != 0 already. */
+ if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
+ goto err_out;
+ /*
+ * If @stop_vcn is given and finishes inside this run, cap the
+ * run length.
+ */
+ if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
+ s64 s1 = last_vcn + 1;
+
+ if (unlikely(rl[1].vcn > s1))
+ length = s1 - rl->vcn;
+ the_end = true;
+ }
+ delta = first_vcn - rl->vcn;
+ /* Header byte + length. */
+ rls += 1 + ntfs_get_nr_significant_bytes(length - delta);
+ /*
+ * If the logical cluster number (lcn) denotes a hole and we
+ * are on NTFS 3.0+, we don't store it at all, i.e. we need
+ * zero space. On earlier NTFS versions we just store the lcn.
+ * Note: this assumes that on NTFS 1.2-, holes are stored with
+ * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
+ */
+ if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
+ prev_lcn = rl->lcn;
+ if (likely(rl->lcn >= 0))
+ prev_lcn += delta;
+ /* Change in lcn. */
+ rls += ntfs_get_nr_significant_bytes(prev_lcn);
+ }
+ /* Go to next runlist element. */
+ rl++;
+ }
+ /* Do the full runs. */
+ for (; rl->length && !the_end; rl++) {
+ s64 length = rl->length;
+
+ if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
+ goto err_out;
+ /*
+ * If @stop_vcn is given and finishes inside this run, cap the
+ * run length.
+ */
+ if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
+ s64 s1 = last_vcn + 1;
+
+ if (unlikely(rl[1].vcn > s1))
+ length = s1 - rl->vcn;
+ the_end = true;
+ }
+ /* Header byte + length. */
+ rls += 1 + ntfs_get_nr_significant_bytes(length);
+ /*
+ * If the logical cluster number (lcn) denotes a hole and we
+ * are on NTFS 3.0+, we don't store it at all, i.e. we need
+ * zero space. On earlier NTFS versions we just store the lcn.
+ * Note: this assumes that on NTFS 1.2-, holes are stored with
+ * an lcn of -1 and not a delta_lcn of -1 (unless both are -1).
+ */
+ if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
+ /* Change in lcn. */
+ rls += ntfs_get_nr_significant_bytes(rl->lcn -
+ prev_lcn);
+ prev_lcn = rl->lcn;
+ }
+
+ if (rls > max_mp_size)
+ break;
+ }
+ return rls;
+err_out:
+ if (rl->lcn == LCN_RL_NOT_MAPPED)
+ rls = -EINVAL;
+ else
+ rls = -EIO;
+ return rls;
+}
+
+/**
+ * ntfs_write_significant_bytes - write the significant bytes of a number
+ * @dst: destination buffer to write to
+ * @dst_max: pointer to last byte of destination buffer for bounds checking
+ * @n: number whose significant bytes to write
+ *
+ * Store in @dst, the minimum bytes of the number @n which are required to
+ * identify @n unambiguously as a signed number, taking care not to exceed
+ * @dest_max, the maximum position within @dst to which we are allowed to
+ * write.
+ *
+ * This is used when building the mapping pairs array of a runlist to compress
+ * a given logical cluster number (lcn) or a specific run length to the minimum
+ * size possible.
+ *
+ * Return the number of bytes written on success. On error, i.e. the
+ * destination buffer @dst is too small, return -ENOSPC.
+ */
+static inline int ntfs_write_significant_bytes(s8 *dst, const s8 *dst_max,
+ const s64 n)
+{
+ s64 l = n;
+ int i;
+ s8 j;
+
+ i = 0;
+ do {
+ if (unlikely(dst > dst_max))
+ goto err_out;
+ *dst++ = l & 0xffll;
+ l >>= 8;
+ i++;
+ } while (l != 0 && l != -1);
+ j = (n >> 8 * (i - 1)) & 0xff;
+ /* If the sign bit is wrong, we need an extra byte. */
+ if (n < 0 && j >= 0) {
+ if (unlikely(dst > dst_max))
+ goto err_out;
+ i++;
+ *dst = (s8)-1;
+ } else if (n > 0 && j < 0) {
+ if (unlikely(dst > dst_max))
+ goto err_out;
+ i++;
+ *dst = (s8)0;
+ }
+ return i;
+err_out:
+ return -ENOSPC;
+}
+
+/**
+ * ntfs_mapping_pairs_build - build the mapping pairs array from a runlist
+ *
+ * Create the mapping pairs array from the locked runlist @rl, starting at vcn
+ * @first_vcn and finishing with vcn @last_vcn and save the array in @dst.
+ * @dst_len is the size of @dst in bytes and it should be at least equal to the
+ * value obtained by calling ntfs_get_size_for_mapping_pairs().
+ *
+ * A @last_vcn of -1 means end of runlist and in that case the mapping pairs
+ * array corresponding to the runlist starting at vcn @first_vcn and finishing
+ * at the end of the runlist is created.
+ *
+ * If @rl is NULL, just write a single terminator byte to @dst.
+ *
+ * On success or -ENOSPC error, if @stop_vcn is not NULL, *@stop_vcn is set to
+ * the first vcn outside the destination buffer. Note that on error, @dst has
+ * been filled with all the mapping pairs that will fit, thus it can be treated
+ * as partial success, in that a new attribute extent needs to be created or
+ * the next extent has to be used and the mapping pairs build has to be
+ * continued with @first_vcn set to *@stop_vcn.
+ */
+int ntfs_mapping_pairs_build(const struct ntfs_volume *vol, s8 *dst,
+ const int dst_len, const struct runlist_element *rl,
+ const s64 first_vcn, const s64 last_vcn, s64 *const stop_vcn,
+ struct runlist_element **stop_rl, unsigned int *de_cluster_count)
+{
+ s64 prev_lcn;
+ s8 *dst_max, *dst_next;
+ int err = -ENOSPC;
+ bool the_end = false;
+ s8 len_len, lcn_len;
+ unsigned int de_cnt = 0;
+
+ BUG_ON(first_vcn < 0);
+ BUG_ON(last_vcn < -1);
+ BUG_ON(last_vcn >= 0 && first_vcn > last_vcn);
+ BUG_ON(dst_len < 1);
+ if (!rl) {
+ BUG_ON(first_vcn);
+ BUG_ON(last_vcn > 0);
+ if (stop_vcn)
+ *stop_vcn = 0;
+ /* Terminator byte. */
+ *dst = 0;
+ return 0;
+ }
+ /* Skip to runlist element containing @first_vcn. */
+ while (rl->length && first_vcn >= rl[1].vcn)
+ rl++;
+ if (unlikely((!rl->length && first_vcn > rl->vcn) ||
+ first_vcn < rl->vcn))
+ return -EINVAL;
+ /*
+ * @dst_max is used for bounds checking in
+ * ntfs_write_significant_bytes().
+ */
+ dst_max = dst + dst_len - 1;
+ prev_lcn = 0;
+ /* Do the first partial run if present. */
+ if (first_vcn > rl->vcn) {
+ s64 delta, length = rl->length;
+
+ /* We know rl->length != 0 already. */
+ if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
+ goto err_out;
+ /*
+ * If @stop_vcn is given and finishes inside this run, cap the
+ * run length.
+ */
+ if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
+ s64 s1 = last_vcn + 1;
+
+ if (unlikely(rl[1].vcn > s1))
+ length = s1 - rl->vcn;
+ the_end = true;
+ }
+ delta = first_vcn - rl->vcn;
+ /* Write length. */
+ len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
+ length - delta);
+ if (unlikely(len_len < 0))
+ goto size_err;
+ /*
+ * If the logical cluster number (lcn) denotes a hole and we
+ * are on NTFS 3.0+, we don't store it at all, i.e. we need
+ * zero space. On earlier NTFS versions we just write the lcn
+ * change.
+ */
+ if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
+ prev_lcn = rl->lcn;
+ if (likely(rl->lcn >= 0))
+ prev_lcn += delta;
+ /* Write change in lcn. */
+ lcn_len = ntfs_write_significant_bytes(dst + 1 +
+ len_len, dst_max, prev_lcn);
+ if (unlikely(lcn_len < 0))
+ goto size_err;
+ } else
+ lcn_len = 0;
+ dst_next = dst + len_len + lcn_len + 1;
+ if (unlikely(dst_next > dst_max))
+ goto size_err;
+ /* Update header byte. */
+ *dst = lcn_len << 4 | len_len;
+ /* Position at next mapping pairs array element. */
+ dst = dst_next;
+ /* Go to next runlist element. */
+ rl++;
+ }
+ /* Do the full runs. */
+ for (; rl->length && !the_end; rl++) {
+ s64 length = rl->length;
+
+ if (unlikely(length < 0 || rl->lcn < LCN_HOLE))
+ goto err_out;
+ /*
+ * If @stop_vcn is given and finishes inside this run, cap the
+ * run length.
+ */
+ if (unlikely(last_vcn >= 0 && rl[1].vcn > last_vcn)) {
+ s64 s1 = last_vcn + 1;
+
+ if (unlikely(rl[1].vcn > s1))
+ length = s1 - rl->vcn;
+ the_end = true;
+ }
+ /* Write length. */
+ len_len = ntfs_write_significant_bytes(dst + 1, dst_max,
+ length);
+ if (unlikely(len_len < 0))
+ goto size_err;
+ /*
+ * If the logical cluster number (lcn) denotes a hole and we
+ * are on NTFS 3.0+, we don't store it at all, i.e. we need
+ * zero space. On earlier NTFS versions we just write the lcn
+ * change.
+ */
+ if (likely(rl->lcn >= 0 || vol->major_ver < 3)) {
+ /* Write change in lcn. */
+ lcn_len = ntfs_write_significant_bytes(dst + 1 +
+ len_len, dst_max, rl->lcn - prev_lcn);
+ if (unlikely(lcn_len < 0))
+ goto size_err;
+ prev_lcn = rl->lcn;
+ } else {
+ if (rl->lcn == LCN_DELALLOC)
+ de_cnt += rl->length;
+ lcn_len = 0;
+ }
+ dst_next = dst + len_len + lcn_len + 1;
+ if (unlikely(dst_next > dst_max))
+ goto size_err;
+ /* Update header byte. */
+ *dst = lcn_len << 4 | len_len;
+ /* Position at next mapping pairs array element. */
+ dst = dst_next;
+ }
+ /* Success. */
+ if (de_cluster_count)
+ *de_cluster_count = de_cnt;
+ err = 0;
+size_err:
+ /* Set stop vcn. */
+ if (stop_vcn)
+ *stop_vcn = rl->vcn;
+ if (stop_rl)
+ *stop_rl = (struct runlist_element *)rl;
+ /* Add terminator byte. */
+ *dst = 0;
+ return err;
+err_out:
+ if (rl->lcn == LCN_RL_NOT_MAPPED)
+ err = -EINVAL;
+ else
+ err = -EIO;
+ return err;
+}
+
+/**
+ * ntfs_rl_truncate_nolock - truncate a runlist starting at a specified vcn
+ * @vol: ntfs volume (needed for error output)
+ * @runlist: runlist to truncate
+ * @new_length: the new length of the runlist in VCNs
+ *
+ * Truncate the runlist described by @runlist as well as the memory buffer
+ * holding the runlist elements to a length of @new_length VCNs.
+ *
+ * If @new_length lies within the runlist, the runlist elements with VCNs of
+ * @new_length and above are discarded. As a special case if @new_length is
+ * zero, the runlist is discarded and set to NULL.
+ *
+ * If @new_length lies beyond the runlist, a sparse runlist element is added to
+ * the end of the runlist @runlist or if the last runlist element is a sparse
+ * one already, this is extended.
+ *
+ * Note, no checking is done for unmapped runlist elements. It is assumed that
+ * the caller has mapped any elements that need to be mapped already.
+ *
+ * Return 0 on success and -errno on error.
+ */
+int ntfs_rl_truncate_nolock(const struct ntfs_volume *vol, struct runlist *const runlist,
+ const s64 new_length)
+{
+ struct runlist_element *rl;
+ int old_size;
+
+ ntfs_debug("Entering for new_length 0x%llx.", (long long)new_length);
+ BUG_ON(!runlist);
+ BUG_ON(new_length < 0);
+ rl = runlist->rl;
+
+ BUG_ON(new_length < rl->vcn);
+ /* Find @new_length in the runlist. */
+ while (likely(rl->length && new_length >= rl[1].vcn))
+ rl++;
+ /*
+ * If not at the end of the runlist we need to shrink it.
+ * If at the end of the runlist we need to expand it.
+ */
+ if (rl->length) {
+ struct runlist_element *trl;
+ bool is_end;
+
+ ntfs_debug("Shrinking runlist.");
+ /* Determine the runlist size. */
+ trl = rl + 1;
+ while (likely(trl->length))
+ trl++;
+ old_size = trl - runlist->rl + 1;
+ /* Truncate the run. */
+ rl->length = new_length - rl->vcn;
+ /*
+ * If a run was partially truncated, make the following runlist
+ * element a terminator.
+ */
+ is_end = false;
+ if (rl->length) {
+ rl++;
+ if (!rl->length)
+ is_end = true;
+ rl->vcn = new_length;
+ rl->length = 0;
+ }
+ rl->lcn = LCN_ENOENT;
+ runlist->count = rl - runlist->rl + 1;
+ /* Reallocate memory if necessary. */
+ if (!is_end) {
+ int new_size = rl - runlist->rl + 1;
+
+ rl = ntfs_rl_realloc(runlist->rl, old_size, new_size);
+ if (IS_ERR(rl))
+ ntfs_warning(vol->sb,
+ "Failed to shrink runlist buffer. This just wastes a bit of memory temporarily so we ignore it and return success.");
+ else
+ runlist->rl = rl;
+ }
+ } else if (likely(/* !rl->length && */ new_length > rl->vcn)) {
+ ntfs_debug("Expanding runlist.");
+ /*
+ * If there is a previous runlist element and it is a sparse
+ * one, extend it. Otherwise need to add a new, sparse runlist
+ * element.
+ */
+ if ((rl > runlist->rl) && ((rl - 1)->lcn == LCN_HOLE))
+ (rl - 1)->length = new_length - (rl - 1)->vcn;
+ else {
+ /* Determine the runlist size. */
+ old_size = rl - runlist->rl + 1;
+ /* Reallocate memory if necessary. */
+ rl = ntfs_rl_realloc(runlist->rl, old_size,
+ old_size + 1);
+ if (IS_ERR(rl)) {
+ ntfs_error(vol->sb, "Failed to expand runlist buffer, aborting.");
+ return PTR_ERR(rl);
+ }
+ runlist->rl = rl;
+ /*
+ * Set @rl to the same runlist element in the new
+ * runlist as before in the old runlist.
+ */
+ rl += old_size - 1;
+ /* Add a new, sparse runlist element. */
+ rl->lcn = LCN_HOLE;
+ rl->length = new_length - rl->vcn;
+ /* Add a new terminator runlist element. */
+ rl++;
+ rl->length = 0;
+ runlist->count = old_size + 1;
+ }
+ rl->vcn = new_length;
+ rl->lcn = LCN_ENOENT;
+ } else /* if (unlikely(!rl->length && new_length == rl->vcn)) */ {
+ /* Runlist already has same size as requested. */
+ rl->lcn = LCN_ENOENT;
+ }
+ ntfs_debug("Done.");
+ return 0;
+}
+
+/**
+ * ntfs_rl_sparse - check whether runlist have sparse regions or not.
+ * @rl: runlist to check
+ *
+ * Return 1 if have, 0 if not, -errno on error.
+ */
+int ntfs_rl_sparse(struct runlist_element *rl)
+{
+ struct runlist_element *rlc;
+
+ if (!rl)
+ return -EINVAL;
+
+ for (rlc = rl; rlc->length; rlc++)
+ if (rlc->lcn < 0) {
+ if (rlc->lcn != LCN_HOLE && rlc->lcn != LCN_DELALLOC) {
+ pr_err("%s: bad runlist", __func__);
+ return -EINVAL;
+ }
+ return 1;
+ }
+ return 0;
+}
+
+/**
+ * ntfs_rl_get_compressed_size - calculate length of non sparse regions
+ * @vol: ntfs volume (need for cluster size)
+ * @rl: runlist to calculate for
+ *
+ * Return compressed size or -errno on error.
+ */
+s64 ntfs_rl_get_compressed_size(struct ntfs_volume *vol, struct runlist_element *rl)
+{
+ struct runlist_element *rlc;
+ s64 ret = 0;
+
+ if (!rl)
+ return -EINVAL;
+
+ for (rlc = rl; rlc->length; rlc++) {
+ if (rlc->lcn < 0) {
+ if (rlc->lcn != LCN_HOLE && rlc->lcn != LCN_DELALLOC) {
+ ntfs_error(vol->sb, "%s: bad runlist, rlc->lcn : %lld",
+ __func__, rlc->lcn);
+ return -EINVAL;
+ }
+ } else
+ ret += rlc->length;
+ }
+ return ret << vol->cluster_size_bits;
+}
+
+static inline bool ntfs_rle_lcn_contiguous(struct runlist_element *left_rle,
+ struct runlist_element *right_rle)
+{
+ if (left_rle->lcn > LCN_HOLE &&
+ left_rle->lcn + left_rle->length == right_rle->lcn)
+ return true;
+ else if (left_rle->lcn == LCN_HOLE && right_rle->lcn == LCN_HOLE)
+ return true;
+ else
+ return false;
+}
+
+static inline bool ntfs_rle_contain(struct runlist_element *rle, s64 vcn)
+{
+ if (rle->length > 0 &&
+ vcn >= rle->vcn && vcn < rle->vcn + rle->length)
+ return true;
+ else
+ return false;
+}
+
+struct runlist_element *ntfs_rl_insert_range(struct runlist_element *dst_rl, int dst_cnt,
+ struct runlist_element *src_rl, int src_cnt,
+ size_t *new_rl_cnt)
+{
+ struct runlist_element *i_rl, *new_rl, *src_rl_origin = src_rl;
+ struct runlist_element dst_rl_split;
+ s64 start_vcn = src_rl[0].vcn;
+ int new_1st_cnt, new_2nd_cnt, new_3rd_cnt, new_cnt;
+
+ if (!dst_rl || !src_rl || !new_rl_cnt)
+ return ERR_PTR(-EINVAL);
+ if (dst_cnt <= 0 || src_cnt <= 0)
+ return ERR_PTR(-EINVAL);
+ if (!(dst_rl[dst_cnt - 1].lcn == LCN_ENOENT &&
+ dst_rl[dst_cnt - 1].length == 0) ||
+ src_rl[src_cnt - 1].lcn < LCN_HOLE)
+ return ERR_PTR(-EINVAL);
+
+ start_vcn = src_rl[0].vcn;
+
+ i_rl = ntfs_rl_find_vcn_nolock(dst_rl, start_vcn);
+ if (!i_rl ||
+ (i_rl->lcn == LCN_ENOENT && i_rl->vcn != start_vcn) ||
+ (i_rl->lcn != LCN_ENOENT && !ntfs_rle_contain(i_rl, start_vcn)))
+ return ERR_PTR(-EINVAL);
+
+ new_1st_cnt = (int)(i_rl - dst_rl);
+ if (new_1st_cnt > dst_cnt)
+ return ERR_PTR(-EINVAL);
+ new_3rd_cnt = dst_cnt - new_1st_cnt;
+ if (new_3rd_cnt < 1)
+ return ERR_PTR(-EINVAL);
+
+ if (i_rl[0].vcn != start_vcn) {
+ if (i_rl[0].lcn == LCN_HOLE && src_rl[0].lcn == LCN_HOLE)
+ goto merge_src_rle;
+
+ /* split @i_rl[0] and create @dst_rl_split */
+ dst_rl_split.vcn = i_rl[0].vcn;
+ dst_rl_split.length = start_vcn - i_rl[0].vcn;
+ dst_rl_split.lcn = i_rl[0].lcn;
+
+ i_rl[0].vcn = start_vcn;
+ i_rl[0].length -= dst_rl_split.length;
+ i_rl[0].lcn += dst_rl_split.length;
+ } else {
+ struct runlist_element *dst_rle, *src_rle;
+merge_src_rle:
+
+ /* not split @i_rl[0] */
+ dst_rl_split.lcn = LCN_ENOENT;
+
+ /* merge @src_rl's first run and @i_rl[0]'s left run if possible */
+ dst_rle = &dst_rl[new_1st_cnt - 1];
+ src_rle = &src_rl[0];
+ if (new_1st_cnt > 0 && ntfs_rle_lcn_contiguous(dst_rle, src_rle)) {
+ BUG_ON(dst_rle->vcn + dst_rle->length != src_rle->vcn);
+ dst_rle->length += src_rle->length;
+ src_rl++;
+ src_cnt--;
+ } else {
+ /* merge @src_rl's last run and @i_rl[0]'s right if possible */
+ dst_rle = &dst_rl[new_1st_cnt];
+ src_rle = &src_rl[src_cnt - 1];
+
+ if (ntfs_rle_lcn_contiguous(dst_rle, src_rle)) {
+ dst_rle->length += src_rle->length;
+ src_cnt--;
+ }
+ }
+ }
+
+ new_2nd_cnt = src_cnt;
+ new_cnt = new_1st_cnt + new_2nd_cnt + new_3rd_cnt;
+ new_cnt += dst_rl_split.lcn >= LCN_HOLE ? 1 : 0;
+ new_rl = ntfs_malloc_nofs(new_cnt * sizeof(*new_rl));
+ if (!new_rl)
+ return ERR_PTR(-ENOMEM);
+
+ /* Copy the @dst_rl's first half to @new_rl */
+ ntfs_rl_mc(new_rl, 0, dst_rl, 0, new_1st_cnt);
+ if (dst_rl_split.lcn >= LCN_HOLE) {
+ ntfs_rl_mc(new_rl, new_1st_cnt, &dst_rl_split, 0, 1);
+ new_1st_cnt++;
+ }
+ /* Copy the @src_rl to @new_rl */
+ ntfs_rl_mc(new_rl, new_1st_cnt, src_rl, 0, new_2nd_cnt);
+ /* Copy the @dst_rl's second half to @new_rl */
+ if (new_3rd_cnt >= 1) {
+ struct runlist_element *rl, *rl_3rd;
+ int dst_1st_cnt = dst_rl_split.lcn >= LCN_HOLE ?
+ new_1st_cnt - 1 : new_1st_cnt;
+
+ ntfs_rl_mc(new_rl, new_1st_cnt + new_2nd_cnt,
+ dst_rl, dst_1st_cnt, new_3rd_cnt);
+ /* Update vcn of the @dst_rl's second half runs to reflect
+ * appended @src_rl.
+ */
+ if (new_1st_cnt + new_2nd_cnt == 0) {
+ rl_3rd = &new_rl[new_1st_cnt + new_2nd_cnt + 1];
+ rl = &new_rl[new_1st_cnt + new_2nd_cnt];
+ } else {
+ rl_3rd = &new_rl[new_1st_cnt + new_2nd_cnt];
+ rl = &new_rl[new_1st_cnt + new_2nd_cnt - 1];
+ }
+ do {
+ rl_3rd->vcn = rl->vcn + rl->length;
+ if (rl_3rd->length <= 0)
+ break;
+ rl = rl_3rd;
+ rl_3rd++;
+ } while (1);
+ }
+ *new_rl_cnt = new_1st_cnt + new_2nd_cnt + new_3rd_cnt;
+
+ ntfs_free(dst_rl);
+ ntfs_free(src_rl_origin);
+ return new_rl;
+}
+
+struct runlist_element *ntfs_rl_punch_hole(struct runlist_element *dst_rl, int dst_cnt,
+ s64 start_vcn, s64 len,
+ struct runlist_element **punch_rl,
+ size_t *new_rl_cnt)
+{
+ struct runlist_element *s_rl, *e_rl, *new_rl, *dst_3rd_rl, hole_rl[1];
+ s64 end_vcn;
+ int new_1st_cnt, dst_3rd_cnt, new_cnt, punch_cnt, merge_cnt;
+ bool begin_split, end_split, one_split_3;
+
+ if (dst_cnt < 2 ||
+ !(dst_rl[dst_cnt - 1].lcn == LCN_ENOENT &&
+ dst_rl[dst_cnt - 1].length == 0))
+ return ERR_PTR(-EINVAL);
+
+ end_vcn = min(start_vcn + len - 1,
+ dst_rl[dst_cnt - 2].vcn + dst_rl[dst_cnt - 2].length - 1);
+
+ s_rl = ntfs_rl_find_vcn_nolock(dst_rl, start_vcn);
+ if (!s_rl ||
+ s_rl->lcn <= LCN_ENOENT ||
+ !ntfs_rle_contain(s_rl, start_vcn))
+ return ERR_PTR(-EINVAL);
+
+ begin_split = s_rl->vcn != start_vcn ? true : false;
+
+ e_rl = ntfs_rl_find_vcn_nolock(dst_rl, end_vcn);
+ if (!e_rl ||
+ e_rl->lcn <= LCN_ENOENT ||
+ !ntfs_rle_contain(e_rl, end_vcn))
+ return ERR_PTR(-EINVAL);
+
+ end_split = e_rl->vcn + e_rl->length - 1 != end_vcn ? true : false;
+
+ /* @s_rl has to be split into left, punched hole, and right */
+ one_split_3 = e_rl == s_rl && begin_split && end_split ? true : false;
+
+ punch_cnt = (int)(e_rl - s_rl) + 1;
+
+ *punch_rl = ntfs_malloc_nofs((punch_cnt + 1) * sizeof(struct runlist_element));
+ if (!*punch_rl)
+ return ERR_PTR(-ENOMEM);
+
+ new_cnt = dst_cnt - (int)(e_rl - s_rl + 1) + 3;
+ new_rl = ntfs_malloc_nofs(new_cnt * sizeof(struct runlist_element));
+ if (!new_rl) {
+ ntfs_free(*punch_rl);
+ *punch_rl = NULL;
+ return ERR_PTR(-ENOMEM);
+ }
+
+ new_1st_cnt = (int)(s_rl - dst_rl) + 1;
+ ntfs_rl_mc(*punch_rl, 0, dst_rl, new_1st_cnt - 1, punch_cnt);
+
+ (*punch_rl)[punch_cnt].lcn = LCN_ENOENT;
+ (*punch_rl)[punch_cnt].length = 0;
+
+ if (!begin_split)
+ new_1st_cnt--;
+ dst_3rd_rl = e_rl;
+ dst_3rd_cnt = (int)(&dst_rl[dst_cnt - 1] - e_rl) + 1;
+ if (!end_split) {
+ dst_3rd_rl++;
+ dst_3rd_cnt--;
+ }
+
+ /* Copy the 1st part of @dst_rl into @new_rl */
+ ntfs_rl_mc(new_rl, 0, dst_rl, 0, new_1st_cnt);
+ if (begin_split) {
+ /* the @e_rl has to be splited and copied into the last of @new_rl
+ * and the first of @punch_rl
+ */
+ s64 first_cnt = start_vcn - dst_rl[new_1st_cnt - 1].vcn;
+
+ if (new_1st_cnt)
+ new_rl[new_1st_cnt - 1].length = first_cnt;
+
+ (*punch_rl)[0].vcn = start_vcn;
+ (*punch_rl)[0].length -= first_cnt;
+ if ((*punch_rl)[0].lcn > LCN_HOLE)
+ (*punch_rl)[0].lcn += first_cnt;
+ }
+
+ /* Copy a hole into @new_rl */
+ hole_rl[0].vcn = start_vcn;
+ hole_rl[0].length = (s64)len;
+ hole_rl[0].lcn = LCN_HOLE;
+ ntfs_rl_mc(new_rl, new_1st_cnt, hole_rl, 0, 1);
+
+ /* Copy the 3rd part of @dst_rl into @new_rl */
+ ntfs_rl_mc(new_rl, new_1st_cnt + 1, dst_3rd_rl, 0, dst_3rd_cnt);
+ if (end_split) {
+ /* the @e_rl has to be splited and copied into the first of
+ * @new_rl and the last of @punch_rl
+ */
+ s64 first_cnt = end_vcn - dst_3rd_rl[0].vcn + 1;
+
+ new_rl[new_1st_cnt + 1].vcn = end_vcn + 1;
+ new_rl[new_1st_cnt + 1].length -= first_cnt;
+ if (new_rl[new_1st_cnt + 1].lcn > LCN_HOLE)
+ new_rl[new_1st_cnt + 1].lcn += first_cnt;
+
+ if (one_split_3)
+ (*punch_rl)[punch_cnt - 1].length -=
+ new_rl[new_1st_cnt + 1].length;
+ else
+ (*punch_rl)[punch_cnt - 1].length = first_cnt;
+ }
+
+ /* Merge left and hole, or hole and right in @new_rl, if left or right
+ * consists of holes.
+ */
+ merge_cnt = 0;
+ if (new_1st_cnt > 0 && new_rl[new_1st_cnt - 1].lcn == LCN_HOLE) {
+ /* Merge right and hole */
+ s_rl = &new_rl[new_1st_cnt - 1];
+ s_rl->length += s_rl[1].length;
+ merge_cnt = 1;
+ /* Merge left and right */
+ if (new_1st_cnt + 1 < new_cnt &&
+ new_rl[new_1st_cnt + 1].lcn == LCN_HOLE) {
+ s_rl->length += s_rl[2].length;
+ merge_cnt++;
+ }
+ } else if (new_1st_cnt + 1 < new_cnt &&
+ new_rl[new_1st_cnt + 1].lcn == LCN_HOLE) {
+ /* Merge left and hole */
+ s_rl = &new_rl[new_1st_cnt];
+ s_rl->length += s_rl[1].length;
+ merge_cnt = 1;
+ }
+ if (merge_cnt) {
+ struct runlist_element *d_rl, *src_rl;
+
+ d_rl = s_rl + 1;
+ src_rl = s_rl + 1 + merge_cnt;
+ ntfs_rl_mm(new_rl, (int)(d_rl - new_rl), (int)(src_rl - new_rl),
+ (int)(&new_rl[new_cnt - 1] - src_rl) + 1);
+ }
+
+ (*punch_rl)[punch_cnt].vcn = (*punch_rl)[punch_cnt - 1].vcn +
+ (*punch_rl)[punch_cnt - 1].length;
+
+ /* punch_cnt elements of dst are replaced with one hole */
+ *new_rl_cnt = dst_cnt - (punch_cnt - (int)begin_split - (int)end_split) +
+ 1 - merge_cnt;
+ ntfs_free(dst_rl);
+ return new_rl;
+}
+
+struct runlist_element *ntfs_rl_collapse_range(struct runlist_element *dst_rl, int dst_cnt,
+ s64 start_vcn, s64 len,
+ struct runlist_element **punch_rl,
+ size_t *new_rl_cnt)
+{
+ struct runlist_element *s_rl, *e_rl, *new_rl, *dst_3rd_rl;
+ s64 end_vcn;
+ int new_1st_cnt, dst_3rd_cnt, new_cnt, punch_cnt, merge_cnt, i;
+ bool begin_split, end_split, one_split_3;
+
+ if (dst_cnt < 2 ||
+ !(dst_rl[dst_cnt - 1].lcn == LCN_ENOENT &&
+ dst_rl[dst_cnt - 1].length == 0))
+ return ERR_PTR(-EINVAL);
+
+ end_vcn = min(start_vcn + len - 1,
+ dst_rl[dst_cnt - 1].vcn - 1);
+
+ s_rl = ntfs_rl_find_vcn_nolock(dst_rl, start_vcn);
+ if (!s_rl ||
+ s_rl->lcn <= LCN_ENOENT ||
+ !ntfs_rle_contain(s_rl, start_vcn))
+ return ERR_PTR(-EINVAL);
+
+ begin_split = s_rl->vcn != start_vcn ? true : false;
+
+ e_rl = ntfs_rl_find_vcn_nolock(dst_rl, end_vcn);
+ if (!e_rl ||
+ e_rl->lcn <= LCN_ENOENT ||
+ !ntfs_rle_contain(e_rl, end_vcn))
+ return ERR_PTR(-EINVAL);
+
+ end_split = e_rl->vcn + e_rl->length - 1 != end_vcn ? true : false;
+
+ /* @s_rl has to be split into left, collapsed, and right */
+ one_split_3 = e_rl == s_rl && begin_split && end_split ? true : false;
+
+ punch_cnt = (int)(e_rl - s_rl) + 1;
+ *punch_rl = ntfs_malloc_nofs((punch_cnt + 1) * sizeof(struct runlist_element));
+ if (!*punch_rl)
+ return ERR_PTR(-ENOMEM);
+
+ new_cnt = dst_cnt - (int)(e_rl - s_rl + 1) + 3;
+ new_rl = ntfs_malloc_nofs(new_cnt * sizeof(struct runlist_element));
+ if (!new_rl) {
+ ntfs_free(*punch_rl);
+ *punch_rl = NULL;
+ return ERR_PTR(-ENOMEM);
+ }
+
+ new_1st_cnt = (int)(s_rl - dst_rl) + 1;
+ ntfs_rl_mc(*punch_rl, 0, dst_rl, new_1st_cnt - 1, punch_cnt);
+ (*punch_rl)[punch_cnt].lcn = LCN_ENOENT;
+ (*punch_rl)[punch_cnt].length = 0;
+
+ if (!begin_split)
+ new_1st_cnt--;
+ dst_3rd_rl = e_rl;
+ dst_3rd_cnt = (int)(&dst_rl[dst_cnt - 1] - e_rl) + 1;
+ if (!end_split) {
+ dst_3rd_rl++;
+ dst_3rd_cnt--;
+ }
+
+ /* Copy the 1st part of @dst_rl into @new_rl */
+ ntfs_rl_mc(new_rl, 0, dst_rl, 0, new_1st_cnt);
+ if (begin_split) {
+ /* the @e_rl has to be splited and copied into the last of @new_rl
+ * and the first of @punch_rl
+ */
+ s64 first_cnt = start_vcn - dst_rl[new_1st_cnt - 1].vcn;
+
+ new_rl[new_1st_cnt - 1].length = first_cnt;
+
+ (*punch_rl)[0].vcn = start_vcn;
+ (*punch_rl)[0].length -= first_cnt;
+ if ((*punch_rl)[0].lcn > LCN_HOLE)
+ (*punch_rl)[0].lcn += first_cnt;
+ }
+
+ /* Copy the 3rd part of @dst_rl into @new_rl */
+ ntfs_rl_mc(new_rl, new_1st_cnt, dst_3rd_rl, 0, dst_3rd_cnt);
+ if (end_split) {
+ /* the @e_rl has to be splited and copied into the first of
+ * @new_rl and the last of @punch_rl
+ */
+ s64 first_cnt = end_vcn - dst_3rd_rl[0].vcn + 1;
+
+ new_rl[new_1st_cnt].vcn = end_vcn + 1;
+ new_rl[new_1st_cnt].length -= first_cnt;
+ if (new_rl[new_1st_cnt].lcn > LCN_HOLE)
+ new_rl[new_1st_cnt].lcn += first_cnt;
+
+ if (one_split_3)
+ (*punch_rl)[punch_cnt - 1].length -=
+ new_rl[new_1st_cnt].length;
+ else
+ (*punch_rl)[punch_cnt - 1].length = first_cnt;
+ }
+
+ /* Adjust vcn */
+ if (new_1st_cnt == 0)
+ new_rl[new_1st_cnt].vcn = 0;
+ for (i = new_1st_cnt == 0 ? 1 : new_1st_cnt; new_rl[i].length; i++)
+ new_rl[i].vcn = new_rl[i - 1].vcn + new_rl[i - 1].length;
+ new_rl[i].vcn = new_rl[i - 1].vcn + new_rl[i - 1].length;
+
+ /* Merge left and hole, or hole and right in @new_rl, if left or right
+ * consists of holes.
+ */
+ merge_cnt = 0;
+ i = new_1st_cnt == 0 ? 1 : new_1st_cnt;
+ if (ntfs_rle_lcn_contiguous(&new_rl[i - 1], &new_rl[i])) {
+ /* Merge right and left */
+ s_rl = &new_rl[new_1st_cnt - 1];
+ s_rl->length += s_rl[1].length;
+ merge_cnt = 1;
+ }
+ if (merge_cnt) {
+ struct runlist_element *d_rl, *src_rl;
+
+ d_rl = s_rl + 1;
+ src_rl = s_rl + 1 + merge_cnt;
+ ntfs_rl_mm(new_rl, (int)(d_rl - new_rl), (int)(src_rl - new_rl),
+ (int)(&new_rl[new_cnt - 1] - src_rl) + 1);
+ }
+
+ (*punch_rl)[punch_cnt].vcn = (*punch_rl)[punch_cnt - 1].vcn +
+ (*punch_rl)[punch_cnt - 1].length;
+
+ /* punch_cnt elements of dst are extracted */
+ *new_rl_cnt = dst_cnt - (punch_cnt - (int)begin_split - (int)end_split) -
+ merge_cnt;
+
+ ntfs_free(dst_rl);
+ return new_rl;
+}
--
2.34.1
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH 09/11] ntfsplus: add reparse and ea operations
2025-10-20 2:12 [PATCH 06/11] ntfsplus: add iomap and address space operations Namjae Jeon
2025-10-20 2:12 ` [PATCH 07/11] ntfsplus: add attrib operatrions Namjae Jeon
2025-10-20 2:12 ` [PATCH 08/11] ntfsplus: add runlist handling and cluster allocator Namjae Jeon
@ 2025-10-20 2:12 ` Namjae Jeon
2025-10-20 2:12 ` [PATCH 10/11] ntfsplus: add misc operations Namjae Jeon
2025-10-20 2:12 ` [PATCH 11/11] ntfsplus: add Kconfig and Makefile Namjae Jeon
4 siblings, 0 replies; 6+ messages in thread
From: Namjae Jeon @ 2025-10-20 2:12 UTC (permalink / raw)
To: viro, brauner, hch, hch, tytso, willy, jack, djwong, josef,
sandeen, rgoldwyn, xiang, dsterba, pali, ebiggers, neil,
amir73il
Cc: linux-fsdevel, linux-kernel, iamjoonsoo.kim, cheol.lee, jay.sim,
gunho.lee, Namjae Jeon
This adds the implementation of reparse and ea operations for ntfsplus.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
---
fs/ntfsplus/ea.c | 712 ++++++++++++++++++++++++++++++++++++++++++
fs/ntfsplus/reparse.c | 550 ++++++++++++++++++++++++++++++++
2 files changed, 1262 insertions(+)
create mode 100644 fs/ntfsplus/ea.c
create mode 100644 fs/ntfsplus/reparse.c
diff --git a/fs/ntfsplus/ea.c b/fs/ntfsplus/ea.c
new file mode 100644
index 000000000000..a1797eea47bb
--- /dev/null
+++ b/fs/ntfsplus/ea.c
@@ -0,0 +1,712 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/**
+ * Pocessing of EA's
+ *
+ * Part of this file is based on code from the NTFS-3G project.
+ *
+ * Copyright (c) 2014-2021 Jean-Pierre Andre
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ */
+
+#include <linux/fs.h>
+#include <linux/posix_acl.h>
+#include <linux/posix_acl_xattr.h>
+#include <linux/xattr.h>
+
+#include "layout.h"
+#include "attrib.h"
+#include "index.h"
+#include "dir.h"
+#include "ea.h"
+#include "misc.h"
+
+static int ntfs_write_ea(struct ntfs_inode *ni, int type, char *value, s64 ea_off,
+ s64 ea_size)
+{
+ struct inode *ea_vi;
+ int err = 0;
+ s64 written;
+
+ ea_vi = ntfs_attr_iget(VFS_I(ni), type, AT_UNNAMED, 0);
+ if (IS_ERR(ea_vi))
+ return PTR_ERR(ea_vi);
+
+ written = ntfs_inode_attr_pwrite(ea_vi, ea_off, ea_size, value, false);
+ if (written != ea_size)
+ err = -EIO;
+ else
+ mark_mft_record_dirty(ni);
+
+ iput(ea_vi);
+ return err;
+}
+
+static int ntfs_ea_lookup(char *ea_buf, s64 ea_buf_size, const char *name,
+ int name_len, s64 *ea_offset, s64 *ea_size)
+{
+ const struct ea_attr *p_ea;
+ s64 offset;
+ unsigned int next;
+
+ if (ea_buf_size < sizeof(struct ea_attr))
+ goto out;
+
+ offset = 0;
+ do {
+ p_ea = (const struct ea_attr *)&ea_buf[offset];
+ next = le32_to_cpu(p_ea->next_entry_offset);
+
+ if (offset + next > ea_buf_size ||
+ ((1 + p_ea->ea_name_length) > (ea_buf_size - offset)))
+ break;
+
+ if (p_ea->ea_name_length == name_len &&
+ !memcmp(p_ea->ea_name, name, name_len)) {
+ *ea_offset = offset;
+ if (next)
+ *ea_size = next;
+ else {
+ unsigned int ea_len = 1 + p_ea->ea_name_length +
+ le16_to_cpu(p_ea->ea_value_length);
+
+ if ((ea_buf_size - offset) < ea_len)
+ goto out;
+
+ *ea_size = ALIGN(struct_size(p_ea, ea_name,
+ 1 + p_ea->ea_name_length +
+ le16_to_cpu(p_ea->ea_value_length)), 4);
+ }
+
+ if (ea_buf_size < *ea_offset + *ea_size)
+ goto out;
+
+ return 0;
+ }
+ offset += next;
+ } while (next > 0 && offset < ea_buf_size &&
+ sizeof(struct ea_attr) < (ea_buf_size - offset));
+
+out:
+ return -ENOENT;
+}
+
+/*
+ * Return the existing EA
+ *
+ * The EA_INFORMATION is not examined and the consistency of the
+ * existing EA is not checked.
+ *
+ * If successful, the full attribute is returned unchanged
+ * and its size is returned.
+ * If the designated buffer is too small, the needed size is
+ * returned, and the buffer is left unchanged.
+ * If there is an error, a negative value is returned and errno
+ * is set according to the error.
+ */
+static int ntfs_get_ea(struct inode *inode, const char *name, size_t name_len,
+ void *buffer, size_t size)
+{
+ struct ntfs_inode *ni = NTFS_I(inode);
+ const struct ea_attr *p_ea;
+ char *ea_buf;
+ s64 ea_off, ea_size, all_ea_size, ea_info_size;
+ int err;
+ unsigned short int ea_value_len, ea_info_qlen;
+ struct ea_information *p_ea_info;
+
+ if (!NInoHasEA(ni))
+ return -ENODATA;
+
+ p_ea_info = ntfs_attr_readall(ni, AT_EA_INFORMATION, NULL, 0,
+ &ea_info_size);
+ if (!p_ea_info || ea_info_size != sizeof(struct ea_information)) {
+ ntfs_free(p_ea_info);
+ return -ENODATA;
+ }
+
+ ea_info_qlen = le16_to_cpu(p_ea_info->ea_query_length);
+ ntfs_free(p_ea_info);
+
+ ea_buf = ntfs_attr_readall(ni, AT_EA, NULL, 0, &all_ea_size);
+ if (!ea_buf)
+ return -ENODATA;
+
+ err = ntfs_ea_lookup(ea_buf, ea_info_qlen, name, name_len, &ea_off,
+ &ea_size);
+ if (!err) {
+ p_ea = (struct ea_attr *)&ea_buf[ea_off];
+ ea_value_len = le16_to_cpu(p_ea->ea_value_length);
+ if (!buffer) {
+ ntfs_free(ea_buf);
+ return ea_value_len;
+ }
+
+ if (ea_value_len > size) {
+ err = -ERANGE;
+ goto free_ea_buf;
+ }
+
+ memcpy(buffer, &p_ea->ea_name[p_ea->ea_name_length + 1],
+ ea_value_len);
+ ntfs_free(ea_buf);
+ return ea_value_len;
+ }
+
+ err = -ENODATA;
+free_ea_buf:
+ ntfs_free(ea_buf);
+ return err;
+}
+
+static inline int ea_packed_size(const struct ea_attr *p_ea)
+{
+ /*
+ * 4 bytes for header (flags and lengths) + name length + 1 +
+ * value length.
+ */
+ return 5 + p_ea->ea_name_length + le16_to_cpu(p_ea->ea_value_length);
+}
+
+/*
+ * Set a new EA, and set EA_INFORMATION accordingly
+ *
+ * This is roughly the same as ZwSetEaFile() on Windows, however
+ * the "offset to next" of the last EA should not be cleared.
+ *
+ * Consistency of the new EA is first checked.
+ *
+ * EA_INFORMATION is set first, and it is restored to its former
+ * state if setting EA fails.
+ */
+static int ntfs_set_ea(struct inode *inode, const char *name, size_t name_len,
+ const void *value, size_t val_size, int flags,
+ __le16 *packed_ea_size)
+{
+ struct ntfs_inode *ni = NTFS_I(inode);
+ struct ea_information *p_ea_info = NULL;
+ int ea_packed, err = 0;
+ struct ea_attr *p_ea;
+ unsigned short int ea_info_qsize;
+ char *ea_buf = NULL;
+ size_t new_ea_size = ALIGN(struct_size(p_ea, ea_name, 1 + name_len + val_size), 4);
+ s64 ea_off, ea_info_size, all_ea_size, ea_size;
+
+ if (name_len > 255)
+ return -ENAMETOOLONG;
+
+ if (ntfs_attr_exist(ni, AT_EA_INFORMATION, AT_UNNAMED, 0)) {
+ p_ea_info = ntfs_attr_readall(ni, AT_EA_INFORMATION, NULL, 0,
+ &ea_info_size);
+ if (!p_ea_info || ea_info_size != sizeof(struct ea_information))
+ goto out;
+
+ ea_buf = ntfs_attr_readall(ni, AT_EA, NULL, 0, &all_ea_size);
+ if (!ea_buf) {
+ ea_info_qsize = 0;
+ ntfs_free(p_ea_info);
+ goto create_ea_info;
+ }
+
+ ea_info_qsize = le16_to_cpu(p_ea_info->ea_query_length);
+ } else {
+create_ea_info:
+ p_ea_info = ntfs_malloc_nofs(sizeof(struct ea_information));
+ if (!p_ea_info)
+ return -ENOMEM;
+
+ ea_info_qsize = 0;
+ err = ntfs_attr_add(ni, AT_EA_INFORMATION, AT_UNNAMED, 0,
+ (char *)p_ea_info, sizeof(struct ea_information));
+ if (err)
+ goto out;
+
+ if (ntfs_attr_exist(ni, AT_EA, AT_UNNAMED, 0)) {
+ err = ntfs_attr_remove(ni, AT_EA, AT_UNNAMED, 0);
+ if (err)
+ goto out;
+ }
+
+ goto alloc_new_ea;
+ }
+
+ if (ea_info_qsize > all_ea_size) {
+ err = -EIO;
+ goto out;
+ }
+
+ err = ntfs_ea_lookup(ea_buf, ea_info_qsize, name, name_len, &ea_off,
+ &ea_size);
+ if (ea_info_qsize && !err) {
+ if (flags & XATTR_CREATE) {
+ err = -EEXIST;
+ goto out;
+ }
+
+ p_ea = (struct ea_attr *)(ea_buf + ea_off);
+
+ if (val_size &&
+ le16_to_cpu(p_ea->ea_value_length) == val_size &&
+ !memcmp(p_ea->ea_name + p_ea->ea_name_length + 1, value,
+ val_size))
+ goto out;
+
+ le16_add_cpu(&p_ea_info->ea_length, 0 - ea_packed_size(p_ea));
+
+ if (p_ea->flags & NEED_EA)
+ le16_add_cpu(&p_ea_info->need_ea_count, -1);
+
+ memmove((char *)p_ea, (char *)p_ea + ea_size, ea_info_qsize - (ea_off + ea_size));
+ ea_info_qsize -= ea_size;
+ memset(ea_buf + ea_info_qsize, 0, ea_size);
+ p_ea_info->ea_query_length = cpu_to_le16(ea_info_qsize);
+
+ err = ntfs_write_ea(ni, AT_EA_INFORMATION, (char *)p_ea_info, 0,
+ sizeof(struct ea_information));
+ if (err)
+ goto out;
+
+ err = ntfs_write_ea(ni, AT_EA, ea_buf, 0, all_ea_size);
+ if (err)
+ goto out;
+
+ if ((flags & XATTR_REPLACE) && !val_size) {
+ /* Remove xattr. */
+ goto out;
+ }
+ } else {
+ if (flags & XATTR_REPLACE) {
+ err = -ENODATA;
+ goto out;
+ }
+ }
+ ntfs_free(ea_buf);
+
+alloc_new_ea:
+ ea_buf = kzalloc(new_ea_size, GFP_NOFS);
+ if (!ea_buf) {
+ err = -ENOMEM;
+ goto out;
+ }
+
+ /*
+ * EA and REPARSE_POINT compatibility not checked any more,
+ * required by Windows 10, but having both may lead to
+ * problems with earlier versions.
+ */
+ p_ea = (struct ea_attr *)ea_buf;
+ memcpy(p_ea->ea_name, name, name_len);
+ p_ea->ea_name_length = name_len;
+ p_ea->ea_name[name_len] = 0;
+ memcpy(p_ea->ea_name + name_len + 1, value, val_size);
+ p_ea->ea_value_length = cpu_to_le16(val_size);
+ p_ea->next_entry_offset = cpu_to_le32(new_ea_size);
+
+ ea_packed = le16_to_cpu(p_ea_info->ea_length) + ea_packed_size(p_ea);
+ p_ea_info->ea_length = cpu_to_le16(ea_packed);
+ p_ea_info->ea_query_length = cpu_to_le32(ea_info_qsize + new_ea_size);
+
+ if (ea_packed > 0xffff ||
+ ntfs_attr_size_bounds_check(ni->vol, AT_EA, new_ea_size)) {
+ err = -EFBIG;
+ goto out;
+ }
+
+ /*
+ * no EA or EA_INFORMATION : add them
+ */
+ if (!ntfs_attr_exist(ni, AT_EA, AT_UNNAMED, 0)) {
+ err = ntfs_attr_add(ni, AT_EA, AT_UNNAMED, 0, (char *)p_ea,
+ new_ea_size);
+ if (err)
+ goto out;
+ } else {
+ err = ntfs_write_ea(ni, AT_EA, (char *)p_ea, ea_info_qsize,
+ new_ea_size);
+ if (err)
+ goto out;
+ }
+
+ err = ntfs_write_ea(ni, AT_EA_INFORMATION, (char *)p_ea_info, 0,
+ sizeof(struct ea_information));
+ if (err)
+ goto out;
+
+ if (packed_ea_size)
+ *packed_ea_size = p_ea_info->ea_length;
+ mark_mft_record_dirty(ni);
+out:
+ if (ea_info_qsize > 0)
+ NInoSetHasEA(ni);
+ else
+ NInoClearHasEA(ni);
+
+ ntfs_free(ea_buf);
+ ntfs_free(p_ea_info);
+
+ return err;
+}
+
+/*
+ * Check for the presence of an EA "$LXDEV" (used by WSL)
+ * and return its value as a device address
+ */
+int ntfs_ea_get_wsl_inode(struct inode *inode, dev_t *rdevp, unsigned int flags)
+{
+ int err;
+ __le32 v;
+
+ if (!(flags & NTFS_VOL_UID)) {
+ /* Load uid to lxuid EA */
+ err = ntfs_get_ea(inode, "$LXUID", sizeof("$LXUID") - 1, &v,
+ sizeof(v));
+ if (err < 0)
+ return err;
+ i_uid_write(inode, le32_to_cpu(v));
+ }
+
+ if (!(flags & NTFS_VOL_UID)) {
+ /* Load gid to lxgid EA */
+ err = ntfs_get_ea(inode, "$LXGID", sizeof("$LXGID") - 1, &v,
+ sizeof(v));
+ if (err < 0)
+ return err;
+ i_gid_write(inode, le32_to_cpu(v));
+ }
+
+ /* Load mode to lxmod EA */
+ err = ntfs_get_ea(inode, "$LXMOD", sizeof("$LXMOD") - 1, &v, sizeof(v));
+ if (err > 0) {
+ inode->i_mode = le32_to_cpu(v);
+ } else {
+ /* Everyone gets all permissions. */
+ inode->i_mode |= 0777;
+ }
+
+ /* Load mode to lxdev EA */
+ err = ntfs_get_ea(inode, "$LXDEV", sizeof("$LXDEV") - 1, &v, sizeof(v));
+ if (err > 0)
+ *rdevp = le32_to_cpu(v);
+ err = 0;
+
+ return err;
+}
+
+int ntfs_ea_set_wsl_inode(struct inode *inode, dev_t rdev, __le16 *ea_size,
+ unsigned int flags)
+{
+ __le32 v;
+ int err;
+
+ if (flags & NTFS_EA_UID) {
+ /* Store uid to lxuid EA */
+ v = cpu_to_le32(i_uid_read(inode));
+ err = ntfs_set_ea(inode, "$LXUID", sizeof("$LXUID") - 1, &v,
+ sizeof(v), 0, ea_size);
+ if (err)
+ return err;
+ }
+
+ if (flags & NTFS_EA_GID) {
+ /* Store gid to lxgid EA */
+ v = cpu_to_le32(i_gid_read(inode));
+ err = ntfs_set_ea(inode, "$LXGID", sizeof("$LXGID") - 1, &v,
+ sizeof(v), 0, ea_size);
+ if (err)
+ return err;
+ }
+
+ if (flags & NTFS_EA_MODE) {
+ /* Store mode to lxmod EA */
+ v = cpu_to_le32(inode->i_mode);
+ err = ntfs_set_ea(inode, "$LXMOD", sizeof("$LXMOD") - 1, &v,
+ sizeof(v), 0, ea_size);
+ if (err)
+ return err;
+ }
+
+ if (rdev) {
+ v = cpu_to_le32(rdev);
+ err = ntfs_set_ea(inode, "$LXDEV", sizeof("$LXDEV") - 1, &v, sizeof(v),
+ 0, ea_size);
+ }
+
+ return err;
+}
+
+ssize_t ntfs_listxattr(struct dentry *dentry, char *buffer, size_t size)
+{
+ struct inode *inode = d_inode(dentry);
+ struct ntfs_inode *ni = NTFS_I(inode);
+ const struct ea_attr *p_ea;
+ s64 offset, ea_buf_size, ea_info_size;
+ int next, err = 0, ea_size;
+ unsigned int ea_info_qsize;
+ char *ea_buf = NULL;
+ ssize_t ret = 0;
+ struct ea_information *ea_info;
+
+ if (!NInoHasEA(ni))
+ return 0;
+
+ mutex_lock(&NTFS_I(inode)->mrec_lock);
+ ea_info = ntfs_attr_readall(ni, AT_EA_INFORMATION, NULL, 0,
+ &ea_info_size);
+ if (!ea_info || ea_info_size != sizeof(struct ea_information))
+ goto out;
+
+ ea_info_qsize = le16_to_cpu(ea_info->ea_query_length);
+
+ ea_buf = ntfs_attr_readall(ni, AT_EA, NULL, 0, &ea_buf_size);
+ if (!ea_buf)
+ goto out;
+
+ if (ea_info_qsize > ea_buf_size)
+ goto out;
+
+ if (ea_buf_size < sizeof(struct ea_attr))
+ goto out;
+
+ offset = 0;
+ do {
+ p_ea = (const struct ea_attr *)&ea_buf[offset];
+ next = le32_to_cpu(p_ea->next_entry_offset);
+ if (next)
+ ea_size = next;
+ else
+ ea_size = ALIGN(struct_size(p_ea, ea_name,
+ 1 + p_ea->ea_name_length +
+ le16_to_cpu(p_ea->ea_value_length)),
+ 4);
+ if (buffer) {
+ if (offset + ea_size > ea_info_qsize)
+ break;
+
+ if (ret + p_ea->ea_name_length + 1 > size) {
+ err = -ERANGE;
+ goto out;
+ }
+
+ if (p_ea->ea_name_length + 1 > (ea_info_qsize - offset))
+ break;
+
+ memcpy(buffer + ret, p_ea->ea_name, p_ea->ea_name_length);
+ buffer[ret + p_ea->ea_name_length] = 0;
+ }
+
+ ret += p_ea->ea_name_length + 1;
+ offset += ea_size;
+ } while (next > 0 && offset < ea_info_qsize &&
+ sizeof(struct ea_attr) < (ea_info_qsize - offset));
+
+out:
+ mutex_unlock(&NTFS_I(inode)->mrec_lock);
+ ntfs_free(ea_info);
+ ntfs_free(ea_buf);
+
+ return err ? err : ret;
+}
+
+static int ntfs_getxattr(const struct xattr_handler *handler,
+ struct dentry *unused, struct inode *inode, const char *name,
+ void *buffer, size_t size)
+{
+ struct ntfs_inode *ni = NTFS_I(inode);
+ int err;
+
+ mutex_lock(&ni->mrec_lock);
+ err = ntfs_get_ea(inode, name, strlen(name), buffer, size);
+ mutex_unlock(&ni->mrec_lock);
+
+ return err;
+}
+
+static int ntfs_setxattr(const struct xattr_handler *handler,
+ struct mnt_idmap *idmap, struct dentry *unused,
+ struct inode *inode, const char *name, const void *value,
+ size_t size, int flags)
+{
+ struct ntfs_inode *ni = NTFS_I(inode);
+ int err;
+
+ mutex_lock(&ni->mrec_lock);
+ err = ntfs_set_ea(inode, name, strlen(name), value, size, flags, NULL);
+ mutex_unlock(&ni->mrec_lock);
+
+ inode_set_ctime_current(inode);
+ mark_inode_dirty(inode);
+ return err;
+}
+
+static bool ntfs_xattr_user_list(struct dentry *dentry)
+{
+ return true;
+}
+
+// clang-format off
+static const struct xattr_handler ntfs_other_xattr_handler = {
+ .prefix = "",
+ .get = ntfs_getxattr,
+ .set = ntfs_setxattr,
+ .list = ntfs_xattr_user_list,
+};
+
+const struct xattr_handler * const ntfs_xattr_handlers[] = {
+ &ntfs_other_xattr_handler,
+ NULL,
+};
+// clang-format on
+
+#ifdef CONFIG_NTFSPLUS_FS_POSIX_ACL
+struct posix_acl *ntfs_get_acl(struct mnt_idmap *idmap, struct dentry *dentry,
+ int type)
+{
+ struct inode *inode = d_inode(dentry);
+ struct ntfs_inode *ni = NTFS_I(inode);
+ const char *name;
+ size_t name_len;
+ struct posix_acl *acl;
+ int err;
+ void *buf;
+
+ /* Allocate PATH_MAX bytes. */
+ buf = __getname();
+ if (!buf)
+ return ERR_PTR(-ENOMEM);
+
+ /* Possible values of 'type' was already checked above. */
+ if (type == ACL_TYPE_ACCESS) {
+ name = XATTR_NAME_POSIX_ACL_ACCESS;
+ name_len = sizeof(XATTR_NAME_POSIX_ACL_ACCESS) - 1;
+ } else {
+ name = XATTR_NAME_POSIX_ACL_DEFAULT;
+ name_len = sizeof(XATTR_NAME_POSIX_ACL_DEFAULT) - 1;
+ }
+
+ mutex_lock(&ni->mrec_lock);
+ err = ntfs_get_ea(inode, name, name_len, buf, PATH_MAX);
+ mutex_unlock(&ni->mrec_lock);
+
+ /* Translate extended attribute to acl. */
+ if (err >= 0)
+ acl = posix_acl_from_xattr(&init_user_ns, buf, err);
+ else if (err == -ENODATA)
+ acl = NULL;
+ else
+ acl = ERR_PTR(err);
+
+ if (!IS_ERR(acl))
+ set_cached_acl(inode, type, acl);
+
+ __putname(buf);
+
+ return acl;
+}
+
+static noinline int ntfs_set_acl_ex(struct mnt_idmap *idmap,
+ struct inode *inode, struct posix_acl *acl,
+ int type, bool init_acl)
+{
+ const char *name;
+ size_t size, name_len;
+ void *value;
+ int err;
+ int flags;
+ umode_t mode;
+
+ if (S_ISLNK(inode->i_mode))
+ return -EOPNOTSUPP;
+
+ mode = inode->i_mode;
+ switch (type) {
+ case ACL_TYPE_ACCESS:
+ /* Do not change i_mode if we are in init_acl */
+ if (acl && !init_acl) {
+ err = posix_acl_update_mode(idmap, inode, &mode, &acl);
+ if (err)
+ return err;
+ }
+ name = XATTR_NAME_POSIX_ACL_ACCESS;
+ name_len = sizeof(XATTR_NAME_POSIX_ACL_ACCESS) - 1;
+ break;
+
+ case ACL_TYPE_DEFAULT:
+ if (!S_ISDIR(inode->i_mode))
+ return acl ? -EACCES : 0;
+ name = XATTR_NAME_POSIX_ACL_DEFAULT;
+ name_len = sizeof(XATTR_NAME_POSIX_ACL_DEFAULT) - 1;
+ break;
+
+ default:
+ return -EINVAL;
+ }
+
+ if (!acl) {
+ /* Remove xattr if it can be presented via mode. */
+ size = 0;
+ value = NULL;
+ flags = XATTR_REPLACE;
+ } else {
+ size = posix_acl_xattr_size(acl->a_count);
+ value = kmalloc(size, GFP_NOFS);
+ if (!value)
+ return -ENOMEM;
+ err = posix_acl_to_xattr(&init_user_ns, acl, value, size);
+ if (err < 0)
+ goto out;
+ flags = 0;
+ }
+
+ mutex_lock(&NTFS_I(inode)->mrec_lock);
+ err = ntfs_set_ea(inode, name, name_len, value, size, flags, NULL);
+ mutex_unlock(&NTFS_I(inode)->mrec_lock);
+ if (err == -ENODATA && !size)
+ err = 0; /* Removing non existed xattr. */
+ if (!err) {
+ set_cached_acl(inode, type, acl);
+ inode->i_mode = mode;
+ inode_set_ctime_current(inode);
+ mark_inode_dirty(inode);
+ }
+
+out:
+ kfree(value);
+
+ return err;
+}
+
+int ntfs_set_acl(struct mnt_idmap *idmap, struct dentry *dentry,
+ struct posix_acl *acl, int type)
+{
+ return ntfs_set_acl_ex(idmap, d_inode(dentry), acl, type, false);
+}
+
+int ntfs_init_acl(struct mnt_idmap *idmap, struct inode *inode,
+ struct inode *dir)
+{
+ struct posix_acl *default_acl, *acl;
+ int err;
+
+ err = posix_acl_create(dir, &inode->i_mode, &default_acl, &acl);
+ if (err)
+ return err;
+
+ if (default_acl) {
+ err = ntfs_set_acl_ex(idmap, inode, default_acl,
+ ACL_TYPE_DEFAULT, true);
+ posix_acl_release(default_acl);
+ } else {
+ inode->i_default_acl = NULL;
+ }
+
+ if (acl) {
+ if (!err)
+ err = ntfs_set_acl_ex(idmap, inode, acl,
+ ACL_TYPE_ACCESS, true);
+ posix_acl_release(acl);
+ } else {
+ inode->i_acl = NULL;
+ }
+
+ return err;
+}
+#endif
diff --git a/fs/ntfsplus/reparse.c b/fs/ntfsplus/reparse.c
new file mode 100644
index 000000000000..ff46ef07178a
--- /dev/null
+++ b/fs/ntfsplus/reparse.c
@@ -0,0 +1,550 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/**
+ * Processing of reparse points
+ *
+ * Part of this file is based on code from the NTFS-3G project.
+ *
+ * Copyright (c) 2008-2021 Jean-Pierre Andre
+ * Copyright (c) 2025 LG Electronics Co., Ltd.
+ */
+
+#include "ntfs.h"
+#include "layout.h"
+#include "attrib.h"
+#include "inode.h"
+#include "dir.h"
+#include "volume.h"
+#include "mft.h"
+#include "index.h"
+#include "lcnalloc.h"
+#include "reparse.h"
+#include "misc.h"
+
+struct WSL_LINK_REPARSE_DATA {
+ __le32 type;
+ char link[];
+};
+
+struct REPARSE_INDEX { /* index entry in $Extend/$Reparse */
+ struct index_entry_header header;
+ struct reparse_index_key key;
+ __le32 filling;
+};
+
+__le16 reparse_index_name[] = { cpu_to_le16('$'),
+ cpu_to_le16('R') };
+
+/*
+ * Do some sanity checks on reparse data
+ *
+ * Microsoft reparse points have an 8-byte header whereas
+ * non-Microsoft reparse points have a 24-byte header. In each case,
+ * 'reparse_data_length' must equal the number of non-header bytes.
+ *
+ * If the reparse data looks like a junction point or symbolic
+ * link, more checks can be done.
+ */
+static bool valid_reparse_data(struct ntfs_inode *ni,
+ const struct reparse_point *reparse_attr, size_t size)
+{
+ bool ok;
+ const struct WSL_LINK_REPARSE_DATA *wsl_reparse_data;
+
+ ok = ni && reparse_attr && (size >= sizeof(struct reparse_point)) &&
+ (reparse_attr->reparse_tag != IO_REPARSE_TAG_RESERVED_ZERO) &&
+ (((size_t)le16_to_cpu(reparse_attr->reparse_data_length) +
+ sizeof(struct reparse_point) +
+ ((reparse_attr->reparse_tag & IO_REPARSE_TAG_IS_MICROSOFT) ?
+ 0 : sizeof(struct guid))) == size);
+ if (ok) {
+ switch (reparse_attr->reparse_tag) {
+ case IO_REPARSE_TAG_LX_SYMLINK:
+ wsl_reparse_data = (const struct WSL_LINK_REPARSE_DATA *)
+ reparse_attr->reparse_data;
+ if ((le16_to_cpu(reparse_attr->reparse_data_length) <=
+ sizeof(wsl_reparse_data->type)) ||
+ (wsl_reparse_data->type != cpu_to_le32(2)))
+ ok = false;
+ break;
+ case IO_REPARSE_TAG_AF_UNIX:
+ case IO_REPARSE_TAG_LX_FIFO:
+ case IO_REPARSE_TAG_LX_CHR:
+ case IO_REPARSE_TAG_LX_BLK:
+ if (reparse_attr->reparse_data_length ||
+ !(ni->flags & FILE_ATTRIBUTE_RECALL_ON_OPEN))
+ ok = false;
+ break;
+ default:
+ break;
+ }
+ }
+ return ok;
+}
+
+static unsigned int ntfs_reparse_tag_mode(struct reparse_point *reparse_attr)
+{
+ unsigned int mode = 0;
+
+ switch (reparse_attr->reparse_tag) {
+ case IO_REPARSE_TAG_SYMLINK:
+ case IO_REPARSE_TAG_LX_SYMLINK:
+ mode = S_IFLNK;
+ break;
+ case IO_REPARSE_TAG_AF_UNIX:
+ mode = S_IFSOCK;
+ break;
+ case IO_REPARSE_TAG_LX_FIFO:
+ mode = S_IFIFO;
+ break;
+ case IO_REPARSE_TAG_LX_CHR:
+ mode = S_IFCHR;
+ break;
+ case IO_REPARSE_TAG_LX_BLK:
+ mode = S_IFBLK;
+ }
+
+ return mode;
+}
+
+/*
+ * Get the target for symbolic link
+ */
+unsigned int ntfs_make_symlink(struct ntfs_inode *ni)
+{
+ s64 attr_size = 0;
+ unsigned int lth;
+ struct reparse_point *reparse_attr;
+ struct WSL_LINK_REPARSE_DATA *wsl_link_data;
+ unsigned int mode = 0;
+
+ reparse_attr = ntfs_attr_readall(ni, AT_REPARSE_POINT, NULL, 0,
+ &attr_size);
+ if (reparse_attr && attr_size &&
+ valid_reparse_data(ni, reparse_attr, attr_size)) {
+ switch (reparse_attr->reparse_tag) {
+ case IO_REPARSE_TAG_LX_SYMLINK:
+ wsl_link_data = (struct WSL_LINK_REPARSE_DATA *)reparse_attr->reparse_data;
+ if (wsl_link_data->type == cpu_to_le32(2)) {
+ lth = le16_to_cpu(reparse_attr->reparse_data_length) -
+ sizeof(wsl_link_data->type);
+ ni->target = ntfs_malloc_nofs(lth + 1);
+ if (ni->target) {
+ memcpy(ni->target, wsl_link_data->link, lth);
+ ni->target[lth] = 0;
+ mode = ntfs_reparse_tag_mode(reparse_attr);
+ }
+ }
+ break;
+ default:
+ mode = ntfs_reparse_tag_mode(reparse_attr);
+ }
+ } else
+ ni->flags &= ~FILE_ATTR_REPARSE_POINT;
+
+ if (reparse_attr)
+ ntfs_free(reparse_attr);
+
+ return mode;
+}
+
+unsigned int ntfs_reparse_tag_dt_types(struct ntfs_volume *vol, unsigned long mref)
+{
+ s64 attr_size = 0;
+ struct reparse_point *reparse_attr;
+ unsigned int dt_type = DT_UNKNOWN;
+ struct inode *vi;
+
+ vi = ntfs_iget(vol->sb, mref);
+ if (IS_ERR(vi))
+ return PTR_ERR(vi);
+
+ reparse_attr = (struct reparse_point *)ntfs_attr_readall(NTFS_I(vi),
+ AT_REPARSE_POINT, NULL, 0, &attr_size);
+
+ if (reparse_attr && attr_size) {
+ switch (reparse_attr->reparse_tag) {
+ case IO_REPARSE_TAG_SYMLINK:
+ case IO_REPARSE_TAG_LX_SYMLINK:
+ dt_type = DT_LNK;
+ break;
+ case IO_REPARSE_TAG_AF_UNIX:
+ dt_type = DT_SOCK;
+ break;
+ case IO_REPARSE_TAG_LX_FIFO:
+ dt_type = DT_FIFO;
+ break;
+ case IO_REPARSE_TAG_LX_CHR:
+ dt_type = DT_CHR;
+ break;
+ case IO_REPARSE_TAG_LX_BLK:
+ dt_type = DT_BLK;
+ }
+ }
+
+ if (reparse_attr)
+ ntfs_free(reparse_attr);
+
+ iput(vi);
+ return dt_type;
+}
+
+/*
+ * Set the index for new reparse data
+ */
+static int set_reparse_index(struct ntfs_inode *ni, struct ntfs_index_context *xr,
+ __le32 reparse_tag)
+{
+ struct REPARSE_INDEX indx;
+ u64 file_id_cpu;
+ __le64 file_id;
+
+ file_id_cpu = MK_MREF(ni->mft_no, ni->seq_no);
+ file_id = cpu_to_le64(file_id_cpu);
+ indx.header.data.vi.data_offset =
+ cpu_to_le16(sizeof(struct index_entry_header) + sizeof(struct reparse_index_key));
+ indx.header.data.vi.data_length = 0;
+ indx.header.data.vi.reservedV = 0;
+ indx.header.length = cpu_to_le16(sizeof(struct REPARSE_INDEX));
+ indx.header.key_length = cpu_to_le16(sizeof(struct reparse_index_key));
+ indx.header.flags = 0;
+ indx.header.reserved = 0;
+ indx.key.reparse_tag = reparse_tag;
+ /* danger on processors which require proper alignment! */
+ memcpy(&indx.key.file_id, &file_id, 8);
+ indx.filling = 0;
+ ntfs_index_ctx_reinit(xr);
+
+ return ntfs_ie_add(xr, (struct index_entry *)&indx);
+}
+
+/*
+ * Remove a reparse data index entry if attribute present
+ */
+static int remove_reparse_index(struct inode *rp, struct ntfs_index_context *xr,
+ __le32 *preparse_tag)
+{
+ struct reparse_index_key key;
+ u64 file_id_cpu;
+ __le64 file_id;
+ s64 size;
+ struct ntfs_inode *ni = NTFS_I(rp);
+ int err = 0, ret = ni->data_size;
+
+ if (ni->data_size == 0)
+ return 0;
+
+ /* read the existing reparse_tag */
+ size = ntfs_inode_attr_pread(rp, 0, 4, (char *)preparse_tag);
+ if (size != 4)
+ return -ENODATA;
+
+ file_id_cpu = MK_MREF(ni->mft_no, ni->seq_no);
+ file_id = cpu_to_le64(file_id_cpu);
+ key.reparse_tag = *preparse_tag;
+ /* danger on processors which require proper alignment! */
+ memcpy(&key.file_id, &file_id, 8);
+ if (!ntfs_index_lookup(&key, sizeof(struct reparse_index_key), xr)) {
+ err = ntfs_index_rm(xr);
+ if (err)
+ ret = err;
+ }
+ return ret;
+}
+
+/*
+ * Open the $Extend/$Reparse file and its index
+ */
+static struct ntfs_index_context *open_reparse_index(struct ntfs_volume *vol)
+{
+ struct ntfs_index_context *xr = NULL;
+ u64 mref;
+ __le16 *uname;
+ struct ntfs_name *name = NULL;
+ int uname_len;
+ struct inode *vi, *dir_vi;
+
+ /* do not use path_name_to inode - could reopen root */
+ dir_vi = ntfs_iget(vol->sb, FILE_Extend);
+ if (IS_ERR(dir_vi))
+ return NULL;
+
+ uname_len = ntfs_nlstoucs(vol, "$Reparse", 8, &uname,
+ NTFS_MAX_NAME_LEN);
+ if (uname_len < 0) {
+ iput(dir_vi);
+ return NULL;
+ }
+
+ mutex_lock_nested(&NTFS_I(dir_vi)->mrec_lock, NTFS_REPARSE_MUTEX_PARENT);
+ mref = ntfs_lookup_inode_by_name(NTFS_I(dir_vi), uname, uname_len,
+ &name);
+ mutex_unlock(&NTFS_I(dir_vi)->mrec_lock);
+ kfree(name);
+ kmem_cache_free(ntfs_name_cache, uname);
+ if (IS_ERR_MREF(mref))
+ goto put_dir_vi;
+
+ vi = ntfs_iget(vol->sb, MREF(mref));
+ if (IS_ERR(vi))
+ goto put_dir_vi;
+
+ xr = ntfs_index_ctx_get(NTFS_I(vi), reparse_index_name, 2);
+ if (!xr)
+ iput(vi);
+put_dir_vi:
+ iput(dir_vi);
+ return xr;
+}
+
+
+/*
+ * Update the reparse data and index
+ *
+ * The reparse data attribute should have been created, and
+ * an existing index is expected if there is an existing value.
+ *
+ */
+static int update_reparse_data(struct ntfs_inode *ni, struct ntfs_index_context *xr,
+ char *value, size_t size)
+{
+ struct inode *rp_inode;
+ int err = 0;
+ s64 written;
+ int oldsize;
+ __le32 reparse_tag;
+ struct ntfs_inode *rp_ni;
+
+ rp_inode = ntfs_attr_iget(VFS_I(ni), AT_REPARSE_POINT, AT_UNNAMED, 0);
+ if (IS_ERR(rp_inode))
+ return -EINVAL;
+ rp_ni = NTFS_I(rp_inode);
+
+ /* remove the existing reparse data */
+ oldsize = remove_reparse_index(rp_inode, xr, &reparse_tag);
+ if (oldsize < 0) {
+ err = oldsize;
+ goto put_rp_inode;
+ }
+
+ /* overwrite value if any */
+ written = ntfs_inode_attr_pwrite(rp_inode, 0, size, value, false);
+ if (written != size) {
+ ntfs_error(ni->vol->sb, "Failed to update reparse data\n");
+ err = -EIO;
+ goto put_rp_inode;
+ }
+
+ if (set_reparse_index(ni, xr, ((const struct reparse_point *)value)->reparse_tag) &&
+ oldsize > 0) {
+ /*
+ * If cannot index, try to remove the reparse
+ * data and log the error. There will be an
+ * inconsistency if removal fails.
+ */
+ ntfs_attr_rm(rp_ni);
+ ntfs_error(ni->vol->sb,
+ "Failed to index reparse data. Possible corruption.\n");
+ }
+
+ mark_mft_record_dirty(ni);
+put_rp_inode:
+ iput(rp_inode);
+
+ return err;
+}
+
+/*
+ * Delete a reparse index entry
+ */
+int ntfs_delete_reparse_index(struct ntfs_inode *ni)
+{
+ struct inode *vi;
+ struct ntfs_index_context *xr;
+ struct ntfs_inode *xrni;
+ __le32 reparse_tag;
+ int err = 0;
+
+ if (!(ni->flags & FILE_ATTR_REPARSE_POINT))
+ return 0;
+
+ vi = ntfs_attr_iget(VFS_I(ni), AT_REPARSE_POINT, AT_UNNAMED, 0);
+ if (IS_ERR(vi))
+ return PTR_ERR(vi);
+
+ /*
+ * read the existing reparse data (the tag is enough)
+ * and un-index it
+ */
+ xr = open_reparse_index(ni->vol);
+ if (xr) {
+ xrni = xr->idx_ni;
+ mutex_lock_nested(&xrni->mrec_lock, NTFS_REPARSE_MUTEX_PARENT);
+ err = remove_reparse_index(vi, xr, &reparse_tag);
+ if (err < 0) {
+ ntfs_index_ctx_put(xr);
+ mutex_unlock(&xrni->mrec_lock);
+ iput(VFS_I(xrni));
+ goto out;
+ }
+ mark_mft_record_dirty(xrni);
+ ntfs_index_ctx_put(xr);
+ mutex_unlock(&xrni->mrec_lock);
+ iput(VFS_I(xrni));
+ }
+
+ ni->flags &= ~FILE_ATTR_REPARSE_POINT;
+ NInoSetFileNameDirty(ni);
+ mark_mft_record_dirty(ni);
+
+out:
+ iput(vi);
+ return err;
+}
+
+/*
+ * Set the reparse data from an extended attribute
+ */
+static int ntfs_set_ntfs_reparse_data(struct ntfs_inode *ni, char *value, size_t size)
+{
+ int err = 0;
+ struct ntfs_inode *xrni;
+ struct ntfs_index_context *xr;
+
+ if (!ni)
+ return -EINVAL;
+
+ /*
+ * reparse data compatibily with EA is not checked
+ * any more, it is required by Windows 10, but may
+ * lead to problems with earlier versions.
+ */
+ if (valid_reparse_data(ni, (const struct reparse_point *)value, size) == false)
+ return -EINVAL;
+
+ xr = open_reparse_index(ni->vol);
+ if (!xr)
+ return -EINVAL;
+ xrni = xr->idx_ni;
+
+ if (!ntfs_attr_exist(ni, AT_REPARSE_POINT, AT_UNNAMED, 0)) {
+ u8 dummy = 0;
+
+ /*
+ * no reparse data attribute : add one,
+ * apparently, this does not feed the new value in
+ * Note : NTFS version must be >= 3
+ */
+ if (ni->vol->major_ver < 3) {
+ err = -EOPNOTSUPP;
+ ntfs_index_ctx_put(xr);
+ goto out;
+ }
+
+ err = ntfs_attr_add(ni, AT_REPARSE_POINT, AT_UNNAMED, 0, &dummy, 0);
+ if (err) {
+ ntfs_index_ctx_put(xr);
+ goto out;
+ }
+ ni->flags |= FILE_ATTR_REPARSE_POINT;
+ NInoSetFileNameDirty(ni);
+ mark_mft_record_dirty(ni);
+ }
+
+ /* update value and index */
+ mutex_lock_nested(&xrni->mrec_lock, NTFS_REPARSE_MUTEX_PARENT);
+ err = update_reparse_data(ni, xr, value, size);
+ if (err) {
+ ni->flags &= ~FILE_ATTR_REPARSE_POINT;
+ NInoSetFileNameDirty(ni);
+ mark_mft_record_dirty(ni);
+ }
+ ntfs_index_ctx_put(xr);
+ mutex_unlock(&xrni->mrec_lock);
+
+out:
+ if (!err)
+ mark_mft_record_dirty(xrni);
+ iput(VFS_I(xrni));
+
+ return err;
+}
+
+/*
+ * Set reparse data for a WSL type symlink
+ */
+int ntfs_reparse_set_wsl_symlink(struct ntfs_inode *ni,
+ const __le16 *target, int target_len)
+{
+ int err = 0;
+ int len;
+ int reparse_len;
+ unsigned char *utarget = NULL;
+ struct reparse_point *reparse;
+ struct WSL_LINK_REPARSE_DATA *data;
+
+ utarget = (char *)NULL;
+ len = ntfs_ucstonls(ni->vol, target, target_len, &utarget, 0);
+ if (len <= 0)
+ return -EINVAL;
+
+ reparse_len = sizeof(struct reparse_point) + sizeof(data->type) + len;
+ reparse = (struct reparse_point *)ntfs_malloc_nofs(reparse_len);
+ if (!reparse) {
+ err = -ENOMEM;
+ ntfs_free(utarget);
+ } else {
+ data = (struct WSL_LINK_REPARSE_DATA *)reparse->reparse_data;
+ reparse->reparse_tag = IO_REPARSE_TAG_LX_SYMLINK;
+ reparse->reparse_data_length =
+ cpu_to_le16(sizeof(data->type) + len);
+ reparse->reserved = 0;
+ data->type = cpu_to_le32(2);
+ memcpy(data->link, utarget, len);
+ err = ntfs_set_ntfs_reparse_data(ni,
+ (char *)reparse, reparse_len);
+ ntfs_free(reparse);
+ if (!err)
+ ni->target = utarget;
+ }
+ return err;
+}
+
+/*
+ * Set reparse data for a WSL special file other than a symlink
+ * (socket, fifo, character or block device)
+ */
+int ntfs_reparse_set_wsl_not_symlink(struct ntfs_inode *ni, mode_t mode)
+{
+ int err;
+ int len;
+ int reparse_len;
+ __le32 reparse_tag;
+ struct reparse_point *reparse;
+
+ len = 0;
+ if (S_ISSOCK(mode))
+ reparse_tag = IO_REPARSE_TAG_AF_UNIX;
+ else if (S_ISFIFO(mode))
+ reparse_tag = IO_REPARSE_TAG_LX_FIFO;
+ else if (S_ISCHR(mode))
+ reparse_tag = IO_REPARSE_TAG_LX_CHR;
+ else if (S_ISBLK(mode))
+ reparse_tag = IO_REPARSE_TAG_LX_BLK;
+ else
+ return -EOPNOTSUPP;
+
+ reparse_len = sizeof(struct reparse_point) + len;
+ reparse = (struct reparse_point *)ntfs_malloc_nofs(reparse_len);
+ if (!reparse)
+ err = -ENOMEM;
+ else {
+ reparse->reparse_tag = reparse_tag;
+ reparse->reparse_data_length = cpu_to_le16(len);
+ reparse->reserved = cpu_to_le16(0);
+ err = ntfs_set_ntfs_reparse_data(ni, (char *)reparse,
+ reparse_len);
+ ntfs_free(reparse);
+ }
+
+ return err;
+}
--
2.34.1
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH 10/11] ntfsplus: add misc operations
2025-10-20 2:12 [PATCH 06/11] ntfsplus: add iomap and address space operations Namjae Jeon
` (2 preceding siblings ...)
2025-10-20 2:12 ` [PATCH 09/11] ntfsplus: add reparse and ea operations Namjae Jeon
@ 2025-10-20 2:12 ` Namjae Jeon
2025-10-20 2:12 ` [PATCH 11/11] ntfsplus: add Kconfig and Makefile Namjae Jeon
4 siblings, 0 replies; 6+ messages in thread
From: Namjae Jeon @ 2025-10-20 2:12 UTC (permalink / raw)
To: viro, brauner, hch, hch, tytso, willy, jack, djwong, josef,
sandeen, rgoldwyn, xiang, dsterba, pali, ebiggers, neil,
amir73il
Cc: linux-fsdevel, linux-kernel, iamjoonsoo.kim, cheol.lee, jay.sim,
gunho.lee, Namjae Jeon
This adds the implementation of misc operations for ntfsplus.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
---
fs/ntfsplus/collate.c | 173 ++++++++++
fs/ntfsplus/logfile.c | 773 ++++++++++++++++++++++++++++++++++++++++++
fs/ntfsplus/misc.c | 221 ++++++++++++
fs/ntfsplus/unistr.c | 471 +++++++++++++++++++++++++
fs/ntfsplus/upcase.c | 73 ++++
5 files changed, 1711 insertions(+)
create mode 100644 fs/ntfsplus/collate.c
create mode 100644 fs/ntfsplus/logfile.c
create mode 100644 fs/ntfsplus/misc.c
create mode 100644 fs/ntfsplus/unistr.c
create mode 100644 fs/ntfsplus/upcase.c
diff --git a/fs/ntfsplus/collate.c b/fs/ntfsplus/collate.c
new file mode 100644
index 000000000000..8547adf7146e
--- /dev/null
+++ b/fs/ntfsplus/collate.c
@@ -0,0 +1,173 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * NTFS kernel collation handling. Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2004 Anton Altaparmakov
+ *
+ * Part of this file is based on code from the NTFS-3G project.
+ * and is copyrighted by the respective authors below:
+ * Copyright (c) 2004 Anton Altaparmakov
+ * Copyright (c) 2005 Yura Pakhuchiy
+ */
+
+#include "collate.h"
+#include "misc.h"
+#include "ntfs.h"
+
+static int ntfs_collate_binary(struct ntfs_volume *vol,
+ const void *data1, const int data1_len,
+ const void *data2, const int data2_len)
+{
+ int rc;
+
+ ntfs_debug("Entering.");
+ rc = memcmp(data1, data2, min(data1_len, data2_len));
+ if (!rc && (data1_len != data2_len)) {
+ if (data1_len < data2_len)
+ rc = -1;
+ else
+ rc = 1;
+ }
+ ntfs_debug("Done, returning %i", rc);
+ return rc;
+}
+
+static int ntfs_collate_ntofs_ulong(struct ntfs_volume *vol,
+ const void *data1, const int data1_len,
+ const void *data2, const int data2_len)
+{
+ int rc;
+ u32 d1, d2;
+
+ ntfs_debug("Entering.");
+ BUG_ON(data1_len != data2_len);
+ BUG_ON(data1_len != 4);
+ d1 = le32_to_cpup(data1);
+ d2 = le32_to_cpup(data2);
+ if (d1 < d2)
+ rc = -1;
+ else {
+ if (d1 == d2)
+ rc = 0;
+ else
+ rc = 1;
+ }
+ ntfs_debug("Done, returning %i", rc);
+ return rc;
+}
+
+/**
+ * ntfs_collate_ntofs_ulongs - Which of two le32 arrays should be listed first
+ *
+ * Returns: -1, 0 or 1 depending of how the arrays compare
+ */
+static int ntfs_collate_ntofs_ulongs(struct ntfs_volume *vol,
+ const void *data1, const int data1_len,
+ const void *data2, const int data2_len)
+{
+ int rc;
+ int len;
+ const __le32 *p1, *p2;
+ u32 d1, d2;
+
+ ntfs_debug("Entering.");
+ if ((data1_len != data2_len) || (data1_len <= 0) || (data1_len & 3)) {
+ ntfs_error(vol->sb, "data1_len or data2_len not valid\n");
+ return -1;
+ }
+
+ p1 = (const __le32 *)data1;
+ p2 = (const __le32 *)data2;
+ len = data1_len;
+ do {
+ d1 = le32_to_cpup(p1);
+ p1++;
+ d2 = le32_to_cpup(p2);
+ p2++;
+ } while ((d1 == d2) && ((len -= 4) > 0));
+ if (d1 < d2)
+ rc = -1;
+ else {
+ if (d1 == d2)
+ rc = 0;
+ else
+ rc = 1;
+ }
+ ntfs_debug("Done, returning %i.", rc);
+ return rc;
+}
+
+/**
+ * ntfs_collate_file_name - Which of two filenames should be listed first
+ */
+static int ntfs_collate_file_name(struct ntfs_volume *vol,
+ const void *data1, const int __always_unused data1_len,
+ const void *data2, const int __always_unused data2_len)
+{
+ int rc;
+
+ ntfs_debug("Entering.\n");
+ rc = ntfs_file_compare_values(data1, data2, -2,
+ IGNORE_CASE, vol->upcase, vol->upcase_len);
+ if (!rc)
+ rc = ntfs_file_compare_values(data1, data2,
+ -2, CASE_SENSITIVE, vol->upcase, vol->upcase_len);
+ ntfs_debug("Done, returning %i.\n", rc);
+ return rc;
+}
+
+typedef int (*ntfs_collate_func_t)(struct ntfs_volume *, const void *, const int,
+ const void *, const int);
+
+static ntfs_collate_func_t ntfs_do_collate0x0[3] = {
+ ntfs_collate_binary,
+ ntfs_collate_file_name,
+ NULL/*ntfs_collate_unicode_string*/,
+};
+
+static ntfs_collate_func_t ntfs_do_collate0x1[4] = {
+ ntfs_collate_ntofs_ulong,
+ NULL/*ntfs_collate_ntofs_sid*/,
+ NULL/*ntfs_collate_ntofs_security_hash*/,
+ ntfs_collate_ntofs_ulongs,
+};
+
+/**
+ * ntfs_collate - collate two data items using a specified collation rule
+ * @vol: ntfs volume to which the data items belong
+ * @cr: collation rule to use when comparing the items
+ * @data1: first data item to collate
+ * @data1_len: length in bytes of @data1
+ * @data2: second data item to collate
+ * @data2_len: length in bytes of @data2
+ *
+ * Collate the two data items @data1 and @data2 using the collation rule @cr
+ * and return -1, 0, ir 1 if @data1 is found, respectively, to collate before,
+ * to match, or to collate after @data2.
+ *
+ * For speed we use the collation rule @cr as an index into two tables of
+ * function pointers to call the appropriate collation function.
+ */
+int ntfs_collate(struct ntfs_volume *vol, __le32 cr,
+ const void *data1, const int data1_len,
+ const void *data2, const int data2_len)
+{
+ int i;
+
+ ntfs_debug("Entering.");
+
+ BUG_ON(cr != COLLATION_BINARY && cr != COLLATION_NTOFS_ULONG &&
+ cr != COLLATION_FILE_NAME && cr != COLLATION_NTOFS_ULONGS);
+ i = le32_to_cpu(cr);
+ BUG_ON(i < 0);
+ if (i <= 0x02)
+ return ntfs_do_collate0x0[i](vol, data1, data1_len,
+ data2, data2_len);
+ BUG_ON(i < 0x10);
+ i -= 0x10;
+ if (likely(i <= 3))
+ return ntfs_do_collate0x1[i](vol, data1, data1_len,
+ data2, data2_len);
+ BUG();
+ return 0;
+}
diff --git a/fs/ntfsplus/logfile.c b/fs/ntfsplus/logfile.c
new file mode 100644
index 000000000000..f6e47accb517
--- /dev/null
+++ b/fs/ntfsplus/logfile.c
@@ -0,0 +1,773 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * NTFS kernel journal handling. Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2002-2007 Anton Altaparmakov
+ */
+
+#include <linux/bio.h>
+
+#include "attrib.h"
+#include "aops.h"
+#include "logfile.h"
+#include "misc.h"
+#include "ntfs.h"
+
+/**
+ * ntfs_check_restart_page_header - check the page header for consistency
+ * @vi: LogFile inode to which the restart page header belongs
+ * @rp: restart page header to check
+ * @pos: position in @vi at which the restart page header resides
+ *
+ * Check the restart page header @rp for consistency and return 'true' if it is
+ * consistent and 'false' otherwise.
+ *
+ * This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
+ * require the full restart page.
+ */
+static bool ntfs_check_restart_page_header(struct inode *vi,
+ struct restart_page_header *rp, s64 pos)
+{
+ u32 logfile_system_page_size, logfile_log_page_size;
+ u16 ra_ofs, usa_count, usa_ofs, usa_end = 0;
+ bool have_usa = true;
+
+ ntfs_debug("Entering.");
+ /*
+ * If the system or log page sizes are smaller than the ntfs block size
+ * or either is not a power of 2 we cannot handle this log file.
+ */
+ logfile_system_page_size = le32_to_cpu(rp->system_page_size);
+ logfile_log_page_size = le32_to_cpu(rp->log_page_size);
+ if (logfile_system_page_size < NTFS_BLOCK_SIZE ||
+ logfile_log_page_size < NTFS_BLOCK_SIZE ||
+ logfile_system_page_size &
+ (logfile_system_page_size - 1) ||
+ !is_power_of_2(logfile_log_page_size)) {
+ ntfs_error(vi->i_sb, "LogFile uses unsupported page size.");
+ return false;
+ }
+ /*
+ * We must be either at !pos (1st restart page) or at pos = system page
+ * size (2nd restart page).
+ */
+ if (pos && pos != logfile_system_page_size) {
+ ntfs_error(vi->i_sb, "Found restart area in incorrect position in LogFile.");
+ return false;
+ }
+ /* We only know how to handle version 1.1. */
+ if (le16_to_cpu(rp->major_ver) != 1 ||
+ le16_to_cpu(rp->minor_ver) != 1) {
+ ntfs_error(vi->i_sb,
+ "LogFile version %i.%i is not supported. (This driver supports version 1.1 only.)",
+ (int)le16_to_cpu(rp->major_ver),
+ (int)le16_to_cpu(rp->minor_ver));
+ return false;
+ }
+ /*
+ * If chkdsk has been run the restart page may not be protected by an
+ * update sequence array.
+ */
+ if (ntfs_is_chkd_record(rp->magic) && !le16_to_cpu(rp->usa_count)) {
+ have_usa = false;
+ goto skip_usa_checks;
+ }
+ /* Verify the size of the update sequence array. */
+ usa_count = 1 + (logfile_system_page_size >> NTFS_BLOCK_SIZE_BITS);
+ if (usa_count != le16_to_cpu(rp->usa_count)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart page specifies inconsistent update sequence array count.");
+ return false;
+ }
+ /* Verify the position of the update sequence array. */
+ usa_ofs = le16_to_cpu(rp->usa_ofs);
+ usa_end = usa_ofs + usa_count * sizeof(u16);
+ if (usa_ofs < sizeof(struct restart_page_header) ||
+ usa_end > NTFS_BLOCK_SIZE - sizeof(u16)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart page specifies inconsistent update sequence array offset.");
+ return false;
+ }
+skip_usa_checks:
+ /*
+ * Verify the position of the restart area. It must be:
+ * - aligned to 8-byte boundary,
+ * - after the update sequence array, and
+ * - within the system page size.
+ */
+ ra_ofs = le16_to_cpu(rp->restart_area_offset);
+ if (ra_ofs & 7 || (have_usa ? ra_ofs < usa_end :
+ ra_ofs < sizeof(struct restart_page_header)) ||
+ ra_ofs > logfile_system_page_size) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart page specifies inconsistent restart area offset.");
+ return false;
+ }
+ /*
+ * Only restart pages modified by chkdsk are allowed to have chkdsk_lsn
+ * set.
+ */
+ if (!ntfs_is_chkd_record(rp->magic) && le64_to_cpu(rp->chkdsk_lsn)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart page is not modified by chkdsk but a chkdsk LSN is specified.");
+ return false;
+ }
+ ntfs_debug("Done.");
+ return true;
+}
+
+/**
+ * ntfs_check_restart_area - check the restart area for consistency
+ * @vi: LogFile inode to which the restart page belongs
+ * @rp: restart page whose restart area to check
+ *
+ * Check the restart area of the restart page @rp for consistency and return
+ * 'true' if it is consistent and 'false' otherwise.
+ *
+ * This function assumes that the restart page header has already been
+ * consistency checked.
+ *
+ * This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
+ * require the full restart page.
+ */
+static bool ntfs_check_restart_area(struct inode *vi, struct restart_page_header *rp)
+{
+ u64 file_size;
+ struct restart_area *ra;
+ u16 ra_ofs, ra_len, ca_ofs;
+ u8 fs_bits;
+
+ ntfs_debug("Entering.");
+ ra_ofs = le16_to_cpu(rp->restart_area_offset);
+ ra = (struct restart_area *)((u8 *)rp + ra_ofs);
+ /*
+ * Everything before ra->file_size must be before the first word
+ * protected by an update sequence number. This ensures that it is
+ * safe to access ra->client_array_offset.
+ */
+ if (ra_ofs + offsetof(struct restart_area, file_size) >
+ NTFS_BLOCK_SIZE - sizeof(u16)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart area specifies inconsistent file offset.");
+ return false;
+ }
+ /*
+ * Now that we can access ra->client_array_offset, make sure everything
+ * up to the log client array is before the first word protected by an
+ * update sequence number. This ensures we can access all of the
+ * restart area elements safely. Also, the client array offset must be
+ * aligned to an 8-byte boundary.
+ */
+ ca_ofs = le16_to_cpu(ra->client_array_offset);
+ if (((ca_ofs + 7) & ~7) != ca_ofs ||
+ ra_ofs + ca_ofs > NTFS_BLOCK_SIZE - sizeof(u16)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart area specifies inconsistent client array offset.");
+ return false;
+ }
+ /*
+ * The restart area must end within the system page size both when
+ * calculated manually and as specified by ra->restart_area_length.
+ * Also, the calculated length must not exceed the specified length.
+ */
+ ra_len = ca_ofs + le16_to_cpu(ra->log_clients) *
+ sizeof(struct log_client_record);
+ if (ra_ofs + ra_len > le32_to_cpu(rp->system_page_size) ||
+ ra_ofs + le16_to_cpu(ra->restart_area_length) >
+ le32_to_cpu(rp->system_page_size) ||
+ ra_len > le16_to_cpu(ra->restart_area_length)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart area is out of bounds of the system page size specified by the restart page header and/or the specified restart area length is inconsistent.");
+ return false;
+ }
+ /*
+ * The ra->client_free_list and ra->client_in_use_list must be either
+ * LOGFILE_NO_CLIENT or less than ra->log_clients or they are
+ * overflowing the client array.
+ */
+ if ((ra->client_free_list != LOGFILE_NO_CLIENT &&
+ le16_to_cpu(ra->client_free_list) >=
+ le16_to_cpu(ra->log_clients)) ||
+ (ra->client_in_use_list != LOGFILE_NO_CLIENT &&
+ le16_to_cpu(ra->client_in_use_list) >=
+ le16_to_cpu(ra->log_clients))) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart area specifies overflowing client free and/or in use lists.");
+ return false;
+ }
+ /*
+ * Check ra->seq_number_bits against ra->file_size for consistency.
+ * We cannot just use ffs() because the file size is not a power of 2.
+ */
+ file_size = le64_to_cpu(ra->file_size);
+ fs_bits = 0;
+ while (file_size) {
+ file_size >>= 1;
+ fs_bits++;
+ }
+ if (le32_to_cpu(ra->seq_number_bits) != 67 - fs_bits) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart area specifies inconsistent sequence number bits.");
+ return false;
+ }
+ /* The log record header length must be a multiple of 8. */
+ if (((le16_to_cpu(ra->log_record_header_length) + 7) & ~7) !=
+ le16_to_cpu(ra->log_record_header_length)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart area specifies inconsistent log record header length.");
+ return false;
+ }
+ /* Dito for the log page data offset. */
+ if (((le16_to_cpu(ra->log_page_data_offset) + 7) & ~7) !=
+ le16_to_cpu(ra->log_page_data_offset)) {
+ ntfs_error(vi->i_sb,
+ "LogFile restart area specifies inconsistent log page data offset.");
+ return false;
+ }
+ ntfs_debug("Done.");
+ return true;
+}
+
+/**
+ * ntfs_check_log_client_array - check the log client array for consistency
+ * @vi: LogFile inode to which the restart page belongs
+ * @rp: restart page whose log client array to check
+ *
+ * Check the log client array of the restart page @rp for consistency and
+ * return 'true' if it is consistent and 'false' otherwise.
+ *
+ * This function assumes that the restart page header and the restart area have
+ * already been consistency checked.
+ *
+ * Unlike ntfs_check_restart_page_header() and ntfs_check_restart_area(), this
+ * function needs @rp->system_page_size bytes in @rp, i.e. it requires the full
+ * restart page and the page must be multi sector transfer deprotected.
+ */
+static bool ntfs_check_log_client_array(struct inode *vi,
+ struct restart_page_header *rp)
+{
+ struct restart_area *ra;
+ struct log_client_record *ca, *cr;
+ u16 nr_clients, idx;
+ bool in_free_list, idx_is_first;
+
+ ntfs_debug("Entering.");
+ ra = (struct restart_area *)((u8 *)rp + le16_to_cpu(rp->restart_area_offset));
+ ca = (struct log_client_record *)((u8 *)ra +
+ le16_to_cpu(ra->client_array_offset));
+ /*
+ * Check the ra->client_free_list first and then check the
+ * ra->client_in_use_list. Check each of the log client records in
+ * each of the lists and check that the array does not overflow the
+ * ra->log_clients value. Also keep track of the number of records
+ * visited as there cannot be more than ra->log_clients records and
+ * that way we detect eventual loops in within a list.
+ */
+ nr_clients = le16_to_cpu(ra->log_clients);
+ idx = le16_to_cpu(ra->client_free_list);
+ in_free_list = true;
+check_list:
+ for (idx_is_first = true; idx != LOGFILE_NO_CLIENT_CPU; nr_clients--,
+ idx = le16_to_cpu(cr->next_client)) {
+ if (!nr_clients || idx >= le16_to_cpu(ra->log_clients))
+ goto err_out;
+ /* Set @cr to the current log client record. */
+ cr = ca + idx;
+ /* The first log client record must not have a prev_client. */
+ if (idx_is_first) {
+ if (cr->prev_client != LOGFILE_NO_CLIENT)
+ goto err_out;
+ idx_is_first = false;
+ }
+ }
+ /* Switch to and check the in use list if we just did the free list. */
+ if (in_free_list) {
+ in_free_list = false;
+ idx = le16_to_cpu(ra->client_in_use_list);
+ goto check_list;
+ }
+ ntfs_debug("Done.");
+ return true;
+err_out:
+ ntfs_error(vi->i_sb, "LogFile log client array is corrupt.");
+ return false;
+}
+
+/**
+ * ntfs_check_and_load_restart_page - check the restart page for consistency
+ * @vi: LogFile inode to which the restart page belongs
+ * @rp: restart page to check
+ * @pos: position in @vi at which the restart page resides
+ * @wrp: [OUT] copy of the multi sector transfer deprotected restart page
+ * @lsn: [OUT] set to the current logfile lsn on success
+ *
+ * Check the restart page @rp for consistency and return 0 if it is consistent
+ * and -errno otherwise. The restart page may have been modified by chkdsk in
+ * which case its magic is CHKD instead of RSTR.
+ *
+ * This function only needs NTFS_BLOCK_SIZE bytes in @rp, i.e. it does not
+ * require the full restart page.
+ *
+ * If @wrp is not NULL, on success, *@wrp will point to a buffer containing a
+ * copy of the complete multi sector transfer deprotected page. On failure,
+ * *@wrp is undefined.
+ *
+ * Simillarly, if @lsn is not NULL, on success *@lsn will be set to the current
+ * logfile lsn according to this restart page. On failure, *@lsn is undefined.
+ *
+ * The following error codes are defined:
+ * -EINVAL - The restart page is inconsistent.
+ * -ENOMEM - Not enough memory to load the restart page.
+ * -EIO - Failed to reading from LogFile.
+ */
+static int ntfs_check_and_load_restart_page(struct inode *vi,
+ struct restart_page_header *rp, s64 pos, struct restart_page_header **wrp,
+ s64 *lsn)
+{
+ struct restart_area *ra;
+ struct restart_page_header *trp;
+ int size, err;
+
+ ntfs_debug("Entering.");
+ /* Check the restart page header for consistency. */
+ if (!ntfs_check_restart_page_header(vi, rp, pos)) {
+ /* Error output already done inside the function. */
+ return -EINVAL;
+ }
+ /* Check the restart area for consistency. */
+ if (!ntfs_check_restart_area(vi, rp)) {
+ /* Error output already done inside the function. */
+ return -EINVAL;
+ }
+ ra = (struct restart_area *)((u8 *)rp + le16_to_cpu(rp->restart_area_offset));
+ /*
+ * Allocate a buffer to store the whole restart page so we can multi
+ * sector transfer deprotect it.
+ */
+ trp = ntfs_malloc_nofs(le32_to_cpu(rp->system_page_size));
+ if (!trp) {
+ ntfs_error(vi->i_sb, "Failed to allocate memory for LogFile restart page buffer.");
+ return -ENOMEM;
+ }
+ /*
+ * Read the whole of the restart page into the buffer. If it fits
+ * completely inside @rp, just copy it from there. Otherwise map all
+ * the required pages and copy the data from them.
+ */
+ size = PAGE_SIZE - (pos & ~PAGE_MASK);
+ if (size >= le32_to_cpu(rp->system_page_size)) {
+ memcpy(trp, rp, le32_to_cpu(rp->system_page_size));
+ } else {
+ pgoff_t idx;
+ struct folio *folio;
+ int have_read, to_read;
+
+ /* First copy what we already have in @rp. */
+ memcpy(trp, rp, size);
+ /* Copy the remaining data one page at a time. */
+ have_read = size;
+ to_read = le32_to_cpu(rp->system_page_size) - size;
+ idx = (pos + size) >> PAGE_SHIFT;
+ BUG_ON((pos + size) & ~PAGE_MASK);
+ do {
+ folio = ntfs_read_mapping_folio(vi->i_mapping, idx);
+ if (IS_ERR(folio)) {
+ ntfs_error(vi->i_sb, "Error mapping LogFile page (index %lu).",
+ idx);
+ err = PTR_ERR(folio);
+ if (err != -EIO && err != -ENOMEM)
+ err = -EIO;
+ goto err_out;
+ }
+ size = min_t(int, to_read, PAGE_SIZE);
+ memcpy((u8 *)trp + have_read, folio_address(folio), size);
+ folio_put(folio);
+ have_read += size;
+ to_read -= size;
+ idx++;
+ } while (to_read > 0);
+ }
+ /*
+ * Perform the multi sector transfer deprotection on the buffer if the
+ * restart page is protected.
+ */
+ if ((!ntfs_is_chkd_record(trp->magic) || le16_to_cpu(trp->usa_count)) &&
+ post_read_mst_fixup((struct ntfs_record *)trp, le32_to_cpu(rp->system_page_size))) {
+ /*
+ * A multi sector transfer error was detected. We only need to
+ * abort if the restart page contents exceed the multi sector
+ * transfer fixup of the first sector.
+ */
+ if (le16_to_cpu(rp->restart_area_offset) +
+ le16_to_cpu(ra->restart_area_length) >
+ NTFS_BLOCK_SIZE - sizeof(u16)) {
+ ntfs_error(vi->i_sb,
+ "Multi sector transfer error detected in LogFile restart page.");
+ err = -EINVAL;
+ goto err_out;
+ }
+ }
+ /*
+ * If the restart page is modified by chkdsk or there are no active
+ * logfile clients, the logfile is consistent. Otherwise, need to
+ * check the log client records for consistency, too.
+ */
+ err = 0;
+ if (ntfs_is_rstr_record(rp->magic) &&
+ ra->client_in_use_list != LOGFILE_NO_CLIENT) {
+ if (!ntfs_check_log_client_array(vi, trp)) {
+ err = -EINVAL;
+ goto err_out;
+ }
+ }
+ if (lsn) {
+ if (ntfs_is_rstr_record(rp->magic))
+ *lsn = le64_to_cpu(ra->current_lsn);
+ else /* if (ntfs_is_chkd_record(rp->magic)) */
+ *lsn = le64_to_cpu(rp->chkdsk_lsn);
+ }
+ ntfs_debug("Done.");
+ if (wrp)
+ *wrp = trp;
+ else {
+err_out:
+ ntfs_free(trp);
+ }
+ return err;
+}
+
+/**
+ * ntfs_check_logfile - check the journal for consistency
+ * @log_vi: struct inode of loaded journal LogFile to check
+ * @rp: [OUT] on success this is a copy of the current restart page
+ *
+ * Check the LogFile journal for consistency and return 'true' if it is
+ * consistent and 'false' if not. On success, the current restart page is
+ * returned in *@rp. Caller must call ntfs_free(*@rp) when finished with it.
+ *
+ * At present we only check the two restart pages and ignore the log record
+ * pages.
+ *
+ * Note that the MstProtected flag is not set on the LogFile inode and hence
+ * when reading pages they are not deprotected. This is because we do not know
+ * if the LogFile was created on a system with a different page size to ours
+ * yet and mst deprotection would fail if our page size is smaller.
+ */
+bool ntfs_check_logfile(struct inode *log_vi, struct restart_page_header **rp)
+{
+ s64 size, pos;
+ s64 rstr1_lsn, rstr2_lsn;
+ struct ntfs_volume *vol = NTFS_SB(log_vi->i_sb);
+ struct address_space *mapping = log_vi->i_mapping;
+ struct folio *folio = NULL;
+ u8 *kaddr = NULL;
+ struct restart_page_header *rstr1_ph = NULL;
+ struct restart_page_header *rstr2_ph = NULL;
+ int log_page_size, err;
+ bool logfile_is_empty = true;
+ u8 log_page_bits;
+
+ ntfs_debug("Entering.");
+ /* An empty LogFile must have been clean before it got emptied. */
+ if (NVolLogFileEmpty(vol))
+ goto is_empty;
+ size = i_size_read(log_vi);
+ /* Make sure the file doesn't exceed the maximum allowed size. */
+ if (size > MaxLogFileSize)
+ size = MaxLogFileSize;
+ /*
+ * Truncate size to a multiple of the page cache size or the default
+ * log page size if the page cache size is between the default log page
+ * log page size if the page cache size is between the default log page
+ * size and twice that.
+ */
+ if (DefaultLogPageSize <= PAGE_SIZE &&
+ DefaultLogPageSize * 2 <= PAGE_SIZE)
+ log_page_size = DefaultLogPageSize;
+ else
+ log_page_size = PAGE_SIZE;
+ /*
+ * Use ntfs_ffs() instead of ffs() to enable the compiler to
+ * optimize log_page_size and log_page_bits into constants.
+ */
+ log_page_bits = ntfs_ffs(log_page_size) - 1;
+ size &= ~(s64)(log_page_size - 1);
+ /*
+ * Ensure the log file is big enough to store at least the two restart
+ * pages and the minimum number of log record pages.
+ */
+ if (size < log_page_size * 2 || (size - log_page_size * 2) >>
+ log_page_bits < MinLogRecordPages) {
+ ntfs_error(vol->sb, "LogFile is too small.");
+ return false;
+ }
+ /*
+ * Read through the file looking for a restart page. Since the restart
+ * page header is at the beginning of a page we only need to search at
+ * what could be the beginning of a page (for each page size) rather
+ * than scanning the whole file byte by byte. If all potential places
+ * contain empty and uninitialzed records, the log file can be assumed
+ * to be empty.
+ */
+ for (pos = 0; pos < size; pos <<= 1) {
+ pgoff_t idx = pos >> PAGE_SHIFT;
+
+ if (!folio || folio->index != idx) {
+ if (folio)
+ ntfs_unmap_folio(folio, kaddr);
+ folio = ntfs_read_mapping_folio(mapping, idx);
+ if (IS_ERR(folio)) {
+ ntfs_error(vol->sb, "Error mapping LogFile page (index %lu).",
+ idx);
+ goto err_out;
+ }
+ }
+ kaddr = (u8 *)kmap_local_folio(folio, 0) + (pos & ~PAGE_MASK);
+ /*
+ * A non-empty block means the logfile is not empty while an
+ * empty block after a non-empty block has been encountered
+ * means we are done.
+ */
+ if (!ntfs_is_empty_recordp((__le32 *)kaddr))
+ logfile_is_empty = false;
+ else if (!logfile_is_empty)
+ break;
+ /*
+ * A log record page means there cannot be a restart page after
+ * this so no need to continue searching.
+ */
+ if (ntfs_is_rcrd_recordp((__le32 *)kaddr))
+ break;
+ /* If not a (modified by chkdsk) restart page, continue. */
+ if (!ntfs_is_rstr_recordp((__le32 *)kaddr) &&
+ !ntfs_is_chkd_recordp((__le32 *)kaddr)) {
+ if (!pos)
+ pos = NTFS_BLOCK_SIZE >> 1;
+ continue;
+ }
+ /*
+ * Check the (modified by chkdsk) restart page for consistency
+ * and get a copy of the complete multi sector transfer
+ * deprotected restart page.
+ */
+ err = ntfs_check_and_load_restart_page(log_vi,
+ (struct restart_page_header *)kaddr, pos,
+ !rstr1_ph ? &rstr1_ph : &rstr2_ph,
+ !rstr1_ph ? &rstr1_lsn : &rstr2_lsn);
+ if (!err) {
+ /*
+ * If we have now found the first (modified by chkdsk)
+ * restart page, continue looking for the second one.
+ */
+ if (!pos) {
+ pos = NTFS_BLOCK_SIZE >> 1;
+ continue;
+ }
+ /*
+ * We have now found the second (modified by chkdsk)
+ * restart page, so we can stop looking.
+ */
+ break;
+ }
+ /*
+ * Error output already done inside the function. Note, we do
+ * not abort if the restart page was invalid as we might still
+ * find a valid one further in the file.
+ */
+ if (err != -EINVAL) {
+ ntfs_unmap_folio(folio, kaddr);
+ goto err_out;
+ }
+ /* Continue looking. */
+ if (!pos)
+ pos = NTFS_BLOCK_SIZE >> 1;
+ }
+ if (folio)
+ ntfs_unmap_folio(folio, kaddr);
+ if (logfile_is_empty) {
+ NVolSetLogFileEmpty(vol);
+is_empty:
+ ntfs_debug("Done. (LogFile is empty.)");
+ return true;
+ }
+ if (!rstr1_ph) {
+ BUG_ON(rstr2_ph);
+ ntfs_error(vol->sb,
+ "Did not find any restart pages in LogFile and it was not empty.");
+ return false;
+ }
+ /* If both restart pages were found, use the more recent one. */
+ if (rstr2_ph) {
+ /*
+ * If the second restart area is more recent, switch to it.
+ * Otherwise just throw it away.
+ */
+ if (rstr2_lsn > rstr1_lsn) {
+ ntfs_debug("Using second restart page as it is more recent.");
+ ntfs_free(rstr1_ph);
+ rstr1_ph = rstr2_ph;
+ /* rstr1_lsn = rstr2_lsn; */
+ } else {
+ ntfs_debug("Using first restart page as it is more recent.");
+ ntfs_free(rstr2_ph);
+ }
+ rstr2_ph = NULL;
+ }
+ /* All consistency checks passed. */
+ if (rp)
+ *rp = rstr1_ph;
+ else
+ ntfs_free(rstr1_ph);
+ ntfs_debug("Done.");
+ return true;
+err_out:
+ if (rstr1_ph)
+ ntfs_free(rstr1_ph);
+ return false;
+}
+
+/**
+ * ntfs_empty_logfile - empty the contents of the LogFile journal
+ * @log_vi: struct inode of loaded journal LogFile to empty
+ *
+ * Empty the contents of the LogFile journal @log_vi and return 'true' on
+ * success and 'false' on error.
+ *
+ * This function assumes that the LogFile journal has already been consistency
+ * checked by a call to ntfs_check_logfile() and that ntfs_is_logfile_clean()
+ * has been used to ensure that the LogFile is clean.
+ */
+bool ntfs_empty_logfile(struct inode *log_vi)
+{
+ s64 vcn, end_vcn;
+ struct ntfs_inode *log_ni = NTFS_I(log_vi);
+ struct ntfs_volume *vol = log_ni->vol;
+ struct super_block *sb = vol->sb;
+ struct runlist_element *rl;
+ unsigned long flags;
+ int err;
+ bool should_wait = true;
+ char *empty_buf = NULL;
+ struct file_ra_state *ra = NULL;
+
+ ntfs_debug("Entering.");
+ if (NVolLogFileEmpty(vol)) {
+ ntfs_debug("Done.");
+ return true;
+ }
+
+ /*
+ * We cannot use ntfs_attr_set() because we may be still in the middle
+ * of a mount operation. Thus we do the emptying by hand by first
+ * zapping the page cache pages for the LogFile/DATA attribute and
+ * then emptying each of the buffers in each of the clusters specified
+ * by the runlist by hand.
+ */
+ vcn = 0;
+ read_lock_irqsave(&log_ni->size_lock, flags);
+ end_vcn = (log_ni->initialized_size + vol->cluster_size_mask) >>
+ vol->cluster_size_bits;
+ read_unlock_irqrestore(&log_ni->size_lock, flags);
+ truncate_inode_pages(log_vi->i_mapping, 0);
+ down_write(&log_ni->runlist.lock);
+ rl = log_ni->runlist.rl;
+ if (unlikely(!rl || vcn < rl->vcn || !rl->length)) {
+map_vcn:
+ err = ntfs_map_runlist_nolock(log_ni, vcn, NULL);
+ if (err) {
+ ntfs_error(sb, "Failed to map runlist fragment (error %d).", -err);
+ goto err;
+ }
+ rl = log_ni->runlist.rl;
+ BUG_ON(!rl || vcn < rl->vcn || !rl->length);
+ }
+ /* Seek to the runlist element containing @vcn. */
+ while (rl->length && vcn >= rl[1].vcn)
+ rl++;
+
+ err = -ENOMEM;
+ empty_buf = ntfs_malloc_nofs(vol->cluster_size);
+ if (!empty_buf)
+ goto err;
+
+ memset(empty_buf, 0xff, vol->cluster_size);
+
+ ra = kzalloc(sizeof(*ra), GFP_NOFS);
+ if (!ra)
+ goto err;
+
+ file_ra_state_init(ra, sb->s_bdev->bd_mapping);
+ do {
+ s64 lcn;
+ loff_t start, end;
+ s64 len;
+
+ /*
+ * If this run is not mapped map it now and start again as the
+ * runlist will have been updated.
+ */
+ lcn = rl->lcn;
+ if (unlikely(lcn == LCN_RL_NOT_MAPPED)) {
+ vcn = rl->vcn;
+ ntfs_free(empty_buf);
+ goto map_vcn;
+ }
+ /* If this run is not valid abort with an error. */
+ if (unlikely(!rl->length || lcn < LCN_HOLE))
+ goto rl_err;
+ /* Skip holes. */
+ if (lcn == LCN_HOLE)
+ continue;
+ start = lcn << vol->cluster_size_bits;
+ len = rl->length;
+ if (rl[1].vcn > end_vcn)
+ len = end_vcn - rl->vcn;
+ end = (lcn + len) << vol->cluster_size_bits;
+
+ page_cache_sync_readahead(sb->s_bdev->bd_mapping, ra, NULL,
+ start >> PAGE_SHIFT, (end - start) >> PAGE_SHIFT);
+
+ do {
+ err = ntfs_dev_write(sb, empty_buf, start,
+ vol->cluster_size, should_wait);
+ if (err) {
+ ntfs_error(sb, "ntfs_dev_write failed, err : %d\n", err);
+ goto io_err;
+ }
+
+ /*
+ * Submit the buffer and wait for i/o to complete but
+ * only for the first buffer so we do not miss really
+ * serious i/o errors. Once the first buffer has
+ * completed ignore errors afterwards as we can assume
+ * that if one buffer worked all of them will work.
+ */
+ if (should_wait)
+ should_wait = false;
+ start += vol->cluster_size;
+ } while (start < end);
+ } while ((++rl)->vcn < end_vcn);
+ up_write(&log_ni->runlist.lock);
+ kfree(empty_buf);
+ kfree(ra);
+ truncate_inode_pages(log_vi->i_mapping, 0);
+ /* Set the flag so we do not have to do it again on remount. */
+ NVolSetLogFileEmpty(vol);
+ ntfs_debug("Done.");
+ return true;
+io_err:
+ ntfs_error(sb, "Failed to write buffer. Unmount and run chkdsk.");
+ goto dirty_err;
+rl_err:
+ ntfs_error(sb, "Runlist is corrupt. Unmount and run chkdsk.");
+dirty_err:
+ NVolSetErrors(vol);
+ err = -EIO;
+err:
+ ntfs_free(empty_buf);
+ kfree(ra);
+ up_write(&log_ni->runlist.lock);
+ ntfs_error(sb, "Failed to fill LogFile with 0xff bytes (error %d).",
+ -err);
+ return false;
+}
diff --git a/fs/ntfsplus/misc.c b/fs/ntfsplus/misc.c
new file mode 100644
index 000000000000..fcb66c106c78
--- /dev/null
+++ b/fs/ntfsplus/misc.c
@@ -0,0 +1,221 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * NTFS kernel debug support. Part of the Linux-NTFS project.
+ *
+ * Copyright (C) 1997 Martin von Löwis, Régis Duchesne
+ * Copyright (c) 2001-2005 Anton Altaparmakov
+ */
+
+#include <linux/module.h>
+#ifdef CONFIG_SYSCTL
+#include <linux/proc_fs.h>
+#include <linux/sysctl.h>
+#endif
+
+#include "misc.h"
+
+#ifdef pr_fmt
+#undef pr_fmt
+#endif
+
+#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
+
+/**
+ * __ntfs_warning - output a warning to the syslog
+ * @function: name of function outputting the warning
+ * @sb: super block of mounted ntfs filesystem
+ * @fmt: warning string containing format specifications
+ * @...: a variable number of arguments specified in @fmt
+ *
+ * Outputs a warning to the syslog for the mounted ntfs filesystem described
+ * by @sb.
+ *
+ * @fmt and the corresponding @... is printf style format string containing
+ * the warning string and the corresponding format arguments, respectively.
+ *
+ * @function is the name of the function from which __ntfs_warning is being
+ * called.
+ *
+ * Note, you should be using debug.h::ntfs_warning(@sb, @fmt, @...) instead
+ * as this provides the @function parameter automatically.
+ */
+void __ntfs_warning(const char *function, const struct super_block *sb,
+ const char *fmt, ...)
+{
+ struct va_format vaf;
+ va_list args;
+ int flen = 0;
+
+ if (function)
+ flen = strlen(function);
+ va_start(args, fmt);
+ vaf.fmt = fmt;
+ vaf.va = &args;
+#ifndef DEBUG
+ if (sb)
+ pr_warn_ratelimited("(device %s): %s(): %pV\n",
+ sb->s_id, flen ? function : "", &vaf);
+ else
+ pr_warn_ratelimited("%s(): %pV\n", flen ? function : "", &vaf);
+#else
+ if (sb)
+ pr_warn("(device %s): %s(): %pV\n",
+ sb->s_id, flen ? function : "", &vaf);
+ else
+ pr_warn("%s(): %pV\n", flen ? function : "", &vaf);
+#endif
+ va_end(args);
+}
+
+/**
+ * __ntfs_error - output an error to the syslog
+ * @function: name of function outputting the error
+ * @sb: super block of mounted ntfs filesystem
+ * @fmt: error string containing format specifications
+ * @...: a variable number of arguments specified in @fmt
+ *
+ * Outputs an error to the syslog for the mounted ntfs filesystem described
+ * by @sb.
+ *
+ * @fmt and the corresponding @... is printf style format string containing
+ * the error string and the corresponding format arguments, respectively.
+ *
+ * @function is the name of the function from which __ntfs_error is being
+ * called.
+ *
+ * Note, you should be using debug.h::ntfs_error(@sb, @fmt, @...) instead
+ * as this provides the @function parameter automatically.
+ */
+void __ntfs_error(const char *function, struct super_block *sb,
+ const char *fmt, ...)
+{
+ struct va_format vaf;
+ va_list args;
+ int flen = 0;
+
+ if (function)
+ flen = strlen(function);
+ va_start(args, fmt);
+ vaf.fmt = fmt;
+ vaf.va = &args;
+#ifndef DEBUG
+ if (sb)
+ pr_err_ratelimited("(device %s): %s(): %pV\n",
+ sb->s_id, flen ? function : "", &vaf);
+ else
+ pr_err_ratelimited("%s(): %pV\n", flen ? function : "", &vaf);
+#else
+ if (sb)
+ pr_err("(device %s): %s(): %pV\n",
+ sb->s_id, flen ? function : "", &vaf);
+ else
+ pr_err("%s(): %pV\n", flen ? function : "", &vaf);
+#endif
+ va_end(args);
+
+ if (sb)
+ ntfs_handle_error(sb);
+}
+
+#ifdef DEBUG
+
+/* If 1, output debug messages, and if 0, don't. */
+int debug_msgs;
+
+void __ntfs_debug(const char *file, int line, const char *function,
+ const char *fmt, ...)
+{
+ struct va_format vaf;
+ va_list args;
+ int flen = 0;
+
+ if (!debug_msgs)
+ return;
+ if (function)
+ flen = strlen(function);
+ va_start(args, fmt);
+ vaf.fmt = fmt;
+ vaf.va = &args;
+ pr_debug("(%s, %d): %s(): %pV", file, line, flen ? function : "", &vaf);
+ va_end(args);
+}
+
+/* Dump a runlist. Caller has to provide synchronisation for @rl. */
+void ntfs_debug_dump_runlist(const struct runlist_element *rl)
+{
+ int i;
+ const char *lcn_str[5] = { "LCN_DELALLOC ", "LCN_HOLE ",
+ "LCN_RL_NOT_MAPPED", "LCN_ENOENT ",
+ "LCN_unknown " };
+
+ if (!debug_msgs)
+ return;
+ pr_debug("Dumping runlist (values in hex):\n");
+ if (!rl) {
+ pr_debug("Run list not present.\n");
+ return;
+ }
+ pr_debug("VCN LCN Run length\n");
+ for (i = 0; ; i++) {
+ s64 lcn = (rl + i)->lcn;
+
+ if (lcn < (s64)0) {
+ int index = -lcn - 1;
+
+ if (index > -LCN_ENOENT - 1)
+ index = 3;
+ pr_debug("%-16Lx %s %-16Lx%s\n",
+ (long long)(rl + i)->vcn, lcn_str[index],
+ (long long)(rl + i)->length,
+ (rl + i)->length ? "" :
+ " (runlist end)");
+ } else
+ pr_debug("%-16Lx %-16Lx %-16Lx%s\n",
+ (long long)(rl + i)->vcn,
+ (long long)(rl + i)->lcn,
+ (long long)(rl + i)->length,
+ (rl + i)->length ? "" :
+ " (runlist end)");
+ if (!(rl + i)->length)
+ break;
+ }
+}
+
+#ifdef CONFIG_SYSCTL
+/* Definition of the ntfs sysctl. */
+static const struct ctl_table ntfs_sysctls[] = {
+ {
+ .procname = "ntfs-debug",
+ .data = &debug_msgs, /* Data pointer and size. */
+ .maxlen = sizeof(debug_msgs),
+ .mode = 0644, /* Mode, proc handler. */
+ .proc_handler = proc_dointvec
+ },
+ {}
+};
+
+/* Storage for the sysctls header. */
+static struct ctl_table_header *sysctls_root_table;
+
+/**
+ * ntfs_sysctl - add or remove the debug sysctl
+ * @add: add (1) or remove (0) the sysctl
+ *
+ * Add or remove the debug sysctl. Return 0 on success or -errno on error.
+ */
+int ntfs_sysctl(int add)
+{
+ if (add) {
+ BUG_ON(sysctls_root_table);
+ sysctls_root_table = register_sysctl("fs", ntfs_sysctls);
+ if (!sysctls_root_table)
+ return -ENOMEM;
+ } else {
+ BUG_ON(!sysctls_root_table);
+ unregister_sysctl_table(sysctls_root_table);
+ sysctls_root_table = NULL;
+ }
+ return 0;
+}
+#endif /* CONFIG_SYSCTL */
+#endif
diff --git a/fs/ntfsplus/unistr.c b/fs/ntfsplus/unistr.c
new file mode 100644
index 000000000000..fb52769d12cd
--- /dev/null
+++ b/fs/ntfsplus/unistr.c
@@ -0,0 +1,471 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * NTFS Unicode string handling. Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2001-2006 Anton Altaparmakov
+ */
+
+#include "ntfs.h"
+#include "misc.h"
+
+/*
+ * IMPORTANT
+ * =========
+ *
+ * All these routines assume that the Unicode characters are in little endian
+ * encoding inside the strings!!!
+ */
+
+/*
+ * This is used by the name collation functions to quickly determine what
+ * characters are (in)valid.
+ */
+static const u8 legal_ansi_char_array[0x40] = {
+ 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
+ 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
+
+ 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
+ 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
+
+ 0x17, 0x07, 0x18, 0x17, 0x17, 0x17, 0x17, 0x17,
+ 0x17, 0x17, 0x18, 0x16, 0x16, 0x17, 0x07, 0x00,
+
+ 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17, 0x17,
+ 0x17, 0x17, 0x04, 0x16, 0x18, 0x16, 0x18, 0x18,
+};
+
+/**
+ * ntfs_are_names_equal - compare two Unicode names for equality
+ * @s1: name to compare to @s2
+ * @s1_len: length in Unicode characters of @s1
+ * @s2: name to compare to @s1
+ * @s2_len: length in Unicode characters of @s2
+ * @ic: ignore case bool
+ * @upcase: upcase table (only if @ic == IGNORE_CASE)
+ * @upcase_size: length in Unicode characters of @upcase (if present)
+ *
+ * Compare the names @s1 and @s2 and return 'true' (1) if the names are
+ * identical, or 'false' (0) if they are not identical. If @ic is IGNORE_CASE,
+ * the @upcase table is used to performa a case insensitive comparison.
+ */
+bool ntfs_are_names_equal(const __le16 *s1, size_t s1_len,
+ const __le16 *s2, size_t s2_len, const u32 ic,
+ const __le16 *upcase, const u32 upcase_size)
+{
+ if (s1_len != s2_len)
+ return false;
+ if (ic == CASE_SENSITIVE)
+ return !ntfs_ucsncmp(s1, s2, s1_len);
+ return !ntfs_ucsncasecmp(s1, s2, s1_len, upcase, upcase_size);
+}
+
+/**
+ * ntfs_collate_names - collate two Unicode names
+ * @name1: first Unicode name to compare
+ * @name2: second Unicode name to compare
+ * @err_val: if @name1 contains an invalid character return this value
+ * @ic: either CASE_SENSITIVE or IGNORE_CASE
+ * @upcase: upcase table (ignored if @ic is CASE_SENSITIVE)
+ * @upcase_len: upcase table size (ignored if @ic is CASE_SENSITIVE)
+ *
+ * ntfs_collate_names collates two Unicode names and returns:
+ *
+ * -1 if the first name collates before the second one,
+ * 0 if the names match,
+ * 1 if the second name collates before the first one, or
+ * @err_val if an invalid character is found in @name1 during the comparison.
+ *
+ * The following characters are considered invalid: '"', '*', '<', '>' and '?'.
+ */
+int ntfs_collate_names(const __le16 *name1, const u32 name1_len,
+ const __le16 *name2, const u32 name2_len,
+ const int err_val, const u32 ic,
+ const __le16 *upcase, const u32 upcase_len)
+{
+ u32 cnt, min_len;
+ u16 c1, c2;
+
+ min_len = name1_len;
+ if (name1_len > name2_len)
+ min_len = name2_len;
+ for (cnt = 0; cnt < min_len; ++cnt) {
+ c1 = le16_to_cpu(*name1++);
+ c2 = le16_to_cpu(*name2++);
+ if (ic) {
+ if (c1 < upcase_len)
+ c1 = le16_to_cpu(upcase[c1]);
+ if (c2 < upcase_len)
+ c2 = le16_to_cpu(upcase[c2]);
+ }
+ if (c1 < 64 && legal_ansi_char_array[c1] & 8)
+ return err_val;
+ if (c1 < c2)
+ return -1;
+ if (c1 > c2)
+ return 1;
+ }
+ if (name1_len < name2_len)
+ return -1;
+ if (name1_len == name2_len)
+ return 0;
+ /* name1_len > name2_len */
+ c1 = le16_to_cpu(*name1);
+ if (c1 < 64 && legal_ansi_char_array[c1] & 8)
+ return err_val;
+ return 1;
+}
+
+/**
+ * ntfs_ucsncmp - compare two little endian Unicode strings
+ * @s1: first string
+ * @s2: second string
+ * @n: maximum unicode characters to compare
+ *
+ * Compare the first @n characters of the Unicode strings @s1 and @s2,
+ * The strings in little endian format and appropriate le16_to_cpu()
+ * conversion is performed on non-little endian machines.
+ *
+ * The function returns an integer less than, equal to, or greater than zero
+ * if @s1 (or the first @n Unicode characters thereof) is found, respectively,
+ * to be less than, to match, or be greater than @s2.
+ */
+int ntfs_ucsncmp(const __le16 *s1, const __le16 *s2, size_t n)
+{
+ u16 c1, c2;
+ size_t i;
+
+ for (i = 0; i < n; ++i) {
+ c1 = le16_to_cpu(s1[i]);
+ c2 = le16_to_cpu(s2[i]);
+ if (c1 < c2)
+ return -1;
+ if (c1 > c2)
+ return 1;
+ if (!c1)
+ break;
+ }
+ return 0;
+}
+
+/**
+ * ntfs_ucsncasecmp - compare two little endian Unicode strings, ignoring case
+ * @s1: first string
+ * @s2: second string
+ * @n: maximum unicode characters to compare
+ * @upcase: upcase table
+ * @upcase_size: upcase table size in Unicode characters
+ *
+ * Compare the first @n characters of the Unicode strings @s1 and @s2,
+ * ignoring case. The strings in little endian format and appropriate
+ * le16_to_cpu() conversion is performed on non-little endian machines.
+ *
+ * Each character is uppercased using the @upcase table before the comparison.
+ *
+ * The function returns an integer less than, equal to, or greater than zero
+ * if @s1 (or the first @n Unicode characters thereof) is found, respectively,
+ * to be less than, to match, or be greater than @s2.
+ */
+int ntfs_ucsncasecmp(const __le16 *s1, const __le16 *s2, size_t n,
+ const __le16 *upcase, const u32 upcase_size)
+{
+ size_t i;
+ u16 c1, c2;
+
+ for (i = 0; i < n; ++i) {
+ c1 = le16_to_cpu(s1[i]);
+ if (c1 < upcase_size)
+ c1 = le16_to_cpu(upcase[c1]);
+ c2 = le16_to_cpu(s2[i]);
+ if (c2 < upcase_size)
+ c2 = le16_to_cpu(upcase[c2]);
+ if (c1 < c2)
+ return -1;
+ if (c1 > c2)
+ return 1;
+ if (!c1)
+ break;
+ }
+ return 0;
+}
+
+int ntfs_file_compare_values(const struct file_name_attr *file_name_attr1,
+ const struct file_name_attr *file_name_attr2,
+ const int err_val, const u32 ic,
+ const __le16 *upcase, const u32 upcase_len)
+{
+ return ntfs_collate_names((__le16 *)&file_name_attr1->file_name,
+ file_name_attr1->file_name_length,
+ (__le16 *)&file_name_attr2->file_name,
+ file_name_attr2->file_name_length,
+ err_val, ic, upcase, upcase_len);
+}
+
+/**
+ * ntfs_nlstoucs - convert NLS string to little endian Unicode string
+ *
+ * Convert the input string @ins, which is in whatever format the loaded NLS
+ * map dictates, into a little endian, 2-byte Unicode string.
+ *
+ * This function allocates the string and the caller is responsible for
+ * calling kmem_cache_free(ntfs_name_cache, *@outs); when finished with it.
+ *
+ * On success the function returns the number of Unicode characters written to
+ * the output string *@outs (>= 0), not counting the terminating Unicode NULL
+ * character. *@outs is set to the allocated output string buffer.
+ *
+ * On error, a negative number corresponding to the error code is returned. In
+ * that case the output string is not allocated. Both *@outs and *@outs_len
+ * are then undefined.
+ *
+ * This might look a bit odd due to fast path optimization...
+ */
+int ntfs_nlstoucs(const struct ntfs_volume *vol, const char *ins,
+ const int ins_len, __le16 **outs, int max_name_len)
+{
+ struct nls_table *nls = vol->nls_map;
+ __le16 *ucs;
+ wchar_t wc;
+ int i, o, wc_len;
+
+ /* We do not trust outside sources. */
+ if (likely(ins)) {
+ if (max_name_len > NTFS_MAX_NAME_LEN)
+ ucs = kvmalloc((max_name_len + 2) * sizeof(__le16),
+ GFP_NOFS | __GFP_ZERO);
+ else
+ ucs = kmem_cache_alloc(ntfs_name_cache, GFP_NOFS);
+ if (likely(ucs)) {
+ if (vol->nls_utf8) {
+ o = utf8s_to_utf16s(ins, ins_len,
+ UTF16_LITTLE_ENDIAN,
+ ucs,
+ max_name_len + 2);
+ if (o < 0 || o > max_name_len) {
+ wc_len = o;
+ goto name_err;
+ }
+ } else {
+ for (i = o = 0; i < ins_len; i += wc_len) {
+ wc_len = nls->char2uni(ins + i, ins_len - i,
+ &wc);
+ if (likely(wc_len >= 0 &&
+ o < max_name_len)) {
+ if (likely(wc)) {
+ ucs[o++] = cpu_to_le16(wc);
+ continue;
+ } /* else if (!wc) */
+ break;
+ }
+
+ goto name_err;
+ }
+ }
+ ucs[o] = 0;
+ *outs = ucs;
+ return o;
+ } /* else if (!ucs) */
+ ntfs_debug("Failed to allocate buffer for converted name from ntfs_name_cache.");
+ return -ENOMEM;
+ } /* else if (!ins) */
+ ntfs_error(vol->sb, "Received NULL pointer.");
+ return -EINVAL;
+name_err:
+ if (max_name_len > NTFS_MAX_NAME_LEN)
+ kvfree(ucs);
+ else
+ kmem_cache_free(ntfs_name_cache, ucs);
+ if (wc_len < 0) {
+ ntfs_debug("Name using character set %s contains characters that cannot be converted to Unicode.",
+ nls->charset);
+ i = -EILSEQ;
+ } else {
+ ntfs_debug("Name is too long (maximum length for a name on NTFS is %d Unicode characters.",
+ max_name_len);
+ i = -ENAMETOOLONG;
+ }
+ return i;
+}
+
+/**
+ * ntfs_ucstonls - convert little endian Unicode string to NLS string
+ * @vol: ntfs volume which we are working with
+ * @ins: input Unicode string buffer
+ * @ins_len: length of input string in Unicode characters
+ * @outs: on return contains the (allocated) output NLS string buffer
+ * @outs_len: length of output string buffer in bytes
+ *
+ * Convert the input little endian, 2-byte Unicode string @ins, of length
+ * @ins_len into the string format dictated by the loaded NLS.
+ *
+ * If *@outs is NULL, this function allocates the string and the caller is
+ * responsible for calling kfree(*@outs); when finished with it. In this case
+ * @outs_len is ignored and can be 0.
+ *
+ * On success the function returns the number of bytes written to the output
+ * string *@outs (>= 0), not counting the terminating NULL byte. If the output
+ * string buffer was allocated, *@outs is set to it.
+ *
+ * On error, a negative number corresponding to the error code is returned. In
+ * that case the output string is not allocated. The contents of *@outs are
+ * then undefined.
+ *
+ * This might look a bit odd due to fast path optimization...
+ */
+int ntfs_ucstonls(const struct ntfs_volume *vol, const __le16 *ins,
+ const int ins_len, unsigned char **outs, int outs_len)
+{
+ struct nls_table *nls = vol->nls_map;
+ unsigned char *ns;
+ int i, o, ns_len, wc;
+
+ /* We don't trust outside sources. */
+ if (ins) {
+ ns = *outs;
+ ns_len = outs_len;
+ if (ns && !ns_len) {
+ wc = -ENAMETOOLONG;
+ goto conversion_err;
+ }
+ if (!ns) {
+ ns_len = ins_len * NLS_MAX_CHARSET_SIZE;
+ ns = kmalloc(ns_len + 1, GFP_NOFS);
+ if (!ns)
+ goto mem_err_out;
+ }
+
+ if (vol->nls_utf8) {
+ o = utf16s_to_utf8s((const wchar_t *)ins, ins_len,
+ UTF16_LITTLE_ENDIAN, ns, ns_len);
+ if (o >= ns_len) {
+ wc = -ENAMETOOLONG;
+ goto conversion_err;
+ }
+ goto done;
+ }
+
+ for (i = o = 0; i < ins_len; i++) {
+retry:
+ wc = nls->uni2char(le16_to_cpu(ins[i]), ns + o,
+ ns_len - o);
+ if (wc > 0) {
+ o += wc;
+ continue;
+ } else if (!wc)
+ break;
+ else if (wc == -ENAMETOOLONG && ns != *outs) {
+ unsigned char *tc;
+ /* Grow in multiples of 64 bytes. */
+ tc = kmalloc((ns_len + 64) &
+ ~63, GFP_NOFS);
+ if (tc) {
+ memcpy(tc, ns, ns_len);
+ ns_len = ((ns_len + 64) & ~63) - 1;
+ kfree(ns);
+ ns = tc;
+ goto retry;
+ } /* No memory so goto conversion_error; */
+ } /* wc < 0, real error. */
+ goto conversion_err;
+ }
+done:
+ ns[o] = 0;
+ *outs = ns;
+ return o;
+ } /* else (!ins) */
+ ntfs_error(vol->sb, "Received NULL pointer.");
+ return -EINVAL;
+conversion_err:
+ ntfs_error(vol->sb,
+ "Unicode name contains characters that cannot be converted to character set %s. You might want to try to use the mount option nls=utf8.",
+ nls->charset);
+ if (ns != *outs)
+ kfree(ns);
+ if (wc != -ENAMETOOLONG)
+ wc = -EILSEQ;
+ return wc;
+mem_err_out:
+ ntfs_error(vol->sb, "Failed to allocate name!");
+ return -ENOMEM;
+}
+
+/**
+ * ntfs_ucsnlen - determine the length of a little endian Unicode string
+ * @s: pointer to Unicode string
+ * @maxlen: maximum length of string @s
+ *
+ * Return the number of Unicode characters in the little endian Unicode
+ * string @s up to a maximum of maxlen Unicode characters, not including
+ * the terminating (__le16)'\0'. If there is no (__le16)'\0' between @s
+ * and @s + @maxlen, @maxlen is returned.
+ *
+ * This function never looks beyond @s + @maxlen.
+ */
+static u32 ntfs_ucsnlen(const __le16 *s, u32 maxlen)
+{
+ u32 i;
+
+ for (i = 0; i < maxlen; i++) {
+ if (!le16_to_cpu(s[i]))
+ break;
+ }
+ return i;
+}
+
+/**
+ * ntfs_ucsndup - duplicate little endian Unicode string
+ * @s: pointer to Unicode string
+ * @maxlen: maximum length of string @s
+ *
+ * Return a pointer to a new little endian Unicode string which is a duplicate
+ * of the string s. Memory for the new string is obtained with ntfs_malloc(3),
+ * and can be freed with free(3).
+ *
+ * A maximum of @maxlen Unicode characters are copied and a terminating
+ * (__le16)'\0' little endian Unicode character is added.
+ *
+ * This function never looks beyond @s + @maxlen.
+ *
+ * Return a pointer to the new little endian Unicode string on success and NULL
+ * on failure with errno set to the error code.
+ */
+__le16 *ntfs_ucsndup(const __le16 *s, u32 maxlen)
+{
+ __le16 *dst;
+ u32 len;
+
+ len = ntfs_ucsnlen(s, maxlen);
+ dst = ntfs_malloc_nofs((len + 1) * sizeof(__le16));
+ if (dst) {
+ memcpy(dst, s, len * sizeof(__le16));
+ dst[len] = cpu_to_le16(L'\0');
+ }
+ return dst;
+}
+
+/**
+ * ntfs_names_are_equal - compare two Unicode names for equality
+ * @s1: name to compare to @s2
+ * @s1_len: length in Unicode characters of @s1
+ * @s2: name to compare to @s1
+ * @s2_len: length in Unicode characters of @s2
+ * @ic: ignore case bool
+ * @upcase: upcase table (only if @ic == IGNORE_CASE)
+ * @upcase_size: length in Unicode characters of @upcase (if present)
+ *
+ * Compare the names @s1 and @s2 and return TRUE (1) if the names are
+ * identical, or FALSE (0) if they are not identical. If @ic is IGNORE_CASE,
+ * the @upcase table is used to perform a case insensitive comparison.
+ */
+bool ntfs_names_are_equal(const __le16 *s1, size_t s1_len,
+ const __le16 *s2, size_t s2_len,
+ const u32 ic,
+ const __le16 *upcase, const u32 upcase_size)
+{
+ if (s1_len != s2_len)
+ return false;
+ if (!s1_len)
+ return true;
+ if (ic == CASE_SENSITIVE)
+ return ntfs_ucsncmp(s1, s2, s1_len) ? false : true;
+ return ntfs_ucsncasecmp(s1, s2, s1_len, upcase, upcase_size) ? false : true;
+}
diff --git a/fs/ntfsplus/upcase.c b/fs/ntfsplus/upcase.c
new file mode 100644
index 000000000000..a2b8e56edeff
--- /dev/null
+++ b/fs/ntfsplus/upcase.c
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: GPL-2.0-or-later
+/*
+ * Generate the full NTFS Unicode upcase table in little endian.
+ * Part of the Linux-NTFS project.
+ *
+ * Copyright (c) 2001 Richard Russon <ntfs@flatcap.org>
+ * Copyright (c) 2001-2006 Anton Altaparmakov
+ */
+
+#include "misc.h"
+#include "ntfs.h"
+
+__le16 *generate_default_upcase(void)
+{
+ static const int uc_run_table[][3] = { /* Start, End, Add */
+ {0x0061, 0x007B, -32}, {0x0451, 0x045D, -80}, {0x1F70, 0x1F72, 74},
+ {0x00E0, 0x00F7, -32}, {0x045E, 0x0460, -80}, {0x1F72, 0x1F76, 86},
+ {0x00F8, 0x00FF, -32}, {0x0561, 0x0587, -48}, {0x1F76, 0x1F78, 100},
+ {0x0256, 0x0258, -205}, {0x1F00, 0x1F08, 8}, {0x1F78, 0x1F7A, 128},
+ {0x028A, 0x028C, -217}, {0x1F10, 0x1F16, 8}, {0x1F7A, 0x1F7C, 112},
+ {0x03AC, 0x03AD, -38}, {0x1F20, 0x1F28, 8}, {0x1F7C, 0x1F7E, 126},
+ {0x03AD, 0x03B0, -37}, {0x1F30, 0x1F38, 8}, {0x1FB0, 0x1FB2, 8},
+ {0x03B1, 0x03C2, -32}, {0x1F40, 0x1F46, 8}, {0x1FD0, 0x1FD2, 8},
+ {0x03C2, 0x03C3, -31}, {0x1F51, 0x1F52, 8}, {0x1FE0, 0x1FE2, 8},
+ {0x03C3, 0x03CC, -32}, {0x1F53, 0x1F54, 8}, {0x1FE5, 0x1FE6, 7},
+ {0x03CC, 0x03CD, -64}, {0x1F55, 0x1F56, 8}, {0x2170, 0x2180, -16},
+ {0x03CD, 0x03CF, -63}, {0x1F57, 0x1F58, 8}, {0x24D0, 0x24EA, -26},
+ {0x0430, 0x0450, -32}, {0x1F60, 0x1F68, 8}, {0xFF41, 0xFF5B, -32},
+ {0}
+ };
+
+ static const int uc_dup_table[][2] = { /* Start, End */
+ {0x0100, 0x012F}, {0x01A0, 0x01A6}, {0x03E2, 0x03EF}, {0x04CB, 0x04CC},
+ {0x0132, 0x0137}, {0x01B3, 0x01B7}, {0x0460, 0x0481}, {0x04D0, 0x04EB},
+ {0x0139, 0x0149}, {0x01CD, 0x01DD}, {0x0490, 0x04BF}, {0x04EE, 0x04F5},
+ {0x014A, 0x0178}, {0x01DE, 0x01EF}, {0x04BF, 0x04BF}, {0x04F8, 0x04F9},
+ {0x0179, 0x017E}, {0x01F4, 0x01F5}, {0x04C1, 0x04C4}, {0x1E00, 0x1E95},
+ {0x018B, 0x018B}, {0x01FA, 0x0218}, {0x04C7, 0x04C8}, {0x1EA0, 0x1EF9},
+ {0}
+ };
+
+ static const int uc_word_table[][2] = { /* Offset, Value */
+ {0x00FF, 0x0178}, {0x01AD, 0x01AC}, {0x01F3, 0x01F1}, {0x0269, 0x0196},
+ {0x0183, 0x0182}, {0x01B0, 0x01AF}, {0x0253, 0x0181}, {0x026F, 0x019C},
+ {0x0185, 0x0184}, {0x01B9, 0x01B8}, {0x0254, 0x0186}, {0x0272, 0x019D},
+ {0x0188, 0x0187}, {0x01BD, 0x01BC}, {0x0259, 0x018F}, {0x0275, 0x019F},
+ {0x018C, 0x018B}, {0x01C6, 0x01C4}, {0x025B, 0x0190}, {0x0283, 0x01A9},
+ {0x0192, 0x0191}, {0x01C9, 0x01C7}, {0x0260, 0x0193}, {0x0288, 0x01AE},
+ {0x0199, 0x0198}, {0x01CC, 0x01CA}, {0x0263, 0x0194}, {0x0292, 0x01B7},
+ {0x01A8, 0x01A7}, {0x01DD, 0x018E}, {0x0268, 0x0197},
+ {0}
+ };
+
+ int i, r;
+ __le16 *uc;
+
+ uc = ntfs_malloc_nofs(default_upcase_len * sizeof(__le16));
+ if (!uc)
+ return uc;
+ memset(uc, 0, default_upcase_len * sizeof(__le16));
+ /* Generate the little endian Unicode upcase table used by ntfs. */
+ for (i = 0; i < default_upcase_len; i++)
+ uc[i] = cpu_to_le16(i);
+ for (r = 0; uc_run_table[r][0]; r++)
+ for (i = uc_run_table[r][0]; i < uc_run_table[r][1]; i++)
+ le16_add_cpu(&uc[i], uc_run_table[r][2]);
+ for (r = 0; uc_dup_table[r][0]; r++)
+ for (i = uc_dup_table[r][0]; i < uc_dup_table[r][1]; i += 2)
+ le16_add_cpu(&uc[i + 1], -1);
+ for (r = 0; uc_word_table[r][0]; r++)
+ uc[uc_word_table[r][0]] = cpu_to_le16(uc_word_table[r][1]);
+ return uc;
+}
--
2.34.1
^ permalink raw reply [flat|nested] 6+ messages in thread
* [PATCH 11/11] ntfsplus: add Kconfig and Makefile
2025-10-20 2:12 [PATCH 06/11] ntfsplus: add iomap and address space operations Namjae Jeon
` (3 preceding siblings ...)
2025-10-20 2:12 ` [PATCH 10/11] ntfsplus: add misc operations Namjae Jeon
@ 2025-10-20 2:12 ` Namjae Jeon
4 siblings, 0 replies; 6+ messages in thread
From: Namjae Jeon @ 2025-10-20 2:12 UTC (permalink / raw)
To: viro, brauner, hch, hch, tytso, willy, jack, djwong, josef,
sandeen, rgoldwyn, xiang, dsterba, pali, ebiggers, neil,
amir73il
Cc: linux-fsdevel, linux-kernel, iamjoonsoo.kim, cheol.lee, jay.sim,
gunho.lee, Namjae Jeon
This adds the Kconfig and Makefile for ntfsplus.
Signed-off-by: Namjae Jeon <linkinjeon@kernel.org>
---
fs/Kconfig | 1 +
fs/Makefile | 1 +
fs/ntfsplus/Kconfig | 45 ++++++++++++++++++++++++++++++++++++++++++++
fs/ntfsplus/Makefile | 18 ++++++++++++++++++
4 files changed, 65 insertions(+)
create mode 100644 fs/ntfsplus/Kconfig
create mode 100644 fs/ntfsplus/Makefile
diff --git a/fs/Kconfig b/fs/Kconfig
index 0bfdaecaa877..70d596b99c8b 100644
--- a/fs/Kconfig
+++ b/fs/Kconfig
@@ -153,6 +153,7 @@ menu "DOS/FAT/EXFAT/NT Filesystems"
source "fs/fat/Kconfig"
source "fs/exfat/Kconfig"
source "fs/ntfs3/Kconfig"
+source "fs/ntfsplus/Kconfig"
endmenu
endif # BLOCK
diff --git a/fs/Makefile b/fs/Makefile
index e3523ab2e587..2e2473451508 100644
--- a/fs/Makefile
+++ b/fs/Makefile
@@ -91,6 +91,7 @@ obj-y += unicode/
obj-$(CONFIG_SMBFS) += smb/
obj-$(CONFIG_HPFS_FS) += hpfs/
obj-$(CONFIG_NTFS3_FS) += ntfs3/
+obj-$(CONFIG_NTFSPLUS_FS) += ntfsplus/
obj-$(CONFIG_UFS_FS) += ufs/
obj-$(CONFIG_EFS_FS) += efs/
obj-$(CONFIG_JFFS2_FS) += jffs2/
diff --git a/fs/ntfsplus/Kconfig b/fs/ntfsplus/Kconfig
new file mode 100644
index 000000000000..c13cd06720e7
--- /dev/null
+++ b/fs/ntfsplus/Kconfig
@@ -0,0 +1,45 @@
+# SPDX-License-Identifier: GPL-2.0-only
+config NTFSPLUS_FS
+ tristate "NTFS+ file system support"
+ select NLS
+ help
+ NTFS is the file system of Microsoft Windows NT, 2000, XP and 2003.
+ This allows you to mount devices formatted with the ntfs file system.
+
+ To compile this as a module, choose M here: the module will be called
+ ntfsplus.
+
+config NTFSPLUS_DEBUG
+ bool "NTFS+ debugging support"
+ depends on NTFSPLUS_FS
+ help
+ If you are experiencing any problems with the NTFS file system, say
+ Y here. This will result in additional consistency checks to be
+ performed by the driver as well as additional debugging messages to
+ be written to the system log. Note that debugging messages are
+ disabled by default. To enable them, supply the option debug_msgs=1
+ at the kernel command line when booting the kernel or as an option
+ to insmod when loading the ntfs module. Once the driver is active,
+ you can enable debugging messages by doing (as root):
+ echo 1 > /proc/sys/fs/ntfs-debug
+ Replacing the "1" with "0" would disable debug messages.
+
+ If you leave debugging messages disabled, this results in little
+ overhead, but enabling debug messages results in very significant
+ slowdown of the system.
+
+ When reporting bugs, please try to have available a full dump of
+ debugging messages while the misbehaviour was occurring.
+
+config NTFSPLUS_FS_POSIX_ACL
+ bool "NTFS+ POSIX Access Control Lists"
+ depends on NTFSPLUS_FS
+ select FS_POSIX_ACL
+ help
+ POSIX Access Control Lists (ACLs) support additional access rights
+ for users and groups beyond the standard owner/group/world scheme,
+ and this option selects support for ACLs specifically for ntfs
+ filesystems.
+ NOTE: this is linux only feature. Windows will ignore these ACLs.
+
+ If you don't know what Access Control Lists are, say N.
diff --git a/fs/ntfsplus/Makefile b/fs/ntfsplus/Makefile
new file mode 100644
index 000000000000..1e7e830dbeec
--- /dev/null
+++ b/fs/ntfsplus/Makefile
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: GPL-2.0
+#
+# Makefile for the ntfsplus filesystem support.
+#
+
+# to check robot warnings
+ccflags-y += -Wint-to-pointer-cast \
+ $(call cc-option,-Wunused-but-set-variable,-Wunused-const-variable) \
+ $(call cc-option,-Wold-style-declaration,-Wout-of-line-declaration)
+
+obj-$(CONFIG_NTFSPLUS_FS) += ntfsplus.o
+
+ntfsplus-y := aops.o attrib.o collate.o misc.o dir.o file.o index.o inode.o \
+ mft.o mst.o namei.o runlist.o super.o unistr.o attrlist.o ea.o \
+ upcase.o bitmap.o lcnalloc.o logfile.o reparse.o compress.o \
+ ntfs_iomap.o
+
+ccflags-$(CONFIG_NTFSPLUS_DEBUG) += -DDEBUG
--
2.34.1
^ permalink raw reply [flat|nested] 6+ messages in thread
end of thread, other threads:[~2025-10-20 2:13 UTC | newest]
Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2025-10-20 2:12 [PATCH 06/11] ntfsplus: add iomap and address space operations Namjae Jeon
2025-10-20 2:12 ` [PATCH 07/11] ntfsplus: add attrib operatrions Namjae Jeon
2025-10-20 2:12 ` [PATCH 08/11] ntfsplus: add runlist handling and cluster allocator Namjae Jeon
2025-10-20 2:12 ` [PATCH 09/11] ntfsplus: add reparse and ea operations Namjae Jeon
2025-10-20 2:12 ` [PATCH 10/11] ntfsplus: add misc operations Namjae Jeon
2025-10-20 2:12 ` [PATCH 11/11] ntfsplus: add Kconfig and Makefile Namjae Jeon
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
all inboxes | Powered by JetHome®